@thebluefox has summarized the most of all. You're only also forced to use JavaScript to make that button to work anyway. Here's an SSCCE, you can copy'n'paste'n'run it:
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 2803532</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$('input.deletable').wrap('<span class="deleteicon" />').after($('<span/>').click(function() {
$(this).prev('input').val('').trigger('change').focus();
}));
});
</script>
<style>
span.deleteicon {
position: relative;
}
span.deleteicon span {
position: absolute;
display: block;
top: 5px;
right: 0px;
width: 16px;
height: 16px;
background: url('http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=4') 0 -690px;
cursor: pointer;
}
span.deleteicon input {
padding-right: 16px;
box-sizing: border-box;
}
</style>
</head>
<body>
<input type="text" class="deletable">
</body>
</html>
_x000D_
jQuery is by the way not necessary, it just nicely separates the logic needed for progressive enhancement from the source, you can of course also go ahead with plain HTML/CSS/JS:
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 2803532, with "plain" HTML/CSS/JS</title>
<style>
span.deleteicon {
position: relative;
}
span.deleteicon span {
position: absolute;
display: block;
top: 5px;
right: 0px;
width: 16px;
height: 16px;
background: url('http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=4') 0 -690px;
cursor: pointer;
}
span.deleteicon input {
padding-right: 16px;
box-sizing: border-box;
}
</style>
</head>
<body>
<span class="deleteicon">
<input type="text">
<span onclick="var input = this.previousSibling; input.value = ''; input.focus();"></span>
</span>
</body>
</html>
_x000D_
You only ends up with uglier HTML (and non-crossbrowser compatible JS ;) ).
Note that when the UI look'n'feel isn't your biggest concern, but the functionality is, then just use <input type="search">
instead of <input type="text">
. It'll show the (browser-specific) clear button on HTML5 capable browsers.
Just for clarification: setRequestProperty("User-Agent", "Mozilla ...")
now works just fine and doesn't append java/xx
at the end! At least with Java 1.6.30 and newer.
I listened on my machine with netcat(a port listener):
$ nc -l -p 8080
It simply listens on the port, so you see anything which gets requested, like raw http-headers.
And got the following http-headers without setRequestProperty:
GET /foobar HTTP/1.1
User-Agent: Java/1.6.0_30
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
And WITH setRequestProperty:
GET /foobar HTTP/1.1
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
As you can see the user agent was properly set.
Full example:
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
public class TestUrlOpener {
public static void main(String[] args) throws IOException {
URL url = new URL("http://localhost:8080/foobar");
URLConnection hc = url.openConnection();
hc.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
System.out.println(hc.getContentType());
}
}
Something like this should suffice, to do what your batch file was doing (dumping the result set as semi-colon delimited text to the console):
// sqlcmd.exe
// -S .\PDATA_SQLEXPRESS
// -U sa
// -P 2BeChanged!
// -d PDATA_SQLEXPRESS
// -s ; -W -w 100
// -Q "SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName, tPatDBirthday FROM [dbo].[TPatientRaw] WHERE tPatSName = '%name%' "
DataTable dt = new DataTable() ;
int rows_returned ;
const string credentials = @"Server=(localdb)\.\PDATA_SQLEXPRESS;Database=PDATA_SQLEXPRESS;User ID=sa;Password=2BeChanged!;" ;
const string sqlQuery = @"
select tPatCulIntPatIDPk ,
tPatSFirstname ,
tPatSName ,
tPatDBirthday
from dbo.TPatientRaw
where tPatSName = @patientSurname
" ;
using ( SqlConnection connection = new SqlConnection(credentials) )
using ( SqlCommand cmd = connection.CreateCommand() )
using ( SqlDataAdapter sda = new SqlDataAdapter( cmd ) )
{
cmd.CommandText = sqlQuery ;
cmd.CommandType = CommandType.Text ;
connection.Open() ;
rows_returned = sda.Fill(dt) ;
connection.Close() ;
}
if ( dt.Rows.Count == 0 )
{
// query returned no rows
}
else
{
//write semicolon-delimited header
string[] columnNames = dt.Columns
.Cast<DataColumn>()
.Select( c => c.ColumnName )
.ToArray()
;
string header = string.Join("," , columnNames) ;
Console.WriteLine(header) ;
// write each row
foreach ( DataRow dr in dt.Rows )
{
// get each rows columns as a string (casting null into the nil (empty) string
string[] values = new string[dt.Columns.Count];
for ( int i = 0 ; i < dt.Columns.Count ; ++i )
{
values[i] = ((string) dr[i]) ?? "" ; // we'll treat nulls as the nil string for the nonce
}
// construct the string to be dumped, quoting each value and doubling any embedded quotes.
string data = string.Join( ";" , values.Select( s => "\""+s.Replace("\"","\"\"")+"\"") ) ;
Console.WriteLine(values);
}
}
This isn't a very beautiful answer, but it's what I use to create zero-length vectors:
0[-1] # numeric
""[-1] # character
TRUE[-1] # logical
0L[-1] # integer
A literal is a vector of length 1, and [-1]
removes the first element (the only element in this case) from the vector, leaving a vector with zero elements.
As a bonus, if you want a single NA
of the respective type:
0[NA] # numeric
""[NA] # character
TRUE[NA] # logical
0L[NA] # integer
I wouldn't have an Object type parameter, no point in casting it to Student if we know it will always be type Student.
As for an explanation, "result == 0" will only occur when the last names are identical, at which point we compare the first names and return that value instead.
public int Compare(Object obj)
{
Student student = (Student) obj;
int result = this.getLastName().compareTo( student.getLastName() );
if ( result == 0 )
{
result = this.getFirstName().compareTo( student.getFirstName() );
}
return result;
}
I think the touch command is the right answer e.g. do something like
touch --date="`date`" aclocal.m4 Makefile.am configure Makefile.in
before [./configure && make].
Sidebar I: Otherwise, I agree with @kaz: adding dependencies for aclocal.m4 and/or configure and/or Makefile.am and/or Makefile.in makes assumptions about the target system that may be invalid. Specifically, those assumptions are
1) that all target systems have autotools,
2) that all target systems have the same version of autotools (e.g. automake.1.15 in this case).
3) that if either (1) or (2) are not true for any user, that the user is extracting the package from a maintainer-produced TAR or ZIP format that maintains timestamps of the relevant files, in which case all autotool/configure/Makefile.am/Makefile.in dependencies in the configure-generated Makefile will be satisfied before the make command is issued.
The second assumption fails on many Mac systems because automake.1.14 is the "latest" for OSX (at least that is what I see in MacPorts, and apparently the same is true for brew).
The third assumption fails spectacularly in a world with Github. This failure is an example of an "everyone thinks they are normative" mindset; specifically, the maintainers, who are the only class of users that should need to edit Makefile.am, have now put everyone into that class.
Perhaps there is an option in autowhatever that keeps these dependencies from being added to Makefile.in and/or Makefile.
Sidebar II [Why @kaz is right]: of course it is obvious, to me and other cognoscenti, to simply try a sequence of [touch] commands to fool the configure-created Makefile from re-running configure and the autotools. But that is not the point of configure; the point of configure is to ensure as many users on as many different systems as as possible can simply do [./configure && make] and move on; most users are not interested in "shaving the yak" e.g. debugging faulty assumptions of the autotools developers.
Sidebar III: it could be argued that ./configure, now that autotools adds these dependencies, is the wrong build tool to use with Github-distributed packages.
Sidebar IV: perhaps configure-based Github repos should put the necessary touch command into their readme, e.g. https://github.com/drbitboy/Tycho2_SQLite_RTree.
Well, In my case the solution was quite simple and straight.
I had to change just the value of log On As
value.
Steps to Resolve-
Sql Server Configuration manager
click on SQL Server (MSSQLSERVER
)Properties
log On As
value to LocalSystem
Hoping this will help you too :)
The function below will take as input # of minutes and output time in the following format: Hours:minutes. I used Math.trunc(), which is a new method added in 2015. It returns the integral part of a number by removing any fractional digits.
function display(a){
var hours = Math.trunc(a/60);
var minutes = a % 60;
console.log(hours +":"+ minutes);
}
display(120); //"2:0"
display(60); //"1:0:
display(100); //"1:40"
display(126); //"2:6"
display(45); //"0:45"
Use -ms-border-radius: 15px
, any element that uses css -ms- is compatible with IE.
You can make a template function, and pass the array by reference to achieve this.
Here is my code snippet
template <typename TypeOfData>
void PrintArray(TypeOfData &arrayOfType);
int main()
{
char charArray[] = "my name is";
int intArray[] = { 1,2,3,4,5,6 };
double doubleArray[] = { 1.1,2.2,3.3 };
PrintArray(charArray);
PrintArray(intArray);
PrintArray(doubleArray);
}
template <typename TypeOfData>
void PrintArray(TypeOfData &arrayOfType)
{
int elementsCount = sizeof(arrayOfType) / sizeof(arrayOfType[0]);
for (int i = 0; i < elementsCount; i++)
{
cout << "Value in elements at position " << i + 1 << " is " << arrayOfType[i] << endl;
}
}
I get same problem in Entity Framewrok and I solved it by under steps :
1-Open your Model.edmx 2-change a table place (for do change in cs file) 3-save it
I hope help you
You can also install Nodejs using NVM or Nodejs Version Manager There are a lot of benefits to using a version manager. One of them being you don't have to worry about this issue.
sudo apt-get update
sudo apt-get install build-essential libssl-dev
Once the prerequisite packages are installed, you can pull down the nvm installation script from the project's GitHub page. The version number may be different, but in general, you can download and install it with the following syntax:
curl https://raw.githubusercontent.com/creationix/nvm/v0.16.1/install.sh | sh
This will download the script and run it. It will install the software into a subdirectory of your home directory at ~/.nvm
. It will also add the necessary lines to your ~/.profile
file to use the file.
To gain access to the nvm functionality, you'll need to log out and log back in again, or you can source the ~/.profile file so that your current session knows about the changes:
source ~/.profile
Now that you have nvm installed, you can install isolated Node.js versions.
To find out the versions of Node.js that are available for installation, you can type:
nvm ls-remote
. . .
v0.11.10
v0.11.11
v0.11.12
v0.11.13
v0.11.14
As you can see, the newest version at the time of this writing is v0.11.14. You can install that by typing:
nvm install 0.11.14
Usually, nvm will switch to use the most recently installed version. You can explicitly tell nvm to use the version we just downloaded by typing:
nvm use 0.11.14
When you install Node.js using nvm, the executable is called node. You can see the version currently being used by the shell by typing:
node -v
The comeplete tutorial can be found here
Change Column Name/Type/Position/Comment:
ALTER TABLE table_name CHANGE [COLUMN] col_old_name col_new_name column_type [COMMENT col_comment] [FIRST|AFTER column_name]
Example:
CREATE TABLE test_change (a int, b int, c int);
// will change column a's name to a1
ALTER TABLE test_change CHANGE a a1 INT;
Simply apply aggregation function, Sum on your column
df.groupby('steps').sum().show()
Follow the Documentation http://spark.apache.org/docs/2.1.0/api/python/pyspark.sql.html
Check out this link also https://www.analyticsvidhya.com/blog/2016/10/spark-dataframe-and-operations/
Your query execution will return list of Object[]
.
List result_source = LoadSource.list();
for(Object[] objA : result_source) {
// read it all
}
You can try these lines:
$("#DynamicValueAssignedHere .formdiv form").contents().find("input[name='FirstName']").prevObject[1].value
Although in the particular example of the OP's question, switch
is not appropriate, there is an example where switch is still appropriate/beneficial, but other evaluation expressions are also required. This can be achieved by using the default clause for the expressions:
switch (foo) {
case 'bar':
// do something
break;
case 'foo':
// do something
break;
... // other plain comparison cases
default:
if (foo.length > 16) {
// something specific
} else if (foo.length < 2) {
// maybe error
} else {
// default action for everything else
}
}
20090320093349
SELECT CONVERT(VARCHAR,@date,112) +
LEFT(REPLACE(CONVERT(VARCHAR,@date,114),':',''),6)
If you just want the bitmap, This too works
InputStream inputStream = mContext.getContentResolver().openInputStream(uri);
Bitmap bmp = BitmapFactory.decodeStream(inputStream);
if( inputStream != null ) inputStream.close();
sample uri : content://media/external/images/media/12345
The password of keystore by default is: "changeit". I functioned to my commands you entered here, for the import of the certificate. I hope you have already solved your problem.
NSURL *url= [NSURL URLWithString:@"https://www.paypal.com/cgi-bin/webscr"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:@"POST"];
NSString *postString = @"userId=2323";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
SELECT
t.*,
(SELECT COUNT(*) FROM city AS tt WHERE tt.name=t.name) AS count
FROM `city` AS t
WHERE
(SELECT count(*) FROM city AS tt WHERE tt.name=t.name) > 1 ORDER BY count DESC
I think the confusion is that on my server I had to right click the Task Scheduler Library on left hand side and right click to get the option to enable or disable all tasks history.
Hope this helps
List foreign key ( NOTE that its different from index name )
SHOW CREATE TABLE <Table Name>
The result will show you the foreign key name.
Format:
CONSTRAINT `FOREIGN_KEY_NAME` FOREIGN KEY (`FOREIGN_KEY_COLUMN`) REFERENCES `FOREIGN_KEY_TABLE` (`id`),
Drop (Foreign/primary/key) Key
ALTER TABLE <Table Name> DROP FOREIGN KEY <Foreign key name>
Drop the index.
this part :
"Your new price is: $"(float(price)
asks python to call this string:
"Your new price is: $"
just like you would a function:
function( some_args)
which will ALWAYS trigger the error:
TypeError: 'str' object is not callable
I am answering this old question just because it still shows up in google queries and I think one optimal answer is missing. Try this code: use ::before or ::after
Would be cool if someone could give me feedback on this one, I used the JUNIT without assert Pattern because it's easy and fast to get it running in Eclipse, I could also have just defined a main method. By the way, I am assuming rand5 gives values 0-4, adding 1 would make it 1-5, same with rand7... So the discussion should be on the solution, it's distribution, not on wether it goes from 0-4 or 1-5...
package random;
import java.util.Random;
import org.junit.Test;
public class RandomTest {
@Test
public void testName() throws Exception {
long times = 100000000;
int indexes[] = new int[7];
for(int i = 0; i < times; i++) {
int rand7 = rand7();
indexes[rand7]++;
}
for(int i = 0; i < 7; i++)
System.out.println("Value " + i + ": " + indexes[i]);
}
public int rand7() {
return (rand5() + rand5() + rand5() + rand5() + rand5() + rand5() + rand5()) % 7;
}
public int rand5() {
return new Random().nextInt(5);
}
}
When I run it, I get this result:
Value 0: 14308087
Value 1: 14298303
Value 2: 14279731
Value 3: 14262533
Value 4: 14269749
Value 5: 14277560
Value 6: 14304037
This seems like a very fair distribution, doesn't it?
If I add rand5() less or more times (where the amount of times is not divisible by 7), the distribution clearly shows offsets. For instance, adding rand5()
3 times:
Value 0: 15199685
Value 1: 14402429
Value 2: 12795649
Value 3: 12796957
Value 4: 14402252
Value 5: 15202778
Value 6: 15200250
So, this would lead to the following:
public int rand(int range) {
int randomValue = 0;
for(int i = 0; i < range; i++) {
randomValue += rand5();
}
return randomValue % range;
}
And then, I could go further:
public static final int ORIGN_RANGE = 5;
public static final int DEST_RANGE = 7;
@Test
public void testName() throws Exception {
long times = 100000000;
int indexes[] = new int[DEST_RANGE];
for(int i = 0; i < times; i++) {
int rand7 = convertRand(DEST_RANGE, ORIGN_RANGE);
indexes[rand7]++;
}
for(int i = 0; i < DEST_RANGE; i++)
System.out.println("Value " + i + ": " + indexes[i]);
}
public int convertRand(int destRange, int originRange) {
int randomValue = 0;
for(int i = 0; i < destRange; i++) {
randomValue += rand(originRange);
}
return randomValue % destRange;
}
public int rand(int range) {
return new Random().nextInt(range);
}
I tried this replacing the destRange and originRange with various values (even 7 for ORIGIN and 13 for DEST), and I get this distribution:
Value 0: 7713763
Value 1: 7706552
Value 2: 7694697
Value 3: 7695319
Value 4: 7688617
Value 5: 7681691
Value 6: 7674798
Value 7: 7680348
Value 8: 7685286
Value 9: 7683943
Value 10: 7690283
Value 11: 7699142
Value 12: 7705561
What I can conclude from here is that you can change any random to anyother by suming the origin random "destination" times. This will get a kind of gaussian distribution (being the middle values more likely, and the edge values more uncommon). However, the modulus of destination seems to distribute itself evenly across this gaussian distribution... It would be great to have feedback from a mathematician...
What is cool is that the cost is 100% predictable and constant, whereas other solutions cause a small probability of infinite loop...
@Chap - you can use this javascript lib, DefiantJS (http://defiantjs.com), with which you can filter matches using XPath on JSON structures. To put it in JS code:
var data = [
{ "restaurant": { "name": "McDonald's", "food": "burger" } },
{ "restaurant": { "name": "KFC", "food": "chicken" } },
{ "restaurant": { "name": "Pizza Hut", "food": "pizza" } }
].
res = JSON.search( data, '//*[food="pizza"]' );
console.log( res[0].name );
// Pizza Hut
DefiantJS extends the global object with the method "search" and returns an array with matches (empty array if no matches were found). You can try out the lib and XPath queries using the XPath Evaluator here:
You can't force accessing/changing element to which the user normally doesn't have access, as Selenium is designed to imitate user interaction.
If this error happens, check if:
maximize()
in node.js, maximize_window()
in Python),executeScript()
in node.js, execute_script()
in Python).I believe pwdencrypt is using a hash so you cannot really reverse the hashed string - the algorithm is designed so it's impossible.
If you are verifying the password that a user entered the usual technique is to hash it and then compare it to the hashed version in the database.
This is how you could verify a usered entered table
SELECT password_field FROM mytable WHERE password_field=pwdencrypt(userEnteredValue)
Replace userEnteredValue with (big surprise) the value that the user entered :)
@Steve Farthing's answer is absolutely right.
But if you rotate more than 4 times then the image will get cropped from both the side. For that you need to do like this.
$("#clockwise").click(function(){
angleInDegrees+=90 % 360;
drawRotated(angleInDegrees);
if(angleInDegrees == 360){ // add this lines
angleInDegrees = 0
}
});
Then you will get the desired result. Thanks. Hope this will help someone :)
try something using a for loop
for i in `egrep -lR "YOURSEARCH" .` ; do echo $i; sed 's/f/k/' <$i >/tmp/`basename $i`; mv /tmp/`basename $i` $i; done
not pretty, but should do.
you can go to mongoDB compass client and follow these steps: 1.Click Fill in connection fields individually:
2.In hostname type : 127.0.0.1
3. Click CONNECT.
Try this:
jquery
$('#save-source').click(function (e) {
e.preventDefault();
var source = {
'ID': 0,
//'ProductID': $('#ID').val(),
'PartNumber': $('#part-number').val(),
//'VendorID': $('#Vendors').val()
}
$.ajax({
type: "POST",
dataType: "json",
url: "/api/PartSourceAPI",
data: source,
success: function (data) {
alert(data);
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
//jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
}
});
});
Controller
public string Post(PartSourceModel model)
{
return model.PartNumber;
}
View
<label>Part Number</label>
<input type="text" id="part-number" name="part-number" />
<input type="submit" id="save-source" name="save-source" value="Add" />
Now when you click 'Add
' after you fill out the text box, the controller
will spit back out what you wrote in the PartNumber
box in an alert.
What about:
char *string = "qwerty";
char *e = string;
int idx = 0;
while (*e++ != 'e') idx++;
copying to e to preserve the original string, I suppose if you don't care you could just operate over *string
file_get_contents()
utilizes the fopen()
wrappers, therefore it is restricted from accessing URLs through the allow_url_fopen
option within php.ini.
You will either need to alter your php.ini to turn this option on or use an alternative method, namely cURL - by far the most popular and, to be honest, standard way to accomplish what you are trying to do.
Adding onKeyPress will work onChange in Text Field.
<TextField
onKeyPress={(ev) => {
console.log(`Pressed keyCode ${ev.key}`);
if (ev.key === 'Enter') {
// Do code here
ev.preventDefault();
}
}}
/>
Git doesn't think in terms of file versions. A version in git is a snapshot of the entire tree.
Given this, what you really want is a tree that has the latest content of most files, but with the contents of one file the same as it was 5 commits ago. This will take the form of a new commit on top of the old ones, and the latest version of the tree will have what you want.
I don't know if there's a one-liner that will revert a single file to the contents of 5 commits ago, but the lo-fi solution should work: checkout master~5
, copy the file somewhere else, checkout master
, copy the file back, then commit.
Try this...
SELECT TO_CHAR(column_name,'99G999D99MI')
as format_column
FROM DUAL;
I liked the answer from kays1 but I couldn't implement it. So I built my own version using his concept.
public class JsonListHelper{
public static final <T> List<T> getList(String json) throws Exception {
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
Type typeOfList = new TypeToken<List<T>>(){}.getType();
return gson.fromJson(json, typeOfList);
}
}
Usage:
List<MyClass> MyList= JsonListHelper.getList(jsonArrayString);
The following may help give you want you need:
SELECT
index_owner, index_name, table_name, column_name, column_position
FROM DBA_IND_COLUMNS
ORDER BY
index_owner,
table_name,
index_name,
column_position
;
For my use case, I wanted the column_names and order that they are in the indices (so that I could recreate them in a different database engine after migrating to AWS). The following was what I used, in case it is of use to anyone else:
SELECT
index_name, table_name, column_name, column_position
FROM DBA_IND_COLUMNS
WHERE
INDEX_OWNER = 'FOO'
AND TABLE_NAME NOT LIKE '%$%'
ORDER BY
table_name,
index_name,
column_position
;
don't put space after \n, otherwise, it won't work. I don't know the reason, but this trick worked for me pretty well.
You should first check the app version on the market and compare it with the version of the app on the device. If they are different, it may be an update available. In this post I wrote down the code for getting the current version of market and current version on the device and compare them together. I also showed how to show the update dialog and redirect the user to the update page. Please visit this link: https://stackoverflow.com/a/33925032/5475941
This alternative approach uses SQL Server's OUTER APPLY
clause. This way, it
The OUTER APPLY
clause can be imagined as a LEFT JOIN
, but with the advantage that you can use values of the main query as parameters in the subquery (here: game).
SELECT colMinPointID
FROM (
SELECT game
FROM table
GROUP BY game
) As rstOuter
OUTER APPLY (
SELECT TOP 1 id As colMinPointID
FROM table As rstInner
WHERE rstInner.game = rstOuter.game
ORDER BY points
) AS rstMinPoints
Parallel.ForEach
requires a list of user-defined workers and a non-async Action
to perform with each worker.
Task.WaitAll
and Task.WhenAll
require a List<Task>
, which are by definition asynchronous.
I found RiaanDP's response very useful to understand the difference, but it needs a correction for Parallel.ForEach
. Not enough reputation to respond to his comment, thus my own response.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsyncTest
{
class Program
{
class Worker
{
public int Id;
public int SleepTimeout;
public void DoWork(DateTime testStart)
{
var workerStart = DateTime.Now;
Console.WriteLine("Worker {0} started on thread {1}, beginning {2} seconds after test start.",
Id, Thread.CurrentThread.ManagedThreadId, (workerStart - testStart).TotalSeconds.ToString("F2"));
Thread.Sleep(SleepTimeout);
var workerEnd = DateTime.Now;
Console.WriteLine("Worker {0} stopped; the worker took {1} seconds, and it finished {2} seconds after the test start.",
Id, (workerEnd - workerStart).TotalSeconds.ToString("F2"), (workerEnd - testStart).TotalSeconds.ToString("F2"));
}
public async Task DoWorkAsync(DateTime testStart)
{
var workerStart = DateTime.Now;
Console.WriteLine("Worker {0} started on thread {1}, beginning {2} seconds after test start.",
Id, Thread.CurrentThread.ManagedThreadId, (workerStart - testStart).TotalSeconds.ToString("F2"));
await Task.Run(() => Thread.Sleep(SleepTimeout));
var workerEnd = DateTime.Now;
Console.WriteLine("Worker {0} stopped; the worker took {1} seconds, and it finished {2} seconds after the test start.",
Id, (workerEnd - workerStart).TotalSeconds.ToString("F2"), (workerEnd - testStart).TotalSeconds.ToString("F2"));
}
}
static void Main(string[] args)
{
var workers = new List<Worker>
{
new Worker { Id = 1, SleepTimeout = 1000 },
new Worker { Id = 2, SleepTimeout = 2000 },
new Worker { Id = 3, SleepTimeout = 3000 },
new Worker { Id = 4, SleepTimeout = 4000 },
new Worker { Id = 5, SleepTimeout = 5000 },
};
var startTime = DateTime.Now;
Console.WriteLine("Starting test: Parallel.ForEach...");
PerformTest_ParallelForEach(workers, startTime);
var endTime = DateTime.Now;
Console.WriteLine("Test finished after {0} seconds.\n",
(endTime - startTime).TotalSeconds.ToString("F2"));
startTime = DateTime.Now;
Console.WriteLine("Starting test: Task.WaitAll...");
PerformTest_TaskWaitAll(workers, startTime);
endTime = DateTime.Now;
Console.WriteLine("Test finished after {0} seconds.\n",
(endTime - startTime).TotalSeconds.ToString("F2"));
startTime = DateTime.Now;
Console.WriteLine("Starting test: Task.WhenAll...");
var task = PerformTest_TaskWhenAll(workers, startTime);
task.Wait();
endTime = DateTime.Now;
Console.WriteLine("Test finished after {0} seconds.\n",
(endTime - startTime).TotalSeconds.ToString("F2"));
Console.ReadKey();
}
static void PerformTest_ParallelForEach(List<Worker> workers, DateTime testStart)
{
Parallel.ForEach(workers, worker => worker.DoWork(testStart));
}
static void PerformTest_TaskWaitAll(List<Worker> workers, DateTime testStart)
{
Task.WaitAll(workers.Select(worker => worker.DoWorkAsync(testStart)).ToArray());
}
static Task PerformTest_TaskWhenAll(List<Worker> workers, DateTime testStart)
{
return Task.WhenAll(workers.Select(worker => worker.DoWorkAsync(testStart)));
}
}
}
The resulting output is below. Execution times are comparable. I ran this test while my computer was doing the weekly anti virus scan. Changing the order of the tests did change the execution times on them.
Starting test: Parallel.ForEach...
Worker 1 started on thread 9, beginning 0.02 seconds after test start.
Worker 2 started on thread 10, beginning 0.02 seconds after test start.
Worker 3 started on thread 11, beginning 0.02 seconds after test start.
Worker 4 started on thread 13, beginning 0.03 seconds after test start.
Worker 5 started on thread 14, beginning 0.03 seconds after test start.
Worker 1 stopped; the worker took 1.00 seconds, and it finished 1.02 seconds after the test start.
Worker 2 stopped; the worker took 2.00 seconds, and it finished 2.02 seconds after the test start.
Worker 3 stopped; the worker took 3.00 seconds, and it finished 3.03 seconds after the test start.
Worker 4 stopped; the worker took 4.00 seconds, and it finished 4.03 seconds after the test start.
Worker 5 stopped; the worker took 5.00 seconds, and it finished 5.03 seconds after the test start.
Test finished after 5.03 seconds.
Starting test: Task.WaitAll...
Worker 1 started on thread 9, beginning 0.00 seconds after test start.
Worker 2 started on thread 9, beginning 0.00 seconds after test start.
Worker 3 started on thread 9, beginning 0.00 seconds after test start.
Worker 4 started on thread 9, beginning 0.00 seconds after test start.
Worker 5 started on thread 9, beginning 0.01 seconds after test start.
Worker 1 stopped; the worker took 1.00 seconds, and it finished 1.01 seconds after the test start.
Worker 2 stopped; the worker took 2.00 seconds, and it finished 2.01 seconds after the test start.
Worker 3 stopped; the worker took 3.00 seconds, and it finished 3.01 seconds after the test start.
Worker 4 stopped; the worker took 4.00 seconds, and it finished 4.01 seconds after the test start.
Worker 5 stopped; the worker took 5.00 seconds, and it finished 5.01 seconds after the test start.
Test finished after 5.01 seconds.
Starting test: Task.WhenAll...
Worker 1 started on thread 9, beginning 0.00 seconds after test start.
Worker 2 started on thread 9, beginning 0.00 seconds after test start.
Worker 3 started on thread 9, beginning 0.00 seconds after test start.
Worker 4 started on thread 9, beginning 0.00 seconds after test start.
Worker 5 started on thread 9, beginning 0.00 seconds after test start.
Worker 1 stopped; the worker took 1.00 seconds, and it finished 1.00 seconds after the test start.
Worker 2 stopped; the worker took 2.00 seconds, and it finished 2.00 seconds after the test start.
Worker 3 stopped; the worker took 3.00 seconds, and it finished 3.00 seconds after the test start.
Worker 4 stopped; the worker took 4.00 seconds, and it finished 4.00 seconds after the test start.
Worker 5 stopped; the worker took 5.00 seconds, and it finished 5.01 seconds after the test start.
Test finished after 5.01 seconds.
tf.nn.softmax
computes the forward propagation through a softmax layer. You use it during evaluation of the model when you compute the probabilities that the model outputs.
tf.nn.softmax_cross_entropy_with_logits
computes the cost for a softmax layer. It is only used during training.
The logits are the unnormalized log probabilities output the model (the values output before the softmax normalization is applied to them).
$date = '2012.11.13';
$dateOfReturn = '2017.10.31';
$substract = str_replace('.', '-', $date);
$substract2 = str_replace('.', '-', $dateOfReturn);
$date1 = $substract;
$date2 = $substract2;
$ts1 = strtotime($date1);
$ts2 = strtotime($date2);
$year1 = date('Y', $ts1);
$year2 = date('Y', $ts2);
$month1 = date('m', $ts1);
$month2 = date('m', $ts2);
echo $diff = (($year2 - $year1) * 12) + ($month2 - $month1);
You can avoid compilation errors if you remove the method definitions from the header files and let the classes contain only the method declarations and variable declarations/definitions. The method definitions should be placed in a .cpp file (just like a best practice guideline says).
The down side of the following solution is (assuming that you had placed the methods in the header file to inline them) that the methods are no longer inlined by the compiler and trying to use the inline keyword produces linker errors.
//A.h
#ifndef A_H
#define A_H
class B;
class A
{
int _val;
B* _b;
public:
A(int val);
void SetB(B *b);
void Print();
};
#endif
//B.h
#ifndef B_H
#define B_H
class A;
class B
{
double _val;
A* _a;
public:
B(double val);
void SetA(A *a);
void Print();
};
#endif
//A.cpp
#include "A.h"
#include "B.h"
#include <iostream>
using namespace std;
A::A(int val)
:_val(val)
{
}
void A::SetB(B *b)
{
_b = b;
cout<<"Inside SetB()"<<endl;
_b->Print();
}
void A::Print()
{
cout<<"Type:A val="<<_val<<endl;
}
//B.cpp
#include "B.h"
#include "A.h"
#include <iostream>
using namespace std;
B::B(double val)
:_val(val)
{
}
void B::SetA(A *a)
{
_a = a;
cout<<"Inside SetA()"<<endl;
_a->Print();
}
void B::Print()
{
cout<<"Type:B val="<<_val<<endl;
}
//main.cpp
#include "A.h"
#include "B.h"
int main(int argc, char* argv[])
{
A a(10);
B b(3.14);
a.Print();
a.SetB(&b);
b.Print();
b.SetA(&a);
return 0;
}
You can always wrap your promise returning functions in a way that they catches failure and returning instead an agreed value (e.g. error.message), so the exception won't roll all the way up to the Promise.all function and disable it.
async function resetCache(ip) {
try {
const response = await axios.get(`http://${ip}/resetcache`);
return response;
}catch (e) {
return {status: 'failure', reason: 'e.message'};
}
}
I'd use RestSharp - https://github.com/restsharp/RestSharp
Create class to deserialize to:
public class MyObject {
public string Id { get; set; }
public string Text { get; set; }
...
}
And the code to get that object:
RestClient client = new RestClient("http://whatever.com");
RestRequest request = new RestRequest("path/to/object");
request.AddParameter("id", "123");
// The above code will make a request URL of
// "http://whatever.com/path/to/object?id=123"
// You can pick and choose what you need
var response = client.Execute<MyObject>(request);
MyObject obj = response.Data;
Check out http://restsharp.org/ to get started.
As a general rule, I'd always advocate explicitly calling the Dispose method for any class that offers it, either by calling the method directly or wrapping in a "using" block.
Most often, classes that implement IDisposible do so because they wrap some unmanaged resource that needs to be freed. While these classes should have finalizers that act as a safeguard, calling Dispose will help free that memory earlier and with lower overhead.
In the case of the Form object, as the link fro Kyra noted, the Close method is documented to invoke Dispose on your behalf so you need not do so explicitly. However, to me, that has always felt like relying on an implementaion detail. I prefer to always call both Close and Dispose for classes that implement them, to guard against implementation changes/errors and for the sake of being clear. A properly implemented Dispose method should be safe to invoke multiple times.
Check out shred. It's a node HTTP client created and maintained by spire.io that handles redirects, sessions, and JSON responses. It's great for interacting with rest APIs. See this blog post for more details.
To get last record details
Model::all()->last();
orModel::orderBy('id', 'desc')->first();
To get last record id
Model::all()->last()->id;
or Model::orderBy('id', 'desc')->first()->id;
You can find more info about what limitations browsers will likely add to mitigate this and what IETF is doing about it as well as why this is needed at IETF SPEC on IP handling
Since you already have notepad++.exe
in your path. Create a shortcut in that folder named np
and point it to notepad++.exe
.
Unfortunately, the file must be locked for updates unless you're using Office 2010 and SharePoint 2010 together. This means that only one user per time can edit a file. The locking and version tracking capabilities of SharePoint are excellent, and this makes it a great tool for the type of collaboration you're talking about, but you would have to split documents into multiple files in order to extend the amount that could be edited at a time. For instance, we sometimes unmerge documents into technical, requirements, and financials sections so that the 3 experts required for the review can work concurrently. We then merge when everyone is finished.
//return is uppercase or lowercase
public boolean isASCIILetter(char c) {
return (c > 64 && c < 91) || (c > 96 && c < 123);
}
From what you printed, it seems var2
is an array containing one string. Or actually, it appears to hold the result of running .inspect
on an array containing one string. It would be helpful to show how you are initializing them.
irb(main):005:0* v1 = "test"
=> "test"
irb(main):006:0> v2 = ["test"]
=> ["test"]
irb(main):007:0> v3 = v2.inspect
=> "[\"test\"]"
irb(main):008:0> puts v1,v2,v3
test
test
["test"]
It's possible you forgot a sheet1
each time somewhere before the columns.count
, or it will count the activesheet
columns and not the sheet1
's.
Also, shouldn't it be xltoleft instead of xltoright? (Ok it is very late here, but I think I know my right from left) I checked it, you must write xltoleft.
lastColumn = Sheet1.Cells(1, sheet1.Columns.Count).End(xlToleft).Column
it almost can ..
ls -l | awk '{k=0;for(i=0;i<=8;i++)k+=((substr($1,i+2,1)~/[rwx]/) \
*2^(8-i));if(k)printf("%0o ",k);print}'
I may be slightly off-topic as you did mention the need for a username and password, and my understanding of the issue is admitedly not the best but is OpenID something worth considering?
If you use OpenID then you don't end up storing any credentials at all if I understand the technology correctly and users can use credentials that they already have, avoiding the need to create a new identity that is specific to your application.
It may not be suitable if the application in question is purely for internal use though
RPX provides a nice easy way to intergrate OpenID support into an application.
A node
is the generic name for any type of object in the DOM hierarchy. A node
could be one of the built-in DOM elements such as document
or document.body
, it could be an HTML tag specified in the HTML such as <input>
or <p>
or it could be a text node that is created by the system to hold a block of text inside another element. So, in a nutshell, a node
is any DOM object.
An element
is one specific type of node
as there are many other types of nodes (text nodes, comment nodes, document nodes, etc...).
The DOM consists of a hierarchy of nodes where each node can have a parent, a list of child nodes and a nextSibling and previousSibling. That structure forms a tree-like hierarchy. The document
node has the html
node as its child.
The html
node has its list of child nodes (the head
node and the body
node). The body
node would have its list of child nodes (the top level elements in your HTML page) and so on.
So, a nodeList
is simply an array-like list of nodes
.
An element is a specific type of node, one that can be directly specified in the HTML with an HTML tag and can have properties like an id
or a class
. can have children, etc... There are other types of nodes such as comment nodes, text nodes, etc... with different characteristics. Each node has a property .nodeType
which reports what type of node it is. You can see the various types of nodes here (diagram from MDN):
You can see an ELEMENT_NODE
is one particular type of node where the nodeType
property has a value of 1
.
So document.getElementById("test")
can only return one node and it's guaranteed to be an element (a specific type of node). Because of that it just returns the element rather than a list.
Since document.getElementsByClassName("para")
can return more than one object, the designers chose to return a nodeList
because that's the data type they created for a list of more than one node. Since these can only be elements (only elements typically have a class name), it's technically a nodeList
that only has nodes of type element in it and the designers could have made a differently named collection that was an elementList
, but they chose to use just one type of collection whether it had only elements in it or not.
EDIT: HTML5 defines an HTMLCollection
which is a list of HTML Elements (not any node, only Elements). A number of properties or methods in HTML5 now return an HTMLCollection
. While it is very similar in interface to a nodeList
, a distinction is now made in that it only contains Elements, not any type of node.
The distinction between a nodeList
and an HTMLCollection
has little impact on how you use one (as far as I can tell), but the designers of HTML5 have now made that distinction.
For example, the element.children
property returns a live HTMLCollection.
In your template, you have access to all the variables that are members of the current $scope
. So, tobedone
should be $scope.tobedone
, and then you can display it with {{tobedone}}
, or [[tobedone]]
in your case.
There is the concatenate function. For example
=CONCATENATE(E2,"-",F2)But the & operator always concatenates strings. + often will work, but if there is a number in one of the cells, it won't work as expected.
I had the same problem after upgrading from Windows 7
to Windows 10
. Tried all the popular answers which did not work. Finally, I understood that Windows had changed the name of the adapter. Virtual Box
was configured to use Realtek PCIe GBE Family Controller
while device manager had this as Realtek PCIe GBE Family Controller #2
. Selecting proper controller fixed the problem.
If you use php-fpm
, the php_admin_value will NOT work and gives an Internal Server Error.
Instead use this in your .htaccess
. It disables the parser in that folder and all subfolders:
<FilesMatch ".+\.*$">
SetHandler !
</FilesMatch>
Adding overflow:auto
before setting overflow-y
seems to do the trick in Google Chrome.
{
width:249px;
height:299px;
background-color:Gray;
overflow: auto;
overflow-y: scroll;
max-width:230px;
max-height:100px;
}
As of Xcode 6.1.1, there are some tiny changes to Dash's answer.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if (editingStyle == UITableViewCellEditingStyle.Delete) {
// handle delete (by removing the data from your array and updating the tableview)
}
}
In short, the answer is no. Once you show an alert
, confirm
, or prompt
the script no longer has control until the user returns control by clicking one of the buttons.
To do what you want, you will want to use DOM elements like a div
and show, then hide it after a specified time. If you need to be modal (takes over the page, allowing no further action) you will have to do additional work.
You could of course use one of the many "dialog" libraries out there. One that comes to mind right away is the jQuery UI Dialog widget
in addition to all answers please note that in sendmail.ini
file:
auth_password=this-is-Not-your-Gmail-password
due to new google security concern, you should follow these steps to make an application password for this purpose:
Is it not safe to always comment out parameter names? If it's not you can do something like
#ifdef _MSC_VER
# define P_(n) n
#else
# define P_(n)
#endif
void ProcessOps::sendToExternalApp(
QString sAppName, QString sImagePath,
qreal P_(qrLeft), qreal P_(qrTop), qreal P_(qrWidth), qreal P_(qrHeight))
It's a bit less ugly.
Try purge
sudo aptitude purge phpmyadmin
Not sure this works with plain old apt-get
though
You might be looking for Promise.race
(native I/O racing solution, not threads)
Assuming you (or others searching this question) want to race threads to avoid failure and avoid the cost of I/O operations, this is a simple and native way to accomplish it (which does not use threads). Node is designed to be single threaded (look up the event loop), so avoid using threads if possible. If my assumption is correct, I recommend you use Promise.race
with setTimeout
(example in link). With this strategy, you would race a list of promises which each try some I/O operation and reject the promise if there is an error (otherwise timeout). The Promise.race
statement continues after the first resolution/rejection, which seems to be what you want. Hope this helps someone!
Similar to this answer, though I used a temporary table instead:
CREATE TEMPORARY TABLE duplicates (
SELECT payer_email
FROM paypal_ipn_orders
GROUP BY payer_email
HAVING COUNT(id) > 1
);
SELECT id, payer_email
FROM paypal_ipn_orders AS p
INNER JOIN duplicates AS d ON d.payer_email=p.payer_email;
In Gson 2.7.2 it's as easy as
Gson gson = new Gson();
String serialized = gson.toJson(map);
SVN is one repo and lots of clients. Git is a repo with lots of client repos, each with a user. It's decentralised to a point where people can track their own edits locally without having to push things to an external server.
SVN is designed to be more central where Git is based on each user having their own Git repo and those repos push changes back up into a central one. For that reason, Git gives individuals better local version control.
Meanwhile you have the choice between TortoiseGit, GitExtensions (and if you host your "central" git-repository on github, their own client – GitHub for Windows).
If you're looking on getting out of SVN, you might want to evaluate Bazaar for a bit. It's one of the next generation of version control systems that have this distributed element. It isn't POSIX dependant like git so there are native Windows builds and it has some powerful open source brands backing it.
But you might not even need these sorts of features yet. Have a look at the features, advantages and disadvantages of the distributed VCSes. If you need more than SVN offers, consider one. If you don't, you might want to stick with SVN's (currently) superior desktop integration.
To send to both remote with one command, you can create a alias for it:
git config alias.pushall '!git push origin devel && git push github devel'
With this, when you use the command git pushall
, it will update both repositories.
Maybe this is what you mean to do:
import random
x = 0
z = input('Please Enter an integer: ')
z = int(z) # you need to capture the result of the expressioin: int(z) and assign it backk to z
def main():
for i in range(x,z):
n1 = random.randrange(1,3)
n2 = random.randrange(1,3)
t1 = n1+n2
print('{0}+{1}={2}'.format(n1,n2,t1))
main()
Here's a link on the range() function: http://docs.python.org/release/1.5.1p1/tut/range.html
Remember that each Add
will check the capacity of the collection and resize it whenever necessary (slower). With AddRange
, the collection will be set the capacity and then added the items (faster). This extension method will be extremely slow, but will work.
It's not evil. Like many things in C++, it's good if used correctly, but there are many pitfalls you should be aware of when using it (like returning a reference to a local variable).
There are good things that can be achieved with it (like map[name] = "hello world")
res/
mipmap-mdpi/ic_launcher.png (48x48 pixels)
mipmap-hdpi/ic_launcher.png (72x72)
mipmap-xhdpi/ic_launcher.png (96x96)
mipmap-xxhdpi/ic_launcher.png (144x144)
mipmap-xxxhdpi/ic_launcher.png (192x192)
MipMap for app icon for launcher
http://android-developers.blogspot.co.uk/2014/10/getting-your-apps-ready-for-nexus-6-and.html
https://androidbycode.wordpress.com/2015/02/14/goodbye-launcher-drawables-hello-mipmaps/
One possible reason here might be your script have wrong shebang (so it is not using python from your virtualenv). I just did this change and it works:
-#!/bin/python
+#!/usr/bin/env python
Or ignore shebang and just run the script with python in your venv:
$ python your_script.py
Type the following commands on the terminal to install Python 3.6 on CentOS 7:
$ sudo yum install https://centos7.iuscommunity.org/ius-release.rpm
Then do :
$ sudo yum install python36u
You can also install any version instead of 3.6 (if you want to) by just replacing 36 by your version number.
this extension https://marketplace.visualstudio.com/items?itemName=sourcegraph.javascript-typescript was causing me the error in visual code, I uninstalled it and it works for me
I am using Android Studio 3.0 and was facing the same problem. I add this to my gradle:
multiDexEnabled true
And it worked!
Example
android {
compileSdkVersion 27
buildToolsVersion '27.0.1'
defaultConfig {
applicationId "com.xx.xxx"
minSdkVersion 15
targetSdkVersion 27
versionCode 1
versionName "1.0"
multiDexEnabled true //Add this
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
shrinkResources true
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
And clean the project.
sleep(1.0/24.0)
As to your follow up question if that's the best way: No, you could get not-so-smooth framerates because the rendering of each frame might not take the same amount of time.
You could try one of these solutions:
I had the same error message after running out of drive space. When I realized somehow the php file was corrupted, I copied the content and created a new file (I´m using Sublime Text for editing), and it solved my problem
You have empty $_POST
. If your web-server wants see data in json-format you need to read the raw input and then parse it with JSON decode.
You need something like that:
$json = file_get_contents('php://input');
$obj = json_decode($json);
Also you have wrong code for testing JSON-communication...
CURLOPT_POSTFIELDS
tells curl
to encode your parameters as application/x-www-form-urlencoded
. You need JSON-string here.
UPDATE
Your php code for test page should be like that:
$data_string = json_encode($data);
$ch = curl_init('http://webservice.local/');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
$result = json_decode($result);
var_dump($result);
Also on your web-service page you should remove one of the lines header('Content-type: application/json');
. It must be called only once.
My response is very late but for others users In your case you have to configure failsafe pluging to use the command line agent configuration saved in itCoverageAgent variable. For exemple
<configuration>
<argLine>${itCoverageAgent}</argLine>
</configuration>
In your maven configuration, jacoco prepare the command line arguments in prepare-agent phase, but failsafe plugin doesn't use it so there is no execution data file.
/*
* convert server time to local time
* simbu
*/
function convertTime(serverdate) {
var date = new Date(serverdate);
// convert to utc time
var toutc = date.toUTCString();
//convert to local time
var locdat = new Date(toutc + " UTC");
return locdat;
}
The rowSums function (as Greg mentions) will do what you want, but you are mixing subsetting techniques in your answer, do not use "$" when using "[]", your code should look something more like:
data$new <- rowSums( data[,43:167] )
If you want to use a function other than sum, then look at ?apply for applying general functions accross rows or columns.
Take at this videos for more details about Indexing
Simple Indexing You can create a unique index on a table. A unique index means that two rows cannot have the same index value. Here is the syntax to create an Index on a table
CREATE UNIQUE INDEX index_name
ON table_name ( column1, column2,...);
You can use one or more columns to create an index. For example, we can create an index on tutorials_tbl
using tutorial_author.
CREATE UNIQUE INDEX AUTHOR_INDEX
ON tutorials_tbl (tutorial_author)
You can create a simple index on a table. Just omit UNIQUE keyword from the query to create simple index. Simple index allows duplicate values in a table.
If you want to index the values in a column in descending order, you can add the reserved word DESC after the column name.
mysql> CREATE UNIQUE INDEX AUTHOR_INDEX
ON tutorials_tbl (tutorial_author DESC)
Combining a few answers from the above, the following works really well for me for destroying Cookies:
/**
* Utility method to obtain the domain URI:
*/
fetchDomainURI() {
if (window.location.port.length > 0) {
return window.location.hostname;
}
return `.${window.location.hostname.match(/\w*\.\w*$/gi)[0]}`;
}
Works for IP addresses with ports, e.g., 0.0.0.0:8000 etc, as well as complex domains like app.staging.example.com
returning .example.com
=> allows for cross-domain Cookie setting and destroying.
Number only regex (Updated)
var reg = new RegExp('[^0-9]','g');
Use perl -i, with a command that replaces the beginning of line 1 with what you want to insert (the .bk will have the effect that your original file is backed up):
perl -i.bk -pe 's/^/column1, column2, column3\n/ if($.==1)' testfile.csv
You can use querySelectorAll()
like this:
var test = document.querySelectorAll('input[value][type="checkbox"]:not([value=""])');
This translates to:
get all inputs with the attribute "value" and has the attribute "value" that is not blank.
In this demo, it disables the checkbox with a non-blank value.
I just experienced the same issue after I had to restart my production server. I am running Debian 8.1 (Jessie) on a DigitalOcean droplet.
This is what I did to resolve my issue:
Check if the file /var/run/mysqld/mysqld.sock
exists. If it doesn't, manually create it by entering touch /var/run/mysqld/mysqld.sock
(which is what I had to do).
So the MySQL process can use this file. Change ownership of said file by entering chown mysql /var/run/mysqld/mysqld.sock
.
Once '2' has been done, restart the MySQL service by entering service mysql restart
or /etc/init.d/mysql restart
.
After going through the above steps, my issue was solved. I rarely have this issue, and there is probably a better way, so by all means provide constructive feedback if need be :).
The file may be existing but may have a different path. Try writing the absolute path for the file.
Try os.listdir()
function to check that atleast python sees the file.
Try it like this:
file1 = open(r'Drive:\Dir\recentlyUpdated.yaml')
Here is a log4j.properties file that I've used with great success.
logDir=/var/log/myapp
log4j.rootLogger=INFO, stdout
#log4j.rootLogger=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.DailyRollingFileAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{MM/dd/yyyy hh:mm:ss a}|%-5p|%-30c{1}| %m%n
log4j.appender.stdout.DatePattern='.'yyyy-MM-dd
log4j.appender.stdout.File=${logDir}/myapp.log
log4j.appender.stdout.append=true
The DailyRollingFileAppender will create new files each day with file names that look like this:
myapp.log.2017-01-27
myapp.log.2017-01-28
myapp.log.2017-01-29
myapp.log <-- today's log
Each entry in the log file will will have this format:
01/30/2017 12:59:47 AM|INFO |Component1 | calling foobar(): userId=123, returning totalSent=1
01/30/2017 12:59:47 AM|INFO |Component2 | count=1 > 0, calling fooBar()
Set the location of the above file by using -Dlog4j.configuration
, as mentioned in this posting:
java -Dlog4j.configuration=file:/home/myapp/config/log4j.properties com.foobar.myapp
In your Java code, be sure to set the name of each software component when you instantiate your logger object. I also like to log to both the log file and standard output, so I wrote this small function.
private static final Logger LOGGER = Logger.getLogger("Component1");
public static void log(org.apache.log4j.Logger logger, String message) {
logger.info(message);
System.out.printf("%s\n", message);
}
public static String stackTraceToString(Exception ex) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
return sw.toString();
}
And then call it like so:
LOGGER.info(String.format("Exception occurred: %s", stackTraceToString(ex)));
Getting one month ago is easy with a single MySQL function:
SELECT DATE_SUB(NOW(), INTERVAL 1 MONTH);
or
SELECT NOW() - INTERVAL 1 MONTH;
Off the top of my head, I can't think of an elegant way to get the first day of last month in MySQL, but this will certainly work:
SELECT CONCAT(LEFT(NOW() - INTERVAL 1 MONTH,7),'-01');
Put them together and you get a query that solves your problem:
SELECT *
FROM your_table
WHERE t >= CONCAT(LEFT(NOW() - INTERVAL 1 MONTH,7),'-01')
AND t <= NOW() - INTERVAL 1 MONTH
You can actually "request" MySQL for a list of all locations where it searches for my.cnf (or my.ini on Windows). It is not an SQL query though. Rather, execute:
$ mysqladmin --help
or, prior 5.7:
$ mysqld --help --verbose
In the very first lines you will find a message with a list of all my.cnf locations it looks for. On my machine it is:
Default options are read from the following files in the given order:
/etc/my.cnf
/etc/mysql/my.cnf
/usr/etc/my.cnf
~/.my.cnf
Or, on Windows:
Default options are read from the following files in the given order:
C:\Windows\my.ini
C:\Windows\my.cnf
C:\my.ini
C:\my.cnf
C:\Program Files\MySQL\MySQL Server 5.5\my.ini
C:\Program Files\MySQL\MySQL Server 5.5\my.cnf
Note however, that it might be the case that there is no my.cnf file at any of these locations. So, you can create the file on your own - use one of the sample config files provided with MySQL distribution (on Linux - see /usr/share/mysql/*.cnf
files and use whichever is appropriate for you - copy it to /etc/my.cnf
and then modify as needed).
Also, note that there is also a command line option --defaults-file
which may define custom path to my.cnf or my.ini file. For example, this is the case for MySQL 5.5 on Windows - it points to a my.ini file in the data directory, which is not normally listed with mysqld --help --verbose
. On Windows - see service properties to find out if this is the case for you.
Finally, check the https://dev.mysql.com/doc/refman/8.0/en/option-files.html - it is described there in more details.
Example from MVC 4 for dropdownlist validation on Submit using Dataannotation and ViewBag (less line of code)
Models:
namespace Project.Models
{
public class EmployeeReferral : Person
{
public int EmployeeReferralId { get; set; }
//Company District
//List
[Required(ErrorMessage = "Required.")]
[Display(Name = "Employee District:")]
public int? DistrictId { get; set; }
public virtual District District { get; set; }
}
namespace Project.Models
{
public class District
{
public int? DistrictId { get; set; }
[Display(Name = "Employee District:")]
public string DistrictName { get; set; }
}
}
EmployeeReferral Controller:
namespace Project.Controllers
{
public class EmployeeReferralController : Controller
{
private ProjDbContext db = new ProjDbContext();
//
// GET: /EmployeeReferral/
public ActionResult Index()
{
return View();
}
public ActionResult Create()
{
ViewBag.Districts = db.Districts;
return View();
}
View:
<td>
<div class="editor-label">
@Html.LabelFor(model => model.DistrictId, "District")
</div>
</td>
<td>
<div class="editor-field">
@*@Html.DropDownList("DistrictId", "----Select ---")*@
@Html.DropDownListFor(model => model.DistrictId, new SelectList(ViewBag.Districts, "DistrictId", "DistrictName"), "--- Select ---")
@Html.ValidationMessageFor(model => model.DistrictId)
</div>
</td>
Why can't we use ViewBag for populating dropdownlists that can be validated with Annotations. It is less lines of code.
Using async/await
async changeHandler(event) {
await this.setState({ yourName: event.target.value });
console.log(this.state.yourName);
}
Kotlin port, call the setDatePicker function
private fun setDatePicker(dateEditText: EditText) {
val myCalendar = Calendar.getInstance()
val datePickerOnDataSetListener = DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth ->
myCalendar.set(Calendar.YEAR, year)
myCalendar.set(Calendar.MONTH, monthOfYear)
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)
updateLabel(myCalendar, dateEditText)
}
dateEditText.setOnClickListener {
DatePickerDialog(this@YourActivityName, datePickerOnDataSetListener, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show()
}
}
private fun updateLabel(myCalendar: Calendar, dateEditText: EditText) {
val myFormat: String = "dd-MMM-yyyy"
val sdf = SimpleDateFormat(myFormat, Locale.UK)
dateEditText.setText(sdf.format(myCalendar.time))
}
A priority queue is an abstract data type that captures the idea of a container whose elements have "priorities" attached to them. An element of highest priority always appears at the front of the queue. If that element is removed, the next highest priority element advances to the front.
The C++ standard library defines a class template priority_queue, with the following operations:
push: Insert an element into the prioity queue.
top: Return (without removing it) a highest priority element from the priority queue.
pop: Remove a highest priority element from the priority queue.
size: Return the number of elements in the priority queue.
empty: Return true or false according to whether the priority queue is empty or not.
The following code snippet shows how to construct two priority queues, one that can contain integers and another one that can contain character strings:
#include <queue>
priority_queue<int> q1;
priority_queue<string> q2;
The following is an example of priority queue usage:
#include <string>
#include <queue>
#include <iostream>
using namespace std; // This is to make available the names of things defined in the standard library.
int main()
{
piority_queue<string> pq; // Creates a priority queue pq to store strings, and initializes the queue to be empty.
pq.push("the quick");
pq.push("fox");
pq.push("jumped over");
pq.push("the lazy dog");
// The strings are ordered inside the priority queue in lexicographic (dictionary) order:
// "fox", "jumped over", "the lazy dog", "the quick"
// The lowest priority string is "fox", and the highest priority string is "the quick"
while (!pq.empty()) {
cout << pq.top() << endl; // Print highest priority string
pq.pop(); // Remmove highest priority string
}
return 0;
}
The output of this program is:
the quick
the lazy dog
jumped over
fox
Since a queue follows a priority discipline, the strings are printed from highest to lowest priority.
Sometimes one needs to create a priority queue to contain user defined objects. In this case, the priority queue needs to know the comparison criterion used to determine which objects have the highest priority. This is done by means of a function object belonging to a class that overloads the operator (). The overloaded () acts as < for the purpose of determining priorities. For example, suppose we want to create a priority queue to store Time objects. A Time object has three fields: hours, minutes, seconds:
struct Time {
int h;
int m;
int s;
};
class CompareTime {
public:
bool operator()(Time& t1, Time& t2) // Returns true if t1 is earlier than t2
{
if (t1.h < t2.h) return true;
if (t1.h == t2.h && t1.m < t2.m) return true;
if (t1.h == t2.h && t1.m == t2.m && t1.s < t2.s) return true;
return false;
}
}
A priority queue to store times according the the above comparison criterion would be defined as follows:
priority_queue<Time, vector<Time>, CompareTime> pq;
Here is a complete program:
#include <iostream>
#include <queue>
#include <iomanip>
using namespace std;
struct Time {
int h; // >= 0
int m; // 0-59
int s; // 0-59
};
class CompareTime {
public:
bool operator()(Time& t1, Time& t2)
{
if (t1.h < t2.h) return true;
if (t1.h == t2.h && t1.m < t2.m) return true;
if (t1.h == t2.h && t1.m == t2.m && t1.s < t2.s) return true;
return false;
}
};
int main()
{
priority_queue<Time, vector<Time>, CompareTime> pq;
// Array of 4 time objects:
Time t[4] = { {3, 2, 40}, {3, 2, 26}, {5, 16, 13}, {5, 14, 20}};
for (int i = 0; i < 4; ++i)
pq.push(t[i]);
while (! pq.empty()) {
Time t2 = pq.top();
cout << setw(3) << t2.h << " " << setw(3) << t2.m << " " <<
setw(3) << t2.s << endl;
pq.pop();
}
return 0;
}
The program prints the times from latest to earliest:
5 16 13
5 14 20
3 2 40
3 2 26
If we wanted earliest times to have the highest priority, we would redefine CompareTime like this:
class CompareTime {
public:
bool operator()(Time& t1, Time& t2) // t2 has highest prio than t1 if t2 is earlier than t1
{
if (t2.h < t1.h) return true;
if (t2.h == t1.h && t2.m < t1.m) return true;
if (t2.h == t1.h && t2.m == t1.m && t2.s < t1.s) return true;
return false;
}
};
You can try something like
SELECT e.EntityId,
e.EntityName,
CASE
WHEN ep.EntityId IS NULL THEN 'False'
ELSE 'TRUE'
END AS HasProfile
FROM Entities e LEFT JOIN
EntityProfiles ep ON e.EntityID = ep.EntityID
Or
SELECT e.EntityId,
e.EntityName,
CASE
WHEN e.EntityProfile IS NULL THEN 'False'
ELSE 'TRUE'
END AS HasProfile
FROM Entities e
Slight change to the FastArray from above:
'pushtest.vbs
imax = 10000000
value = "Testvalue"
s = imax & " of """ & value & """"
t0 = timer 'Fast array
a = array()
ub = UBound(a)
For i = 0 To imax
If i>ub Then
ReDim Preserve a(Int((ub+10)*1.1))
ub = UBound(a)
End If
a(i) = value
Next
ReDim Preserve a(i-1)
s = s & "[FastArr " & FormatNumber(timer - t0, 3, -1) & "]"
MsgBox s
There is no point in checking UBound(a)
in every cycle of the for if we know exactly when it changes.
I've changed it so that it checks does UBound(a)
just before the for starts and then only every time the ReDim
is called
On my computer the old method took 7.52 seconds for an imax of 10 millions.
The new method took 5.29 seconds for an imax of also 10 millions, which signifies a performance increase of over 20% (for 10 millions tries, obviously this percentage has a direct relationship to the number of tries)
After few years, I moved to leaflet map and I have fixed this issue completely, the following could be applied to google maps too:
var headerHeight = $("#navMap").outerHeight();
var footerHeight = $("footer").outerHeight();
var windowHeight = window.innerHeight;
var mapContainerHeight = headerHeight + footerHeight;
var totalMapHeight = windowHeight - mapContainerHeight;
$("#map").css("margin-top", headerHeight);
$("#map").height(totalMapHeight);
$(window).resize(function(){
var headerHeight = $("#navMap").outerHeight();
var footerHeight = $("footer").outerHeight();
var windowHeight = window.innerHeight;
var mapContainerHeight = headerHeight + footerHeight;
var totalMapHeight = windowHeight - mapContainerHeight;
$("#map").css("margin-top", headerHeight);
$("#map").height(totalMapHeight);
map.fitBounds(group1.getBounds());
});
I think it's well covered with all the answers, but if you are using a button with some JavaScript validation code you could just set the form's onkeypress for Enter to call your submit as expected:
<form method="POST" action="..." onkeypress="if(event.keyCode == 13) mySubmitFunction(this); return false;">
The onkeypress JS could be whatever you need to do. There's no need for a larger, global change. This is especially true if you're not the one coding the app from scratch, and you've been brought into fix someone else's web site without tearing it apart and re-testing it.
Just to make sure you are not confusing the tid (thread id) and the pid (process id):
DWORD pid;
DWORD tid = GetWindowThreadProcessId( this->m_hWnd, &pid);
Just toggle each time it is called
this.boolValue = !this.boolValue;
This does and will do: :)
# python... 3.x
import operator
...
# line: line of text
return " ".join(filter(lambda a: operator.is_not(a, ""), line.strip().split(" ")))
Since many people arrive here debugging their slow website I would like to inform you about my case which none of the google explanations helped to resolve. My huge stalled times (sometimes 1min) were caused by Apache running on Windows having too few worker threads to handle the connections, therefore they were being queued.
This may apply to you if you apache log has following note:
Server ran out of threads to serve requests. Consider raising the ThreadsPerChild setting
This issue is resolved in Apache httpd.conf. Uncomment : Include conf/extra/httpd-mpm.conf
And edit httpd-mpm.conf
<IfModule mpm_winnt_module>
ThreadLimit 2000
ThreadsPerChild 2000
MaxConnectionsPerChild 0
</IfModule>
Note that you may not need 2000 threads, or may need more. 2000 was OK for my case.
Are you looking for the code to do it or understanding the algorithm?
Does this do what you need? Specifically a2b_uu
and b2a_uu
? There are LOTS of other options in there in case those aren't what you want.
(NOTE: Not a Python guy but this seemed like an obvious answer)
I am in ubuntu 14.04 and mongod is registered as an upstart service. The answers in this post sent me in the right direction. The only adaptation I had to do to make things work with the upstart service was to edit /etc/mongod.conf
. Look for the lines that read:
# Enable the HTTP interface (Defaults to port 28017).
# httpinterface = true
Just remove the #
in front of httpinterface and restart the mongod service:
sudo restart mongod
Note: You can also enable the rest interface by adding a line that reads
rest=true
right below the httpinterface line mentioned above.
Java 9 has the following method to create an immutable list:
List<String> places = List.of("Buenos Aires", "Córdoba", "La Plata");
which is easily adapted to create a mutable list, if required:
List<String> places = new ArrayList<>(List.of("Buenos Aires", "Córdoba", "La Plata"));
Similar methods are available for Set
and Map
.
I believe date.isocalendar()
is going to be the answer. This article explains the math behind ISO 8601 Calendar. Check out the date.isocalendar() portion of the datetime page of the Python documentation.
>>> dt = datetime.date(2010, 6, 16)
>>> wk = dt.isocalendar()[1]
24
.isocalendar() return a 3-tuple with (year, wk num, wk day). dt.isocalendar()[0]
returns the year,dt.isocalendar()[1]
returns the week number, dt.isocalendar()[2]
returns the week day. Simple as can be.
Like this:
void * p = (void *)0x28ff44;
Or if you want it as a char *
:
char * p = (char *)0x28ff44;
...etc.
If you're pointing to something you really, really aren't meant to change, add a const
:
const void * p = (const void *)0x28ff44;
const char * p = (const char *)0x28ff44;
...since I figure this must be some kind of "well-known address" and those are typically (though by no means always) read-only.
Write your <span>
in <h1>
or <h2>
:
<h1> <span class="glyphicon glyphicon-th-list"></span></h1>
I'd probably split the long statement up into multiple shorter statements so that the program logic is separated from the definition of the long string:
>>> def fun():
... format_string = '{0} Here is a really long ' \
... 'sentence with {1}'
... print format_string.format(3, 5)
If the string is only just too long and you choose a short variable name then by doing this you might even avoid having to split the string:
>>> def fun():
... s = '{0} Here is a really long sentence with {1}'
... print s.format(3, 5)
When you start a thread, it begins executing a function you give it (if you're extending threading.Thread
, the function will be run()
). To end the thread, just return from that function.
According to this, you can also call thread.exit()
, which will throw an exception that will end the thread silently.
Faced the same problem as OP:
Tomcat SSL certificate was expired while a browser showed it as secure - Apache certificate was far from expiration. Updating Tomcat KeyStore file solved the problem.
Try to point the classpathentry output path in the .classpath
file to target/classes
The classpath file is located in the project folder. Edit it manually.
In my case, it was like this before:
classpathentry kind="output" path="bin"
I changed it to:
classpathentry kind="output" path="target/classes"
Paste the following at the top of your JavaScript (before using the console):
/**
* Protect window.console method calls, e.g. console is not defined on IE
* unless dev tools are open, and IE doesn't define console.debug
*
* Chrome 41.0.2272.118: debug,error,info,log,warn,dir,dirxml,table,trace,assert,count,markTimeline,profile,profileEnd,time,timeEnd,timeStamp,timeline,timelineEnd,group,groupCollapsed,groupEnd,clear
* Firefox 37.0.1: log,info,warn,error,exception,debug,table,trace,dir,group,groupCollapsed,groupEnd,time,timeEnd,profile,profileEnd,assert,count
* Internet Explorer 11: select,log,info,warn,error,debug,assert,time,timeEnd,timeStamp,group,groupCollapsed,groupEnd,trace,clear,dir,dirxml,count,countReset,cd
* Safari 6.2.4: debug,error,log,info,warn,clear,dir,dirxml,table,trace,assert,count,profile,profileEnd,time,timeEnd,timeStamp,group,groupCollapsed,groupEnd
* Opera 28.0.1750.48: debug,error,info,log,warn,dir,dirxml,table,trace,assert,count,markTimeline,profile,profileEnd,time,timeEnd,timeStamp,timeline,timelineEnd,group,groupCollapsed,groupEnd,clear
*/
(function() {
// Union of Chrome, Firefox, IE, Opera, and Safari console methods
var methods = ["assert", "cd", "clear", "count", "countReset",
"debug", "dir", "dirxml", "error", "exception", "group", "groupCollapsed",
"groupEnd", "info", "log", "markTimeline", "profile", "profileEnd",
"select", "table", "time", "timeEnd", "timeStamp", "timeline",
"timelineEnd", "trace", "warn"];
var length = methods.length;
var console = (window.console = window.console || {});
var method;
var noop = function() {};
while (length--) {
method = methods[length];
// define undefined methods as noops to prevent errors
if (!console[method])
console[method] = noop;
}
})();
The function closure wrapper is to scope the variables as to not define any variables. This guards against both undefined console
and undefined console.debug
(and other missing methods).
EDIT: I noticed that HTML5 Boilerplate uses similar code in its js/plugins.js file, if you're looking for a solution that will (probably) be kept up-to-date.
This works for me
msg.BodyFormat = MailFormat.Html;
and then you can use html in your body
msg.Body = "<em>It's great to use HTML in mail!!</em>"
Updating timestamp, only if the values changed
Based on E.J's link and add a if statement from this link (https://stackoverflow.com/a/3084254/1526023)
CREATE OR REPLACE FUNCTION update_modified_column()
RETURNS TRIGGER AS $$
BEGIN
IF row(NEW.*) IS DISTINCT FROM row(OLD.*) THEN
NEW.modified = now();
RETURN NEW;
ELSE
RETURN OLD;
END IF;
END;
$$ language 'plpgsql';
If you want to check if a variable (say v) has been defined and is not null:
if (typeof v !== 'undefined' && v !== null) {
// Do some operation
}
If you want to check for all falsy values such as: undefined
, null
, ''
, 0
, false
:
if (v) {
// Do some operation
}
I have opened a (trivial) bug for this at m2e. Vote for it if you want the warning message to be gone for good...
In Git, to "fast forward" means to update the HEAD
pointer in such a way that its new value is a direct descendant of the prior value. In other words, the prior value is a parent, or grandparent, or grandgrandparent, ...
Fast forwarding is not possible when the new HEAD
is in a diverged state relative to the stream you want to integrate. For instance, you are on master
and have local commits, and git fetch
has brought new upstream commits into origin/master
. The branch now diverges from its upstream and cannot be fast forwarded: your master
HEAD
commit is not an ancestor of origin/master
HEAD
. To simply reset master
to the value of origin/master
would discard your local commits. The situation requires a rebase or merge.
If your local master
has no changes, then it can be fast-forwarded: simply updated to point to the same commit as the latestorigin/master
. Usually, no special steps are needed to do fast-forwarding; it is done by merge
or rebase
in the situation when there are no local commits.
Is it ok to assume that fast-forward means all commits are replayed on the target branch and the HEAD is set to the last commit on that branch?
No, that is called rebasing, of which fast-forwarding is a special case when there are no commits to be replayed (and the target branch has new commits, and the history of the target branch has not been rewritten, so that all the commits on the target branch have the current one as their ancestor.)
with all the adjusting css. if possible, wrap it with a table with height and width as 100% and td set it to vertical align to middle, text-align to center
For me the thing that worked was the order in which the namespaces were defined in the xsi:schemaLocation tag : [ since the version was all good and also it was transaction-manager already ]
The error was with :
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
AND RESOLVED WITH :
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
ALTER TABLE {TABLE NAME}
ALTER COLUMN {COLUMN NAME} SET DEFAULT '{DEFAULT VALUES}'
example :
ALTER TABLE RESULT
ALTER COLUMN STATUS SET DEFAULT 'FAIL'
Another thing which might be causing this is a 'weird' symbol in your file and directory names. All umlaut (äöå) and other (éóâ etc) characters should be removed from the file and folder names. I've had this same issue sometimes because of these characters.
You can use math.ceil()
to round up, and then multiply by 10
import math
def roundup(x):
return int(math.ceil(x / 10.0)) * 10
To use just do
>>roundup(45)
50
in your receiving intent use as
Intent intent = getActivity().getIntent();
((TextView)view.findViewById(R.id.hello)).setText(intent.getStringExtra("Hello"));
and in your send intent
Intent intent = new Intent(getActivity(),Main2Activity.class);
intent.putExtra("Hello","Nisar");
getActivity().startActivity(intent);
remember both are in fragments
ArrayList
is unique in its naming standards. Here are the equivalencies:
Array.push -> ArrayList.add(Object o); // Append the list
Array.pop -> ArrayList.remove(int index); // Remove list[index]
Array.shift -> ArrayList.remove(0); // Remove first element
Array.unshift -> ArrayList.add(int index, Object o); // Prepend the list
Note that unshift
does not remove an element, but instead adds one to the list. Also note that corner-case behaviors are likely to be different between Java and JS, since they each have their own standards.
i was looking for the same problem and stumbled upon the following code.
How to get Client MAC address(Web):
To get the client MAC address only way we can rely on JavaScript and Active X control of Microsoft.It is only work in IE if Active X enable for IE. As the ActiveXObject is not available with the Firefox, its not working with the firefox and is working fine in IE.
This script is for IE only:
function showMacAddress() {_x000D_
var obj = new ActiveXObject("WbemScripting.SWbemLocator");_x000D_
var s = obj.ConnectServer(".");_x000D_
var properties = s.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration");_x000D_
var e = new Enumerator(properties);_x000D_
var output;_x000D_
output = '<table border="0" cellPadding="5px" cellSpacing="1px" bgColor="#CCCCCC">';_x000D_
output = output + '<tr bgColor="#EAEAEA"><td>Caption</td><td>MACAddress</td></tr>';_x000D_
while (!e.atEnd()) {_x000D_
e.moveNext();_x000D_
var p = e.item();_x000D_
if (!p) continue;_x000D_
output = output + '<tr bgColor="#FFFFFF">';_x000D_
output = output + '<td>' + p.Caption; +'</td>';_x000D_
output = output + '<td>' + p.MACAddress + '</td>';_x000D_
output = output + '</tr>';_x000D_
}_x000D_
output = output + '</table>';_x000D_
document.getElementById("box").innerHTML = output;_x000D_
}_x000D_
_x000D_
showMacAddress();
_x000D_
<div id='box'></div>
_x000D_
Below code worked for me
$today_start = Carbon::now()->format('Y-m-d 00:00:00');
$today_end = Carbon::now()->format('Y-m-d 23:59:59');
$start_activity = MarketingActivity::whereBetween('created_at', [$today_start, $today_end])
->orderBy('id', 'ASC')->limit(1)->get();
You can run the pipenv
command with the --rm
option as in:
pipenv --rm
This will remove the virtualenv created for you under ~/.virtualenvs
See https://pipenv.kennethreitz.org/en/latest/cli/#cmdoption-pipenv-rm
Here is another solution you could have used. It is working in my app.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
android.support.v7.app.ActionBar actionBar =getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.activity_main)
Then you can get rid of that import for the one line ActionBar use.
force it with -l
sudo umount -l ${HOME}/mount_dir
Beyond what's been said already about selectors, you may want to look at the NSInvocation class.
An NSInvocation is an Objective-C message rendered static, that is, it is an action turned into an object. NSInvocation objects are used to store and forward messages between objects and between applications, primarily by NSTimer objects and the distributed objects system.
An NSInvocation object contains all the elements of an Objective-C message: a target, a selector, arguments, and the return value. Each of these elements can be set directly, and the return value is set automatically when the NSInvocation object is dispatched.
Keep in mind that while it's useful in certain situations, you don't use NSInvocation in a normal day of coding. If you're just trying to get two objects to talk to each other, consider defining an informal or formal delegate protocol, or passing a selector and target object as has already been mentioned.
In my case problem was that my version of gradle was incompatible with jdk14, but despite in project structure dialog was selected 8jdk, it was necessarily to set jdk home for gradle separately in gradle.propperties
org.gradle.java.home=/Library/Java/JavaVirtualMachines/jdk1.8.0_251.jdk/Contents/Home
Nowadays, people use DESC
instead of DESCRIPTION
. For example:-
DESC users;
This can also happen in Intellij Ultimate, which has PyCharm integrated. The issue is as diagnosed above, you have the wrong interpreter selected.
The exact method to fix this for any given project is to go to Project Settings...Project and adjust the Project SDK. You can add a New Project SDK if you don't have Python 3 added by navigating to the python3 binary. This will fix the errors listed above. A shortcut to Project Settings is the blue checkerboard-type icon.
You can also add Python 3 as the default interpreter for Python projects. On OSX this is in File..Other Settings...Default Project Structure. There you can set the Project SDK which will now apply on each new project. It can be different on other platforms, but still similar.
Please do not copy from the clipboard . Just copy the url from your browser's location / Address bar .
We can check using ps command
# ps -aux | grep ssh
Will show all shh service running and we can find the tunnel service listed
import operator
sorted_x = sorted(x, key=operator.attrgetter('score'))
if you want to sort x in-place, you can also:
x.sort(key=operator.attrgetter('score'))
You can use one of the following technique to remove the last comma(,)
Solution1:
$string = "'name', 'name2', 'name3',"; // this is the full string or text.
$string = chop($string,","); // remove the last character (,) and store the updated value in $string variable.
echo $string; // to print update string.
Solution 2:
$string = '10,20,30,'; // this is the full string or text.
$string = rtrim($string,',');
echo $string; // to print update string.
Solution 3:
$string = "'name', 'name2', 'name3',"; // this is the full string or text.
$string = substr($string , 0, -1);
echo $string;
[Update]
As noted by other answers and commenters, as of Java 8 you can simply call Map#getOrDefault(...)
.
[Original]
There's no Map implementation that does this exactly but it would be trivial to implement your own by extending HashMap:
public class DefaultHashMap<K,V> extends HashMap<K,V> {
protected V defaultValue;
public DefaultHashMap(V defaultValue) {
this.defaultValue = defaultValue;
}
@Override
public V get(Object k) {
return containsKey(k) ? super.get(k) : defaultValue;
}
}
use window.open("file2.html");
to open on new window,
or use window.location.href = "file2.html"
to open on same window.
As mentioned by @Mike Ritacco but updated for SSMS 2008 R2
You will then get all of the INSERT statements for the data straight out of SSMS.
EDIT 2016-10-25 SQL Server 2016/SSMS 13.0.15900.1
Right click on the database name
Choose Tasks > Generate scripts
Depending on your settings the intro page may show or not
Choose 'Select specific database objects',
Expand the tree view and check the relevant tables
Click Next
Click Advanced
Under General section, choose the appropriate option for 'Types of data to script'
Click OK
Pick whether you want the output to go to a new query, the clipboard or a file
Click Next twice
Your script is prepared in accordance with the settings you picked above
Click Finish
CrossAlignment.center is using the Width of the 'Child Widget'
to center itself and hence gets rendered at the start of the page.
When the Column is centered within the page body's 'Center Container'
, the CrossAlignment.center uses page body's 'Center' as reference and renders the widget at the center of the page
Code
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(
title:"DynamicWidgetApp",
home:DynamicWidgetApp(),
));
class DynamicWidgetApp extends StatefulWidget{
@override
DynamicWidgetAppState createState() => DynamicWidgetAppState();
}
class DynamicWidgetAppState extends State<DynamicWidgetApp>{
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
//Removing body:Center will change the reference
// and render the widget at the start of the page
child: Column(
mainAxisAlignment : MainAxisAlignment.center,
crossAxisAlignment : CrossAxisAlignment.center,
children: [
Text("My Centered Widget"),
]
),
),
floatingActionButton: FloatingActionButton(
// onPressed: ,
child : Icon(Icons.add),
),
);
}
}
I just got another case to display backslash \
with Razor and Java Script.
My @Model.AreaName
looks like Name1\Name2\Name3 so when I display it all backslashes are gone and I see Name1Name2Name3
I found solution to fix it:
var areafullName = JSON.parse("@Html.Raw(HttpUtility.JavaScriptStringEncode(JsonConvert.SerializeObject(Model.AreaName)))");
Don't forget to add @using Newtonsoft.Json
on top of chtml
page.
In Python, strings are immutable, so you can't change their characters in-place.
You can, however, do the following:
for i in str:
srr += i
The reasons this works is that it's a shortcut for:
for i in str:
srr = srr + i
The above creates a new string with each iteration, and stores the reference to that new string in srr
.
Using a normal css selector:
$('.sys input[type=text], .sys select').each(function() {...})
If you don't like the repetition:
$('.sys').find('input[type=text],select').each(function() {...})
Or more concisely, pass in the context
argument:
$('input[type=text],select', '.sys').each(function() {...})
Note: Internally jQuery
will convert the above to find()
equivalent
Internally, selector context is implemented with the .find() method, so $('span', this) is equivalent to $(this).find('span').
I personally find the first alternative to be the most readable :), your take though
Use df.count()
to get the number of rows.
something like:
$("ul#wizard li").click(function () {
var index = $("ul#wizard li").index(this);
alert("index is: " + index)
});
Use List<T>.Insert(0, item)
or a LinkedList<T>.AddFirst()
.
$text="abc1234567890";
// truncate to 4 chars
echo substr(str_pad($text,4),0,4);
This avoids the problem of truncating a 4 char string to 10 chars .. (i.e. source is smaller than the required)
For completeness and future searches:
It's a matter of how cURL manages the buffer, the buffer disables the output stream with the -N option.
Example:
curl -s -N "URL" | grep -q Welcome
Try this:
{ "dt" : { "$gte" : ISODate("2013-10-01") } }
As an update, when doing
brew unlink python # If you have installed (with brew) another version of python
brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/f2a764ef944b1080be64bd88dca9a1d80130c558/Formula/python.rb
You may encounter
Error: python contains a recursive dependency on itself:
python depends on sphinx-doc
sphinx-doc depends on python
To bypass it, add the --ignore-dependencies
argument to brew install.
brew unlink python # If you have installed (with brew) another version of python
brew install --ignore-dependencies https://raw.githubusercontent.com/Homebrew/homebrew-core/f2a764ef944b1080be64bd88dca9a1d80130c558/Formula/python.rb
It is probably not the best thing to do. You need to at least check out your PHP error log for things going wrong ;)
# PHP error handling for development servers
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
php_flag log_errors on
php_flag ignore_repeated_errors off
php_flag ignore_repeated_source off
php_flag report_memleaks on
php_flag track_errors on
php_value docref_root 0
php_value docref_ext 0
php_value error_log /home/path/public_html/domain/PHP_errors.log
php_value error_reporting -1
php_value log_errors_max_len 0
str_replace
with arrays just performs all the replacements sequentially. Use strtr
instead to do them all at once:
$new_message = strtr($message, 'lmnopq...', 'abcdef...');
private void Form1_Load(object sender, EventArgs e)
{
PictureBox pb = new PictureBox();
pb.Location = new Point(0, 0);
pb.Size = new Size(150, 150);
pb.Image = Image.FromFile("E:\\Wallpaper (204).jpg");
pb.Visible = true;
this.Controls.Add(pb);
}
I have a simple solution on handling home button press. Here is my code, it can be useful:
public class LifeCycleActivity extends Activity {
boolean activitySwitchFlag = false;
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode == KeyEvent.KEYCODE_BACK)
{
activitySwitchFlag = true;
// activity switch stuff..
return true;
}
return false;
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
public void onPause(){
super.onPause();
Log.v("TAG", "onPause" );
if(activitySwitchFlag)
Log.v("TAG", "activity switch");
else
Log.v("TAG", "home button");
activitySwitchFlag = false;
}
public void gotoNext(View view){
activitySwitchFlag = true;
startActivity(new Intent(LifeCycleActivity.this, NextActivity.class));
}
}
As a summary, put a boolean in the activity, when activity switch occurs(startactivity event), set the variable and in onpause event check this variable..
This error occur when you don't correctly write blocks. Forgetting a ":", or not using "Tab" button for blocks and use spaces. When you are transporting a code from one editor to another editor,it can happen. And never forget this: errors aren't always on that line. I came here for this, but I've forgotten an except after a try. because of my unstandard editor, it happend. But it's possible in normal editor.
system()
executes a shell which is then responsible for parsing the arguments and executing the desired program. To execute the program directly, use fork() and exec() (which is what system() uses to execute the shell as well as what the shell itself uses to execute commands).
#include <unistd.h>
int main() {
if (fork() == 0) {
/*
* fork() returns 0 to the child process
* and the child's PID to the parent.
*/
execl("/path/to/foo", "foo", "arg1", "arg2", "arg3", 0);
/*
* We woundn't still be here if execl() was successful,
* so a non-zero exit value is appropriate.
*/
return 1;
}
return 0;
}
As mentioned in the comments to the question, the JDBC-ODBC Bridge is - as the name indicates - only a mechanism for the JDBC layer to "talk to" the ODBC layer. Even if you had a JDBC-ODBC Bridge on your Mac you would also need to have
So, for most people, using JDBC-ODBC Bridge technology to manipulate ACE/Jet ("Access") databases is really a practical option only under Windows. It is also important to note that the JDBC-ODBC Bridge will be has been removed in Java 8 (ref: here).
There are other ways of manipulating ACE/Jet databases from Java, such as UCanAccess and Jackcess. Both of these are pure Java implementations so they work on non-Windows platforms. For details on how to use UCanAccess see
You can iterate over the index values if your dataframe has already been created.
df = df.groupby('l_customer_id_i').agg(lambda x: ','.join(x))
for name in df.index:
print name
print df.loc[name]
Just adding a bit of extra information here in case someone has the same issue as me.
I use namespaces in my code and I had a class with a function that throws an Exception.
However my try/catch code in another class file was completely ignored and the normal PHP error for an uncatched exception was thrown.
Turned out I forgot to add "use \Exception;" at the top, adding that solved the error.
Dictionaries are not Serializable in C# by default, I don't know why, but it seems to have been a design choice.
Right now, I'd recommend using Json.NET to convert it to JSON and from there into a dictionary (and vice versa). Unless you really need the XML, I'd recommend using JSON completely.
The solution is given in the error itself, Goto My computer(Right click)-->properties-->Advanced system settings-->Environment variables-->Create new variable.
Give the following details to it:
Variable name : JAVA_HOME.
Variable value : (your path to java jdk installation folder).
To find the path for java installation, go to program files in your window installation drive (normally C drive). Find folder named JAVA, in that navigate to JDK folder.
Copy the link address from the top, and paste it in the Variable value .
Now Press Ok and once environment variable gets created restart the android studio.
Hope it helps.
Place your scripts in this order:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
I hesitate to post this answer, it is actually technically possible but it doesn't work that well in practice. The version numbers of the CLR and the core framework assemblies were not changed in 4.5. You still target v4.0.30319 of the CLR and the framework assembly version numbers are still 4.0.0.0. The only thing that's distinctive about the assembly manifest when you look at it with a disassembler like ildasm.exe is the presence of a [TargetFramework] attribute that says that 4.5 is needed, that would have to be altered. Not actually that easy, it is emitted by the compiler.
The biggest difference is not that visible, Microsoft made a long-overdue change in the executable header of the assemblies. Which specifies what version of Windows the executable is compatible with. XP belongs to a previous generation of Windows, started with Windows 2000. Their major version number is 5. Vista was the start of the current generation, major version number 6.
.NET compilers have always specified the minimum version number to be 4.00, the version of Windows NT and Windows 9x. You can see this by running dumpbin.exe /headers on the assembly. Sample output looks like this:
OPTIONAL HEADER VALUES
10B magic # (PE32)
...
4.00 operating system version
0.00 image version
4.00 subsystem version // <=== here!!
0 Win32 version
...
What's new in .NET 4.5 is that the compilers change that subsystem version to 6.00. A change that was over-due in large part because Windows pays attention to that number, beyond just checking if it is small enough. It also turns on appcompat features since it assumes that the program was written to work on old versions of Windows. These features cause trouble, particularly the way Windows lies about the size of a window in Aero is troublesome. It stops lying about the fat borders of an Aero window when it can see that the program was designed to run on a Windows version that has Aero.
You can alter that version number and set it back to 4.00 by running Editbin.exe on your assemblies with the /subsystem option. This answer shows a sample postbuild event.
That's however about where the good news ends, a significant problem is that .NET 4.5 isn't very compatible with .NET 4.0. By far the biggest hang-up is that classes were moved from one assembly to another. Most notably, that happened for the [Extension] attribute. Previously in System.Core.dll, it got moved to Mscorlib.dll in .NET 4.5. That's a kaboom on XP if you declare your own extension methods, your program says to look in Mscorlib for the attribute, enabled by a [TypeForwardedTo] attribute in the .NET 4.5 version of the System.Core reference assembly. But it isn't there when you run your program on .NET 4.0
And of course there's nothing that helps you stop using classes and methods that are only available on .NET 4.5. When you do, your program will fail with a TypeLoadException or MissingMethodException when run on 4.0
Just target 4.0 and all of these problems disappear. Or break that logjam and stop supporting XP, a business decision that programmers cannot often make but can certainly encourage by pointing out the hassles that it is causing. There is of course a non-zero cost to having to support ancient operating systems, just the testing effort is substantial. A cost that isn't often recognized by management, Windows compatibility is legendary, unless it is pointed out to them. Forward that cost to the client and they tend to make the right decision a lot quicker :) But we can't help you with that.
I found the problem was that I had the server path within the connection string in one of these variants:
SERVER\SQLEXPRESS
SERVER
When really I should have:
.\SQLEXPRESS
For some reason I got the error whenever it had difficulty locating the instance of SQL.
This maybe because the c compiler is designed to work in linux.I had this problem too and to fix it go to tools
and select compiler options
.In the box click on programs
Now you will see a tab with gcc
and make
and the respective path to it.Edit the gcc
and make
path to use mingw32-c++.exe
and mingw32-make.exe
respectively.Now it will work.
The reason was that you were using compilers built for linux.
Here is an easy way that guarantee to output the myFixedNumber rounded to two decimal places:
import java.text.DecimalFormat;
public class TwoDecimalPlaces {
static double myFixedNumber = 98765.4321;
public static void main(String[] args) {
System.out.println(new DecimalFormat("0.00").format(myFixedNumber));
}
}
The result is: 98765.43
^\+[1-9]{1}[0-9]{7,11}$
The Regular Expression ^\+[1-9]{1}[0-9]{7,11}$
fails for "+290 8000" and similar valid numbers that are shorter than 8 digits.
The longest numbers could be something like 3 digit country code, 3 digit area code, 8 digit subscriber number, making 14 digits.
It turns out that, out of the four possible permutations of including or excluding trailing or leading forward slashes on the BaseAddress
and the relative URI passed to the GetAsync
method -- or whichever other method of HttpClient
-- only one permutation works. You must place a slash at the end of the BaseAddress
, and you must not place a slash at the beginning of your relative URI, as in the following example.
using (var handler = new HttpClientHandler())
using (var client = new HttpClient(handler))
{
client.BaseAddress = new Uri("http://something.com/api/");
var response = await client.GetAsync("resource/7");
}
Even though I answered my own question, I figured I'd contribute the solution here since, again, this unfriendly behavior is undocumented. My colleague and I spent most of the day trying to fix a problem that was ultimately caused by this oddity of HttpClient
.
A shorter answer from here, adapted to this question:
var arr = $('.requiredText');
arr.each(function(index, item) {
var is_last_item = (index == (arr.length - 1));
});
Just for completeness.
If you are only unfamiliar with the auto-complete while typing syntax or inbuilt methods in the eclipse you can simply type the desired syntax or method name and press Ctrl+Space that will display the list of desired options and you can select one of them.
If the auto-complete option is not enabled then you have to check your settings from Windows menu -> Preferences -> Java -> Editor -> Content assist
a little example that works for me
.carousel-control-prev,
.carousel-control-next{
height: 50px;
width: 50px;
outline: $color-white;
background-size: 100%, 100%;
border-radius: 50%;
border: 1px solid $color-white;
background-color: $color-white;
}
.carousel-control-prev-icon {
background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23009be1' viewBox='0 0 8 8'%3E%3Cpath d='M5.25 0l-4 4 4 4 1.5-1.5-2.5-2.5 2.5-2.5-1.5-1.5z'/%3E%3C/svg%3E");
width: 30px;
height: 48px;
}
.carousel-control-next-icon {
background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23009be1' viewBox='0 0 8 8'%3E%3Cpath d='M2.75 0l-1.5 1.5 2.5 2.5-2.5 2.5 1.5 1.5 4-4-4-4z'/%3E%3C/svg%3E");
width: 30px;
height: 48px;
}
This is a perfect example of where you should use the macro recorder. Turn on the recorder and set the color of the cells through the UI. Stop the recorder and review the macro. It will generate a bunch of extraneous code, but it will also show you syntax that works for what you are trying to accomplish. Strip out what you don't need and modify (if you need to) what's left.
I was facing the same issue. In my case XML files were generated from c# program and feeded into AS400 for further processing. After some analysis identified that I was using UTF8 encoding while generating XML files whereas javac(in AS400) uses "UTF8 without BOM". So, had to write extra code similar to mentioned below:
//create encoding with no BOM
Encoding outputEnc = new UTF8Encoding(false);
//open file with encoding
TextWriter file = new StreamWriter(filePath, false, outputEnc);
file.Write(doc.InnerXml);
file.Flush();
file.Close(); // save and close it
I agree withe the other answers regarding the correct way to loop through the files. However the OP asked:
The code above doesn't work, do you know why?
Yes!
An excellent article What is the difference between test, [ and [[ ?] explains in detail that among other differences, you cannot use expression matching
or pattern matching
within the test
command (which is shorthand for [
)
Feature new test [[ old test [ Example Pattern matching = (or ==) (not available) [[ $name = a* ]] || echo "name does not start with an 'a': $name" Regular Expression =~ (not available) [[ $(date) =~ ^Fri\ ...\ 13 ]] && echo "It's Friday the 13th!" matching
So this is the reason your script fails. If the OP is interested in an answer with the [[
syntax (which has the disadvantage of not being supported on as many platforms as the [
command), I would be happy to edit my answer to include it.
EDIT: Any protips for how to format the data in the answer as a table would be helpful!
Yes, it is a shorthand form of
int count;
if (isHere)
count = getHereCount(index);
else
count = getAwayCount(index);
It's called the conditional operator. Many people (erroneously) call it the ternary operator, because it's the only ternary (three-argument) operator in Java, C, C++, and probably many other languages. But theoretically there could be another ternary operator, whereas there can only be one conditional operator.
The official name is given in the Java Language Specification:
§15.25 Conditional Operator ? :
The conditional operator
? :
uses the boolean value of one expression to decide which of two other expressions should be evaluated.
Note that both branches must lead to methods with return values:
It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.
In fact, by the grammar of expression statements (§14.8), it is not permitted for a conditional expression to appear in any context where an invocation of a void method could appear.
So, if doSomething()
and doSomethingElse()
are void methods, you cannot compress this:
if (someBool)
doSomething();
else
doSomethingElse();
into this:
someBool ? doSomething() : doSomethingElse();
Simple words:
booleanCondition ? executeThisPartIfBooleanConditionIsTrue : executeThisPartIfBooleanConditionIsFalse
For some odd reason, the width and height of the button have been reset. You need to specify them in the ID selector as well:
#rock {
width: 150px;
height: 150px;
background-image: url(http://th07.deviantart.net/fs70/150/i/2013/012/c/6/rock_01_png___by_alzstock-d5r84up.png);
background-repeat: no-repeat;
}
If your files have inconsistent use of spaces and tabs, you may find it helpful to include the -t
argument to expand the tabs:
diff -ty file1 file2
This is the Kotlin version of the function posted by VVB. I used it in the ListView Adapter to implement the "go to next row first EditText when Enter key is pressed on the last EditText of current row" feature in the getView().
In the ListViewAdapter class, fun getView(), add lastEditText.setOnKeyListner as below:
lastEditText.setOnKeyListener { v, keyCode, event ->
var setOnKeyListener = false
if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_UP) {
try {
val nextRow = getViewByPosition(position + 1, parent as ListView) as LinearLayout
val nextET = nextRow.findViewById(R.id.firstEditText) as EditText
nextET.isFocusableInTouchMode = true
nextET.requestFocus()
} catch (e: Exception) {
// do nothing
}
setOnKeyListener = true
}
setOnKeyListener
}
add the fun getViewByPosition() after fun getView() as below:
private fun getViewByPosition(pos: Int, listView: ListView): View? {
val firstListItemPosition: Int = listView.firstVisiblePosition
val lastListItemPosition: Int = firstListItemPosition + listView.childCount - 1
return if (pos < firstListItemPosition || pos > lastListItemPosition) {
listView.adapter.getView(pos, null, listView)
} else {
val childIndex = pos + listView.headerViewsCount - firstListItemPosition
listView.getChildAt(childIndex)
}
}
The client has a pre-seeded store of SSL certificate authorities' public keys. There must be a chain of trust from the certificate for the server up through intermediate authorities up to one of the so-called "root" certificates in order for the server to be trusted.
You can examine and/or alter the list of trusted authorities. Often you do this to add a certificate for a local authority that you know you trust - like the company you work for or the school you attend or what not.
The pre-seeded list can vary depending on which client you use. The big SSL certificate vendors insure that their root certs are in all the major browsers ($$$).
Monkey-in-the-middle attacks are "impossible" unless the attacker has the private key of a trusted root certificate. Since the corresponding certificates are widely deployed, the exposure of such a private key would have serious implications for the security of eCommerce generally. Because of that, those private keys are very, very closely guarded.
Double-tap only
It is quite easy to detect a double tap on a view by using SimpleOnGestureListener
(as demonstrated in Hannes Niederhausen's answer).
private class GestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onDoubleTap(MotionEvent e) {
return true;
}
}
I can't see a big advantage to re-inventing the logic for this (like bughi's answer).
Double-tap and Single-tap with delay
You can also use the SimpleOnGestureListener
to differentiate a single-tap and a double-tap as mutually exclusive events. To do that you just override onSingleTapConfirmed
. This will delay running the single-tap code until the system is certain that the user hasn't double-tapped (ie, the delay > ViewConfiguration.getDoubleTapTimeout()
). There is definately no reason to re-invent all the logic for that (as is done in this, this and other answers).
private class GestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
return true;
}
@Override
public boolean onDoubleTap(MotionEvent e) {
return true;
}
}
Double-tap and Single-tap with no delay
The potential problem with onSingleTapConfirmed
is the delay. Sometimes a noticeable delay is not acceptable. In that case you can replace onSingleTapConfirmed
with onSingleTapUp
.
private class GestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public boolean onDoubleTap(MotionEvent e) {
return true;
}
}
You need to realize, though, that both onSingleTapUp
and onDoubleTap
will be called if there is a double-tap. (This is essentially what bughi's answer does and what some of the commenters were complaining about.) You either need to use the delay or call both methods. It's not possible have a single-tap with no delay and at the same time know whether the user is going to tap again.
If the single-tap delay is not acceptable for you then you have a couple options:
onSingleTapUp
and onDoubleTap
will be called for a double-tap. Just divide up your logic appropriately so that it doesn't matter. This is essentially what I did when I implemented a double-tap for caps-lock on a custom keyboard.Don't use a double-tap. It's not an intuitive UI action for most things. As Dave Webb suggests, a long press is probably better. You can also implement that with the SimpleOnGestureListener
:
private class GestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
}
}
Both are equivalent. Take a look at the following:
int[] array;
// is equivalent to
int array[];
int var, array[];
// is equivalent to
int var;
int[] array;
int[] array1, array2[];
// is equivalent to
int[] array1;
int[][] array2;
public static int[] getArray()
{
// ..
}
// is equivalent to
public static int getArray()[]
{
// ..
}
In android studio do the following steps to check the gradle downloaded jar file.
In intellij you can auto generate toString method by pressing alt+inset and then selecting toString() here is an out put for a test class:
public class test {
int a;
char b;
String c;
Test2 test2;
@Override
public String toString() {
return "test{" +
"a=" + a +
", b=" + b +
", c='" + c + '\'' +
", test2=" + test2 +
'}';
}
}
As you can see, it generates a String by concatenating, several attributes of the class, for primitives it will print their values and for reference types it will use their class type (in this case to string method of Test2).