Use FileSaver.js
. It supports Chrome, Edge, Firefox, and IE 10+ (and probably IE < 10 with a few "polyfills" - see Note 4). FileSaver.js
implements the saveAs() FileSaver interface in browsers that do not natively support it:
https://github.com/eligrey/FileSaver.js
Minified version is really small at < 2.5KB, gzipped < 1.2KB.
Usage:
/* TODO: replace the blob content with your byte[] */
var blob = new Blob([yourBinaryDataAsAnArrayOrAsAString], {type: "application/octet-stream"});
var fileName = "myFileName.myExtension";
saveAs(blob, fileName);
You might need Blob.js in some browsers (see Note 3). Blob.js implements the W3C Blob interface in browsers that do not natively support it. It is a cross-browser implementation:
https://github.com/eligrey/Blob.js
Consider StreamSaver.js if you have files larger than blob's size limitations.
Complete example:
/* Two options_x000D_
* 1. Get FileSaver.js from here_x000D_
* https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.min.js -->_x000D_
* <script src="FileSaver.min.js" />_x000D_
*_x000D_
* Or_x000D_
*_x000D_
* 2. If you want to support only modern browsers like Chrome, Edge, Firefox, etc., _x000D_
* then a simple implementation of saveAs function can be:_x000D_
*/_x000D_
function saveAs(blob, fileName) {_x000D_
var url = window.URL.createObjectURL(blob);_x000D_
_x000D_
var anchorElem = document.createElement("a");_x000D_
anchorElem.style = "display: none";_x000D_
anchorElem.href = url;_x000D_
anchorElem.download = fileName;_x000D_
_x000D_
document.body.appendChild(anchorElem);_x000D_
anchorElem.click();_x000D_
_x000D_
document.body.removeChild(anchorElem);_x000D_
_x000D_
// On Edge, revokeObjectURL should be called only after_x000D_
// a.click() has completed, atleast on EdgeHTML 15.15048_x000D_
setTimeout(function() {_x000D_
window.URL.revokeObjectURL(url);_x000D_
}, 1000);_x000D_
}_x000D_
_x000D_
(function() {_x000D_
// convert base64 string to byte array_x000D_
var byteCharacters = atob("R0lGODlhkwBYAPcAAAAAAAABGRMAAxUAFQAAJwAANAgwJSUAACQfDzIoFSMoLQIAQAAcQwAEYAAHfAARYwEQfhkPfxwXfQA9aigTezchdABBckAaAFwpAUIZflAre3pGHFpWVFBIf1ZbYWNcXGdnYnl3dAQXhwAXowkgigIllgIxnhkjhxktkRo4mwYzrC0Tgi4tiSQzpwBIkBJIsyxCmylQtDVivglSxBZu0SlYwS9vzDp94EcUg0wziWY0iFROlElcqkxrtW5OjWlKo31kmXp9hG9xrkty0ziG2jqQ42qek3CPqn6Qvk6I2FOZ41qn7mWNz2qZzGaV1nGOzHWY1Gqp3Wy93XOkx3W1x3i33G6z73nD+ZZIHL14KLB4N4FyWOsECesJFu0VCewUGvALCvACEfEcDfAcEusKJuoINuwYIuoXN+4jFPEjCvAgEPM3CfI5GfAxKuoRR+oaYustTus2cPRLE/NFJ/RMO/dfJ/VXNPVkNvFPTu5KcfdmQ/VuVvl5SPd4V/Nub4hVj49ol5RxoqZfl6x0mKp5q8Z+pu5NhuxXiu1YlvBdk/BZpu5pmvBsjfBilvR/jvF3lO5nq+1yre98ufBoqvBrtfB6p/B+uPF2yJiEc9aQMsSKQOibUvqKSPmEWPyfVfiQaOqkSfaqTfyhXvqwU+u7dfykZvqkdv+/bfy1fpGvvbiFnL+fjLGJqqekuYmTx4SqzJ2+2Yy36rGawrSwzpjG3YjB6ojG9YrU/5XI853U75bV/J3l/6PB6aDU76TZ+LHH6LHX7rDd+7Lh3KPl/bTo/bry/MGJm82VqsmkjtSptfWMj/KLsfu0je6vsNW1x/GIxPKXx/KX1ea8w/Wnx/Oo1/a3yPW42/S45fvFiv3IlP/anvzLp/fGu/3Xo/zZt//knP7iqP7qt//xpf/0uMTE3MPd1NXI3MXL5crS6cfe99fV6cXp/cj5/tbq+9j5/vbQy+bY5/bH6vbJ8vfV6ffY+f7px/3n2f/4yP742OPm8ef9//zp5vjn/f775/7+/gAAACwAAAAAkwBYAAAI/wD9CRxIsKDBgwgTKlzIsKHDhxAjSpxIsaLFixgzatzIsaPHjxD7YQrSyp09TCFSrQrxCqTLlzD9bUAAAMADfVkYwCIFoErMn0AvnlpAxR82A+tGWWgnLoCvoFCjOsxEopzRAUYwBFCQgEAvqWDDFgTVQJhRAVI2TUj3LUAusXDB4jsQxZ8WAMNCrW37NK7foN4u1HThD0sBWpoANPnL+GG/OV2gSUT24Yi/eltAcPAAooO+xqAVbkPT5VDo0zGzfemyqLE3a6hhmurSpRLjcGDI0ItdsROXSAn5dCGzTOC+d8j3gbzX5ky8g+BoTzq4706XL1/KzONdEBWXL3AS3v/5YubavU9fuKg/44jfQmbK4hdn+Jj2/ILRv0wv+MnLdezpweEed/i0YcYXkCQkB3h+tPEfgF3AsdtBzLSxGm1ftCHJQqhc54Y8B9UzxheJ8NfFgWakSF6EA57WTDN9kPdFJS+2ONAaKq6Whx88enFgeAYx892FJ66GyEHvvGggeMs0M01B9ajRRYkD1WMgF60JpAx5ZEgGWjZ44MHFdSkeSBsceIAoED5gqFgGbAMxQx4XlxjESRdcnFENcmmcGBlBfuDh4Ikq0kYGHoxUKSWVApmCnRsFCddlaEPSVuaFED7pDz5F5nGQJ9cJWFA/d1hSUCfYlSFQfdgRaqal6UH/epmUjRDUx3VHEtTPHp5SOuYyn5x4xiMv3jEmlgKNI+w1B/WTxhdnwLnQY2ZwEY1AeqgHRzN0/PiiMmh8x8Vu9YjRxX4CjYcgdwhhE6qNn8DBrD/5AXnQeF3ct1Ap1/VakB3YbThQgXEIVG4X1w7UyXUFs2tnvwq5+0XDBy38RZYMKQuejf7Yw4YZXVCjEHwFyQmyyA4TBPAXhiiUDcMJzfaFvwXdgWYbz/jTjxjgTTiQN2qYQca8DxV44KQpC7SyIi7DjJCcExeET7YAplcGNQvC8RxB3qS6XUTacHEgF7mmvHTTUT+Nnb06Ozi2emOWYeEZRAvUdXZfR/SJ2AdS/8zuymUf9HLaFGLnt3DkPTIQqTLSXRDQ2W0tETbYHSgru3eyjLbfJa9dpYEIG6QHdo4T5LHQdUfUjduas9vhxglJzLaJhKtGOEHdhKrm4gB3YapFdlznHLvhiB1tQtqEmpDFFL9umkH3hNGzQTF+8YZjzGi6uBgg58yuHH0nFM67CIH/xfP+OH9Q9LAXRHn3Du1NhuQCgY80dyZ/4caee58xocYSOgg+uOe7gWzDcwaRWMsOQocVLQI5bOBCggzSDzx8wQsTFEg4RnQ8h1nnVdchA8rucZ02+Iwg4xOaly4DOu8tbg4HogRC6uGfVx3oege5FbQ0VQ8Yts9hnxiUpf9qtapntYF+AxFFqE54qwPlYR772Mc2xpAiLqSOIPiwIG3OJC0ooQFAOVrNFbnTj/jEJ3U4MgPK/oUdmumMDUWCm6u6wDGDbMOMylhINli3IjO4MGkLqcMX7rc4B1nRIPboXdVUdLmNvExFGAMkQxZGHAHmYYXQ4xGPogGO1QBHkn/ZhhfIsDuL3IMLbjghKDECj3O40pWrjIk6XvkZj9hDCEKggAh26QAR9IAJsfzILXkpghj0RSPOYAEJdikCEjjTmczURTA3cgxmQlMEJbBFRlixAms+85vL3KUVpomRQOwSnMtUwTos8g4WnBOd8BTBCNxBzooA4p3oFAENKLL/Dx/g85neRCcEblDPifjzm/+UJz0jkgx35tMBSWDFCZqZTxWwo6AQYQVFwzkFh17zChG550YBKoJx9iMHIwVoCY6J0YVUk6K7TII/UEpSJRQNpSkNZy1WRdN8lgAXLWXIOyYKUIv2o5sklWlD7EHUfIrApsbxKDixqc2gJqQfOBipA4qwqRVMdQgNaWdOw2kD00kVodm0akL+MNJdfuYdbRWBUhVy1LGmc6ECEWs8S0AMtR4kGfjcJREEAliEPnUh9uipU1nqD8COVQQqwKtfBWIPXSJUBcEQCFsNO06F3BOe4ZzrQDQKWhHMYLIFEURKRVCDz5w0rlVFiEbtCtla/xLks/B0wBImAo98iJSZIrDBRTPSjqECd5c7hUgzElpSyjb1msNF0j+nCtJRaeCxIoiuQ2YhhF4el5cquIg9kJAD735Xt47RwWqzS9iEhjch/qTtaQ0C18fO1yHvQAFzmflTiwBiohv97n0bstzV3pcQCR0sQlQxXZLGliDVjGdzwxrfADvgBULo60WSEQHm8uAJE8EHUqfaWX8clKSMHViDAfoC2xJksxWVbEKSMWKSOgGvhOCBjlO8kPgi1AEqAMbifqDjsjLkpVNVZ15rvMwWI4SttBXBLQR41muWWCFQnuoLhquOCoNXxggRa1yVuo9Z6PK4okVklZdpZH8YY//MYWZykhFS4Io2JMsIjQE97cED814TstpFkgSY29lk4DTAMZ1xTncJVX+oF60aNgiMS8vVg4h0qiJ4MEJ8jNAX0FPMpR2wQaRRZUYLZBArDueVCXJdn0rzMgmttEHwYddr8riy603zQfBM0uE6o5u0dcCqB/IOyxq2zeasNWTBvNx4OtkfSL4mmE9d6yZPm8EVdfFBZovpRm/qzBJ+tq7WvEvtclvCw540QvepsxOH09u6UqxTdd3V1UZ2IY7FdAy0/drSrtQg7ibpsJsd6oLoNZ+vdsY7d9nmUT/XqcP2RyGYy+NxL9oB1TX4isVZkHxredq4zec8CXJuhI5guCH/L3dCLu3vYtD3rCpfCKoXPQJFl7bh/TC2YendbuwOg9WPZXd9ba2QgNtZ0ohWQaQTYo81L5PdzZI3QBse4XyS4NV/bfAusQ7X0ioVxrvUdEHsIeepQn0gdQ6nqBOCagmLneRah3rTH6sCbeuq7LvMeNUxPU69hn0hBAft0w0ycxEAORYI2YcrWJoBuq8zIdLQeps9PtWG73rRUh6I0aHZ3wqrAKiArzYJ0FsQbjjAASWIRTtkywIH3Hfo+RQ3ksjd5pCDU9gyx/zPN+V0EZiAGM3o5YVXP5Bk1OAgbxa8M3EfEXNUgJltnnk8bWB3i+dztzprfGkzTmfMDzftH8fH/w9igHWBBF8EuzBI8pUvAu43JNnLL7G6EWp5Na8X9GQXvAjKf5DAF3Ug0fZxCPFaIrB7BOF/8fR2COFYMFV3q7IDtFV/Y1dqniYQ3KBs/GcQhXV72OcPtpdn1eeBzBRo/tB1ysd8C+EMELhwIqBg/rAPUjd1IZhXMBdcaKdsCjgQbWdYx7R50KRn28ZM71UQ+6B9+gdvFMRp16RklOV01qYQARhOWLd3AoWEBfFoJCVuPrhM+6aB52SDllZt+pQQswAE3jVVpPeAUZaBBGF0pkUQJuhsCgF714R4mkdbTDhavRROoGcQUThVJQBmrLADZ4hpQzgQ87duCUGH4fRgIuOmfyXAhgLBctDkgHfob+UHf00Wgv1WWpDFC+qADuZwaNiVhwCYarvEY1gFZwURg9fUhV4YV0vnD+bkiS+ADurACoW4dQoBfk71XcFmA9NWD6mWTozVD+oVYBAge9SmfyIgAwbhDINmWEhIeZh2XNckgQVBicrHfrvkBFgmhsW0UC+FaMxIg8qGTZ3FD0r4bgfBVKKnbzM4EP1UjN64Sz1AgmOHU854eoUYTg4gjIqGirx0eoGFTVbYjN0IUMs4bc1yXfFoWIZHA/ngEGRnjxImVwwxWxFpWCPgclfVagtpeC9AfKIPwY3eGAM94JCehZGGFQOzuIj8uJDLhHrgKFRlh2k8xxCz8HwBFU4FaQOzwJIMQQ5mCFzXaHg28AsRUWbA9pNA2UtQ8HgNAQ8QuV6HdxHvkALudFwpAAMtEJMWMQgsAAPAyJVgxU47AANdCVwlAJaSuJEsAGDMBJYGiBH94Ap6uZdEiRGysJd7OY8S8Q6AqZe8kBHOUJiCiVqM2ZiO+ZgxERAAOw==");_x000D_
var byteNumbers = new Array(byteCharacters.length);_x000D_
for (var i = 0; i < byteCharacters.length; i++) {_x000D_
byteNumbers[i] = byteCharacters.charCodeAt(i);_x000D_
}_x000D_
var byteArray = new Uint8Array(byteNumbers);_x000D_
_x000D_
// now that we have the byte array, construct the blob from it_x000D_
var blob1 = new Blob([byteArray], {type: "application/octet-stream"});_x000D_
_x000D_
var fileName1 = "cool.gif";_x000D_
saveAs(blob1, fileName1);_x000D_
_x000D_
// saving text file_x000D_
var blob2 = new Blob(["cool"], {type: "text/plain"});_x000D_
var fileName2 = "cool.txt";_x000D_
saveAs(blob2, fileName2);_x000D_
})();
_x000D_
Tested on Chrome, Edge, Firefox, and IE 11 (use FileSaver.js
for supporting IE 11).
You can also save from a canvas
element. See https://github.com/eligrey/FileSaver.js#saving-a-canvas.
Demos: https://eligrey.com/demos/FileSaver.js/
Blog post by author of FileSaver.js
: http://eligrey.com/blog/post/saving-generated-files-on-the-client-side
Note 1: Browser support: https://github.com/eligrey/FileSaver.js#supported-browsers
Note 2: Failed to execute 'atob' on 'Window'
Note 3: Polyfill for browsers not supporting Blob: https://github.com/eligrey/Blob.js
See http://caniuse.com/#search=blob
Note 4: IE < 10 support (I've not tested this part):
https://github.com/eligrey/FileSaver.js#ie--10
https://github.com/eligrey/FileSaver.js/issues/56#issuecomment-30917476
Downloadify is a Flash-based polyfill for supporting IE6-9: https://github.com/dcneiner/downloadify (I don't recommend Flash-based solutions in general, though.)
Demo using Downloadify and FileSaver.js for supporting IE6-9 also: http://sheetjs.com/demos/table.html
Note 5: Creating a BLOB from a Base64 string in JavaScript
Note 6: FileSaver.js
examples: https://github.com/eligrey/FileSaver.js#examples
Very Simple to clear editText values.when u click button then only follow 1 line code.
Inside button or anywhere u want.Only use this
editText.setText("");
You need to check the keycloak admin console for fronted configuration. It must be wrongly configured for redirect url and web origins.
Use this.
if(_dialog!=null && _dialog.isShowing()) _dialog.dismiss();
Old topic, but worth a try.
Here is a simple and efficient var_dump
function:
def var_dump(var, prefix=''):
"""
You know you're a php developer when the first thing you ask for
when learning a new language is 'Where's var_dump?????'
"""
my_type = '[' + var.__class__.__name__ + '(' + str(len(var)) + ')]:'
print(prefix, my_type, sep='')
prefix += ' '
for i in var:
if type(i) in (list, tuple, dict, set):
var_dump(i, prefix)
else:
if isinstance(var, dict):
print(prefix, i, ': (', var[i].__class__.__name__, ') ', var[i], sep='')
else:
print(prefix, '(', i.__class__.__name__, ') ', i, sep='')
Sample output:
>>> var_dump(zen)
[list(9)]:
(str) hello
(int) 3
(int) 43
(int) 2
(str) goodbye
[list(3)]:
(str) hey
(str) oh
[tuple(3)]:
(str) jij
(str) llll
(str) iojfi
(str) call
(str) me
[list(7)]:
(str) coucou
[dict(2)]:
oKey: (str) oValue
key: (str) value
(str) this
[list(4)]:
(str) a
(str) new
(str) nested
(str) list
What do you mean by "not always reliable"? If the system succeeds in setting your socket non non-blocking, it will be non-blocking. Socket operations will return EWOULDBLOCK
if they would block need to block (e.g. if the output buffer is full and you're calling send/write too often).
This forum thread has a few good points when working with non-blocking calls.
For me what worked has is using NavLink as it has this active class property.
First import it
import { NavLink } from 'react-router-dom';
Use an activeClassName to get the active class property.
<NavLink to="/" activeClassName="active">
Home
</NavLink>
<NavLink to="/store" activeClassName="active">
Store
</NavLink>
<NavLink to="/about" activeClassName="active">
About Us
</NavLink>
Style your class in the css by the property active.
.active{
color:#fcfcfc;
}
That was my case. It actually links to question #4485874, but I'm going to explain it here shortly.
When you try to require path/to/script.php?parameter=value
, PHP looks for file named script.php?parameter=value
, because UNIX allows you to have paths like this.
If you are really need to pass some data to included script, just declare it as $variable=...
or $GLOBALS[]=...
or other way you like.
The compiler replaces null comparisons with a call to HasValue
, so there is no real difference. Just do whichever is more readable/makes more sense to you and your colleagues.
Try this:
$('#myAnchor')[0].click();
It works for me.
Swift 2.1 Version of Usman Y's answer. Use a print statement to verify so call by some string value
print(self.validateCardType(self.creditCardField.text!))
func validateCardType(testCard: String) -> String {
let regVisa = "^4[0-9]{12}(?:[0-9]{3})?$"
let regMaster = "^5[1-5][0-9]{14}$"
let regExpress = "^3[47][0-9]{13}$"
let regDiners = "^3(?:0[0-5]|[68][0-9])[0-9]{11}$"
let regDiscover = "^6(?:011|5[0-9]{2})[0-9]{12}$"
let regJCB = "^(?:2131|1800|35\\d{3})\\d{11}$"
let regVisaTest = NSPredicate(format: "SELF MATCHES %@", regVisa)
let regMasterTest = NSPredicate(format: "SELF MATCHES %@", regMaster)
let regExpressTest = NSPredicate(format: "SELF MATCHES %@", regExpress)
let regDinersTest = NSPredicate(format: "SELF MATCHES %@", regDiners)
let regDiscoverTest = NSPredicate(format: "SELF MATCHES %@", regDiscover)
let regJCBTest = NSPredicate(format: "SELF MATCHES %@", regJCB)
if regVisaTest.evaluateWithObject(testCard){
return "Visa"
}
else if regMasterTest.evaluateWithObject(testCard){
return "MasterCard"
}
else if regExpressTest.evaluateWithObject(testCard){
return "American Express"
}
else if regDinersTest.evaluateWithObject(testCard){
return "Diners Club"
}
else if regDiscoverTest.evaluateWithObject(testCard){
return "Discover"
}
else if regJCBTest.evaluateWithObject(testCard){
return "JCB"
}
return ""
}
Here's another way to drop a default constraint with an unknown name without having to first run a separate query to get the constraint name:
DECLARE @ConstraintName nvarchar(200)
SELECT @ConstraintName = Name FROM SYS.DEFAULT_CONSTRAINTS
WHERE PARENT_OBJECT_ID = OBJECT_ID('__TableName__')
AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns
WHERE NAME = N'__ColumnName__'
AND object_id = OBJECT_ID(N'__TableName__'))
IF @ConstraintName IS NOT NULL
EXEC('ALTER TABLE __TableName__ DROP CONSTRAINT ' + @ConstraintName)
Add new column to DataTable
and use column Expression
property to set your Status expression.
Here you can find good example: DataColumn.Expression
Property
DataTable and DataColumn Expressions in ADO.NET - Calculated Columns
UPDATE
Code sample:
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("colBestBefore", typeof(DateTime)));
dt.Columns.Add(new DataColumn("colStatus", typeof(string)));
dt.Columns["colStatus"].Expression = String.Format("IIF(colBestBefore < #{0}#, 'Ok','Not ok')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
dt.Rows.Add(DateTime.Now.AddDays(-1));
dt.Rows.Add(DateTime.Now.AddDays(1));
dt.Rows.Add(DateTime.Now.AddDays(2));
dt.Rows.Add(DateTime.Now.AddDays(-2));
demoGridView.DataSource = dt;
UPDATE #2
dt.Columns["colStatus"].Expression = String.Format("IIF(CONVERT(colBestBefore, 'System.DateTime') < #{0}#, 'Ok','Not ok')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
PropertyInfo.SetValue() can assign ints to enums, ints to nullable ints, enums to nullable enums, but not ints to nullable enums.
enumProperty.SetValue(obj, 1, null); //works
nullableIntProperty.SetValue(obj, 1, null); //works
nullableEnumProperty.SetValue(obj, MyEnum.Foo, null); //works
nullableEnumProperty.SetValue(obj, 1, null); // throws an exception !!!
Full description here
If the package provides a Makefile.PL
- one can use:
perl Makefile.PL PREFIX=/home/my/local/lib LIB=/home/my/local/lib
make
make test
make install
* further explanation: https://www.perlmonks.org/?node_id=564720
This solves the issue in the appropriate way
// Merge a row
ws.Cell("B2").Value = "Merged Row(1) of Range (B2:D3)";
ws.Range("B2:D3").Row(1).Merge();
git cherry-pick
: Apply the changes introduced by some existing commits
Assume we have branch A with (X, Y, Z) commits. We need to add these commits to branch B. We are going to use the cherry-pick
operations.
When we use cherry-pick
, we should add commits on branch B in the same chronological order that the commits appear in Branch A.
cherry-pick does support a range of commits, but if you have merge commits in that range, it gets really complicated
git checkout B
git cherry-pick SHA-COMMIT-X
git cherry-pick SHA-COMMIT-Y
git cherry-pick SHA-COMMIT-Z
Example of workflow :
We can use cherry-pick
with options
-e or --edit : With this option, git cherry-pick will let you edit the commit message prior to committing.
-n or --no-commit : Usually the command automatically creates a sequence of commits. This flag applies the changes necessary to cherry-pick each named commit to your working tree and the index, without making any commit. In addition, when this option is used, your index does not have to match the HEAD commit. The cherry-pick is done against the beginning state of your index.
Here an interesting article concerning cherry-pick
.
If you use the Eclipse "New Android Project" wizard in a recent ADT bundle, you'll automatically get tabs implemented as a Fragments. This makes the conversion of your application to the tablet format much easier in the future.
For simple single screen layouts you may still use Activity
.
More information about how you'll be working with your data before transferring it would help a ton. The json module provides dump(s) and load(s) methods that'll help if you're using 2.6 or newer: http://docs.python.org/library/json.html.
-- EDITED --
Without knowing which libraries you're using I can't tell you for sure if you'll find a method like that. Normally, I'll process query results like this (examples with kinterbasdb because it's what we're currently working with):
qry = "Select Id, Name, Artist, Album From MP3s Order By Name, Artist"
# Assumes conn is a database connection.
cursor = conn.cursor()
cursor.execute(qry)
rows = [x for x in cursor]
cols = [x[0] for x in cursor.description]
songs = []
for row in rows:
song = {}
for prop, val in zip(cols, row):
song[prop] = val
songs.append(song)
# Create a string representation of your array of songs.
songsJSON = json.dumps(songs)
There are undoubtedly better experts out there who'll have list comprehensions to eliminate the need for written out loops, but this works and should be something you could adapt to whatever library you're retrieving records with.
This msdn article explains it very well with examples, "A tuple is a data structure that has a specific number and sequence of elements".
Tuples are commonly used in four ways:
To represent a single set of data. For example, a tuple can represent a database record, and its components can represent individual fields of the record.
To provide easy access to, and manipulation of, a data set.
To return multiple values from a method without using out parameters (in C#) or
ByRef
parameters (in Visual Basic).To pass multiple values to a method through a single parameter. For example, the
Thread.Start(Object)
method has a single parameter that lets you supply one value to the method that the thread executes at startup time. If you supply aTuple<T1, T2, T3>
object as the method argument, you can supply the thread’s startup routine with three items of data.
This Worked for me. i implemented this solution in reactJS
const requestOptions = {`enter code here`
method: 'GET',
headers: { 'Content-Type': 'application/json' }
};
fetch(`${url}`, requestOptions)
.then((res) => {
return res.blob();
})
.then((blob) => {
const href = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = href;
link.setAttribute('download', 'config.json'); //or any other extension
document.body.appendChild(link);
link.click();
})
.catch((err) => {
return Promise.reject({ Error: 'Something Went Wrong', err });
})
You actually don't have to use FormData
to send a Blob
to the server from JavaScript (and a File
is also a Blob
).
jQuery example:
var file = $('#fileInput').get(0).files.item(0); // instance of File
$.ajax({
type: 'POST',
url: 'upload.php',
data: file,
contentType: 'application/my-binary-type', // set accordingly
processData: false
});
Vanilla JavaScript example:
var file = $('#fileInput').get(0).files.item(0); // instance of File
var xhr = new XMLHttpRequest();
xhr.open('POST', '/upload.php', true);
xhr.onload = function(e) { ... };
xhr.send(file);
Granted, if you are replacing a traditional HTML multipart form with an "AJAX" implementation (that is, your back-end consumes multipart form data), you want to use the FormData
object as described in another answer.
In C# Predicates are simply delegates that return booleans. They're useful (in my experience) when you're searching through a collection of objects and want something specific.
I've recently run into them in using 3rd party web controls (like treeviews) so when I need to find a node within a tree, I use the .Find() method and pass a predicate that will return the specific node I'm looking for. In your example, if 'a' mod 2 is 0, the delegate will return true. Granted, when I'm looking for a node in a treeview, I compare it's name, text and value properties for a match. When the delegate finds a match, it returns the specific node I was looking for.
You should never be writing code that looks like this:
private void DoGUISwitch() {
if (object1.InvokeRequired) {
object1.Invoke(new MethodInvoker(() => { DoGUISwitch(); }));
} else {
object1.Visible = true;
object2.Visible = false;
}
}
If you do have code that looks like this then your application is not thread-safe. It means that you have code which is already calling DoGUISwitch() from a different thread. It's too late to be checking to see if it's in a different thread. InvokeRequire must be called BEFORE you make a call to DoGUISwitch. You should not access any method or property from a different thread.
Reference: Control.InvokeRequired Property where you can read the following:
In addition to the InvokeRequired property, there are four methods on a control that are thread safe to call: Invoke, BeginInvoke, EndInvoke and CreateGraphics if the handle for the control has already been created.
In a single CPU architecture there's no problem, but in a multi-CPU architecture you can cause part of the UI thread to be assigned to the processor where the calling code was running...and if that processor is different from where the UI thread was running then when the calling thread ends Windows will think that the UI thread has ended and will kill the application process i.e. your application will exit without error.
Simple, standard library only. Gives timezone-aware datetime, unlike datetime.utcnow()
.
from datetime import datetime,timezone
now_utc = datetime.now(timezone.utc)
Unfortunately there is no such class in Bootstrap as of now (27th Jan 2019).
I scanned through bootstrap code and discovered following classes that use cursor: pointer. Seems like it is not a good idea to use any of them specifically for cursor: pointer.
summary {
display: list-item;
cursor: pointer;
}
.btn:not(:disabled):not(.disabled) {
cursor: pointer;
}
.custom-range::-webkit-slider-runnable-track {
width: 100%;
height: 0.5rem;
color: transparent;
cursor: pointer;
background-color: #dee2e6;
border-color: transparent;
border-radius: 1rem;
}
.custom-range::-moz-range-track {
width: 100%;
height: 0.5rem;
color: transparent;
cursor: pointer;
background-color: #dee2e6;
border-color: transparent;
border-radius: 1rem;
}
.custom-range::-ms-track {
width: 100%;
height: 0.5rem;
color: transparent;
cursor: pointer;
background-color: transparent;
border-color: transparent;
border-width: 0.5rem;
}
.navbar-toggler:not(:disabled):not(.disabled) {
cursor: pointer;
}
.page-link:not(:disabled):not(.disabled) {
cursor: pointer;
}
.close:not(:disabled):not(.disabled) {
cursor: pointer;
}
.carousel-indicators li {
box-sizing: content-box;
-ms-flex: 0 1 auto;
flex: 0 1 auto;
width: 30px;
height: 3px;
margin-right: 3px;
margin-left: 3px;
text-indent: -999px;
cursor: pointer;
background-color: #fff;
background-clip: padding-box;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
opacity: .5;
transition: opacity 0.6s ease;
}
The only OBVIOUS SOLUTION:
What I would suggest you is just to create a class in your common css as cursor-pointer
. That is simple and elegant as of now.
.cursor-pointer{_x000D_
cursor: pointer;_x000D_
}
_x000D_
<div class="cursor-pointer">Hover on me</div>
_x000D_
I think this is a nice balance of conciseness, clarity and ease of modification.
characters = ('a'..'z').to_a + ('A'..'Z').to_a
# Prior to 1.9, use .choice, not .sample
(0..8).map{characters.sample}.join
For example, including digits:
characters = ('a'..'z').to_a + ('A'..'Z').to_a + (0..9).to_a
Uppercase hexadecimal:
characters = ('A'..'F').to_a + (0..9).to_a
For a truly impressive array of characters:
characters = (32..126).to_a.pack('U*').chars.to_a
This is not possible, it will give you a compile time error,
You can use array for this type of requirement .
For your Reference :
http://msdn.microsoft.com/en-us/library/aa288453%28v=vs.71%29.aspx
Just type the code and save it in .cpp format. then try "gcc filename.cpp" . This will create the object file. then try "./a.out" (This is the default object file name). If you want to know about gcc you can always try "man gcc"
Try this code You may want something like this
<button class="normal" id="myButton"
value="Hover" onmouseover="mouseOver()"
onmouseout="mouseOut()">Some text</button>
Then on your .js file enter this.Make sure your html is connected to your .js
var tag=document.getElementById("myButton");
function mouseOver() {
tag.style.background="yellow";
};
function mouseOut() {
tag.style.background="white";
};
Are you including "stdlib.h" or "cstdlib" in this file? NULL is defined in stdlib.h/cstdlib
#include <stdlib.h>
or
#include <cstdlib> // This is preferrable for c++
Well 'Abstract Interface' is a Lexical construct: http://en.wikipedia.org/wiki/Lexical_analysis.
It is required by the compiler, you could also write interface
.
Well don't get too much into Lexical construct of the language as they might have put it there to resolve some compilation ambiguity which is termed as special cases during compiling process or for some backward compatibility, try to focus on core Lexical construct.
The essence of `interface is to capture some abstract concept (idea/thought/higher order thinking etc) whose implementation may vary ... that is, there may be multiple implementation.
An Interface is a pure abstract data type that represents the features of the Object it is capturing or representing.
Features can be represented by space or by time. When they are represented by space (memory storage) it means that your concrete class will implement a field and method/methods that will operate on that field or by time which means that the task of implementing the feature is purely computational (requires more cpu clocks for processing) so you have a trade off between space and time for feature implementation.
If your concrete class does not implement all features it again becomes abstract because you have a implementation of your thought or idea or abstractness but it is not complete , you specify it by abstract
class.
A concrete class will be a class/set of classes which will fully capture the abstractness you are trying to capture class XYZ.
So the Pattern is
Interface--->Abstract class/Abstract classes(depends)-->Concrete class
To make an Image fill its parent, simply wrap it into a FittedBox
:
FittedBox(
child: Image.asset('foo.png'),
fit: BoxFit.fill,
)
FittedBox
here will stretch the image to fill the space.
(Note that this functionality used to be provided by BoxFit.fill
, but the API has meanwhile changed such that BoxFit
no longer provides this functionality. FittedBox
should work as a drop-in replacement, no changes need to be made to the constructor arguments.)
Alternatively, for complex decorations you can use a Container
instead of an Image
– and use decoration
/foregroundDecoration
fields.
To make the Container
will its parent, it should either:
alignment
property not null
Here's an example that combines two images and a Text
in a single Container
, while taking 100% width/height of its parent:
Container(
foregroundDecoration: const BoxDecoration(
image: DecorationImage(
image: NetworkImage(
'https://p6.storage.canalblog.com/69/50/922142/85510911_o.png'),
fit: BoxFit.fill),
),
decoration: const BoxDecoration(
image: DecorationImage(
alignment: Alignment(-.2, 0),
image: NetworkImage(
'http://www.naturerights.com/blog/wp-content/uploads/2017/12/Taranaki-NR-post-1170x550.png'),
fit: BoxFit.cover),
),
alignment: Alignment.bottomCenter,
padding: EdgeInsets.only(bottom: 20),
child: Text(
"Hello World",
style: Theme.of(context)
.textTheme
.display1
.copyWith(color: Colors.white),
),
),
xgboost-0.6-cp36-cp36m-win_amd64.whl
for anaconda 3 (python 3.6)C:\
cd C:\
pip install C:\xgboost-0.6-cp36-cp36m-win_amd64.whl
conda update scikit-learn
I submitted an updated version of a patch to the PostgreSQL JDBC driver to enable this a few years back. You'll have to build the PostreSQL JDBC driver from source (after adding in the patch) to use it:
http://archives.postgresql.org/pgsql-jdbc/2008-07/msg00012.php
The for-each loop should generally be preferred. The "get" approach may be slower if the List implementation you are using does not support random access. For example, if a LinkedList is used, you would incur a traversal cost, whereas the for-each approach uses an iterator that keeps track of its position in the list. More information on the nuances of the for-each loop.
I think the article is now here: new location
The link shown here was dead.
Indeed, use onclick="this.select();"
but remember not to combine it with disabled="disabled"
- it will not work then and you will need to manually select or multi-click to select, still. If you wish to lock the content value to be selected, combine with the attribute readonly
.
By using event.key we can get values prior entry into HTML Input Text Box. Here is the code.
function checkText()_x000D_
{_x000D_
console.log("Value Entered which was prevented was - " + event.key);_x000D_
_x000D_
//Following will prevent displaying value on textbox_x000D_
//You need to use your validation functions here and return value true or false._x000D_
return false;_x000D_
}
_x000D_
<input type="text" placeholder="Enter Value" onkeypress="return checkText()" />
_x000D_
If you're using Qt Jambi, this should work:
QApplication.closeAllWindows();
You can do something like this using 'Java 8'
private static void appendNamesWithComma() {
List<String> namesList = Arrays.asList("test1", "tester2", "testers3", "t4");
System.out.println(namesList.stream()
.collect(Collectors.joining(", ")));
}
Yes, Eclipse can be a pain, as almost any IDE can. Please remain factual, however.
Switching to a new workspace should help you. Eclipse has almost no settings that are stored outside your workspace.
Please try to change the code as below:
<form
onSubmit={e => {
e.preventDefault();
e.stopPropagation();
const elements = Array.from(e.currentTarget) as HTMLInputElement[];
const state = elements.reduce((acc, el) => {
if (el.name) {
acc[el.name] = el.value;
}
return acc;
}, {});
console.log(state); // {test: '123'}
}}
>
<input name='test' value='123' />
</form>
I know this is an old thread but I thought I would chime in.
Chrome currently has a solution built in.
CTRL+SHIFT+I
(or navigate to Current Page Control > Developer > Developer Tools
. In the newer versions of Chrome, click the Wrench icon > Tools > Developer Tools.) to enable the Developer Tools. Network
button. If it isn't already, enable it for the session or always. "XHR"
sub-button.AJAX call
. "Resources"
. Although this code is likely beyond the understanding of a novice, it can be done in one line using a regex with positive and negative look-aheads:
boolean ok =
password.matches("^(?=.*[A-Z])(?=.*[!@#$%^&*])(?=.*\\d)(?!.*(AND|NOT)).*[a-z].*");
I have a simple example to show how to do angular 2 rc6 dynamic component.
Say, you have a dynamic html template = template1 and want to dynamic load, firstly wrap into component
@Component({template: template1})
class DynamicComponent {}
here template1 as html, may be contains ng2 component
From rc6, have to have @NgModule wrap this component. @NgModule, just like module in anglarJS 1, it decouple different part of ng2 application, so:
@Component({
template: template1,
})
class DynamicComponent {
}
@NgModule({
imports: [BrowserModule,RouterModule],
declarations: [DynamicComponent]
})
class DynamicModule { }
(Here import RouterModule as in my example there is some route components in my html as you can see later on)
Now you can compile DynamicModule as:
this.compiler.compileModuleAndAllComponentsAsync(DynamicModule).then(
factory => factory.componentFactories.find(x => x.componentType === DynamicComponent))
And we need put above in app.moudule.ts to load it, please see my app.moudle.ts. For more and full details check: https://github.com/Longfld/DynamicalRouter/blob/master/app/MyRouterLink.ts and app.moudle.ts
and see demo: http://plnkr.co/edit/1fdAYP5PAbiHdJfTKgWo?p=preview
You can simply do something like...
...
<head>
...
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'your-app-id', // you need to create an facebook app
autoLogAppEvents : true,
xfbml : true,
version : 'v3.3'
});
};
</script>
<script async defer src="https://connect.facebook.net/en_US/sdk.js"></script>
</head>
<body>
...
<button id="share-btn"></button>
<!-- load jquery -->
<script>
$('#share-btn').on('click', function () {
FB.ui({
method: 'share',
href: location.href, // Current url
}, function (response) { });
});
</script>
</body>
Because b + a ="someonedamage"
, try this to achieve :
if (d.Contains(b) && d.Contains(a))
{
Console.WriteLine(" " + d);
Console.ReadLine();
}
If you are using Oracle (or configure the application to the SQL Server) then Oracle SQL Developer does this for you. choose 'unload' for a table and follow the options through (untick DDL if you don't want all the table create stuff).
Saw an interesting one the other day, maybe week, on a blog that I can't remember. Basically I can't take credit for this but I thought it might have some useful application.
Say you wanted an abstract class to be seen by another assembly but you don't want someone to be able to inherit from it. Sealed won't work because it's abstract for a reason, other classes in that assembly do inherit from it. Private won't work because you might want to declare a Parent class somewhere in the other assembly.
namespace Base.Assembly { public abstract class Parent { internal abstract void SomeMethod(); } //This works just fine since it's in the same assembly. public class ChildWithin : Parent { internal override void SomeMethod() { } } } namespace Another.Assembly { //Kaboom, because you can't override an internal method public class ChildOutside : Parent { } public class Test { //Just fine private Parent _parent; public Test() { //Still fine _parent = new ChildWithin(); } } }
As you can see, it effectively allows someone to use the Parent class without being able to inherit from.
I know this question already has some good answers but I think my solution is worth of sharing.
It works for both std::map
and std::vector<std::pair<T, U>>
and is available from C++11.
template <typename ForwardIterator, typename Key>
bool contains_key(ForwardIterator first, ForwardIterator last, Key const key) {
using ValueType = typename std::iterator_traits<ForwardIterator>::value_type;
auto search_result = std::find_if(
first, last,
[&key](ValueType const& item) {
return item.first == key;
}
);
if (search_result == last) {
return false;
} else {
return true;
}
}
Here is a little utility function that is useful in situations like this
// returns true if $needle is a substring of $haystack
function contains($needle, $haystack)
{
return strpos($haystack, $needle) !== false;
}
An updated version of Rails/ActiveRecord may support this syntax natively. It would look similar to:
Foo.where(foo: 'bar').or.where(bar: 'bar')
As noted in this pull request https://github.com/rails/rails/pull/9052
For now, simply sticking with the following works great:
Foo.where('foo= ? OR bar= ?', 'bar', 'bar')
Update: According to https://github.com/rails/rails/pull/16052 the or
feature will be available in Rails 5
Update: Feature has been merged to Rails 5 branch
LINQ Any() would do the job:
bool contains = myList.Any(s => s.Contains(pattern));
Determines whether any element of a sequence satisfies a condition
If you need to support more than one format you will have to pattern match your input and parse accordingly.
final DateFormat fmt;
if (dateString.endsWith("Z")) {
fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
} else {
fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
}
I'd guess you're dealing with a bug in the API you're using which has quoted the Z
timezone date pattern somewhere...
Make a text using notepad or any text editor of you choice. Open notepad, write this short command "cmd.exe" without the quote aand save it as cmd.bat.
Click cmd.bat and choose "run as administrator".
Its a start, it can list:
models = Dir.new("#{RAILS_ROOT}/app/models").entries
Looking some more...
I've invested a lot of time trying to solve this problem.
There are 3 approaches:
Use JavaScript. The clear drawbacks: it's not possible to open a new tab natively, and when hovering over the row there will be no indication on status bar like regular links have. Accessibility is also a question.
Use HTML/CSS only. This means putting <a>
nested under each <td>
. A simple approach like this fiddle doesn't work - Because the clickable surface is not necessarily equal for each column. This is a serious UX concern. Also, if you need a <button>
on the row, it is not valid HTML to nest it under <a>
tag (although browsers are ok with that).
I've found 3 other ways to implement this approach. First is ok, the other two are not great.
a) Have a look on this example:
tr {
height: 0;
}
td {
height: 0;
padding: 0;
}
/* A hack to overcome differences between Chrome and Firefox */
@-moz-document url-prefix() {
td {
height: 100%;
}
}
a {
display: block;
height: 100%;
}
It works, but due to inconsistencies between Chrome and Firefox it requires browser-specific hack to overcome the differences. Also Chrome will always align the cell content to the top, which can cause problems with long texts, especially if varying line heights are involved.
b) Setting <td>
to { display: contents; }
. This leads to 2 other problems:
b1. If someone else tries to style directly the <td>
tag, like setting it to { width: 20px; }
, we need to pass that style somehow to the <a>
tag. We need some magic to do that, probably more magic than in the Javascript alternative.
b2. { display: contents; }
is still experimental; specifically it's not supported on Edge.
c) Setting <td>
to { height: --some-fixed-value; }
. This is just not flexible enough.
The last approach, which I recommend to seriously thinking of, is to not using clickable rows at all. Clickable rows is not a great UX experience: it's not easy to visually mark them as clickable, and it poses challenges when multiple parts are clickable within the rows, like buttons. So a viable alternative could be to have an <a>
tag only on the first column, displayed as a regular link, and give it the role of navigating the whole row.
There are a number of ways to comment in a batch file
1)Using rem
This is the official way. It apparently takes longer to execute than ::
, although it apparently stops parsing early, before the carets are processed. Percent expansion happens before rem and ::
are identified, so incorrect percent usage i.e. %~
will cause errors if percents are present. Safe to use anywhere in code blocks.
2)Using labels :
, ::
or :;
etc.
For :: comment
, ': comment' is an invalid label name because it begins with an invalid character. It is okay to use a colon in the middle of a label though. If a space begins at the start of label, it is removed : label
becomes :label
. If a space or a colon appears in the middle of the label, the rest of the name is not interpreted meaning that if there are two labels :f:oo
and :f rr
, both will be interpreted as :f
and only the later defined label in the file will be jumped to. The rest of the label is effectively a comment. There are multiple alternatives to ::
, listed here. You can never goto
or call
a ::foo
label. goto :foo
and goto ::foo
will not work.
They work fine outside of code blocks but after a label in a code block, invalid or not, there has to be a valid command line. :: comment
is indeed another valid command. It interprets it as a command and not a label; the command has precedence. Which is the command to cd to the ::
volume, which will work if you have executed subst :: C:\
, otherwise you get a cannot find the volume error. That's why :;
is arguably better because it cannot be interpreted in this way, and therefore is interpreted as a label instead, which serves as the valid command. This is not recursive, i.e, the next label does not need a command after it. That's why they come in twos.
You need to provide a valid command after the label e.g. echo something
. A label in a code block has to come with at least one valid command, so the lines come in pairs of two. You will get an unexpected )
error if there is a space or a closing parenthesis on the next line. If there is a space between the two ::
lines you will get an invalid syntax error.
You can also use the caret operator in the ::
comment like so:
@echo off
echo hello
(
:;(^
this^
is^
a^
comment^
)
:;
)
:;^
this^
is^
a^
comment
:;
)
But you need the trailing :;
for the reason stated above.
@echo off
(
echo hello
:;
:; comment
:; comment
:;
)
echo hello
It is fine as long as there is an even number. This is undoubtedly the best way to comment -- with 4 lines and :;
. With :;
you don't get any errors that need to be suppressed using 2> nul
or subst :: C:\
. You could use subst :: C:\
to make the volume not found error go away but it means you will have to also put C: in the code to prevent your working directory from becoming ::\
.
To comment at the end of a line you can do
command &::
or command & rem comment
, but there still has to be an even number, like so:
@echo off
(
echo hello & :;yes
echo hello & :;yes
:;
)
echo hello
The first echo hello & :;yes
has a valid command on the next line but the second & :;yes
does not, so it needs one i.e. the :;
.
3)Using an invalid environment variable
%= comment =%
. In a batch file, environment variables that are not defined are removed from the script. This makes it possible to use them at the end of a line without using &
. It is custom to use an invalid environment variable i.e. one that contains an equals sign. The extra equals is not required but makes it look symmetrical. Also, variable names starting with "=" are reserved for undocumented dynamic variables. Those dynamic variables never end with "=", so by using an "=" at both the start and end of the comment, there is no possibility of a name clash. The comment cannot contain %
or :
.
@echo off
echo This is an example of an %= Inline Comment =% in the middle of a line.
4)As a command, redirecting stderr to nul
@echo off
(
echo hello
;this is a comment 2> nul
;this is another comment 2> nul
)
5)At the end of a file, everything after an unclosed parenthesis is a comment
@echo off
(
echo hello
)
(this is a comment
this is a comment
this is a comment
Press Alt+H(h) and then you'll see the shortcuts on the toolbar, press FC to operate color menu and press A(Automatic) for black or browse through other colors using arrow keys.
You don't need to test if $?
is not 0
. The shell provides &&
and ||
so you can easily branch based on implicit result of that test:
some_command && {
# executes this block of code,
# if some_command would result in: $? -eq 0
} || {
# executes this block of code,
# if some_command would result in: $? -ne 0
}
You can remove either branch, depending on what you want. So if you just want to test for failure (i.e. $? -ne 0
):
some_command_returning_nonzero || {
# executes this block of code when: $? -ne 0
# and nothing if the command succeeds: $? -eq 0
}
However, the code you provided in the question works, as is. I'm confused that you got syntax errors & concluded that $?
was a string. It's most likely that the errant code causing the syntax error was not provided with the question. This is especially evident because you claim that no one else's solutions work either. When this happens, you have to re-evaluate your assumptions.
NB: The code above may give confusing results if the code inside the braces returns an error. In that case simply use the if command instead, like this:
if some_command; then
# executes this block of code,
# if some_command would result in: $? -eq 0
else
# executes this block of code,
# if some_command would result in: $? -ne 0
fi
If you need to retrieve more columns other than columns which are in group by then you can consider below query. Check it once whether it is performing well or not.
SELECT
a.[CUSTOMER ID],
a.[NAME],
(select SUM(b.[AMOUNT]) from INV_DATA b
where b.[CUSTOMER ID] = a.[CUSTOMER ID]
GROUP BY b.[CUSTOMER ID]) AS [TOTAL AMOUNT]
FROM RES_DATA a
You can have a responsive canvas in 3 short and simple steps:
Remove the width
and height
attributes from your <canvas>
.
<canvas id="responsive-canvas"></canvas>
Using CSS, set the width
of your canvas to 100%
.
#responsive-canvas {
width: 100%;
}
Using JavaScript, set the height to some ratio of the width.
var canvas = document.getElementById('responsive-canvas');
var heightRatio = 1.5;
canvas.height = canvas.width * heightRatio;
If you organize your test cases, that is, follow the same organization like the actual code and also use relative imports for modules in the same package, you can also use the following command format:
python -m unittest mypkg.tests.test_module.TestClass.test_method
# In your case, this would be:
python -m unittest testMyCase.MyCase.testItIsHot
Python 3 documentation for this: Command-Line Interface
!undefined
is true in javascript, so if you want to know whether your variable or object is undefined and want to take actions, you could do something like this:
if(<object or variable>) {
//take actions if object is not undefined
} else {
//take actions if object is undefined
}
I agree with both previous answers. Basically, you want to use what is known as a "lightbox" - http://en.wikipedia.org/wiki/Lightbox_(JavaScript)
It is essentially a div than is created within the DOM of your current window/tab. In addition to the div that contains your dialog, a transparent overlay blocks the user from engaging all underlying elements. This can effectively create a modal dialog (i.e. user MUST make some kind of decision before moving on).
Use the Take method:
var foo = (from t in MyTable
select t.Foo).Take(10);
In VB LINQ has a take expression:
Dim foo = From t in MyTable _
Take 10 _
Select t.Foo
From the documentation:
Take<TSource>
enumeratessource
and yields elements untilcount
elements have been yielded orsource
contains no more elements. Ifcount
exceeds the number of elements insource
, all elements ofsource
are returned.
If you use Laravel and want to use Carbon the correct solution would be the following:
$start_date = Carbon::createFromFormat('Y-m-d', '2020-01-01');
$end_date = Carbon::createFromFormat('Y-m-d', '2020-01-31');
$period = new CarbonPeriod($start_date, '1 day', $end_date);
foreach ($period as $dt) {
echo $dt->format("l Y-m-d H:i:s\n");
}
Remember to add:
I think you mean:
unsigned long n;
printf("%lu", n); // unsigned long
or
long n;
printf("%ld", n); // signed long
It depends. On MySQL an index is created if you don't create it on your own:
MySQL requires that foreign key columns be indexed; if you create a table with a foreign key constraint but no index on a given column, an index is created.
Source: https://dev.mysql.com/doc/refman/8.0/en/constraint-foreign-key.html
The same for MySQL 5.6 eh.
For those who would like to listen to the actual inner height and vertical scroll of the window while the Chrome mobile browser is transition the URL bar from shown to hidden and vice versa, the only solution that I found is to set an interval function, and measure the discrepancy of the window.innerHeight
with its previous value.
This introduces this code:
var innerHeight = window.innerHeight;_x000D_
window.setInterval(function ()_x000D_
{_x000D_
var newInnerHeight = window.innerHeight;_x000D_
if (newInnerHeight !== innerHeight)_x000D_
{_x000D_
var newScrollY = window.scrollY + newInnerHeight - innerHeight;_x000D_
// ... do whatever you want with this new scrollY_x000D_
innerHeight = newInnerHeight;_x000D_
}_x000D_
}, 1000 / 60);
_x000D_
I hope that this will be handy. Does anyone knows a better solution?
Both do different things.
The first creates an object with automatic storage duration. It is created, used, and then goes out of scope when the current block ({ ... }
) ends. It's the simplest way to create an object, and is just the same as when you write int x = 0;
The second creates an object with dynamic storage duration and allows two things:
Fine control over the lifetime of the object, since it does not go out of scope automatically; you must destroy it explicitly using the keyword delete
;
Creating arrays with a size known only at runtime, since the object creation occurs at runtime. (I won't go into the specifics of allocating dynamic arrays here.)
Neither is preferred; it depends on what you're doing as to which is most appropriate.
Use the former unless you need to use the latter.
Your C++ book should cover this pretty well. If you don't have one, go no further until you have bought and read, several times, one of these.
Good luck.
Your original code is broken, as it delete
s a char
array that it did not new
. In fact, nothing new
d the C-style string; it came from a string literal. delete
ing that is an error (albeit one that will not generate a compilation error, but instead unpredictable behaviour at runtime).
Usually an object should not have the responsibility of delete
ing anything that it didn't itself new
. This behaviour should be well-documented. In this case, the rule is being completely broken.
def fact(n):
f = 1
for i in range(1, n + 1):
f *= i
return f
In intellij8 I was using a specific plugin "Jar Tool" that is configurable and allows to pack a JAR archive.
$image = 'http://images.itracki.com/2011/06/favicon.png';
// Read image path, convert to base64 encoding
$imageData = base64_encode(file_get_contents($image));
// Format the image SRC: data:{mime};base64,{data};
$src = 'data: '.mime_content_type($image).';base64,'.$imageData;
// Echo out a sample image
echo '<img src="' . $src . '">';
../images/logo.png
will move you back one folder.
../../images/logo.png
will move you back two folders.
/images/logo.png
will take you back to the root folder no matter where you are/.
Yep, just add the following function to your Utils class or something:
public static string cleanForJSON(string s)
{
if (s == null || s.Length == 0) {
return "";
}
char c = '\0';
int i;
int len = s.Length;
StringBuilder sb = new StringBuilder(len + 4);
String t;
for (i = 0; i < len; i += 1) {
c = s[i];
switch (c) {
case '\\':
case '"':
sb.Append('\\');
sb.Append(c);
break;
case '/':
sb.Append('\\');
sb.Append(c);
break;
case '\b':
sb.Append("\\b");
break;
case '\t':
sb.Append("\\t");
break;
case '\n':
sb.Append("\\n");
break;
case '\f':
sb.Append("\\f");
break;
case '\r':
sb.Append("\\r");
break;
default:
if (c < ' ') {
t = "000" + String.Format("X", c);
sb.Append("\\u" + t.Substring(t.Length - 4));
} else {
sb.Append(c);
}
break;
}
}
return sb.ToString();
}
Turns out the binding of style to a string doesn't work. The solution would be to bind the background of the style.
<div class="circle" [style.background]="color">
I would suggest looking at how browsers handle forms by default. For example take a look at the form element <select multiple>
and how it handles multiple values from this example at w3schools.
<form action="/action_page.php">
<select name="cars" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<input type="submit">
</form>
For PHP use:
<select name="cars[]" multiple>
Live example from above at w3schools.com
From above if you click "saab, opel" and click submit, it will generate a result of cars=saab&cars=opel. Then depending on the back-end server, the parameter cars should come across as an array that you can further process.
Hope this helps anyone looking for a more 'standard' way of handling this issue.
You can use the split()
function to break input on the basis of line break.
yourString.split("\n")
I couldn't find any exact and valid way to do this. So after a whole day, I came with this mixed code achieved from different sources and trying to get the job done.
But it is still generating an exception ExecuteNonQuery: CommandText property has not been Initialized
even though it successfully runs the script file - in my case, it successfully creates the database and inserts data on the first startup.
public partial class Form1 : MetroForm
{
SqlConnection cn;
SqlCommand cm;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
if (!CheckDatabaseExist())
{
GenerateDatabase();
}
}
private bool CheckDatabaseExist()
{
SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=SalmanTradersDB;Integrated Security=true");
try
{
con.Open();
return true;
}
catch
{
return false;
}
}
private void GenerateDatabase()
{
try
{
cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=master;Integrated Security=True");
StringBuilder sb = new StringBuilder();
sb.Append(string.Format("drop databse {0}", "SalmanTradersDB"));
cm = new SqlCommand(sb.ToString() , cn);
cn.Open();
cm.ExecuteNonQuery();
cn.Close();
}
catch
{
}
try
{
//Application.StartupPath is the location where the application is Installed
//Here File Path Can Be Provided Via OpenFileDialog
if (File.Exists(Application.StartupPath + "\\script.sql"))
{
string script = null;
script = File.ReadAllText(Application.StartupPath + "\\script.sql");
string[] ScriptSplitter = script.Split(new string[] { "GO" }, StringSplitOptions.None);
using (cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"))
{
cn.Open();
foreach (string str in ScriptSplitter)
{
using (cm = cn.CreateCommand())
{
cm.CommandText = str;
cm.ExecuteNonQuery();
}
}
}
}
}
catch
{
}
}
}
$mail->IsSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Username = "[email protected]";
$mail->Password = "**********";
$mail->Port = "465";
That is a working configuration.
try to replace what you have
With Behaviors and Actions in Blend for Visual Studio 2013 you can use the InvokeCommandAction. I tried this with the Drop event and although no CommandParameter was specified in the XAML, to my surprise, the Execute Action parameter contained the DragEventArgs. I presume this would happen for other events but have not tested them.
<script type="text/javascript">
function lnkLogout_Confirm()
{
var bResponse = confirm('Are you sure you want to exit?');
if (bResponse === true) {
////console.log("lnkLogout_Confirm clciked.");
var url = '@Url.Action("Login", "Login")';
window.location.href = url;
}
return bResponse;
}
</script>
\d{1,3}
will match numbers like 00
or 333
as well which wouldn't be a valid ID.
This is an excellent answer from smink, citing:
ValidIpAddressRegex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";
If you don't have a page which is accessing the websocket, you can open up the Chrome console and type your JavaScript in:
var webSocket = new WebSocket('ws://address:port');
webSocket.onmessage = function(data) { console.log(data); }
This will open up the web socket so you can see it in the network tab and in the console.
This is a bit more compact, you get the hours, minutes and seconds in two lines.
days = td.days
hours, remainder = divmod(td.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
# If you want to take into account fractions of a second
seconds += td.microseconds / 1e6
you should not use Nested List in List.
List<List<T>>
is not legal, even if T were a defined type.
Answered a question such as this before, you can take a look at the results here:
Creating form to have fields and text next to each other - what is the semantic way to do it?
So to apply the same rules to your fiddle you can use display:inline-block
to display your label and input groups side by side, like so:
CSS
input {
margin-top: 5px;
margin-bottom: 5px;
display:inline-block;
*display: inline; /* for IE7*/
zoom:1; /* for IE7*/
vertical-align:middle;
margin-left:20px
}
label {
display:inline-block;
*display: inline; /* for IE7*/
zoom:1; /* for IE7*/
float: left;
padding-top: 5px;
text-align: right;
width: 140px;
}
Compare modifying value of variable versus modifying value of pointer:
#include <stdio.h>
#include <stdlib.h>
void changeA(int (*a))
{
(*a) = 10;
}
void changeP(int *(*P))
{
(*P) = malloc(sizeof((*P)));
}
int main(void)
{
int A = 0;
printf("orig. A = %d\n", A);
changeA(&A);
printf("modi. A = %d\n", A);
/*************************/
int *P = NULL;
printf("orig. P = %p\n", P);
changeP(&P);
printf("modi. P = %p\n", P);
free(P);
return EXIT_SUCCESS;
}
This helped me to avoid returning value of pointer when the pointer was modified by the called function (used in singly linked list).
OLD (bad):
int *func(int *P)
{
...
return P;
}
int main(void)
{
int *pointer;
pointer = func(pointer);
...
}
NEW (better):
void func(int **pointer)
{
...
}
int main(void)
{
int *pointer;
func(&pointer);
...
}
An alternative, is install the unused package you want to delete in any project of your solution, after that, uninstall it and Nuget will remove it too.
A proper uninstaller is needed here.
If you looking for some command in CLI, Then ans is NO for now. But you can do manually by deleting the component folder and all the references.
You can use String.getBytes()
which returns the byte[]
array.
When you correct the measurements - as mentioned above: Any and Exists, and adding average - we'll get following output:
Executing search Exists() 1000 times ...
Average Exists(): 35566,023
Fastest Exists() execution: 32226
Executing search Any() 1000 times ...
Average Any(): 58852,435
Fastest Any() execution: 52269 ticks
Benchmark finished. Press any key.
this is how you can create an array of boolean in TS and initialize it with false:
var array: boolean[] = [false, false, false]
or another approach can be:
var array2: Array<boolean> =[false, false, false]
you can specify the type after the colon which in this case is boolean array
Maybe std::ostream_iterator
and std::ostringstream
:
#include <vector>
#include <string>
#include <algorithm>
#include <sstream>
#include <iterator>
#include <iostream>
int main()
{
std::vector<int> vec;
vec.push_back(1);
vec.push_back(4);
vec.push_back(7);
vec.push_back(4);
vec.push_back(9);
vec.push_back(7);
std::ostringstream oss;
if (!vec.empty())
{
// Convert all but the last element to avoid a trailing ","
std::copy(vec.begin(), vec.end()-1,
std::ostream_iterator<int>(oss, ","));
// Now add the last element with no delimiter
oss << vec.back();
}
std::cout << oss.str() << std::endl;
}
Netscape ANSI encoded files use 0D 0D 0A for their line breaks.
I posted a somewhat similar question a while back, but regarding a model on CI.
Returning two separate query results within a model function
Although your question is not exactly the same, I believe the solution follows the same principle: if you're proposing to do what you mention in your question, there may be something wrong in the way you're coding and some refactoring could be in order.
The take home message is that what you're asking is not the way to go when working with MVC.
The best practice is to either use a Model to place reusable functions and call them in a controller that outputs the data through a view -- or even better use helpers or libraries (for functions that may be needed repeatedly).
I think that you can make some changes in your data format when you create dictionary, then you can easily convert it to DataFrame:
input:
a={'Dates':['2012-06-08','2012-06-10'],'Date_value':[388,389]}
output:
{'Date_value': [388, 389], 'Dates': ['2012-06-08', '2012-06-10']}
input:
aframe=DataFrame(a)
output: will be your DataFrame
You just need to use some text editing in somewhere like Sublime or maybe Excel.
Try the Content-Disposition
header
Content-Disposition: attachment; filename=<file name.ext>
If you want to play around with border-size
, width
and height
and see how those can create different shapes, try this:
const sizes = [32, 32, 32, 32];_x000D_
const triangle = document.getElementById('triangle');_x000D_
_x000D_
function update({ target }) {_x000D_
let index = null;_x000D_
_x000D_
if (target) {_x000D_
index = parseInt(target.id);_x000D_
_x000D_
if (!isNaN(index)) {_x000D_
sizes[index] = target.value;_x000D_
}_x000D_
}_x000D_
_x000D_
window.requestAnimationFrame(() => {_x000D_
triangle.style.borderWidth = sizes.map(size => `${ size }px`).join(' ');_x000D_
_x000D_
if (isNaN(index)) {_x000D_
triangle.style[target.id] = `${ target.value }px`;_x000D_
}_x000D_
});_x000D_
}_x000D_
_x000D_
document.querySelectorAll('input').forEach(input => {_x000D_
input.oninput = update;_x000D_
});_x000D_
_x000D_
update({});
_x000D_
body {_x000D_
margin: 0;_x000D_
min-height: 100vh;_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
align-items: center;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
#triangle {_x000D_
border-style: solid;_x000D_
border-color: yellow magenta blue black;_x000D_
background: cyan;_x000D_
height: 0px;_x000D_
width: 0px;_x000D_
}_x000D_
_x000D_
#controls {_x000D_
position: fixed;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
background: white;_x000D_
display: flex;_x000D_
box-shadow: 0 0 32px rgba(0, 0, 0, .125);_x000D_
}_x000D_
_x000D_
#controls > div {_x000D_
position: relative;_x000D_
width: 25%;_x000D_
padding: 8px;_x000D_
box-sizing: border-box;_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
input {_x000D_
margin: 0;_x000D_
width: 100%;_x000D_
position: relative;_x000D_
}
_x000D_
<div id="triangle" style="border-width: 32px 32px 32px 32px;"></div>_x000D_
_x000D_
<div id="controls">_x000D_
<div><input type="range" min="0" max="128" value="32" id="0" /></div>_x000D_
<div><input type="range" min="0" max="128" value="32" id="1" /></div>_x000D_
<div><input type="range" min="0" max="128" value="32" id="2" /></div>_x000D_
<div><input type="range" min="0" max="128" value="32" id="3" /></div>_x000D_
<div><input type="range" min="0" max="128" value="0" id="width" /></div>_x000D_
<div><input type="range" min="0" max="128" value="0" id="height" /></div>_x000D_
</div>
_x000D_
Spring has an util class for that:
import org.springframework.util.FileCopyUtils;
InputStream is = connection.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
FileCopyUtils.copy(is, bos);
String data = new String(bos.toByteArray());
no, you need to do something like:
$('input.sitebg').val('000000');
but you should really be using unique IDs if you can.
You can also get more specific, such as:
$('input[type=text].sitebg').val('000000');
EDIT:
do this to find your input based on the name attribute:
$('input[name=sitebg]').val('000000');
Even if you have unchecked the "Display intranet sites in Compatibility View" option, and have the X-UA-Compatible in your response headers, there is another reason why your browser might default to "Compatibility View" anyways - your Group Policy. Look at your console for the following message:
HTML1203: xxx.xxx has been configured to run in Compatibility View through Group Policy.
Where xxx.xxx is the domain for your site (i.e. test.com). If you see this then the group policy for your domain is set so that any site ending in test.com will automatically render in Compatibility mode regardless of doctype, headers, etc.
For more information, please see the following link (explains the html codes): http://msdn.microsoft.com/en-us/library/ie/hh180764(v=vs.85).aspx
What you ask for should be reasonably straightforward in jQuery-
$(function() {
$('#myAnchorId').click(function() {
var areaValue = $('#area').val();
$('#area').val(areaValue + 'Whatever you want to enter');
});
});
The best way that I can think of highlighting inserted text is by wrapping it in a span with a CSS class with background-color
set to the color of your choice. On the next insert, you could remove the class from any existing spans (or strip the spans out).
However, There are plenty of free WYSIWYG HTML/Rich Text editors available on the market, I'm sure one will fit your needs
If you are not using GitBash - you need to start your ssh-agent using this command
start-ssh-agent.cmd
This is brutally buried in the comments and hard to find. This should be accepted answer.
If your ssh agent is not set up, you can open PowerShell as admin and set it to manual mode
Get-Service -Name ssh-agent | Set-Service -StartupType Manual
The underscore usually means a C module (i.e. DLL), and Python can't find it. Did you build python yourself? If so, you need to include SSL support.
The approach that I am giving is the fastest pagination that SQL server can achieve. I have tested this on 5 million records. This approach is far better than "OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY" provided by SQL Server.
-- The below given code computes the page numbers and the max row of previous page
-- Replace <<>> with the correct table data.
-- Eg. <<IdentityColumn of Table>> can be EmployeeId and <<Table>> will be dbo.Employees
DECLARE @PageNumber int=1; --1st/2nd/nth page. In stored proc take this as input param.
DECLARE @NoOfRecordsPerPage int=1000;
DECLARE @PageDetails TABLE
(
<<IdentityColumn of Table>> int,
rownum int,
[PageNumber] int
)
INSERT INTO @PageDetails values(0, 0, 0)
;WITH CTE AS
(
SELECT <<IdentityColumn of Table>>, ROW_NUMBER() OVER(ORDER BY <<IdentityColumn of Table>>) rownum FROM <<Table>>
)
Insert into @PageDetails
SELECT <<IdentityColumn of Table>>, CTE.rownum, ROW_NUMBER() OVER (ORDER BY rownum) as [PageNumber] FROM CTE WHERE CTE.rownum%@NoOfRecordsPerPage=0
--SELECT * FROM @PageDetails
-- Actual pagination
SELECT TOP (@NoOfRecordsPerPage)
FROM <<Table>> AS <<Table>>
WHERE <<IdentityColumn of Table>> > (SELECT <<IdentityColumn of Table>> FROM
@PageDetails WHERE PageNumber=@PageNumber)
ORDER BY <<Identity Column of Table>>
To keep the change in file but not to commit I did this
git add .
git reset -- main/dontcheckmein.txt
git commit -m "commit message"
to verify the file is excluded do
git status
To prevent the jump, this is what I used
export function toggleBodyScroll(disable) {
if (!window.tempScrollTop) {
window.tempScrollTop = window.pageYOffset;
// save the current position in a global variable so I can access again later
}
if (disable) {
document.body.classList.add('disable-scroll');
document.body.style.top = `-${window.tempScrollTop}px`;
} else {
document.body.classList.remove('disable-scroll');
document.body.style.top = `0px`;
window.scrollTo({top: window.tempScrollTop});
window.tempScrollTop = 0;
}
}
and in my css
.disable-scroll {
height: 100%;
overflow: hidden;
width: 100%;
position: fixed;
}
The two structs are different. When you initialize the first struct, about 40 bytes of memory are allocated. When you initialize the second struct, about 10 bytesof memory are allocated. (Actual amount is architecture dependent)
You can use the string literals (string constants) to initalize character arrays. This is why
person p = {"John", "Doe",30};
works in the first example.
You cannot assign (in the conventional sense) a string in C.
The string literals you have ("John") are loaded into memory when your code executes. When you initialize an array with one of these literals, then the string is copied into a new memory location. In your second example, you are merely copying the pointer to (location of) the string literal. Doing something like:
char* string = "Hello";
*string = 'C'
might cause compile or runtime errors (I am not sure.) It is a bad idea because you are modifying the literal string "Hello" which, for example on a microcontroler, could be located in read-only memory.
Please use json.Decoder
instead of json.Unmarshal
.
func test(rw http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(req.Body)
var t test_struct
err := decoder.Decode(&t)
if err != nil {
panic(err)
}
log.Println(t.Test)
}
public static string DataTable2String(DataTable dataTable)
{
StringBuilder sb = new StringBuilder();
if (dataTable != null)
{
string seperator = " | ";
#region get min length for columns
Hashtable hash = new Hashtable();
foreach (DataColumn col in dataTable.Columns)
hash[col.ColumnName] = col.ColumnName.Length;
foreach (DataRow row in dataTable.Rows)
for (int i = 0; i < row.ItemArray.Length; i++)
if (row[i] != null)
if (((string)row[i]).Length > (int)hash[dataTable.Columns[i].ColumnName])
hash[dataTable.Columns[i].ColumnName] = ((string)row[i]).Length;
int rowLength = (hash.Values.Count + 1) * seperator.Length;
foreach (object o in hash.Values)
rowLength += (int)o;
#endregion get min length for columns
sb.Append(new string('=', (rowLength - " DataTable ".Length) / 2));
sb.Append(" DataTable ");
sb.AppendLine(new string('=', (rowLength - " DataTable ".Length) / 2));
if (!string.IsNullOrEmpty(dataTable.TableName))
sb.AppendLine(String.Format("{0,-" + rowLength + "}", String.Format("{0," + ((rowLength + dataTable.TableName.Length) / 2).ToString() + "}", dataTable.TableName)));
#region write values
foreach (DataColumn col in dataTable.Columns)
sb.Append(seperator + String.Format("{0,-" + hash[col.ColumnName] + "}", col.ColumnName));
sb.AppendLine(seperator);
sb.AppendLine(new string('-', rowLength));
foreach (DataRow row in dataTable.Rows)
{
for (int i = 0; i < row.ItemArray.Length; i++)
{
sb.Append(seperator + String.Format("{0," + hash[dataTable.Columns[i].ColumnName] + "}", row[i]));
if (i == row.ItemArray.Length - 1)
sb.AppendLine(seperator);
}
}
#endregion write values
sb.AppendLine(new string('=', rowLength));
}
else
sb.AppendLine("================ DataTable is NULL ================");
return sb.ToString();
}
output:
======================= DataTable =======================
MyTable
| COL1 | COL2 | COL3 1000000ng name |
----------------------------------------------------------
| 1 | 2 | 3 |
| abc | Dienstag, 12. März 2013 | xyz |
| Have | a nice | day! |
==========================================================
Here is one way that I hope is easy to understand:
$(document).ready(function() {
$("#chkdwn2").click(function() {
if ($(this).is(":checked")) {
$("#dropdown").prop("disabled", true);
} else {
$("#dropdown").prop("disabled", false);
}
});
});
It depends on what you are trying to do.
file, err := os.Open("file.txt")
fmt.print(file)
The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File
), not file-content. To obtain file-content, you may READ
from a file-descriptor.
To read all file content(in bytes) to memory, ioutil.ReadAll
package main
import (
"fmt"
"io/ioutil"
"os"
"log"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
b, err := ioutil.ReadAll(file)
fmt.Print(b)
}
But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read
from *os.File
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
buf := make([]byte, 32*1024) // define your buffer size here.
for {
n, err := file.Read(buf)
if n > 0 {
fmt.Print(buf[:n]) // your read buffer.
}
if err == io.EOF {
break
}
if err != nil {
log.Printf("read %d bytes: %v", n, err)
break
}
}
}
Otherwise, you could also use the standard util package: bufio
, try Scanner
. A Scanner
reads your file in tokens: separator.
By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).
package main
import (
"fmt"
"os"
"log"
"bufio"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
scanner := bufio.NewScanner(file)
for scanner.Scan() { // internally, it advances token based on sperator
fmt.Println(scanner.Text()) // token in unicode-char
fmt.Println(scanner.Bytes()) // token in bytes
}
}
Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.
I don't like to install stuff with sudo. once you start with sudo you can't stop..
try giving permissions to the Gems directory.
sudo chown -R $(whoami) /Library/Ruby/Gems/2.0.0
I happen to use cwRsync (Cygwin + Rsync for Windows) where cygwin comes bundled, and I couldn't find /etc/passwd.
And it kept saying
Could not create directory '/home/username/.ssh'.
...
Failed to add the host to the list of known hosts (/home/username/.ssh/known_hosts).
So I wrote a batch file which changed the HOME variable before running rsync. Something like:
set HOME=.
rsync /path1 user@host:/path2
And voila! The .ssh folder appeared in the current working dir, and rsync stopped annoying with rsa fingerprints.
It's a quick hotfix, but later you should change HOME to a more secure location.
If Android Studio shows you the path /Users/<name>/Library/Android/sdk
but you can not find it in your folder, just right-click and select "Show View Option". There you will be able to select "Show Library Folder"; select it and you can access the SDK.
Because os.path.abspath = os.path.dirname + os.path.basename
does not hold. we rather have
os.path.dirname(filename) + os.path.basename(filename) == filename
Both dirname()
and basename()
only split the passed filename into components without taking into account the current directory. If you want to also consider the current directory, you have to do so explicitly.
To get the dirname of the absolute path, use
os.path.dirname(os.path.abspath(__file__))
From wiki
A null pointer has a reserved value, often but not necessarily the value zero, indicating that it refers to no object
..Since a null-valued pointer does not refer to a meaningful object, an attempt to dereference a null pointer usually causes a run-time error.
int val =1;
int *p = NULL;
*p = val; // Whooosh!!!!
It's hard to answer you without the HTML, but in general you can put:
style="width: 50%;"
On either the table cell, or place a div inside the table cell, and put the style on that.
But one problem is "50% of what?" It's 50% of the parent element which may not be what you want.
Post a copy of your HTML and maybe you'll get a better answer.
Here is a way how I found how to extend a enum into other enum, is a very straighfoward approach:
Suposse you have a enum with common constants:
public interface ICommonInterface {
String getName();
}
public enum CommonEnum implements ICommonInterface {
P_EDITABLE("editable"),
P_ACTIVE("active"),
P_ID("id");
private final String name;
EnumCriteriaComun(String name) {
name= name;
}
@Override
public String getName() {
return this.name;
}
}
then you can try to do a manual extends in this way:
public enum SubEnum implements ICommonInterface {
P_EDITABLE(CommonEnum.P_EDITABLE ),
P_ACTIVE(CommonEnum.P_ACTIVE),
P_ID(CommonEnum.P_ID),
P_NEW_CONSTANT("new_constant");
private final String name;
EnumCriteriaComun(CommonEnum commonEnum) {
name= commonEnum.name;
}
EnumCriteriaComun(String name) {
name= name;
}
@Override
public String getName() {
return this.name;
}
}
of course every time you need to extend a constant you have to modify your SubEnum files.
Try this:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rel_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/ImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src=//source of image />
<TextView
android:id="@+id/ImageViewText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@id/ImageView"
android:layout_alignTop="@id/ImageView"
android:layout_alignRight="@id/ImageView"
android:layout_alignBottom="@id/ImageView"
android:text=//u r text here
android:gravity="center"
/>
Hope this could help you.
I also faced similar issues when tried to do ng serve. I was able to resolve it as below.
Note:
C:\Windows\system32> is on windows command prompt
C:\apps\workspace\testProj> is on VS code Terminal (can also be doable in another command prompt)
Following are the steps which I used to resolve this.
Step1. Verify the cli version installed on command prompt (will be Angular CLI global version)
C:\Windows\system32>ng --version
Angular CLI: 8.3.13
If cli was installed earlier, it shows the global cli version.
If cli was not installed, we may get the error
ng is not recognized as an internal or external command
a. (Optional Step) Install Angular CLI global version
C:\Windows\system32>npm install -g @angular/cli
C:\Windows\system32>npm install -g @angular-cli/latest
b. Check version again
C:\Windows\system32>ng --version
Angular CLI: 8.3.13
Step2. Verify the local cli version installed on your angular project(VS code ide or command prompt cd'd to your project project)
C:\apps\workspace\testProj>ng --version
Angular CLI: 7.3.8
Note: Clearly versions are not in sync. Do the following in your angular project
C:\apps\workspace\testProj>ng update @angular/cli -> important to sync with global cli version
Note: If upgrade donot work using above command (ref: How to upgrade Angular CLI to the latest version)
On command prompt, uninstall global angular cli, clean the cache and reinstall the cli
C:\Windows\system32>npm uninstall -g angular-cli
C:\Windows\system32>npm cache clean or npm cache verify #(if npm > 5)
C:\Windows\system32>npm install -g @angular/cli@latest
Now update your local project version, because cli version of your local project is having higher priority than global one when you try to execute your project.
C:\apps\workspace\testProj>rm -rf node_modules
C:\apps\workspace\testProj>npm uninstall --save-dev angular-cli
C:\apps\workspace\testProj>npm install --save-dev @angular/cli@latest
C:\apps\workspace\testProj>npm install
C:\apps\workspace\testProj>ng update @angular/cli
Step3. Verify if local project cli version now in sync with global one
C:\Windows\system32>ng --version
Angular CLI: 8.3.13
C:\apps\workspace\testProj>ng --version
Angular CLI: 8.3.13
Step4.. Revalidate on the project
C:\apps\workspace\testProj>ng serve
Should work now
You need to delegate event to the document level
$(document).on('submit','form.remember',function(){
// code
});
$('form.remember').on('submit'
work same as $('form.remember').submit(
but when you use $(document).on('submit','form.remember'
then it will also work for the DOM added later.
To have it in one line, this is what I did:
if any(([True if 'MICHAEL89' in username.upper() else False for username in USERNAMES])):
print('username exists in list')
I didn't test it time-wise though. I am not sure how fast/efficient it is.
In my case, six was installed for python 2.7 and for 3.7 too, and both pip install six
and pip3 install six
reported it as already installed, while I still had apps (particularly, the apt program itself) complaining about missing six.
The solution was to install it for python3.6 specifically:
/usr/bin/python3.6 -m pip install six
netcat
(nc.exe
) is the right tool. I have a feeling that any tool that does what you want it to do will have exactly the same problem with your antivirus software. Just flag this program as "OK" in your antivirus software (how you do this will depend on what type of antivirus software you use).
Of course you will also need to configure your sysadmin to accept that you're not trying to do anything illegal...
SIMPLE SOLUTION (tested on Red Hat):
run command: curl -sS https://getcomposer.org/installer | php
to use it: php composer.phar
SYSTEM WIDE SOLLUTION (tested on Red Hat):
run command: mv composer.phar /usr/local/bin/composer
to use it: composer update
now you can call composer from any directory.
Source: http://www.agix.com.au/install-composer-on-centosredhat/
SetRetainInstance(true) allows the fragment sort of survive. Its members will be retained during configuration change like rotation. But it still may be killed when the activity is killed in the background. If the containing activity in the background is killed by the system, it's instanceState should be saved by the system you handled onSaveInstanceState properly. In another word the onSaveInstanceState will always be called. Though onCreateView won't be called if SetRetainInstance is true and fragment/activity is not killed yet, it still will be called if it's killed and being tried to be brought back.
Here are some analysis of the android activity/fragment hope it helps. http://ideaventure.blogspot.com.au/2014/01/android-activityfragment-life-cycle.html
Try this maybe :
Bootply : http://www.bootply.com/106527
Js :
$('input').on('click', function(){
var valeur = 0;
$('input:checked').each(function(){
if ( $(this).attr('value') > valeur )
{
valeur = $(this).attr('value');
}
});
$('.progress-bar').css('width', valeur+'%').attr('aria-valuenow', valeur);
});
HTML :
<div class="progress progress-striped active">
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
</div>
</div>
<div class="row tasks">
<div class="col-md-6">
<p><span>Identify your campaign audience.</span>Who are we talking to here? Understand your buyer persona before launching into a campaign, so you can target them correctly.</p>
</div>
<div class="col-md-2">
<label>2014-01-29</label>
</div>
<div class="col-md-2">
<input name="progress" class="progress" type="checkbox" value="10">
</div>
<div class="col-md-2">
<input name="done" class="done" type="checkbox" value="20">
</div>
</div><!-- tasks -->
<div class="row tasks">
<div class="col-md-6">
<p><span>Set your goals + benchmarks</span>Having SMART goals can help you be
sure that you’ll have tangible results to share with the world (or your
boss) at the end of your campaign.</p>
</div>
<div class="col-md-2">
<label>2014-01-25</label>
</div>
<div class="col-md-2">
<input name="progress" class="progress" type="checkbox" value="30">
</div>
<div class="col-md-2">
<input name="done" class="done" type="checkbox" value="40">
</div>
</div><!-- tasks -->
Css
.tasks{
background-color: #F6F8F8;
padding: 10px;
border-radius: 5px;
margin-top: 10px;
}
.tasks span{
font-weight: bold;
}
.tasks input{
display: block;
margin: 0 auto;
margin-top: 10px;
}
.tasks a{
color: #000;
text-decoration: none;
border:none;
}
.tasks a:hover{
border-bottom: dashed 1px #0088cc;
}
.tasks label{
display: block;
text-align: center;
}
$(function(){_x000D_
$('input').on('click', function(){_x000D_
var valeur = 0;_x000D_
$('input:checked').each(function(){_x000D_
if ( $(this).attr('value') > valeur )_x000D_
{_x000D_
valeur = $(this).attr('value');_x000D_
}_x000D_
});_x000D_
$('.progress-bar').css('width', valeur+'%').attr('aria-valuenow', valeur); _x000D_
});_x000D_
_x000D_
});
_x000D_
.tasks{_x000D_
background-color: #F6F8F8;_x000D_
padding: 10px;_x000D_
border-radius: 5px;_x000D_
margin-top: 10px;_x000D_
}_x000D_
.tasks span{_x000D_
font-weight: bold;_x000D_
}_x000D_
.tasks input{_x000D_
display: block;_x000D_
margin: 0 auto;_x000D_
margin-top: 10px;_x000D_
}_x000D_
.tasks a{_x000D_
color: #000;_x000D_
text-decoration: none;_x000D_
border:none;_x000D_
}_x000D_
.tasks a:hover{_x000D_
border-bottom: dashed 1px #0088cc;_x000D_
}_x000D_
.tasks label{_x000D_
display: block;_x000D_
text-align: center;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="progress progress-striped active">_x000D_
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">_x000D_
</div>_x000D_
</div>_x000D_
<div class="row tasks">_x000D_
<div class="col-md-6">_x000D_
<p><span>Identify your campaign audience.</span>Who are we talking to here? Understand your buyer persona before launching into a campaign, so you can target them correctly.</p>_x000D_
</div>_x000D_
<div class="col-md-2">_x000D_
<label>2014-01-29</label>_x000D_
</div>_x000D_
<div class="col-md-2">_x000D_
<input name="progress" class="progress" type="checkbox" value="10">_x000D_
</div>_x000D_
<div class="col-md-2">_x000D_
<input name="done" class="done" type="checkbox" value="20">_x000D_
</div>_x000D_
</div><!-- tasks -->_x000D_
_x000D_
<div class="row tasks">_x000D_
<div class="col-md-6">_x000D_
<p><span>Set your goals + benchmarks</span>Having SMART goals can help you be_x000D_
sure that you’ll have tangible results to share with the world (or your_x000D_
boss) at the end of your campaign.</p>_x000D_
</div>_x000D_
<div class="col-md-2">_x000D_
<label>2014-01-25</label>_x000D_
</div>_x000D_
<div class="col-md-2">_x000D_
<input name="progress" class="progress" type="checkbox" value="30">_x000D_
</div>_x000D_
<div class="col-md-2">_x000D_
<input name="done" class="done" type="checkbox" value="40">_x000D_
</div>_x000D_
</div><!-- tasks -->
_x000D_
found this on Zurb's github
In case you want to do some more custom styling. Here's all the default CSS for webkit rendering of the date components.
input[type="date"] {
-webkit-align-items: center;
display: -webkit-inline-flex;
font-family: monospace;
overflow: hidden;
padding: 0;
-webkit-padding-start: 1px;
}
input::-webkit-datetime-edit {
-webkit-flex: 1;
-webkit-user-modify: read-only !important;
display: inline-block;
min-width: 0;
overflow: hidden;
}
input::-webkit-datetime-edit-fields-wrapper {
-webkit-user-modify: read-only !important;
display: inline-block;
padding: 1px 0;
white-space: pre;
}
For me, I found the suggestion in the following thread helped:
It suggested running the following command in the Terminal application:
sudo /usr/sbin/DevToolsSecurity --enable
Just change "target": "es2015" to "target": "es5" in your tsconfig.json.
Work for me with Angular 8.2.XX
Tested on IE11 and Edge
If you still get Permission denied
errors when you try to run your script in the docker's entrypoint, just try DO NOT use the shell form of the entrypoint:
Instead of:
ENTRYPOINT ./bin/watcher
write ENTRYPOINT ["./bin/watcher"]
:
https://docs.docker.com/engine/reference/builder/#entrypoint
I use this:
public class ReversedView<E> extends AbstractList<E>{
public static <E> List<E> of(List<E> list) {
return new ReversedView<>(list);
}
private final List<E> backingList;
private ReversedView(List<E> backingList){
this.backingList = backingList;
}
@Override
public E get(int i) {
return backingList.get(backingList.size()-i-1);
}
@Override
public int size() {
return backingList.size();
}
}
like this:
ReversedView.of(backingList) // is a fully-fledged generic (but read-only) list
You can use PostBackUrl="~/Confirm.aspx"
For example:
In your .aspx file
<asp:Button ID="btnConfirm" runat="server" Text="Confirm"
PostBackUrl="~/Confirm.aspx" />
or in your .cs file
btnConfirm.PostBackUrl="~/Confirm.aspx"
Setting the environment variable NODE_PATH to point to your global node_modules
folder.
In Windows 7 or higher the path is something like %AppData%\npm\node_modules
while in UNIX could be something like /home/sg/.npm_global/lib/node_modules/
but it depends on user configuration.
The command npm config get prefix
could help finding out which is the correct path.
In UNIX systems you can accomplish it with the following command:
export NODE_PATH=`npm config get prefix`/lib/node_modules/
There is a dynamic comparison chart over at the versioncontrolblog where you can compare several different version control systems.
var theString = "TEST";
char[] myChar = theString.ToCharArray();
I tested this in the C# interactive window of Visual Studio 2019 and got:
char[4] { 'T', 'E', 'S', 'T' }
I went through this and found all the answers super cool, however wants to add to answer given by @deejers
SELECT
col1,
col2,
col3,
CASE
WHEN condition1 THEN calculation1
WHEN condition2 THEN calculation2
WHEN condition3 THEN calculation3
WHEN condition4 THEN calculation4
WHEN condition5 THEN calculation5
END AS 'calculatedcol1',
col4,
col5 -- etc
FROM table
you can make ELSE optional as its not mandatory, it is very helpful in many scenarios.
If you apply utf8_encode()
to an already UTF-8 string, it will return garbled UTF-8 output.
I made a function that addresses all this issues. It´s called Encoding::toUTF8()
.
You don't need to know what the encoding of your strings is. It can be Latin1 (ISO 8859-1), Windows-1252 or UTF-8, or the string can have a mix of them. Encoding::toUTF8()
will convert everything to UTF-8.
I did it because a service was giving me a feed of data all messed up, mixing UTF-8 and Latin1 in the same string.
Usage:
require_once('Encoding.php');
use \ForceUTF8\Encoding; // It's namespaced now.
$utf8_string = Encoding::toUTF8($utf8_or_latin1_or_mixed_string);
$latin1_string = Encoding::toLatin1($utf8_or_latin1_or_mixed_string);
Download:
https://github.com/neitanod/forceutf8
I've included another function, Encoding::fixUFT8()
, which will fix every UTF-8 string that looks garbled.
Usage:
require_once('Encoding.php');
use \ForceUTF8\Encoding; // It's namespaced now.
$utf8_string = Encoding::fixUTF8($garbled_utf8_string);
Examples:
echo Encoding::fixUTF8("Fédération Camerounaise de Football");
echo Encoding::fixUTF8("Fédération Camerounaise de Football");
echo Encoding::fixUTF8("FÃÂédÃÂération Camerounaise de Football");
echo Encoding::fixUTF8("Fédération Camerounaise de Football");
will output:
Fédération Camerounaise de Football
Fédération Camerounaise de Football
Fédération Camerounaise de Football
Fédération Camerounaise de Football
I've transformed the function (forceUTF8
) into a family of static functions on a class called Encoding
. The new function is Encoding::toUTF8()
.
Putting this information here for future readers' benefit.
401 (Unauthorized) response header -> Request authentication header
Here are several WWW-Authenticate
response headers. (The full list is at IANA: HTTP Authentication Schemes.)
WWW-Authenticate: Basic
-> Authorization: Basic + token - Use for basic authentication WWW-Authenticate: NTLM
-> Authorization: NTLM + token (2 challenges)WWW-Authenticate: Negotiate
-> Authorization: Negotiate + token - used for Kerberos authentication
Negotiate
: This authentication scheme violates both HTTP semantics (being connection-oriented) and syntax (use of syntax incompatible with the WWW-Authenticate and Authorization header field syntax).You can set the Authorization: Basic
header only when you also have the WWW-Authenticate: Basic
header on your 401 challenge.
But since you have WWW-Authenticate: Negotiate
this should be the case for Kerberos based authentication.
Note that the above solutions will not tell you if your installation is correct only if your install.exe is correct (you can trust it to produce a correct install.)
You would need MD5 sums for each file/folder to test if the installed code has been messed with after the install completed.
WinMerg is useful to compare two installs (on two different machines perhaps) to see if one has been changed or why one is broken.
I tried all of the suggestions found here, from enabling less secure apps, to trying port 587... nothing worked. Finally I just commented out the line UseDefaultCredentials = false
. Everything worked if I didn't touch that boolean.
You can't do a bulk-update in SSIS within a dataflow task with the OOB components.
The general pattern is to identify your inserts, updates and deletes and push the updates and deletes to a staging table(s) and after the Dataflow Task, use a set-based update or delete in an Execute SQL Task. Look at Andy Leonard's Stairway to Integration Services series. Scroll about 3/4 the way down the article to "Set-Based Updates" to see the pattern.
Stage data
Set based updates
You'll get much better performance with a pattern like this versus using the OLE DB Command
transformation for anything but trivial amounts of data.
If you are into third party tools, I believe CozyRoc and I know PragmaticWorks have a merge destination component.
Log.v("blah", "blah blah");
You need to add the android Log view in eclipse to see them. There are also other methods depending on the severity of the message (error, verbose, warning, etc..).
Spring has org.springframework.core.io.Resource which is designed for such situations. From context.xml you can pass classpath to the bean
<bean class="test.Test1">
<property name="path" value="classpath:/test/test1.xml" />
</bean>
and you get it in your bean as Resource:
public void setPath(Resource path) throws IOException {
File file = path.getFile();
System.out.println(file);
}
output
D:\workspace1\spring\target\test-classes\test\test1.xml
Now you can use it in new FileReader(file)
I use viewbag with the same variable name in the Controller. E.g if the variable is called "IsActive" and I want this to default to true on the "Create" form, on the Create Action I set the value ViewBag.IsActive = true;
public ActionResult Create()
{
ViewBag.IsActive = true;
return View();
}
By the time the image is loaded, the renderer has already drawn the scene, hence it is too late. The solution is to change
texture = THREE.ImageUtils.loadTexture('crate.gif'),
into
texture = THREE.ImageUtils.loadTexture('crate.gif', {}, function() {
renderer.render(scene);
}),
try FileSaver.js
library. it might help.
The correct answer is already stated (just use SortedDictionary).
However, if by chance you have some need to retain your collection as Dictionary, it is possible to access the Dictionary keys in an ordered way, by, for example, ordering the keys in a List, then using this list to access the Dictionary. An example...
Dictionary<string, int> dupcheck = new Dictionary<string, int>();
...some code that fills in "dupcheck", then...
if (dupcheck.Count > 0) {
Console.WriteLine("\ndupcheck (count: {0})\n----", dupcheck.Count);
var keys_sorted = dupcheck.Keys.ToList();
keys_sorted.Sort();
foreach (var k in keys_sorted) {
Console.WriteLine("{0} = {1}", k, dupcheck[k]);
}
}
Don't forget using System.Linq;
for this.
My two cents... This is the way I understand it. (Feel free to correct me if I'm wrong)
It's time to throw out everything you know about pass by value / reference.
Because in JavaScript, it doesn't matter whether it's passed by value or by reference or whatever. What matters is mutation vs assignment of the parameters passed into a function.
OK, let me do my best to explain what I mean. Let's say you have a few objects.
var object1 = {};
var object2 = {};
What we have done is "assignment"... We've assigned 2 separate empty objects to the variables "object1" and "object2".
Now, let's say that we like object1 better... So, we "assign" a new variable.
var favoriteObject = object1;
Next, for whatever reason, we decide that we like object 2 better. So, we do a little re-assignment.
favoriteObject = object2;
Nothing happened to object1 or to object2. We haven't changed any data at all. All we did was re-assign what our favorite object is. It is important to know that object2 and favoriteObject are both assigned to the same object. We can change that object via either of those variables.
object2.name = 'Fred';
console.log(favoriteObject.name) // Logs Fred
favoriteObject.name = 'Joe';
console.log(object2.name); // Logs Joe
OK, now let's look at primitives like strings for example
var string1 = 'Hello world';
var string2 = 'Goodbye world';
Again, we pick a favorite.
var favoriteString = string1;
Both our favoriteString and string1 variables are assigned to 'Hello world'. Now, what if we want to change our favoriteString??? What will happen???
favoriteString = 'Hello everyone';
console.log(favoriteString); // Logs 'Hello everyone'
console.log(string1); // Logs 'Hello world'
Uh oh.... What has happened. We couldn't change string1 by changing favoriteString... Why?? Because we didn't change our string object. All we did was "RE ASSIGN" the favoriteString variable to a new string. This essentially disconnected it from string1. In the previous example, when we renamed our object, we didn't assign anything. (Well, not to the variable itself, ... we did, however, assign the name property to a new string.) Instead, we mutated the object which keeps the connections between the 2 variables and the underlying objects. (Even if we had wanted to modify or mutate the string object itself, we couldn't have, because strings are actually immutable in JavaScript.)
Now, on to functions and passing parameters.... When you call a function, and pass a parameter, what you are essentially doing is an "assignment" to a new variable, and it works exactly the same as if you assigned using the equal (=) sign.
Take these examples.
var myString = 'hello';
// Assign to a new variable (just like when you pass to a function)
var param1 = myString;
param1 = 'world'; // Re assignment
console.log(myString); // Logs 'hello'
console.log(param1); // Logs 'world'
Now, the same thing, but with a function
function myFunc(param1) {
param1 = 'world';
console.log(param1); // Logs 'world'
}
var myString = 'hello';
// Calls myFunc and assigns param1 to myString just like param1 = myString
myFunc(myString);
console.log(myString); // logs 'hello'
OK, now let’s give a few examples using objects instead... first, without the function.
var myObject = {
firstName: 'Joe',
lastName: 'Smith'
};
// Assign to a new variable (just like when you pass to a function)
var otherObj = myObject;
// Let's mutate our object
otherObj.firstName = 'Sue'; // I guess Joe decided to be a girl
console.log(myObject.firstName); // Logs 'Sue'
console.log(otherObj.firstName); // Logs 'Sue'
// Now, let's reassign the variable
otherObj = {
firstName: 'Jack',
lastName: 'Frost'
};
// Now, otherObj and myObject are assigned to 2 very different objects
// And mutating one object has no influence on the other
console.log(myObject.firstName); // Logs 'Sue'
console.log(otherObj.firstName); // Logs 'Jack';
Now, the same thing, but with a function call
function myFunc(otherObj) {
// Let's mutate our object
otherObj.firstName = 'Sue';
console.log(otherObj.firstName); // Logs 'Sue'
// Now let's re-assign
otherObj = {
firstName: 'Jack',
lastName: 'Frost'
};
console.log(otherObj.firstName); // Logs 'Jack'
// Again, otherObj and myObject are assigned to 2 very different objects
// And mutating one object doesn't magically mutate the other
}
var myObject = {
firstName: 'Joe',
lastName: 'Smith'
};
// Calls myFunc and assigns otherObj to myObject just like otherObj = myObject
myFunc(myObject);
console.log(myObject.firstName); // Logs 'Sue', just like before
OK, if you read through this entire post, perhaps you now have a better understanding of how function calls work in JavaScript. It doesn't matter whether something is passed by reference or by value... What matters is assignment vs mutation.
Every time you pass a variable to a function, you are "Assigning" to whatever the name of the parameter variable is, just like if you used the equal (=) sign.
Always remember that the equals sign (=) means assignment. Always remember that passing a parameter to a function in JavaScript also means assignment. They are the same and the 2 variables are connected in exactly the same way (which is to say they aren't, unless you count that they are assigned to the same object).
The only time that "modifying a variable" affects a different variable is when the underlying object is mutated (in which case you haven't modified the variable, but the object itself.
There is no point in making a distinction between objects and primitives, because it works the same exact way as if you didn't have a function and just used the equal sign to assign to a new variable.
The only gotcha is when the name of the variable you pass into the function is the same as the name of the function parameter. When this happens, you have to treat the parameter inside the function as if it was a whole new variable private to the function (because it is)
function myFunc(myString) {
// myString is private and does not affect the outer variable
myString = 'hello';
}
var myString = 'test';
myString = myString; // Does nothing, myString is still 'test';
myFunc(myString);
console.log(myString); // Logs 'test'
The necessary method is Mockito#verify:
public static <T> T verify(T mock,
VerificationMode mode)
mock
is your mocked object and mode
is the VerificationMode
that describes how the mock should be verified. Possible modes are:
verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");
You'll need these static imports from the Mockito
class in order to use the verify
method and these verification modes:
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
So in your case the correct syntax will be:
Mockito.verify(mock, times(4)).send()
This verifies that the method send
was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.
If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode
. A simple
verify(mock).someMethod("was called once");
would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");
.
It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");
, but we can write
verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");
instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.
It is, in principle, impossible to determine the encoding of a text file, in the general case. So no, there is no standard Python library to do that for you.
If you have more specific knowledge about the text file (e.g. that it is XML), there might be library functions.
simply don't cast to int
switch(operator)
{
case Operator.Plus:
//todo
Currently (Laravel 5.4) the way to achieve this is:
$model = new Model();
$model->created_at = Carbon::now();
$model->save(['timestamps' => false]);
Pages are intended for use in Navigation applications (usually with Back and Forward buttons, e.g. Internet Explorer). Pages must be hosted in a NavigationWindow or a Frame
Windows are just normal WPF application Windows, but can host Pages via a Frame container
PHP has no explicit byte
type, but its string
is already the equivalent of Java's byte array. You can safely write fputs($connection, "The quick brown fox …")
. The only thing you must be aware of is character encoding, they must be the same on both sides. Use mb_convert_encoding() when in doubt.
Use path.join(__dirname, '/start.html')
;
var fs = require('fs'),
path = require('path'),
filePath = path.join(__dirname, 'start.html');
fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
if (!err) {
console.log('received data: ' + data);
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data);
response.end();
} else {
console.log(err);
}
});
Thanks to dc5.
A bit late, but I just stumbled across the same problem while trying to provide analytics for my web app that involved sending app version based on the package.json version.
Configuration is as follows: React + Redux, Webpack 3.5.6
The json-loader isn't doing much since Webpack 2+, so after some fiddling with it, I ended up removing it.
The solution that actually worked for me, was simply using fetch. While this will most probably enforce some code changes to adapt to the async approach, it worked perfectly, especially given the fact that fetch will offer json decoding on the fly.
So here it is:
fetch('../../package.json')
.then(resp => resp.json())
.then((packageJson) => {
console.log(packageJson.version);
});
Do keep in mind, that since we're talking about package.json specifically here, the file will not usually come bundled in your production build (or even dev for that matter), so you will have to use the CopyWebpackPlugin to have access to it when using fetch.
For AspNetCore, it looks like this:
<aspNetCore requestTimeout="00:20:00">
By Timestamp
, I presume you mean java.sql.Timestamp
. You will notice that this class has a constructor that accepts a long
argument. You can parse this using the DateFormat
class:
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateFormat.parse("23/09/2007");
long time = date.getTime();
new Timestamp(time);
var lat = homeMarker.getPosition().lat();
var lng = homeMarker.getPosition().lng();
See the google.maps.LatLng docs and google.maps.Marker getPosition()
.
services.msc
Find MySql and change properties to the disabled.Xampp
uninstall MySql by the checkbox on the left side, and install again by the click in the same checkbox.It's weird that the Swing toolkit doesn't include this functionality, but here's the best answer to your question:
textField = new JTextField();
textField.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
if (txtGuess.getText().length() >= 3 ) // limit to 3 characters
e.consume();
}
});
I use this in a fun guessing game example in my Udemy.com course "Learn Java Like a Kid". Cheers - Bryson
How to run a shell script from a Perl program
1. Using system
system($command, @arguments);
For example:
system("sh", "script.sh", "--help" ); system("sh script.sh --help");
System will execute the $command with @arguments and return to your script when finished. You may check $! for certain errors passed to the OS by the external application. Read the documentation for system for the nuances of how various invocations are slightly different.
2. Using
exec
This is very similar to the use of system, but it will terminate your script upon execution. Again, read the documentation for exec for more.
3. Using backticks or
qx//
my $output = `script.sh --option`; my $output = qx/script.sh --option/;
The backtick operator and it's equivalent
qx//
, excute the command and options inside the operator and return that commands output to STDOUT when it finishes.There are also ways to run external applications through creative use of open, but this is advanced use; read the documentation for more.
I figured this one out. I know this will help someone someday.
How to Vertically & Horizontally Center a Div Over a Relatively Positioned Image
The key was a 3rd wrapper. I would vote up any answer that uses less wrappers.
HTML
<div class="wrapper">
<img src="my-slide.jpg">
<div class="outer-wrapper">
<div class="table-wrapper">
<div class="table-cell-wrapper">
<h1>My Title</h1>
<p>Subtitle</p>
</div>
</div>
</div>
</div>
CSS
html, body {
margin: 0; padding: 0;
width: 100%; height: 100%;
}
ul {
width: 100%;
height: 100%;
list-style-position: outside;
margin: 0; padding: 0;
}
li {
width: 100%;
display: table;
}
img {
width: 100%;
height: 100%;
}
.outer-wrapper {
width: 100%;
height: 100%;
position: absolute;
top: 0;
margin: 0; padding: 0;
}
.table-wrapper {
width: 100%;
height: 100%;
display: table;
vertical-align: middle;
text-align: center;
}
.table-cell-wrapper {
width: 100%;
height: 100%;
display: table-cell;
vertical-align: middle;
text-align: center;
}
You can see the working jsFiddle here.
I figured out myself.
cmp
calls ComputeBetasAndNuHat
which returns a list which has objective
as minusloglik
So I can change the function cmp
to get this value.
The gdi32 library is already installed on your computer, few programs will run without it. Your compiler will (if installed properly) normally come with an import library, which is what the linker uses to make a binding between your program and the file in the system. (In the unlikely case that your compiler does not come with import libraries for the system libs, you will need to download the Microsoft Windows Platform SDK.)
To link with gdi32:
This will reliably work with MinGW-gcc for all system libraries (it should work if you use any other compiler too, but I can't talk about things I've not tried). You can also write the library's full name, but writing libgdi32.a
has no advantage over gdi32
other than being more type work.
If it does not work for some reason, you may have to provide a different name (for example the library is named gdi32.lib
for MSVC).
For libraries in some odd locations or project subfolders, you will need to provide a proper pathname (click on the "..." button for a file select dialog).
I recently ran into the same problem, and found a workaround though it'll only be useful if you can change the html code to suit.
I used tables to achieve my padded layout, so to create the equivalent of a div with internal padding I made a table with 3 columns/3 rows and put the content in the centre row/column. The first and last columns/rows are used for the padding.
eg.
<table>
<tr>
<td width="10"> </td>
<td> </td>
<td width="10"> </td>
</tr>
<tr>
<td> </td>
<td>content goes here</td>
<td> </td>
</tr>
<tr>
<td width="10"> </td>
<td> </td>
<td width="10"> </td>
</tr>
</table>
Hope that helps.
Joe
The problem is that even JavaScript does not see the option
element being hovered. This is just to put emphasis on how it's not going to be solved (any time soon at least) by using just CSS:
window.onmouseover = function(e)
{
console.log(e.target.nodeName);
}
The only way to resolve this issue (besides waiting a millennia for browser vendors to fix bugs, let alone one that afflicts what you're trying to do) is to replace the drop-down menu with your own HTML/XML using JavaScript. This would likely involve the use of replacing the select
element with a ul
element and the use of a radio
input
element per li
element.
autocomplete=off
is largely ignored in modern browsers - primarily due to password managers etc.
You can try adding this autocomplete="new-password"
it's not fully supported by all browsers, but it works on some
It's just docker pull busybox
, are you using an up to date version of the docker
client. I think they stopped supporting clients lower than 1.5.
Incidentally that curl works for me:
$ curl -k https://registry.hub.docker.com/v1/repositories/busybox/tags
[{"layer": "fc0db02f", "name": "latest"}, {"layer": "fc0db02f", "name": "1"}, {"layer": "a6dbc8d6", "name": "1-ubuntu"}, {"layer": "a6dbc8d6", "name": "1.21-ubuntu"}, {"layer": "a6dbc8d6", "name": "1.21.0-ubuntu"}, {"layer": "d7057cb0", "name": "1.23"}, {"layer": "d7057cb0", "name": "1.23.2"}, {"layer": "fc0db02f", "name": "1.24"}, {"layer": "3d5bcd78", "name": "1.24.0"}, {"layer": "fc0db02f", "name": "1.24.1"}, {"layer": "1c677c87", "name": "buildroot-2013.08.1"}, {"layer": "0f864637", "name": "buildroot-2014.02"}, {"layer": "a6dbc8d6", "name": "ubuntu"}, {"layer": "ff8f955d", "name": "ubuntu-12.04"}, {"layer": "633fcd11", "name": "ubuntu-14.04"}]
Interesting enough if you sniff the headers you get a HTTP 405 (Method not allowed). I think this might be to do with the fact that Docker have deprecated their Registry API.
A few comments:
analog=True
in the call to butter
, and you should use scipy.signal.freqz
(not freqs
) to generate the frequency response.Here's my modified version of your script, followed by the plot that it generates.
import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt
def butter_lowpass(cutoff, fs, order=5):
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
b, a = butter(order, normal_cutoff, btype='low', analog=False)
return b, a
def butter_lowpass_filter(data, cutoff, fs, order=5):
b, a = butter_lowpass(cutoff, fs, order=order)
y = lfilter(b, a, data)
return y
# Filter requirements.
order = 6
fs = 30.0 # sample rate, Hz
cutoff = 3.667 # desired cutoff frequency of the filter, Hz
# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)
# Plot the frequency response.
w, h = freqz(b, a, worN=8000)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()
# Demonstrate the use of the filter.
# First make some data to be filtered.
T = 5.0 # seconds
n = int(T * fs) # total number of samples
t = np.linspace(0, T, n, endpoint=False)
# "Noisy" data. We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t)
# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)
plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()
plt.subplots_adjust(hspace=0.35)
plt.show()
Workaround for Linq-to-SQL:
var result = from entry in table
where entry.something.Equals(value)
select entry;
Workaround for Linq-to-Entities (ouch!):
var result = from entry in table
where (value == null ? entry.something == null : entry.something == value)
select entry;
This is a nasty bug which has bitten me several times. If this bug has affected you too, please visit the bug report on UserVoice and let Microsoft know that this bug has affected you as well.
Edit: This bug is being fixed in EF 4.5! Thanks everyone for upvoting this bug!
For backwards compatibility, it will be opt-in - you need manually enable a setting to make entry == value
work. No word yet on what this setting is. Stay tuned!
Edit 2: According to this post by the EF team, this issue has been fixed in EF6! Woohoo!
We changed the default behavior of EF6 to compensate for three-valued logic.
This means that existing code that relies on the old behavior (null != null
, but only when comparing to a variable) will either need to be changed to not rely on that behavior, or set UseCSharpNullComparisonBehavior
to false to use the old broken behavior.
Fundamentally if you use it as part of a business then its commercial use - so its not a matter of whether the tools are directly generating income or not rather one of if they are being used in support of income generation directly or indirectly.
To take your specific example, if the purpose of the site is to sell or promote your paid services/product then its a commercial enterprise.
If the usage pattern justifies it, why not? While your team doesn't recognize the operator right away, with time they could. Humans learn new words all the time. Why not in programming?
The only caution I might state is that "^" doesn't have the short circuit semantics of your second boolean check. If you really need the short circuit semantics, then a static util method works too.
public static boolean xor(boolean a, boolean b) {
return (a && !b) || (b && !a);
}
If you have not committed any changes all you have to do is stash those changes and you will be back to the last working commit.
git stash
git stash clear
git clean
If in case you are using ubuntu trusty 14.0 then search for Network and select Network Proxy and make it none. Now proxy may still be set in system environment variables. check
env|grep -i proxy
you may get output as
http_proxy=http://192.168.X.X:8080/
ftp_proxy=ftp://192.168.X.X:8080/
socks_proxy=socks://192.168.X.X:8080/
https_proxy=https://192.168.X.X:8080/
unset these environment variable as:
unset(http_proxy)
and in this way unset all. Now run npm install ensuring user must have permission to make node_modules folder where you are installing module.
To make the code clear that you are intending to get the first row, CodeIgniter now allows you to use:
if ($query->num_rows() > 0) {
return $query->first_row();
}
To retrieve the first row.
Works perfect for me:
(SELECT content FROM tblopportunitycomments WHERE opportunityid = 1 ORDER BY dateadded DESC LIMIT 1);
@jim's answer is correct -- fuser
is what you want.
Additionally (or alternately), you can use lsof
to get more information including the username, in case you need permission (without having to run an additional command) to kill the process. (THough of course, if killing the process is what you want, fuser
can do that with its -k
option. You can have fuser
use other signals with the -s
option -- check the man page for details.)
For example, with a tail -F /etc/passwd
running in one window:
ghoti@pc:~$ lsof | grep passwd
tail 12470 ghoti 3r REG 251,0 2037 51515911 /etc/passwd
Note that you can also use lsof
to find out what processes are using particular sockets. An excellent tool to have in your arsenal.
Something like this:
if($('#postageyes').is(':checked')) {
// do stuff
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Library
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
string query = "INSERT INTO [Table] (BookName , AuthorName , Category) VALUES('" + textBox1.Text.ToString() + "' , '" + textBox2.Text.ToString() + "' , '" + textBox3.Text.ToString() + "')";
SqlCommand com = new SqlCommand(query, con);
con.Open();
com.ExecuteNonQuery();
con.Close();
MessageBox.Show("Entry Added");
}
private void button3_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
string query = "SELECT * FROM [TABLE] WHERE BookName='" + textBox1.Text.ToString() + "' OR AuthorName='" + textBox2.Text.ToString() + "'";
string query1 = "SELECT BookStatus FROM [Table] where BookName='" + textBox1.Text.ToString() + "'";
string query2 = "SELECT DateOfReturn FROM [Table] where BookName='" + textBox1.Text.ToString() + "'";
SqlCommand com = new SqlCommand(query, con);
SqlDataReader dr, dr1,dr2;
con.Open();
com.ExecuteNonQuery();
dr = com.ExecuteReader();
if (dr.Read())
{
con.Close();
con.Open();
SqlCommand com1 = new SqlCommand(query1, con);
com1.ExecuteNonQuery();
dr1 = com1.ExecuteReader();
dr1.Read();
string i = dr1["BookStatus"].ToString();
if (i =="1" )
{
con.Close();
con.Open();
SqlCommand com2 = new SqlCommand(query2, con);
com2.ExecuteNonQuery();
dr2 = com2.ExecuteReader();
dr2.Read();
MessageBox.Show("This book is already issued\n " + "Book will be available by "+ dr2["DateOfReturn"] );
}
else
{
con.Close();
con.Open();
dr = com.ExecuteReader();
dr.Read();
MessageBox.Show("BookFound\n" + "BookName=" + dr["BookName"] + "\n AuthorName=" + dr["AuthorName"]);
}
con.Close();
}
else
{
MessageBox.Show("This Book is not available in the library");
}
}
private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
string query = "SELECT * FROM [TABLE] WHERE BookName='" + textBox1.Text.ToString() + "'";
string dateofissue1 = DateTime.Today.ToString("dd-MM-yyyy");
string dateofreturn = DateTime.Today.AddDays(15).ToString("dd-MM-yyyy");
string query1 = "update [Table] set BookStatus=1,DateofIssue='"+ dateofissue1 +"',DateOfReturn='"+ dateofreturn +"' where BookName='" + textBox1.Text.ToString() + "'";
con.Open();
SqlCommand com = new SqlCommand(query, con);
SqlDataReader dr;
com.ExecuteNonQuery();
dr = com.ExecuteReader();
if (dr.Read())
{
con.Close();
con.Open();
string dateofissue = DateTime.Today.ToString("dd-MM-yyyy");
textBox4.Text = dateofissue;
textBox5.Text = DateTime.Today.AddDays(15).ToString("dd-MM-yyyy");
SqlCommand com1 = new SqlCommand(query1, con);
com1.ExecuteNonQuery();
MessageBox.Show("Book Isuued");
}
else
{
MessageBox.Show("Book Not Found");
}
con.Close();
}
private void button4_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
string query1 = "update [Table] set BookStatus=0 WHERE BookName='"+textBox1.Text.ToString()+"'";
con.Open();
SqlCommand com = new SqlCommand(query1, con);
com.ExecuteNonQuery();
string today = DateTime.Today.ToString("dd-MM-yyyy");
DateTime today1 = DateTime.Parse(today);
string query = "SELECT dateofReturn from [Table] where BookName='" + textBox1.Text.ToString() + "'";
con.Close();
con.Open();
SqlDataReader dr;
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
dr = cmd.ExecuteReader();
dr.Read();
string DOR = dr["DateOfReturn"].ToString();
DateTime dor = DateTime.Parse(DOR);
TimeSpan ts = today1.Subtract(dor);
string query2 = "update [Table] set DateOfIssue=NULL, DateOfReturn=NULL WHERE BookName='" + textBox1.Text.ToString() + "'";
con.Close();
con.Open();
SqlCommand com2 = new SqlCommand(query2, con);
com2.ExecuteNonQuery();
int x = int.Parse(ts.Days.ToString());
if (x > 0)
{
int fine = x * 5;
textBox6.Text = fine.ToString();
MessageBox.Show("Book Received\nFine=" + fine);
}
else
{
textBox6.Text = "0";
MessageBox.Show("Book Received\nFine=0");
}
con.Close();
}
}
}
If you use same color for whole program , you can define printf()
function.
#include<stdio.h>
#define ah_red "\e[31m"
#define printf(X) printf(ah_red "%s",X);
#int main()
{
printf("Bangladesh");
printf("\n");
return 0;
}
When you include a string literal in a query, you can enclose the string in either single or double quotes; Access' database engine will accept either. So double quotes will avoid the problem with a string which contains a single quote.
SELECT * FROM tblStudents WHERE [name] Like "Daniel O'Neal";
If you want to keep the single quotes around your string, you can double up the single quote within it, as mentioned in other answers.
SELECT * FROM tblStudents WHERE [name] Like 'Daniel O''Neal';
Notice the square brackets surrounding name. I used the brackets to lessen the chance of confusing the database engine because name is a reserved word.
It's not clear why you're using the Like comparison in your query. Based on what you've shown, this should work instead.
SELECT * FROM tblStudents WHERE [name] = "Daniel O'Neal";
As a workaround I've been returning the last object in the array that you get back from the function... It is not a great solution, but it's better than nothing:
someFunction {
$a = "hello"
"Function is running"
return $a
}
$b = someFunction
$b = $b[($b.count - 1)] # Or
$b = $b[-1] # Simpler
All in all, a more one-lineish way of writing the same thing could be:
$b = (someFunction $someParameter $andAnotherOne)[-1]
Hey Its working for me..
$shell = New-Object -ComObject shell.application
$zip = $shell.NameSpace("put ur zip file path here")
foreach ($item in $zip.items()) {
$shell.Namespace("destination where files need to unzip").CopyHere($item)
}
Just set the property of textbox that is
PasswordChar and set the *
as a property
of textbox. That will work for password.
passwordtextbox.PasswordChar = '*';
where passwordtextbox
is the text box name.
int(limit)
returns the value converted into an integer, and doesn't change it in place as you call the function (which is what you are expecting it to).
Do this instead:
limit = int(limit)
Or when definiting limit
:
if 'limit' in user_data :
limit = int(user_data['limit'])
A very useful solution is use the config module.
after install the module:
$ npm install config
You could create a default.json configuration file. (you could use JSON or JS object using extension .json5 )
For example
$ vi config/default.json
{
"name": "My App Name",
"configPath": "/my/default/path",
"port": 3000
}
This default configuration could be override by environment config file or a local config file for a local develop environment:
production.json could be:
{
"configPath": "/my/production/path",
"port": 8080
}
development.json could be:
{
"configPath": "/my/development/path",
"port": 8081
}
In your local PC you could have a local.json that override all environment, or you could have a specific local configuration as local-production.json or local-development.json.
The full list of load order.
Inside your App
In your app you only need to require config and the needed attribute.
var conf = require('config'); // it loads the right file
var login = require('./lib/everyauthLogin', {configPath: conf.get('configPath'));
Load the App
load the app using:
NODE_ENV=production node app.js
or setting the correct environment with forever or pm2
Forever:
NODE_ENV=production forever [flags] start app.js [app_flags]
PM2 (via shell):
export NODE_ENV=staging
pm2 start app.js
PM2 (via .json):
process.json
{
"apps" : [{
"name": "My App",
"script": "worker.js",
"env": {
"NODE_ENV": "development",
},
"env_production" : {
"NODE_ENV": "production"
}
}]
}
And then
$ pm2 start process.json --env production
This solution is very clean and it makes easy set different config files for Production/Staging/Development environment and for local setting too.
SOAP uses WSDL for communication btw consumer and provider, whereas REST just uses XML or JSON to send and receive data
WSDL defines contract between client and service and is static by its nature. In case of REST contract is somewhat complicated and is defined by HTTP, URI, Media Formats and Application Specific Coordination Protocol. It's highly dynamic unlike WSDL.
SOAP doesn't return human readable result, whilst REST result is readable with is just plain XML or JSON
This is not true. Plain XML or JSON are not RESTful at all. None of them define any controls(i.e. links and link relations, method information, encoding information etc...) which is against REST as far as messages must be self contained and coordinate interaction between agent/client and service.
With links + semantic link relations clients should be able to determine what is next interaction step and follow these links and continue communication with service.
It is not necessary that messages be human readable, it's possible to use cryptic format and build perfectly valid REST applications. It doesn't matter whether message is human readable or not.
Thus, plain XML(application/xml) or JSON(application/json) are not sufficient formats for building REST applications. It's always reasonable to use subset of these generic media types which have strong semantic meaning and offer enough control information(links etc...) to coordinate interactions between client and server.
REST is over only HTTP
Not true, HTTP is most widely used and when we talk about REST web services we just assume HTTP. HTTP defines interface with it's methods(GET, POST, PUT, DELETE, PATCH etc) and various headers which can be used uniformly for interacting with resources. This uniformity can be achieved with other protocols as well.
P.S. Very simple, yet very interesting explanation of REST: http://www.looah.com/source/view/2284
There are two possible scenario, in my case I used 2nd point.
If you are facing this issue in production environment and you can easily deploy new code to the production then you can use of below solution.
You can add below line of code before making api call,
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // .NET 4.5
If you cannot deploy new code and you want to resolve with the same code which is present in the production, then this issue can be done by changing some configuration setting file. You can add either of one in your config file.
<runtime>
<AppContextSwitchOverrides value="Switch.System.Net.DontEnableSchUseStrongCrypto=false"/>
</runtime>
or
<runtime>
<AppContextSwitchOverrides value="Switch.System.Net.DontEnableSystemDefaultTlsVersions=false"
</runtime>
For most of the people still receiving the error after fixing project properties, you probably installed Java 7 SDK when setting up your environment, but it is not currently supported for Android development.
As the error message sais, you should have installed Java 5.0 or 6.0, but Java 7 was found.
If you fix project properties without first installing Java 5 or 6, you will see the same error again.
And then:
OR
You can try :
document.getElementById('your_id_iframe').contentWindow.postMessage('your_message', 'your_domain_iframe')