Programs & Examples On #Evc

This tag is used for questions related to evc (eMbedded Visual C++).

Can't push to the heroku

Read this doc which will explain to you what to do.
https://devcenter.heroku.com/articles/buildpacks

Setting a buildpack on an application

You can change the buildpack used by an application by setting the buildpack value.
When the application is next pushed, the new buildpack will be used.

$ heroku buildpacks:set heroku/php

Buildpack set. Next release on random-app-1234 will use heroku/php.
Run git push heroku master to create a new release using this buildpack.

This is whay its not working for you since you did not set it up.

... When the application is next pushed, the new buildpack will be used.

You may also specify a buildpack during app creation:

$ heroku create myapp --buildpack heroku/python

setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op

I had this problem before, and solved it according to React official page isMounted is an Antipattern.

Set a property isMounted flag to be true in componentDidMount , and toggle it false in componentWillUnmount. When you setState() in your callbacks, check isMounted first! It works for me.

state = {
    isMounted: false
  }
  componentDidMount() {
      this.setState({isMounted: true})
  }
  componentWillUnmount(){
      this.setState({isMounted: false})
  }

callback:

if (this.state.isMounted) {
 this.setState({'time': remainTimeInfo});}

Error: stray '\240' in program

As mentioned in a previous reply, this generally comes when compiling copy pasted code. If you have a bash shell, the following command generally works:

iconv -f utf-8 -t ascii//translit input.c > output.c

Pycharm does not show plot

Just use

plt.show()

This command tells the system to draw the plot in Pycharm.

Example:

plt.imshow(img.reshape((28, 28)))
plt.show()

Mailx send html message

EMAILCC=" -c [email protected],[email protected]"
TURNO_EMAIL="[email protected]"

mailx $EMAILCC -s "$(echo "Status: Control Aplicactivo \nContent-Type: text/html")" $TURNO_EMAIL < tmp.tmp

Error: Cannot pull with rebase: You have unstaged changes

Pulling with rebase is a good practice in general.

However you cannot do that if your index is not clean, i.e. you have made changes that have not been committed.

You can do this to work around, assuming you want to keep your changes:

  1. stash your changes with: git stash
  2. pull from master with rebase
  3. reapply the changes you stashed in (1) with: git stash apply stash@{0} or the simpler git stash pop

Saving binary data as file using JavaScript from a browser

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:

_x000D_
_x000D_
/* 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_
_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

select from one table, insert into another table oracle sql query

You will get useful information from here.

SELECT ticker
INTO quotedb
FROM tickerdb;

Should I check in folder "node_modules" to Git when creating a Node.js app on Heroku?

Scenario 1:

One scenario:

You use a package that gets removed from npm. If you have all the modules in the folder node_modules, then it won't be a problem for you. If you do only have the package name in the package.json, you can't get it anymore.

If a package is less than 24 hours old, you can easily remove it from npm. If it's older than 24 hours old, then you need to contact them.

But:

If you contact support, they will check to see if removing that version of your package would break any other installs. If so, we will not remove it.

read more

So the chances for this are low, but there is scenario 2...


Scenario 2:

An other scenario where this is the case:

You develop an enterprise version of your software or a very important software and write in your package.json:

"dependencies": {
    "studpid-package": "~1.0.1"
}

You use the method function1(x)of that package.

Now the developers of studpid-package rename the method function1(x)to function2(x) and they make a fault... They change the version of their package from 1.0.1 to 1.1.0. That's a problem because when you call npm install the next time, you will accept version 1.1.0 because you used the tilde ("studpid-package": "~1.0.1").

Calling function1(x) can cause errors and problems now.


Pushing the whole node_modules folder (often more than 100 MB) to your repository, will cost you memory space. A few kb (package.json only) compared with hundreds of MB (package.json & node_modules)... Think about it.

You could do it / should think about it if:

  • the software is very important.

  • it costs you money when something fails.

  • you don't trust the npm registry. npm is centralized and could theoretically be shut down.

You don't need to publish the node_modules folder in 99.9% of the cases if:

  • you develop a software just for yourself.

  • you've programmed something and just want to publish the result on GitHub because someone else could maybe be interested in it.


If you don't want the node_modules to be in your repository, just create a .gitignore file and add the line node_modules.

How to convert image into byte array and byte array to base64 String in android?

I wrote the following code to convert an image from sdcard to a Base64 encoded string to send as a JSON object.And it works great:

String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
    fis = new FileInputStream(imagefile);
    } catch (FileNotFoundException e) {
    e.printStackTrace();
}

Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);    
byte[] b = baos.toByteArray(); 
encImage = Base64.encodeToString(b, Base64.DEFAULT);

VBA - how to conditionally skip a for loop iteration

Hi I am also facing this issue and I solve this using below example code

For j = 1 To MyTemplte.Sheets.Count

       If MyTemplte.Sheets(j).Visible = 0 Then
           GoTo DoNothing        
       End If 


'process for this for loop
DoNothing:

Next j 

How to configure heroku application DNS to Godaddy Domain?

The trick is to

  1. create a CNAME for www.myapp.com to myapp.heroku.com
  2. create a 301 redirection from myapp.com to www.myapp.com

Arithmetic overflow error converting numeric to data type numeric

My guess is that you're trying to squeeze a number greater than 99999.99 into your decimal fields. Changing it to (8,3) isn't going to do anything if it's greater than 99999.999 - you need to increase the number of digits before the decimal. You can do this by increasing the precision (which is the total number of digits before and after the decimal). You can leave the scale the same unless you need to alter how many decimal places to store. Try decimal(9,2) or decimal(10,2) or whatever.

You can test this by commenting out the insert #temp and see what numbers the select statement is giving you and see if they are bigger than your column can handle.

Convert Object to JSON string

Also useful is Object.toSource() for debugging purposes, where you want to show the object and its properties for debugging purposes. This is a generic Javascript (not jQuery) function, however it only works in "modern" browsers.

What's the most useful and complete Java cheat sheet?

Here is a great one http://download.oracle.com/javase/1.5.0/docs/api/

These languages are big. You cant expect a cheat sheet to fit on a piece of paper

Python base64 data decode

After decoding, it looks like the data is a repeating structure that's 8 bytes long, or some multiple thereof. It's just binary data though; what it might mean, I have no idea. There are 2064 entries, which means that it could be a list of 2064 8-byte items down to 129 128-byte items.

How to create Python egg file

You are reading the wrong documentation. You want this: https://setuptools.readthedocs.io/en/latest/setuptools.html#develop-deploy-the-project-source-in-development-mode

  1. Creating setup.py is covered in the distutils documentation in Python's standard library documentation here. The main difference (for python eggs) is you import setup from setuptools, not distutils.

  2. Yep. That should be right.

  3. I don't think so. pyc files can be version and platform dependent. You might be able to open the egg (they should just be zip files) and delete .py files leaving .pyc files, but it wouldn't be recommended.

  4. I'm not sure. That might be “Development Mode”. Or are you looking for some “py2exe” or “py2app” mode?

How can I create a dynamically sized array of structs?

This looks like an academic exercise which unfortunately makes it harder since you can't use C++. Basically you have to manage some of the overhead for the allocation and keep track how much memory has been allocated if you need to resize it later. This is where the C++ standard library shines.

For your example, the following code allocates the memory and later resizes it:

// initial size
int count = 100;
words *testWords = (words*) malloc(count * sizeof(words));
// resize the array
count = 76;
testWords = (words*) realloc(testWords, count* sizeof(words));

Keep in mind, in your example you are just allocating a pointer to a char and you still need to allocate the string itself and more importantly to free it at the end. So this code allocates 100 pointers to char and then resizes it to 76, but does not allocate the strings themselves.

I have a suspicion that you actually want to allocate the number of characters in a string which is very similar to the above, but change word to char.

EDIT: Also keep in mind it makes a lot of sense to create functions to perform common tasks and enforce consistency so you don't copy code everywhere. For example, you might have a) allocate the struct, b) assign values to the struct, and c) free the struct. So you might have:

// Allocate a words struct
words* CreateWords(int size);
// Assign a value
void AssignWord(word* dest, char* str);
// Clear a words structs (and possibly internal storage)
void FreeWords(words* w);

EDIT: As far as resizing the structs, it is identical to resizing the char array. However the difference is if you make the struct array bigger, you should probably initialize the new array items to NULL. Likewise, if you make the struct array smaller, you need to cleanup before removing the items -- that is free items that have been allocated (and only the allocated items) before you resize the struct array. This is the primary reason I suggested creating helper functions to help manage this.

// Resize words (must know original and new size if shrinking
// if you need to free internal storage first)
void ResizeWords(words* w, size_t oldsize, size_t newsize);

What are examples of TCP and UDP in real life?

TCP :

Transmission Control Protocol is a connection-oriented protocol, which means that it requires handshaking to set up end-to-end communications. Once a connection is set up, user data may be sent bi-directionally over the connection.

Reliable – Strictly only at transport layer, TCP manages message acknowledgment, retransmission and timeout. Multiple attempts to deliver the message are made. If it gets lost along the way, the server will re-request the lost part. In TCP, there's either no missing data, or, in case of multiple timeouts, the connection is dropped. (This reliability however does not cover application layer, at which a separate acknowledgement flow control is still necessary)

Ordered – If two messages are sent over a connection in sequence, the first message will reach the receiving application first. When data segments arrive in the wrong order, TCP buffers delay the out-of-order data until all data can be properly re-ordered and delivered to the application.

Heavyweight – TCP requires three packets to set up a socket connection, before any user data can be sent. TCP handles reliability and congestion control. Streaming – Data is read as a byte stream, no distinguishing indications are transmitted to signal message (segment) boundaries.

Applications of TCP

World Wide Web, email, remote administration, and file transfer rely on TCP.

UDP :

User Datagram Protocol is a simpler message-based connectionless protocol. Connectionless protocols do not set up a dedicated end-to-end connection. Communication is achieved by transmitting information in one direction from source to destination without verifying the readiness or state of the receiver.

Unreliable – When a UDP message is sent, it cannot be known if it will reach its destination; it could get lost along the way. There is no concept of acknowledgment, retransmission, or timeout.

Not ordered – If two messages are sent to the same recipient, the order in which they arrive cannot be predicted.

Lightweight – There is no ordering of messages, no tracking connections, etc. It is a small transport layer designed on top of IP.

Datagrams – Packets are sent individually and are checked for integrity only if they arrive. Packets have definite boundaries which are honored upon receipt, meaning a read operation at the receiver socket will yield an entire message as it was originally sent. No congestion control – UDP itself does not avoid congestion. Congestion control measures must be implemented at the application level.

Broadcasts – being connectionless, UDP can broadcast - sent packets can be addressed to be receivable by all devices on the subnet.

Multicast – a multicast mode of operation is supported whereby a single datagram packet can be automatically routed without duplication to very large numbers of subscribers.

Applications of UDP

Numerous key Internet applications use UDP, including: the Domain Name System (DNS), where queries must be fast and only consist of a single request followed by a single reply packet, the Simple Network Management Protocol (SNMP), the Routing Information Protocol (RIP) and the Dynamic Host Configuration Protocol (DHCP).

Voice and video traffic is generally transmitted using UDP. Real-time video and audio streaming protocols are designed to handle occasional lost packets, so only slight degradation in quality occurs, rather than large delays if lost packets were retransmitted. Because both TCP and UDP run over the same network, many businesses are finding that a recent increase in UDP traffic from these real-time applications is hindering the performance of applications using TCP, such as point of sale, accounting, and database systems. When TCP detects packet loss, it will throttle back its data rate usage. Since both real-time and business applications are important to businesses, developing quality of service solutions is seen as crucial by some.

Some VPN systems such as OpenVPN may use UDP while implementing reliable connections and error checking at the application level.

Saving and loading objects and using pickle

Always open in binary mode, in this case

file = open("Fruits.obj",'rb')

Show/hide widgets in Flutter programmatically

Flutter now contains a Visibility Widget that you should use to show/hide widgets. The widget can also be used to switch between 2 widgets by changing the replacement.

This widget can achieve any of the states visible, invisible, gone and a lot more.

    Visibility(
      visible: true //Default is true,
      child: Text('Ndini uya uya'),
      //maintainSize: bool. When true this is equivalent to invisible;
      //replacement: Widget. Defaults to Sizedbox.shrink, 0x0
    ),

Using Laravel Homestead: 'no input file specified'

This happens because you need to configure your nginx server properly in order to serve you application. You can do this following this guide, starting in the topic Configure Nginx and the Web Root.

After properly configuring your symbolic link between your /etc/nginx/sites-available and /etc/nginx/sites-enabled you need to make sure your root variable is set to your application's folder path. Set your nginx root from

root /usr/share/nginx/html;

to

/home/vagrant/Projects/ProjectOne/public

Also, you have to place index.php before your html files so php is served before html. Change this

index index.html index.htm;

to this

index index.php index.html index.htm;

After finish your configuration restart your nginx server with

sudo service nginx restart

Your application should be served now.

How to use OAuth2RestTemplate?

You can find examples for writing OAuth clients here:

In your case you can't just use default or base classes for everything, you have a multiple classes Implementing OAuth2ProtectedResourceDetails. The configuration depends of how you configured your OAuth service but assuming from your curl connections I would recommend:

@EnableOAuth2Client
@Configuration
class MyConfig{

    @Value("${oauth.resource:http://localhost:8082}")
    private String baseUrl;
    @Value("${oauth.authorize:http://localhost:8082/oauth/authorize}")
    private String authorizeUrl;
    @Value("${oauth.token:http://localhost:8082/oauth/token}")
    private String tokenUrl;

    @Bean
    protected OAuth2ProtectedResourceDetails resource() {
        ResourceOwnerPasswordResourceDetails resource;
        resource = new ResourceOwnerPasswordResourceDetails();

        List scopes = new ArrayList<String>(2);
        scopes.add("write");
        scopes.add("read");
        resource.setAccessTokenUri(tokenUrl);
        resource.setClientId("restapp");
        resource.setClientSecret("restapp");
        resource.setGrantType("password");
        resource.setScope(scopes);
        resource.setUsername("**USERNAME**");
        resource.setPassword("**PASSWORD**");
        return resource;
    }

    @Bean
    public OAuth2RestOperations restTemplate() {
        AccessTokenRequest atr = new DefaultAccessTokenRequest();
        return new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(atr));
    }
}

@Service
@SuppressWarnings("unchecked")
class MyService {

    @Autowired
    private OAuth2RestOperations restTemplate;

    public MyService() {
        restTemplate.getAccessToken();
    }
}

Do not forget about @EnableOAuth2Client on your config class, also I would suggest to try that the urls you are using are working with curl first, also try to trace it with the debugger because lot of exceptions are just consumed and never printed out due security reasons, so it gets little hard to find where the issue is. You should use logger with debug enabled set. Good luck

I uploaded sample springboot app on github https://github.com/mariubog/oauth-client-sample to depict your situation because I could not find any samples for your scenario .

Error: allowDefinition='MachineToApplication' beyond application level

After deleting Crystal Reports Backup Files from the project folder it is working for me.

How to check if element is visible after scrolling?

I have such a method in my application, but it does not use jQuery:

/* Get the TOP position of a given element. */
function getPositionTop(element){
    var offset = 0;
    while(element) {
        offset += element["offsetTop"];
        element = element.offsetParent;
    }
    return offset;
}

/* Is a given element is visible or not? */
function isElementVisible(eltId) {
    var elt = document.getElementById(eltId);
    if (!elt) {
        // Element not found.
        return false;
    }
    // Get the top and bottom position of the given element.
    var posTop = getPositionTop(elt);
    var posBottom = posTop + elt.offsetHeight;
    // Get the top and bottom position of the *visible* part of the window.
    var visibleTop = document.body.scrollTop;
    var visibleBottom = visibleTop + document.documentElement.offsetHeight;
    return ((posBottom >= visibleTop) && (posTop <= visibleBottom));
}

Edit : This method works well for I.E. (at least version 6). Read the comments for compatibility with FF.

What are public, private and protected in object oriented programming?

They are access modifiers and help us implement Encapsulation (or information hiding). They tell the compiler which other classes should have access to the field or method being defined.

private - Only the current class will have access to the field or method.

protected - Only the current class and subclasses (and sometimes also same-package classes) of this class will have access to the field or method.

public - Any class can refer to the field or call the method.

This assumes these keywords are used as part of a field or method declaration within a class definition.

Finding duplicate values in a SQL table

The most important thing here is to have the fastest function. Also indices of duplicates should be identified. Self join is a good option but to have a faster function it is better to first find rows that have duplicates and then join with original table for finding id of duplicated rows. Finally order by any column except id to have duplicated rows near each other.

SELECT u.*
FROM users AS u
JOIN (SELECT username, email
      FROM users
      GROUP BY username, email
      HAVING COUNT(*)>1) AS w
ON u.username=w.username AND u.email=w.email
ORDER BY u.email;

How to load a resource from WEB-INF directory of a web archive

The problem I had accessing the sqlite db file I created in my java (jersey) server had solely to due with path. Some of the docs say the jdbc connect url should look like "jdbc:sqlite://path-to-file/sample.db". I thought the double-slash was part of a htt protocol-style path and would map properly when deployed, but in actuality, it's an absolute or relative path. So, when I placed the file at the root of the WebContent folder (tomcat project), a uri like this worked "jdbc:sqlite:sample.db".

The one thing that was throwing me was that when I was stepping through the debugger, I received a message that said "opening db: ... permission denied". I thought it was a matter of file system permissions or perhaps sql user permissions. After finding out that SQLite doesn't have the concept of roles/permissions like MySQL, etc, I did eventually change the file permissions before I came to what I believe was the correct solution, but I think it was just a bad message (i.e. permission denied, instead of File not found).

Hope this helps someone.

How to POST form data with Spring RestTemplate?

here is the full program to make a POST rest call using spring's RestTemplate.

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.ituple.common.dto.ServiceResponse;

   public class PostRequestMain {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
        Map map = new HashMap<String, String>();
        map.put("Content-Type", "application/json");

        headers.setAll(map);

        Map req_payload = new HashMap();
        req_payload.put("name", "piyush");

        HttpEntity<?> request = new HttpEntity<>(req_payload, headers);
        String url = "http://localhost:8080/xxx/xxx/";

        ResponseEntity<?> response = new RestTemplate().postForEntity(url, request, String.class);
        ServiceResponse entityResponse = (ServiceResponse) response.getBody();
        System.out.println(entityResponse.getData());
    }

}

Find a commit on GitHub given the commit hash

A URL of the form https://github.com/<owner>/<project>/commit/<hash> will show you the changes introduced in that commit. For example here's a recent bugfix I made to one of my projects on GitHub:

https://github.com/jerith666/git-graph/commit/35e32b6a00dec02ae7d7c45c6b7106779a124685

You can also shorten the hash to any unique prefix, like so:

https://github.com/jerith666/git-graph/commit/35e32b


I know you just asked about GitHub, but for completeness: If you have the repository checked out, from the command line, you can achieve basically the same thing with either of these commands (unique prefixes work here too):

git show 35e32b6a00dec02ae7d7c45c6b7106779a124685
git log -p -1 35e32b6a00dec02ae7d7c45c6b7106779a124685

Note: If you shorten the commit hash too far, the command line gives you a helpful disambiguation message, but GitHub will just return a 404.

Bootstrap 3 modal responsive

You should be able to adjust the width using the .modal-dialog class selector (in conjunction with media queries or whatever strategy you're using for responsive design):

.modal-dialog {
    width: 400px;
}

How do I remove lines between ListViews on Android?

  1. If you want to remove a divider line, use this code:

    android:divider="@null"
    
  2. If you want to add a space instead of a divider line:

    android:divider="@android:color/transparent"
    android:dividerHeight="5dp"
    

So, you can use any drawable or color in the divider attribute.

How to list the tables in a SQLite database file that was opened with ATTACH?

As of the latest versions of SQLite 3 you can issue:

.fullschema

to see all of your create statements.

password for postgres

What's the default superuser username/password for postgres after a new install?:

CAUTION The answer about changing the UNIX password for "postgres" through "$ sudo passwd postgres" is not preferred, and can even be DANGEROUS!

This is why: By default, the UNIX account "postgres" is locked, which means it cannot be logged in using a password. If you use "sudo passwd postgres", the account is immediately unlocked. Worse, if you set the password to something weak, like "postgres", then you are exposed to a great security danger. For example, there are a number of bots out there trying the username/password combo "postgres/postgres" to log into your UNIX system.

What you should do is follow Chris James's answer:

sudo -u postgres psql postgres

# \password postgres

Enter new password: 

To explain it a little bit...

How do I check if a variable is of a certain type (compare two types) in C?

C is statically typed language. You can't declare a function which operate on type A or type B, and you can't declare variable which hold type A or type B. Every variable has an explicitly declared and unchangeable type, and you supposed to use this knowledge.

And when you want to know if void * points to memory representation of float or integer - you have to store this information somewhere else. The language is specifically designed not to care if char * points to something stored as int or char.

How do I open workbook programmatically as read-only?

Check out the language reference:

http://msdn.microsoft.com/en-us/library/aa195811(office.11).aspx

expression.Open(FileName, UpdateLinks, ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, Delimiter, Editable, Notify, Converter, AddToMru, Local, CorruptLoad)

How do I execute multiple SQL Statements in Access' Query Editor?

"I hoped (and still hope) that there is something like my beloved SQL*Plus for Oracle that can execute a file with all kinds of SQL Statements."

If you're looking for a simple program that can import a file and execute the SQL statements in it, take a look at DBWConsole (freeware). I have used it to process DDL scripts (table schema) as well as action queries. It does not return data sets so it's not useful for SELECT queries. It supports single line comments prefixed by -- but not multi-line comments wrapped in /* */. It supports command line parameters.

enter image description here

If you want an interactive UI like Oracle SQL Developer or SSMS for Access then Matthew Lock's reference to WinSQL is what you should try.

Specifying content of an iframe instead of the src attribute to a page

You can use data: URL in the src:

_x000D_
_x000D_
var html = 'Hello from <img src="http://stackoverflow.com/favicon.ico" alt="SO">';_x000D_
var iframe = document.querySelector('iframe');_x000D_
iframe.src = 'data:text/html,' + encodeURIComponent(html);
_x000D_
<iframe></iframe>
_x000D_
_x000D_
_x000D_

Difference between srcdoc=“…” and src=“data:text/html,…” in an iframe.

Convert HTML to data:text/html link using JavaScript.

Oracle Error ORA-06512

The variable pCv is of type VARCHAR2 so when you concat the insert you aren't putting it inside single quotes:

 EXECUTE IMMEDIATE  'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('''||pCv||''', '||pSup||', '||pIdM||')';

Additionally the error ORA-06512 raise when you are trying to insert a value too large in a column. Check the definiton of the table M_pNum_GR and the parameters that you are sending. Just for clarify if you try to insert the value 100 on a NUMERIC(2) field the error will raise.

PHP: Split a string in to an array foreach char

you can convert a string to array with str_split and use foreach

$chars = str_split($str);
foreach($chars as $char){
    // your code
}

FileSystemWatcher Changed event is raised twice

I know this is an old issue, but had the same problem and none of the above solution really did the trick for the problem I was facing. I have created a dictionary which maps the file name with the LastWriteTime. So if the file is not in the dictionary will go ahead with the process other wise check to see when was the last modified time and if is different from what it is in the dictionary run the code.

    Dictionary<string, DateTime> dateTimeDictionary = new Dictionary<string, DateTime>(); 

        private void OnChanged(object source, FileSystemEventArgs e)
            {
                if (!dateTimeDictionary.ContainsKey(e.FullPath) || (dateTimeDictionary.ContainsKey(e.FullPath) && System.IO.File.GetLastWriteTime(e.FullPath) != dateTimeDictionary[e.FullPath]))
                {
                    dateTimeDictionary[e.FullPath] = System.IO.File.GetLastWriteTime(e.FullPath);

                    //your code here
                }
            }

image.onload event and browser cache

As you're generating the image dynamically, set the onload property before the src.

var img = new Image();
img.onload = function () {
   alert("image is loaded");
}
img.src = "img.jpg";

Fiddle - tested on latest Firefox and Chrome releases.

You can also use the answer in this post, which I adapted for a single dynamically generated image:

var img = new Image();
// 'load' event
$(img).on('load', function() {
  alert("image is loaded");
});
img.src = "img.jpg";

Fiddle

Difference between PCDATA and CDATA in DTD

From here (Google is your friend):

In a DTD, PCDATA and CDATA are used to assert something about the allowable content of elements and attributes, respectively. In an element's content model, #PCDATA says that the element contains (may contain) "any old text." (With exceptions as noted below.) In an attribute's declaration, CDATA is one sort of constraint you can put on the attribute's allowable values (other sorts, all mutually exclusive, include ID, IDREF, and NMTOKEN). An attribute whose allowable values are CDATA can (like PCDATA in an element) contain "any old text."

A potentially really confusing issue is that there's another "CDATA," also referred to as marked sections. A marked section is a portion of element (#PCDATA) content delimited with special strings: to close it. If you remember that PCDATA is "parsed character data," a CDATA section is literally the same thing, without the "parsed." Parsers transmit the content of a marked section to downstream applications without hiccupping every time they encounter special characters like < and &. This is useful when you're coding a document that contains lots of those special characters (like scripts and code fragments); it's easier on data entry, and easier on reading, than the corresponding entity reference.

So you can infer that the exception to the "any old text" rule is that PCDATA cannot include any of these unescaped special characters, UNLESS they fall within the scope of a CDATA marked section.

How can I truncate a double to only two decimal places in Java?

Here is the method I use:

double a=3.545555555; // just assigning your decimal to a variable
a=a*100;              // this sets a to 354.555555
a=Math.floor(a);      // this sets a to 354
a=a/100;              // this sets a to 3.54 and thus removing all your 5's

This can also be done:

a=Math.floor(a*100) / 100;

BehaviorSubject vs Observable?

BehaviorSubject

The BehaviorSubject builds on top of the same functionality as our ReplaySubject, subject like, hot, and replays previous value.

The BehaviorSubject adds one more piece of functionality in that you can give the BehaviorSubject an initial value. Let’s go ahead and take a look at that code

import { ReplaySubject } from 'rxjs';

const behaviorSubject = new BehaviorSubject(
  'hello initial value from BehaviorSubject'
);

behaviorSubject.subscribe(v => console.log(v));

behaviorSubject.next('hello again from BehaviorSubject');

Observables

To get started we are going to look at the minimal API to create a regular Observable. There are a couple of ways to create an Observable. The way we will create our Observable is by instantiating the class. Other operators can simplify this, but we will want to compare the instantiation step to our different Observable types

import { Observable } from 'rxjs';

const observable = new Observable(observer => {
  setTimeout(() => observer.next('hello from Observable!'), 1000);
});

observable.subscribe(v => console.log(v));

ActiveRecord: size vs count

As the other answers state:

  • count will perform an SQL COUNT query
  • length will calculate the length of the resulting array
  • size will try to pick the most appropriate of the two to avoid excessive queries

But there is one more thing. We noticed a case where size acts differently to count/lengthaltogether, and I thought I'd share it since it is rare enough to be overlooked.

  • If you use a :counter_cache on a has_many association, size will use the cached count directly, and not make an extra query at all.

    class Image < ActiveRecord::Base
      belongs_to :product, counter_cache: true
    end
    
    class Product < ActiveRecord::Base
      has_many :images
    end
    
    > product = Product.first  # query, load product into memory
    > product.images.size      # no query, reads the :images_count column
    > product.images.count     # query, SQL COUNT
    > product.images.length    # query, loads images into memory
    

This behaviour is documented in the Rails Guides, but I either missed it the first time or forgot about it.

Is it safe to use Project Lombok?

I read some opinions about the Lombok and actually I'm using it in some projects.

Well, in the first contact with Lombok I had a bad impression. After some weeks, I started to like it. But after some months I figure out a lot of tiny problems using it. So, my final impression about Lombok is not so positive.

My reasons to think in this way:

  • IDE plugin dependency. The IDE support for Lombok is through plugins. Even working good in most part of the time, you are always a hostage from this plugins to be maintained in the future releases of the IDEs and even the language version (Java 10+ will accelerate the development of the language). For example, I tried to update from Intellij IDEA 2017.3 to 2018.1 and I couldn't do that because there was some problem on the actual lombok plugin version and I needed to wait the plugin be updated... This also is a problem if you would like to use a more alternative IDE that don't have any Lombok plugin support.
  • 'Find usages' problem.. Using Lombok you don't see the generated getter, setter, constructor, builder methods and etc. So, if you are planning to find out where these methods are being used in your project by your IDE, you can't do this only looking for the class that owns this hidden methods.
  • So easy that the developers don't care to break the encapsulation. I know that it's not really a problem from Lombok. But I saw a bigger tendency from the developers to not control anymore what methods needs to be visible or not. So, many times they are just copying and pasting @Getter @Setter @Builder @AllArgsConstructor @NoArgsConstructor annotations block without thinking what methods the class really need to be exposed.
  • Builder Obssession ©. I invented this name (get off, Martin Fowler). Jokes apart, a Builder is so easy to create that even when a class have only two parameters the developers prefer to use @Builder instead of constructor or a static constructor method. Sometimes they even try to create a Builder inside the lombok Builder, creating weird situations like MyClass.builder().name("Name").build().create().
  • Barriers when refactoring. If you are using, for example, a @AllArgsConstructor and need to add one more parameter on the constructor, the IDE can't help you to add this extra parameter in all places (mostly, tests) that are instantiating the class.
  • Mixing Lombok with concrete methods. You can't use Lombok in all scenarios to create a getter/setter/etc. So, you will see these two approaches mixed in your code. You get used to this after some time, but feels like a hack on the language.

Like another answer said, if you are angry about the Java verbosity and use Lombok to deal with it, try Kotlin.

How do you create a UIImage View Programmatically - Swift

You can use above in one line.

  let imageView = UIImageView(image: UIImage(named: "yourImage.png")!)

image processing to improve tesseract OCR accuracy

What was EXTREMLY HELPFUL to me on this way are the source codes for Capture2Text project. http://sourceforge.net/projects/capture2text/files/Capture2Text/.

BTW: Kudos to it's author for sharing such a painstaking algorithm.

Pay special attention to the file Capture2Text\SourceCode\leptonica_util\leptonica_util.c - that's the essence of image preprocession for this utility.

If you will run the binaries, you can check the image transformation before/after the process in Capture2Text\Output\ folder.

P.S. mentioned solution uses Tesseract for OCR and Leptonica for preprocessing.

Is it possible to set async:false to $.getJSON call

If you just need to await to avoid nesting code:

let json;
await new Promise(done => $.getJSON('https://***', async function (data) {
    json = data;
    done();
}));

Is it possible only to declare a variable without assigning any value in Python?

I'd heartily recommend that you read Other languages have "variables" (I added it as a related link) – in two minutes you'll know that Python has "names", not "variables".

val = None
# ...
if val is None:
   val = any_object

Single line sftp from terminal

sftp supports batch files.

From the man page:

-b batchfile

Batch mode reads a series of commands from an input batchfile instead of stdin.  
Since it lacks user interaction it should be used in conjunction with non-interactive
authentication.  A batchfile of `-' may be used to indicate standard input.  sftp 
will abort if any of the following commands fail: get, put, rename, ln, rm, mkdir, 
chdir, ls, lchdir, chmod, chown, chgrp, lpwd, df, symlink, and lmkdir.  Termination 
on error can be suppressed on a command by command basis by prefixing the command 
with a `-' character (for example, -rm /tmp/blah*).

Pandas/Python: Set value of one column based on value in another column

one way to do this would be to use indexing with .loc.

Example

In the absence of an example dataframe, I'll make one up here:

import numpy as np
import pandas as pd

df = pd.DataFrame({'c1': list('abcdefg')})
df.loc[5, 'c1'] = 'Value'

>>> df
      c1
0      a
1      b
2      c
3      d
4      e
5  Value
6      g

Assuming you wanted to create a new column c2, equivalent to c1 except where c1 is Value, in which case, you would like to assign it to 10:

First, you could create a new column c2, and set it to equivalent as c1, using one of the following two lines (they essentially do the same thing):

df = df.assign(c2 = df['c1'])
# OR:
df['c2'] = df['c1']

Then, find all the indices where c1 is equal to 'Value' using .loc, and assign your desired value in c2 at those indices:

df.loc[df['c1'] == 'Value', 'c2'] = 10

And you end up with this:

>>> df
      c1  c2
0      a   a
1      b   b
2      c   c
3      d   d
4      e   e
5  Value  10
6      g   g

If, as you suggested in your question, you would perhaps sometimes just want to replace the values in the column you already have, rather than create a new column, then just skip the column creation, and do the following:

df['c1'].loc[df['c1'] == 'Value'] = 10
# or:
df.loc[df['c1'] == 'Value', 'c1'] = 10

Giving you:

>>> df
      c1
0      a
1      b
2      c
3      d
4      e
5     10
6      g

Fast way to discover the row count of a table in PostgreSQL

How wide is the text column?

With a GROUP BY there's not much you can do to avoid a data scan (at least an index scan).

I'd recommend:

  1. If possible, changing the schema to remove duplication of text data. This way the count will happen on a narrow foreign key field in the 'many' table.

  2. Alternatively, creating a generated column with a HASH of the text, then GROUP BY the hash column. Again, this is to decrease the workload (scan through a narrow column index)

Edit:

Your original question did not quite match your edit. I'm not sure if you're aware that the COUNT, when used with a GROUP BY, will return the count of items per group and not the count of items in the entire table.

Using generic std::function objects with member functions in one class

Either you need

std::function<void(Foo*)> f = &Foo::doSomething;

so that you can call it on any instance, or you need to bind a specific instance, for example this

std::function<void(void)> f = std::bind(&Foo::doSomething, this);

How to set the UITableView Section title programmatically (iPhone/iPad)?

Use the UITableViewDataSource method

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

SQL - How to find the highest number in a column?

If you are using AUTOINCREMENT, use:

SELECT LAST\_INSERT\_ID();

Assumming that you are using Mysql: http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html

Postgres handles this similarly via the currval(sequence_name) function.

Note that using MAX(ID) is not safe, unless you lock the table, since it's possible (in a simplified case) to have another insert that occurs before you call MAX(ID) and you lose the id of the first insert. The functions above are session based so if another session inserts you still get the ID that you inserted.

LOAD DATA INFILE Error Code : 13

I had a lot of trouble to fix this, there are two things to do :

  • update file /etc/mysql/my.cnf with local-infile =1 at two locations after [mysql] paragraphs (this allows to use LOCAL INFILE sql command).

  • update via sudo gedit /etc/apparmor.d/usr.sbin.mysqld so apparmor will allow you to write into the special files of /var/www/ by adding the lines:

/name of your directory/ r,

/name of your directory/* rw,

The name of your directory can be as /var/www/toto/ (this allows to use the directory where your files are located).

SSRS expression to format two decimal places does not show zeros

You need to make sure that the first numeral to the right of the decimal point is always displayed. In custom format strings, # means display the number if it exists, and 0 means always display something, with 0 as the placeholder.

So in your case you will need something like:

=Format(Fields!CUL1.Value, "#,##0.##")

This saying: display 2 DP if they exist, for the non-zero part always display the lowest part, and use , as the grouping separator.

This is how it looks on your data (I've added a large value as well for reference):

enter image description here

If you're not interested in separating thousands, millions, etc, just use #0.## as Paul-Jan suggested.

The standard docs for Custom Numeric Format Strings are your best reference here.

How do you right-justify text in an HTML textbox?

Using inline styles:

<input type="text" style="text-align: right"/>

or, put it in a style sheet, like so:

<style>
   .rightJustified {
        text-align: right;
    }
</style>

and reference the class:

<input type="text" class="rightJustified"/>

How can I delay a :hover effect in CSS?

For a more aesthetic appearance :) can be:

left:-9999em; 
top:-9999em; 

position for .sNv2 .nav UL can be replaced by z-index:-1 and z-index:1 for .sNv2 .nav LI:Hover UL

Copy rows from one Datatable to another DataTable?

Copy Specified Rows from Table to another

// here dttablenew is a new Table  and dttableOld is table Which having the data 

dttableNew  = dttableOld.Clone();  

foreach (DataRow drtableOld in dttableOld.Rows)
{
   if (/*put some Condition */)
   {
      dtTableNew.ImportRow(drtableOld);
   }
}

SQL Server "AFTER INSERT" trigger doesn't see the just-inserted row

UPDATE: DELETE from a trigger works on both MSSql 7 and MSSql 2008.

I'm no relational guru, nor a SQL standards wonk. However - contrary to the accepted answer - MSSQL deals just fine with both recursive and nested trigger evaluation. I don't know about other RDBMSs.

The relevant options are 'recursive triggers' and 'nested triggers'. Nested triggers are limited to 32 levels, and default to 1. Recursive triggers are off by default, and there's no talk of a limit - but frankly, I've never turned them on, so I don't know what happens with the inevitable stack overflow. I suspect MSSQL would just kill your spid (or there is a recursive limit).

Of course, that just shows that the accepted answer has the wrong reason, not that it's incorrect. However, prior to INSTEAD OF triggers, I recall writing ON INSERT triggers that would merrily UPDATE the just inserted rows. This all worked fine, and as expected.

A quick test of DELETEing the just inserted row also works:

 CREATE TABLE Test ( Id int IDENTITY(1,1), Column1 varchar(10) )
 GO

 CREATE TRIGGER trTest ON Test 
 FOR INSERT 
 AS
    SET NOCOUNT ON
    DELETE FROM Test WHERE Column1 = 'ABCDEF'
 GO

 INSERT INTO Test (Column1) VALUES ('ABCDEF')
 --SCOPE_IDENTITY() should be the same, but doesn't exist in SQL 7
 PRINT @@IDENTITY --Will print 1. Run it again, and it'll print 2, 3, etc.
 GO

 SELECT * FROM Test --No rows
 GO

You have something else going on here.

What does it mean when Statement.executeUpdate() returns -1?

So 4 years later, Microsoft has open sourced their JDBC driver on Github. I got a notification about this question today, and went and had a look, and I believe I have found the culprit here, mssql-jdbc/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerStatement.java:1713.

Basically, the driver tries to understand what SQL Server sends back if it is not a definite result set. According to the comments, it goes like this:

  1. Check for errors first. (ln 1669)

  2. Not an error. Is it a result set? (ln 1680)

  3. Not an error or a result set. Maybe a result from a T-SQL statement? That is, one of the following:

    • a positive count of the number of rows affected (from INSERT, UPDATE, or DELETE),
    • a zero indicating no rows affected, or the statement was DDL, or
    • a -1 indicating the statement succeeded, but there is no update count information available (translates to Statement.SUCCESS_NO_INFO in batch update count arrays). (ln 1706)
  4. None of the above. Last chance here... Going into the parser above, we know moreResults was initially true. If we come out with moreResults false, the we hit a DONE token (either DONE (FINAL) or DONE (RPC in batch)) that indicates that the batch succeeded overall, but that there is no information on individual statements' update counts. This is similar to the last case above, except that there is no update count. That is: we have a successful result (return true), but we have no other information about it (updateCount = -1). (ln 1693)

  5. Only way to get here (moreResults is still true, but no apparent results of any kind) is if the TDSParser didn't actually parse anything. That is, we are at EOF in the response. In that case, there truly are no more results. We're done. (ln 1717)

(Emphasis mine)

So you guys were right in the end. SQL simply can't tell how many rows are affected, and defaults to -1. :)

Display all views on oracle database

Open a new worksheet on the related instance (Alt-F10) and run the following query

SELECT view_name, owner
FROM sys.all_views 
ORDER BY owner, view_name

ERROR:'keytool' is not recognized as an internal or external command, operable program or batch file

My case is, it doesn't work wherever I call it, no matter I path the file or not, if I open it with powershell.

but it works if I open it with cmd.

Identifying Exception Type in a handler Catch Block

you can add some extra information to your exception in your class and then when you catch the exception you can control your custom information to identify your exception

this.Data["mykey"]="keyvalue"; //you can add any type of data if you want 

and then you can get your value

string mystr = (string) err.Data["mykey"];

like that for more information: http://msdn.microsoft.com/en-us/library/system.exception.data.aspx

Allow access permission to write in Program Files of Windows 7

Your program has to run with Administrative Rights. You can't do this automatically with code, but you can request the user (in code) to elevate the rights of your program while it's running. There's a wiki on how to do this. Alternatively, any program can be run as administrator by right-clicking its icon and clicking "Run as administrator".

However, I wouldn't suggest doing this. It would be better to use something like this:

Environment.GetFolderPath(SpecialFolder.ApplicationData);

to get the AppData Folder path and create a folder there for your app. Then put the temp files there.

How can I use Helvetica Neue Condensed Bold in CSS?

After a lot of fiddling, got it working (only tested in Webkit) using:

font-family: "HelveticaNeue-CondensedBold";

font-stretch was dropped between CSS2 and 2.1, though is back in CSS3, but is only supported in IE9 (never thought I'd be able to say that about any CSS prop!)

This works because I'm using the postscript name (find the font in Font Book, hit cmd+I), which is non-standard behaviour. It's probably worth using:

font-family: "HelveticaNeue-CondensedBold", "Helvetica Neue";

As a fallback, else other browsers might default to serif if they can't work it out.

Demo: http://jsfiddle.net/ndFTL/12/

Where is the documentation for the values() method of Enum?

You can't see this method in javadoc because it's added by the compiler.

Documented in three places :

The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type.

  • Enum.valueOf class
    (The special implicit values method is mentioned in description of valueOf method)

All the constants of an enum type can be obtained by calling the implicit public static T[] values() method of that type.

The values function simply list all values of the enumeration.

Getting data from selected datagridview row and which event?

First take a label. set its visibility to false, then on the DataGridView_CellClick event write this

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    label.Text=dataGridView1.Rows[e.RowIndex].Cells["Your Coloumn name"].Value.ToString();
    // then perform your select statement according to that label.
}
//try it it might work for you

Generate HTML table from 2D JavaScript array

One-liner using es6 reduce

function makeTableHTML(ar) {
  return `<table>${ar.reduce((c, o) => c += `<tr>${o.reduce((c, d) => (c += `<td>${d}</td>`), '')}</tr>`, '')}</table>`
}

dd: How to calculate optimal blocksize?

  • for better performace use the biggest blocksize you RAM can accomodate (will send less I/O calls to the OS)
  • for better accurancy and data recovery set the blocksize to the native sector size of the input

As dd copies data with the conv=noerror,sync option, any errors it encounters will result in the remainder of the block being replaced with zero-bytes. Larger block sizes will copy more quickly, but each time an error is encountered the remainder of the block is ignored.

source

Find Process Name by its Process ID

Using only "native" Windows utilities, try the following, where "516" is the process ID that you want the image name for:

for /f "delims=," %a in ( 'tasklist /fi "PID eq 516" /nh /fo:csv' ) do ( echo %~a )
for /f %a in ( 'tasklist /fi "PID eq 516" ^| findstr "516"' ) do ( echo %a )

Or you could use wmic (the Windows Management Instrumentation Command-line tool) and get the full path to the executable:

wmic process where processId=516 get name
wmic process where processId=516 get ExecutablePath

Or you could download Microsoft PsTools, or specifically download just the pslist utility, and use PsList:

for /f %a in ( 'pslist 516 ^| findstr "516"' ) do ( echo %a )

Provide schema while reading csv file as a dataframe

This is one of option where we can pass the column names to the dataframe while loading CSV.

import pandas
    names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'class']
    dataset = pandas.read_csv("C:/Users/NS00606317/Downloads/Iris.csv", names=names, header=0)
print(dataset.head(10))

Output

    sepal-length  sepal-width  petal-length  petal-width        class
1            5.1          3.5           1.4          0.2  Iris-setosa
2            4.9          3.0           1.4          0.2  Iris-setosa
3            4.7          3.2           1.3          0.2  Iris-setosa
4            4.6          3.1           1.5          0.2  Iris-setosa
5            5.0          3.6           1.4          0.2  Iris-setosa
6            5.4          3.9           1.7          0.4  Iris-setosa
7            4.6          3.4           1.4          0.3  Iris-setosa
8            5.0          3.4           1.5          0.2  Iris-setosa
9            4.4          2.9           1.4          0.2  Iris-setosa
10           4.9          3.1           1.5          0.1  Iris-setosa

Oracle SqlDeveloper JDK path

On Windows,Close all the SQL Developer windows. Then You need to completely delete the SQL Developer and sqldeveloper folders located in user/AppData/Roaming. Finally, run the program, you will be prompted for new JDK.

Note that AppData is a hidden folder.

Spring boot - configure EntityManager

Hmmm you can find lot of examples for configuring spring framework. Anyways here is a sample

@Configuration
@Import({PersistenceConfig.class})
@ComponentScan(basePackageClasses = { 
    ServiceMarker.class,
    RepositoryMarker.class }
)
public class AppConfig {

}

PersistenceConfig

@Configuration
@PropertySource(value = { "classpath:database/jdbc.properties" })
@EnableTransactionManagement
public class PersistenceConfig {

    private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
    private static final String PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH = "hibernate.max_fetch_depth";
    private static final String PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE = "hibernate.jdbc.fetch_size";
    private static final String PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE = "hibernate.jdbc.batch_size";
    private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
    private static final String[] ENTITYMANAGER_PACKAGES_TO_SCAN = {"a.b.c.entities", "a.b.c.converters"};

    @Autowired
    private Environment env;

     @Bean(destroyMethod = "close")
     public DataSource dataSource() {
         BasicDataSource dataSource = new BasicDataSource();
         dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
         dataSource.setUrl(env.getProperty("jdbc.url"));
         dataSource.setUsername(env.getProperty("jdbc.username"));
         dataSource.setPassword(env.getProperty("jdbc.password"));
         return dataSource;
     }

     @Bean
     public JpaTransactionManager jpaTransactionManager() {
         JpaTransactionManager transactionManager = new JpaTransactionManager();
         transactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject());
         return transactionManager;
     }

    private HibernateJpaVendorAdapter vendorAdaptor() {
         HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
         vendorAdapter.setShowSql(true);
         return vendorAdapter;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {

         LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
         entityManagerFactoryBean.setJpaVendorAdapter(vendorAdaptor());
         entityManagerFactoryBean.setDataSource(dataSource());
         entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
         entityManagerFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);             
         entityManagerFactoryBean.setJpaProperties(jpaHibernateProperties());

         return entityManagerFactoryBean;
     }

     private Properties jpaHibernateProperties() {

         Properties properties = new Properties();

         properties.put(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH, env.getProperty(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH));
         properties.put(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE));
         properties.put(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE));
         properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));

         properties.put(AvailableSettings.SCHEMA_GEN_DATABASE_ACTION, "none");
         properties.put(AvailableSettings.USE_CLASS_ENHANCER, "false");      
         return properties;       
     }

}

Main

public static void main(String[] args) { 
    try (GenericApplicationContext springContext = new AnnotationConfigApplicationContext(AppConfig.class)) {
        MyService myService = springContext.getBean(MyServiceImpl.class);
        try {
            myService.handleProcess(fromDate, toDate);
        } catch (Exception e) {
            logger.error("Exception occurs", e);
            myService.handleException(fromDate, toDate, e);
        }
    } catch (Exception e) {
        logger.error("Exception occurs in loading Spring context: ", e);
    }
}

MyService

@Service
public class MyServiceImpl implements MyService {

    @Inject
    private MyDao myDao;

    @Override
    public void handleProcess(String fromDate, String toDate) {
        List<Student> myList = myDao.select(fromDate, toDate);
    }
}

MyDaoImpl

@Repository
@Transactional
public class MyDaoImpl implements MyDao {

    @PersistenceContext
    private EntityManager entityManager;

    public Student select(String fromDate, String toDate){

        TypedQuery<Student> query = entityManager.createNamedQuery("Student.findByKey", Student.class);
        query.setParameter("fromDate", fromDate);
        query.setParameter("toDate", toDate);
        List<Student> list = query.getResultList();
        return CollectionUtils.isEmpty(list) ? null : list;
    }

}

Assuming maven project: Properties file should be in src/main/resources/database folder

jdbc.properties file

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=your db url
jdbc.username=your Username
jdbc.password=Your password

hibernate.max_fetch_depth = 3
hibernate.jdbc.fetch_size = 50
hibernate.jdbc.batch_size = 10
hibernate.show_sql = true

ServiceMarker and RepositoryMarker are just empty interfaces in your service or repository impl package.

Let's say you have package name a.b.c.service.impl. MyServiceImpl is in this package and so is ServiceMarker.

public interface ServiceMarker {

}

Same for repository marker. Let's say you have a.b.c.repository.impl or a.b.c.dao.impl package name. Then MyDaoImpl is in this this package and also Repositorymarker

public interface RepositoryMarker {

}

a.b.c.entities.Student

//dummy class and dummy query
@Entity
@NamedQueries({
@NamedQuery(name="Student.findByKey", query="select s from Student s where s.fromDate=:fromDate" and s.toDate = :toDate)
})
public class Student implements Serializable {

    private LocalDateTime fromDate;
    private LocalDateTime toDate;

    //getters setters

}

a.b.c.converters

@Converter(autoApply = true)
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, Timestamp> {

    @Override
    public Timestamp convertToDatabaseColumn(LocalDateTime dateTime) {

        if (dateTime == null) {
            return null;
        }
        return Timestamp.valueOf(dateTime);
    }

    @Override
    public LocalDateTime convertToEntityAttribute(Timestamp timestamp) {

        if (timestamp == null) {
            return null;
        }    
        return timestamp.toLocalDateTime();
    }
}

pom.xml

<properties>
    <java-version>1.8</java-version>
    <org.springframework-version>4.2.1.RELEASE</org.springframework-version>
    <hibernate-entitymanager.version>5.0.2.Final</hibernate-entitymanager.version>
    <commons-dbcp2.version>2.1.1</commons-dbcp2.version>
    <mysql-connector-java.version>5.1.36</mysql-connector-java.version>
     <junit.version>4.12</junit.version> 
</properties>

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
        <scope>test</scope>
    </dependency>

    <!-- Spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
        <groupId>javax.inject</groupId>
        <artifactId>javax.inject</artifactId>
        <version>1</version>
        <scope>compile</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>${hibernate-entitymanager.version}</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysql-connector-java.version}</version>
    </dependency>

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-dbcp2</artifactId>
        <version>${commons-dbcp2.version}</version>
    </dependency>
</dependencies>

<build>
     <finalName>${project.artifactId}</finalName>
     <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.3</version>
            <configuration>
                <source>${java-version}</source>
                <target>${java-version}</target>
                <compilerArgument>-Xlint:all</compilerArgument>
                <showWarnings>true</showWarnings>
                <showDeprecation>true</showDeprecation>
            </configuration>
        </plugin>
     </plugins>
</build>

Hope it helps. Thanks

php create object without class

you can always use new stdClass(). Example code:

   $object = new stdClass();
   $object->property = 'Here we go';

   var_dump($object);
   /*
   outputs:

   object(stdClass)#2 (1) {
      ["property"]=>
      string(10) "Here we go"
    }
   */

Also as of PHP 5.4 you can get same output with:

$object = (object) ['property' => 'Here we go'];

How to Increase Import Size Limit in phpMyAdmin

You can increase the limit from php.ini file. If you are using windows, you will the get php.ini file from C:\xampp\php directory.

Now changes the following lines & set your limit

post_max_size = 128M
upload_max_filesize = 128M 
max_execution_time = 2000
max_input_time = 3000
memory_limit = 256M

How to convert BigDecimal to Double in Java?

You can convert BigDecimal to double using .doubleValue(). But believe me, don't use it if you have currency manipulations. It should always be performed on BigDecimal objects directly. Precision loss in these calculations are big time problems in currency related calculations.

ValueError: Length of values does not match length of index | Pandas DataFrame.unique()

The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:

A data frame of four rows:

df = pd.DataFrame({'A': [1,2,3,4]})

Now trying to assign a list/array of two elements to it:

df['B'] = [3,4]   # or df['B'] = np.array([3,4])

Both errors out:

ValueError: Length of values does not match length of index

Because the data frame has four rows but the list and array has only two elements.

Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:

df['B'] = pd.Series([3,4])

df
#   A     B
#0  1   3.0
#1  2   4.0
#2  3   NaN          # NaN because the value at index 2 and 3 doesn't exist in the Series
#3  4   NaN

For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:

df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))

#   A     B
#0  1   1.0
#1  2   5.0
#2  7   9.0
#3  8   NaN

What is git tag, How to create tags & How to checkout git remote tag(s)

Let's start by explaining what a tag in git is

enter image description here

A tag is used to label and mark a specific commit in the history.
It is usually used to mark release points (eg. v1.0, etc.).

Although a tag may appear similar to a branch, a tag, however, does not change. It points directly to a specific commit in the history and will not change unless explicitly updated.

enter image description here


You will not be able to checkout the tags if it's not locally in your repository so first, you have to fetch the tags to your local repository.

First, make sure that the tag exists locally by doing

# --all will fetch all the remotes.
# --tags will fetch all tags as well
$ git fetch --all --tags --prune

Then check out the tag by running

$ git checkout tags/<tag_name> -b <branch_name>

Instead of origin use the tags/ prefix.


In this sample you have 2 tags version 1.0 & version 1.1 you can check them out with any of the following:

$ git checkout A  ...
$ git checkout version 1.0  ...
$ git checkout tags/version 1.0  ...

All of the above will do the same since the tag is only a pointer to a given commit.

enter image description here
origin: https://backlog.com/git-tutorial/img/post/stepup/capture_stepup4_1_1.png


How to see the list of all tags?

# list all tags
$ git tag

# list all tags with given pattern ex: v-
$ git tag --list 'v-*'

How to create tags?

There are 2 ways to create a tag:

# lightweight tag 
$ git tag 

# annotated tag
$ git tag -a

The difference between the 2 is that when creating an annotated tag you can add metadata as you have in a git commit:
name, e-mail, date, comment & signature

enter image description here

How to delete tags?

Delete a local tag

$ git tag -d <tag_name>
Deleted tag <tag_name> (was 000000)

Note: If you try to delete a non existig Git tag, there will be see the following error:

$ git tag -d <tag_name>
error: tag '<tag_name>' not found.

Delete remote tags

# Delete a tag from the server with push tags
$ git push --delete origin <tag name>

How to clone a specific tag?

In order to grab the content of a given tag, you can use the checkout command. As explained above tags are like any other commits so we can use checkout and instead of using the SHA-1 simply replacing it with the tag_name

Option 1:

# Update the local git repo with the latest tags from all remotes
$ git fetch --all

# checkout the specific tag
$ git checkout tags/<tag> -b <branch>

Option 2:

Using the clone command

Since git supports shallow clone by adding the --branch to the clone command we can use the tag name instead of the branch name. Git knows how to "translate" the given SHA-1 to the relevant commit

# Clone a specific tag name using git clone 
$ git clone <url> --branch=<tag_name>

git clone --branch=

--branch can also take tags and detaches the HEAD at that commit in the resulting repository.


How to push tags?

git push --tags

To push all tags:

# Push all tags
$ git push --tags 

Using the refs/tags instead of just specifying the <tagname>.

Why?

  • It's recommended to use refs/tags since sometimes tags can have the same name as your branches and a simple git push will push the branch instead of the tag

To push annotated tags and current history chain tags use:

git push --follow-tags

This flag --follow-tags pushes both commits and only tags that are both:

  • Annotated tags (so you can skip local/temp build tags)
  • Reachable tags (an ancestor) from the current branch (located on the history)

enter image description here

From Git 2.4 you can set it using configuration

$ git config --global push.followTags true

Cheatsheet: enter image description here


Simple Deadlock Examples

package test.concurrent;
public class DeadLockTest {
   private static long sleepMillis;
   private final Object lock1 = new Object();
   private final Object lock2 = new Object();

   public static void main(String[] args) {
       sleepMillis = Long.parseLong(args[0]);
       DeadLockTest test = new DeadLockTest();
       test.doTest();
   }

   private void doTest() {
       Thread t1 = new Thread(new Runnable() {
           public void run() {
               lock12();
           }
       });
       Thread t2 = new Thread(new Runnable() {
           public void run() {
               lock21();
           }
       });
       t1.start();
       t2.start();
   }

   private void lock12() {
       synchronized (lock1) {
           sleep();
           synchronized (lock2) {
               sleep();
           }
       }
   }

   private void lock21() {
       synchronized (lock2) {
           sleep();
           synchronized (lock1) {
               sleep();
           }
       }
   }

   private void sleep() {
       try {
           Thread.sleep(sleepMillis);
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
   }
}
To run the deadlock test with sleep time 1 millisecond:
java -cp . test.concurrent.DeadLockTest 1

Importing .py files in Google Colab

Below are the steps that worked for me

  1. Mount your google drive in google colab

    from google.colab import drive drive.mount('/content/drive')

  2. Insert the directory

    import sys sys.path.insert(0,’/content/drive/My Drive/ColabNotebooks’)

  3. check the current directory path

    %cd drive/MyDrive/ColabNotebooks %pwd

  4. Import your module or file

    import my_module

  5. If you get the following error 'Name Null is not defined' then do the following

    5.1 Download my_module.ipynb from colab as my_module.py file (file->Download .py)

    5.2 Upload the *.py file to drive/MyDrive/ColabNotebooks in Google drive

    5.3 import my_module will work now

Reference: https://medium.com/analytics-vidhya/importing-your-own-python-module-or-python-file-into-colab-3e365f0a35ec

https://github.com/googlecolab/colabtools/issues/1358

How do you assert that a certain exception is thrown in JUnit 4 tests?

Additionally to what NamShubWriter has said, make sure that:

  • The ExpectedException instance is public (Related Question)
  • The ExpectedException isn't instantiated in say, the @Before method. This post clearly explains all the intricacies of JUnit's order of execution.

Do not do this:

@Rule    
public ExpectedException expectedException;

@Before
public void setup()
{
    expectedException = ExpectedException.none();
}

Finally, this blog post clearly illustrates how to assert that a certain exception is thrown.

How to get URL of current page in PHP

The other answers are correct. However, a quick note: if you're looking to grab the stuff after the ? in a URI, you should use the $_GET[] array.

Total Number of Row Resultset getRow Method

One better way would be to use SELECT COUNT statement of SQL.

Just when you need the count of number of rows returned, execute another query returning the exact number of result of that query.

 try
{
   Conn=ConnectionODBC.getConnection();
   Statement stmt = Conn.createStatement();        
    String sqlStmt = sql;        
    String sqlrow = SELECT COUNT(*) from (sql) rowquery;
    String total = stmt.executeQuery(sqlrow);
    int rowcount = total.getInt(1);
    }

How do you force a CIFS connection to unmount

I use lazy unmount: umount -l (that's a lowercase L)

Lazy unmount. Detach the filesystem from the filesystem hierarchy now, and cleanup all references to the filesystem as soon as it is not busy anymore. (Requires kernel 2.4.11 or later.)

Integer to hex string in C++

Use <iomanip>'s std::hex. If you print, just send it to std::cout, if not, then use std::stringstream

std::stringstream stream;
stream << std::hex << your_int;
std::string result( stream.str() );

You can prepend the first << with << "0x" or whatever you like if you wish.

Other manips of interest are std::oct (octal) and std::dec (back to decimal).

One problem you may encounter is the fact that this produces the exact amount of digits needed to represent it. You may use setfill and setw this to circumvent the problem:

stream << std::setfill ('0') << std::setw(sizeof(your_type)*2) 
       << std::hex << your_int;

So finally, I'd suggest such a function:

template< typename T >
std::string int_to_hex( T i )
{
  std::stringstream stream;
  stream << "0x" 
         << std::setfill ('0') << std::setw(sizeof(T)*2) 
         << std::hex << i;
  return stream.str();
}

How can I convert a string to a number in Perl?

Google lead me here while searching on the same question phill asked (sorting floats) so I figured it would be worth posting the answer despite the thread being kind of old. I'm new to perl and am still getting my head wrapped around it but brian d foy's statement "Perl cares more about the verbs than it does the nouns." above really hits the nail on the head. You don't need to convert the strings to floats before applying the sort. You need to tell the sort to sort the values as numbers and not strings. i.e.

my @foo = ('1.2', '3.4', '2.1', '4.6');
my @foo_sort = sort {$a <=> $b} @foo;

See http://perldoc.perl.org/functions/sort.html for more details on sort

How to convert / cast long to String?

String longString = new String(""+long);

or

String longString = new Long(datelong).toString();

Is there an opposite of include? for Ruby Arrays?

module Enumerable
  def does_not_include?(item)
    !include?(item)
  end
end

Ok, but seriously, the unless works fine.

How to get a list of installed Jenkins plugins with name and version pair

These days I use the same approach as the answer described by @Behe below instead, updated link: https://stackoverflow.com/a/35292719/3423146 (old link: https://stackoverflow.com/a/35292719/1597808)


You can use the API in combination with depth, XPath, and wrapper arguments.

The following will query the API of the pluginManager to list all plugins installed, but only to return their shortName and version attributes. You can of course retrieve additional fields by adding '|' to the end of the XPath parameter and specifying the pattern to identify the node.

wget http://<jenkins>/pluginManager/api/xml?depth=1&xpath=/*/*/shortName|/*/*/version&wrapper=plugins

The wrapper argument is required in this case, because it's returning more than one node as part of the result, both in that it is matching multiple fields with the XPath and multiple plugin nodes.

It's probably useful to use the following URL in a browser to see what information on the plugins is available and then decide what you want to limit using XPath:

http://<jenkins>/pluginManager/api/xml?depth=1

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

I came here with the same Error, though one with a different origin.

It is caused by unsupported float index in 1.12.0 and newer numpy versions even if the code should be considered as valid.

An int type is expected, not a np.float64

Solution: Try to install numpy 1.11.0

sudo pip install -U numpy==1.11.0.

Using variables inside strings

In C# 6 you can use string interpolation:

string name = "John";
string result = $"Hello {name}";

The syntax highlighting for this in Visual Studio makes it highly readable and all of the tokens are checked.

Usage of MySQL's "IF EXISTS"

I found the example RichardTheKiwi quite informative.

Just to offer another approach if you're looking for something like IF EXISTS (SELECT 1 ..) THEN ...

-- what I might write in MSSQL

IF EXISTS (SELECT 1 FROM Table WHERE FieldValue='')
BEGIN
    SELECT TableID FROM Table WHERE FieldValue=''
END
ELSE
BEGIN
    INSERT INTO TABLE(FieldValue) VALUES('')
    SELECT SCOPE_IDENTITY() AS TableID
END

-- rewritten for MySQL

IF (SELECT 1 = 1 FROM Table WHERE FieldValue='') THEN
BEGIN
    SELECT TableID FROM Table WHERE FieldValue='';
END;
ELSE
BEGIN
    INSERT INTO Table (FieldValue) VALUES('');
    SELECT LAST_INSERT_ID() AS TableID;
END;
END IF;

How to get values and keys from HashMap?

With java8 streaming API:

List values = map.entrySet().stream().map(Map.Entry::getValue).collect(Collectors.toList());

How to get first 5 characters from string

Use substr():

$result = substr($myStr, 0, 5);

Can I invoke an instance method on a Ruby module without including it?

A. In case you, always want to call them in a "qualified", standalone way (UsefulThings.get_file), then just make them static as others pointed out,

module UsefulThings
  def self.get_file; ...
  def self.delete_file; ...

  def self.format_text(x); ...

  # Or.. make all of the "static"
  class << self
     def write_file; ...
     def commit_file; ...
  end

end

B. If you still want to keep the mixin approach in same cases, as well the one-off standalone invocation, you can have a one-liner module that extends itself with the mixin:

module UsefulThingsMixin
  def get_file; ...
  def delete_file; ...

  def format_text(x); ...
end

module UsefulThings
  extend UsefulThingsMixin
end

So both works then:

  UsefulThings.get_file()       # one off

   class MyUser
      include UsefulThingsMixin  
      def f
         format_text             # all useful things available directly
      end
   end 

IMHO it's cleaner than module_function for every single method - in case want all of them.

Parsing time string in Python

In [117]: datetime.datetime.strptime?
Type:           builtin_function_or_method
Base Class:     <type 'builtin_function_or_method'>
String Form:    <built-in method strptime of type object at 0x9a2520>
Namespace:      Interactive
Docstring:
    string, format -> new datetime parsed from a string (like time.strptime()).

How to make <label> and <input> appear on the same line on an HTML form?

_x000D_
_x000D_
#form {_x000D_
    background-color: #FFF;_x000D_
    height: 600px;_x000D_
    width: 600px;_x000D_
    margin-right: auto;_x000D_
    margin-left: auto;_x000D_
    margin-top: 0px;_x000D_
    border-top-left-radius: 10px;_x000D_
    border-top-right-radius: 10px;_x000D_
    padding: 0px;_x000D_
    text-align:center;_x000D_
}_x000D_
label {_x000D_
    font-family: Georgia, "Times New Roman", Times, serif;_x000D_
    font-size: 18px;_x000D_
    color: #333;_x000D_
    height: 20px;_x000D_
    width: 200px;_x000D_
    margin-top: 10px;_x000D_
    margin-left: 10px;_x000D_
    text-align: right;_x000D_
    margin-right:15px;_x000D_
    float:left;_x000D_
}_x000D_
input {_x000D_
    height: 20px;_x000D_
    width: 300px;_x000D_
    border: 1px solid #000;_x000D_
    margin-top: 10px;_x000D_
}
_x000D_
<div id="form">_x000D_
    <form action="" method="post" name="registration" class="register">_x000D_
        <fieldset>_x000D_
            <div class="form-group">_x000D_
                <label for="Student">Name:</label>_x000D_
                <input name="Student" />_x000D_
            </div>_x000D_
            <div class="form-group">_x000D_
                <label for="Matric_no">Matric number:</label>_x000D_
                <input name="Matric_no" />_x000D_
            </div>_x000D_
            <div class="form-group">_x000D_
                <label for="Email">Email:</label>_x000D_
                <input name="Email" />_x000D_
            </div>_x000D_
            <div class="form-group">_x000D_
                <label for="Username">Username:</label>_x000D_
                <input name="Username" />_x000D_
            </div>_x000D_
            <div class="form-group">_x000D_
                <label for="Password">Password:</label>_x000D_
                <input name="Password" type="password" />_x000D_
            </div>_x000D_
            <input name="regbutton" type="button" class="button" value="Register" />_x000D_
        </fieldset>_x000D_
    </form>_x000D_
</div>
_x000D_
_x000D_
_x000D_

upgade python version using pip

Basically, pip comes with python itself.Therefore it carries no meaning for using pip itself to install or upgrade python. Thus,try to install python through installer itself,visit the site "https://www.python.org/downloads/" for more help. Thank you.

Get data from file input in JQuery

input element, of type file

<input id="fileInput" type="file" />

On your input change use the FileReader object and read your input file property:

$('#fileInput').on('change', function () {
    var fileReader = new FileReader();
    fileReader.onload = function () {
      var data = fileReader.result;  // data <-- in this var you have the file data in Base64 format
    };
    fileReader.readAsDataURL($('#fileInput').prop('files')[0]);
});

FileReader will load your file and in fileReader.result you have the file data in Base64 format (also the file content-type (MIME), text/plain, image/jpg, etc)

Why is HttpContext.Current null?

In IIS7 with integrated mode, Current is not available in Application_Start. There is a similar thread here.

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

How do I iterate over an NSArray?

The three ways are:

        //NSArray
    NSArray *arrData = @[@1,@2,@3,@4];

    // 1.Classical
    for (int i=0; i< [arrData count]; i++){
        NSLog(@"[%d]:%@",i,arrData[i]);
    }

    // 2.Fast iteration
    for (id element in arrData){
        NSLog(@"%@",element);
    }

    // 3.Blocks
    [arrData enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
         NSLog(@"[%lu]:%@",idx,obj);
         // Set stop to YES in case you want to break the iteration
    }];
  1. Is the fastest way in execution, and 3. with autocompletion forget about writing iteration envelope.

Dynamically load a JavaScript file

I used a much less complicated version recently with jQuery:

<script src="scripts/jquery.js"></script>
<script>
  var js = ["scripts/jquery.dimensions.js", "scripts/shadedborder.js", "scripts/jqmodal.js", "scripts/main.js"];
  var $head = $("head");
  for (var i = 0; i < js.length; i++) {
    $head.append("<script src=\"" + js[i] + "\"></scr" + "ipt>");
  }
</script>

It worked great in every browser I tested it in: IE6/7, Firefox, Safari, Opera.

Update: jQuery-less version:

<script>
  var js = ["scripts/jquery.dimensions.js", "scripts/shadedborder.js", "scripts/jqmodal.js", "scripts/main.js"];
  for (var i = 0, l = js.length; i < l; i++) {
    document.getElementsByTagName("head")[0].innerHTML += ("<script src=\"" + js[i] + "\"></scr" + "ipt>");
  }
</script>

Xampp MySQL not starting - "Attempting to start MySQL service..."

One of many reasons is xampp cannot start MySQL service by itself. Everything you need to do is run mySQL service manually.

First, make sure that 'mysqld.exe' is not running, if have, end it. (go to Task Manager > Progresses Tab > right click 'mysqld.exe' > end task)

Open your services.msc by Run (press 'Window + R') > services.msc or 0n your XAMPP ControlPanel, click 'Services' button. Find 'MySQL' service, right click and run it.

java.util.Date and getYear()

Year.now()

There's an easier way to use the java.time library in Java 8+. The expression:

java.time.Year.now().getValue()

returns the current year as a four-digit int, using your default time zone. There are lots of options for different time ZoneIds, Calendars and Clocks, but I think this is what you will want most of the time. If you want the code to look cleaner (and don't need any other java.time.*.now() functions), put:

import static java.time.Year.now;

at the top of your file, and call:

now().getValue()

as needed.

org.springframework.web.client.HttpClientErrorException: 400 Bad Request

This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.

MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
        headers);
JSONObject jsonObject = null;

try {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> responseEntity = restTemplate.exchange(
            "https://url", HttpMethod.POST, entity,
            String.class);

    if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
        try {
            jsonObject = new JSONObject(responseEntity.getBody());
        } catch (JSONException e) {
            throw new RuntimeException("JSONException occurred");
        }
    }
  } catch (final HttpClientErrorException httpClientErrorException) {
        throw new ExternalCallBadRequestException();
  } catch (HttpServerErrorException httpServerErrorException) {
        throw new ExternalCallServerErrorException(httpServerErrorException);
  } catch (Exception exception) {
        throw new ExternalCallServerErrorException(exception);
    } 

ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.

Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.

Performance differences between ArrayList and LinkedList

Even they seem to identical(same implemented inteface List - non thread-safe),they give different results in terms of performance in add/delete and searching time and consuming memory (LinkedList consumes more).

LinkedLists can be used if you use highly insertion/deletion with performance O(1). ArrayLists can be used if you use direct access operations with performance O(1)

This code may make clear of these comments and you can try to understand performance results. (Sorry for boiler plate code)

public class Test {

    private static Random rnd;


    static {
        rnd = new Random();
    }


    static List<String> testArrayList;
    static List<String> testLinkedList;
    public static final int COUNT_OBJ = 2000000;

    public static void main(String[] args) {
        testArrayList = new ArrayList<>();
        testLinkedList = new LinkedList<>();

        insertSomeDummyData(testLinkedList);
        insertSomeDummyData(testArrayList);

        checkInsertionPerformance(testLinkedList);  //O(1)
        checkInsertionPerformance(testArrayList);   //O(1) -> O(n)

        checkPerformanceForFinding(testArrayList);  // O(1)
        checkPerformanceForFinding(testLinkedList); // O(n)

    }


    public static void insertSomeDummyData(List<String> list) {
        for (int i = COUNT_OBJ; i-- > 0; ) {
            list.add(new String("" + i));
        }
    }

    public static void checkInsertionPerformance(List<String> list) {

        long startTime, finishedTime;
        startTime = System.currentTimeMillis();
        int rndIndex;
        for (int i = 200; i-- > 0; ) {
            rndIndex = rnd.nextInt(100000);
            list.add(rndIndex, "test");
        }
        finishedTime = System.currentTimeMillis();
        System.out.println(String.format("%s time passed at insertion:%d", list.getClass().getSimpleName(), (finishedTime - startTime)));
    }

    public static void checkPerformanceForFinding(List<String> list) {

        long startTime, finishedTime;
        startTime = System.currentTimeMillis();
        int rndIndex;
        for (int i = 200; i-- > 0; ) {
            rndIndex = rnd.nextInt(100000);
            list.get(rndIndex);
        }
        finishedTime = System.currentTimeMillis();
        System.out.println(String.format("%s time passed at searching:%d", list.getClass().getSimpleName(), (finishedTime - startTime)));

    }

}

Making button go full-width?

In Bootstrap 5, the class btn-block doesn't work anymore. But instead, you can add the class w-100 to the button to make it as wide as its container.

_x000D_
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />

<div class="row"><div class=" col-5 ">
            <a class="btn btn-outline-primary w-100  " href="# "><span>Button 1</span></a> 
</div><div class="col-5 ">

            <a class=" btn btn-primary w-100 weiss " href="# "><span>Button 2</span></a> 
</div></div>
_x000D_
_x000D_
_x000D_

How to leave a message for a github.com user

Besides the removal of the github messaging service, usage was often not necessary due to many githubbers communicating with- and advocating twitter.

The advantage is that there is:

  • full transparency
  • better coverage
  • better search features for tweets
  • better archiving, for instance by the US Library of Congress

It is probably no coincidence that stackoverflow doesn't allow private messaging either, to ensure full transparency. The entire messaging issue is thoroughly discussed on meta-stackoverflow here.

"Are you missing an assembly reference?" compile error - Visual Studio

Delete 'Web.Debug.config' and 'Web.Release.config' file for your solution directory,it should remove all errors

What is Linux’s native GUI API?

The linux kernel graphical operations are in /include/linux/fb.h as struct fb_ops. Eventually this is what add-ons like X11, Wayland, or DRM appear to reference. As these operations are only for video cards, not vector or raster hardcopy or tty oriented terminal devices, their usefulness as a GUI is limited; it's just not entirely true you need those add-ons to get graphical output if you don't mind using some assembler to bypass syscall as necessary.

How to set HTML Auto Indent format on Sublime Text 3?

This was bugging me too, since this was a standard feature in Sublime Text 2, but somehow automatic indentation no longer worked in Sublime Text 3 for HTML files.

My solution was to find the Miscellaneous.tmPreferences file from Sublime Text 2 (found under %AppData%/Roaming/Sublime Text 2/Packages/HTML) and copy those settings to the same file for ST3.

Now package handling has been made more difficult for ST3, but luckily you can just add the files to your %AppData%/Roaming/Sublime Text 3/Packages folder and they overwrite default settings in the install directory. Just save this file as "%AppData%/Roaming/Sublime Text 3/Packages/HTML/Miscellaneous.tmPreferences" and auto indent works again like it did in ST2.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>name</key>
    <string>Miscellaneous</string>
    <key>scope</key>
    <string>text.html</string>
    <key>settings</key>
    <dict>
        <key>decreaseIndentPattern</key>
            <string>(?x)
            ^\s*
            (&lt;/(?!html)
              [A-Za-z0-9]+\b[^&gt;]*&gt;
            |--&gt;
            |&lt;\?(php)?\s+(else(if)?|end(if|for(each)?|while))
            |\}
            )</string>
        <key>batchDecreaseIndentPattern</key>
            <string>(?x)
            ^\s*
            (&lt;/(?!html)
              [A-Za-z0-9]+\b[^&gt;]*&gt;
            |--&gt;
            |&lt;\?(php)?\s+(else(if)?|end(if|for(each)?|while))
            |\}
            )</string>
        <key>increaseIndentPattern</key>
            <string>(?x)
            ^\s*
            &lt;(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^&gt;]*/&gt;)
              ([A-Za-z0-9]+)(?=\s|&gt;)\b[^&gt;]*&gt;(?!.*&lt;/\1&gt;)
            |&lt;!--(?!.*--&gt;)
            |&lt;\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
            |\{[^}"']*$
            </string>
        <key>batchIncreaseIndentPattern</key>
            <string>(?x)
            ^\s*
            &lt;(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^&gt;]*/&gt;)
              ([A-Za-z0-9]+)(?=\s|&gt;)\b[^&gt;]*&gt;(?!.*&lt;/\1&gt;)
            |&lt;!--(?!.*--&gt;)
            |&lt;\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
            |\{[^}"']*$
            </string>
        <key>bracketIndentNextLinePattern</key>
         <string>&lt;!DOCTYPE(?!.*&gt;)</string>
    </dict>
</dict>
</plist>

How to make RatingBar to show five stars

If you are wrapping the RatingBar inside a ConstraintLayout with match_constraint for its width, the editor preview is going to show a number of stars proportional to its actual width, no matter what if you set android:numStars property. Use wrap_content to get the correct preview:

<RatingBar android:id="@+id/myRatingBar"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_marginStart="48dp"
           android:layout_marginEnd="48dp"
           android:numStars="5"
           app:layout_constraintEnd_toEndOf="parent"
           app:layout_constraintStart_toStartOf="parent"
           app:layout_constraintTop_toBottomOf="parent" />

Merge or combine by rownames

cbind.fill <- function(x, y){
  xrn <- rownames(x)
  yrn <- rownames(y)
  rn <- union(xrn, yrn)
  xcn <- colnames(x)
  ycn <- colnames(y)
  if(is.null(xrn) | is.null(yrn) | is.null(xcn) | is.null(ycn)) 
    stop("NULL rownames or colnames")
  z <- matrix(NA, nrow=length(rn), ncol=length(xcn)+length(ycn))
  rownames(z) <- rn
  colnames(z) <- c(xcn, ycn)
  idx <- match(rn, xrn)
  z[!is.na(idx), 1:length(xcn)] <- x[na.omit(idx),]
  idy <- match(rn, yrn)
  z[!is.na(idy), length(xcn)+(1:length(ycn))] <- y[na.omit(idy),]
  return(z)
}

What does if [ $? -eq 0 ] mean for shell scripts?

It is an extremely overused way to check for the success/failure of a command. Typically, the code snippet you give would be refactored as:

if grep -e ERROR ${LOG_DIR_PATH}/${LOG_NAME} > /dev/null; then
   ...
fi

(Although you can use 'grep -q' in some instances instead of redirecting to /dev/null, doing so is not portable. Many implementations of grep do not support the -q option, so your script may fail if you use it.)

How to enable DataGridView sorting when user clicks on the column header?

As Niraj suggested, use a SortableBindingList. I've used this very successfully with the DataGridView.

Here's a link to the updated code I used - Presenting the SortableBindingList - Take Two - archive

Just add the two source files to your project, and you'll be in business.

Source is in SortableBindingList.zip - 404 dead link

Convert normal Java Array or ArrayList to Json Array in android

This is the correct syntax:

String arlist1 [] = { "value1`", "value2", "value3" };
JSONArray jsonArray1 = new JSONArray(arlist1);

Remove empty strings from array while keeping record Without Loop?

i.e we need to take multiple email addresses separated by comma, spaces or newline as below.

    var emails = EmailText.replace(","," ").replace("\n"," ").replace(" ","").split(" ");
    for(var i in emails)
        emails[i] = emails[i].replace(/(\r\n|\n|\r)/gm,"");

    emails.filter(Boolean);
    console.log(emails);

Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE] even if app appears to not be installed

Using Ionic with Cordova via command line...

ionic cordova run android --prod

I ran into this and found that I had deleted the release version from a previous test install, but had an old debug version that was hanging out in apps drawer that I missed. I unplugged my device from the computer, opened the app drawer and used "Search apps.." to find all instances of the app to uninstall them. Then I re-plugged in the device to the computer and viola, it worked!

Thanks for the help everyone!

How to split a data frame?

If you want to split a dataframe according to values of some variable, I'd suggest using daply() from the plyr package.

library(plyr)
x <- daply(df, .(splitting_variable), function(x)return(x))

Now, x is an array of dataframes. To access one of the dataframes, you can index it with the name of the level of the splitting variable.

x$Level1
#or
x[["Level1"]]

I'd be sure that there aren't other more clever ways to deal with your data before splitting it up into many dataframes though.

How do I build JSON dynamically in javascript?

First, I think you're calling it the wrong thing. "JSON" stands for "JavaScript Object Notation" - it's just a specification for representing some data in a string that explicitly mimics JavaScript object (and array, string, number and boolean) literals. You're trying to build up a JavaScript object dynamically - so the word you're looking for is "object".

With that pedantry out of the way, I think that you're asking how to set object and array properties.

// make an empty object
var myObject = {};

// set the "list1" property to an array of strings
myObject.list1 = ['1', '2'];

// you can also access properties by string
myObject['list2'] = [];
// accessing arrays is the same, but the keys are numbers
myObject.list2[0] = 'a';
myObject['list2'][1] = 'b';

myObject.list3 = [];
// instead of placing properties at specific indices, you
// can push them on to the end
myObject.list3.push({});
// or unshift them on to the beginning
myObject.list3.unshift({});
myObject.list3[0]['key1'] = 'value1';
myObject.list3[1]['key2'] = 'value2';

myObject.not_a_list = '11';

That code will build up the object that you specified in your question (except that I call it myObject instead of myJSON). For more information on accessing properties, I recommend the Mozilla JavaScript Guide and the book JavaScript: The Good Parts.

How to Set Variables in a Laravel Blade Template

I'm going to extend the answer given by @Pim.

Add this to the boot method of your AppServiceProvider

<?php
/*
|--------------------------------------------------------------------------
| Extend blade so we can define a variable
| <code>
| @set(name, value)
| </code>
|--------------------------------------------------------------------------
*/

Blade::directive('set', function($expression) {
    list($name, $val) = explode(',', $expression);
    return "<?php {$name} = {$val}; ?>";
});

This way you don't expose the ability to write any php expression.

You can use this directive like:

@set($var, 10)
@set($var2, 'some string')

TypeError: unhashable type: 'list' when using built-in set function

    python 3.2


    >>>> from itertools import chain
    >>>> eg=sorted(list(set(list(chain(*eg)))), reverse=True)
        [7, 6, 5, 4, 3, 2, 1]


   ##### eg contain 2 list within a list. so if you want to use set() function
   you should flatten the list like [1, 2, 3, 4, 4, 5, 6, 7]

   >>> res= list(chain(*eg))       # [1, 2, 3, 4, 4, 5, 6, 7]                   
   >>> res1= set(res)                    #   [1, 2, 3, 4, 5, 6, 7]
   >>> res1= sorted(res1,reverse=True)

What does principal end of an association means in 1:1 relationship in Entity framework

In one-to-one relation one end must be principal and second end must be dependent. Principal end is the one which will be inserted first and which can exist without the dependent one. Dependent end is the one which must be inserted after the principal because it has foreign key to the principal.

In case of entity framework FK in dependent must also be its PK so in your case you should use:

public class Boo
{
    [Key, ForeignKey("Foo")]
    public string BooId{get;set;}
    public Foo Foo{get;set;}
}

Or fluent mapping

modelBuilder.Entity<Foo>()
            .HasOptional(f => f.Boo)
            .WithRequired(s => s.Foo);

How do I change the default schema in sql developer?

Just right clic on the created connection and select "Schema browser", then use the filter to display the desired one.

Cheers.

How can I export a GridView.DataSource to a datatable or dataset?

Assuming your DataSource is of type DataTable, you can just do this:

myGridView.DataSource as DataTable

Log.INFO vs. Log.DEBUG

Debug: fine-grained statements concerning program state, typically used for debugging;

Info: informational statements concerning program state, representing program events or behavior tracking;

Warn: statements that describe potentially harmful events or states in the program;

Error: statements that describe non-fatal errors in the application; this level is used quite often for logging handled exceptions;

Fatal: statements representing the most severe of error conditions, assumedly resulting in program termination.

Found on http://www.beefycode.com/post/Log4Net-Tutorial-pt-1-Getting-Started.aspx

How to move screen without moving cursor in Vim?

You may find answers to "Scrolling Vim relative to cursor, custom mapping" useful.

You can use ScrollToPercent(0) from that question to do this.

Posting a File and Associated Data to a RESTful WebService preferably as JSON

@RequestMapping(value = "/uploadImageJson", method = RequestMethod.POST)
    public @ResponseBody Object jsongStrImage(@RequestParam(value="image") MultipartFile image, @RequestParam String jsonStr) {
-- use  com.fasterxml.jackson.databind.ObjectMapper convert Json String to Object
}

How do I raise the same Exception with a custom message in Python?

None of the above solutions did exactly what I wanted, which was to add some information to the first part of the error message i.e. I wanted my users to see my custom message first.

This worked for me:

exception_raised = False
try:
    do_something_that_might_raise_an_exception()
except ValueError as e:
    message = str(e)
    exception_raised = True

if exception_raised:
    message_to_prepend = "Custom text"
    raise ValueError(message_to_prepend + message)

How to make a <ul> display in a horizontal row

List items are normally block elements. Turn them into inline elements via the display property.

In the code you gave, you need to use a context selector to make the display: inline property apply to the list items, instead of the list itself (applying display: inline to the overall list will have no effect):

#ul_top_hypers li {
    display: inline;
}

Here is the working example:

_x000D_
_x000D_
#div_top_hypers {_x000D_
    background-color:#eeeeee;_x000D_
    display:inline;      _x000D_
}_x000D_
#ul_top_hypers li{_x000D_
    display: inline;_x000D_
}
_x000D_
<div id="div_top_hypers">_x000D_
    <ul id="ul_top_hypers">_x000D_
        <li>&#8227; <a href="" class="a_top_hypers"> Inbox</a></li>_x000D_
        <li>&#8227; <a href="" class="a_top_hypers"> Compose</a></li>_x000D_
        <li>&#8227; <a href="" class="a_top_hypers"> Reports</a></li>_x000D_
        <li>&#8227; <a href="" class="a_top_hypers"> Preferences</a></li>_x000D_
        <li>&#8227; <a href="" class="a_top_hypers"> logout</a></li>_x000D_
    </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

html cellpadding the left side of a cell

I would suggest using inline CSS styling.

<table border="1" style="padding-right: 10px;">
<tr>
<td>Content</td>
</tr>
</table>

or

<table border="1">
<tr style="padding-right: 10px;">
<td>Content</td>
</tr>
</table>

or

<table border="1">
<tr>
<td style="padding-right: 10px;">Content</td>
</tr>
</table>

I don't quite follow what you need, but this is what I would do, assuming I understand you needs.

How to set input type date's default value to today?

If you are using ruby you can use this to set the default value to today's date and time:

<input type="datetime-local" name="time" value="<%= Time.now.strftime('%Y-%m-%dT%H:%M') %>" />

sqlplus: error while loading shared libraries: libsqlplus.so: cannot open shared object file: No such file or directory

On Oracle's own Linux (Version 7.7, PRETTY_NAME="Oracle Linux Server 7.7" in /etc/os-release), if you installed the 18.3 client libraries with

sudo yum install oracle-instantclient18.3-basic.x86_64
sudo yum install oracle-instantclient18.3-sqlplus.x86_64

then you need to put the following in your .bash_profile:

export ORACLE_HOME=/usr/lib/oracle/18.3/client64
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ORACLE_HOME/lib:$ORACLE_HOME

in order to be able to invoke the SQLPlus client, which, incidentally, is called sqlplus64 on this platform.

How to read Excel cell having Date with Apache POI?

You can use CellDateFormatter to fetch the Date in the same format as in excel cell. See the following code:

CellValue cv = formulaEv.evaluate(cell);
double dv = cv.getNumberValue();
if (HSSFDateUtil.isCellDateFormatted(cell)) {
    Date date = HSSFDateUtil.getJavaDate(dv);

    String df = cell.getCellStyle().getDataFormatString();

    strValue = new CellDateFormatter(df).format(date); 
}

PDO::__construct(): Server sent charset (255) unknown to the client. Please, report to the developers

MySQL 8 changed the default charset to utf8mb4. But some clients don't know this charset. Hence when the server reports its default charset to the client, and the client doesn't know what the server means, it throws this error.

See also https://bugs.mysql.com/bug.php?id=71606

That bug is against the MySQL Connector/C++ so it's affecting more than just PHP.

Okay—I got it to work by changing the character set to utf8, to be compatible with non-upgraded clients. I added this to /etc/my.cnf and restarted mysqld:

[client]
default-character-set=utf8

[mysql]
default-character-set=utf8


[mysqld]
collation-server = utf8_unicode_ci
character-set-server = utf8

I found these settings in an answer from 2010: Change MySQL default character set to UTF-8 in my.cnf?

Android: How can I get the current foreground activity (from a service)?

Use this code for API 21 or above. This works and gives better result compared to the other answers, it detects perfectly the foreground process.

if (Build.VERSION.SDK_INT >= 21) {
    String currentApp = null;
    UsageStatsManager usm = (UsageStatsManager) this.getSystemService(Context.USAGE_STATS_SERVICE);
    long time = System.currentTimeMillis();
    List<UsageStats> applist = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);
    if (applist != null && applist.size() > 0) {
        SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
        for (UsageStats usageStats : applist) {
            mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);

        }
        if (mySortedMap != null && !mySortedMap.isEmpty()) {
            currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
        }
    }

Recommended way to embed PDF in HTML?

If you don't want to host PDF.JS on your own, you could try DocDroid. It is similar to the Google Drive PDF viewer but allows custom branding.

iOS 10: "[App] if we're in the real pre-commit handler we can't actually add any new fences due to CA restriction"

Try putting the following in the environment variables for the scheme under run(debug)

OS_ACTIVITY_MODE = disable

How do I resize a Google Map with JavaScript after it has loaded?

If you're using Google Maps v2, call checkResize() on your map after resizing the container. link

UPDATE

Google Maps JavaScript API v2 was deprecated in 2011. It is not available anymore.

Timing a command's execution in PowerShell

Using Stopwatch and formatting elapsed time:

Function FormatElapsedTime($ts) 
{
    $elapsedTime = ""

    if ( $ts.Minutes -gt 0 )
    {
        $elapsedTime = [string]::Format( "{0:00} min. {1:00}.{2:00} sec.", $ts.Minutes, $ts.Seconds, $ts.Milliseconds / 10 );
    }
    else
    {
        $elapsedTime = [string]::Format( "{0:00}.{1:00} sec.", $ts.Seconds, $ts.Milliseconds / 10 );
    }

    if ($ts.Hours -eq 0 -and $ts.Minutes -eq 0 -and $ts.Seconds -eq 0)
    {
        $elapsedTime = [string]::Format("{0:00} ms.", $ts.Milliseconds);
    }

    if ($ts.Milliseconds -eq 0)
    {
        $elapsedTime = [string]::Format("{0} ms", $ts.TotalMilliseconds);
    }

    return $elapsedTime
}

Function StepTimeBlock($step, $block) 
{
    Write-Host "`r`n*****"
    Write-Host $step
    Write-Host "`r`n*****"

    $sw = [Diagnostics.Stopwatch]::StartNew()
    &$block
    $sw.Stop()
    $time = $sw.Elapsed

    $formatTime = FormatElapsedTime $time
    Write-Host "`r`n`t=====> $step took $formatTime"
}

Usage Samples

StepTimeBlock ("Publish {0} Reports" -f $Script:ArrayReportsList.Count)  { 
    $Script:ArrayReportsList | % { Publish-Report $WebServiceSSRSRDL $_ $CarpetaReports $CarpetaDataSources $Script:datasourceReport };
}

StepTimeBlock ("My Process")  {  .\do_something.ps1 }

Convert HTML string to image

Thanks all for your responses. I used HtmlRenderer external dll (library) to achieve the same and found below code for the same.

Here is the code for this

public void ConvertHtmlToImage()
{
   Bitmap m_Bitmap = new Bitmap(400, 600);
   PointF point = new PointF(0, 0);
   SizeF maxSize = new System.Drawing.SizeF(500, 500);
   HtmlRenderer.HtmlRender.Render(Graphics.FromImage(m_Bitmap),
                                           "<html><body><p>This is some html code</p>"
                                           + "<p>This is another html line</p></body>",
                                            point, maxSize);

   m_Bitmap.Save(@"C:\Test.png", ImageFormat.Png);
}

HTTPS setup in Amazon EC2

Use Elastic Load Balacing, it supports SSL termination at the Load Balancer, including offloading SSL decryption from application instances and providing centralized management of SSL certificates.

How to convert a pandas DataFrame subset of columns AND rows into a numpy array?

.loc accept row and column selectors simultaneously (as do .ix/.iloc FYI) This is done in a single pass as well.

In [1]: df = DataFrame(np.random.rand(4,5), columns = list('abcde'))

In [2]: df
Out[2]: 
          a         b         c         d         e
0  0.669701  0.780497  0.955690  0.451573  0.232194
1  0.952762  0.585579  0.890801  0.643251  0.556220
2  0.900713  0.790938  0.952628  0.505775  0.582365
3  0.994205  0.330560  0.286694  0.125061  0.575153

In [5]: df.loc[df['c']>0.5,['a','d']]
Out[5]: 
          a         d
0  0.669701  0.451573
1  0.952762  0.643251
2  0.900713  0.505775

And if you want the values (though this should pass directly to sklearn as is); frames support the array interface

In [6]: df.loc[df['c']>0.5,['a','d']].values
Out[6]: 
array([[ 0.66970138,  0.45157274],
       [ 0.95276167,  0.64325143],
       [ 0.90071271,  0.50577509]])

What do I do when my program crashes with exception 0xc0000005 at address 0?

Problems with the stack frames could indicate stack corruption (a truely horrible beast), optimisation, or mixing frameworks such as C/C++/C#/Delphi and other craziness as that - there is no absolute standard with respect to stack frames. (Some languages do not even have them!).

So, I suggest getting slightly annoyed with the stack frame issues, ignoring it, and then just use Remy's answer.

Trust Store vs Key Store - creating with keytool

keystore simply stores private keys, wheras truststore stores public keys. You will want to generate a java certificate for SSL communication. You can use a keygen command in windows, this will probably be the most easy solution.

c++ bool question

false == 0 and true = !false

i.e. anything that is not zero and can be converted to a boolean is not false, thus it must be true.

Some examples to clarify:

if(0)          // false
if(1)          // true
if(2)          // true
if(0 == false) // true
if(0 == true)  // false
if(1 == false) // false
if(1 == true)  // true
if(2 == false) // false
if(2 == true)  // false
cout << false  // 0
cout << true   // 1

true evaluates to 1, but any int that is not false (i.e. 0) evaluates to true but is not equal to true since it isn't equal to 1.

Jquery href click - how can I fire up an event?

Try:

$(document).ready(function(){
   $('a .sign_new').click(function(){
      alert('Sign new href executed.'); 
   }); 
});

You've mixed up the class and href names / selector type.

Calling the base class constructor from the derived class constructor

The base-class constructor is already automatically called by your derived-class constructor. In C++, if the base class has a default constructor (takes no arguments, can be auto-generated by the compiler!), and the derived-class constructor does not invoke another base-class constructor in its initialisation list, the default constructor will be called. I.e. your code is equivalent to:

class PetStore: public Farm
{
public :
    PetStore()
    : Farm()     // <---- Call base-class constructor in initialision list
    {
     idF=0;
    };
private:
    int idF;
    string nameF;
}

Curl command without using cache

The -H 'Cache-Control: no-cache' argument is not guaranteed to work because the remote server or any proxy layers in between can ignore it. If it doesn't work, you can do it the old-fashioned way, by adding a unique querystring parameter. Usually, the servers/proxies will think it's a unique URL and not use the cache.

curl "http://www.example.com?foo123"

You have to use a different querystring value every time, though. Otherwise, the server/proxies will match the cache again. To automatically generate a different querystring parameter every time, you can use date +%s, which will return the seconds since epoch.

curl "http://www.example.com?$(date +%s)"

Table scroll with HTML and CSS

Table with Fixed Header

_x000D_
_x000D_
<table cellspacing="0" cellpadding="0" border="0" width="325">_x000D_
  <tr>_x000D_
    <td>_x000D_
       <table cellspacing="0" cellpadding="1" border="1" width="300" >_x000D_
         <tr style="color:white;background-color:grey">_x000D_
            <th>Header 1</th>_x000D_
            <th>Header 2</th>_x000D_
         </tr>_x000D_
       </table>_x000D_
    </td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>_x000D_
       <div style="width:320px; height:80px; overflow:auto;">_x000D_
         <table cellspacing="0" cellpadding="1" border="1" width="300" >_x000D_
           <tr>_x000D_
             <td>new item</td>_x000D_
             <td>new item</td>_x000D_
           </tr>_x000D_
           <tr>_x000D_
             <td>new item</td>_x000D_
             <td>new item</td>_x000D_
           </tr>_x000D_
              <tr>_x000D_
             <td>new item</td>_x000D_
             <td>new item</td>_x000D_
           </tr>_x000D_
              <tr>_x000D_
             <td>new item</td>_x000D_
             <td>new item</td>_x000D_
           </tr>_x000D_
              <tr>_x000D_
             <td>new item</td>_x000D_
             <td>new item</td>_x000D_
           </tr>_x000D_
              <tr>_x000D_
             <td>new item</td>_x000D_
             <td>new item</td>_x000D_
           </tr>_x000D_
              <tr>_x000D_
             <td>new item</td>_x000D_
             <td>new item</td>_x000D_
           </tr>_x000D_
              <tr>_x000D_
             <td>new item</td>_x000D_
             <td>new item</td>_x000D_
           </tr>_x000D_
              <tr>_x000D_
             <td>new item</td>_x000D_
             <td>new item</td>_x000D_
           </tr>_x000D_
              <tr>_x000D_
             <td>new item</td>_x000D_
             <td>new item</td>_x000D_
           </tr>_x000D_
         </table>  _x000D_
       </div>_x000D_
    </td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Result

Demo Image

This is working in all browser

Demo jsfiddle http://jsfiddle.net/nyCKE/6302/

How do I call an Angular 2 pipe with multiple arguments?

You're missing the actual pipe.

{{ myData | date:'fullDate' }}

Multiple parameters can be separated by a colon (:).

{{ myData | myPipe:'arg1':'arg2':'arg3' }}

Also you can chain pipes, like so:

{{ myData | date:'fullDate' | myPipe:'arg1':'arg2':'arg3' }}

Transfer data between iOS and Android via Bluetooth?

Maybe a bit delayed, but technologies have evolved since so there is certainly new info around which draws fresh light on the matter...

As iOS has yet to open up an API for WiFi Direct and Multipeer Connectivity is iOS only, I believe the best way to approach this is to use BLE, which is supported by both platforms (some better than others).

On iOS a device can act both as a BLE Central and BLE Peripheral at the same time, on Android the situation is more complex as not all devices support the BLE Peripheral state. Also the Android BLE stack is very unstable (to date).

If your use case is feature driven, I would suggest to look at Frameworks and Libraries that can achieve cross platform communication for you, without you needing to build it up from scratch.

For example: http://p2pkit.io or google nearby

Disclaimer: I work for Uepaa, developing p2pkit.io for Android and iOS.

How can I convert a comma-separated string to an array?

Return function

var array = (new Function("return [" + str+ "];")());

Its accept string and objectstrings:

var string = "0,1";

var objectstring = '{Name:"Tshirt", CatGroupName:"Clothes", Gender:"male-female"}, {Name:"Dress", CatGroupName:"Clothes", Gender:"female"}, {Name:"Belt", CatGroupName:"Leather", Gender:"child"}';

var stringArray = (new Function("return [" + string+ "];")());

var objectStringArray = (new Function("return [" + objectstring+ "];")());

JSFiddle https://jsfiddle.net/7ne9L4Lj/1/

Matching special characters and letters in regex

Well, why not just add them to your existing character class?

var pattern = /[a-zA-Z0-9&._-]/

If you need to check whether a string consists of nothing but those characters you have to anchor the expression as well:

var pattern = /^[a-zA-Z0-9&._-]+$/

The added ^ and $ match the beginning and end of the string respectively.

Testing for letters, numbers or underscore can be done with \w which shortens your expression:

var pattern = /^[\w&.-]+$/

As mentioned in the comment from Nathan, if you're not using the results from .match() (it returns an array with what has been matched), it's better to use RegExp.test() which returns a simple boolean:

if (pattern.test(qry)) {
    // qry is non-empty and only contains letters, numbers or special characters.
}

Update 2

In case I have misread the question, the below will check if all three separate conditions are met.

if (/[a-zA-Z]/.test(qry) && /[0-9]/.test(qry) && /[&._-]/.test(qry)) {
   // qry contains at least one letter, one number and one special character
}

How can Bash execute a command in a different directory context?

Use cd in a subshell; the shorthand way to use this kind of subshell is parentheses.

(cd wherever; mycommand ...)

That said, if your command has an environment that it requires, it should really ensure that environment itself instead of putting the onus on anything that might want to use it (unless it's an internal command used in very specific circumstances in the context of a well defined larger system, such that any caller already needs to ensure the environment it requires). Usually this would be some kind of shell script wrapper.

Why does my 'git branch' have no master?

To checkout a branch which does not exist locally but is in the remote repo you could use this command:

git checkout -t -b master origin/master

Dynamically adding HTML form field using jQuery

There appears to be a bug with appendTo using a frameset ID appending to a FORM in Chrome. Swapped out the attribute type directly with div and it works.

Create a <ul> and fill it based on a passed array

What are disadvantages of the following solution? Seems to be faster and shorter.

var options = {
    set0: ['Option 1','Option 2'],
    set1: ['First Option','Second Option','Third Option']
};

var list = "<li>" + options.set0.join("</li><li>") + "</li>";
document.getElementById("list").innerHTML = list;

Class is inaccessible due to its protection level

Try adding the below code to the class that you want to use

[Serializable()]
public partial class Class
{

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare();

runOnUiThread(new Runnable(){
   public void run() {
     Toast.makeText(getApplicationContext(), "Status = " + message.getBody() , Toast.LENGTH_LONG).show();
   }
 });

this works for me

Convert char array to string use C

Assuming array is a character array that does not end in \0, you will want to use strncpy:

char * strncpy(char * destination, const char * source, size_t num);

like so:

strncpy(string, array, 20);
string[20] = '\0'

Then string will be a null terminated C string, as desired.

Solving "adb server version doesn't match this client" error

  1. adb kill-server
  2. close any pc side application you are using for manage the android phone, e.g. 360mobile(360????). you might need to end them in task manager in necessary.
  3. adb start-server and it should be solved

Easiest way to change font and font size

This should do it (bold as well);

label1.Font = new Font("Serif", 24,FontStyle.Bold);

How to manage a redirect request after a jQuery Ajax call

I know this topic is old, but I'll give yet another approach I've found and previously described here. Basically I'm using ASP.MVC with WIF (but this is not really important for the context of this topic - answer is adequate no matter which frameworks are used. The clue stays unchanged - dealing with issues related to authentication failures while performing ajax requests).

The approach shown below can be applied to all ajax requests out of the box (if they do not redefine beforeSend event obviously).

$.ajaxSetup({
    beforeSend: checkPulse,
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        document.open();
        document.write(XMLHttpRequest.responseText);
        document.close();
    }
});

Before any ajax request is performed CheckPulse method is invoked (the controller method which can be anything simplest):

[Authorize]
public virtual void CheckPulse() {}

If user is not authenticated (token has expired) such method cannot be accessed (protected by Authorize attribute). Because the framework handles authentication, while token expires, it puts http status 302 to the response. If you don't want your browser to handle 302 response transparently, catch it in Global.asax and change response status - for example to 200 OK. Additionally, add header, which instructs you to process such response in special way (later at the client side):

protected void Application_EndRequest()
{
    if (Context.Response.StatusCode == 302
        && (new HttpContextWrapper(Context)).Request.IsAjaxRequest())
    {                
        Context.Response.StatusCode = 200;
        Context.Response.AddHeader("REQUIRES_AUTH", "1");
    }
}

Finally at the client side check for such custom header. If present - full redirection to logon page should be done (in my case window.location is replaced by url from request which is handled automatically by my framework).

function checkPulse(XMLHttpRequest) {
    var location = window.location.href;
    $.ajax({
        url: "/Controller/CheckPulse",
        type: 'GET',
        async: false,
        beforeSend: null,
        success:
            function (result, textStatus, xhr) {
                if (xhr.getResponseHeader('REQUIRES_AUTH') === '1') {
                    XMLHttpRequest.abort(); // terminate further ajax execution
                    window.location = location;
                }
            }
    });
}

How can I convert a DOM element to a jQuery element?

What about constructing the element using jQuery? e.g.

$("<div></div>")

creates a new div element, ready to be added to the page. Can be shortened further to

$("<div>")

then you can chain on commands that you need, set up event handlers and append it to the DOM. For example

$('<div id="myid">Div Content</div>')
    .bind('click', function(e) { /* event handler here */ })
    .appendTo('#myOtherDiv');

How can I create a product key for my C# application?

If you are asking about the keys that you can type in, like Windows product keys, then they are based on some checks. If you are talking about the keys that you have to copy paste, then they are based on a digitial signature (private key encryption).

A simple product key logic could be to start with saying that the product key consists of four 5-digit groups, like abcde-fghij-kljmo-pqrst, and then go on to specify internal relationships like f+k+p should equal a, meaning the first digits of the 2, 3 and 4 group should total to a. This means that 8xxxx-2xxxx-4xxxx-2xxxx is valid, so is 8xxxx-1xxxx-0xxxx-7xxxx. Of course, there would be other relationships as well, including complex relations like, if the second digit of the first group is odd, then the last digit of the last group should be odd too. This way there would be generators for product keys and verification of product keys would simply check if it matches all the rules.

Encryption are normally the string of information about the license encrypted using a private key (== digitally signed) and converted to Base64. The public key is distributed with the application. When the Base64 string arrives, it is verified (==decrypted) by the public key and if found valid, the product is activated.

How to check if a key exists in Json Object and get its value

Use:

if (containerObject.has("video")) {
    //get value of video
}

403 - Forbidden: Access is denied. ASP.Net MVC

In addition to the answers above, you may also get that error when you have Windows Authenticaton set and :

  • IIS is pointing to an empty folder.
  • You do not have a default document set.

Failed to install android-sdk: "java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema"

My Java version is 15.0.1 . For the OS Mac.

and this is how i fixed the issue.

  1. downloaded zip: jaf-1_1_1.zip from: https://download.oracle.com/otn-pub/java/jaf/1.1.1/jaf-1_1_1.zip?AuthParam=1609860571_68ca6f30491c76e81970a3849504fb6a

  2. downloaded the zip: jaxb-ri-2.3.1.zip from: https://download.oracle.com/otn-pub/java/jaf/1.1.1/jaf-1_1_1.zip?AuthParam=1609860571_68ca6f30491c76e81970a3849504fb6a

  3. unziped into a folder: ~/jars/ . exported classpath as follows

export  
 CLASSPATH=~/jars/FastInfoset.jar:~/jars/activation.jar:~/jars/codemodel.jar:~/jars/dtd-parser.jar:~/jars/istack-commons-runtime.jar:~/jars/istack-commons-tools.jar:~/jars/jaf-1.1.1:~/jars/jaf-1_1_1.zip:~/jars/javax.activation-api.jar:~/jars/jaxb-api.jar:~/jars/jaxb-jxc.jar:~/jars/jaxb-ri:~/jars/jaxb-ri-2.3.1.zip:~/jars/jaxb-runtime.jar:~/jars/jaxb-xjc.jar:~/jars/relaxng-datatype.jar:~/jars/rngom.jar:~/jars/stax-ex.jar:~/jars/txw2.jar:~/jars/xsom.jar
  1. next edit the file: cd ~/Library/Android/sdk/tools/bin/sdkmanager change the CLASSPATH to the below

CLASSPATH=$CLASSPATH:$APP...

save the file and run the command again.

lodash multi-column sortBy descending

It's worth noting that if you want to sort particular properties descending, you don't want to simply append .reverse() at the end, as this will make all of the sorts descending.

To make particular sorts descending, chain your sorts from least significant to most significant, calling .reverse() after each sort that you want to be descending.

var data = _(data).chain()
    .sort("date")
    .reverse()    // sort by date descending
    .sort("name") // sort by name ascending
    .result()

Since _'s sort is a stable sort, you can safely chain and reverse sorts because if two items have the same value for a property, their order is preserved.

More information

find all subsets that sum to a particular value

I used Dynamic Programming & Memoization to find count of subsets from a set having a particular total. The code below code is in java. Have included the comments to explain the code intentions -

package com.company.dynamicProgramming;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class FindSumInSubSet {

    public static void main(String...args){

        int[] arr = {3, 2, 4, 6, 10};
        int total = 16;
        // Challenge is to find the subsets of numbers total 6 in above super set (represented as array)
        // In general - Write a code to count subset of elements totalling m(6 above) in given set of n(9 as array size above) elements

        Map<Entry, Integer> memoMap = new HashMap<>();

        Entry entry = new Entry(total, arr.length-1);

        int count = countSubSetForSum(arr, entry, memoMap);
        System.out.format("In set of %d elements, the number of subsets having total=%d is %d %n", arr.length,total, count);
    }


    static int countSubSetForSum(int[] arr, Entry entry, Map<Entry, Integer> memoMap){

        int total = entry.getTotal();
        int i = entry.getI();

        if (total == 0){             // means element was equal in previous recursion
            return 1;
        }else if(total < 0){         // means element was less in previous recursion i.e. not equal
            return 0;
        }else if (i < 0){            // means arr was finished previous recursion
            return 0;
        }else if (arr[i] > total){   // means element is greater than total
                                     // i.e. leave that element and look further sets excluding this element
            return getCountForIthAndTotal(arr, new Entry( total, i-1), memoMap);

        }else{                       // means element is less than total i.e. 2 possibilities :
                                     // 1st - look further sets including this element
                                     // 2nd - look further sets excluding this element
            return getCountForIthAndTotal(arr, new Entry( total-arr[i], i-1), memoMap) +
                    getCountForIthAndTotal(arr, new Entry( total, i-1), memoMap);
        }
    }


    static int getCountForIthAndTotal(int[] arr, Entry entry, Map<Entry, Integer> memoMap){
        if (memoMap.containsKey(entry)){     //look up in has table if we already calculated particular total for ith subset..
            return memoMap.get(entry);       //This is nothing but using memoization that reduce the entire below code i.e. further recursion -
        }else {
            int count = countSubSetForSum(arr, entry, memoMap);  //Recursion
            memoMap.put(entry, count); //Build memoization
            return count;
        }
    }


    //Just Data Structure for Key in HashMap (memoMaP)... intent to include particular total for ith element's subset.
    static class Entry {
        int total;
        int i;

        public Entry(int total, int i) {
            this.total = total;
            this.i = i;
        }

        public int getTotal() {
            return total;
        }

        public int getI() {
            return i;
        }


        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Entry entry = (Entry) o;
            return total == entry.total &&
                    i == entry.i;
        }

        @Override
        public int hashCode() {
            return Objects.hash(total, i);
        }
    }

}

When i ran this the out put is :

In set of 5 elements, the number of subsets having total=16 is 2 
Process finished with exit code 0

android image button

You just use an ImageButton and make the background whatever you want and set the icon as the src.

<ImageButton
    android:id="@+id/ImageButton01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/album_icon"
    android:background="@drawable/round_button" />

enter image description here

Convert a Python list with strings all to lowercase or uppercase

If your purpose is to matching with another string by converting in one pass, you can use str.casefold() as well.

This is useful when you have non-ascii characters and matching with ascii versions(eg: maße vs masse).Though str.lower or str.upper fails in such cases, str.casefold() will pass. This is available in Python 3 and the idea is discussed in detail with the answer https://stackoverflow.com/a/31599276/4848659.

>>>str="Hello World";
>>>print(str.lower());
hello world
>>>print(str.upper());
HELLO WOLRD
>>>print(str.casefold());
hello world

Use LIKE %..% with field values in MySQL

  SELECT t1.a, t2.b
  FROM t1
  JOIN t2 ON t1.a LIKE '%'+t2.b +'%'

because the last answer not work

Setting up a websocket on Apache?

I struggled to understand the proxy settings for websockets for https therefore let me put clarity here what i realized.

First you need to enable proxy and proxy_wstunnel apache modules and the apache configuration file will look like this.

<IfModule mod_ssl.c>
    <VirtualHost _default_:443>
      ServerName www.example.com
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/your_project_public_folder

      SSLEngine on
      SSLCertificateFile    /etc/ssl/certs/path_to_your_ssl_certificate
      SSLCertificateKeyFile /etc/ssl/private/path_to_your_ssl_key

      <Directory /var/www/your_project_public_folder>
              Options Indexes FollowSymLinks
              AllowOverride All
              Require all granted
              php_flag display_errors On
      </Directory>
      ProxyRequests Off 
      ProxyPass /wss/  ws://example.com:port_no

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
    </VirtualHost>
</IfModule>

in your frontend application use the url "wss://example.com/wss/" this is very important mostly if you are stuck with websockets you might be making mistake in the front end url. You probably putting url wrongly like below.

wss://example.com:8080/wss/ -> port no should not be mentioned
ws://example.com/wss/ -> url should start with wss only.
wss://example.com/wss -> url should end with / -> most important

also interesting part is the last /wss/ is same as proxypass value if you writing proxypass /ws/ then in the front end you should write /ws/ in the end of url.

ubuntu "No space left on device" but there is tons of space

It's possible that you've run out of memory or some space elsewhere and it prompted the system to mount an overflow filesystem, and for whatever reason, it's not going away.

Try unmounting the overflow partition:

umount /tmp

or

umount overflow

Override hosts variable of Ansible playbook from the command line

An other solution is to use the special variable ansible_limit which is the contents of the --limit CLI option for the current execution of Ansible.

- hosts: "{{ ansible_limit | default(omit) }}"

If the --limit option is omitted, then Ansible issues a warning, but does nothing since no host matched.

[WARNING]: Could not match supplied host pattern, ignoring: None

PLAY ****************************************************************
skipping: no hosts matched

How to convert java.lang.Object to ArrayList?

The conversion fails (java.lang.ClassCastException: java.lang.String cannot be cast to java.util.ArrayList) because you have surely some objects that are not ArrayList. verify the types of your different objects.

How do I put variables inside javascript strings?

I wrote a function which solves the problem precisely.

First argument is the string that wanted to be parameterized. You should put your variables in this string like this format "%s1, %s2, ... %s12".

Other arguments are the parameters respectively for that string.

/***
 * @example parameterizedString("my name is %s1 and surname is %s2", "John", "Doe");
 * @return "my name is John and surname is Doe"
 *
 * @firstArgument {String} like "my name is %s1 and surname is %s2"
 * @otherArguments {String | Number}
 * @returns {String}
 */
const parameterizedString = (...args) => {
  const str = args[0];
  const params = args.filter((arg, index) => index !== 0);
  if (!str) return "";
  return str.replace(/%s[0-9]+/g, matchedStr => {
    const variableIndex = matchedStr.replace("%s", "") - 1;
    return params[variableIndex];
  });
}

Examples

parameterizedString("my name is %s1 and surname is %s2", "John", "Doe");
// returns "my name is John and surname is Doe"

parameterizedString("this%s1 %s2 %s3", " method", "sooo", "goood");
// returns "this method sooo goood"

If variable position changes in that string, this function supports it too without changing the function parameters.

parameterizedString("i have %s2 %s1 and %s4 %s3.", "books", 5, "pencils", "6");
// returns "i have 5 books and 6 pencils."

C# Linq Group By on multiple columns

Given a list:

var list = new List<Child>()
{
    new Child()
        {School = "School1", FavoriteColor = "blue", Friend = "Bob", Name = "John"},
    new Child()
        {School = "School2", FavoriteColor = "blue", Friend = "Bob", Name = "Pete"},
    new Child()
        {School = "School1", FavoriteColor = "blue", Friend = "Bob", Name = "Fred"},
    new Child()
        {School = "School2", FavoriteColor = "blue", Friend = "Fred", Name = "Bob"},
};

The query would look like:

var newList = list
    .GroupBy(x => new {x.School, x.Friend, x.FavoriteColor})
    .Select(y => new ConsolidatedChild()
        {
            FavoriteColor = y.Key.FavoriteColor,
            Friend = y.Key.Friend,
            School = y.Key.School,
            Children = y.ToList()
        }
    );

Test code:

foreach(var item in newList)
{
    Console.WriteLine("School: {0} FavouriteColor: {1} Friend: {2}", item.School,item.FavoriteColor,item.Friend);
    foreach(var child in item.Children)
    {
        Console.WriteLine("\t Name: {0}", child.Name);
    }
}

Result:

School: School1 FavouriteColor: blue Friend: Bob
    Name: John
    Name: Fred
School: School2 FavouriteColor: blue Friend: Bob
    Name: Pete
School: School2 FavouriteColor: blue Friend: Fred
    Name: Bob

Install MySQL on Ubuntu without a password prompt

sudo debconf-set-selections <<< 'mysql-server mysql-server/root_password password your_password'
sudo debconf-set-selections <<< 'mysql-server mysql-server/root_password_again password your_password'
sudo apt-get -y install mysql-server

For specific versions, such as mysql-server-5.6, you'll need to specify the version in like this:

sudo debconf-set-selections <<< 'mysql-server-5.6 mysql-server/root_password password your_password'
sudo debconf-set-selections <<< 'mysql-server-5.6 mysql-server/root_password_again password your_password'
sudo apt-get -y install mysql-server-5.6

For mysql-community-server, the keys are slightly different:

sudo debconf-set-selections <<< 'mysql-community-server mysql-community-server/root-pass password your_password'
sudo debconf-set-selections <<< 'mysql-community-server mysql-community-server/re-root-pass password your_password'
sudo apt-get -y install mysql-community-server

Replace your_password with the desired root password. (it seems your_password can also be left blank for a blank root password.)

If your shell doesn't support here-strings (zsh, ksh93 and bash support them), use:

echo ... | sudo debconf-set-selections 

How to get attribute of element from Selenium?

Python

element.get_attribute("attribute name")

Java

element.getAttribute("attribute name")

Ruby

element.attribute("attribute name")

C#

element.GetAttribute("attribute name");

How to convert entire dataframe to numeric while preserving decimals?

> df2 <- data.frame(sapply(df1, function(x) as.numeric(as.character(x))))
> df2
     a b
1 0.01 2
2 0.02 4
3 0.03 5
4 0.04 7
> sapply(df2, class)
        a         b 
"numeric" "numeric" 

TortoiseSVN Error: "OPTIONS of 'https://...' could not connect to server (...)"

It sounds like you are almost definitely behind a proxy server.

Where this does not work for me behind my proxy:

svn checkout http://v8.googlecode.com/svn/trunk/ v8-read-only

this does:

svn --config-option servers:global:http-proxy-host=MY_PROXY_HOST --config-option servers:global:http-proxy-port=MY_PROXY_PORT checkout http://v8.googlecode.com/svn/trunk/ v8-read-only

UPDATE I forgot to quote my source :-)

http://svnbook.red-bean.com/en/1.1/ch07.html#svn-ch-7-sect-1.3.1

String to date in Oracle with milliseconds

Oracle stores only the fractions up to second in a DATE field.

Use TIMESTAMP instead:

SELECT  TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9')
FROM    dual

, possibly casting it to a DATE then:

SELECT  CAST(TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9') AS DATE)
FROM    dual

jquery data selector

Here's a plugin that simplifies life https://github.com/rootical/jQueryDataSelector

Use it like that:

data selector           jQuery selector
  $$('name')              $('[data-name]')
  $$('name', 10)          $('[data-name=10]')
  $$('name', false)       $('[data-name=false]')
  $$('name', null)        $('[data-name]')
  $$('name', {})          Syntax error

Print <div id="printarea"></div> only?

I picked up the content using JavaScript and created a window that I could print in stead...

c++ boost split string

My best guess at why you had problems with the ----- covering your first result is that you actually read the input line from a file. That line probably had a \r on the end so you ended up with something like this:

-----------test2-------test3

What happened is the machine actually printed this:

test-------test2-------test3\r-------

That means, because of the carriage return at the end of test3, that the dashes after test3 were printed over the top of the first word (and a few of the existing dashes between test and test2 but you wouldn't notice that because they were already dashes).

How to Check whether Session is Expired or not in asp.net

this way many people detect session has expired or not. the below code may help u.

protected void Page_Init(object sender, EventArgs e)
    {
        if (Context.Session != null)
        {
            if (Session.IsNewSession)
            {
                HttpCookie newSessionIdCookie = Request.Cookies["ASP.NET_SessionId"];
                if (newSessionIdCookie != null)
                {
                    string newSessionIdCookieValue = newSessionIdCookie.Value;
                    if (newSessionIdCookieValue != string.Empty)
                    {
                        // This means Session was timed Out and New Session was started
                        Response.Redirect("Login.aspx");
                    }
                }
            }
        }
    }

Find specific string in a text file with VBS script

Try to change like this ..

firstStr = "<?xml version" 'my file always starts like this

Do until objInputFile.AtEndOfStream  

    strToAdd = "<tr><td><a href=" & chr(34) & "../../Logs/DD/Beginning_of_DD_TC" & CStr(index) & ".html" & chr(34) & ">Beginning_of_DD_TC" & CStr(index) & "</a></td></tr>"  

   substrToFind = "<tr><td><a href=" & chr(34) & "../Test case " & trim(cstr((index)))

   tmpStr = objInputFile.ReadLine

   If InStr(tmpStr, substrToFind) <= 0 Then
       If Instr(tmpStr, firstStr) > 0 Then
          text = tmpStr 'to avoid the first empty line
       Else
          text = text & vbCrLf & tmpStr
       End If
   Else
      text = text & vbCrLf & strToAdd & vbCrLf & tmpStr

   End If
   index = index + 1
Loop

Eclipse error: 'Failed to create the Java Virtual Machine'

Reduce param size upto -256

See my eclipse.ini file

    -startup
   plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar
   --launcher.library
  plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.100.v20110502
  -product
   org.eclipse.epp.package.jee.product
   --launcher.defaultAction
   openFile
   --launcher.XXMaxPermSize
   256M
  -showsplash
   org.eclipse.platform
   --launcher.XXMaxPermSize
   256M
  --launcher.defaultAction
  openFile
  -vmargs
  -Dosgi.requiredJavaVersion=1.6
  -Xms40m
  -Xmx512m

Int to byte array

Marc's answer is of course the right answer. But since he mentioned the shift operators and unsafe code as an alternative. I would like to share a less common alternative. Using a struct with Explicit layout. This is similar in principal to a C/C++ union.

Here is an example of a struct that can be used to get to the component bytes of the Int32 data type and the nice thing is that it is two way, you can manipulate the byte values and see the effect on the Int.

  using System.Runtime.InteropServices;

  [StructLayout(LayoutKind.Explicit)]
  struct Int32Converter
  {
    [FieldOffset(0)] public int Value;
    [FieldOffset(0)] public byte Byte1;
    [FieldOffset(1)] public byte Byte2;
    [FieldOffset(2)] public byte Byte3;
    [FieldOffset(3)] public byte Byte4;

    public Int32Converter(int value)
    {
      Byte1 = Byte2 = Byte3 = Byte4 = 0;
      Value = value;
    }

    public static implicit operator Int32(Int32Converter value)
    {
      return value.Value;
    }

    public static implicit operator Int32Converter(int value)
    {
      return new Int32Converter(value);
    }
  }

The above can now be used as follows

 Int32Converter i32 = 256;
 Console.WriteLine(i32.Byte1);
 Console.WriteLine(i32.Byte2);
 Console.WriteLine(i32.Byte3);
 Console.WriteLine(i32.Byte4);

 i32.Byte2 = 2;
 Console.WriteLine(i32.Value);

Of course the immutability police may not be excited about the last possiblity :)

Django download a file

Reference:

In view.py Implement function like,

def download(request, id):
    obj = your_model_name.objects.get(id=id)
    filename = obj.model_attribute_name.path
    response = FileResponse(open(filename, 'rb'))
    return response

What is the difference between Digest and Basic Authentication?

HTTP Basic Access Authentication

  • STEP 1 : the client makes a request for information, sending a username and password to the server in plain text
  • STEP 2 : the server responds with the desired information or an error

Basic Authentication uses base64 encoding(not encryption) for generating our cryptographic string which contains the information of username and password. HTTP Basic doesn’t need to be implemented over SSL, but if you don’t, it isn’t secure at all. So I’m not even going to entertain the idea of using it without.

Pros:

  • Its simple to implement, so your client developers will have less work to do and take less time to deliver, so developers could be more likely to want to use your API
  • Unlike Digest, you can store the passwords on the server in whatever encryption method you like, such as bcrypt, making the passwords more secure
  • Just one call to the server is needed to get the information, making the client slightly faster than more complex authentication methods might be

Cons:

  • SSL is slower to run than basic HTTP so this causes the clients to be slightly slower
  • If you don’t have control of the clients, and can’t force the server to use SSL, a developer might not use SSL, causing a security risk

In Summary – if you have control of the clients, or can ensure they use SSL, HTTP Basic is a good choice. The slowness of the SSL can be cancelled out by the speed of only making one request

Syntax of basic Authentication

Value = username:password
Encoded Value =  base64(Value)
Authorization Value = Basic <Encoded Value> 
//at last Authorization key/value map added to http header as follows
Authorization: <Authorization Value>

HTTP Digest Access Authentication
Digest Access Authentication uses the hashing(i.e digest means cut into small pieces) methodologies to generate the cryptographic result. HTTP Digest access authentication is a more complex form of authentication that works as follows:

  • STEP 1 : a client sends a request to a server
  • STEP 2 : the server responds with a special code (called a i.e. number used only once), another string representing the realm(a hash) and asks the client to authenticate
  • STEP 3 : the client responds with this nonce and an encrypted version of the username, password and realm (a hash)
  • STEP 4 : the server responds with the requested information if the client hash matches their own hash of the username, password and realm, or an error if not

Pros:

  • No usernames or passwords are sent to the server in plaintext, making a non-SSL connection more secure than an HTTP Basic request that isn’t sent over SSL. This means SSL isn’t required, which makes each call slightly faster

Cons:

  • For every call needed, the client must make 2, making the process slightly slower than HTTP Basic
  • HTTP Digest is vulnerable to a man-in-the-middle security attack which basically means it could be hacked
  • HTTP Digest prevents use of the strong password encryption, meaning the passwords stored on the server could be hacked

In Summary, HTTP Digest is inherently vulnerable to at least two attacks, whereas a server using strong encryption for passwords with HTTP Basic over SSL is less likely to share these vulnerabilities.

If you don’t have control over your clients however they could attempt to perform Basic authentication without SSL, which is much less secure than Digest.

RFC 2069 Digest Access Authentication Syntax

Hash1=MD5(username:realm:password)
Hash2=MD5(method:digestURI)
response=MD5(Hash1:nonce:Hash2)

RFC 2617 Digest Access Authentication Syntax

Hash1=MD5(username:realm:password)
Hash2=MD5(method:digestURI)
response=MD5(Hash1:nonce:nonceCount:cnonce:qop:Hash2)
//some additional parameters added 

source and example

In Postman looks as follows:

enter image description here

Note:

  • The Basic and Digest schemes are dedicated to the authentication using a username and a secret.
  • The Bearer scheme is dedicated to the authentication using a token.

Set variable value to array of strings

In SQL you can not have a variable array.
However, the best alternative solution is to use a temporary table.

Is there a MessageBox equivalent in WPF?

The WPF equivalent would be the System.Windows.MessageBox. It has a quite similar interface, but uses other enumerations for parameters and return value.

Error executing command 'ant' on Mac OS X 10.9 Mavericks when building for Android with PhoneGap/Cordova

As an alternative to homebrew, you could download and install macports. Once you have macports, you can use:

sudo port install apache-ant

Convert a python dict to a string and back

If your dictionary isn't too big maybe str + eval can do the work:

dict1 = {'one':1, 'two':2, 'three': {'three.1': 3.1, 'three.2': 3.2 }}
str1 = str(dict1)

dict2 = eval(str1)

print dict1==dict2

You can use ast.literal_eval instead of eval for additional security if the source is untrusted.

IIS7 URL Redirection from root to sub directory

Here it is. Add this code to your web.config file:

<system.webServer>
    <rewrite>
        <rules>
            <rule name="Root Hit Redirect" stopProcessing="true">
                <match url="^$" />
                <action type="Redirect" url="/menu_1/MainScreen.aspx" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

It will do 301 Permanent Redirect (URL will be changed in browser). If you want to have such "redirect" to be invisible (rewrite, internal redirect), then use this rule (the only difference is that "Redirect" has been replaced by "Rewrite"):

<system.webServer>
    <rewrite>
        <rules>
            <rule name="Root Hit Redirect" stopProcessing="true">
                <match url="^$" />
                <action type="Rewrite" url="/menu_1/MainScreen.aspx" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

Host 'xxx.xx.xxx.xxx' is not allowed to connect to this MySQL server

simple way is to login to phpmyadmin with root account , there goto mysql database and select user table , there edit root account and in host field add % wild card . and then through ssh flush privileges

 FLUSH PRIVILEGES;

Bootstrap 3 .col-xs-offset-* doesn't work?

The problem is that you're putting .name class instead of nameclass

Run batch file from Java code

Your code is fine, but the problem is inside the batch file.

You have to show the content of the bat file, your problem is in the paths inside the bat file.

referenced before assignment error in python

My Scenario

def example():
    cl = [0, 1]
    def inner():
        #cl = [1, 2] # access this way will throw `reference before assignment`
        cl[0] = 1 
        cl[1] = 2   # these won't

    inner()

What's the difference between isset() and array_key_exists()?

Answer to an old question as no answer here seem to address the 'warning' problem (explanation follows)

Basically, in this case of checking if a key exists in an array, isset

  • tells if the expression (array) is defined, and the key is set
  • no warning or error if the var is not defined, not an array ...
  • but returns false if the value for that key is null

and array_key_exists

  • tells if a key exists in an array as the name implies
  • but gives a warning if the array parameter is not an array

So how do we check if a key exists which value may be null in a variable

  • that may or may not be an array
  • (or similarly is a multidimensional array for which the key check happens at dim 2 and dim 1 value may not be an array for the 1st dim (etc...))

without getting a warning, without missing the existing key when its value is null (what were the PHP devs thinking would also be an interesting question, but certainly not relevant on SO). And of course we don't want to use @

isset($var[$key]);            // silent but misses null values
array_key_exists($key, $var); // works but warning if $var not defined/array

It seems is_array should be involved in the equation, but it gives a warning if $var is not defined, so that could be a solution:

if (isset($var[$key]) || 
    isset($var) && is_array($var) && array_key_exists($key, $var)) ...

which is likely to be faster if the tests are mainly on non-null values. Otherwise for an array with mostly null values

if (isset($var) && is_array($var) && array_key_exists($key, $var)) ...

will do the work.

How to vertically align <li> elements in <ul>?

I assume that since you're using an XML declaration, you're not worrying about IE or older browsers.

So you can use display:table-cell and display:table-row like so:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <style type="text/css">
        .toolbar ul {
            display:table-row;
        }
        .toolbar ul li
        {
            display: table-cell;
            height: 100px;
            list-style-type: none;
            margin: 10px;
            vertical-align: middle;
        }
        .toolbar ul li a {
            display:table-cell;
            vertical-align: middle;
            height:100px;
            border: solid 1px black;
        }
        .toolbar ul li.button a {
            height:50px;
            border: solid 1px black;
        }
    </style>
</head>
<body>
    <div class="toolbar">
        <ul>
            <li><a href="#">first item<br />
                first item<br />
                first item</a></li>
            <li><a href="#">second item</a></li>
            <li><a href="#">last item</a></li>
            <li class="button"><a href="#">button<br />
                button</a></li>
        </ul>
    </div>
</body>
</html>

Defining an abstract class without any abstract methods

yes, we can declare an abstract class without any abstract method. the purpose of declaring a class as abstract is not to instantiate the class.

so two cases

1) abstract class with abstract methods.

these type of classes, we must inherit a class from this abstract class and must override the abstract methods in our class, ex: GenricServlet class

2) abstract class without abstract methods.

these type of classes, we must inherit a class from this abstract class, ex: HttpServlet class purpose of doing is although you if you don't implement your logic in child class you can get the parent logic

please check the HttpServlet source code

How to loop in excel without VBA or macros?

I was just searching for something similar:

I want to sum every odd row column.

SUMIF has TWO possible ranges, the range to sum from, and a range to consider criteria in.

SUMIF(B1:B1000,1,A1:A1000)

This function will consider if a cell in the B range is "=1", it will sum the corresponding A cell only if it is.

To get "=1" to return in the B range I put this in B:

=MOD(ROWNUM(B1),2)

Then auto fill down to get the modulus to fill, you could put and calculatable criteria here to get the SUMIF or SUMIFS conditions you need to loop through each cell.

Easier than ARRAY stuff and hides the back-end of loops!

creating batch script to unzip a file without additional zip tools

Another approach to this issue could be to create a self extracting executable (.exe) using something like winzip and use this as the install vector rather than the zip file. Similarly, you could use NSIS to create an executable installer and use that instead of the zip.