Programs & Examples On #Objectarx

AutoDesk AutoCAD API to write 3rd party tools for AutoCAD. ObjectARX is also used in RealDWG package. RealDWG library is a subset of ObjectARX to handle AutoCAD database files (dwg and dxf files).

How to install mysql-connector via pip

If loading via pip install mysql-connector and leads an error Unable to find Protobuf include directory then this would be useful pip install mysql-connector==2.1.4

mysql-connector is obsolete, so use pip install mysql-connector-python. Same here

PHP - SSL certificate error: unable to get local issuer certificate

Finally got this to work!

  1. Download the certificate bundle.

  2. Put it somewhere. In my case, that was c:\wamp\ directory (if you are using Wamp 64 bit then it's c:\wamp64\).

  3. Enable mod_ssl in Apache and php_openssl.dll in php.ini (uncomment them by removing ; at the beginning). But be careful, my problem was that I had two php.ini files and I need to do this in both of them. One is the one you get from your WAMP taskbar icon, and another one is, in my case, in C:\wamp\bin\php\php5.5.12\

  4. Add these lines to your cert in both php.ini files:

    curl.cainfo="C:/wamp/cacert.pem"
    openssl.cafile="C:/wamp/cacert.pem"
    
  5. Restart Wamp services.

Remove duplicate rows in MySQL

I found a simple way. (keep latest)

DELETE t1 FROM tablename t1 INNER JOIN tablename t2 
WHERE t1.id < t2.id AND t1.column1 = t2.column1 AND t1.column2 = t2.column2;

How do I find files that do not contain a given string pattern?

You will actually need:

find .  -not  -ipath '.*svn*' -exec  grep  -H -E -o -c  "foo"  {} \; | grep :0\$

java : convert float to String and String to float

well this method is not a good one, but easy and not suggested. Maybe i should say this is the least effective method and the worse coding practice but, fun to use,

float val=10.0;
String str=val+"";

the empty quotes, add a null string to the variable str, upcasting 'val' to the string type.

Dynamic variable names in Bash

Wow, most of the syntax is horrible! Here is one solution with some simpler syntax if you need to indirectly reference arrays:

#!/bin/bash

foo_1=(fff ddd) ;
foo_2=(ggg ccc) ;

for i in 1 2 ;
do
    eval mine=( \${foo_$i[@]} ) ;
    echo ${mine[@]}" " ;
done ;

For simpler use cases I recommend the syntax described in the Advanced Bash-Scripting Guide.

How to reload / refresh model data from the server programmatically?

You're half way there on your own. To implement a refresh, you'd just wrap what you already have in a function on the scope:

function PersonListCtrl($scope, $http) {
  $scope.loadData = function () {
     $http.get('/persons').success(function(data) {
       $scope.persons = data;
     });
  };

  //initial load
  $scope.loadData();
}

then in your markup

<div ng-controller="PersonListCtrl">
    <ul>
        <li ng-repeat="person in persons">
            Name: {{person.name}}, Age {{person.age}}
        </li>
    </ul>
   <button ng-click="loadData()">Refresh</button>
</div>

As far as "accessing your model", all you'd need to do is access that $scope.persons array in your controller:

for example (just puedo code) in your controller:

$scope.addPerson = function() {
     $scope.persons.push({ name: 'Test Monkey' });
};

Then you could use that in your view or whatever you'd want to do.

How to drop all user tables?

Another answer that worked for me is (credit to http://snipt.net/Fotinakis/drop-all-tables-and-constraints-within-an-oracle-schema/)

BEGIN

FOR c IN (SELECT table_name FROM user_tables) LOOP
EXECUTE IMMEDIATE ('DROP TABLE "' || c.table_name || '" CASCADE CONSTRAINTS');
END LOOP;

FOR s IN (SELECT sequence_name FROM user_sequences) LOOP
EXECUTE IMMEDIATE ('DROP SEQUENCE ' || s.sequence_name);
END LOOP;

END;

Note that this works immediately after you run it. It does NOT produce a script that you need to paste somewhere (like other answers here). It runs directly on the DB.

How can I detect keydown or keypress event in angular.js?

You can checkout Angular UI @ http://angular-ui.github.io/ui-utils/ which provide details event handle callback function for detecting keydown,keyup,keypress (also Enter key, backspace key, alter key ,control key)

<textarea ui-keydown="{27:'keydownCallback($event)'}"></textarea>
<textarea ui-keypress="{13:'keypressCallback($event)'}"></textarea>
<textarea ui-keydown="{'enter alt-space':'keypressCallback($event)'}"> </textarea>
<textarea ui-keyup="{'enter':'keypressCallback($event)'}"> </textarea>

How to merge a specific commit in Git

'git cherry-pick' should be your answer here.

Apply the change introduced by an existing commit.

Do not forget to read bdonlan's answer about the consequence of cherry-picking in this post:
"Pull all commits from a branch, push specified commits to another", where:

A-----B------C
 \
  \
   D

becomes:

A-----B------C
 \
  \
   D-----C'

The problem with this commit is that git considers commits to include all history before them

Where C' has a different SHA-1 ID.
Likewise, cherry picking a commit from one branch to another basically involves generating a patch, then applying it, thus losing history that way as well.

This changing of commit IDs breaks git's merging functionality among other things (though if used sparingly there are heuristics that will paper over this).
More importantly though, it ignores functional dependencies - if C actually used a function defined in B, you'll never know.

Efficient way of having a function only execute once in a loop

If I understand the updated question correctly, something like this should work

def function1():
    print "function1 called"

def function2():
    print "function2 called"

def function3():
    print "function3 called"

called_functions = set()
while True:
    n = raw_input("choose a function: 1,2 or 3 ")
    func = {"1": function1,
            "2": function2,
            "3": function3}.get(n)

    if func in called_functions:
        print "That function has already been called"
    else:
        called_functions.add(func)
        func()

How can we convert an integer to string in AngularJs

.toString() is available, or just add "" to the end of the int

var x = 3,
    toString = x.toString(),
    toConcat = x + "";

Angular is simply JavaScript at the core.

How can one check to see if a remote file exists using PHP?

You could use the following:

$file = 'http://mysite.co.za/images/favicon.ico';
$file_exists = (@fopen($file, "r")) ? true : false;

Worked for me when trying to check if an image exists on the URL

Map vs Object in JavaScript

The key difference is that Objects only support string and Symbol keys where as Maps support more or less any key type.

If I do obj[123] = true and then Object.keys(obj) then I will get ["123"] rather than [123]. A Map would preserve the type of the key and return [123] which is great. Maps also allow you to use Objects as keys. Traditionally to do this you would have to give objects some kind of unique identifier to hash them (I don't think I've ever seen anything like getObjectId in JS as part of the standard). Maps also guarantee preservation of order so are all round better for preservation and can sometimes save you needing to do a few sorts.

Between maps and objects in practice there are several pros and cons. Objects gain both advantages and disadvantages being very tightly integrated into the core of JavaScript which sets them apart from significantly Map beyond the difference in key support.

An immediate advantage is that you have syntactical support for Objects making it easy to access elements. You also have direct support for it with JSON. When used as a hash it's annoying to get an object without any properties at all. By default if you want to use Objects as a hash table they will be polluted and you will often have to call hasOwnProperty on them when accessing properties. You can see here how by default Objects are polluted and how to create hopefully unpolluted objects for use as hashes:

({}).toString
    toString() { [native code] }
JSON.parse('{}').toString
    toString() { [native code] }
(Object.create(null)).toString
    undefined
JSON.parse('{}', (k,v) => (typeof v === 'object' && Object.setPrototypeOf(v, null) ,v)).toString
    undefined

Pollution on objects is not only something that makes code more annoying, slower, etc but can also have potential consequences for security.

Objects are not pure hash tables but are trying to do more. You have headaches like hasOwnProperty, not being able to get the length easily (Object.keys(obj).length) and so on. Objects are not meant to purely be used as hash maps but as dynamic extensible Objects as well and so when you use them as pure hash tables problems arise.

Comparison/List of various common operations:

    Object:
       var o = {};
       var o = Object.create(null);
       o.key = 1;
       o.key += 10;
       for(let k in o) o[k]++;
       var sum = 0;
       for(let v of Object.values(m)) sum += v;
       if('key' in o);
       if(o.hasOwnProperty('key'));
       delete(o.key);
       Object.keys(o).length
    Map:
       var m = new Map();
       m.set('key', 1);
       m.set('key', m.get('key') + 10);
       m.foreach((k, v) => m.set(k, m.get(k) + 1));
       for(let k of m.keys()) m.set(k, m.get(k) + 1);
       var sum = 0;
       for(let v of m.values()) sum += v;
       if(m.has('key'));
       m.delete('key');
       m.size();

There are a few other options, approaches, methodologies, etc with varying ups and downs (performance, terse, portable, extendable, etc). Objects are a bit strange being core to the language so you have a lot of static methods for working with them.

Besides the advantage of Maps preserving key types as well as being able to support things like objects as keys they are isolated from the side effects that objects much have. A Map is a pure hash, there's no confusion about trying to be an object at the same time. Maps can also be easily extended with proxy functions. Object's currently have a Proxy class however performance and memory usage is grim, in fact creating your own proxy that looks like Map for Objects currently performs better than Proxy.

A substantial disadvantage for Maps is that they are not supported with JSON directly. Parsing is possible but has several hangups:

JSON.parse(str, (k,v) => {
    if(typeof v !== 'object') return v;
    let m = new Map();
    for(k in v) m.set(k, v[k]);
    return m;
});

The above will introduce a serious performance hit and will also not support any string keys. JSON encoding is even more difficult and problematic (this is one of many approaches):

// An alternative to this it to use a replacer in JSON.stringify.
Map.prototype.toJSON = function() {
    return JSON.stringify({
        keys: Array.from(this.keys()),
        values: Array.from(this.values())
    });
};

This is not so bad if you're purely using Maps but will have problems when you are mixing types or using non-scalar values as keys (not that JSON is perfect with that kind of issue as it is, IE circular object reference). I haven't tested it but chances are that it will severely hurt performance compared to stringify.

Other scripting languages often don't have such problems as they have explicit non-scalar types for Map, Object and Array. Web development is often a pain with non-scalar types where you have to deal with things like PHP merges Array/Map with Object using A/M for properties and JS merges Map/Object with Array extending M/O. Merging complex types is the devil's bane of high level scripting languages.

So far these are largely issues around implementation but performance for basic operations is important as well. Performance is also complex because it depends on engine and usage. Take my tests with a grain of salt as I cannot rule out any mistake (I have to rush this). You should also run your own tests to confirm as mine examine only very specific simple scenarios to give a rough indication only. According to tests in Chrome for very large objects/maps the performance for objects is worse because of delete which is apparently somehow proportionate to the number of keys rather than O(1):

Object Set Took: 146
Object Update Took: 7
Object Get Took: 4
Object Delete Took: 8239
Map Set Took: 80
Map Update Took: 51
Map Get Took: 40
Map Delete Took: 2

Chrome clearly has a strong advantage with getting and updating but the delete performance is horrific. Maps use a tiny amount more memory in this case (overhead) but with only one Object/Map being tested with millions of keys the impact of overhead for maps is not expressed well. With memory management objects also do seem to free earlier if I am reading the profile correctly which might be one benefit in favor of objects.

In Firefox for this particular benchmark it is a different story:

Object Set Took: 435
Object Update Took: 126
Object Get Took: 50
Object Delete Took: 2
Map Set Took: 63
Map Update Took: 59
Map Get Took: 33
Map Delete Took: 1

I should immediately point out that in this particular benchmark deleting from objects in Firefox is not causing any problems, however in other benchmarks it has caused problems especially when there are many keys just as in Chrome. Maps are clearly superior in Firefox for large collections.

However this is not the end of the story, what about many small objects or maps? I have done a quick benchmark of this but not an exhaustive one (setting/getting) of which performs best with a small number of keys in the above operations. This test is more about memory and initialization.

Map Create: 69    // new Map
Object Create: 34 // {}

Again these figures vary but basically Object has a good lead. In some cases the lead for Objects over maps is extreme (~10 times better) but on average it was around 2-3 times better. It seems extreme performance spikes can work both ways. I only tested this in Chrome and creation to profile memory usage and overhead. I was quite surprised to see that in Chrome it appears that Maps with one key use around 30 times more memory than Objects with one key.

For testing many small objects with all the above operations (4 keys):

Chrome Object Took: 61
Chrome Map Took: 67
Firefox Object Took: 54
Firefox Map Took: 139

In terms of memory allocation these behaved the same in terms of freeing/GC but Map used 5 times more memory. This test used 4 keys where as in the last test I only set one key so this would explain the reduction in memory overhead. I ran this test a few times and Map/Object are more or less neck and neck overall for Chrome in terms of overall speed. In Firefox for small Objects there is a definite performance advantage over maps overall.

This of course doesn't include the individual options which could vary wildly. I would not advice micro-optimizing with these figures. What you can get out of this is that as a rule of thumb, consider Maps more strongly for very large key value stores and objects for small key value stores.

Beyond that the best strategy with these two it to implement it and just make it work first. When profiling it is important to keep in mind that sometimes things that you wouldn't think would be slow when looking at them can be incredibly slow because of engine quirks as seen with the object key deletion case.

Can I compile all .cpp files in src/ to .o's in obj/, then link to binary in ./?

Wildcard works for me also, but I'd like to give a side note for those using directory variables. Always use slash for folder tree (not backslash), otherwise it will fail:

BASEDIR = ../..
SRCDIR = $(BASEDIR)/src
INSTALLDIR = $(BASEDIR)/lib

MODULES = $(wildcard $(SRCDIR)/*.cpp)
OBJS = $(wildcard *.o)

jQuery UI DatePicker - Change Date Format

You can add and try this way:

HTML file:

<p><input type="text" id="demoDatepicker" /></p>

JavaScript file:

$(function() {  
    $("#demoDatepicker").datepicker({
        dateFormat: 'dd/mm/yy',
        changeMonth: true,
        changeYear: true,
        constrainInput: false
    });
});

Docker Repository Does Not Have a Release File on Running apt-get update on Ubuntu

This is what worked for me on LinuxMint 19.

curl -s https://yum.dockerproject.org/gpg | sudo apt-key add
apt-key fingerprint 58118E89F3A912897C070ADBF76221572C52609D
sudo add-apt-repository "deb https://apt.dockerproject.org/repo ubuntu-$(lsb_release -cs) main"
sudo apt-get update
sudo apt-get install docker-ce docker-ce-cli containerd.io

How to uncheck a checkbox in pure JavaScript?

You will need to assign an ID to the checkbox:

<input id="checkboxId" type="checkbox" checked="" name="copyNewAddrToBilling">

and then in JavaScript:

document.getElementById("checkboxId").checked = false;

How is CountDownLatch used in Java Multithreading?

One good example of when to use something like this is with Java Simple Serial Connector, accessing serial ports. Typically you'll write something to the port, and asyncronously, on another thread, the device will respond on a SerialPortEventListener. Typically, you'll want to pause after writing to the port to wait for the response. Handling the thread locks for this scenario manually is extremely tricky, but using Countdownlatch is easy. Before you go thinking you can do it another way, be careful about race conditions you never thought of!!

Pseudocode:

CountDownLatch latch;
void writeData() { 
   latch = new CountDownLatch(1);
   serialPort.writeBytes(sb.toString().getBytes())
   try {
      latch.await(4, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
   }
}
class SerialPortReader implements SerialPortEventListener {
    public void serialEvent(SerialPortEvent event) {
        if(event.isRXCHAR()){//If data is available
            byte buffer[] = serialPort.readBytes(event.getEventValue());
            latch.countDown();
         }
     }
}

What is the difference between "JPG" / "JPEG" / "PNG" / "BMP" / "GIF" / "TIFF" Image?

PNG supports alphachannel transparency.

TIFF can have extended options I.e. Geo referencing for GIS applications.

I recommend only ever using JPEG for photographs, never for images like clip art, logos, text, diagrams, line art.

Favor PNG.

How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator

When programming I often have strings with just plain A-Za-z and 0-9. No need for difficult Index actions. This extension is based on the plain old left / mid / right functions.

extension String {

    // LEFT
    // Returns the specified number of chars from the left of the string
    // let str = "Hello"
    // print(str.left(3))         // Hel
    func left(_ to: Int) -> String {
        return "\(self[..<self.index(startIndex, offsetBy: to)])"
    }

    // RIGHT
    // Returns the specified number of chars from the right of the string
    // let str = "Hello"
    // print(str.left(3))         // llo
    func right(_ from: Int) -> String {
        return "\(self[self.index(startIndex, offsetBy: self.length-from)...])"
    }

    // MID
    // Returns the specified number of chars from the startpoint of the string
    // let str = "Hello"
    // print(str.left(2,amount: 2))         // ll
    func mid(_ from: Int, amount: Int) -> String {
        let x = "\(self[self.index(startIndex, offsetBy: from)...])"
        return x.left(amount)
    }
}

Auto increment in MongoDB to store sequence of Unique User ID

I know this is an old question, but I shall post my answer for posterity...

It depends on the system that you are building and the particular business rules in place.

I am building a moderate to large scale CRM in MongoDb, C# (Backend API), and Angular (Frontend web app) and found ObjectId utterly terrible for use in Angular Routing for selecting particular entities. Same with API Controller routing.

The suggestion above worked perfectly for my project.

db.contacts.insert({
 "id":db.contacts.find().Count()+1,
 "name":"John Doe",
 "emails":[
    "[email protected]",
    "[email protected]"
 ],
 "phone":"555111322",
 "status":"Active"
});

The reason it is perfect for my case, but not all cases is that as the above comment states, if you delete 3 records from the collection, you will get collisions.

My business rules state that due to our in house SLA's, we are not allowed to delete correspondence data or clients records for longer than the potential lifespan of the application I'm writing, and therefor, I simply mark records with an enum "Status" which is either "Active" or "Deleted". You can delete something from the UI, and it will say "Contact has been deleted" but all the application has done is change the status of the contact to "Deleted" and when the app calls the respository for a list of contacts, I filter out deleted records before pushing the data to the client app.

Therefore, db.collection.find().count() + 1 is a perfect solution for me...

It won't work for everyone, but if you will not be deleting data, it works fine.

jquery, domain, get URL

check this

alert(window.location.hostname);

this will return host name as www.domain.com

Adding background image to div using CSS

To use an image for body background in CSS

body {
  background-image: url("image.jpg");
}

Display image as grayscale using matplotlib

Use no interpolation and set to gray.

import matplotlib.pyplot as plt
plt.imshow(img[:,:,1], cmap='gray',interpolation='none')

Find an item in List by LINQ?

If it really is a List<string> you don't need LINQ, just use:

int GetItemIndex(string search)
{
    return _list == null ? -1 : _list.IndexOf(search);
}

If you are looking for the item itself, try:

string GetItem(string search)
{
    return _list == null ? null : _list.FirstOrDefault(s => s.Equals(search));
}

Choose File Dialog

Thanx schwiz for idea! Here is modified solution:

public class FileDialog {
    private static final String PARENT_DIR = "..";
    private final String TAG = getClass().getName();
    private String[] fileList;
    private File currentPath;
    public interface FileSelectedListener {
        void fileSelected(File file);
    }
    public interface DirectorySelectedListener {
        void directorySelected(File directory);
    }
    private ListenerList<FileSelectedListener> fileListenerList = new ListenerList<FileDialog.FileSelectedListener>();
    private ListenerList<DirectorySelectedListener> dirListenerList = new ListenerList<FileDialog.DirectorySelectedListener>();
    private final Activity activity;
    private boolean selectDirectoryOption;
    private String fileEndsWith;    

    /**
    * @param activity 
    * @param initialPath
    */
    public FileDialog(Activity activity, File initialPath) {
        this(activity, initialPath, null);
    }

    public FileDialog(Activity activity, File initialPath, String fileEndsWith) {
        this.activity = activity;
        setFileEndsWith(fileEndsWith);
        if (!initialPath.exists()) initialPath = Environment.getExternalStorageDirectory();
            loadFileList(initialPath);
    }

    /**
    * @return file dialog
    */
    public Dialog createFileDialog() {
        Dialog dialog = null;
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);

        builder.setTitle(currentPath.getPath());
        if (selectDirectoryOption) {
            builder.setPositiveButton("Select directory", new OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Log.d(TAG, currentPath.getPath());
                    fireDirectorySelectedEvent(currentPath);
                }
            });
        }

        builder.setItems(fileList, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                String fileChosen = fileList[which];
                File chosenFile = getChosenFile(fileChosen);
                if (chosenFile.isDirectory()) {
                    loadFileList(chosenFile);
                    dialog.cancel();
                    dialog.dismiss();
                    showDialog();
                } else fireFileSelectedEvent(chosenFile);
            }
        });

        dialog = builder.show();
        return dialog;
    }


    public void addFileListener(FileSelectedListener listener) {
        fileListenerList.add(listener);
    }

    public void removeFileListener(FileSelectedListener listener) {
        fileListenerList.remove(listener);
    }

    public void setSelectDirectoryOption(boolean selectDirectoryOption) {
        this.selectDirectoryOption = selectDirectoryOption;
    }

    public void addDirectoryListener(DirectorySelectedListener listener) {
        dirListenerList.add(listener);
    }

    public void removeDirectoryListener(DirectorySelectedListener listener) {
        dirListenerList.remove(listener);
    }

    /**
    * Show file dialog
    */
    public void showDialog() {
        createFileDialog().show();
    }

    private void fireFileSelectedEvent(final File file) {
        fileListenerList.fireEvent(new FireHandler<FileDialog.FileSelectedListener>() {
            public void fireEvent(FileSelectedListener listener) {
                listener.fileSelected(file);
            }
        });
    }

    private void fireDirectorySelectedEvent(final File directory) {
        dirListenerList.fireEvent(new FireHandler<FileDialog.DirectorySelectedListener>() {
            public void fireEvent(DirectorySelectedListener listener) {
                listener.directorySelected(directory);
            }
        });
    }

    private void loadFileList(File path) {
        this.currentPath = path;
        List<String> r = new ArrayList<String>();
        if (path.exists()) {
            if (path.getParentFile() != null) r.add(PARENT_DIR);
            FilenameFilter filter = new FilenameFilter() {
                public boolean accept(File dir, String filename) {
                    File sel = new File(dir, filename);
                    if (!sel.canRead()) return false;
                    if (selectDirectoryOption) return sel.isDirectory();
                    else {
                        boolean endsWith = fileEndsWith != null ? filename.toLowerCase().endsWith(fileEndsWith) : true;
                        return endsWith || sel.isDirectory();
                    }
                }
            };
            String[] fileList1 = path.list(filter);
            for (String file : fileList1) {
                r.add(file);
            }
        }
        fileList = (String[]) r.toArray(new String[]{});
    }

    private File getChosenFile(String fileChosen) {
        if (fileChosen.equals(PARENT_DIR)) return currentPath.getParentFile();
        else return new File(currentPath, fileChosen);
    }

    private void setFileEndsWith(String fileEndsWith) {
        this.fileEndsWith = fileEndsWith != null ? fileEndsWith.toLowerCase() : fileEndsWith;
    }
}

class ListenerList<L> {
    private List<L> listenerList = new ArrayList<L>();

    public interface FireHandler<L> {
        void fireEvent(L listener);
    }

    public void add(L listener) {
        listenerList.add(listener);
    }

    public void fireEvent(FireHandler<L> fireHandler) {
        List<L> copy = new ArrayList<L>(listenerList);
        for (L l : copy) {
            fireHandler.fireEvent(l);
        }
    }

    public void remove(L listener) {
        listenerList.remove(listener);
    }

    public List<L> getListenerList() {
        return listenerList;
    }
}

Use it on activity onCreate (directory selection option is commented):

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    File mPath = new File(Environment.getExternalStorageDirectory() + "//DIR//");
    fileDialog = new FileDialog(this, mPath, ".txt");
    fileDialog.addFileListener(new FileDialog.FileSelectedListener() {
        public void fileSelected(File file) {
            Log.d(getClass().getName(), "selected file " + file.toString());
        }
    });
    //fileDialog.addDirectoryListener(new FileDialog.DirectorySelectedListener() {
    //  public void directorySelected(File directory) {
    //      Log.d(getClass().getName(), "selected dir " + directory.toString());
    //  }
    //});
    //fileDialog.setSelectDirectoryOption(false);
    fileDialog.showDialog();
}

Can I do Model->where('id', ARRAY) multiple where conditions?

WHERE AND SELECT Condition In Array Format Laravel

use DB;

$conditions = array(
    array('email', '=', '[email protected]')
);
$selected = array('id','name','email','mobile','created');
$result = DB::table('users')->select($selected)->where($conditions)->get();

draw diagonal lines in div background with CSS

Here is how I did this using the css clip-path property alongside relative and absolute positioning to create a more fancy cross.

_x000D_
_x000D_
.cross {_x000D_
  width:150px;_x000D_
  height: 150px;_x000D_
  border: 2px solid #555;_x000D_
  border-radius: 5px;_x000D_
  position: relative;_x000D_
  background: #efefef;_x000D_
}_x000D_
_x000D_
.cross .diag1{_x000D_
  position: absolute;_x000D_
  width:100%; height:100%;_x000D_
  clip-path: polygon(90% 0, 100% 0%, 10% 100%, 0% 100%);_x000D_
  background: #311B92;_x000D_
}_x000D_
_x000D_
.cross .diag2{_x000D_
  position: absolute;_x000D_
  width:100%; height:100%;_x000D_
  clip-path: polygon(0 0, 10% 0, 100% 100%, 90% 100%);_x000D_
  background: #1B5E20;_x000D_
}
_x000D_
<div class="cross">_x000D_
  <div class="diag1"></div>_x000D_
  <div class="diag2"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Here is a link to the code on codepen if you'd like to tweak it.

How to do a SQL NOT NULL with a DateTime?

I faced this problem where the following query doesn't work as expected:

select 1 where getdate()<>null

we expect it to show 1 because getdate() doesn't return null. I guess it has something to do with SQL failing to cast null as datetime and skipping the row! of course we know we should use IS or IS NOT keywords to compare a variable with null but when comparing two parameters it gets hard to handle the null situation. as a solution you can create your own compare function like the following:

CREATE FUNCTION [dbo].[fnCompareDates]
(
    @DateTime1 datetime,
    @DateTime2 datetime
)
RETURNS bit
AS
BEGIN
    if (@DateTime1 is null and @DateTime2 is null) return 1;
    if (@DateTime1 = @DateTime2) return 1;
    return 0
END

and re writing the query like:

select 1 where dbo.fnCompareDates(getdate(),null)=0

Avoiding NullPointerException in Java

Depending on what kind of objects you are checking you may be able to use some of the classes in the apache commons such as: apache commons lang and apache commons collections

Example:

String foo;
...
if( StringUtils.isBlank( foo ) ) {
   ///do something
}

or (depending on what you need to check):

String foo;
...
if( StringUtils.isEmpty( foo ) ) {
   ///do something
}

The StringUtils class is only one of many; there are quite a few good classes in the commons that do null safe manipulation.

Here follows an example of how you can use null vallidation in JAVA when you include apache library(commons-lang-2.4.jar)

public DOCUMENT read(String xml, ValidationEventHandler validationEventHandler) {
    Validate.notNull(validationEventHandler,"ValidationHandler not Injected");
    return read(new StringReader(xml), true, validationEventHandler);
}

And if you are using Spring, Spring also has the same functionality in its package, see library(spring-2.4.6.jar)

Example on how to use this static classf from spring(org.springframework.util.Assert)

Assert.notNull(validationEventHandler,"ValidationHandler not Injected");

Get a list of all functions and procedures in an Oracle database

Do a describe on dba_arguments, dba_errors, dba_procedures, dba_objects, dba_source, dba_object_size. Each of these has part of the pictures for looking at the procedures and functions.

Also the object_type in dba_objects for packages is 'PACKAGE' for the definition and 'PACKAGE BODY" for the body.

If you are comparing schemas on the same database then try:

select * from dba_objects 
   where schema_name = 'ASCHEMA' 
     and object_type in ( 'PROCEDURE', 'PACKAGE', 'FUNCTION', 'PACKAGE BODY' )
minus
select * from dba_objects 
where schema_name = 'BSCHEMA' 
  and object_type in ( 'PROCEDURE', 'PACKAGE', 'FUNCTION', 'PACKAGE BODY' )

and switch around the orders of ASCHEMA and BSCHEMA.

If you also need to look at triggers and comparing other stuff between the schemas you should take a look at the Article on Ask Tom about comparing schemas

How to use mongoose findOne

Use obj[0].nick and you will get desired result,

Circle-Rectangle collision detection (intersection)

I've a method which avoids the expensive pythagoras if not necessary - ie. when bounding boxes of the rectangle and the circle do not intersect.

And it'll work for non-euclidean too:

class Circle {
 // create the bounding box of the circle only once
 BBox bbox;

 public boolean intersect(BBox b) {
    // test top intersect
    if (lat > b.maxLat) {
        if (lon < b.minLon)
            return normDist(b.maxLat, b.minLon) <= normedDist;
        if (lon > b.maxLon)
            return normDist(b.maxLat, b.maxLon) <= normedDist;
        return b.maxLat - bbox.minLat > 0;
    }

    // test bottom intersect
    if (lat < b.minLat) {
        if (lon < b.minLon)
            return normDist(b.minLat, b.minLon) <= normedDist;
        if (lon > b.maxLon)
            return normDist(b.minLat, b.maxLon) <= normedDist;
        return bbox.maxLat - b.minLat > 0;
    }

    // test middle intersect
    if (lon < b.minLon)
        return bbox.maxLon - b.minLon > 0;
    if (lon > b.maxLon)
        return b.maxLon - bbox.minLon > 0;
    return true;
  }
}
  • minLat,maxLat can be replaced with minY,maxY and the same for minLon, maxLon: replace it with minX, maxX
  • normDist ist just a bit faster method then the full distance calculation. E.g. without the square-root in euclidean space (or without a lot of other stuff for haversine): dLat=(lat-circleY); dLon=(lon-circleX); normed=dLat*dLat+dLon*dLon. Of course if you use that normDist method you'll need to do create a normedDist = dist*dist; for the circle

See the full BBox and Circle code of my GraphHopper project.

Iterating through a range of dates in Python

Can't* believe this question has existed for 9 years without anyone suggesting a simple recursive function:

from datetime import datetime, timedelta

def walk_days(start_date, end_date):
    if start_date <= end_date:
        print(start_date.strftime("%Y-%m-%d"))
        next_date = start_date + timedelta(days=1)
        walk_days(next_date, end_date)

#demo
start_date = datetime(2009, 5, 30)
end_date   = datetime(2009, 6, 9)

walk_days(start_date, end_date)

Output:

2009-05-30
2009-05-31
2009-06-01
2009-06-02
2009-06-03
2009-06-04
2009-06-05
2009-06-06
2009-06-07
2009-06-08
2009-06-09

Edit: *Now I can believe it -- see Does Python optimize tail recursion? . Thank you Tim.

Get month and year from date cells Excel

You could right click on those cells, go to format, select custom, then type mm yyyy.

Inheritance and Overriding __init__ in python

In each class that you need to inherit from, you can run a loop of each class that needs init'd upon initiation of the child class...an example that can copied might be better understood...

class Female_Grandparent:
    def __init__(self):
        self.grandma_name = 'Grandma'

class Male_Grandparent:
    def __init__(self):
        self.grandpa_name = 'Grandpa'

class Parent(Female_Grandparent, Male_Grandparent):
    def __init__(self):
        Female_Grandparent.__init__(self)
        Male_Grandparent.__init__(self)

        self.parent_name = 'Parent Class'

class Child(Parent):
    def __init__(self):
        Parent.__init__(self)
#---------------------------------------------------------------------------------------#
        for cls in Parent.__bases__: # This block grabs the classes of the child
             cls.__init__(self)      # class (which is named 'Parent' in this case), 
                                     # and iterates through them, initiating each one.
                                     # The result is that each parent, of each child,
                                     # is automatically handled upon initiation of the 
                                     # dependent class. WOOT WOOT! :D
#---------------------------------------------------------------------------------------#



g = Female_Grandparent()
print g.grandma_name

p = Parent()
print p.grandma_name

child = Child()

print child.grandma_name

How to programmatically set style attribute in a view

I faced the same problem recently. here is how i solved it.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

    <!-- This is the special two colors background START , after this LinearLayout, you can add all view that have it for main background-->
    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:weightSum="2"

    android:background="#FFFFFF"
    android:orientation="horizontal"
    >

    <View
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#0000FF" />

    <View
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#F000F0" />
    </LinearLayout>
    <!-- This is the special two colors background END-->

   <TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:gravity="center"
    android:text="This Text is centered with a special backgound,
    You can add as much elements as you want as child of this RelativeLayout"
    android:textColor="#FFFFFF"
    android:textSize="20sp" />
</RelativeLayout>
  • I used a LinearLayout with android:weightSum="2"
  • I gave to the two child elements android:layout_weight="1" (I gave each 50% of the parent space(width & height))
  • And finally, i gave the two child element different background colors to have the final effect.

Thanks !

Checking if a string is empty or null in Java

You can leverage Apache Commons StringUtils.isEmpty(str), which checks for empty strings and handles null gracefully.

Example:

System.out.println(StringUtils.isEmpty("")); // true
System.out.println(StringUtils.isEmpty(null)); // true

Google Guava also provides a similar, probably easier-to-read method: Strings.isNullOrEmpty(str).

Example:

System.out.println(Strings.isNullOrEmpty("")); // true
System.out.println(Strings.isNullOrEmpty(null)); // true

Reading content from URL with Node.js

HTTP and HTTPS:

const getScript = (url) => {
    return new Promise((resolve, reject) => {
        const http      = require('http'),
              https     = require('https');

        let client = http;

        if (url.toString().indexOf("https") === 0) {
            client = https;
        }

        client.get(url, (resp) => {
            let data = '';

            // A chunk of data has been recieved.
            resp.on('data', (chunk) => {
                data += chunk;
            });

            // The whole response has been received. Print out the result.
            resp.on('end', () => {
                resolve(data);
            });

        }).on("error", (err) => {
            reject(err);
        });
    });
};

(async (url) => {
    console.log(await getScript(url));
})('https://sidanmor.com/');

failed to push some refs to [email protected]

Just switch the branch to main, It will surely work, and delete the project from Heroku remote. Delete all branches from local and use only one "main".

For reference: https://help.heroku.com/O0EXQZTA/how-do-i-switch-branches-from-master-to-main

Set the table column width constant regardless of the amount of text in its cells?

If you need one ore more fixed-width columns while other columns should resize, try setting both min-width and max-width to the same value.

How to pass data using NotificationCenter in swift 3.0 and NSNotificationCenter in swift 2.0?

For Swift 3

let imageDataDict:[String: UIImage] = ["image": image]

  // post a notification
  NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict) 
  // `default` is now a property, not a method call

 // Register to receive notification in your class
 NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

 // handle notification
 func showSpinningWheel(_ notification: NSNotification) {
        print(notification.userInfo ?? "")
        if let dict = notification.userInfo as NSDictionary? {
            if let id = dict["image"] as? UIImage{
                // do something with your image
            }
        }
 }

For Swift 4

let imageDataDict:[String: UIImage] = ["image": image]

  // post a notification
  NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict) 
  // `default` is now a property, not a method call

 // Register to receive notification in your class
 NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

 // handle notification
 @objc func showSpinningWheel(_ notification: NSNotification) {
        print(notification.userInfo ?? "")
        if let dict = notification.userInfo as NSDictionary? {
            if let id = dict["image"] as? UIImage{
                // do something with your image
            }
        }
 }

How to import local packages in go?

Well, I figured out the problem. Basically Go starting path for import is $HOME/go/src

So I just needed to add myapp in front of the package names, that is, the import should be:

import (
    "log"
    "net/http"
    "myapp/common"
    "myapp/routers"
)

Select max value of each group

select name, max(value)
from out_pumptable
group by name

How to update record using Entity Framework 6?

Try It....

UpdateModel(book);

var book = new Model.Book
{
    BookNumber =  _book.BookNumber,
    BookName = _book.BookName,
    BookTitle = _book.BookTitle,
};
using (var db = new MyContextDB())
{
    var result = db.Books.SingleOrDefault(b => b.BookNumber == bookNumber);
    if (result != null)
    {
        try
        {
            UpdateModel(book);
            db.Books.Attach(book);
            db.Entry(book).State = EntityState.Modified;
            db.SaveChanges();
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}

Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?

I think the following is equivalent to the safe navigation operator, although a bit longer:

var streetName = user && user.address && user.address.street;

streetName will then be either the value of user.address.street or undefined.

If you want it to default to something else you can combine with the above shortcut or to give:

var streetName = (user && user.address && user.address.street) || "Unknown Street";

What is the "assert" function?

C++11 N3337 standard draft

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf

19.3 Assertions

1 The header <cassert>, described in (Table 42), provides a macro for documenting C ++ program assertions and a mechanism for disabling the assertion checks.

2 The contents are the same as the Standard C library header <assert.h>.

C99 N1256 standard draft

http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf

7.2 Diagnostics <assert.h>

1 The header <assert.h> defines the assert macro and refers to another macro, NDEBUG which is not defined by <assert.h>. If NDEBUG is defined as a macro name at the point in the source file where <assert.h> is included, the assert macro is defined simply as

 #define assert(ignore) ((void)0)

The assert macro is redefined according to the current state of NDEBUG each time that <assert.h> is included.

2. The assert macro shall be implemented as a macro, not as an actual function. If the macro definition is suppressed in order to access an actual function, the behavior is undefined.

7.2.1 Program diagnostics

7.2.1.1 The assert macro

Synopsis

1.

#include <assert.h>
void assert(scalar expression);

Description

2 The assert macro puts diagnostic tests into programs; it expands to a void expression. When it is executed, if expression (which shall have a scalar type) is false (that is, compares equal to 0), the assert macro writes information about the particular call that failed (including the text of the argument, the name of the source file, the source line number, and the name of the enclosing function — the latter are respectively the values of the preprocessing macros __FILE__ and __LINE__ and of the identifier __func__) on the standard error stream in an implementation-defined format. 165) It then calls the abort function.

Returns

3 The assert macro returns no value.

100% width table overflowing div container

Well, given your constraints, I think setting overflow: scroll; on the .page div is probably your only option. 280 px is pretty narrow, and given your font size, word wrapping alone isn't going to do it. Some words are just long and can't be wrapped. You can either reduce your font size drastically or go with overflow: scroll.

Using an array from Observable Object with ngFor and Async Pipe Angular 2

I think what u r looking for is this

<article *ngFor="let news of (news$ | async)?.articles">
<h4 class="head">{{news.title}}</h4>
<div class="desc"> {{news.description}}</div>
<footer>
    {{news.author}}
</footer>

WordPress Get the Page ID outside the loop

If you're using pretty permalinks, get_query_var('page_id') won't work.

Instead, get the queried object ID from the global $wp_query:

// Since 3.1 - recommended!
$page_object = get_queried_object();
$page_id     = get_queried_object_id();


// "Dirty" pre 3.1
global $wp_query;

$page_object = $wp_query->get_queried_object();
$page_id     = $wp_query->get_queried_object_id();

How can I represent an 'Enum' in Python?

What I use:

class Enum(object):
    def __init__(self, names, separator=None):
        self.names = names.split(separator)
        for value, name in enumerate(self.names):
            setattr(self, name.upper(), value)
    def tuples(self):
        return tuple(enumerate(self.names))

How to use:

>>> state = Enum('draft published retracted')
>>> state.DRAFT
0
>>> state.RETRACTED
2
>>> state.FOO
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
AttributeError: 'Enum' object has no attribute 'FOO'
>>> state.tuples()
((0, 'draft'), (1, 'published'), (2, 'retracted'))

So this gives you integer constants like state.PUBLISHED and the two-tuples to use as choices in Django models.

Add empty columns to a dataframe with specified names from a vector

set.seed(1)
example <- data.frame(col1 = rnorm(10, 0, 1), col2 = rnorm(10, 2, 3))
namevector <- c("col3", "col4")
example[ , namevector] <- NA

example
#          col1       col2 col3 col4
# 1  -0.6264538  6.5353435   NA   NA
# 2   0.1836433  3.1695297   NA   NA
# 3  -0.8356286  0.1362783   NA   NA
# 4   1.5952808 -4.6440997   NA   NA
# 5   0.3295078  5.3747928   NA   NA
# 6  -0.8204684  1.8651992   NA   NA
# 7   0.4874291  1.9514292   NA   NA
# 8   0.7383247  4.8315086   NA   NA
# 9   0.5757814  4.4636636   NA   NA
# 10 -0.3053884  3.7817040   NA   NA

SQL grouping by month and year

SELECT CAST(MONTH(date) AS VARCHAR(2)) + '-' + CAST(YEAR(date) AS VARCHAR(4)) AS Mjesec, SUM(marketingExpense) AS SumaMarketing, SUM(revenue) AS SumaZarada 
FROM [Order]
WHERE (idCustomer = 1) AND (date BETWEEN '2001-11-3' AND '2011-11-3')
GROUP BY CAST(MONTH(date) AS VARCHAR(2)) + '-' + CAST(YEAR(date) AS VARCHAR(4))

Or as @40-Love mentioned you can cast with leading zeroes:

GROUP BY 
  CAST(YEAR(date) AS VARCHAR(4)) + '-' + right('00' + CAST(MONTH(date) AS VARCHAR(2)), 2) 

How to increment datetime by custom months in python without using library

Well with some tweaks and use of timedelta here we go:

from datetime import datetime, timedelta


def inc_date(origin_date):
    day = origin_date.day
    month = origin_date.month
    year = origin_date.year
    if origin_date.month == 12:
        delta = datetime(year + 1, 1, day) - origin_date
    else:
        delta = datetime(year, month + 1, day) - origin_date
    return origin_date + delta

final_date = inc_date(datetime.today())
print final_date.date()

Calling a class method raises a TypeError in Python

To minimally modify your example, you could amend the code to:

class myclass(object):
        def __init__(self): # this method creates the class object.
                pass

        def average(self,a,b,c): #get the average of three numbers
                result=a+b+c
                result=result/3
                return result


mystuff=myclass()  # by default the __init__ method is then called.      
print mystuff.average(a,b,c)

Or to expand it more fully, allowing you to add other methods.

class myclass(object):
        def __init__(self,a,b,c):
                self.a=a
                self.b=b
                self.c=c
        def average(self): #get the average of three numbers
                result=self.a+self.b+self.c
                result=result/3
                return result

a=9
b=18
c=27
mystuff=myclass(a, b, c)        
print mystuff.average()

Add "Appendix" before "A" in thesis TOC

You can easily achieve what you want using the appendix package. Here's a sample file that shows you how. The key is the titletoc option when calling the package. It takes whatever value you've defined in \appendixname and the default value is Appendix.

\documentclass{report}
\usepackage[titletoc]{appendix}
\begin{document}
\tableofcontents

\chapter{Lorem ipsum}
\section{Dolor sit amet}
\begin{appendices}
  \chapter{Consectetur adipiscing elit}
  \chapter{Mauris euismod}
\end{appendices}
\end{document}

The output looks like

enter image description here

What is jQuery Unobtrusive Validation?

Brad Wilson has a couple great articles on unobtrusive validation and unobtrusive ajax.
It is also shown very nicely in this Pluralsight video in the section on " AJAX and JavaScript".

Basically, it is simply Javascript validation that doesn't pollute your source code with its own validation code. This is done by making use of data- attributes in HTML.

What is the difference between 'java', 'javaw', and 'javaws'?

java.exe is associated with the console, whereas javaw.exe doesn't have any such association. So, when java.exe is run, it automatically opens a command prompt window where output and error streams are shown.

The operation couldn’t be completed. (com.facebook.sdk error 2.) ios6

Another potential cause for this error: Attempting to get permission for a Facebook app in sandbox mode when the Facebook user is not listed in the app's admins, developers or testers.

Is there a .NET/C# wrapper for SQLite?

A barebones wrapper of the functions as provided by the sqlite library. Latest version supports functions provided sqlite library 3.7.10

SQLiteWrapper project

Make column fixed position in bootstrap

Use .col instead of col-lg-3 :

<div class="row">
   <div class="col">
      Fixed content
   </div>
   <div class="col-lg-9">
      Normal scrollable content
   </div>
</div>

How to change navigation bar color in iOS 7 or 6?

Try the code below in the - (void)viewDidLoad of your ViewController.m

[[[self navigationController] navigationBar] setTintColor:[UIColor yellowColor]];

this did work for me in iOS 6.. Try it..

async for loop in node.js

Node.js introduced async await in 7.6 so this makes Javascript more beautiful.

var results = [];
var config = JSON.parse(queries);
for (var key in config) {
  var query = config[key].query;
  results.push(await search(query));
}
res.writeHead( ... );
res.end(results);

For this to work search fucntion has to return a promise or it has to be async function

If it is not returning a Promise you can help it to return a Promise

function asyncSearch(query) {
  return new Promise((resolve, reject) => {
   search(query,(result)=>{
    resolve(result);
   })
  })
}

Then replace this line await search(query); by await asyncSearch(query);

getResourceAsStream returns null

The rules are as follows:

  1. check the location of the file you want to load inside the JAR (and thus also make sure it actually added to the JAR)
  2. use either an absolute path: path starts at the root of the JAR
  3. use an relative path: path starts at the package directory of the class you're calling getResource/ getResoucreAsStream

And try:

Lifepaths.class.getResourceAsStream("/initialization/Lifepaths.txt")

instead of

Lifepaths.class.getClass().getResourceAsStream("/initialization/Lifepaths.txt")

(not sure if it makes a difference, but the former will use the correct ClassLoader/ JAR, while I'm not sure with the latter)

How do you get the length of a list in the JSF expression language?

Note: This solution is better for older versions of JSTL. For versions greater then 1.1 I recommend using fn:length(MyBean.somelist) as suggested by Bill James.


This article has some more detailed information, including another possible solution;

The problem is that we are trying to invoke the list's size method (which is a valid LinkedList method), but it's not a JavaBeans-compliant getter method, so the expression list.size-1 cannot be evaluated.

There are two ways to address this dilemma. First, you can use the RT Core library, like this:

<c_rt:out value='<%= list[list.size()-1] %>'/>

Second, if you want to avoid Java code in your JSP pages, you can implement a simple wrapper class that contains a list and provides access to the list's size property with a JavaBeans-compliant getter method. That bean is listed in Listing 2.25.

The problem with c_rt method is that you need to get the variable from request manually, because it doesn't recognize it otherwise. At this point you are putting in a lot of code for what should be built in functionality. This is a GIANT flaw in the EL.

I ended up using the "wrapper" method, here is the class for it;

public class CollectionWrapper {

    Collection collection;

    public CollectionWrapper(Collection collection) {
        this.collection = collection;
    }

    public Collection getCollection() {
        return collection;
    }

    public int getSize() {
        return collection.size();
    }
}

A third option that no one has mentioned yet is to put your list size into the model (assuming you are using MVC) as a separate attribute. So in your model you would have "someList" and then "someListSize". That may be simplest way to solve this issue.

How can I reference a dll in the GAC from Visual Studio?

In VS, right click your project, select "Add Reference...", and you will see all the namespaces that exist in your GAC. Choose Microsoft.SqlServer.Management.RegisteredServers and click OK, and you should be good to go

EDIT:

That is the way you want to do this most of the time. However, after a bit of poking around I found this issue on MS Connect. MS says it is a known deployment issue, and they don't have a work around. The guy says if he copies the dll from the GAC folder and drops it in his bin, it works.

How long is the SHA256 hash?

I prefer to use BINARY(32) since it's the optimized way!

You can place in that 32 hex digits from (00 to FF).

Therefore BINARY(32)!

Rules for C++ string literals escape character

With the magic of user-defined literals, we have yet another solution to this. C++14 added a std::string literal operator.

using namespace std::string_literals;
auto const x = "\0" "0"s;

Constructs a string of length 2, with a '\0' character (null) followed by a '0' character (the digit zero). I am not sure if it is more or less clear than the initializer_list<char> constructor approach, but it at least gets rid of the ' and , characters.

What causes signal 'SIGILL'?

It could be some un-initialized function pointer, in particular if you have corrupted memory (then the bogus vtable of C++ bad pointers to invalid objects might give that).

BTW gdb watchpoints & tracepoints, and also valgrind might be useful (if available) to debug such issues. Or some address sanitizer.

Visual Studio can't 'see' my included header files

I know this is an older question, but none of the above answers worked for me. In my case, the issue turned out to be that I had absolute include paths but without drive letters. Compilation was fine, but Visual Studio couldn't find an include file when I right-clicked and tried to open it. Adding the drive letters to my include paths corrected the problem.

I would never recommend hard-coding drive letters in any aspect of your project files; either use relative paths, macros, environment variables, or some mix of the tree for any permanent situation. However, in this case, I'm working in some temporary projects where absolute paths were necessary in the short term. Not being able to right-click to open the files was extremely frustrating, and hopefully this will help others.

How to call VS Code Editor from terminal / command line

Sometimes setting path from VS Code command palette does not work

Instead manually add your VS Code to your path:

  1. Run in terminal

    sudo nano /etc/paths

  2. Go to the bottom of the file, and enter the path you wish to add

  3. Hit control-x to quit. Enter “Y” to save the modified buffer.

  4. Restart your terminal and to test echo $PATH. You should something similar

~ echo $PATH /Users/shashank/.nvm/versions/node/v8.9.2/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Applications/Visual Studio Code.app/Contents/Resources/app/bin

Next time, you navigate to your project folder from terminal

Enter:

code .

or

code /path/to/project

Source

How do I mock an autowired @Value field in Spring with Mockito?

You can use this magic Spring Test annotation :

@TestPropertySource(properties = { "my.spring.property=20" }) 

see org.springframework.test.context.TestPropertySource

For example, this is the test class :

@ContextConfiguration(classes = { MyTestClass.Config.class })
@TestPropertySource(properties = { "my.spring.property=20" })
public class MyTestClass {

  public static class Config {
    @Bean
    MyClass getMyClass() {
      return new MyClass ();
    }
  }

  @Resource
  private MyClass myClass ;

  @Test
  public void myTest() {
   ...

And this is the class with the property :

@Component
public class MyClass {

  @Value("${my.spring.property}")
  private int mySpringProperty;
   ...

Difference between CLOB and BLOB from DB2 and Oracle Perspective?

BLOB primarily intended to hold non-traditional data, such as images,videos,voice or mixed media. CLOB intended to retain character-based data.

Set default syntax to different filetype in Sublime Text 2

You can turn on syntax highlighting based on the contents of the file.

For example, my Makefiles regardless of their extension the first line as follows:

#-*-Makefile-*- vim:syntax=make

This is typical practice for other editors such as vim.

However, for this to work you need to modify the Makefile.tmLanguage file.

  1. Find the file (for Sublime Text 3 in Ubuntu) at:

    /opt/sublime_text/Packages/Makefile.sublime-package
    

Note, that is really a zip file. Copy it, rename with .zip at the end, and extract the Makefile.tmLanguage file from it.

  1. Edit the new Makefile.tmLanguage by adding the "firstLineMatch" key and string after the "fileTypes" section. In the example below, the last two lines are new (should be added by you). The <string> section holds the regular expression, that will enable syntax highlighting for the files that match the first line. This expression recognizes two patterns: "-*-Makefile-*-" and "vim:syntax=make".

    ...
    <key>fileTypes</key>
    <array>
        <string>GNUmakefile</string>
        <string>makefile</string>
        <string>Makefile</string>
        <string>OCamlMakefile</string>
        <string>make</string>
    </array>
    
    <key>firstLineMatch</key>
    <string>^#\s*-\*-Makefile-\*-|^#.*\s*vim:syntax=make</string>
    
  2. Place the modified Makefile.tmLanguage in the User settings directory:

    ~/.config/sublime-text-3/Packages/User/Makefile.tmLanguage
    

All the files matching the first line rule should turn the syntax highlighting on when opened.

How to add custom method to Spring Data JPA

The accepted answer works, but has three problems:

  • It uses an undocumented Spring Data feature when naming the custom implementation as AccountRepositoryImpl. The documentation clearly states that it has to be called AccountRepositoryCustomImpl, the custom interface name plus Impl
  • You cannot use constructor injection, only @Autowired, that are considered bad practice
  • You have a circular dependency inside of the custom implementation (that's why you cannot use constructor injection).

I found a way to make it perfect, though not without using another undocumented Spring Data feature:

public interface AccountRepository extends AccountRepositoryBasic,
                                           AccountRepositoryCustom 
{ 
}

public interface AccountRepositoryBasic extends JpaRepository<Account, Long>
{
    // standard Spring Data methods, like findByLogin
}

public interface AccountRepositoryCustom 
{
    public void customMethod();
}

public class AccountRepositoryCustomImpl implements AccountRepositoryCustom 
{
    private final AccountRepositoryBasic accountRepositoryBasic;

    // constructor-based injection
    public AccountRepositoryCustomImpl(
        AccountRepositoryBasic accountRepositoryBasic)
    {
        this.accountRepositoryBasic = accountRepositoryBasic;
    }

    public void customMethod() 
    {
        // we can call all basic Spring Data methods using
        // accountRepositoryBasic
    }
}

What is cardinality in Databases?

Definition: We have tables in database. In relational database, we have relations among the tables. These relations can be one-to-one, one-to-many or many-to-many. These relations are called 'cardinality'.

Significant of cardinality:

Many relational databases have been designed following stick business rules.When you design the database we define the cardinality based on the business rules. But every objects has its own nature as well.

When you define cardinality among object you have to consider all these things to define the correct cardinality.

Expand div to max width when float:left is set

The most cross-compatible way I've found of doing this is not very obvious. You need to remove the float from the second column, and apply overflow:hidden to it. Although this would seem to be hiding any content that goes outside of the div, it actually forces the div to stay within its parent.

Using your code, this is an example of how it could be done:

<div style="width: 100px; float: left;">menu</div>
<div style="overflow: hidden;">content</div>

Hope this is useful to anyone having this issue, it's what I found works the best for the site I was building, after trying to get it to adjust to other resolutions. Unfortunately, this doesn't to work if you include a right-floated div after the content as well, if anyone knows a good way to get that to work, with good IE compatibility, I'd be very happy to hear it.

New, better option using display: flex;

Now that the Flexbox model is fairly widely implemented, I'd actually recommend using it instead, since it allows much more flexibility with the layout. Here's a simple two-column like the original:

<div style="display: flex;">
    <div style="width: 100px;">menu</div>
    <div style="flex: 1;">content</div>
</div>

And here's a three-column with a flexible-width center column!

<div style="display: flex;">
    <div style="width: 100px;">menu</div>
    <div style="flex:1;">content</div>
    <div style="width: 100px;">sidebar</div>
</div>

ERROR Android emulator gets killed

For Android Studio v4.1 and above:

Menu -> Android Studio -> Preferences -> Tools -> Emulator

Uncheck Launch in a tool window option.

enter image description here

How to jump to a particular line in a huge text file?

Here's an example using 'readlines(sizehint)' to read a chunk of lines at a time. DNS pointed out that solution. I wrote this example because the other examples here are single-line oriented.

def getlineno(filename, lineno):
    if lineno < 1:
        raise TypeError("First line is line 1")
    f = open(filename)
    lines_read = 0
    while 1:
        lines = f.readlines(100000)
        if not lines:
            return None
        if lines_read + len(lines) >= lineno:
            return lines[lineno-lines_read-1]
        lines_read += len(lines)

print getlineno("nci_09425001_09450000.smi", 12000)

How to set default value to all keys of a dict object in python?

Is this what you want:

>>> d={'a':1,'b':2,'c':3}
>>> default_val=99
>>> for k in d:
...     d[k]=default_val
...     
>>> d
{'a': 99, 'b': 99, 'c': 99}
>>> 

>>> d={'a':1,'b':2,'c':3}
>>> from collections import defaultdict
>>> d=defaultdict(lambda:99,d)
>>> d
defaultdict(<function <lambda> at 0x03D21630>, {'a': 1, 'c': 3, 'b': 2})
>>> d[3]
99

Key Shortcut for Eclipse Imports

Some other useful shortcuts:

  1. Alt + Shift + R : Rename
  2. Alt + Shift + Y : Word wrap
  3. Alt + Shift + V : Move the selected elements
  4. Alt + Shift + I : Inline refactoring
  5. Alt + Shift + M : Extract Method refactoring.
  6. Alt + Shift + L : Extract Local Variable
  7. Alt + Shift + A : Block selection mode
  8. Alt + Shift + Arrow Keys: selects enclosing elements
  9. Alt + Shift + F1: Focus on eclipse element to know plugin implementation details.
  10. Alt + Shift + F2: Plugin implementation details.
  11. F4 : Type Hierarchy
  12. Ctrl + Shift + T : Open Type
  13. Ctrl + Shift + H: Open Type in Hierarchy
  14. Ctrl + Alt + H: Call Hierarchy
  15. Ctrl + Shift + G: Reference in workspace
  16. Ctrl + Alt + G: Quick Search for selected text
  17. Ctrl + Shift + O: Organize imports
  18. Ctrl + Shift + M: Add import for currently selected.
  19. Ctrl + Shift + L: Shows you a List of your currently defined shortcut keys
  20. Ctrl + Shift + U: Occurrence in current file
  21. Ctrl + Shift + A: Open plug-in Artifact
  22. Ctrl + Shift + {: Two side by side editors with current file
  23. Ctrl + Shift + Space : Parameter Hints
  24. Ctrl + Shift + Mouse hover : To view javadoc
  25. Shift + Mouse hover : To view source code
  26. Ctrl + Space : Content Assist
  27. Ctrl + F3/O : Outline
  28. Ctrl + T: Type Hierarchy
  29. Ctrl + H : Open Search Dialog
  30. Ctrl + 1 : Quick Fix
  31. Ctrl+Shift+NUM_KEYPAD_DIVIDE : Collapse All code blocks
  32. Ctrl+Shift+NUM_KEYPAD_MULTIPLY : To open all code blocks
  33. Alt + left arrow : Open recently closed file

Ctrl+Shift+ any key :Direct actions (on text mostly)

Alt+Shift+ any key : Indirect actions


Ctrl It was originally used to send Control character to terminals. Ctrl commands are commonly used shortcuts. (In Mac Command)

Alt It enables alternate uses for other keys.


The above shortcuts are default, if we want to change shortcuts we can do. In eclipse -> Windows -> preferences -> keys. Where we can find all shortcuts with full details:
enter image description here

and
https://shortcutworld.com/IntelliJ-IDEA/win/IntelliJ_Shortcuts https://shortcutworld.com/Eclipse/win/Eclipse-Helios_Shortcuts https://www.jetbrains.com/help/idea/migrating-from-eclipse-to-intellij-idea.html#Shortcuts

How to add header row to a pandas DataFrame

You can use names directly in the read_csv

names : array-like, default None List of column names to use. If file contains no header row, then you should explicitly pass header=None

Cov = pd.read_csv("path/to/file.txt", 
                  sep='\t', 
                  names=["Sequence", "Start", "End", "Coverage"])

Add a new line to the end of a JtextArea

When you want to create a new line or wrap in your TextArea you have to add \n (newline) after the text.

TextArea t = new TextArea();
t.setText("insert text when you want a new line add \nThen more text....);
setBounds();
setFont();
add(t);

This is the only way I was able to do it, maybe there is a simpler way but I havent discovered that yet.

How do I convert a file path to a URL in ASP.NET

So far as I know there's no single function which does this (maybe you were looking for the inverse of MapPath?). I'd love to know if such a function exists. Until then, I would just take the filename(s) returned by GetFiles, remove the path, and prepend the URL root. This can be done generically.

Measure string size in Bytes in php

You have to figure out if the string is ascii encoded or encoded with a multi-byte format.

In the former case, you can just use strlen.

In the latter case you need to find the number of bytes per character.

the strlen documentation gives an example of how to do it : http://www.php.net/manual/en/function.strlen.php#72274

Windows ignores JAVA_HOME: how to set JDK as default?

I have this issue too. I am running 1.6 but want to build the code I'm working on with 1.5. I've changed the JAVA_HOME and PATH (both user and system) to no avail.

The answer is that the installer for 1.6 dropped java.exe, javaw.exe, and javaws.exe into my Windows\System32 folder (Windows 7).

I solved it by renaming those files to java_wrong.exe, javaw_wrong.exe, and javaws_wrong.exe. Only after doing that does it pick up the correct version of java as defined in JAVA_HOME and PATH. I renamed the files thusly because that deleted them in an easily reversible manner.

Hope this helps!

HTML combo box with option to type an entry

This link can help you: http://www.scriptol.com/html5/combobox.php

You have two examples. One in html4 and other in html5

HTML5

<input type="text" list="browsers"/>
 <datalist id="browsers">
    <option>Google</option>
    <option>IE9</option>
 </datalist>

HTML4

 <input type="text" id="theinput" name="theinput" />
 <select name="thelist" onChange="combo(this, 'theinput')">
   <option>one</option>
   <option>two</option>
   <option>three</option>
 </select>
 function combo(thelist, theinput) {
     theinput = document.getElementById(theinput);
     var idx = thelist.selectedIndex;
     var content = thelist.options[idx].innerHTML;
     theinput.value = content;
 }

keyword not supported data source

I was getting the same error, then updated my connection string as below,

<add name="EmployeeContext" connectionString="data source=*****;initial catalog=EmployeeDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />

Try this it will solve your issue.

Java Synchronized list

You can have 2 diffent problems with lists :
1) If you do a modification within an iteration even though in a mono thread environment, you will have ConcurrentModificationException like in this following example :

List<String> list = new ArrayList<String>();
for (int i=0;i<5;i++)
   list.add("Hello "+i);

for(String msg:list)
   list.remove(msg);

So, to avoid this problem, you can do :

for(int i=list.size()-1;i>=0;i--)
   list.remove(i);

2)The second problem could be multi threading environment. As mentioned above, you can use synchronized(list) to avoid exceptions.

CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response

You have to add options also in allowed headers. browser sends a preflight request before original request is sent. See below

 res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');

From source https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS

In CORS, a preflight request with the OPTIONS method is sent, so that the server can respond whether it is acceptable to send the request with these parameters. The Access-Control-Request-Method header notifies the server as part of a preflight request that when the actual request is sent, it will be sent with a POST request method. The Access-Control-Request-Headers header notifies the server that when the actual request is sent, it will be sent with a X-PINGOTHER and Content-Type custom headers. The server now has an opportunity to determine whether it wishes to accept a request under these circumstances.

EDITED

You can avoid this manual configuration by using npmjs.com/package/cors npm package.I have used this method also, it is clear and easy.

Correct MySQL configuration for Ruby on Rails Database.yml file

If you have multiple databases for testing and development this might help

development:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: DBNAME
  pool: 5
  username: usr
  password: paswd
  shost: localhost
test:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: DBNAME
  pool: 5
  username: usr
  password: paswd
  shost: localhost
production:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: DBNAME
  pool: 5
  username: usr
  password: paswd
  shost: localhost

Appending to an object

How about storing the alerts as records in an array instead of properties of a single object ?

var alerts = [ 
    {num : 1, app:'helloworld',message:'message'},
    {num : 2, app:'helloagain',message:'another message'} 
]

And then to add one, just use push:

alerts.push({num : 3, app:'helloagain_again',message:'yet another message'});

jQuery multiple events to trigger the same function

You can use .on() to bind a function to multiple events:

$('#element').on('keyup keypress blur change', function(e) {
    // e.type is the type of event fired
});

Or just pass the function as the parameter to normal event functions:

var myFunction = function() {
   ...
}

$('#element')
    .keyup(myFunction)
    .keypress(myFunction)
    .blur(myFunction)
    .change(myFunction)

What's the difference between import java.util.*; and import java.util.Date; ?

You probably have some other "Date" class imported somewhere (or you have a Date class in you package, which does not need to be imported). With "import java.util.*" you are using the "other" Date. In this case it's best to explicitly specify java.util.Date in the code.

Or better, try to avoid naming your classes "Date".

How do I view / replay a chrome network debugger har file saved with content?

  1. Open Chrome & click F12
  2. Click Network
  3. Drag and drop the har file in the chrome network tab.

enter image description here

What's the difference between the Window.Loaded and Window.ContentRendered events

If you visit this link https://msdn.microsoft.com/library/ms748948%28v=vs.100%29.aspx#Window_Lifetime_Events and scroll down to Window Lifetime Events it will show you the event order.

Open:

  1. SourceInitiated
  2. Activated
  3. Loaded
  4. ContentRendered

Close:

  1. Closing
  2. Deactivated
  3. Closed

Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction

Html.Partial: returns MvcHtmlString and slow

Html.RenderPartial: directly render/write on output stream and returns void and it's very fast in comparison to Html.Partial

How can I get a specific number child using CSS?

For IE 7 & 8 (and other browsers without CSS3 support not including IE6) you can use the following to get the 2nd and 3rd children:

2nd Child:

td:first-child + td

3rd Child:

td:first-child + td + td

Then simply add another + td for each additional child you wish to select.

If you want to support IE6 that can be done too! You simply need to use a little javascript (jQuery in this example):

$(function() {
    $('td:first-child').addClass("firstChild");
    $(".table-class tr").each(function() {
        $(this).find('td:eq(1)').addClass("secondChild");
        $(this).find('td:eq(2)').addClass("thirdChild");
    });
});

Then in your css you simply use those class selectors to make whatever changes you like:

table td.firstChild { /*stuff here*/ }
table td.secondChild { /*stuff to apply to second td in each row*/ }

2D Euclidean vector rotations

Rotating a vector 90 degrees is particularily simple.

(x, y) rotated 90 degrees around (0, 0) is (-y, x).

If you want to rotate clockwise, you simply do it the other way around, getting (y, -x).

Regex doesn't work in String.matches()

Used

String[] words = {"{apf","hum_","dkoe","12f"};
    for(String s:words)
    {
        if(s.matches("[a-z]+"))
        {
            System.out.println(s);
        }
    }

How to stretch a fixed number of horizontal navigation items evenly and fully across a specified container

This is the sort of thing that the CSS flexbox model will fix, because it will let you specify that each li will receive an equal proportion of the remaining width.

How do I make a Docker container start automatically on system boot?

Yes, docker has restart policies such as docker run --restart=always that will handle this. This is also available in the compose.yml config file as restart: always.

Centering FontAwesome icons vertically and horizontally

So I finally got it(http://jsfiddle.net/ncapito/eYtU5/):

.centerWrapper:before {
    content:'';
    height: 100%;
    display: inline-block;
    vertical-align: middle;
}

.center {
    display:inline-block;
    vertical-align: middle;
}

<div class='row'>
    <div class='login-icon'>
        <div class='centerWrapper'>
            <div class='center'> <i class='icon-user'></i></div>
       </div>
    </div>
    <input type="text" placeholder="Email" />
 </div>

EOL conversion in notepad ++

In Notepad++, use replace all with regular expression. This has advantage over conversion command in menu that you can operate on entire folder w/o having to open each file or drag n drop (on several hundred files it will noticeably become slower) plus you can also set filename wildcard filter.

(\r?\n)|(\r\n?)

to

\n

This will match every possible line ending pattern (single \r, \n or \r\n) back to \n. (Or \r\n if you are converting to windows-style)

To operate on multiple files, either:

  • Use "Replace All in all opened document" in "Replace" tab. You will have to drag and drop all files into Notepad++ first. It's good that you will have control over which file to operate on but can be slow if there several hundreds or thousands files.
  • "Replace in files" in "Find in files" tab, by file filter of you choice, e.g., *.cpp *.cs under one specified directory.

Is it possible to display my iPhone on my computer monitor?

The latest SDKs (beginning with 2.2, I believe), include TV-Out functionality. With a special cable connected to the iPhone dock connector, a program can send RCA signals representing its current screen contents through the iPhone->RCA cable. If you have a TV Tuner for your computer (i.e. I have an EyeTV Hybrid) with RCA inputs, you can display the screen contents of your iPhone directly in the TV viewer.

Android, How to limit width of TextView (and add three dots at the end of text)?

code:

TextView your_text_view = (TextView) findViewById(R.id.your_id_textview);
your_text_view.setEllipsize(TextUtils.TruncateAt.END);

xml:

android:maxLines = "5"

e.g.

In Matthew 13, the disciples asked Jesus why He spoke to the crowds in parables. He answered, "It has been given to you to know the mysteries of the kingdom of heaven, but to them it has not been given.

Output: In Matthew 13, the disciples asked Jesus why He spoke to the crowds in parables. He answered, "It has been given to you to know...

How do you use colspan and rowspan in HTML tables?

If anyone is looking for a rowspan on both the left AND on the right, here is how you can do it:

_x000D_
_x000D_
table { _x000D_
    border-collapse: collapse;_x000D_
}_x000D_
_x000D_
td {_x000D_
    padding: 20px; _x000D_
    border: 1px solid black; _x000D_
    text-align: center;_x000D_
}
_x000D_
<table>_x000D_
    <tbody>_x000D_
    <tr>_x000D_
        <td rowspan="2">LEFT</td>_x000D_
        <td> 1 </td>_x000D_
        <td> 2 </td>_x000D_
        <td> 3 </td>_x000D_
        <td> 4 </td>_x000D_
        <td rowspan="2">RIGHT</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td> 5 </td>_x000D_
        <td> 6 </td>_x000D_
        <td> 7 </td>_x000D_
        <td> 8 </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
    </tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Alternatively, if you want to add the LEFT and RIGHT to an existing rowset, you can achieve the same result by throwing them in with a collapsed colspan in between:

_x000D_
_x000D_
table {_x000D_
    border-collapse: collapse;_x000D_
}_x000D_
_x000D_
td {_x000D_
    padding: 20px; _x000D_
    border: 1px solid black; _x000D_
    text-align: center;_x000D_
}
_x000D_
<table>_x000D_
    <tbody>_x000D_
    <tr>_x000D_
        <td rowspan="3">LEFT</td>_x000D_
        <td colspan="4" style="padding: 0; border-bottom: solid 1px transparent;"></td>_x000D_
        <td rowspan="3">RIGHT</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td> 1 </td>_x000D_
        <td> 2 </td>_x000D_
        <td> 3 </td>_x000D_
        <td> 4 </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td> 5 </td>_x000D_
        <td> 6 </td>_x000D_
        <td> 7 </td>_x000D_
        <td> 8 </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
    </tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Getting hold of the outer class object from the inner class object

The more general answer to this question involves shadowed variables and how they are accessed.

In the following example (from Oracle), the variable x in main() is shadowing Test.x:

class Test {
    static int x = 1;
    public static void main(String[] args) {
        InnerClass innerClassInstance = new InnerClass()
        {
            public void printX()
            {
                System.out.print("x=" + x);
                System.out.println(", Test.this.x=" + Test.this.x);
            }
        }
        innerClassInstance.printX();
    }

    public abstract static class InnerClass
    {
        int x = 0;

        public InnerClass() { }

        public abstract void printX();
    }
}

Running this program will print:

x=0, Test.this.x=1

More at: http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6

AngularJS - Access to child scope

You can try this:

$scope.child = {} //declare it in parent controller (scope)

then in child controller (scope) add:

var parentScope = $scope.$parent;
parentScope.child = $scope;

Now the parent has access to the child's scope.

Combine two or more columns in a dataframe into a new column with a new name

Using dplyr::mutate:

library(dplyr)
df <- mutate(df, x = paste(n, s)) 

df 
> df
  n  s     b    x
1 2 aa  TRUE 2 aa
2 3 bb FALSE 3 bb
3 5 cc  TRUE 5 cc

how to install tensorflow on anaconda python 3.6

I will simply leave this here because none of the other approaches worked for me. Also, I can look it up myself when I need it for new devices.

THIS IS THE WAY IT WORKS:

  1. Install Anaconda
  2. Open Anaconda Prompt
  3. conda create --name tensorflow
  4. conda activate tensorflow
  5. Search with conda search tensorflow for all available TensorFlow versions
  6. Choose the one you need (usually the newest one)
  7. Explicitly name the version now (otherwise it happened to me that version 1.14 was installed): conda install -c conda-forge tensorflow=YOUR_VERSION
  8. Open Anaconda, choose the new environment and install Spyder
  9. Install Microsoft Visual C++ Redistributable for Visual Studio 2015, 2017 and 2019
  10. Download msvcp140.dll and add the .dll-File to the Windows\System32 folder

Now it should work like a charm!

TROUBLESHOOTING:

If it still doesn't work, try this, it worked for me:

Open Anaconda-Prompt:

  1. Create an environment with Python 3.6 like this: conda create --name tensorflow_env python=3.6
  2. conda activate tensorflow
  3. Steps 6. and 6. from the list above
  4. conda install tensorflow=YOUR_VERSION(not forge, just like this!)
  5. Now do steps 8, 9, 10 from above

TENSORFLOW GPU:

If you want to use your GPU, do it the same way as described above, with the only difference to install tensorflow-gpu instead if tensorflow.

And, you must install the newest NVIDIA driver for your GPU, you can find and choose the right one here.

(Yes, in TF 2 there's both, a CPU and GPU support, in the "normal" library. However, if you install tensorflow-gpu via conda, it installs the CUDA and cudNN etc. you need automatically for you - also the right versions. This way easier and faster.)

A table name as a variable

You can't use a table name for a variable. You'd have to do this instead:

DECLARE @sqlCommand varchar(1000)
SET @sqlCommand = 'SELECT * from yourtable'
EXEC (@sqlCommand)

Insert Picture into SQL Server 2005 Image Field using only SQL

CREATE TABLE Employees
(
    Id int,
    Name varchar(50) not null,
    Photo varbinary(max) not null
)


INSERT INTO Employees (Id, Name, Photo) 
SELECT 10, 'John', BulkColumn 
FROM Openrowset( Bulk 'C:\photo.bmp', Single_Blob) as EmployeePicture

How do I resize an image using PIL and maintain its aspect ratio?

I was trying to resize some images for a slideshow video and because of that, I wanted not just one max dimension, but a max width and a max height (the size of the video frame).
And there was always the possibility of a portrait video...
The Image.thumbnail method was promising, but I could not make it upscale a smaller image.

So after I couldn't find an obvious way to do that here (or at some other places), I wrote this function and put it here for the ones to come:

from PIL import Image

def get_resized_img(img_path, video_size):
    img = Image.open(img_path)
    width, height = video_size  # these are the MAX dimensions
    video_ratio = width / height
    img_ratio = img.size[0] / img.size[1]
    if video_ratio >= 1:  # the video is wide
        if img_ratio <= video_ratio:  # image is not wide enough
            width_new = int(height * img_ratio)
            size_new = width_new, height
        else:  # image is wider than video
            height_new = int(width / img_ratio)
            size_new = width, height_new
    else:  # the video is tall
        if img_ratio >= video_ratio:  # image is not tall enough
            height_new = int(width / img_ratio)
            size_new = width, height_new
        else:  # image is taller than video
            width_new = int(height * img_ratio)
            size_new = width_new, height
    return img.resize(size_new, resample=Image.LANCZOS)

How to zoom in/out an UIImage object when user pinches screen?

Keep in mind that you're NEVER zooming in on a UIImage. EVER.

Instead, you're zooming in and out on the view that displays the UIImage.

In this particular case, you chould choose to create a custom UIView with custom drawing to display the image, a UIImageView which displays the image for you, or a UIWebView which will need some additional HTML to back it up.

In all cases, you'll need to implement touchesBegan, touchesMoved, and the like to determine what the user is trying to do (zoom, pan, etc.).

How to check if a "lateinit" variable has been initialized?

You can easily do this by:

::variableName.isInitialized

or

this::variableName.isInitialized

But if you are inside a listener or inner class, do this:

this@OuterClassName::variableName.isInitialized

Note: The above statements work fine if you are writing them in the same file(same class or inner class) where the variable is declared but this will not work if you want to check the variable of other class (which could be a superclass or any other class which is instantiated), for ex:

class Test {
    lateinit var str:String
}

And to check if str is initialized:

enter image description here

What we are doing here: checking isInitialized for field str of Test class in Test2 class. And we get an error backing field of var is not accessible at this point. Check a question already raised about this.

Python convert set to string and vice versa

Use repr and eval:

>>> s = set([1,2,3])
>>> strs = repr(s)
>>> strs
'set([1, 2, 3])'
>>> eval(strs)
set([1, 2, 3])

Note that eval is not safe if the source of string is unknown, prefer ast.literal_eval for safer conversion:

>>> from ast import literal_eval
>>> s = set([10, 20, 30])
>>> lis = str(list(s))
>>> set(literal_eval(lis))
set([10, 20, 30])

help on repr:

repr(object) -> string
Return the canonical string representation of the object.
For most object types, eval(repr(object)) == object.

how to get a list of dates between two dates in java

please find the below code.

List<Date> dates = new ArrayList<Date>();

String str_date ="27/08/2010";
String end_date ="02/09/2010";

DateFormat formatter ; 

formatter = new SimpleDateFormat("dd/MM/yyyy");
Date  startDate = (Date)formatter.parse(str_date); 
Date  endDate = (Date)formatter.parse(end_date);
long interval = 24*1000 * 60 * 60; // 1 hour in millis
long endTime =endDate.getTime() ; // create your endtime here, possibly using Calendar or Date
long curTime = startDate.getTime();
while (curTime <= endTime) {
    dates.add(new Date(curTime));
    curTime += interval;
}
for(int i=0;i<dates.size();i++){
    Date lDate =(Date)dates.get(i);
    String ds = formatter.format(lDate);    
    System.out.println(" Date is ..." + ds);
}

output:

Date is ...27/08/2010
Date is ...28/08/2010
Date is ...29/08/2010
Date is ...30/08/2010
Date is ...31/08/2010
Date is ...01/09/2010
Date is ...02/09/2010

Setting Java heap space under Maven 2 on Windows

If you are running out of heap space during the surefire (or failsafe) JUnit testing run, changing MAVEN_OPTS may not help you. I kept trying different configurations in MAVEN_OPTS with no luck until I found this post that fixed the problem.

Basically the JUnits fork off into their own environment and ignore the settings in MAVEN_OPTS. You need to configure surefire in your pom to add more memory for the JUnits.

Hopefully this can save someone else some time!


Edit: Copying solution from Keith Chapman's blog just in case the link breaks some day:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <configuration>
    <forkMode>pertest</forkMode> 
    <argLine>-Xms256m -Xmx512m</argLine>
    <testFailureIgnore>false</testFailureIgnore> 
    <skip>false</skip> 
    <includes> 
      <include>**/*IntegrationTestSuite.java</include>
    </includes>
  </configuration>
</plugin>

Update (5/31/2017): Thanks to @johnstosh for pointing this out - surefire has evolved a bit since I put this answer out there. Here is a link to their documentation and an updated code sample (arg line is still the important part for this question):

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.20</version>
    <configuration>
        <forkCount>3</forkCount>
        <reuseForks>true</reuseForks>
        <argLine>-Xmx1024m -XX:MaxPermSize=256m</argLine>
        <systemPropertyVariables>
            <databaseSchema>MY_TEST_SCHEMA_${surefire.forkNumber}</databaseSchema>
        </systemPropertyVariables>
        <workingDirectory>FORK_DIRECTORY_${surefire.forkNumber}</workingDirectory>
    </configuration>
  </plugin>

SQL Server - How to lock a table until a stored procedure finishes

BEGIN TRANSACTION

select top 1 *
from table1
with (tablock, holdlock)

-- You do lots of things here

COMMIT

This will hold the 'table lock' until the end of your current "transaction".

SMTPAuthenticationError when sending mail using gmail and python

Your code looks correct but sometimes google blocks an IP when you try to send a email from an unusual location. You can try to unblock it by visiting https://accounts.google.com/DisplayUnlockCaptcha from the IP and following the prompts.

Reference: https://support.google.com/accounts/answer/6009563

Splitting comma separated string in a PL/SQL stored proc

Many good solutions have been provided already. However, if he text is provided in a very simple comma delimited format or similar, and speed is of importance, then I have for you a solution with a TABLE function (in PL/SQL). I have also provided a rundown of some other solutions.

Please see more on the Blog Entry on Parsing a CSV into multiple columns.

How to display pandas DataFrame of floats using a format string for columns?

import pandas as pd
pd.options.display.float_format = '${:,.2f}'.format
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
                  index=['foo','bar','baz','quux'],
                  columns=['cost'])
print(df)

yields

        cost
foo  $123.46
bar  $234.57
baz  $345.68
quux $456.79

but this only works if you want every float to be formatted with a dollar sign.

Otherwise, if you want dollar formatting for some floats only, then I think you'll have to pre-modify the dataframe (converting those floats to strings):

import pandas as pd
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
                  index=['foo','bar','baz','quux'],
                  columns=['cost'])
df['foo'] = df['cost']
df['cost'] = df['cost'].map('${:,.2f}'.format)
print(df)

yields

         cost       foo
foo   $123.46  123.4567
bar   $234.57  234.5678
baz   $345.68  345.6789
quux  $456.79  456.7890

How do I specify "close existing connections" in sql script

I know it's too late but may be its helps some one. on using this take your database offline

ALTER DATABASE dbname SET OFFLINE

How can I fix the form size in a C# Windows Forms application and not to let user change its size?

Try to set

this.MinimumSize = new Size(140, 480);
this.MaximumSize = new Size(140, 480);

Converting an object to a string

/*
    This function is as JSON.Stringify (but if you has not in your js-engine you can use this)
    Params:
        obj - your object
        inc_ident - can be " " or "\t".
        show_types - show types of object or not
        ident - need for recoursion but you can not set this parameter.
*/
function getAsText(obj, inc_ident, show_types, ident) {
    var res = "";
    if (!ident)
        ident = "";
    if (typeof(obj) == "string") {
        res += "\"" + obj + "\" ";
        res += (show_types == true) ? "/* typeobj: " + typeof(obj) + "*/" : "";
    } else if (typeof(obj) == "number" || typeof(obj) == "boolean") {
        res += obj;
        res += (show_types == true) ? "/* typeobj: " + typeof(obj) + "*/" : "";
    } else if (obj instanceof Array) {
        res += "[ ";
        res += show_types ? "/* typeobj: " + typeof(obj) + "*/" : "";
        res += "\r\n";
        var new_ident = ident + inc_ident;
        var arr = [];
        for(var key in obj) {
            arr.push(new_ident + getAsText(obj[key], inc_ident, show_types, new_ident));
        } 
        res += arr.join(",\r\n") + "\r\n";
        res += ident + "]";
    } else {
        var new_ident = ident + inc_ident;      
        res += "{ ";
        res += (show_types == true) ? "/* typeobj: " + typeof(obj) + "*/" : "";
        res += "\r\n";
        var arr = [];
        for(var key in obj) {
            arr.push(new_ident + '"' + key + "\" : " + getAsText(obj[key], inc_ident, show_types, new_ident));
        }
        res += arr.join(",\r\n") + "\r\n";
        res += ident + "}\r\n";
    } 
    return res;
};

example to use:

var obj = {
    str : "hello",
    arr : ["1", "2", "3", 4],
b : true,
    vobj : {
        str : "hello2"
    }
}

var ForReading = 1, ForWriting = 2;
var fso = new ActiveXObject("Scripting.FileSystemObject")
f1 = fso.OpenTextFile("your_object1.txt", ForWriting, true)
f1.Write(getAsText(obj, "\t"));
f1.Close();

f2 = fso.OpenTextFile("your_object2.txt", ForWriting, true)
f2.Write(getAsText(obj, "\t", true));
f2.Close();

your_object1.txt:

{ 
    "str" : "hello" ,
    "arr" : [ 
        "1" ,
        "2" ,
        "3" ,
        4
    ],
    "b" : true,
    "vobj" : { 
        "str" : "hello2" 
    }

}

your_object2.txt:

{ /* typeobj: object*/
    "str" : "hello" /* typeobj: string*/,
    "arr" : [ /* typeobj: object*/
        "1" /* typeobj: string*/,
        "2" /* typeobj: string*/,
        "3" /* typeobj: string*/,
        4/* typeobj: number*/
    ],
    "b" : true/* typeobj: boolean*/,
    "vobj" : { /* typeobj: object*/
        "str" : "hello2" /* typeobj: string*/
    }

}

TSQL How do you output PRINT in a user defined function?

You can try returning the variable you wish to inspect. E.g. I have this function:

--Contencates seperate date and time strings and converts to a datetime. Date should be in format 25.03.2012. Time as 9:18:25.
ALTER FUNCTION [dbo].[ufn_GetDateTime] (@date nvarchar(11), @time nvarchar(11))
RETURNS datetime
AS
BEGIN

        --select dbo.ufn_GetDateTime('25.03.2012.', '9:18:25')

    declare @datetime datetime

    declare @day_part nvarchar(3)
    declare @month_part nvarchar(3)
    declare @year_part nvarchar(5)

    declare @point_ix int

    set @point_ix = charindex('.', @date)
    set @day_part = substring(@date, 0, @point_ix)

    set @date = substring(@date, @point_ix, len(@date) - @point_ix)
    set @point_ix = charindex('.', @date)

    set @month_part = substring(@date, 0, @point_ix)

    set @date = substring(@date, @point_ix, len(@date) - @point_ix)
    set @point_ix = charindex('.', @date)

    set @year_part = substring(@date, 0, @point_ix)

    set @datetime = @month_part + @day_part  + @year_part + ' ' + @time

    return @datetime
END

When I run it.. I get: Msg 241, Level 16, State 1, Line 1 Conversion failed when converting date and/or time from character string.

Arghh!!

So, what do I do?

ALTER FUNCTION [dbo].[ufn_GetDateTime] (@date nvarchar(11), @time nvarchar(11))
RETURNS nvarchar(22)
AS
BEGIN

        --select dbo.ufn_GetDateTime('25.03.2012.', '9:18:25')

    declare @day_part nvarchar(3)
    declare @point_ix int

    set @point_ix = charindex('.', @date)
    set @day_part = substring(@date, 0, @point_ix)

    return @day_part
END

And I get '25'. So, I am off by one and so I change to..

set @day_part = substring(@date, 0, @point_ix + 1)

Voila! Now it works :)

How to deselect all selected rows in a DataGridView control?

Thanks Cody heres the c# for ref:

if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            DataGridView.HitTestInfo hit = dgv_track.HitTest(e.X, e.Y);
            if (hit.Type == DataGridViewHitTestType.None)
            {
                dgv_track.ClearSelection();
                dgv_track.CurrentCell = null;
            }
        }

Does a finally block always get executed in Java?

That's actually true in any language...finally will always execute before a return statement, no matter where that return is in the method body. If that wasn't the case, the finally block wouldn't have much meaning.

Why does JSHint throw a warning if I am using const?

When you start using ECMAScript 6 this error thrown by your IDE.

There are two options available:

if you have only one file and want to use the es6 then simply add below line at the top of the file.

/*jshint esversion: 6 */

Or if you have number of js file or you are using any framework(like nodejs express)you can create a new file named .jshintrc in your root directory and add code below in the file:

{
    "esversion": 6
}

If you want to use the es6 version onward for each project you can configure your IDE.

How do I convert an existing callback API to promises?

When you have a few functions that take a callback and you want them to return a promise instead you can use this function to do the conversion.

function callbackToPromise(func){

    return function(){

        // change this to use what ever promise lib you are using
        // In this case i'm using angular $q that I exposed on a util module

        var defered = util.$q.defer();

        var cb = (val) => {
            defered.resolve(val);
        }

        var args = Array.prototype.slice.call(arguments);
        args.push(cb);    
        func.apply(this, args);

        return defered.promise;
    }
}

MySQL SELECT WHERE datetime matches day (and not necessarily time)

You can use %:

SELECT * FROM datetable WHERE datecol LIKE '2012-12-25%'

Python JSON encoding

Python lists translate to JSON arrays. What it is giving you is a perfectly valid JSON string that could be used in a Javascript application. To get what you expected, you would need to use a dict:

>>> json.dumps({'apple': 'cat', 'banana':'dog', 'pear':'fish'})
'{"pear": "fish", "apple": "cat", "banana": "dog"}'

python how to "negate" value : if true return false, if false return true

Use the not boolean operator:

nyval = not myval

not returns a boolean value (True or False):

>>> not 1
False
>>> not 0
True

If you must have an integer, cast it back:

nyval = int(not myval)

However, the python bool type is a subclass of int, so this may not be needed:

>>> int(not 0)
1
>>> int(not 1)
0
>>> not 0 == 1
True
>>> not 1 == 0
True

How to increase the Java stack size?

The only way to control the size of stack within process is start a new Thread. But you can also control by creating a self-calling sub Java process with the -Xss parameter.

public class TT {
    private static int level = 0;

    public static long fact(int n) {
        level++;
        return n < 2 ? n : n * fact(n - 1);
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(null, null, "TT", 1000000) {
            @Override
            public void run() {
                try {
                    level = 0;
                    System.out.println(fact(1 << 15));
                } catch (StackOverflowError e) {
                    System.err.println("true recursion level was " + level);
                    System.err.println("reported recursion level was "
                            + e.getStackTrace().length);
                }
            }

        };
        t.start();
        t.join();
        try {
            level = 0;
            System.out.println(fact(1 << 15));
        } catch (StackOverflowError e) {
            System.err.println("true recursion level was " + level);
            System.err.println("reported recursion level was "
                    + e.getStackTrace().length);
        }
    }

}

How to round up a number to nearest 10?

We can "cheat" via round with

$rounded = round($roundee / 10) * 10;

We can also avoid going through floating point division with

function roundToTen($roundee)
{
  $r = $roundee % 10;
  return ($r <= 5) : $roundee - $r : $roundee + (10 - $r);
}

Edit: I didn't know (and it's not well documented on the site) that round now supports "negative" precision, so you can more easily use

$round = round($roundee, -1);

Edit again: If you always want to round up, you can try

function roundUpToTen($roundee)
{
  $r = $roundee % 10;
  if ($r == 0)
    return $roundee;
  return $roundee + 10 - $r;    
}

Single vs double quotes in JSON

JSON syntax is not Python syntax. JSON requires double quotes for its strings.

TypeError: $ is not a function when calling jQuery function

(function( $ ) {
  "use strict";

  $(function() {

    //Your code here

  });

}(jQuery));

Bootstrap 4 File Input

I just solved it this way

Html:

<div class="custom-file">
   <input id="logo" type="file" class="custom-file-input">
   <label for="logo" class="custom-file-label text-truncate">Choose file...</label>
</div>

JS:

$('.custom-file-input').on('change', function() { 
   let fileName = $(this).val().split('\\').pop(); 
   $(this).next('.custom-file-label').addClass("selected").html(fileName); 
});

Note: Thanks to ajax333221 for mentioning the .text-truncate class that will hide the overflow within label if the selected file name is too long.

Find index of last occurrence of a sub-string using T-SQL

I came across this thread while searching for a solution to my similar problem which had the exact same requirement but was for a different kind of database that was also lacking the REVERSE function.

In my case this was for a OpenEdge (Progress) database, which has a slightly different syntax. This made the INSTR function available to me that most Oracle typed databases offer.

So I came up with the following code:

SELECT 
  INSTR(foo.filepath, '/',1, LENGTH(foo.filepath) - LENGTH( REPLACE( foo.filepath, '/',  ''))) AS IndexOfLastSlash 
FROM foo

However, for my specific situation (being the OpenEdge (Progress) database) this did not result into the desired behaviour because replacing the character with an empty char gave the same length as the original string. This doesn't make much sense to me but I was able to bypass the problem with the code below:

SELECT 
  INSTR(foo.filepath, '/',1, LENGTH( REPLACE( foo.filepath, '/',  'XX')) - LENGTH(foo.filepath))  AS IndexOfLastSlash 
FROM foo

Now I understand that this code won't solve the problem for T-SQL because there is no alternative to the INSTR function that offers the Occurence property.

Just to be thorough I'll add the code needed to create this scalar function so it can be used the same way like I did in the above examples.

  -- Drop the function if it already exists
  IF OBJECT_ID('INSTR', 'FN') IS NOT NULL
    DROP FUNCTION INSTR
  GO

  -- User-defined function to implement Oracle INSTR in SQL Server
  CREATE FUNCTION INSTR (@str VARCHAR(8000), @substr VARCHAR(255), @start INT, @occurrence INT)
  RETURNS INT
  AS
  BEGIN
    DECLARE @found INT = @occurrence,
            @pos INT = @start;

    WHILE 1=1 
    BEGIN
        -- Find the next occurrence
        SET @pos = CHARINDEX(@substr, @str, @pos);

        -- Nothing found
        IF @pos IS NULL OR @pos = 0
            RETURN @pos;

        -- The required occurrence found
        IF @found = 1
            BREAK;

        -- Prepare to find another one occurrence
        SET @found = @found - 1;
        SET @pos = @pos + 1;
    END

    RETURN @pos;
  END
  GO

To avoid the obvious, when the REVERSE function is available you do not need to create this scalar function and you can just get the required result like this:

SELECT
  LEN(foo.filepath) - CHARINDEX('/', REVERSE(foo.filepath))+1 AS LastIndexOfSlash 
FROM foo

What is the curl error 52 "empty reply from server"?

In case of SSL connections this may be caused by issue in older versions of nginx server that segfault during curl and Safari requests. This bug was fixed around version 1.10 of nginx but there is still a lot of older versions of nginx on the internet.

For nginx admins: adding ssl_session_cache shared:SSL:1m; to http block should solve the problem.

I'm aware that OP was asking for non-SSL case but since this is the top page in goole for "empty reply from server" issue, I'm leaving the SSL answer here as I was one of many that was banging my head against the wall with this issue.

How to rename a file using Python

If you are Using Windows and you want to rename your 1000s of files in a folder then: You can use the below code. (Python3)

import os

path = os.chdir(input("Enter the path of the Your Image Folder :  ")) #Here put the path of your folder where your images are stored

image_name = input("Enter your Image name : ") #Here, enter the name you want your images to have

i = 0

for file in os.listdir(path):

    new_file_name = image_name+"_" + str(i) + ".jpg" #here you can change the extention of your renmamed file.
    os.rename(file,new_file_name)

    i = i + 1

input("Renamed all Images!!")

Remove CSS from a Div using JQuery

You can remove specific css that is on the element like this:

$(this).css({'background-color' : '', 'font-weight' : ''});

Although I agree with karim that you should probably be using CSS classes.

Cannot find module cv2 when using OpenCV

Another way I got opencv to install and work was inside visual studio 2017 community. Visual studio has a nice python environment with debugging.
So from the vs python env window I searched and added opencv. Just thought I would share because I like to try things different ways and on different computers.

VisualStudio2017 python environments with opencv

How do I disable Git Credential Manager for Windows?

you can just delete the Credential Manager.

C:\Users\<USER>\AppData\Local\Programs\Git\mingw64\libexec\git-core

Find duplicate records in MySQL

SELECT date FROM logs group by date having count(*) >= 2

"Could not find a part of the path" error message

Is the drive E a mapped drive? Then, it can be created by another account other than the user account. This may be the cause of the error.

How to style components using makeStyles and still have lifecycle methods in Material UI?

Hi instead of using hook API, you should use Higher-order component API as mentioned here

I'll modify the example in the documentation to suit your need for class component

import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/styles';
import Button from '@material-ui/core/Button';

const styles = theme => ({
  root: {
    background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
    border: 0,
    borderRadius: 3,
    boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
    color: 'white',
    height: 48,
    padding: '0 30px',
  },
});

class HigherOrderComponentUsageExample extends React.Component {
  
  render(){
    const { classes } = this.props;
    return (
      <Button className={classes.root}>This component is passed to an HOC</Button>
      );
  }
}

HigherOrderComponentUsageExample.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(HigherOrderComponentUsageExample);

add an element to int [] array in java

int[] oldArray = {1,2,3,4,5};

    //new value
    int newValue = 10;

    //define the new array
    int[] newArray = new int[oldArray.length + 1];

    //copy values into new array
    for(int i=0;i < oldArray.length;i++)
        newArray[i] = oldArray[i];
    //another solution is to use 
    //System.arraycopy(oldArray, 0, newArray, 0, oldArray.length);

    //add new value to the new array
    newArray[newArray.length-1] = newValue;

    //copy the address to the old reference 
    //the old array values will be deleted by the Garbage Collector
    oldArray = newArray;

Get current URL from IFRAME

I had an issue with blob url hrefs. So, with a reference to the iframe, I just produced an url from the iframe's src attribute:

    const iframeReference = document.getElementById("iframe_id");
    const iframeUrl = iframeReference ? new URL(iframeReference.src) : undefined;
    if (iframeUrl) {
        console.log("Voila: " + iframeUrl);
    } else {
        console.warn("iframe with id iframe_id not found");
    }

How to create an Excel File with Nodejs?

You should check ExcelJS

Works with CSV and XLSX formats.

Great for reading/writing XLSX streams. I've used it to stream an XLSX download to an Express response object, basically like this:

app.get('/some/route', function(req, res) {
  res.writeHead(200, {
    'Content-Disposition': 'attachment; filename="file.xlsx"',
    'Transfer-Encoding': 'chunked',
    'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  })
  var workbook = new Excel.stream.xlsx.WorkbookWriter({ stream: res })
  var worksheet = workbook.addWorksheet('some-worksheet')
  worksheet.addRow(['foo', 'bar']).commit()
  worksheet.commit()
  workbook.commit()
}

Works great for large files, performs much better than excel4node (got huge memory usage & Node process "out of memory" crash after nearly 5 minutes for a file containing 4 million cells in 20 sheets) since its streaming capabilities are much more limited (does not allows to "commit()" data to retrieve chunks as soon as they can be generated)

See also this SO answer.

Deleting an SVN branch

You can also delete the branch on the remote directly. Having done that, the next update will remove it from your working copy.

svn rm "^/reponame/branches/name_of_branch" -m "cleaning up old branch name_of_branch"

The ^ is short for the URL of the remote, as seen in 'svn info'. The double quotes are necessary on Windows command line, because ^ is a special character.

This command will also work if you have never checked out the branch.

Double vs. BigDecimal?

There are two main differences from double:

  • Arbitrary precision, similarly to BigInteger they can contain number of arbitrary precision and size
  • Base 10 instead of Base 2, a BigDecimal is n*10^scale where n is an arbitrary large signed integer and scale can be thought of as the number of digits to move the decimal point left or right

The reason you should use BigDecimal for monetary calculations is not that it can represent any number, but that it can represent all numbers that can be represented in decimal notion and that include virtually all numbers in the monetary world (you never transfer 1/3 $ to someone).

How to continue the code on the next line in VBA

(i, j, n + 1) = k * b_xyt(xi, yi, tn) / (4 * hx * hy) * U_matrix(i + 1, j + 1, n) + _
(k * (a_xyt(xi, yi, tn) / hx ^ 2 + d_xyt(xi, yi, tn) / (2 * hx)))

From ms support

To continue a statement from one line to the next, type a space followed by the line-continuation character [the underscore character on your keyboard (_)].

You can break a line at an operator, list separator, or period.

How to get list of all installed packages along with version in composer?

Ivan's answer above is good:

composer global show -i

Added info: if you get a message somewhat like:

Composer could not find a composer.json file in ~/.composer

...you might have no packages installed yet. If so, you can ignore the next part of the message containing:

... please create a composer.json file ...

...as once you install a package the message will go away.

Using Mysql in the command line in osx - command not found?

So there are few places where terminal looks for commands. This places are stored in your $PATH variable. Think of it as a global variable where terminal iterates over to look up for any command. This are usually binaries look how /bin folder is usually referenced.

/bin folder has lots of executable files inside it. Turns out this are command. This different folder locations are stored inside one Global variable i.e. $PATH separated by :

Now usually programs upon installation takes care of updating PATH & telling your terminal that hey i can be all commands inside my bin folder.

Turns out MySql doesn't do it upon install so we manually have to do it.

We do it by following command,

export PATH=$PATH:/usr/local/mysql/bin

If you break it down, export is self explanatory. Think of it as an assignment. So export a variable PATH with value old $PATH concat with new bin i.e. /usr/local/mysql/bin

This way after executing it all the commands inside /usr/local/mysql/bin are available to us.

There is a small catch here. Think of one terminal window as one instance of program and maybe something like $PATH is class variable ( maybe ). Note this is pure assumption. So upon close we lose the new assignment. And if we reopen terminal we won't have access to our command again because last when we exported, it was stored in primary memory which is volatile.

Now we need to have our mysql binaries exported every-time we use terminal. So we have to persist concat in our path.

You might be aware that our terminal using something called dotfiles to load configuration on terminal initialisation. I like to think of it's as sets of thing passed to constructer every-time a new instance of terminal is created ( Again an assumption but close to what it might be doing ). So yes by now you get the point what we are going todo.

.bash_profile is one of the primary known dotfile.

So in following command,

echo 'export PATH=$PATH:/usr/local/mysql/bin' >> ~/.bash_profile

What we are doing is saving result of echo i.e. output string to ~/.bash_profile

So now as we noted above every-time we open terminal or instance of terminal our dotfiles are loaded. So .bash_profile is loaded respectively and export that we appended above is run & thus a our global $PATH gets updated and we get all the commands inside /usr/local/mysql/bin.

P.s.

if you are not running first command export directly but just running second in order to persist it? Than for current running instance of terminal you have to,

source ~/.bash_profile

This tells our terminal to reload that particular file.

Initialize Array of Objects using NSArray

There is also a shorthand of doing this:

NSArray *persons = @[person1, person2, person3];

It's equivalent to

NSArray *persons = [NSArray arrayWithObjects:person1, person2, person3, nil];

As iiFreeman said, you still need to do proper memory management if you're not using ARC.

Retrieve data from website in android app

Use this

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.someplace.com");
ResponseHandler<String> resHandler = new BasicResponseHandler();
String page = httpClient.execute(httpGet, resHandler);

This can be used to grab the whole webpage as a string of html, i.e., "<html>...</html>"

Note You need to declare the following 'uses-permission' in the android manifest xml file... answer by @Squonk here

And also check this answer

how to check if item is selected from a comboBox in C#

I've found that using this null comparison works well:

if (Combobox.SelectedItem != null){
   //Do something
}
else{
  MessageBox.show("Please select a item");
}

This will only accept the selected item and no other value which may have been entered manually by the user which could cause validation issues.

Combine Points with lines with ggplot2

You may find that using the `group' aes will help you get the result you want. For example:

tu <- expand.grid(Land       = gl(2, 1, labels = c("DE", "BB")),
                  Altersgr   = gl(5, 1, labels = letters[1:5]),
                  Geschlecht = gl(2, 1, labels = c('m', 'w')),
                  Jahr       = 2000:2009)

set.seed(42)
tu$Wert <- unclass(tu$Altersgr) * 200 + rnorm(200, 0, 10)

ggplot(tu, aes(x = Jahr, y = Wert, color = Altersgr, group = Altersgr)) + 
  geom_point() + geom_line() + 
  facet_grid(Geschlecht ~ Land)

Which produces the plot found here:

enter image description here

Printing long int value in C

To take input " long int " and output " long int " in C is :

long int n;
scanf("%ld", &n);
printf("%ld", n);

To take input " long long int " and output " long long int " in C is :

long long int n;
scanf("%lld", &n);
printf("%lld", n);

Hope you've cleared..

What's the best way to break from nested loops in JavaScript?

the best way is -
1) Sort the both array which are used in first and second loop.
2) if item matched then break the inner loop and hold the index value.
3) when start next iteration start inner loop with hold index value.

What's the use of ob_start() in php?

This function isn't just for headers. You can do a lot of interesting stuff with this. Example: You could split your page into sections and use it like this:

$someTemplate->selectSection('header');
echo 'This is the header.';

$someTemplate->selectSection('content');
echo 'This is some content.';

You can capture the output that is generated here and add it at two totally different places in your layout.

Is it possible to specify a different ssh port when using rsync?

use the "rsh option" . e.g.:

rsync -avz --rsh='ssh -p3382' root@remote_server_name:/opt/backups

refer to: http://www.linuxquestions.org/questions/linux-software-2/rsync-ssh-on-different-port-448112/

How to convert datetime to integer in python

This in an example that can be used for example to feed a database key, I sometimes use instead of using AUTOINCREMENT options.

import datetime 

dt = datetime.datetime.now()
seq = int(dt.strftime("%Y%m%d%H%M%S"))

Error retrieving parent for item: No resource found that matches the given name '@android:style/TextAppearance.Holo.Widget.ActionBar.Title'

I tried to change target sdk to 13 but does not works!! then when I changed compileSdkVersion 13 to compileSdkVersion 14 is compiled successfully :)

NOTE: I Work with Android Studio not Eclipse

Output single character in C

Be careful of difference between 'c' and "c"

'c' is a char suitable for formatting with %c

"c" is a char* pointing to a memory block with a length of 2 (with the null terminator).

Converting string to integer

The function you need is CInt.

ie CInt(PrinterLabel)

See Type Conversion Functions (Visual Basic) on MSDN

Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!

How should I pass an int into stringWithFormat?

Keep in mind that @"%d" will only work on 32 bit. Once you start using NSInteger for compatibility if you ever compile for a 64 bit platform, you should use @"%ld" as your format specifier.

Error when trying vagrant up

If you're using OS X and used the standard install, Delete vagrant's old curl and it should now work

sudo rm /opt/vagrant/embedded/bin/curl

Should I learn C before learning C++?

No.

It's generally more useful to learn C++ because it's closer to the most modern OO-based languages, like Eiffel or C#.

If your goal is to learn C++, learn modern, standard C++ in the first place. Leave the mallocs aside.


But Steve Rowe has a point...

Getting the document object of an iframe

In my case, it was due to Same Origin policies. To explain it further, MDN states the following:

If the iframe and the iframe's parent document are Same Origin, returns a Document (that is, the active document in the inline frame's nested browsing context), else returns null.

Pass variables from servlet to jsp

If you are using Action, Actionforward way to process business logic and next page to show, check out if redirect is called. As many others pointed out, redirecting doesn't keep your original request since it is basically forcing you to make a new request to designated path. So the value set in original request will be vanished if you use redirection instead of requestdispatch.

How to push elements in JSON from javascript array

You can directly access BODY.values:

for (var ln = 0; ln < names.length; ln++) {
  var item1 = {
    "person": {
      "_path": "/people/"+names[ln],
    },
  };

  BODY.values.push(item1);
}

When to use static classes in C#

Based on MSDN:

  1. You cannot create the instance for static classes
  2. If the class declared as static, member variable should be static for that class
  3. Sealed [Cannot be Inherited]
  4. Cannot contains Instance constructor
  5. Memory Management

Example: Math calculations (math values) does not changes [STANDARD CALCULATION FOR DEFINED VALUES]

Selecting a row in DataGridView programmatically

DataGridView.Rows
    .OfType<DataGridViewRow>()
     .Where(x => (int)x.Cells["Id"].Value == pId)
     .ToArray<DataGridViewRow>()[0]
     .Selected = true;

Can you have multiple $(document).ready(function(){ ... }); sections?

Yes you can.

Multiple document ready sections are particularly useful if you have other modules haging off the same page that use it. With the old window.onload=func declaration, every time you specified a function to be called, it replaced the old.

Now all functions specified are queued/stacked (can someone confirm?) regardless of which document ready section they are specified in.

Why is my element value not getting changed? Am I using the wrong function?

It's document.getElementById, not document.getElementsByID

I'm assuming you have <input id="Tue" ...> somewhere in your markup.

Subset and ggplot2

Try filter to subset only the rows of P1 and P3

df2 <- filter(df, ID == "P1" | ID == "P3")

Than yo can plot Value1. vs Value2.

How to show changed file name only with git log?

This gives almost what you need:

git log --stat --oneline

Commit id + short one line still remains, followed by list of changed files by that commit.

How do I run a batch file from my Java Application?

Batch files are not an executable. They need an application to run them (i.e. cmd).

On UNIX, the script file has shebang (#!) at the start of a file to specify the program that executes it. Double-clicking in Windows is performed by Windows Explorer. CreateProcess does not know anything about that.

Runtime.
   getRuntime().
   exec("cmd /c start \"\" build.bat");

Note: With the start \"\" command, a separate command window will be opened with a blank title and any output from the batch file will be displayed there. It should also work with just `cmd /c build.bat", in which case the output can be read from the sub-process in Java if desired.

Include .so library in apk in android studio

To include native libraries you need:

  1. create "jar" file with special structure containing ".so" files;
  2. include that file in dependencies list.

To create jar file, use the following snippet:

task nativeLibsToJar(type: Zip, description: 'create a jar archive of the native libs') {
    destinationDir file("$buildDir/native-libs")
    baseName 'native-libs'
    extension 'jar'
    from fileTree(dir: 'libs', include: '**/*.so')
    into 'lib/'
}

tasks.withType(Compile) {
    compileTask -> compileTask.dependsOn(nativeLibsToJar)
}

To include resulting file, paste the following line into "dependencies" section in "build.gradle" file:

compile fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar')

Launch Android application without main Activity and start Service on launching application

Yes you can do that by just creating a BroadcastReceiver that calls your Service when your Application boots. Here is a complete answer given by me.
Android - Start service on boot

If you don't want any icon/launcher for you Application you can do that also, just don't create any Activity with

<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

Just declare your Service as declared normally.

What does the 'b' character do in front of a string literal?

Here's an example where the absence of b would throw a TypeError exception in Python 3.x

>>> f=open("new", "wb")
>>> f.write("Hello Python!")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' does not support the buffer interface

Adding a b prefix would fix the problem.

Get string between two strings in a string

If you want to handle multiple occurrences of substring pairs, it won't be easy without RegEx:

Regex.Matches(input ?? String.Empty, "(?=key : )(.*)(?<= - )", RegexOptions.Singleline);
  • input ?? String.Empty avoids argument null exception
  • ?= keeps 1st substring and ?<= keeps 2nd substring
  • RegexOptions.Singleline allows newline between substring pair

If order & occurrence count of substrings doesn't matter, this quick & dirty one may be an option:

var parts = input?.Split(new string[] { "key : ", " - " }, StringSplitOptions.None);
string result = parts?.Length >= 3 ? result[1] : input;

At least it avoids most exceptions, by returning the original string if none/single substring match.

Best way to get the max value in a Spark dataframe column

First add the import line:

from pyspark.sql.functions import min, max

To find the min value of age in the dataframe:

df.agg(min("age")).show()

+--------+
|min(age)|
+--------+
|      29|
+--------+

To find the max value of age in the dataframe:

df.agg(max("age")).show()

+--------+
|max(age)|
+--------+
|      77|
+--------+

SSL handshake alert: unrecognized_name error since upgrade to Java 1.7.0

Java 7 introduced SNI support which is enabled by default. I have found out that certain misconfigured servers send an "Unrecognized Name" warning in the SSL handshake which is ignored by most clients... except for Java. As @Bob Kerns mentioned, the Oracle engineers refuse to "fix" this bug/feature.

As workaround, they suggest to set the jsse.enableSNIExtension property. To allow your programs to work without re-compiling, run your app as:

java -Djsse.enableSNIExtension=false yourClass

The property can also be set in the Java code, but it must be set before any SSL actions. Once the SSL library has loaded, you can change the property, but it won't have any effect on the SNI status. To disable SNI on runtime (with the aforementioned limitations), use:

System.setProperty("jsse.enableSNIExtension", "false");

The disadvantage of setting this flag is that SNI is disabled everywhere in the application. In order to make use of SNI and still support misconfigured servers:

  1. Create a SSLSocket with the host name you want to connect to. Let's name this sslsock.
  2. Try to run sslsock.startHandshake(). This will block until it is done or throw an exception on error. Whenever an error occurred in startHandshake(), get the exception message. If it equals to handshake alert: unrecognized_name, then you have found a misconfigured server.
  3. When you have received the unrecognized_name warning (fatal in Java), retry opening a SSLSocket, but this time without a host name. This effectively disables SNI (after all, the SNI extension is about adding a host name to the ClientHello message).

For the Webscarab SSL proxy, this commit implements the fall-back setup.

When is a language considered a scripting language?

A script is a relatively small program. A system is a relatively large program, or a collection of relatively large programs.

Some programming languages are designed with features that the language designer and the programming community consider to be useful when writing relatively small programs. These programming languages are known as scripting languages, e.g. PHP.

Similarly, other programming languages are designed with features that the language designer and the programming community consider to be useful when writing relatively large programs. These programming languages are known as systems languages, e.g. Java.

Now, small and large programs can be written in any language. A small Java program is a script. For example, a Java "Hello World" program is a script, not a system. A large program, or collection of programs, written in PHP is a system. For example, Facebook, written in PHP, is a system, not a script.

Considering a single language feature as a "litmus test" for deciding whether the language is best suited for scripting or systems programming is questionable. For example, scripts may be compiled to byte code or machine code, or they may be executed by direct abstract syntax tree (AST) interpretation.

So, a language is a scripting language if it is typically used to write scripts. A scripting language might be used to write systems, but such applications are likely to be considered dubious.

Convert string into integer in bash script - "Leading Zero" number error

See ARITHMETIC EVALUATION in man bash:

Constants with a leading 0 are interpreted as octal numbers.

You can remove the leading zero by parameter expansion:

hour=${hour#0}

or force base-10 interpretation:

$((10#$hour + 1))

How can I mark a foreign key constraint using Hibernate annotations?

@JoinColumn(name="reference_column_name") annotation can be used above that property or field of class that is being referenced from some other entity.

How do I set proxy for chrome in python webdriver?

Its working for me...

from selenium import webdriver

PROXY = "23.23.23.23:3128" # IP:PORT or HOST:PORT

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=http://%s' % PROXY)

chrome = webdriver.Chrome(chrome_options=chrome_options)
chrome.get("http://whatismyipaddress.com")

A Simple, 2d cross-platform graphics library for c or c++?

What about SDL?

Perhaps it's a bit too complex for your needs, but it's certainly cross-platform.

Why can't I use background image and color together?

Hello everyone I tried another way to combine background-image and background-color together:

HTML

<article><canvas id="color"></canvas></article>

CSS

article {
  height: 490px;
  background: url("Your IMAGE") no-repeat center cover;
  opacity:1;
} 

canvas{
  width: 100%; 
  height: 490px; 
  opacity: 0.9;
}

JAVASCRIPT

window.onload = init();

var canvas, ctx;

function init(){
  canvas = document.getElementeById('color'); 
  ctx = canvas.getContext('2d'); 
  ctx.save();  
  ctx.fillstyle = '#00833d'; 
  ctx.fillRect(0,0,490,490);ctx.restore();
}

Please let me know if it worked for you Thanks

Postgresql column reference "id" is ambiguous

You need the table name/alias in the SELECT part (maybe (vg.id, name)) :

SELECT (vg.id, name) FROM v_groups vg 
inner join people2v_groups p2vg on vg.id = p2vg.v_group_id
where p2vg.people_id =0;

Escape sequence \f - form feed - what exactly is it?

It's go to newline then add spaces to start second line at end of first line

Output

Hello
     Goodbye

Refresh DataGridView when updating data source

Well, it doesn't get much better than that. Officially, you should use

dataGridView1.DataSource = typeof(List); 
dataGridView1.DataSource = itemStates;

It's still a "clear/reset source" kind of solution, but I have yet to find anything else that would reliably refresh the DGV data source.

How to enable TLS 1.2 support in an Android application (running on Android 4.1 JB)

As the OP said, TLS v1.1 and v1.2 protocols are supported in API level 16+, but are not enabled by default, we just need to enable it.

Example here uses HttpsUrlConnection, not HttpUrlConnection. Follow https://blog.dev-area.net/2015/08/13/android-4-1-enable-tls-1-1-and-tls-1-2/, we can create a factory

class MyFactory extends SSLSocketFactory {

    private javax.net.ssl.SSLSocketFactory internalSSLSocketFactory;

    public MyFactory() throws KeyManagementException, NoSuchAlgorithmException {
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, null, null);
        internalSSLSocketFactory = context.getSocketFactory();
    }

    @Override
    public String[] getDefaultCipherSuites() {
        return internalSSLSocketFactory.getDefaultCipherSuites();
    }

    @Override
    public String[] getSupportedCipherSuites() {
        return internalSSLSocketFactory.getSupportedCipherSuites();
    }

    @Override
    public Socket createSocket() throws IOException {
        return enableTLSOnSocket(internalSSLSocketFactory.createSocket());
    }

    @Override
    public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
        return enableTLSOnSocket(internalSSLSocketFactory.createSocket(s, host, port, autoClose));
    }

    @Override
    public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
        return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port));
    }

    @Override
    public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
        return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port, localHost, localPort));
    }

    @Override
    public Socket createSocket(InetAddress host, int port) throws IOException {
        return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port));
    }

    @Override
    public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
        return enableTLSOnSocket(internalSSLSocketFactory.createSocket(address, port, localAddress, localPort));
    }

    private Socket enableTLSOnSocket(Socket socket) {
        if(socket != null && (socket instanceof SSLSocket)) {
            ((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1.2"});
        }
        return socket;
    }
}

No matter which Networking library you use, make sure ((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1.2"}); gets called so the Socket has enabled TLS protocols.

Now, you can use that in HttpsUrlConnection

class MyHttpRequestTask extends AsyncTask<String,Integer,String> {

    @Override
    protected String doInBackground(String... params) {
        String my_url = params[0];
        try {
            URL url = new URL(my_url);
            HttpsURLConnection httpURLConnection = (HttpsURLConnection) url.openConnection();
            httpURLConnection.setSSLSocketFactory(new MyFactory());
            // setting the  Request Method Type
            httpURLConnection.setRequestMethod("GET");
            // adding the headers for request
            httpURLConnection.setRequestProperty("Content-Type", "application/json");


            String result = readStream(httpURLConnection.getInputStream());
            Log.e("My Networking", "We have data" + result.toString());


        }catch (Exception e){
            e.printStackTrace();
            Log.e("My Networking", "Oh no, error occurred " + e.toString());
        }

        return null;
    }

    private static String readStream(InputStream is) throws IOException {
        final BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("US-ASCII")));
        StringBuilder total = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            total.append(line);
        }
        if (reader != null) {
            reader.close();
        }
        return total.toString();
    }
}

For example

new MyHttpRequestTask().execute(myUrl);

Also, remember to bump minSdkVersion in build.gradle to 16

minSdkVersion 16