Programs & Examples On #Mouse cursor

How to move mouse cursor using C#?

First Add a Class called Win32.cs

public class Win32
    public static extern long SetCursorPos(int x, int y);

    public static extern bool ClientToScreen(IntPtr hWnd, ref POINT point);

    public struct POINT
        public int x;
        public int y;

        public POINT(int X, int Y)
            x = X;
            y = Y;

You can use it then like this:

Win32.POINT p = new Win32.POINT(xPos, yPos);

Win32.ClientToScreen(this.Handle, ref p);
Win32.SetCursorPos(p.x, p.y);

How to get the cursor to change to the hand when hovering a <button> tag

 #more {
    font-family:Verdana, Geneva, sans-serif;
    cursor: pointer;

Accessing variables from other functions without using global variables

Another approach is one that I picked up from a Douglas Crockford forum post( Here it is...

Douglas Crockford wrote:

Jul 15 '06

"If you want to retrieve objects by id, then you should use an object, not an array. Since functions are also objects, you could store the members in the function itself."

function objFacility(id, name, adr, city, state, zip) {

    return objFacility[id] = {

        id: id,
        name: name,
        adr: adr,
        city: city,
        state: state,
        zip: zip


objFacility('wlevine', 'Levine', '23 Skid Row', 'Springfield', 'Il', 10010);

"The object can be obtained with"


The objects properties are now accessable from within any other function.

IntelliJ and Tomcat.. Howto..?

Which version of IntelliJ are you using? Note that since last year, IntelliJ exists in two versions:

  • Ultimate Edition, which is the complete IDE
  • Community Edition, which is free but does not support JavaEE developments.

(see differences here)

In case you are using the Community Edition, you will not be able to manage a Tomcat installation.

In case you are using the Ultimate Edition, you can have a look at:

What is the origin of foo and bar?


  • "Foo" and "bar" as metasyntactic variables were popularised by MIT and DEC, the first references are in work on LISP and PDP-1 and Project MAC from 1964 onwards.

  • Many of these people were in MIT's Tech Model Railroad Club, where we find the first documented use of "foo" in tech circles in 1959 (and a variant in 1958).

  • Both "foo" and "bar" (and even "baz") were well known in popular culture, especially from Smokey Stover and Pogo comics, which will have been read by many TMRC members.

  • Also, it seems likely the military FUBAR contributed to their popularity.

The use of lone "foo" as a nonsense word is pretty well documented in popular culture in the early 20th century, as is the military FUBAR. (Some background reading: FOLDOC FOLDOC Jargon File Jargon File Wikipedia RFC3092)

OK, so let's find some references.

STOP PRESS! After posting this answer, I discovered this perfect article about "foo" in the Friday 14th January 1938 edition of The Tech ("MIT's oldest and largest newspaper & the first newspaper published on the web"), Volume LVII. No. 57, Price Three Cents:

On Foo-ism

The Lounger thinks that this business of Foo-ism has been carried too far by its misguided proponents, and does hereby and forthwith take his stand against its abuse. It may be that there's no foo like an old foo, and we're it, but anyway, a foo and his money are some party. (Voice from the bleachers- "Don't be foo-lish!")

As an expletive, of course, "foo!" has a definite and probably irreplaceable position in our language, although we fear that the excessive use to which it is currently subjected may well result in its falling into an early (and, alas, a dark) oblivion. We say alas because proper use of the word may result in such happy incidents as the following.

It was an 8.50 Thermodynamics lecture by Professor Slater in Room 6-120. The professor, having covered the front side of the blackboard, set the handle that operates the lift mechanism, turning meanwhile to the class to continue his discussion. The front board slowly, majestically, lifted itself, revealing the board behind it, and on that board, writ large, the symbols that spelled "FOO"!

The Tech newspaper, a year earlier, the Letter to the Editor, September 1937:

By the time the train has reached the station the neophytes are so filled with the stories of the glory of Phi Omicron Omicron, usually referred to as Foo, that they are easy prey.


It is not that I mind having lost my first four sons to the Grand and Universal Brotherhood of Phi Omicron Omicron, but I do wish that my fifth son, my baby, should at least be warned in advance.

Hopefully yours,

Indignant Mother of Five.

And The Tech in December 1938:

General trend of thought might be best interpreted from the remarks made at the end of the ballots. One vote said, '"I don't think what I do is any of Pulver's business," while another merely added a curt "Foo."

The first documented "foo" in tech circles is probably 1959's Dictionary of the TMRC Language:

FOO: the sacred syllable (FOO MANI PADME HUM); to be spoken only when under inspiration to commune with the Deity. Our first obligation is to keep the Foo Counters turning.

These are explained at FOLDOC. The dictionary's compiler Pete Samson said in 2005:

Use of this word at TMRC antedates my coming there. A foo counter could simply have randomly flashing lights, or could be a real counter with an obscure input.

And from 1996's Jargon File 4.0.0:

Earlier versions of this lexicon derived 'baz' as a Stanford corruption of bar. However, Pete Samson (compiler of the TMRC lexicon) reports it was already current when he joined TMRC in 1958. He says "It came from "Pogo". Albert the Alligator, when vexed or outraged, would shout 'Bazz Fazz!' or 'Rowrbazzle!' The club layout was said to model the (mythical) New England counties of Rowrfolk and Bassex (Rowrbazzle mingled with (Norfolk/Suffolk/Middlesex/Essex)."

A year before the TMRC dictionary, 1958's MIT Voo Doo Gazette ("Humor suplement of the MIT Deans' office") (PDF) mentions Foocom, in "The Laws of Murphy and Finagle" by John Banzhaf (an electrical engineering student):

Further research under a joint Foocom and Anarcom grant expanded the law to be all embracing and universally applicable: If anything can go wrong, it will!

Also 1964's MIT Voo Doo (PDF) references the TMRC usage:

Yes! I want to be an instant success and snow customers. Send me a degree in: ...

  • Foo Counters

  • Foo Jung

Let's find "foo", "bar" and "foobar" published in code examples.

So, Jargon File 4.4.7 says of "foobar":

Probably originally propagated through DECsystem manuals by Digital Equipment Corporation (DEC) in 1960s and early 1970s; confirmed sightings there go back to 1972.

The first published reference I can find is from February 1964, but written in June 1963, The Programming Language LISP: its Operation and Applications by Information International, Inc., with many authors, but including Timothy P. Hart and Michael Levin:

Thus, since "FOO" is a name for itself, "COMITRIN" will treat both "FOO" and "(FOO)" in exactly the same way.

Also includes other metasyntactic variables such as: FOO CROCK GLITCH / POOT TOOR / ON YOU / SNAP CRACKLE POP / X Y Z

I expect this is much the same as this next reference of "foo" from MIT's Project MAC in January 1964's AIM-064, or LISP Exercises by Timothy P. Hart and Michael Levin:

car[((FOO . CROCK) . GLITCH)]


For both "foo" and "bar" together, the earliest reference I could find is from MIT's Project MAC in June 1966's AIM-098, or PDP-6 LISP by none other than Peter Samson:

EXPLODE, like PRIN1, inserts slashes, so (EXPLODE (QUOTE FOO/ BAR)) PRIN1's as (F O O // / B A R) or PRINC's as (F O O / B A R).

Some more recallations.

@Walter Mitty recalled on this site in 2008:

I second the jargon file regarding Foo Bar. I can trace it back at least to 1963, and PDP-1 serial number 2, which was on the second floor of Building 26 at MIT. Foo and Foo Bar were used there, and after 1964 at the PDP-6 room at project MAC.

John V. Everett recalls in 1996:

When I joined DEC in 1966, foobar was already being commonly used as a throw-away file name. I believe fubar became foobar because the PDP-6 supported six character names, although I always assumed the term migrated to DEC from MIT. There were many MIT types at DEC in those days, some of whom had worked with the 7090/7094 CTSS. Since the 709x was also a 36 bit machine, foobar may have been used as a common file name there.

Foo and bar were also commonly used as file extensions. Since the text editors of the day operated on an input file and produced an output file, it was common to edit from a .foo file to a .bar file, and back again.

It was also common to use foo to fill a buffer when editing with TECO. The text string to exactly fill one disk block was IFOO$HXA127GA$$. Almost all of the PDP-6/10 programmers I worked with used this same command string.

Daniel P. B. Smith in 1998:

Dick Gruen had a device in his dorm room, the usual assemblage of B-battery, resistors, capacitors, and NE-2 neon tubes, which he called a "foo counter." This would have been circa 1964 or so.

Robert Schuldenfrei in 1996:

The use of FOO and BAR as example variable names goes back at least to 1964 and the IBM 7070. This too may be older, but that is where I first saw it. This was in Assembler. What would be the FORTRAN integer equivalent? IFOO and IBAR?

Paul M. Wexelblat in 1992:

The earliest PDP-1 Assembler used two characters for symbols (18 bit machine) programmers always left a few words as patch space to fix problems. (Jump to patch space, do new code, jump back) That space conventionally was named FU: which stood for Fxxx Up, the place where you fixed Fxxx Ups. When spoken, it was known as FU space. Later Assemblers ( e.g. MIDAS allowed three char tags so FU became FOO, and as ALL PDP-1 programmers will tell you that was FOO space.

Bruce B. Reynolds in 1996:

On the IBM side of FOO(FU)BAR is the use of the BAR side as Base Address Register; in the middle 1970's CICS programmers had to worry out the various xxxBARs...I think one of those was FRACTBAR...

Here's a straight IBM "BAR" from 1955.

Other early references:

I haven't been able to find any references to foo bar as "inverted foo signal" as suggested in RFC3092 and elsewhere.

Here are a some of even earlier F00s but I think they're coincidences/false positives:

Can an int be null in Java?

As @Glen mentioned in a comment, you basically have two ways around this:

  • use an "out of bound" value. For instance, if "data" can never be negative in normal use, return a negative value to indicate it's invalid.
  • Use an Integer. Just make sure the "check" method returns an Integer, and you assign it to an Integer not an int. Because if an "int" gets involved along the way, the automatic boxing and unboxing can cause problems.

Parse String date in (yyyy-MM-dd) format

I convert String to Date in format ("yyyy-MM-dd") to save into Mysql data base .

 String date ="2016-05-01";
 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
 Date parsed = format.parse(date);
 java.sql.Date sql = new java.sql.Date(parsed.getTime());

sql it's my output in date format

Page Redirect after X seconds wait using JavaScript

<script type="text/javascript">
      function idleTimer() {
    var t;
    //window.onload = resetTimer;
    window.onmousemove = resetTimer; // catches mouse movements
    window.onmousedown = resetTimer; // catches mouse movements
    window.onclick = resetTimer;     // catches mouse clicks
    window.onscroll = resetTimer;    // catches scrolling
    window.onkeypress = resetTimer;  //catches keyboard actions

    function logout() {
        window.location.href = 'logout.php';  //Adapt to actual logout script

   function reload() {
          window.location = self.location.href;  //Reloads the current page

   function resetTimer() {
        t = setTimeout(logout, 1800000);  // time is in milliseconds (1000 is 1 second)
        t= setTimeout(reload, 300000);  // time is in milliseconds (1000 is 1 second)

How to disable gradle 'offline mode' in android studio?

@mikepenz has the right one.

You could just hit SHIFT+COMMAND+A (if you're using OSX and 1.4 android studio) and enter OFFLINE in the search box.

Then you'll see what mike have shown you.

Just deselect offline.

Show/Hide the console window of a C# console application

"Just to hide" you can:

Change the output type from Console Application to Windows Application,

And Instead of Console.Readline/key you can use new ManualResetEvent(false).WaitOne() at the end to keep the app running.

How could I create a function with a completion handler in Swift?

Say you have a download function to download a file from network, and want to be notified when download task has finished.

typealias CompletionHandler = (success:Bool) -> Void

func downloadFileFromURL(url: NSURL,completionHandler: CompletionHandler) {

    // download code.

    let flag = true // true if download succeed,false otherwise

    completionHandler(success: flag)

// How to use it.

downloadFileFromURL(NSURL(string: "url_str")!, { (success) -> Void in

    // When download completes,control flow goes here.
    if success {
        // download success
    } else {
        // download fail

Hope it helps.

Laravel - Route::resource vs Route::controller

For route controller method we have to define only one route. In get or post method we have to define the route separately.

And the resources method is used to creates multiple routes to handle a variety of Restful actions.

Here the Laravel documentation about this.

DateTime.ToString() format that can be used in a filename or extension?

I would use the ISO 8601 format, without separators:


How to use npm with node.exe?

I've just installed 64 bit Node.js v0.12.0 for Windows 8.1 from here. It's about 8MB and since it's an MSI you just double click to launch. It will automatically set up your environment paths etc.

Then to get the command line it's just [Win-Key]+[S] for search and then enter "node.js" as your search phrase.

Choose the Node.js Command Prompt entry NOT the Node.js entry.

Both will given you a command prompt but only the former will actually work. npm is built into that download so then just npm -whatever at prompt.

How to find value using key in javascript dictionary

Arrays in JavaScript don't use strings as keys. You will probably find that the value is there, but the key is an integer.

If you make Dict into an object, this will work:

var dict = {};
var addPair = function (myKey, myValue) {
    dict[myKey] = myValue;
var giveValue = function (myKey) {
    return dict[myKey];

The myKey variable is already a string, so you don't need more quotes.

ToggleButton in C# WinForms

use if command to check status and let operate as a toggle button

private void Protection_ON_OFF_Button_Click(object sender, EventArgs e)

            if (FolderAddButton.Enabled == true)
                FolderAddButton.Enabled = false;
                FolderAddButton.Enabled = true;

scp files from local to remote machine error: no such file or directory

In my case I had to specify the Port Number using

scp -P 2222 username@hostip:/directory/ /localdirectory/

Check if a number has a decimal place/is a whole number

//How about byte-ing it?

Number.prototype.isInt= function(){
 return this== this>> 0;

I always feel kind of bad for bit operators in javascript-

they hardly get any exercise.

Create a string and append text to it

Another way to do this is to add the new characters to the string as follows:

Dim str As String

str = ""

To append text to your string this way:

str = str & "and this is more text"

How to build a RESTful API?

I know that this question is accepted and has a bit of age but this might be helpful for some people who still find it relevant. Although the outcome is not a full RESTful API the API Builder mini lib for PHP allows you to easily transform MySQL databases into web accessible JSON APIs.

Why I can't access remote Jupyter Notebook server?

From your command line, we can see your jupyter server is running normally.The reason you can't access your remote jupyter server is that your remote centos6.5 server's firewall rules block the incoming request from your local browser,i.e. block your tcp:8045 port.
sudo ufw allow 80 # enable http server
sudo ufw allow 443 # enable https server
sudo ufw allow 8045 # enable your tcp:8045 port
then try to access your jupyter again.

Maybe you also need to uncomment and edit that place in your file:

c.NotebookApp.allow_remote_access = True

and even shut down your VPN if you have one.

Location of sqlite database on the device

You can find your database file :


getDatabaseName from class SQLiteOpenHelper

How to create localhost database using mysql?

removing temp files, and did you restart the computer or stop the MySQL service? That's the error message you get when there isn't a MySQL server running.

How to convert numpy arrays to standard TensorFlow format?

You can use tf.pack (tf.stack in TensorFlow 1.0.0) method for this purpose. Here is how to pack a random image of type numpy.ndarray into a Tensor:

import numpy as np
import tensorflow as tf
random_image = np.random.randint(0,256, (300,400,3))
random_image_tensor = tf.pack(random_image)
evaluated_tensor = random_image_tensor.eval()

UPDATE: to convert a Python object to a Tensor you can use tf.convert_to_tensor function.

Get parent of current directory from Python script

import os
import sys
from os.path import dirname, abspath

d = dirname(dirname(abspath(__file__)))
path1 = os.path.dirname(os.path.realpath(sys.argv[0]))
path = os.path.split(os.path.realpath(__file__))[0]

Best Practice to Use HttpClient in Multithreaded Environment

Method A is recommended by httpclient developer community.

Please refer[email protected]/msg02455.html for more details.

Add horizontal scrollbar to html table

I was running into the same issue. I discovered the following solution, which has only been tested in Chrome v31:

table {
    table-layout: fixed;

tbody {
    display: block;
    overflow: scroll;

How do you append to an already existing string?

message="some text"
message="$message add some more"

echo $message

some text add some more

selecting from multi-index pandas

You can use DataFrame.loc:

>>> df.loc[1]


>>> print(df)
A B C        
1 1 1       6
    2       9
  2 1       8
    2      11
2 1 1       7
    2      10
  2 1       9
    2      12

>>> print(df.loc[1])
B C        
1 1       6
  2       9
2 1       8
  2      11

>>> print(df.loc[2, 1])
1       7
2      10

Access HTTP response as string in Go

The method you're using to read the http body response returns a byte slice:

func ReadAll(r io.Reader) ([]byte, error)

official documentation

You can convert []byte to a string by using

body, err := ioutil.ReadAll(resp.Body)
bodyString := string(body)

How can I add the new "Floating Action Button" between two widgets/layouts

Keep it Simple Adding Floating Action Button using TextView by giving rounded xml background. - Add compile to gradle file

  • Use CoordinatorLayout as root view.
  • Before Ending the CoordinatorLayout introduce a textView.
  • Inside Drawable draw a circle.

Circle Xml is

<?xml version="1.0" encoding="utf-8"?>


Layout xml is

<?xml version="1.0" encoding="utf-8"?>






                android:text="Ritesh Kumar Singh"






                android:text="[email protected]"









Click here to se how it Will look like

"Debug certificate expired" error in Eclipse Android plugins

In Windows debug.keystore file is localtes at C:\Users\%Username%\.android folder. This file is created when you install your android SDK and is valid only for a year. After this perod you will start getting this error Error getting final archive: Debug certificate expired on xx/xx/xxxx.

To remove this error simply delete the file and run the program again. In my Eclipse I have enabled Project->Build Automatically so it directly worked but in case you have disabled it you will need to clean the project Project->Clean.. select your project and press ok. Then you will need to build it manually. 3rd click on your project and select Build project.(Note - You will only see this option if you have diabled Build Automatically feature in your Projects Menu)

How can I serve static html from spring boot?

I am using :: Spring Boot :: (v2.0.4.RELEASE) with Spring Framework 5

Spring Boot 2.0 requires Java 8 as a minimum version. Many existing APIs have been updated to take advantage of Java 8 features such as: default methods on interfaces, functional callbacks, and new APIs such as javax.time.

Static Content

By default, Spring Boot serves static content from a directory called /static (or /public or /resources or /META-INF/resources) in the classpath or from the root of the ServletContext. It uses the ResourceHttpRequestHandler from Spring MVC so that you can modify that behavior by adding your own WebMvcConfigurer and overriding the addResourceHandlers method.

By default, resources are mapped on /** and located on /static directory. But you can customize the static loactions programmatically inside our web context configuration class.

@Configuration @EnableWebMvc
public class Static_ResourceHandler implements WebMvcConfigurer {

    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // When overriding default behavior, you need to add default(/) as well as added static paths(/webapp).

        // src/main/resources/static/...
            //.addResourceHandler("/**") // « /css/myStatic.css
            .addResourceHandler("/static/**") // « /static/css/myStatic.css
            .addResourceLocations("classpath:/static/") // Default Static Loaction
            .setCachePeriod( 3600 )
            .resourceChain(true) // 4.1
            .addResolver(new GzipResourceResolver()) // 4.1
            .addResolver(new PathResourceResolver()); //4.1

        // src/main/resources/templates/static/...
            .addResourceHandler("/templates/**") // « /templates/style.css

        // Do not use the src/main/webapp/... directory if your application is packaged as a jar.
            .addResourceHandler("/webapp/**") // « /webapp/css/style.css

        // File located on disk
                    /static         /css/myStatic.css
                    /webapp         /css/style.css
                    /templates      /style.css

In Spring every request will go through the DispatcherServlet. To avoid Static file request through DispatcherServlet(Front contoller) we configure MVC Static content.

As @STEEL said static resources should not go through Controller. Thymleaf is a ViewResolver which takes the view name form controller and adds prefix and suffix to View Layer.

How to use Elasticsearch with MongoDB?

River is a good solution once you want to have a almost real time synchronization and general solution.

If you have data in MongoDB already and want to ship it very easily to Elasticsearch like "one-shot" you can try my package in Node.js

It's using Node.js streams so you can import data from everything what is supporting streams (i.e. MongoDB, PostgreSQL, MySQL, JSON files, etc)

Example for MongoDB to Elasticsearch:

Install packages:

npm install elasticbulk
npm install mongoose
npm install bluebird

Create script i.e. script.js:

const elasticbulk = require('elasticbulk');
const mongoose = require('mongoose');
const Promise = require('bluebird');
mongoose.connect('mongodb://localhost/your_database_name', {
  useMongoClient: true

mongoose.Promise = Promise;

var Page = mongoose.model('Page', new mongoose.Schema({
  title: String,
  categories: Array
}), 'your_collection_name');

// stream query 
var stream = Page.find({
}, {title: 1, _id: 0, categories: 1}).limit(1500000).skip(0).batchSize(500).stream();

elasticbulk.import(stream, {
  index: 'my_index_name',
  type: 'my_type_name',
  host: 'localhost:9200',
.then(function(res) {
  console.log('Importing finished');

Ship your data:

node script.js

It's not extremely fast but it's working for millions of records (thanks to streams).

Chrome dev tools fails to show response even the content returned has header Content-Type:text/html; charset=UTF-8

For the once who receive this error while requesting large JSON data it is, as mentioned by Blauhirn, not a solution to just open the request in new tab if you are using authentication headers and suchlike.

Forturnatly chrome does have other options such as Copy -> Copy as curl. Running this call from the commandoline through cURL will be a exact replicate of the original call.

I added > ~/result.json to the last part of the commando to save the result to a file. Otherwise it will be outputted to the console.

Is it possible to animate scrollTop with jQuery?

You can just use .animate() the scrollTop property, like this:

$("html, body").animate({ scrollTop: "300px" });

Delete all files in directory (but not directory) - one liner solution

I think this will work (based on NonlinearFruit previous answer):

                .filter(item -> !item.getPath().equals("C:/test/ABC/"))


How to send a message to a particular client with

Here is the full solution for Android Client + Socket IO Server (Lot of code but works). There seems to be lack of support for Android and IOS when it comes to socket io which is a tragedy of sorts.

Basically creating a room name by joining user unique id from mysql or mongo then sorting it (done in Android Client and sent to server). So each pair has a unique but common amongst the pair room name. Then just go about chatting in that room.

For quick refernce how room is created in Android

 // Build The Chat Room
        if (Integer.parseInt(mySqlUserId) < Integer.parseInt(toMySqlUserId)) {
            room = "ic" + mySqlUserId + toMySqlUserId;
        } else {
            room = "ic" + toMySqlUserId + mySqlUserId;

The Full Works

Package Json

"dependencies": {
    "express": "^4.17.1",
    "": "^2.3.0"
  "devDependencies": {
    "nodemon": "^2.0.6"

Socket IO Server

app = require('express')()
http = require('http').createServer(app)
io = require('')(http)

app.get('/', (req, res) => {

    res.send('Chat server is running on port 5000')

io.on('connection', (socket) => {

    // console.log('one user connected ' +;

    // Join Chat Room
    socket.on('join', function(data) {

        console.log('======Joined Room========== ');

        // Json Parse String To Access Child Elements
        var messageJson = JSON.parse(data);
        const room =;



    // On Receiving Individual Chat Message (ic_message)
    socket.on('ic_message', function(data) {
        console.log('======IC Message========== ');

        // Json Parse String To Access Child Elements
        var messageJson = JSON.parse(data);
        const room =;
        const message = messageJson.message;


        // Sending to all clients in room except sender'new_msg', {
            msg: message


    socket.on('disconnect', function() {
        console.log('one user disconnected ' +;


http.listen(5000, () => {

    console.log('Node app is running on port 5000')

Android Socket IO Class

public class SocketIOClient {

    public Socket mSocket;

        try {
            mSocket = IO.socket("");
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);

    public Socket getSocket() {
        return mSocket;

Android Activity

public class IndividualChatSocketIOActivity extends AppCompatActivity {

    // Activity Number For Bottom Navigation Menu
    private final Context mContext = IndividualChatSocketIOActivity.this;

    // Strings
    private String mySqlUserId;
    private String toMySqlUserId;

    // Widgets
    private EditText etTextMessage;
    private ImageView ivSendMessage;

    // Socket IO
    SocketIOClient socketIOClient = new SocketIOClient();
    private String room;

    protected void onCreate(@Nullable Bundle savedInstanceState) {

        // Widgets
        etTextMessage = findViewById(;
        ivSendMessage = findViewById(;

        // Get The MySql UserId from Shared Preference
        mySqlUserId = StartupMethods.getFromSharedPreferences("shared",

        // Variables From Individual List Adapter
        Intent intent = getIntent();

        if (intent.hasExtra("to_id")) {

            toMySqlUserId = Objects.requireNonNull(Objects.requireNonNull(getIntent().getExtras())

        // Build The Chat Room
        if (Integer.parseInt(mySqlUserId) < Integer.parseInt(toMySqlUserId)) {
            room = "ic" + mySqlUserId + toMySqlUserId;
        } else {
            room = "ic" + toMySqlUserId + mySqlUserId;







    protected void onPause() {


    private void connectToSocketIO() {

        socketIOClient.mSocket = socketIOClient.getSocket();

    private void joinChat() {

        // Prepare To Send Data Through WebSockets
        JSONObject jsonObject = new JSONObject();

        // Header Fields
        try {



        } catch (JSONException e) {


    private void leaveChat() {

    private void getChatMessages() {

                                  new Emitter.Listener() {
                                      public void call(Object... args) {
                                          try {
                                              JSONObject messageJson = new JSONObject(args[0].toString());
                                              String message = String.valueOf(messageJson);

                                              runOnUiThread(new Runnable() {
                                                  public void run() {
                                          } catch (JSONException e) {

    private void sendChatMessages() {

        ivSendMessage.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                String message = etTextMessage.getText()

                // Prepare To Send Data Thru WebSockets
                JSONObject jsonObject = new JSONObject();

                // Header Fields
                try {



                } catch (JSONException e) {


    public Emitter.Listener onConnect = new Emitter.Listener() {
        public void call(Object... args) {

            runOnUiThread(new Runnable() {
                public void run() {
                                   "Connected To Socket Server",


                  "Socket Connected!");

    private Emitter.Listener onConnectError = new Emitter.Listener() {
        public void call(Object... args) {

            runOnUiThread(new Runnable() {
                public void run() {

    private Emitter.Listener onDisconnect = new Emitter.Listener() {
        public void call(Object... args) {

            runOnUiThread(new Runnable() {
                public void run() {



Android Gradle

// SocketIO
implementation ('') {
    // excluding org.json which is provided by Android
    exclude group: 'org.json', module: 'json'

Remove git mapping in Visual Studio 2015

NoGit extension simply hides the problem, by turning off the Git source control provider each time the solution is loaded. It does this job for every solution that is loaded in Visual Studio.

I solved by opening another project and removing the Git repository from the Local Git Repositories, as Chris C. suggested (View > Team Explorer > Local Git Repositories, select the repository that has to be removed and click Remove). Then I removed .git folder from the project path, as suggested by helix. Reopened the project and finally Git integration was gone!

Java SimpleDateFormat for time zone with a colon separator?


OffsetDateTime.parse( "2010-03-01T00:00:00-08:00" )


The answer by BalusC is correct, but now outdated as of Java 8.


The java.time framework is the successor to both Joda-Time library and the old troublesome date-time classes bundled with the earliest versions of Java (java.util.Date/.Calendar & java.text.SimpleDateFormat).

ISO 8601

Your input data string happens to comply with the ISO 8601 standard.

The java.time classes use ISO 8601 formats by default when parsing/generating textual representations of date-time values. So no need to define a formatting pattern.


The OffsetDateTime class represents a moment on the time line adjusted to some particular offset-from-UTC. In your input, the offset is 8 hours behind UTC, commonly used on much of the west coast of North America.

OffsetDateTime odt = OffsetDateTime.parse( "2010-03-01T00:00:00-08:00" );

You seem to want the date-only, in which case use the LocalDate class. But keep in mind you are discarding data, (a) time-of-day, and (b) the time zone. Really, a date has no meaning without the context of a time zone. For any given moment the date varies around the world. For example, just after midnight in Paris is still “yesterday” in Montréal. So while I suggest sticking with date-time values, you can easily convert to a LocalDate if you insist.

LocalDate localDate = odt.toLocalDate();

Time Zone

If you know the intended time zone, apply it. A time zone is an offset plus the rules to use for handling anomalies such as Daylight Saving Time (DST). Applying a ZoneId gets us a ZonedDateTime object.

ZoneId zoneId = ZoneId.of( "America/Los_Angeles" );
ZonedDateTime zdt = odt.atZoneSameInstant( zoneId );

Generating strings

To generate a string in ISO 8601 format, call toString.

String output = odt.toString();

If you need strings in other formats, search Stack Overflow for use of the java.util.format package.

Converting to java.util.Date

Best to avoid java.util.Date, but if you must, you can convert. Call the new methods added to the old classes such as java.util.Date.from where you pass an Instant. An Instant is a moment on the timeline in UTC. We can extract an Instant from our OffsetDateTime.

java.util.Date utilDate = java.util.Date( odt.toInstant() );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to make external HTTP requests with Node.js

You can use the built-in http module to do an http.request().

However if you want to simplify the API you can use a module such as superagent

Live video streaming using Java?

You can do this today in Java with the Red5 media server from Flash. If you want to also decode and encode video in Java, you can use the Xuggler project.

How to horizontally center a floating element of a variable width?

You can use fit-content value for width.

#wrap {
  width: -moz-fit-content;
  width: -webkit-fit-content;
  width: fit-content;
  margin: auto;   

Note: It works only in latest browsers.

Easiest way to mask characters in HTML(5) text input

  1. Basic validation can be performed by choosing the type attribute of input elements. For example: <input type="email" /> <input type="URL" /> <input type="number" />

  2. using pattern attribute like: <input type="text" pattern="[1-4]{5}" />

  3. required attribute <input type="text" required />

  4. maxlength: <input type="text" maxlength="20" />

  5. min & max: <input type="number" min="1" max="4" />

Running script upon login mac

tl;dr: use OSX's native process launcher and manager, launchd.

To do so, make a launchctl daemon. You'll have full control over all aspects of the script. You can run once or keep alive as a daemon. In most cases, this is the way to go.

  1. Create a .plist file according to the instructions in the Apple Dev docs here or more detail below.
  2. Place in ~/Library/LaunchAgents
  3. Log in (or run manually via launchctl load [filename.plist])

For more on launchd, the wikipedia article is quite good and describes the system and its advantages over other older systems.

Here's the specific plist file to run a script at login.

Updated 2017/09/25 for OSX El Capitan and newer (credit to José Messias Jr):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "">
<plist version="1.0">

Replace the <string> after the Program key with your desired command (note that any script referenced by that command must be executable: chmod a+x /path/to/executable/ to ensure it is for all users).

Save as ~/Library/LaunchAgents/com.user.loginscript.plist

Run launchctl load ~/Library/LaunchAgents/com.user.loginscript.plist and log out/in to test (or to test directly, run launchctl start com.user.loginscript)

Tail /var/log/system.log for error messages.

The key is that this is a User-specific launchd entry, so it will be run on login for the given user. System-specific launch daemons (placed in /Library/LaunchDaemons) are run on boot.

If you want a script to run on login for all users, I believe LoginHook is your only option, and that's probably the reason it exists.

How to convert this var string to URL in Swift

In swift 3 use:

let url = URL(string: "Whatever url you have(eg:")

Java converting int to hex and back again

Java's parseInt method is actally a bunch of code eating "false" hex : if you want to translate -32768, you should convert the absolute value into hex, then prepend the string with '-'.

There is a sample of file :

public static int parseInt(String s, int radix)

The description is quite explicit :

* Parses the string argument as a signed integer in the radix 
* specified by the second argument. The characters in the string 
* parseInt("0", 10) returns 0
* parseInt("473", 10) returns 473
* parseInt("-0", 10) returns 0
* parseInt("-FF", 16) returns -255

Algorithm/Data Structure Design Interview Questions

Follow up any question like this with: "How could you improve this code so the developer who maintains it can figure out how it works easily?"

How to make html <select> element look like "disabled", but pass values?

My solution was to create a disabled class in CSS:

.disabled {
    pointer-events: none;
    cursor: not-allowed;

and then your select would be:

<select name="sel" class="disabled">

The user would be unable to pick any values but the select value would still be passed on form submission.

Convert UTC Epoch to local date

The simplest solution I've found to this, is:

var timestamp =, // returns milliseconds since epoch time
    normalisedTime = new Date(timestamp);

Notice this doesn't have the * 1000 at the end of new Date(timestamp) statement as this (for me anyway!) always seems to give out the wrong date, ie instead of giving the year 2019 it gives the year as 51015, so just bear that in mind.

What is the best way to conditionally apply a class?

I faced a similar problem recently and decided to just create a conditional filter:

  angular.module('myFilters', []).
     * "if" filter
     * Simple filter useful for conditionally applying CSS classes and decouple
     * view from controller 
    filter('if', function() {
      return function(input, value) {
        if (typeof(input) === 'string') {
          input = [input, ''];
        return value? input[0] : input[1];

It takes a single argument, which is either a 2-element array or a string, which gets turned into an array that is appended an empty string as the second element:

<li ng-repeat="item in products | filter:search | orderBy:orderProp |
  page:pageNum:pageLength" ng-class="'opened'|if:isOpen(item)">

fork and exec in bash

How about:

(sleep 5; echo "Hello World") &

CSS - Make divs align horizontally

This seems close to what you want:

#foo {_x000D_
  background: red;_x000D_
  max-height: 100px;_x000D_
  overflow-y: hidden;_x000D_
.bar {_x000D_
  background: blue;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  float: left;_x000D_
  margin: 1em;_x000D_
<div id="foo">_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_

Javascript select onchange='this.form.submit()'

If you're using jQuery, it's as simple as this:


CMD command to check connected USB devices

You can use the wmic command:

wmic path CIM_LogicalDevice where "Description like 'USB%'" get /value

Change first commit of project with Git?

As stated in 1.7.12 Release Notes, you may use

$ git rebase -i --root

What does ON [PRIMARY] mean?

To add a very important note on what Mark S. has mentioned in his post. In the specific SQL Script that has been mentioned in the question you can NEVER mention two different file groups for storing your data rows and the index data structure.

The reason why is due to the fact that the index being created in this case is a clustered Index on your primary key column. The clustered index data and the data rows of your table can NEVER be on different file groups.

So in case you have two file groups on your database e.g. PRIMARY and SECONDARY then below mentioned script will store your row data and clustered index data both on PRIMARY file group itself even though I've mentioned a different file group ([SECONDARY]) for the table data. More interestingly the script runs successfully as well (when I was expecting it to give an error as I had given two different file groups :P). SQL Server does the trick behind the scene silently and smartly.

CREATE TABLE [dbo].[be_Categories](
    [CategoryID] [uniqueidentifier] ROWGUIDCOL  NOT NULL CONSTRAINT [DF_be_Categories_CategoryID]  DEFAULT (newid()),
    [CategoryName] [nvarchar](50) NULL,
    [Description] [nvarchar](200) NULL,
    [ParentID] [uniqueidentifier] NULL,
    [CategoryID] ASC

NOTE: Your index can reside on a different file group ONLY if the index being created is non-clustered in nature.

The below script which creates a non-clustered index will get created on [SECONDARY] file group instead when the table data already resides on [PRIMARY] file group:

CREATE NONCLUSTERED INDEX [IX_Categories] ON [dbo].[be_Categories]
    [CategoryName] ASC

You can get more information on how storing non-clustered indexes on a different file group can help your queries perform better. Here is one such link.

Reading from file using read() function

fgets would work for you. here is very good documentation on this :-

If you don't want to use fgets, following method will work for you :-

int readline(FILE *f, char *buffer, size_t len)
   char c; 
   int i;

   memset(buffer, 0, len);

   for (i = 0; i < len; i++)
      int c = fgetc(f); 

      if (!feof(f)) 
         if (c == '\r')
            buffer[i] = 0;
         else if (c == '\n')
            buffer[i] = 0;

            return i+1;
            buffer[i] = c; 
         //fprintf(stderr, "read_line(): recv returned %d\n", c);
         return -1; 

   return -1; 

Append data to a POST NSURLRequest

All the changes to the NSMutableURLRequest must be made before calling NSURLConnection.

I see this problem as I copy and paste the code above and run TCPMon and see the request is GET instead of the expected POST.

NSURL *aUrl = [NSURL URLWithString:@""];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl

[request setHTTPMethod:@"POST"];
NSString *postString = @"company=Locassa&quality=AWESOME!";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request 

How to add new line into txt file

var Line = textBox1.Text + "," + textBox2.Text;

File.AppendAllText(@"C:\Documents\m2.txt", Line + Environment.NewLine);

How to run Pip commands from CMD

In my case I was trying to install Flask. I wanted to run pip install Flask command. But when I open command prompt it I goes to C:\Users[user]>. If you give here it will say pip is not recognized. I did below steps

On your desktop right click Computer and select Properties

Select Advanced Systems Settings

In popup which you see select Advanced tab and then click Environment Variables

In popup double click PATH and from popup copy variable value for variable name PATH and paste the variable value in notepad or so and look for an entry for Python.

In my case it was C:\Users\[user]\AppData\Local\Programs\Python\Python36-32

Now in my command prompt i moved to above location and gave pip install Flask

enter image description here

Navigation bar show/hide

First read the the section in the View Controller Programming Guide for iOS about 'Adopting a Full-Screen Layout for Navigation Views' and the section about the same for Custom Views. If you are trying to do something like the then you are probably using a scroll view. Note the comment that Navigation bars automatically add a scroll content inset to your scroll view to account for the height of the navigation bar (and status bar) so you have to reset the contentInset property of your scroll view back to zero (UIEdgeInsetsZero) right after setting up the initial state of the navigationBar and before the view appears.

Then if you have a single tap that toggles the navigationBar and/or status bar to show or hide, you need to do two things in you toggling method. The first seems to be to save the scroll view's contentOffset property before changing the NavigationBar hidden property and restore your saved value to contentOffset right afterward. And second to again zero out the contentInset property to UIEdgeInsetsZero after changing the navigationBarHidden property. Also, if you are toggling the status bar, you need to change its state before you change the navigationBar's state.

Using an HTTP PROXY - Python

I encountered this on jython client. The server was only talking TLS and the client using SSL context."SSL")

Once the client was to TLS, things started working.

Easiest way to ignore blank lines when reading a file in Python

You could use list comprehension:

with open("names", "r") as f:
    names_list = [line.strip() for line in f if line.strip()]

Updated: Removed unnecessary readlines().

To avoid calling line.strip() twice, you can use a generator:

names_list = [l for l in (line.strip() for line in f) if l]

"401 Unauthorized" on a directory

Another simple fix I found was to delete the local IIS site (from within IIS Manager) and then re-create the virtual directory from the "Properties" of your web project in Visual Studio.

Python: download a file from an FTP server

Try using the wget library for python. You can find the documentation for it here.

import wget
link = ''

ORA-12516, TNS:listener could not find available handler

You opened a lot of connections and that's the issue. I think in your code, you did not close the opened connection.

A database bounce could temporarily solve, but will re-appear when you do consecutive execution. Also, it should be verified the number of concurrent connections to the database. If maximum DB processes parameter has been reached this is a common symptom.

Courtesy of this thread:

ConcurrentModificationException for ArrayList

We can use concurrent collection classes to avoid ConcurrentModificationException while iterating over a collection, for example CopyOnWriteArrayList instead of ArrayList.

Check this post for ConcurrentHashMap

How to programmatically set SelectedValue of Dropdownlist when it is bound to XmlDataSource

Have you tried, after calling DataBind on your DropDownList, to do something like ddl.SelectedIndex = 0 ?

How to change the font and font size of an HTML input tag?

in your css :

 #txtComputer {
      font-size: 24px;

You can style an input entirely (background, color, etc.) and even use the hover event.

Pandas DataFrame: replace all values in a column, based on condition

You need to select that column:

In [41]:
df.loc[df['First Season'] > 1990, 'First Season'] = 1

                 Team  First Season  Total Games
0      Dallas Cowboys          1960          894
1       Chicago Bears          1920         1357
2   Green Bay Packers          1921         1339
3      Miami Dolphins          1966          792
4    Baltimore Ravens             1          326
5  San Franciso 49ers          1950         1003

So the syntax here is:

df.loc[<mask>(here mask is generating the labels to index) , <optional column(s)> ]

You can check the docs and also the 10 minutes to pandas which shows the semantics


If you want to generate a boolean indicator then you can just use the boolean condition to generate a boolean Series and cast the dtype to int this will convert True and False to 1 and 0 respectively:

In [43]:
df['First Season'] = (df['First Season'] > 1990).astype(int)

                 Team  First Season  Total Games
0      Dallas Cowboys             0          894
1       Chicago Bears             0         1357
2   Green Bay Packers             0         1339
3      Miami Dolphins             0          792
4    Baltimore Ravens             1          326
5  San Franciso 49ers             0         1003

Date constructor returns NaN in IE, but works in Firefox and Chrome

Try out using getDate feature of datepicker.

$.datepicker.formatDate('yy-mm-dd',new Date(pField.datepicker("getDate")));

What is a Y-combinator?

Here is a JavaScript implementation of the Y-Combinator and the Factorial function (from Douglas Crockford's article, available at:

function Y(le) {
    return (function (f) {
        return f(f);
    }(function (f) {
        return le(function (x) {
            return f(f)(x);

var factorial = Y(function (fac) {
    return function (n) {
        return n <= 2 ? n : n * fac(n - 1);

var number120 = factorial(5);

Show an image preview before upload

Without FileReader, we can use URL.createObjectURL method to get the DOMString that represents the object ( our image file ).

Don't forget to validate image extension.

<input type="file" id="files" multiple />
<div class="image-preview"></div>
let file_input = document.querySelector('#files');
let image_preview = document.querySelector('.image-preview');

const handle_file_preview = (e) => {
  let files =;
  let length = files.length;

  for(let i = 0; i < length; i++) {
      let image = document.createElement('img');
      // use the DOMstring for source
      image.src = window.URL.createObjectURL(files[i]);

file_input.addEventListener('change', handle_file_preview);

Find a file by name in Visual Studio Code

Press Ctl+T will open a search box. Delete # symbol and enter your file name.

Accessing MP3 metadata with Python

The first answer that uses eyed3 is outdated so here is an updated version of it.

Reading tags from an mp3 file:

 import eyed3

 audiofile = eyed3.load("some/file.mp3")

An example from the website to modify tags:

 import eyed3

 audiofile = eyed3.load("some/file.mp3")
 audiofile.tag.artist = u"Integrity"
 audiofile.tag.album = u"Humanity Is The Devil"
 audiofile.tag.album_artist = u"Integrity"
 audiofile.tag.title = u"Hollow"
 audiofile.tag.track_num = 2

An issue I encountered while trying to use eyed3 for the first time had to do with an import error of libmagic even though it was installed. To fix this install the magic-bin whl from here

cannot find zip-align when publishing app

On a Mac, I did the following:

  1. Find it on o/s (I had already downloaded build tools for 19 and 20)

  2. Press Ctrl-Open to allow apps from the internet

  3. Move it from sdk/build-tools/android-4.4W folder to sdk/tools/. Whew.

Failed to allocate memory: 8

In my case:

  • Using built in WXGA720 to simulate 720p device, always got this error
  • Manually set AVD resolution to 720 x 1280, works for me

hope it helps~

difference between new String[]{} and new String[] in java


  • An array variable has to be typed T[]
    (note that T can be an arry type itself -> multidimensional arrays)
  • The length of the array must be determined either by:
    • giving it an explicit size
      (can be int constant or int expression, see n below)
    • initializing all the values inside the array
      (length is implicitly calculated from given elements)
  • Any variable that is typed T[] has one read-only field: length and an index operator [int] for reading/writing data at certain indices.


1. String[] array= new String[]{}; what is the use of { } here ?

It initializes the array with the values between { }. In this case 0 elements, so array.length == 0 and array[0] throws IndexOutOfBoundsException: 0.

2. what is the diff between String array=new String[]; and String array=new String[]{};

The first won't compile for two reasons while the second won't compile for one reason. The common reason is that the type of the variable array has to be an array type: String[] not just String. Ignoring that (probably just a typo) the difference is:

new String[]   // size not known, compile error
new String[]{} // size is known, it has 0 elements, listed inside {}
new String[0]  // size is known, it has 0 elements, explicitly sized

3. when am writing String array=new String[10]{}; got error why ?

(Again, ignoring the missing [] before array) In this case you're over-eager to tell Java what to do and you're giving conflicting data. First you tell Java that you want 10 elements for the array to hold and then you're saying you want the array to be empty via {}. Just make up your mind and use one of those - Java thinks.

help me i am confused


String[] noStrings = new String[0];
String[] noStrings = new String[] { };
String[] oneString = new String[] { "atIndex0" };
String[] oneString = new String[1];
String[] oneString = new String[] { null }; // same as previous
String[] threeStrings = new String[] { "atIndex0", "atIndex1", "atIndex2" };
String[] threeStrings = new String[] { "atIndex0", null, "atIndex2" }; // you can skip an index
String[] threeStrings = new String[3];
String[] threeStrings = new String[] { null, null, null }; // same as previous
int[] twoNumbers = new int[2];
int[] twoNumbers = new int[] { 0, 0 }; // same as above
int[] twoNumbers = new int[] { 1, 2 }; // twoNumbers.length == 2 && twoNumbers[0] == 1 && twoNumbers[1] == 2
int n = 2;
int[] nNumbers = new int[n]; // same as [2] and { 0, 0 }
int[] nNumbers = new int[2*n]; // same as new int[4] if n == 2

(Here, "same as" means it will construct the same array.)

Getting Checkbox Value in ASP.NET MVC 4

If working with FormCollection rather than model, the assignment can be as simple as:

MyModel.Remember = fields["Remember"] != "false";

Function for Factorial in Python

For performance reasons, please do not use recursion. It would be disastrous.

def fact(n, total=1):
    while True:
        if n == 1:
            return total
        n, total = n - 1, total * n

Check running results'fact(126000)')

4 function calls in 5.164 seconds

Using the stack is convenient(like recursive call), but it comes at a cost: storing detailed information can take up a lot of memory.

If the stack is high, it means that the computer stores a lot of information about function calls.

The method only takes up constant memory(like iteration).

Or Using for loop

def fact(n):
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result

Check running results'fact(126000)')

4 function calls in 4.708 seconds

Or Using builtin function math

def fact(n):
    return math.factorial(n)

Check running results'fact(126000)')

5 function calls in 0.272 seconds

Is there a way I can capture my iPhone screen as a video?

I've continued to research this item myself, and it does appear to remain beyond us at this point.

I even tried buying a Apple Composite AV Cable, but it doesn't capture screen, just video playing like YouTube, etc.

So I decided to go with the iShowU path and that has worked out well so far.

Thanks Guys!

Can someone explain the dollar sign in Javascript?

A '$' in a variable means nothing special to the interpreter, much like an underscore.

From what I've seen, many people using jQuery (which is what your example code looks like to me) tend to prefix variables that contain a jQuery object with a $ so that they are easily identified and not mixed up with, say, integers.

The dollar sign function $() in jQuery is a library function that is frequently used, so a short name is desirable.

CodeIgniter query: How to move a column value to another column in the same row and save the current time in the original column?

Yes, this is possible and I would like to provide a slight alternative to Rajeev's answer that does not pass a php-generated datetime formatted string to the query.

The important distinction about how to declare the values to be SET in the UPDATE query is that they must not be quoted as literal strings.

To prevent CodeIgniter from doing this "favor" automatically, use the set() method with a third parameter of false.

$userId = 444;
$this->db->set('Last', 'Current', false);
$this->db->set('Current', 'NOW()', false);
$this->db->where('Id', $userId);
// return $this->db->get_compiled_update('Login');  // uncomment to see the rendered query
return $this->db->affected_rows();  // this is expected to return the integer: 1

The generated query (depending on your database adapter) would be like this:

UPDATE `Login` SET Last = Current, Current = NOW() WHERE `Id` = 444

Demonstrated proof that the query works:

In this case, Last and Current ARE MySQL Keywords, but they are not Reserved Keywords, so they don't need to be backtick-wrapped.

If your precise query needs to have properly quoted identifiers (table/column names), then there is always protectIdentifiers().

"Default Activity Not Found" on Android Studio upgrade

In case your application doesn't have an Activity (only a service for example), change the run/debug configuration 'Launch' option to Nothing.

How do I know the script file name in a Bash script?

These answers are correct for the cases they state but there is a still a problem if you run the script from another script using the 'source' keyword (so that it runs in the same shell). In this case, you get the $0 of the calling script. And in this case, I don't think it is possible to get the name of the script itself.

This is an edge case and should not be taken TOO seriously. If you run the script from another script directly (without 'source'), using $0 will work.

Call to undefined function curl_init().?

You have to enable curl with php.

Here is the instructions for same

MSBUILD : error MSB1008: Only one project can be specified

For me adding the path to the solution file in double quotes solved the issue. One of the folders in the path had a blank space in the name and this caused it to consider 2 solution files instead of one. I executed in the following was and it worked.

MSBuild.exe "C:\Folder Name With Space\Project\project.sln"

How to get index of an item in java.util.Set

you can extend LinkedHashSet adding your desired getIndex() method. It's 15 minutes to implement and test it. Just go through the set using iterator and counter, check the object for equality. If found, return the counter.

Remove First and Last Character C++

Well, you could erase() the first character too (note that erase() modifies the string):

m_VirtualHostName.erase(0, 1);
m_VirtualHostName.erase(m_VirtualHostName.size() - 1);

But in this case, a simpler way is to take a substring:

m_VirtualHostName = m_VirtualHostName.substr(1, m_VirtualHostName.size() - 2);

Be careful to validate that the string actually has at least two characters in it first...

MySQL: Grant **all** privileges on database

To access from remote server to mydb database only

GRANT ALL PRIVILEGES ON mydb.* TO 'root'@'';

To access from remote server to all databases.


Exporting results of a Mysql query to excel?

The quick and dirty way I use to export mysql output to a file is

$ mysql <database_name> --tee=<file_path>

and then use the exported output (which you can find in <file_path>) wherever I want.

Note that this is the only way you have in order to avoid databases running using the secure-file-priv option, which prevents the usage of INTO OUTFILE suggested in the previous answers:

ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

How can I troubleshoot Python "Could not find platform independent libraries <prefix>"

My pycharm ce had the same error, was easy to fix it, if someone has that error, just uninstall and delete the folder, use ctrl+h if you can't find the folder in your documents, install the software again and should work again.

Remember to save the scratches folder before erasing the pycharm folder.

Django: How can I call a view function from template?

Assuming that you want to get a value from the user input in html textbox whenever the user clicks 'Click' button, and then call a python function (mypythonfunction) that you wrote inside Note that "btn" class is defined in a css file.

inside templateHTML.html:

<form action="#" method="get">
 <input type="text" value="8" name="mytextbox" size="1"/>
 <input type="submit" class="btn" value="Click" name="mybtn">


import mypythoncode

def request_page(request):
    mypythoncode.mypythonfunction( int(request.GET.get('mytextbox')) )
return render(request,'myApp/templateHTML.html')

How do I make entire div a link?


<a href="foo.html"><div class="xyz"></div></a>

works in browsers, even though it violates current HTML specifications. It is permitted according to HTML5 drafts.

When you say that it does not work, you should explain exactly what you did (including jsfiddle code is a good idea), what you expected, and how the behavior different from your expectations.

It is unclear what you mean by “all the content in that div is in the css”, but I suppose it means that the content is really empty in HTML markup and you have CSS like

.xyz:before { content: "Hello world"; }

The entire block is then clickable, with the content text looking like link text there. Isn’t this what you expected?

How can I check if a key exists in a dictionary?

Another method is has_key() (if still using Python 2.X):

>>> a={"1":"one","2":"two"}
>>> a.has_key("1")

HTML5 : Iframe No scrolling?

In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see for other changes. Well and the CSS solution:

CSS solution:

HTML4's scrolling="no" is kind of an alias of the CSS's overflow: hidden, to do so it is important to set size attributes width/height:

  width: 250px; /*or any other size*/
  height: 300px; /*or any other size*/
  overflow: hidden;

Add this class to your iframe and you're done:

<iframe src="" class="noScrolling"></iframe>

! IMPORTANT NOTE ! : overflow: hidden for <iframe> is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no" and overflow:hidden at the same time :)

UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors

How to set selected item of Spinner by value, not by position?

Based on Merrill's answer, I came up with this single line solution... it's not very pretty, but you can blame whoever maintains the code for Spinner for neglecting to include a function that does this for that.


You'll get a warning about how the cast to a ArrayAdapter<String> is unchecked... really, you could just use an ArrayAdapter as Merrill did, but that just exchanges one warning for another.

CSS3 Transparency + Gradient

This is some really cool stuff! I needed pretty much the same, but with horizontal gradient from white to transparent. And it is working just fine! Here ist my code:

        /* webkit example */
        background-image: -webkit-gradient(
          linear, right top, left top, from(rgba(255, 255, 255, 1.0)),
          to(rgba(255, 255, 255, 0))

        /* mozilla example - FF3.6+ */
        background-image: -moz-linear-gradient(
          right center,
          rgba(255, 255, 255, 1.0) 20%, rgba(255, 255, 255, 0) 95%

        /* IE 5.5 - 7 */
        filter: progid:DXImageTransform.Microsoft.gradient(
          gradientType=1, startColor=0, endColorStr=#FFFFFF

        /* IE8 uses -ms-filter for whatever reason... */
        -ms-filter: progid:DXImageTransform.Microsoft.gradient(
          gradientType=1, startColor=0, endColoStr=#FFFFFF

How to convert a number to string and vice versa in C++

#include <iostream>
#include <string.h>
using namespace std;
int main() {
   string s="000101";
   int a = stoi(s);
   return 0;


  • 000101
  • 101
  • 1011

How to use graphics.h in codeblocks?

  1. First download WinBGIm from Extract it.
  2. Copy graphics.h and winbgim.h files in include folder of your compiler directory
  3. Copy libbgi.a to lib folder of your compiler directory
  4. In code::blocks open Settings >> Compiler and debugger >>linker settings click Add button in link libraries part and browse and select libbgi.a file
  5. In right part (i.e. other linker options) paste commands -lbgi -lgdi32 -lcomdlg32 -luuid -loleaut32 -lole32
  6. Click OK

For detail information follow this link.

CSS to make HTML page footer stay at bottom of the page with a minimum height, but not overlap the page

I have used in my many projects and never got any single issue :)

for your reference, Code are in snippet

* {_x000D_
 margin: 0;_x000D_
html, body {_x000D_
 height: 100%;_x000D_
.wrapper {_x000D_
 min-height: 100%;_x000D_
 height: auto !important; /* This line and the next line are not necessary unless you need IE6 support */_x000D_
 height: 100%;_x000D_
 margin: 0 auto -50px; /* the bottom margin is the negative value of the footer's height */_x000D_
.footer, .push {_x000D_
 height: 50px; /* .push must be the same height as .footer */_x000D_
<meta charset="utf-8">_x000D_
<title>Untitled Document</title>_x000D_
  <div class="wrapper">_x000D_
    Content Area_x000D_
  <div class="push">_x000D_
  <div class="footer">_x000D_
    Footer Area_x000D_

Compile/run assembler in Linux?

There is also FASM for Linux.

format ELF executable

segment readable executable

mov eax, 4
mov ebx, 1
mov ecx, hello_msg
mov edx, hello_size
int 80h

mov eax, 1
mov ebx, 0
int 80h

segment readable writeable

hello_msg db "Hello World!",10,0
hello_size = $-hello_msg

It comiles with

fasm hello.asm hello

Palindrome check in Javascript

25x faster than the standard answer

function isPalindrome(s,i) {
 return (i=i||0)<0||i>=s.length>>1||s[i]==s[s.length-1-i]&&isPalindrome(s,++i);

use like:


as it defines "i" itself


This is ~25 times faster than the standard answer below.

function checkPalindrome(str) {
  return str == str.split('').reverse().join('');


View console for performance results.

Although the solution is difficult to read and maintain, I would recommend understanding it to demonstrate non-branching with recursion and bit shifting to impress your next interviewer.


The || and && are used for control flow like "if" "else". If something left of || is true, it just exits with true. If something is false left of || it must continue. If something left of && is false, it exits as false, if something left of a && is true, it must continue. This is considered "non-branching" as it does not need if-else interupts, rather its just evaluated.

1. Used an initializer not requiring "i" to be defined as an argument. Assigns "i" to itself if defined, otherwise initialize to 0. Always is false so next OR condition is always evaluated.

(i = i || 0) < 0

2. Checks if "i" went half way but skips checking middle odd char. Bit shifted here is like division by 2 but to lowest even neighbor division by 2 result. If true then assumes palindrome since its already done. If false evaluates next OR condition.

i >= s.length >> 1

3. Compares from beginning char and end char according to "i" eventually to meet as neighbors or neighbor to middle char. If false exits and assumes NOT palindrome. If true continues on to next AND condition.

s[i] == s[s.length-1-i]

4. Calls itself again for recursion passing the original string as "s". Since "i" is defined for sure at this point, it is pre-incremented to continue checking the string's position. Returns boolean value indicating if palindrome.



A simple for loop is still about twice as fast as my fancy answer (aka KISS principle)

function fastestIsPalindrome(str) {
  var len = Math.floor(str.length / 2);
  for (var i = 0; i < len; i++)
    if (str[i] !== str[str.length - i - 1])
      return false;
  return true;

Could not read JSON: Can not deserialize instance of hello.Country[] out of START_OBJECT token

Another solution:

public class CountryInfoResponse {
  private List<Object> geonames;

Usage of a generic Object-List solved my problem, as there were other Datatypes like Boolean too.

How to place the cursor (auto focus) in text box when a page gets loaded without javascript support?

Just add autofocus in first input or textarea.

<input type="text" name="name" id="xax" autofocus="autofocus" />

Http Basic Authentication in Java using HttpClient?

Ok so this one works. Just in case anybody wants it, here's the version that works for me :)

import java.util.Base64;

public class HttpBasicAuth {

    public static void main(String[] args) {

        try {
            URL url = new URL ("http://ip:port/login");
            String encoding = Base64.getEncoder().encodeToString(("test1:test1").getBytes(?"UTF??-8"?));

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty  ("Authorization", "Basic " + encoding);
            InputStream content = (InputStream)connection.getInputStream();
            BufferedReader in   = 
                new BufferedReader (new InputStreamReader (content));
            String line;
            while ((line = in.readLine()) != null) {
        } catch(Exception e) {



Could not open input file: composer.phar

This is how it worked for me:

  • Make sure composer is installed without no errors.

  • Open "System Properties" on windows and go to the "Advanced" tab. (You can just press the windows button on your keyboard and type in "Edit the system environment variables`

  • "Environment variables"

  • Under "System variables" Edit "PATH"

  • Click on "New".

  • Type in: C:\ProgramData\ComposerSetup\bin\composer.phar

  • Close all folders & CMDs + restart you WAMP server.

  • Go to whatever directory you want to install a package in and type in

    composer.phar create-project slim/slim-skeleton

for example.

How to check for null/empty/whitespace values with a single test?

This phpMyAdmin query is returning those rows, that are NOT null or empty or just whitespaces:

SELECT * FROM `table_name` WHERE NOT ((`column_name` IS NULL) OR (TRIM(`column_name`) LIKE ''))

if you want to select rows that are null/empty/just whitespaces just remove NOT.

How is returning the output of a function different from printing it?

The print statement will output an object to the user. A return statement will allow assigning the dictionary to a variable once the function is finished.

>>> def foo():
...     print "Hello, world!"
>>> a = foo()
Hello, world!
>>> a
>>> def foo():
...     return "Hello, world!"
>>> a = foo()
>>> a
'Hello, world!'

Or in the context of returning a dictionary:

>>> def foo():
...     print {'a' : 1, 'b' : 2}
>>> a = foo()
{'a': 1, 'b': 2}
>>> a
>>> def foo():
...     return {'a' : 1, 'b' : 2}
>>> a = foo()
>>> a
{'a': 1, 'b': 2}

(The statements where nothing is printed out after a line is executed means the last statement returned None)

What is logits, softmax and softmax_cross_entropy_with_logits?

One more thing that I would definitely like to highlight as logit is just a raw output, generally the output of last layer. This can be a negative value as well. If we use it as it's for "cross entropy" evaluation as mentioned below:

-tf.reduce_sum(y_true * tf.log(logits))

then it wont work. As log of -ve is not defined. So using o softmax activation, will overcome this problem.

This is my understanding, please correct me if Im wrong.

Should Gemfile.lock be included in .gitignore?

No Gemfile.lock means:

  • new contributors cannot run tests because weird things fail, so they won't contribute or get failing PRs ... bad first experience.
  • you cannot go back to a x year old project and fix a bug without having to update/rewrite the project if you lost your local Gemfile.lock

-> Always check in Gemfile.lock, make travis delete it if you want to be extra thorough

Get text from pressed button

If you're sure that the OnClickListener instance is applied to a Button, then you could just cast the received view to a Button and get the text:

public void onClick(View view){
Button b = (Button)view;
String text = b.getText().toString();

How to test REST API using Chrome's extension "Advanced Rest Client"

With latest ARC for GET request with authentication need to add a raw header named Authorization:authtoken.

Please find the screen shot Get request with authentication and query params

To add Query param click on drop down arrow on left side of URL box.

jQuery - determine if input element is textbox or select list

You could do this:

if( ctrl[0].nodeName.toLowerCase() === 'input' ) {
    // it was an input

or this, which is slower, but shorter and cleaner:

if('input') ) {
    // it was an input

If you want to be more specific, you can test the type:

if('input:text') ) {
    // it was an input

Google Map API v3 ~ Simply Close an infowindow?

I was having a similar issue. I simply added the following to my code:

closeInfoWindow = function() {

google.maps.event.addListener(map, 'click', closeInfoWindow);

The full js code is (the code above is about 15 lines from the bottom):

jQuery(window).load(function() {
if (jQuery("#map_canvas").length > 0){

function googlemap() {

jQuery('#map_canvas').css({'height': '400px'});

// Create the map 
// No need to specify zoom and center as we fit the map further down.
var map = new google.maps.Map(document.getElementById("map_canvas"), {
  mapTypeId: google.maps.MapTypeId.ROADMAP,
  streetViewControl: false

// Create the shared infowindow with two DIV placeholders
// One for a text string, the other for the StreetView panorama.
var content = document.createElement("div");
var title = document.createElement("div");
var boxText = document.createElement("div");

var myOptions = {
         content: boxText
        ,disableAutoPan: false
        ,maxWidth: 0
        ,pixelOffset: new google.maps.Size(-117,-200)
        ,zIndex: null
        ,boxStyle: { 
          background: "url('"+siteRoot+"images/house-icon-flat.png') no-repeat"
          ,opacity: 1
          ,width: "236px"
          ,height: "300px"
        ,closeBoxMargin: "10px 0px 2px 2px"
        ,closeBoxURL: ""
        ,infoBoxClearance: new google.maps.Size(1, 1)
        ,isHidden: false
        ,pane: "floatPane"
        ,enableEventPropagation: false

var infoWindow = new InfoBox(myOptions);
var MarkerImage = siteRoot+'images/house-web-marker.png';

// Create the markers
for (index in markers) addMarker(markers[index]);
function addMarker(data) {
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(, data.lng),
        map: map,
        title: data.title,
        content: data.html,
        icon: MarkerImage
    google.maps.event.addListener(marker, "click", function() {, this);         
        title.innerHTML = marker.getTitle();
        infoWindow.setContent(marker.content);, marker);
        jQuery(".innerinfo").parent().css({'overflow':'hidden', 'margin-right':'10px'});            

// Zoom and center the map to fit the markers
// This logic could be conbined with the marker creation.
// Just keeping it separate for code clarity.
var bounds = new google.maps.LatLngBounds();
for (index in markers) {
    var data = markers[index];
    bounds.extend(new google.maps.LatLng(, data.lng));
var origcent = new google.maps.LatLng(map.getCenter());
// Handle the DOM ready event to create the StreetView panorama
// as it can only be created once the DIV inside the infowindow is loaded in the DOM.

closeInfoWindow = function() {

google.maps.event.addListener(map, 'click', closeInfoWindow);

google.maps.event.addListener(infoWindow, 'closeclick', function()

function centermap()

jQuery(window).resize(function() {

Spring Boot Program cannot find main class

Error:Could not load or find main class

Project:Spring Boot Tool:STS

Resolve Steps:

  1. Run the project

  1. See in problems tab, it will show the corrupted error

  1. Delete that particular jar(corrupted jar) in .m2 folder

  1. Update project

  1. Run successfully

Java count occurrence of each item in an array

// An Answer w/o using Hashset or map or Arraylist

public class Count {
    static String names[] = {"name1","name1","name2","name2", "name2"};
    public static void main(String args[]) {



    public static void printCount(String[] names){

        int n = names.length, c;
        for(int i=0;i<n;i++){
            System.out.print(names[i]+" ");
        int result[] = new int[n];
        for(int i=0;i<n;i++){
            result[i] = 0;

        for(int i =0;i<n;i++){
            if (i != n-1){
                for(int j=0;j<n;j++){
                    if(names[i] == names[j] )
            else if (names[n-2] == names[n-1]){
            result[i] = result[i-1];

         else result[i] = 1;
        int max = 0,index = 0;
        for(int i=0;i<n;i++){
         System.out.print(result[i]+"     ");
            if (result[i] >= max){
                max = result[i];
                index = i;


Change background color on mouseover and remove it after mouseout

Set the original background-color in you CSS file:


You don't have to capture the original color in jQuery. Remember that jQuery will alter the style INLINE, so by setting the background-color to null you will get the same result.

$(function() {
    function() {
        $(this).css('background-color', '#ff0')
    }, function() {
        $(this).css('background-color', '')

Unbound classpath container in Eclipse

I got the Similar issue while importing the project.

The issue is you select "Use an execution environment JRE" and which is lower then the libraries used in the projects being imported.

There are two ways to resolve this issue:

1.While first time importing the project:

in JRE tab select "USE project specific JRE" instead of "Use an execution environment JRE".

2.Delete the Project from your work space and import again. This time:

select "Check out as a project in the workspace" instead of "Check out as a project configured using the new Project Wizard"

Trying to detect browser close event

jQuery .bind() has been deprecated. Use .on() instead

$(window).on("beforeunload", function() {

How do I delete multiple rows with different IDs?

Disclaim: the following suggestion could be an overhead depending on the situation. The function is only tested with MSSQL 2008 R2 but seams be compatible to other versions

if you wane do this with many Id's you may could use a function which creates a temp table where you will be able to DELETE FROM the selection

how the query could look like:

-- not tested
-- @ids will contain a varchar with your ids e.g.'9 12 27 37'
DELETE FROM table WHERE id IN (SELECT i.number FROM iter_intlist_to_tbl(@ids))

here is the function:

ALTER FUNCTION iter_intlist_to_tbl (@list nvarchar(MAX))
   RETURNS @tbl TABLE (listpos int IDENTITY(1, 1) NOT NULL,
                       number  int NOT NULL) AS

   -- funktion gefunden auf
   -- dient zum übergeben einer liste von elementen

    -- Deklaration der Variablen
    DECLARE @startpos int,
            @endpos   int,
            @textpos  int,
            @chunklen smallint,
            @str      nvarchar(4000),
            @tmpstr   nvarchar(4000),
            @leftover nvarchar(4000)

    -- Startwerte festlegen
   SET @textpos = 1
   SET @leftover = ''

   -- Loop 1
    WHILE @textpos <= datalength(@list) / 2

        SET @chunklen = 4000 - datalength(@leftover) / 2 --datalength() gibt die anzahl der bytes zurück (mit Leerzeichen)

        SET @tmpstr = ltrim(@leftover + substring(@list, @textpos, @chunklen))--SUBSTRING ( @string ,start , length ) | ltrim(@string) abschneiden aller Leerzeichen am Begin des Strings

        --hochzählen der TestPosition
        SET @textpos = @textpos + @chunklen

        --start position 0 setzen
        SET @startpos = 0

        -- end position bekommt den charindex wo ein [LEERZEICHEN] gefunden wird
        SET @endpos = charindex(' ' COLLATE Slovenian_BIN2, @tmpstr)--charindex(searchChar,Wo,Startposition)

        -- Loop 2
        WHILE @endpos > 0
            --str ist der string welcher zwischen den [LEERZEICHEN] steht
            SET @str = substring(@tmpstr, @startpos + 1, @endpos - @startpos - 1) 

            --wenn @str nicht leer ist wird er zu int Convertiert und @tbl unter der Spalte 'number' hinzugefügt
            IF @str <> ''
                INSERT @tbl (number) VALUES(convert(int, @str))-- convert(Ziel-Type,Value)

            -- start wird auf das letzte bekannte end gesetzt
            SET @startpos = @endpos

            -- end position bekommt den charindex wo ein [LEERZEICHEN] gefunden wird
            SET @endpos = charindex(' ' COLLATE Slovenian_BIN2, @tmpstr, @startpos + 1)
        -- Loop 2

        -- dient dafür den letzten teil des strings zu selektieren
        SET @leftover = right(@tmpstr, datalength(@tmpstr) / 2 - @startpos)--right(@string,anzahl der Zeichen) bsp.: right("abcdef",3) => "def"
    -- Loop 1

    --wenn @leftover nach dem entfernen aller [LEERZEICHEN] nicht leer ist wird er zu int Convertiert und @tbl unter der Spalte 'number' hinzugefügt
    IF ltrim(rtrim(@leftover)) <> ''
        INSERT @tbl (number) VALUES(convert(int, @leftover))


    -- ############################ WICHTIG ############################
    -- das is ein Beispiel wie man die Funktion benutzt
    --CREATE    PROCEDURE get_product_names_iter 
    --      @ids varchar(50) AS
    --SELECT    P.ProductName, P.ProductID
    --FROM      Northwind.Products P
    --JOIN      iter_intlist_to_tbl(@ids) i ON P.ProductID = i.number
    --EXEC get_product_names_iter '9 12 27 37'
    -- Funktion gefunden auf
    -- dient zum übergeben einer Liste von Id's
    -- ############################ WICHTIG ############################

Most efficient way to check if a file is empty in Java on Windows

Stolen from

FileInputStream fis = new FileInputStream(new File("file_name"));  
int b =;  
if (b == -1)  
  System.out.println("!!File " + file_name + " emty!!");  

Updated: My first answer was premature and contained a bug.

How to get the selected item of a combo box to a string variable in c#

SelectedText = this.combobox.SelectionBoxItem.ToString();

Objective-C Static Class Level variables

Issue Description:

  1. You want your ClassA to have a ClassB class variable.
  2. You are using Objective-C as programming language.
  3. Objective-C does not support class variables as C++ does.

One Alternative:

Simulate a class variable behavior using Objective-C features

  1. Declare/Define an static variable within the classA.m so it will be only accessible for the classA methods (and everything you put inside classA.m).

  2. Overwrite the NSObject initialize class method to initialize just once the static variable with an instance of ClassB.

  3. You will be wondering, why should I overwrite the NSObject initialize method. Apple documentation about this method has the answer: "The runtime sends initialize to each class in a program exactly one time just before the class, or any class that inherits from it, is sent its first message from within the program. (Thus the method may never be invoked if the class is not used.)".

  4. Feel free to use the static variable within any ClassA class/instance method.

Code sample:

file: classA.m

static ClassB *classVariableName = nil;

@implementation ClassA

+(void) initialize
    if (! classVariableName)
        classVariableName = [[ClassB alloc] init];

+(void) classMethodName
    [classVariableName doSomething]; 

-(void) instanceMethodName
    [classVariableName doSomething]; 




  1. Class variables explained comparing Objective-C and C++ approaches

How to fetch FetchType.LAZY associations with JPA and Hibernate in a Spring Controller

it can only be lazily loaded whilst within a transaction. So you could access the collection in your repository, which has a transaction - or what I normally do is a get with association, or set fetchmode to eager.

Counting number of occurrences in column?


=ArrayFormula(QUERY(A:A&{"",""};"select Col1, count(Col2) where Col1 != '' group by Col1 label count(Col2) 'Count'";1))

22/07/2014 Some time in the last month, Sheets has started supporting more flexible concatenation of arrays, using an embedded array. So the solution may be shortened slightly to:

=QUERY({A:A,A:A},"select Col1, count(Col2) where Col1 != '' group by Col1 label count(Col2) 'Count'",1)

ASP.NET MVC View Engine Comparison

I like ndjango. It is very easy to use and very flexible. You can easily extend view functionality with custom tags and filters. I think that "greatly tied to F#" is rather advantage than disadvantage.

How to change the hosts file on android

Probably the easiest way would be use this app Hosts Editor . You need to have root

In C#, how to check if a TCP port is available?

Thanks for this tip. I needed the same functionality but on the Server side to check if a Port was in use so I modified it to this code.

 private bool CheckAvailableServerPort(int port) {
    LOG.InfoFormat("Checking Port {0}", port);
    bool isAvailable = true;

    // Evaluate current system tcp connections. This is the same information provided
    // by the netstat command line application, just in .Net strongly-typed object
    // form.  We will look through the list, and if our port we would like to use
    // in our TcpClient is occupied, we will set isAvailable to false.
    IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
    IPEndPoint[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpListeners();

    foreach (IPEndPoint endpoint in tcpConnInfoArray) {
        if (endpoint.Port == port) {
            isAvailable = false;

    LOG.InfoFormat("Port {0} available = {1}", port, isAvailable);

    return isAvailable;

SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost'

Just Create New User for MySQL do not use root. there is a problem its security issue

sudo mysql -p -u root

Login into MySQL or MariaDB with root privileges

CREATE USER 'troy121'@'%' IDENTIFIED BY 'mypassword123';

login and create a new user


and grant privileges to access "." and "@" "%" any location not just only 'localhost'


if you want to see your privilege table SHOW GRANTS; & Enjoy.

How can I test if a letter in a string is uppercase or lowercase using JavaScript?

const isUpperCase = (string) => /^[A-Z]*$/.test(string)

then :

isUpperCase('A') // true
isUpperCase('a') // false

How to find out mySQL server ip address from phpmyadmin

MySQL doesn't care what IP its on. Closest you could get would be hostname:

select * from GLOBAL_variables where variable_name like 'hostname';

Django datetime issues (

From the documentation on the django model default field:

The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.

Therefore following should work:

date = models.DateTimeField(,blank=True)

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Check encoding format of your file and use corresponding encoding format while reading file. It will solve your problem.

with open("AB.json", encoding='utf-8', errors='ignore') as json_data:
     data = json.load(json_data, strict=False)

How to make inactive content inside a div?

  pointer-events: none;
  opacity: 0.7;

The above code makes the contents of the div disabled. You can make div disabled by adding disabled attribute.

<div disabled>
  /* Contents */

Extract subset of key-value pairs from Python dictionary object?

Okay, this is something that has bothered me a few times, so thank you Jayesh for asking it.

The answers above seem like as good a solution as any, but if you are using this all over your code, it makes sense to wrap the functionality IMHO. Also, there are two possible use cases here: one where you care about whether all keywords are in the original dictionary. and one where you don't. It would be nice to treat both equally.

So, for my two-penneth worth, I suggest writing a sub-class of dictionary, e.g.

class my_dict(dict):
    def subdict(self, keywords, fragile=False):
        d = {}
        for k in keywords:
                d[k] = self[k]
            except KeyError:
                if fragile:
        return d

Now you can pull out a sub-dictionary with


Usage examples:

## our keywords are letters of the alphabet
keywords = 'abcdefghijklmnopqrstuvwxyz'
## our dictionary maps letters to their index
d = my_dict([(k,i) for i,k in enumerate(keywords)])
print('Original dictionary:\n%r\n\n' % (d,))
## constructing a sub-dictionary with good keywords
oddkeywords = keywords[::2]
subd = d.subdict(oddkeywords)
print('Dictionary from odd numbered keys:\n%r\n\n' % (subd,))
## constructing a sub-dictionary with mixture of good and bad keywords
somebadkeywords = keywords[1::2] + 'A'
    subd2 = d.subdict(somebadkeywords)
    print("We shouldn't see this message")
except KeyError:
    print("subd2 construction fails:")
    print("\toriginal dictionary doesn't contain some keys\n\n")
## Trying again with fragile set to false
    subd3 = d.subdict(somebadkeywords, fragile=False)
    print('Dictionary constructed using some bad keys:\n%r\n\n' % (subd3,))
except KeyError:
    print("We shouldn't see this message")

If you run all the above code, you should see (something like) the following output (sorry for the formatting):

Original dictionary:
{'a': 0, 'c': 2, 'b': 1, 'e': 4, 'd': 3, 'g': 6, 'f': 5, 'i': 8, 'h': 7, 'k': 10, 'j': 9, 'm': 12, 'l': 11, 'o': 14, 'n': 13, 'q': 16, 'p': 15, 's': 18, 'r': 17, 'u': 20, 't': 19, 'w': 22, 'v': 21, 'y': 24, 'x': 23, 'z': 25}

Dictionary from odd numbered keys:
{'a': 0, 'c': 2, 'e': 4, 'g': 6, 'i': 8, 'k': 10, 'm': 12, 'o': 14, 'q': 16, 's': 18, 'u': 20, 'w': 22, 'y': 24}

subd2 construction fails:
original dictionary doesn't contain some keys

Dictionary constructed using some bad keys:
{'b': 1, 'd': 3, 'f': 5, 'h': 7, 'j': 9, 'l': 11, 'n': 13, 'p': 15, 'r': 17, 't': 19, 'v': 21, 'x': 23, 'z': 25}

iOS 10 - Changes in asking permissions of Camera, microphone and Photo Library causing application to crash

Please find below codes for ios 10 request permission sample for info.plist.
You can modify for your custom message.

    <string>${PRODUCT_NAME} Camera Usage</string>

    <string>${PRODUCT_NAME} BluetoothPeripheral</string>

    <string>${PRODUCT_NAME} Calendar Usage</string>

    <string>${PRODUCT_NAME} Contact fetch</string>

    <string>${PRODUCT_NAME} Health Description</string>

    <string>${PRODUCT_NAME} Health Updates</string>

    <string>${PRODUCT_NAME} HomeKit Usage</string>

    <string>${PRODUCT_NAME} Use location always</string>

    <string>${PRODUCT_NAME} Location Updates</string>

    <string>${PRODUCT_NAME} WhenInUse Location</string>

    <string>${PRODUCT_NAME} Music Usage</string>

    <string>${PRODUCT_NAME} Microphone Usage</string>

    <string>${PRODUCT_NAME} Motion Usage</string>

    <string>${PRODUCT_NAME} MediaLibrary Usage</string>

    <string>${PRODUCT_NAME} PhotoLibrary Usage</string>

    <string>${PRODUCT_NAME} Reminder Usage</string>

    <string>${PRODUCT_NAME} Siri Usage</string>

    <string>${PRODUCT_NAME} Speech Recognition Usage</string>

    <string>${PRODUCT_NAME} Video Subscribe Usage</string>

iOS 11 and plus, If you want to add photo/image to your library then you must add this key

    <string>${PRODUCT_NAME} library Usage</string>

How add class='active' to html menu with php

The solution i'm using is as follows and allows you to set the active class per php page.

Give each of your menu items a unique class, i use .nav-x (nav-about, here).

<li class="nav-item nav-about"> <a class="nav-link" href="about.php">About</a> </li>

At the top of each page (about.php here):

<!-- Navbar Active Class -->
<?php $activeClass = '.nav-about > a'; ?>

Elsewhere (header.php / index.php):

<?php echo $activeClass; ?> {
    color: #fff !important;

Simply change the .nav-about > a per page, .nav-forum > a, for example.

If you want different styling (colors etc) for each nav item, just attach the inline styling to that page instead of the index / header page.

Doing a cleanup action just before Node.js exits

In the case where the process was spawned by another node process, like:

var child = spawn('gulp', ['watch'], {
    stdio: 'inherit',

And you try to kill it later, via:


This is how you handle the event [on the child]:

process.on('SIGTERM', function() {

Converting a char to ASCII?

A char is an integral type. When you write

char ch = 'A';

you're setting the value of ch to whatever number your compiler uses to represent the character 'A'. That's usually the ASCII code for 'A' these days, but that's not required. You're almost certainly using a system that uses ASCII.

Like any numeric type, you can initialize it with an ordinary number:

char ch = 13;

If you want do do arithmetic on a char value, just do it: ch = ch + 1; etc.

However, in order to display the value you have to get around the assumption in the iostreams library that you want to display char values as characters rather than numbers. There are a couple of ways to do that.

std::cout << +ch << '\n';
std::cout << int(ch) << '\n'

How to use Git and Dropbox together?

For my 2 cents Dropbox only makes sence for personal use where you don't want to bother getting a central repo host. For any professional development you'll probably create more problems than you'll solve, as have been mentioned several times in the thread already, Dropbox isn't designed for this use case. That said, a perfectly safe method to dump repositories on Dropbox without any third-party plugins or tools is to use bundles. I have the following aliases in my .gitconfig to save typing:

        bundle-push = "!cd \"${GIT_PREFIX:-.}\" && if path=\"$(git config remote.\"$1\".url)\" && [ \"${path:0:1}\" = / ]; then git bundle create \"$path\" --all && git fetch \"$1\"; else echo \"Not a bundle remote\"; exit 1; fi #"
        bundle-fetch = "!cd \"${GIT_PREFIX:-.}\" && if path=\"$(git config remote.\"$1\".url)\" && [ \"${path:0:1}\" = / ]; then git bundle verify \"$path\" && git fetch \"$1\"; else echo \"Not a bundle remote\"; exit 1; fi #"
        bundle-new = "!cd \"${GIT_PREFIX:-.}\" && if [ -z \"${1:-}\" -o -z \"${2:-}\" ]; then echo \"Usage: git bundle-new <file> <remote name>\"; exit 1; elif [ -e \"$2\" ]; then echo \"File exist\"; exit 1; else git bundle create \"$2\" --all && git remote add -f \"$1\" \"$(realpath \"$2\")\"; fi #"


# Create bundle remote (in local repo)
$ git bundle-new dropbox ~/Dropbox/my-repo.bundle
# Fetch updates from dropbox
$ git bundle-fetch dropbox
# NOTE: writes over previous bundle. Thus, roughly equivalent to push --force --prune --all
$ git bundle-push

CSS selector for "foo that contains bar"?

Is there any way you could programatically apply a class to the object?

<object class="hasparams">

then do


Amazon products API - Looking for basic overview and information

Straight from the horse's moutyh: Summary of Product Advertising API Operations which has the following categories:

  • Find Items
  • Find Out More About Specific Items
  • Shopping Cart
  • Customer Content
  • Seller Information
  • Other Operations

Extract month and year from a zoo::yearmon object

For large vectors:

y = as.POSIXlt(date1)$year + 1900    # x$year : years since 1900
m = as.POSIXlt(date1)$mon + 1        # x$mon : 0–11

How do I get JSON data from RESTful service using Python?

You basically need to make a HTTP request to the service, and then parse the body of the response. I like to use httplib2 for it:

import httplib2 as http
import json

    from urlparse import urlparse
except ImportError:
    from urllib.parse import urlparse

headers = {
    'Accept': 'application/json',
    'Content-Type': 'application/json; charset=UTF-8'

uri = ''
path = '/path/to/resource/'

target = urlparse(uri+path)
method = 'GET'
body = ''

h = http.Http()

# If you need authentication some example:
if auth:
    h.add_credentials(auth.user, auth.password)

response, content = h.request(

# assume that content is a json reply
# parse content with the json module
data = json.loads(content)

How do I create a random alpha-numeric string in C++?

#include <iostream>
#include <string>
#include <random>

std::string generateRandomId(size_t length = 0)
    static const std::string allowed_chars {"123456789BCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz"};

    static thread_local std::default_random_engine randomEngine(std::random_device{}());
    static thread_local std::uniform_int_distribution<int> randomDistribution(0, allowed_chars.size() - 1);

    std::string id(length ? length : 32, '\0');

    for (std::string::value_type& c : id) {
        c = allowed_chars[randomDistribution(randomEngine)];

    return id;

int main()
    std::cout << generateRandomId() << std::endl;

Change the fill color of a cell based on a selection from a Drop Down List in an adjacent cell

In Excel 2010 it is easy, just takes a few more steps for each list items.

The following steps must be completed for each item within the validation list. (Have the worksheet open to where the drop down was created)

1) Click on cell with drop down list.
2) Select which answer to apply format to.
3) Click on "Home" tab, then click the "Styles" tool button on the ribbon.
4) Click "Conditional Formatting", in drop down list click the "*New Rule" option.
5) Select a Rule Type: "Format only cells that contain"
6) Edit the Rule Description: "Cell Value", "equal to", click the cell formula icon in the formula bar (far right), select which worksheet the validation list was created in, select the cell within the list to which you wish to apply the formatting.

Formula should look something like: ='Workbook Data'!$A$2

7) Click the formula icon again to return to format menu.
8) Click on Format button beside preview pane.
9) Select all format options desired.
10) Press "OK" twice.

You are finished with only one item within list. Repeat steps 1 thru 10 until all drop down list items are finished.

MySQL parameterized queries

As an alternative to the chosen answer, and with the same safe semantics of Marcel's, here is a compact way of using a Python dictionary to specify the values. It has the benefit of being easy to modify as you add or remove columns to insert:

  insert='insert into Songs ({0}) values ({1})'.
        .format(','.join(meta_cols), ','.join( ['%s']*len(meta_cols) ))
  args = [ meta[i] for i in meta_cols ]

Where meta is the dictionary holding the values to insert. Update can be done in the same way:

  update='update Songs set {0} where id=%s'.
        .format(','.join([ '{0}=%s'.format(c) for c in meta_cols ]))
  args = [ meta[i] for i in meta_cols ]
  args.append( songid )

Ajax call Into MVC Controller- Url Issue

In order for this to work that Javascript must be placed within a Razor view so that the line


is parsed by Razor and the real value replaced.

If you don't want to move your Javascript into your View you could look at creating a settings object in the view and then referencing that from your Javascript file.


var MyAppUrlSettings = {
    MyUsefulUrl : '@Url.Action("Action","Controller")'

and in your .js file

 type: "POST",
 url: MyAppUrlSettings.MyUsefulUrl,
 data: "{queryString:'" + searchVal + "'}",
 contentType: "application/json; charset=utf-8",
 dataType: "html",
 success: function (data) {
 alert("here" + data.d.toString());

or alternatively look at levering the framework's built in Ajax methods within the HtmlHelpers which allow you to achieve the same without "polluting" your Views with JS code.

TimePicker Dialog from clicking EditText

I dont know if this will work for you, it works for me just fine.

Create a method for the Date/Time picker dialog.

private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

    // when dialog box is called, below method will be called.
    // The arguments will be working to get the Day of Week to show it in a special TextView for it.

    public void onDateSet(DatePicker view, int selectedYear,
                          int selectedMonth, int selectedDay) {
        String year1 = String.valueOf(selectedYear);
        String month1 = String.valueOf(selectedMonth + 1);
        String day1 = String.valueOf(selectedDay);
        delivDate.setText(month1 + "/" + day1 + "/" + year1);
        delivDay.setText(DateFormat.format("EEEE", new Date(selectedYear, selectedMonth, selectedDay - 1)).toString());

and then, wherever you want you can do it just like this

public void setDateOnClick (View view) {
    Calendar cal = Calendar.getInstance();

    DatePickerDialog datePicker = new DatePickerDialog(this, datePickerListener,
    //Create a cancel button and set the title of the dialog.
    datePicker.setTitle("Select the date");;

hope you find this as your solution.

Best way to do a PHP switch with multiple values per case?

Switch in combination with variable variables will give you more flexibility:

$p = 'home'; //For testing

$p = ( strpos($p, 'users') !== false? 'users': $p);
switch ($p) { 
        $varContainer = 'current_' . $p; //Stores the variable [$current_"xyORz"] into $varContainer
        ${$varContainer} = 'current'; //Sets the VALUE of [$current_"xyORz"] to 'current'

//For testing
echo $current_home;

To learn more, checkout variable variables and the examples I submitted to php manual:
Example 1:
Example 2:

PS: This example code is SMALL AND SIMPLE, just the way I like it. It's tested and works too

How do I get Fiddler to stop ignoring traffic to localhost?

For Fiddler to capture traffic from localhost on local IIS, there are 3 steps (It worked on my computer):

  1. Click Tools > Fiddler Options. Ensure Allow remote clients to connect is checked. Close Fiddler.

enter image description here

  1. Create a new DWORD named ReverseProxyForPort inside KEY_CURRENT_USER\SOFTWARE\Microsoft\Fiddler2. Set the DWORD to port 80 (choose decimal here). Restart Fiddler.

enter image description here

  1. Add port 8888 to the addresses defined in your client. For example localhost:8888/MyService/WebAPI/v1/

How can I find out what version of git I'm running?

$ git --version
git version

git help and man git both hint at the available arguments you can pass to the command-line tool

Parse XML using JavaScript

I'm guessing from your last question, asked 20 minutes before this one, that you are trying to parse (read and convert) the XML found through using GeoNames' FindNearestAddress.

If your XML is in a string variable called txt and looks like this:

  <street>Roble Ave</street>
  <placename>Menlo Park</placename>
  <adminName2>San Mateo</adminName2>

Then you can parse the XML with Javascript DOM like this:

if (window.DOMParser)
    parser = new DOMParser();
    xmlDoc = parser.parseFromString(txt, "text/xml");
else // Internet Explorer
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = false;

And get specific values from the nodes like this:

//Gets house address number

//Gets Street name

//Gets Postal Code


Feb. 2019 edit:

In response to @gaugeinvariante's concerns about xml with Namespace prefixes. Should you have a need to parse xml with Namespace prefixes, everything should work almost identically:

NOTE: this will only work in browsers that support xml namespace prefixes such as Microsoft Edge

// XML with namespace prefixes 's', 'sn', and 'p' in a variable called txt_x000D_
txt = `_x000D_
<address xmlns:p='' xmlns:s='' xmlns:sn=''>_x000D_
  <s:street>Roble Ave</s:street>_x000D_
//Everything else the same_x000D_
if (window.DOMParser)_x000D_
    parser = new DOMParser();_x000D_
    xmlDoc = parser.parseFromString(txt, "text/xml");_x000D_
else // Internet Explorer_x000D_
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");_x000D_
    xmlDoc.async = false;_x000D_
//The prefix should not be included when you request the xml namespace_x000D_
//Gets "streetNumber" (note there is no prefix of "sn"_x000D_
//Gets Street name_x000D_
//Gets Postal Code_x000D_

PHP's array_map including keys

Based on eis's answer, here's what I eventually did in order to avoid messing the original array:

$test_array = array("first_key" => "first_value",
                    "second_key" => "second_value");

$result_array = array();
           function($a, $b) use (&$result_array) 
           { $result_array[] = "$b loves $a"; }, 

jQuery UI - Draggable is not a function?

The cause to this error is usually because you're probably using a bootstrap framework and have already included a jquery file somewhere else may at the head or right above the closing body tag, in that case all you need to do is to include the jquery ui file wherever you have the jquery file or on both both places and you'll be fine...

  <script src="" type="text/javascript"></script>

just include the above jquery ui script wherever you are importing the jquery file along with other bootstrap dependencies.

Serializing a list to JSON

building on an answer from another posting.. I've come up with a more generic way to build out a list, utilizing dynamic retrieval with Json.NET version 12.x

using Newtonsoft.Json;

static class JsonObj
    /// <summary>
    /// Deserializes a json file into an object list
    /// Author: Joseph Poirier 2/26/2019
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="fileName"></param>
    /// <returns></returns>
    public static List<T> DeSerializeObject<T>(string fileName)
        List<T> objectOut = new List<T>();

        if (string.IsNullOrEmpty(fileName)) { return objectOut; }

            // reading in full file as text
            string ss = File.ReadAllText(fileName);

            // went with <dynamic> over <T> or <List<T>> to avoid error..
            //  unexpected character at line 1 column 2
            var output = JsonConvert.DeserializeObject<dynamic>(ss);

            foreach (var Record in output)
                foreach (T data in Record)
        catch (Exception ex)
            //Log exception here

        return objectOut;

call to process

        string fname = "../../Names.json"; // <- your json file path

        // for alternate types replace string with custom class below
        List<string> jsonFile = JsonObj.DeSerializeObject<string>(fname);

or this call to process

        string fname = "../../Names.json"; // <- your json file path

        // for alternate types replace string with custom class below
        List<string> jsonFile = new List<string>();

What tool can decompile a DLL into C++ source code?

The closest you will ever get to doing such thing is a dissasembler, or debug info (Log2Vis.pdb).

How do I properly set the Datetimeindex for a Pandas datetime object in a dataframe?

To simplify Kirubaharan's answer a bit:

df['Datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'])
df = df.set_index('Datetime')

And to get rid of unwanted columns (as OP did but did not specify per se in the question):

df = df.drop(['date','time'], axis=1)

Java 8 forEach with index

There are workarounds but no clean/short/sweet way to do it with streams and to be honest, you would probably be better off with:

int idx = 0;
for (Param p : params) query.bind(idx++, p);

Or the older style:

for (int idx = 0; idx < params.size(); idx++) query.bind(idx, params.get(idx));

Map implementation with duplicate keys

Multimap<Integer, String> multimap = ArrayListMultimap.create();

multimap.put(1, "A");
multimap.put(1, "B");
multimap.put(1, "C");
multimap.put(1, "A");

multimap.put(2, "A");
multimap.put(2, "B");
multimap.put(2, "C");

multimap.put(3, "A");


Output is:


Note: we need to import library files.



import org.apache.commons.collections.MultiMap;

Setting public class variables

Add getter and setter method to your class.

public function setValue($new_value)
    $this->testvar = $new_value;

public function getValue()
    return $this->testvar;        

android : Error converting byte to dex

I've noticed this can happen (sometimes) when editing java files while Android Studio is building.

I solved this by manually deleting the build folder and running agin.

TypeError: can only concatenate list (not "str") to list

Let me fix your code

inventory=["sword", "potion", "armour", "bow"]
print("\ncommands: use (remove) and pickup (add)")
selection=input("choose a command [use/pickup]")

if selection == "use":
    inventory.remove(input("What do you want to use? "))
elif selection == "pickup":
    add=input("What do you want to pickup? ")
    newinv=inventory+[str(add)] #use '[str(add)]' or list(str(add))

The error is you are adding string and list, you should use list or [] to make the string become list type

Is there any difference between DECIMAL and NUMERIC in SQL Server?

They are the same. Numeric is functionally equivalent to decimal.

MSDN: decimal and numeric

jquery $(this).id return Undefined

Hiya demo

this is a reference to the DOM element, so you can wrap it directly.

attr api:

The .attr() method gets the attribute value for only the first element in the matched set.

have a nice one, cheers!


$(document).ready(function () {
    $(".inputs").click(function () {

        alert(" or " + $(this).attr("id"));



How do I run a Java program from the command line on Windows?

Source: javaindos.

Let's say your file is in C:\mywork\

Run Command Prompt

C:\> cd \mywork

This makes C:\mywork the current directory.

C:\mywork> dir

This displays the directory contents. You should see among the files.

C:\mywork> set path=%path%;C:\Program Files\Java\jdk1.5.0_09\bin

This tells the system where to find JDK programs.

C:\mywork> javac

This runs javac.exe, the compiler. You should see nothing but the next system prompt...

C:\mywork> dir

javac has created the filenamehere.class file. You should see and filenamehere.class among the files.

C:\mywork> java filenamehere

This runs the Java interpreter. You should then see your program output.

If the system cannot find javac, check the set path command. If javac runs but you get errors, check your Java text. If the program compiles but you get an exception, check the spelling and capitalization in the file name and the class name and the java HelloWorld command. Java is case-sensitive!

Writing to CSV with Python adds blank lines

You need to open the file in binary b mode to take care of blank lines in Python 2. This isn't required in Python 3.

So, change open('test.csv', 'w') to open('test.csv', 'wb').

Functions are not valid as a React child. This may happen if you return a Component instead of from render

In my case i forgot to add the () after the function name inside the render function of a react component

public render() {
       let ctrl = (
                <div className="aaa">

       return ctrl;

    private renderView() : JSX.Element {
        // some html

Changing the render method, as it states in the error message to

        <div className="aaa">

fixed the problem

Python Selenium Chrome Webdriver

You need to specify the path where your chromedriver is located.

  1. Download chromedriver for your desired platform from here.

  2. Place chromedriver on your system path, or where your code is.

  3. If not using a system path, link your chromedriver.exe (For non-Windows users, it's just called chromedriver):

    browser = webdriver.Chrome(executable_path=r"C:\path\to\chromedriver.exe")

    (Set executable_path to the location where your chromedriver is located.)

    If you've placed chromedriver on your System Path, you can shortcut by just doing the following:

    browser = webdriver.Chrome()

  4. If you're running on a Unix-based operating system, you may need to update the permissions of chromedriver after downloading it in order to make it executable:

    chmod +x chromedriver

  5. That's all. If you're still experiencing issues, more info can be found on this other StackOverflow article: Can't use chrome driver for Selenium

how can I Update top 100 records in sql server

You can also update from select using alias and join:

SET     T.SomeColumn = 'Value'
FROM    SomeTable T
        INNER JOIN OtherTable O ON O.OtherTableFK = T.SomeTablePK
WHERE   T.SomeOtherColumn = 1

How to see if a directory exists or not in Perl?

Use -d (full list of file tests)

if (-d "cgi-bin") {
    # directory called cgi-bin exists
elsif (-e "cgi-bin") {
    # cgi-bin exists but is not a directory
else {
    # nothing called cgi-bin exists

As a note, -e doesn't distinguish between files and directories. To check if something exists and is a plain file, use -f.

How to print a number with commas as thousands separators in JavaScript

For Integers I used a very simple method:

var myNumber = 99999,
    myString = myNumber + "";

myString.length > 3 ? return myString.substring(0, myString.length - 3) + "," + 
    myString.substring(myString.length - 3) : return myString;

Example for boost shared_mutex (multiple reads/one write)?

Just to add some more empirical info, I have been investigating the whole issue of upgradable locks, and Example for boost shared_mutex (multiple reads/one write)? is a good answer adding the important info that only one thread can have an upgrade_lock even if it is not upgraded, that is important as it means you cannot upgrade from a shared lock to a unique lock without releasing the shared lock first. (This has been discussed elsewhere but the most interesting thread is here

However I did find an important (undocumented) difference between a thread waiting for an upgrade to a lock (ie needs to wait for all readers to release the shared lock) and a writer lock waiting for the same thing (ie a unique_lock).

  1. The thread that is waiting for a unique_lock on the shared_mutex blocks any new readers coming in, they have to wait for the writers request. This ensures readers do not starve writers (however I believe writers could starve readers).

  2. The thread that is waiting for an upgradeable_lock to upgrade allows other threads to get a shared lock, so this thread could be starved if readers are very frequent.

This is an important issue to consider, and probably should be documented.

T-SQL Format integer to 2-digit string

replace(str(month(DATEADD(month, -1, '2012-02-29')), 2),' ' , '0')

Detect and exclude outliers in Pandas data frame

For each series in the dataframe, you could use between and quantile to remove outliers.

x = pd.Series(np.random.normal(size=200)) # with outliers
x = x[x.between(x.quantile(.25), x.quantile(.75))] # without outliers

Select DISTINCT individual columns in django?

User order by with that field, and then do distinct.

ProductOrder.objects.order_by('category').values_list('category', flat=True).distinct()

How to test an Internet connection with bash?

Execute the following command to check whether a web site is up, and what status message the web server is showing:

curl -Is | head -1 HTTP/1.1 200 OK

Status code ‘200 OK’ means that the request has succeeded and a website is reachable.

bad operand types for binary operator "&" java

You have to be more precise, using parentheses, otherwise Java will not use the order of operands that you want it to use.

if ((a[0] & 1 == 0) && (a[1] & 1== 0) && (a[2] & 1== 0)){


if (((a[0] & 1) == 0) && ((a[1] & 1) == 0) && ((a[2] & 1) == 0)){

TypeError: unhashable type: 'numpy.ndarray'

Your variable energies probably has the wrong shape:

>>> from numpy import array
>>> set([1,2,3]) & set(range(2, 10))
set([2, 3])
>>> set(array([1,2,3])) & set(range(2,10))
set([2, 3])
>>> set(array([[1,2,3],])) & set(range(2,10))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'numpy.ndarray'

And that's what happens if you read columnar data using your approach:

>>> data
array([[  1.,   2.,   3.],
       [  3.,   4.,   5.],
       [  5.,   6.,   7.],
       [  8.,   9.,  10.]])
>>> hsplit(data,3)[0]
array([[ 1.],
       [ 3.],
       [ 5.],
       [ 8.]])

Probably you can simply use

>>> data[:,0]
array([ 1.,  3.,  5.,  8.])


(P.S. Your code looks like it's undecided about whether it's data or elementdata. I've assumed it's simply a typo.)

Parameter binding on left joins with array in Laravel Query Builder

You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw(), ensure that you binding the parameters.

Try the following:

$array = array(1,2,3);       $query = DB::table('offers');             $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used');             $query->leftJoin('user_offer_collection', function ($join) use ($array)             {                 $join->on('user_offer_collection.offers_id', '=', '')                       ->whereIn('user_offer_collection.user_id', $array);             });       $query->get(); 

How do I calculate a trendline for a graph?

Regarding a previous answer

if (B) y = offset + slope*x

then (C) offset = y/(slope*x) is wrong

(C) should be:

offset = y-(slope*x)


Set Icon Image in Java

I use this:

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;

public class IconImageUtilities
    public static void setIconImage(Window window)
            InputStream imageInputStream = window.getClass().getResourceAsStream("/Icon.png");
            BufferedImage bufferedImage =;
        } catch (IOException exception)

Just place your image called Icon.png in the resources folder and call the above method with itself as parameter inside a class extending a class from the Window family such as JFrame or JDialog:


Origin is not allowed by Access-Control-Allow-Origin

If you have an ASP.NET / ASP.NET MVC application, you can include this header via the Web.config file:


            <!-- Enable Cross Domain AJAX calls -->
            <remove name="Access-Control-Allow-Origin" />
            <add name="Access-Control-Allow-Origin" value="*" />

How to use sudo inside a docker container?

There is no answer on how to do this on CentOS. On Centos, you can add following to Dockerfile

RUN echo "user ALL=(root) NOPASSWD:ALL" > /etc/sudoers.d/user && \
    chmod 0440 /etc/sudoers.d/user

How can I include a YAML file inside another?

With Yglu, you can import other files like this:


foo: !? $import('B.yaml')


bar: Hello
$ yglu A.yaml
  bar: Hello

As $import is a function, you can also pass an expression as argument:

  dep: !- b
  foo: !? $import($_.dep.toUpper() + '.yaml')

This would give the same output as above.

Disclaimer: I am the author of Yglu.

python : list index out of range error while iteratively popping elements

You're changing the size of the list while iterating over it, which is probably not what you want and is the cause of your error.

Edit: As others have answered and commented, list comprehensions are better as a first choice and especially so in response to this question. I offered this as an alternative for that reason, and while not the best answer, it still solves the problem.

So on that note, you could also use filter, which allows you to call a function to evaluate the items in the list you don't want.


>>> l = [1,2,3,0,0,1]
>>> filter(lambda x: x > 0, l)
[1, 2, 3]

Live and learn. Simple is better, except when you need things to be complex.

jQuery validation: change default error message

instead of these custom error messages we can specify the type of the text field.

Ex: set type of the field in to type = 'email'

then plugin will identify the field and validate correctly.

XML Schema minOccurs / maxOccurs default values

New, expanded answer to an old, commonly asked question...

Default Values

  • Occurrence constraints minOccurs and maxOccurs default to 1.

Common Cases Explained

<xsd:element name="A"/>

means A is required and must appear exactly once.

<xsd:element name="A" minOccurs="0"/>

means A is optional and may appear at most once.

 <xsd:element name="A" maxOccurs="unbounded"/>

means A is required and may repeat an unlimited number of times.

 <xsd:element name="A" minOccurs="0" maxOccurs="unbounded"/>

means A is optional and may repeat an unlimited number of times.

See Also

  • W3C XML Schema Part 0: Primer

    In general, an element is required to appear when the value of minOccurs is 1 or more. The maximum number of times an element may appear is determined by the value of a maxOccurs attribute in its declaration. This value may be a positive integer such as 41, or the term unbounded to indicate there is no maximum number of occurrences. The default value for both the minOccurs and the maxOccurs attributes is 1. Thus, when an element such as comment is declared without a maxOccurs attribute, the element may not occur more than once. Be sure that if you specify a value for only the minOccurs attribute, it is less than or equal to the default value of maxOccurs, i.e. it is 0 or 1. Similarly, if you specify a value for only the maxOccurs attribute, it must be greater than or equal to the default value of minOccurs, i.e. 1 or more. If both attributes are omitted, the element must appear exactly once.

  • W3C XML Schema Part 1: Structures Second Edition

      maxOccurs = (nonNegativeInteger | unbounded)  : 1
      minOccurs = nonNegativeInteger : 1

Call to undefined function mysql_query() with Login

You are mixing mysql and mysqli

Change these lines:

$sql = mysql_query("SELECT * FROM login WHERE username = '".$_POST['username']."' and password = '".md5($_POST['password'])."'");
$row = mysql_num_rows($sql);


$sql = mysqli_query($success, "SELECT * FROM login WHERE username = '".$_POST['username']."' and password = '".md5($_POST['password'])."'");
$row = mysqli_num_rows($sql);

getting a checkbox array value from POST

// if you do the input like this
<input id="'.$userid.'" value="'.$userid.'"  name="invite['.$userid.']" type="checkbox">

// you can access the value directly like this:
$invite = $_POST['invite'][$userid];

How to drop all tables from a database with one SQL query?

The simplest way is to drop the whole database and create it once again:

drop database db_name
create database db_name

That's all.

How can I tell AngularJS to "refresh"



remember to inject $route to your controller.

Python Requests library redirect new url

For python3.5, you can use the following code:

import urllib.request
res = urllib.request.urlopen(starturl)
finalurl = res.geturl()

I'm getting Key error in python

Let us make it simple if you're using Python 3

mydict = {'a':'apple','b':'boy','c':'cat'}
check = 'c' in mydict
if check:
    print('c key is present')

If you need else condition

mydict = {'a':'apple','b':'boy','c':'cat'}
if 'c' in mydict:
    print('key present')
    print('key not found')

For the dynamic key value, you can also handle through try-exception block

mydict = {'a':'apple','b':'boy','c':'cat'}
except KeyError:
    print('key value not found')mydict = {'a':'apple','b':'boy','c':'cat'}

HTML "overlay" which allows clicks to fall through to elements behind it

Generally, this isn't a great idea. Taking your scenario, if you had evil intentions, you could hide everything underneath your "overlay". Then, when a user clicks on a link they think should take them to, instead it triggers the hidden link which takes them to

That said, event bubbling works, and if it's within an application, it's not a big deal. The following code is an example. Clicking the blue area pops up an alert, even though the alert is set on the red area. Note that the orange area does NOT work, because the event will propagate through the PARENT elements, so your overlay needs to be inside whatever element you're observing the clicks on. In your scenario, you may be out of luck.

    <div id="outer" style="position:absolute;height:50px;width:60px;z-index:1;background-color:red;top:5px;left:5px;" onclick="alert('outer')"> 
        <div id="nested" style="position:absolute;height:50px;width:60px;z-index:2;background-color:blue;top:15px;left:15px;">
    <div id="separate" style="position:absolute;height:50px;width:60px;z-index:3;background-color:orange;top:25px;left:25px;">

How can I pass a file argument to my bash script using a Terminal command in Linux?

It'll be easier (and more "proper", see below) if you just run your script as

myprogram /path/to/file

Then you can access the path within the script as $1 (for argument #1, similarly $2 is argument #2, etc.)

externalprogram "$file" [other parameters]

Or just

externalprogram "$1" [otherparameters]

If you want to extract the path from something like --file=/path/to/file, that's usually done with the getopts shell function. But that's more complicated than just referencing $1, and besides, switches like --file= are intended to be optional. I'm guessing your script requires a file name to be provided, so it doesn't make sense to pass it in an option.

Connect to mysql in a docker container from the host

  • docker run -e MYSQL_ROOT_PASSWORD=pass --name sql-db -p 3306:3306 mysql

  • docker exec -it sql-db bash

  • mysql -u root -p

CRC32 C or C++ implementation

The crc code in zlib ( is among the fastest there is, and has a very liberal open source license.

And you should not use adler-32 except for special applications where speed is more important than error detection performance.