Programs & Examples On #Wkhtmltopdf

A shell utility to convert HTML to PDF using the Webkit rendering engine and Qt.

Rails: Why "sudo" command is not recognized?

sudo is a command for Linux so it cant be used in windows so you will get that error

How to install wkhtmltopdf on a linux based (shared hosting) web server

After trying, below command work for me

cd ~
yum install -y xorg-x11-fonts-75dpi xorg-x11-fonts-Type1 openssl git-core fontconfig
wget https://downloads.wkhtmltopdf.org/0.12/0.12.4/wkhtmltox-0.12.4_linux-generic-amd64.tar.xz
tar xvf wkhtmltox-0.12.4_linux-generic-amd64.tar.xz
mv wkhtmltox/bin/wkhtmlto* /usr/bin

wkhtmltopdf: cannot connect to X server

Problem is probably in old version of wkhtmltopdf - version 0.9 from distribution repository require running X server, but current version - 0.12.2.1 doesnt require it - can run headless.

Download package for your distribution from http://wkhtmltopdf.org/downloads.html and install it - for Ubuntu:

sudo apt-get install xfonts-75dpi
sudo dpkg -i wkhtmltox-0.12.2.1_linux-trusty-amd64.deb

Getting the text from a drop-down box

function getValue(obj)
{  
   // it will return the selected text
   // obj variable will contain the object of check box
   var text = obj.options[obj.selectedIndex].innerHTML ; 

}

HTML Snippet

 <asp:DropDownList ID="ddl" runat="server" CssClass="ComboXXX" 
  onchange="getValue(this)">
</asp:DropDownList>

Iterating over dictionaries using 'for' loops

When you iterate through dictionaries using the for .. in ..-syntax, it always iterates over the keys (the values are accessible using dictionary[key]).

To iterate over key-value pairs, in Python 2 use for k,v in s.iteritems(), and in Python 3 for k,v in s.items().

Python - Create list with numbers between 2 values?

I got here because I wanted to create a range between -10 and 10 in increments of 0.1 using list comprehension. Instead of doing an overly complicated function like most of the answers above I just did this

simple_range = [ x*0.1 for x in range(-100, 100) ]

By changing the range count to 100 I now get my range of -10 through 10 by using the standard range function. So if you need it by 0.2 then just do range(-200, 200) and so on etc

check all socket opened in linux OS

Also you can use ss utility to dump sockets statistics.

To dump summary:

ss -s

Total: 91 (kernel 0)
TCP:   18 (estab 11, closed 0, orphaned 0, synrecv 0, timewait 0/0), ports 0

Transport Total     IP        IPv6
*         0         -         -        
RAW       0         0         0        
UDP       4         2         2        
TCP       18        16        2        
INET      22        18        4        
FRAG      0         0         0

To display all sockets:

ss -a

To display UDP sockets:

ss -u -a

To display TCP sockets:

ss -t -a

Here you can read ss man: ss

How do I capture SIGINT in Python?

thanks for existing answers, but added signal.getsignal()

import signal

# store default handler of signal.SIGINT
default_handler = signal.getsignal(signal.SIGINT)
catch_count = 0

def handler(signum, frame):
    global default_handler, catch_count
    catch_count += 1
    print ('wait:', catch_count)
    if catch_count > 3:
        # recover handler for signal.SIGINT
        signal.signal(signal.SIGINT, default_handler)
        print('expecting KeyboardInterrupt')

signal.signal(signal.SIGINT, handler)
print('Press Ctrl+c here')

while True:
    pass

How to turn NaN from parseInt into 0 for an empty string?

Also this way, why not write a function and call it where ever required . I'm assuming it's the entry into the form fields to perform calculations.

var Nanprocessor = function (entry) {
    if(entry=="NaN") {
        return 0;
    } else {
        return entry;
    }
}

 outputfield.value = Nanprocessor(x); 

// where x is a value that is collected from a from field
// i.e say x =parseInt(formfield1.value); 

what's wrong doing this?

What is callback in Android?

CallBack Interface are used for Fragment to Fragment communication in android.

Refer here for your understanding.

How to compile and run C files from within Notepad++ using NppExec plugin?

Here's a procedure for Perl, just adapt it for C. Hope it helps.

  • Open Notepad++
  • Type F6 to open the execute window
  • Write the following commands:
    • npp_save <-- Saves the current document
    • CD $(CURRENT_DIRECTORY) <-- Moves to the current directory
    • perl.exe -c -w "$(FILE_NAME)" <-- executes the command perl.exe -c -w , example: perl.exe -c -w test.pl (-c = compile -w = warnings)
  • Click on Save
  • Type a name to save the script (e.g. "Perl Compile")
  • Go to Menu Plugins -> Nppexec -> advanced options -> Menu Item (Note: this is right BELOW 'Menu Items *')
  • In the combobox titled 'Associated Script' select the script recently created in its dropdown menu, select Add/Modify and click OK -> OK
  • Restart Notepad++
  • Go to Settings -> Shortcut mapper -> Plugins -> search for the script name
  • Select the shortcut to use (ie Ctrl + 1), click OK
  • Verify that you can now run the script created with the shortcut selected.

ASP.NET MVC5/IIS Express unable to debug - Code Not Running

The solution to the above problem was a simple one. Close down dev environments, go to Documents folder and rename IISExpress. Now set environment variable _CSRUN_DISABLE_WORKAROUNDS ( ref: http://gauravmantri.com/2013/02/05/workaround-for-iis-express-crashing-when-running-windows-azure-cloud-service-web-role-with-multiple-instances-in-windows-azure-sdk-1-8-compute-emulator/ ).

Now reboot PC, start VS, load website and run in debug. IIS automatically regenerated the IISExpress folder and the environment variable resolved conflicts.

How to remove new line characters from data rows in mysql?

My 2 cents.

To get rid of my \n's I needed to do a \\n. Hope that helps someone.

update mytable SET title = TRIM(TRAILING '\\n' FROM title)

fetch in git doesn't get all branches

write it from the terminal

git fetch --prune.

it works fine.

How to change Android usb connect mode to charge only?

Nothing worked until I went this way: Settings>Developer options>Default USB configuration now you can choose your default USB connection purpose.

Difference between Running and Starting a Docker container

daniele3004's answer is already pretty good.

Just a quick and dirty formula for people like me who mixes up run and start from time to time:

docker run [...] = docker pull [...] + docker start [...]

How to save a new sheet in an existing excel file, using Pandas?

For creating a new file

x1 = np.random.randn(100, 2)
df1 = pd.DataFrame(x1)
with pd.ExcelWriter('sample.xlsx') as writer:  
    df1.to_excel(writer, sheet_name='x1')

For appending to the file, use the argument mode='a' in pd.ExcelWriter.

x2 = np.random.randn(100, 2)
df2 = pd.DataFrame(x2)
with pd.ExcelWriter('sample.xlsx', engine='openpyxl', mode='a') as writer:  
    df2.to_excel(writer, sheet_name='x2')

Default is mode ='w'. See documentation.

How can I convert ArrayList<Object> to ArrayList<String>?

You can use wildcard to do this as following

ArrayList<String> strList = (ArrayList<String>)(ArrayList<?>)(list);

ValueError: not enough values to unpack (expected 11, got 1)

For the line

line.split()

What are you splitting on? Looks like a CSV, so try

line.split(',')

Example:

"one,two,three".split()  # returns one element ["one,two,three"]
"one,two,three".split(',')  # returns three elements ["one", "two", "three"]

As @TigerhawkT3 mentions, it would be better to use the CSV module. Incredibly quick and easy method available here.

Why does Oracle not find oci.dll?

if you use 64-bit pc, oracle doesn't compatible with it. Oracle doesn't find oci.dll file in 64-bit.

Therefore, you can try to change oracle home on the top. As a result of that, home path will change.

At least, I solved that error with changing path.

Simple pagination in javascript

I created a class structure for collections in general that would meet this requirement. and it looks like this:

class Collection {

    constructor() {
        this.collection = [];
        this.index = 0;
    }

    log() {
        return console.log(this.collection);
    }

    push(value) {
        return this.collection.push(value);
    }

    pushAll(...values) {
        return this.collection.push(...values);
    }

    pop() {
        return this.collection.pop();
    }

    shift() {
        return this.collection.shift();
    }

    unshift(value) {
        return this.collection.unshift(value);
    }

    unshiftAll(...values) {
        return this.collection.unshift(...values);
    }

    remove(index) {
        return this.collection.splice(index, 1);
    }

    add(index, value) {
        return this.collection.splice(index, 0, value);
    }

    replace(index, value) {
        return this.collection.splice(index, 1, value);
    }

    clear() {
        this.collection.length = 0;
    }

    isEmpty() {
        return this.collection.length === 0;
    }

    viewFirst() {
        return this.collection[0];
    }

    viewLast() {
        return this.collection[this.collection.length - 1];
    }

    current(){
        if((this.index <= this.collection.length - 1) && (this.index >= 0)){
            return this.collection[this.index];
        }
        else{
            return `Object index exceeds collection range.`;
        }
    }

    next() {
        this.index++;
        this.index > this.collection.length - 1 ? this.index = 0 : this.index;
        return this.collection[this.index];
    }

    previous(){
        this.index--;
        this.index < 0 ? (this.index = this.collection.length-1) : this.index;
        return this.collection[this.index];
    }
}

...and essentially what you would do is have a collection of arrays of whatever length for your pages pushed into the class object, and then use the next() and previous() functions to display whatever 'page' (index) you wanted to display. Would essentially look like this:

let books = new Collection();
let firstPage - [['dummyData'], ['dummyData'], ['dummyData'], ['dummyData'], ['dummyData'],];
let secondPage - [['dumberData'], ['dumberData'], ['dumberData'], ['dumberData'], ['dumberData'],];
books.pushAll(firstPage, secondPage); // loads each array individually
books.current() // display firstPage
books.next() // display secondPage

What is the difference between json.dumps and json.load?

json loads -> returns an object from a string representing a json object.

json dumps -> returns a string representing a json object from an object.

load and dump -> read/write from/to file instead of string

React.js: Wrapping one component into another

In addition to Sophie's answer, I also have found a use in sending in child component types, doing something like this:

var ListView = React.createClass({
    render: function() {
        var items = this.props.data.map(function(item) {
            return this.props.delegate({data:item});
        }.bind(this));
        return <ul>{items}</ul>;
    }
});

var ItemDelegate = React.createClass({
    render: function() {
        return <li>{this.props.data}</li>
    }
});

var Wrapper = React.createClass({    
    render: function() {
        return <ListView delegate={ItemDelegate} data={someListOfData} />
    }
});

Manage toolbar's navigation and back button from fragment in android

You have to manage your back button pressed action on your main Activity because your main Activity is container for your fragment.

First, add your all fragment to transaction.addToBackStack(null) and now navigation back button call will be going on main activity. I hope following code will help you...

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        onBackPressed();
        }
    return super.onOptionsItemSelected(item);
}

you can also use

Fragment fragment =fragmentManager.findFragmentByTag(Constant.TAG); 
if(fragment!=null) {          
      FragmentTransaction transaction = fragmentManager.beginTransaction();
      transaction.remove(fragment).commit();
}

And to change the title according to fragment name from fragment you can use the following code:

activity.getSupportActionBar().setTitle("Keyword Report Detail");

Python sys.argv lists and indexes

As explained in the different asnwers already, sys.argv contains the command line arguments that called your Python script.

However, Python comes with libraries that help you parse command line arguments very easily. Namely, the new standard argparse. Using argparse would spare you the need to write a lot of boilerplate code.

The specified DSN contains an architecture mismatch between the Driver and Application. JAVA

By default, the Command Prompt is connected to System32. Run a 64-bit command prompt, i.e., C:\WINDOWS\SYSWOW64\CMD.EXE. In that, compile and run your java application.

What do the return values of Comparable.compareTo mean in Java?

It can be used for sorting, and 0 means "equal" while -1, and 1 means "less" and "more (greater)".

Any return value that is less than 0 means that left operand is lesser, and if value is bigger than 0 then left operand is bigger.

Which version of CodeIgniter am I currently using?

Yes, the constant CI_VERSION will give you the current CodeIgniter version number. It's defined in: /system/codeigniter/CodeIgniter.php As of CodeIgniter 2, it's defined in /system/core/CodeIgniter.php

For example,

echo CI_VERSION; // echoes something like 1.7.1

Is Spring annotation @Controller same as @Service?

From Spring In Action

As you can see, this class is annotated with @Controller. On its own, @Controller doesn’t do much. Its primary purpose is to identify this class as a component for component scanning. Because HomeController is annotated with @Controller, Spring’s component scanning automatically discovers it and creates an instance of HomeController as a bean in the Spring application context.

In fact, a handful of other annotations (including @Component, @Service, and @Repository) serve a purpose similar to @Controller. You could have just as effectively annotated HomeController with any of those other annotations, and it would have still worked the same. The choice of @Controller is, however, more descriptive of this component’s role in the application.

Creating all possible k combinations of n items in C++

I thought my simple "all possible combination generator" might help someone, i think its a really good example for building something bigger and better

you can change N (characters) to any you like by just removing/adding from string array (you can change it to int as well). Current amount of characters is 36

you can also change K (size of the generated combinations) by just adding more loops, for each element, there must be one extra loop. Current size is 4

#include<iostream>

using namespace std;

int main() {
string num[] = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z" };

for (int i1 = 0; i1 < sizeof(num)/sizeof(string); i1++) {
    for (int i2 = 0; i2 < sizeof(num)/sizeof(string); i2++) {
        for (int i3 = 0; i3 < sizeof(num)/sizeof(string); i3++) {
            for (int i4 = 0; i4 < sizeof(num)/sizeof(string); i4++) {
                cout << num[i1] << num[i2] << num[i3] << num[i4] << endl;
            }
        }
    }
}}

Result

0: A A A
1: B A A
2: C A A
3: A B A
4: B B A
5: C B A
6: A C A
7: B C A
8: C C A
9: A A B
...

just keep in mind that the amount of combinations can be ridicules.

--UPDATE--

a better way to generate all possible combinations would be with this code, which can be easily adjusted and configured in the "variables" section of the code.

#include<iostream>
#include<math.h>

int main() {
    //VARIABLES
    char chars[] = { 'A', 'B', 'C' };
    int password[4]{0};

    //SIZES OF VERIABLES
    int chars_length = sizeof(chars) / sizeof(char);
    int password_length = sizeof(password) / sizeof(int);

    //CYCKLE TROUGH ALL OF THE COMBINATIONS
    for (int i = 0; i < pow(chars_length, password_length); i++){
       
        //CYCKLE TROUGH ALL OF THE VERIABLES IN ARRAY
        for (int i2 = 0; i2 < password_length; i2++) {
            //IF VERIABLE IN "PASSWORD" ARRAY IS THE LAST VERIABLE IN CHAR "CHARS" ARRRAY
            if (password[i2] == chars_length) {
                //THEN INCREMENT THE NEXT VERIABLE IN "PASSWORD" ARRAY
                password[i2 + 1]++;
                //AND RESET THE VERIABLE BACK TO ZERO
                password[i2] = 0;
            }}

        //PRINT OUT FIRST COMBINATION
        std::cout << i << ": ";
        for (int i2 = 0; i2 < password_length; i2++) {
            std::cout << chars[password[i2]] << " ";
        }
        std::cout << "\n";

        //INCREMENT THE FIRST VERIABLE IN ARRAY
        password[0]++;
    }}

    

Get DOS path instead of Windows path

A someone more direct answer is to fix the bug.

%SPARK_HOME%\bin\spark-class2.cmd; Line 54
Broken: set RUNNER="%JAVA_HOME%\bin\java"
Windows Style: set "RUNNER=%JAVA_HOME%\bin\java"

Otherwise, the RUNNER ends up with quotes, and the command "%RUNNER%" -Xmx128m ... ends up with double-quotes. The result is that the Program and File are treated as separate parameters.

How to split a single column values to multiple column values?

An alternative to Martin's

select LEFT(name, CHARINDEX(' ', name + ' ') -1),
       STUFF(name, 1, Len(Name) +1- CHARINDEX(' ',Reverse(name)), '')
from somenames

Sample table

create table somenames (Name varchar(100))
insert somenames select 'abcd efgh'
insert somenames select 'ijk lmn opq'
insert somenames select 'asd j. asdjja'
insert somenames select 'asb (asdfas) asd'
insert somenames select 'asd'
insert somenames select ''
insert somenames select null

AngularJS For Loop with Numbers & Ranges

This is jzm's improved answer (i cannot comment else i would comment her/his answer because s/he included errors). The function has a start/end range value, so it's more flexible, and... it works. This particular case is for day of month:

$scope.rangeCreator = function (minVal, maxVal) {
    var arr = [];
   for (var i = minVal; i <= maxVal; i++) {
      arr.push(i);
   }
   return arr;
};


<div class="col-sm-1">
    <select ng-model="monthDays">
        <option ng-repeat="day in rangeCreator(1,31)">{{day}}</option>
    </select>
</div>

How do I load a file into the python console?

For Python 2 give execfile a try. (See other answers for Python 3)

execfile('file.py')

Example usage:
Let's use "copy con" to quickly create a small script file...

C:\junk>copy con execfile_example.py
a = [9, 42, 888]
b = len(a)
^Z
        1 file(s) copied.

...and then let's load this script like so:

C:\junk>\python27\python
Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> execfile('execfile_example.py')
>>> a
[9, 42, 888]
>>> b
3
>>>

fatal: Not a valid object name: 'master'

When I git init a folder it doesn't create a master branch

This is true, and expected behaviour. Git will not create a master branch until you commit something.

When I do git --bare init it creates the files.

A non-bare git init will also create the same files, in a hidden .git directory in the root of your project.

When I type git branch master it says "fatal: Not a valid object name: 'master'"

That is again correct behaviour. Until you commit, there is no master branch.

You haven't asked a question, but I'll answer the question I assumed you mean to ask. Add one or more files to your directory, and git add them to prepare a commit. Then git commit to create your initial commit and master branch.

Find nearest latitude/longitude with an SQL query

Mysql query for search coordinates with distance limit and where condition

SELECT , ( 3959 acos( cos( radians('28.5850154') ) cos( radians(lat) ) cos( radians( lng ) - radians('77.07207489999999') ) + sin( radians('28.5850154') ) * sin( radians( lat ) ) ) ) AS distance FROM `Wo_Products` WHERE `active` = '1' HAVING distance < 5

Getting the first and last day of a month, using a given DateTime object

DateTime structure stores only one value, not range of values. MinValue and MaxValue are static fields, which hold range of possible values for instances of DateTime structure. These fields are static and do not relate to particular instance of DateTime. They relate to DateTime type itself.

Suggested reading: static (C# Reference)

UPDATE: Getting month range:

DateTime date = ...
var firstDayOfMonth = new DateTime(date.Year, date.Month, 1);
var lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1);

Python MySQLdb TypeError: not all arguments converted during string formatting

Instead of this:

cur.execute( "SELECT * FROM records WHERE email LIKE '%s'", search )

Try this:

cur.execute( "SELECT * FROM records WHERE email LIKE %s", [search] )

See the MySQLdb documentation. The reasoning is that execute's second parameter represents a list of the objects to be converted, because you could have an arbitrary number of objects in a parameterized query. In this case, you have only one, but it still needs to be an iterable (a tuple instead of a list would also be fine).

HQL ERROR: Path expected for join

You need to name the entity that holds the association to User. For example,

... INNER JOIN ug.user u ...

That's the "path" the error message is complaining about -- path from UserGroup to User entity.

Hibernate relies on declarative JOINs, for which the join condition is declared in the mapping metadata. This is why it is impossible to construct the native SQL query without having the path.

How to delete an object by id with entity framework

dwkd's answer mostly worked for me in Entity Framework core, except when I saw this exception:

InvalidOperationException: The instance of entity type 'Customer' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.

To avoid the exception, I updated the code:

Customer customer = context.Customers.Local.First(c => c.Id == id);
if (customer == null) {
    customer = new Customer () { Id = id };
    context.Customers.Attach(customer);
}
context.Customers.Remove(customer);
context.SaveChanges();

Find object in list that has attribute equal to some value (that meets any condition)

Since it has not been mentioned just for completion. The good ol' filter to filter your to be filtered elements.

Functional programming ftw.

####### Set Up #######
class X:

    def __init__(self, val):
        self.val = val

elem = 5

my_unfiltered_list = [X(1), X(2), X(3), X(4), X(5), X(5), X(6)]

####### Set Up #######

### Filter one liner ### filter(lambda x: condition(x), some_list)
my_filter_iter = filter(lambda x: x.val == elem, my_unfiltered_list)
### Returns a flippin' iterator at least in Python 3.5 and that's what I'm on

print(next(my_filter_iter).val)
print(next(my_filter_iter).val)
print(next(my_filter_iter).val)

### [1, 2, 3, 4, 5, 5, 6] Will Return: ###
# 5
# 5
# Traceback (most recent call last):
#   File "C:\Users\mousavin\workspace\Scripts\test.py", line 22, in <module>
#     print(next(my_filter_iter).value)
# StopIteration


# You can do that None stuff or whatever at this point, if you don't like exceptions.

I know that generally in python list comprehensions are preferred or at least that is what I read, but I don't see the issue to be honest. Of course Python is not an FP language, but Map / Reduce / Filter are perfectly readable and are the most standard of standard use cases in functional programming.

So there you go. Know thy functional programming.

filter condition list

It won't get any easier than this:

next(filter(lambda x: x.val == value,  my_unfiltered_list)) # Optionally: next(..., None) or some other default value to prevent Exceptions

Installing Python 3 on RHEL

For those working on AWS EC2 RHEL 7.5, (use sudo) enable required repos

yum-config-manager --enable rhui-REGION-rhel-server-optional
yum-config-manager --enable rhui-REGION-rhel-server-rhscl

Install Python 3.6

yum install rh-python36

Install other dependencies

yum install rh-python36-numpy  rh-python36-scipy  rh-python36-python-tools  rh-python36-python-six

No route matches "/users/sign_out" devise rails 3

The problem begin with rails 3.1... in /app/assets/javascript/ just look for application.js.

If the file doesn't exist create a file with that name I don't know why my file disappear or never was created on "rails new app"....

That file is the instance for jquery....

Getting list of pixel values from PIL

data = numpy.asarray(im)

Notice:In PIL, img is RGBA. In cv2, img is BGRA.

My robust solution:

def cv_from_pil_img(pil_img):
    assert pil_img.mode=="RGBA"
    return cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGBA2BGRA)

Sum values in a column based on date

If the second row has the same pattern as the first row, you just need edit first row manually, then you position your mouse pointer to the bottom-right corner, in the mean time, press ctrl key to drag the cell down. the pattern should be copied automatically.

How to force NSLocalizedString to use a specific language

Based on Tudorizer's answer to change language without leaving or restarting the application.

Instead of a macro, use a class for accessing the preferred language in order to check if a specific language code is present.

Below is a class used to obtain the current language bundle that is working for iOS 9:

@implementation OSLocalization

+ (NSBundle *)currentLanguageBundle
{
    // Default language incase an unsupported language is found
    NSString *language = @"en";

    if ([NSLocale preferredLanguages].count) {
        // Check first object to be of type "en","es" etc
        // Codes seen by my eyes: "en-US","en","es-US","es" etc

        NSString *letterCode = [[NSLocale preferredLanguages] objectAtIndex:0];

        if ([letterCode rangeOfString:@"en"].location != NSNotFound) {
            // English
            language = @"en";
        } else if ([letterCode rangeOfString:@"es"].location != NSNotFound) {
            // Spanish
            language = @"es";
        } else if ([letterCode rangeOfString:@"fr"].location != NSNotFound) {
            // French
            language = @"fr";
        } // Add more if needed
    }

    return [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:language ofType:@"lproj"]];
}

/// Check if preferred language is English
+ (BOOL)isCurrentLanguageEnglish
{
    if (![NSLocale preferredLanguages].count) {
        // Just incase check for no items in array
        return YES;
    }

    if ([[[NSLocale preferredLanguages] objectAtIndex:0] rangeOfString:@"en"].location == NSNotFound) {
        // No letter code for english found
        return NO;
    } else {
        // Tis English
        return YES;
    }
}

/*  Swap language between English & Spanish
 *  Could send a string argument to directly pass the new language
 */
+ (void)changeCurrentLanguage
{
    if ([self isCurrentLanguageEnglish]) {
        [[NSUserDefaults standardUserDefaults] setObject:@[@"es"] forKey:@"AppleLanguages"];
    } else {
        [[NSUserDefaults standardUserDefaults] setObject:@[@"en"] forKey:@"AppleLanguages"];
    }
}
@end

Use the class above to reference a string file / image / video / etc:

// Access a localized image
[[OSLocalization currentLanguageBundle] pathForResource:@"my_image_name.png" ofType:nil]
// Access  a localized string from Localizable.strings file
NSLocalizedStringFromTableInBundle(@"StringKey", nil, [OSLocalization currentLanguageBundle], @"comment")

Change language in-line like below or update the "changeCurrentLanguage" method in the class above to take a string parameter referencing the new language.

[[NSUserDefaults standardUserDefaults] setObject:@[@"es"] forKey:@"AppleLanguages"];

Reverse order of foreach list items

Walking Backwards

If you're looking for a purely PHP solution, you can also simply count backwards through the list, access it front-to-back:

$accounts = Array(
  '@jonathansampson',
  '@f12devtools',
  '@ieanswers'
);

$index = count($accounts);

while($index) {
  echo sprintf("<li>%s</li>", $accounts[--$index]);
}

The above sets $index to the total number of elements, and then begins accessing them back-to-front, reducing the index value for the next iteration.

Reversing the Array

You could also leverage the array_reverse function to invert the values of your array, allowing you to access them in reverse order:

$accounts = Array(
  '@jonathansampson',
  '@f12devtools',
  '@ieanswers'
);

foreach ( array_reverse($accounts) as $account ) {
  echo sprintf("<li>%s</li>", $account);
}

How do I execute .js files locally in my browser?

If you're using Google Chrome you can use the Chrome Dev Editor: https://github.com/dart-lang/chromedeveditor

Javascript, Change google map marker color

I have 4 ships to set on one single map, so I use the Google Developers example and then twisted it

https://developers.google.com/maps/documentation/javascript/examples/icon-complex

In the function bellow I set 3 more color options:

function setMarkers(map, locations) {
...
var image = {
    url: 'img/bullet_amarelo.png',
    // This marker is 20 pixels wide by 32 pixels tall.
    size: new google.maps.Size(40, 40),
    // The origin for this image is 0,0.
    origin: new google.maps.Point(0,0),
    // The anchor for this image is the base of the flagpole at 0,32.
    anchor: new google.maps.Point(0, 40)
  };
  var image1 = {
            url: 'img/bullet_azul.png',
            // This marker is 20 pixels wide by 32 pixels tall.
            size: new google.maps.Size(40, 40),
            // The origin for this image is 0,0.
            origin: new google.maps.Point(0,0),
            // The anchor for this image is the base of the flagpole at 0,32.
            anchor: new google.maps.Point(0, 40)
          };
  var image2 = {
          url: 'img/bullet_vermelho.png',
          // This marker is 20 pixels wide by 32 pixels tall.
          size: new google.maps.Size(40, 40),
          // The origin for this image is 0,0.
          origin: new google.maps.Point(0,0),
          // The anchor for this image is the base of the flagpole at 0,32.
          anchor: new google.maps.Point(0, 40)
        };
  var image3 = {
          url: 'img/bullet_verde.png',
          // This marker is 20 pixels wide by 32 pixels tall.
          size: new google.maps.Size(40, 40),
          // The origin for this image is 0,0.
          origin: new google.maps.Point(0,0),
          // The anchor for this image is the base of the flagpole at 0,32.
          anchor: new google.maps.Point(0, 40)
        };
...
}

And in the FOR bellow I set one color for each ship:

for (var i = 0; i < locations.length; i++) {
...
    if (i==0) var imageV=image;
    if (i==1) var imageV=image1;
    if (i==2) var imageV=image2;
    if (i==3) var imageV=image3;
...
# remember to change icon: image to icon: imageV
}

The final result:

http://www.mercosul-line.com.br/site/teste.html

SQL grammar for SELECT MIN(DATE)

SELECT  MIN(Date)  AS Date  FROM tbl_Employee /*To get First date Of Employee*/

Curl to return http status code along with the response

A one-liner, just to get the status-code would be:

curl -s -i https://www.google.com | head -1

Changing it to head -2 will give the time as well.


If you want a while-true loop over it, it would be:

URL="https://www.google.com"

while true; do
    echo "------"
    curl -s -i $URL | head -2
    sleep 2;
done

Which produces the following, until you do cmd+C (or ctrl+C in Windows).

------
HTTP/2 200
date: Sun, 07 Feb 2021 20:03:38 GMT
------
HTTP/2 200
date: Sun, 07 Feb 2021 20:03:41 GMT
------
HTTP/2 200
date: Sun, 07 Feb 2021 20:03:43 GMT
------
HTTP/2 200
date: Sun, 07 Feb 2021 20:03:45 GMT
------
HTTP/2 200
date: Sun, 07 Feb 2021 20:03:47 GMT
------
HTTP/2 200
date: Sun, 07 Feb 2021 20:03:49 GMT

How do you access the element HTML from within an Angular attribute directive?

Base on @Mark answer, I add the constructor to directive and it work with me.

I share a sample to whom concern.

constructor(private el: ElementRef, private renderer: Renderer) {
}

TS file

@Directive({ selector: '[accordion]' })
export class AccordionDirective {

  constructor(private el: ElementRef, private renderer: Renderer) {
  }

  @HostListener('click', ['$event']) onClick($event) {
    console.info($event);

    this.el.nativeElement.classList.toggle('is-open');

    var content = this.el.nativeElement.nextElementSibling;
    if (content.style.maxHeight) {
      // accordion is currently open, so close it
      content.style.maxHeight = null;
    } else {
      // accordion is currently closed, so open it
      content.style.maxHeight = content.scrollHeight + "px";

    }
  }
}

HTML

<button accordion class="accordion">Accordian #1</button>
    <div class="accordion-content">
      <p>
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas deleniti molestias necessitatibus quaerat quos incidunt! Quas officiis repellat dolore omnis nihil quo,
        ratione cupiditate! Sed, deleniti, recusandae! Animi, sapiente, nostrum?
      </p>     
    </div>

Demo https://stackblitz.com/edit/angular-directive-accordion?file=src/app/app.component.ts

How can I pad a value with leading zeros?

To pad at the end of the number, use num.toFixed

for example:

  document.getElementById('el').value = amt.toFixed(2);

It's the simplest solution i've found, and it works.

await vs Task.Wait - Deadlock?

Some important facts were not given in other answers:

"async await" is more complex at CIL level and thus costs memory and CPU time.

Any task can be canceled if the waiting time is unacceptable.

In the case "async await" we do not have a handler for such a task to cancel it or monitoring it.

Using Task is more flexible then "async await".

Any sync functionality can by wrapped by async.

public async Task<ActionResult> DoAsync(long id) 
{ 
    return await Task.Run(() => { return DoSync(id); } ); 
} 

"async await" generate many problems. We do not now is await statement will be reached without runtime and context debugging. If first await not reached everything is blocked. Some times even await seems to be reached still everything is blocked:

https://github.com/dotnet/runtime/issues/36063

I do not see why I'm must live with the code duplication for sync and async method or using hacks.

Conclusion: Create Task manually and control them is much better. Handler to Task give more control. We can monitor Tasks and manage them:

https://github.com/lsmolinski/MonitoredQueueBackgroundWorkItem

Sorry for my english.

Calling a particular PHP function on form submit

If you want to call a function on clicking of submit button then you have
to use ajax or jquery,if you want to call your php function after submission of form you can do that as :

<html>
<body>
<form method="post" action="display()">
<input type="text" name="studentname">
<input type="submit" value="click">
</form>
<?php
function display()
{
echo "hello".$_POST["studentname"];
}
if($_SERVER['REQUEST_METHOD']=='POST')
{
       display();
} 
?>
</body>
</html>

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'

If seeing this message in Hive with new MySQL connector 8.x (MySQL metastore)

open hive-site.xml and change:

   <property>
      <name>javax.jdo.option.ConnectionDriverName</name>
      <value>com.mysql.jdbc.Driver</value>
      <description>MySQL JDBC driver class</description>
   </property>

to

   <property>
      <name>javax.jdo.option.ConnectionDriverName</name>
      <value>com.mysql.cj.jdbc.Driver</value>
      <description>MySQL JDBC driver class</description>
   </property>

Getting "cannot find Symbol" in Java project in Intellij

I know this is old, but for anyone else, make sure that the class that's missing is in the same package as the class where you get the error/where your calling it from.

Sql script to find invalid email addresses

select
    email 
from loginuser where
patindex ('%[ &'',":;!+=\/()<>]*%', email) > 0  -- Invalid characters
or patindex ('[@.-_]%', email) > 0   -- Valid but cannot be starting character
or patindex ('%[@.-_]', email) > 0   -- Valid but cannot be ending character
or email not like '%@%.%'   -- Must contain at least one @ and one .
or email like '%..%'        -- Cannot have two periods in a row
or email like '%@%@%'       -- Cannot have two @ anywhere
or email like '%.@%' or email like '%@.%' -- Cant have @ and . next to each other
or email like '%.cm' or email like '%.co' -- Unlikely. Probably typos 
or email like '%.or' or email like '%.ne' -- Missing last letter

This worked for me. Had to apply rtrim and ltrim to avoid false positives.

Source: http://sevenwires.blogspot.com/2008/09/sql-how-to-find-invalid-email-in-sql.html

Postgres version:

select user_guid, user_guid email_address, creation_date, email_verified, active
from user_data where
length(substring (email_address from '%[ &'',":;!+=\/()<>]%')) > 0  -- Invalid characters
or length(substring (email_address from '[@.-_]%')) > 0   -- Valid but cannot be starting character
or length(substring (email_address from '%[@.-_]')) > 0   -- Valid but cannot be ending character
or email_address not like '%@%.%'   -- Must contain at least one @ and one .
or email_address like '%..%'        -- Cannot have two periods in a row
or email_address like '%@%@%'       -- Cannot have two @ anywhere
or email_address like '%.@%' or email_address like '%@.%' -- Cant have @ and . next to each other
or email_address like '%.cm' or email_address like '%.co' -- Unlikely. Probably typos 
or email_address like '%.or' or email_address like '%.ne' -- Missing last letter
;

While, Do While, For loops in Assembly Language (emu8086)

For-loops:

For-loop in C:

for(int x = 0; x<=3; x++)
{
    //Do something!
}

The same loop in 8086 assembler:

        xor cx,cx   ; cx-register is the counter, set to 0
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        inc cx      ; Increment
        cmp cx,3    ; Compare cx to the limit
        jle loop1   ; Loop while less or equal

That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:

        mov cx,4    ; 4 iterations
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        loop loop1  ; loop instruction decrements cx and jumps to label if not 0

If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction

times 4 nop

Do-while-loops

Do-while-loop in C:

int x=1;
do{
    //Do something!
}
while(x==1)

The same loop in assembler:

        mov ax,1
loop1   nop         ; Whatever you wanna do goes here
        cmp ax,1    ; Check wether cx is 1
        je loop1    ; And loop if equal

While-loops

While-loop in C:

while(x==1){
    //Do something
}

The same loop in assembler:

        jmp loop1   ; Jump to condition first
cloop1  nop         ; Execute the content of the loop
loop1   cmp ax,1    ; Check the condition
        je cloop1   ; Jump to content of the loop if met

For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.

How is Java platform-independent when it needs a JVM to run?

Java is platform-independent as it has JVM(Java virtual machine). Let us illustrate it with a real life example. Let's assume you are free to your family members. But why?

Because you know them well and they know you as well. But, you are not free to my family members. Because you don't know them and they don't know you either. But, if I'm your friend and when I can introduce you to my family members, hence you will be able to talk to them freely.

In a similar way, if you are a code and I am a JVM. Also, your family is windows platform and mine is the Linux platform. In the case you were a C or other platform-dependent languages, you only know your family members and vice versa. That's why only the platform on which you were written knows that Code and will support it. But if you are a JAVA code and when you come to my family viz. the Linux platform and if there you find me, JVM, then I can introduce you to my family, the Linux platform and you will be able to interact with it.

For platform-dependent languages, there isn't any friend like JVM available to them to introduce themselves to any platform family. That is how Java is platform-independent. :)

Fastest way to set all values of an array?

As of Java-8, there are four variants of the setAll method which sets all elements of the specified array, using a provided generator function to compute each element.

Of those four overloads only three of them accept an array of primitives declared as such:





Examples of how to use the aforementioned methods:

// given an index, set the element at the specified index with the provided value
double [] doubles = new double[50];
Arrays.setAll(doubles, index -> 30D);

// given an index, set the element at the specified index with the provided value
int [] ints = new int[50];
Arrays.setAll(ints, index -> 60);

 // given an index, set the element at the specified index with the provided value
long [] longs = new long[50];
Arrays.setAll(longs, index -> 90L);

The function provided to the setAll method receives the element index and returns a value for that index.

you may be wondering how about characters array?

This is where the fourth overload of the setAll method comes into play. As there is no overload that consumes an array of character primitives, the only option we have is to change the declaration of our character array to a type Character[].

If changing the type of the array to Character is not appropriate then you can fall back to the Arrays.fill method.

Example of using the setAll method with Character[]:

// given an index, set the element at the specified index with the provided value
Character[] character = new Character[50];
Arrays.setAll(characters, index -> '+'); 

Although, it's simpler to use the Arrays.fill method rather than the setAll method to set a specific value.

The setAll method has the advantage that you can either set all the elements of the array to have the same value or generate an array of even numbers, odd numbers or any other formula:

e.g.

int[] evenNumbers = new int[10]; 
Arrays.setAll(evenNumbers, i -> i * 2);

There's also several overloads of the parallelSetAll method which is executed in parallel, although it's important to note that the function passed to the parallelSetAll method must be side-effect free.

Conclusion

If your goal is simply to set a specific value for each element of the array then using the Arrays.fill overloads would be the most appropriate option. However, if you want to be more flexible or generate elements on demand then using the Arrays.setAll or Arrays.parallelSetAll (when appropriate) would be the option to go for.

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

This is a simple solution:

Example 1

my $var1 = "123abc";
print $var1 + 0;

Result

123

Example 2

my $var2 = "abc123";
print $var2 + 0;

Result

0

Angular 2 change event on every keypress

<input type="text" [ngModel]="mymodel" (keypress)="mymodel=$event.target.value"/>
{{mymodel}}

Creating and Naming Worksheet in Excel VBA

Are you using an error handler? If you're ignoring errors and try to name a sheet the same as an existing sheet or a name with invalid characters, it could be just skipping over that line. See the CleanSheetName function here

http://www.dailydoseofexcel.com/archives/2005/01/04/naming-a-sheet-based-on-a-cell/

for a list of invalid characters that you may want to check for.

Update

Other things to try: Fully qualified references, throwing in a Doevents, code cleaning. This code qualifies your Sheets reference to ThisWorkbook (you can change it to ActiveWorkbook if that suits). It also adds a thousand DoEvents (stupid overkill, but if something's taking a while to get done, this will allow it to - you may only need one DoEvents if this actually fixes anything).

Dim WS As Worksheet
Dim i As Long

With ThisWorkbook
    Set WS = .Worksheets.Add(After:=.Sheets(.Sheets.Count))
End With

For i = 1 To 1000
    DoEvents
Next i

WS.Name = txtSheetName.Value

Finally, whenever I have a goofy VBA problem that just doesn't make sense, I use Rob Bovey's CodeCleaner. It's an add-in that exports all of your modules to text files then re-imports them. You can do it manually too. This process cleans out any corrupted p-code that's hanging around.

jQuery check/uncheck radio button onclick

toggleAttr() is provided by this very nice and tiny plugin.

Sample code

$('#my_radio').click(function() {
    $(this).toggleAttr('checked');
});

/**
 * toggleAttr Plugin
 */
jQuery.fn.toggleAttr = function(attr) {
    return this.each(function() {
        var $this = $(this);
        $this.attr(attr) ? $this.removeAttr(attr) : $this.attr(attr, attr);
    });
};

Even more fun, demo

You can use place your radio button inside label or button tags and do some nice things.

Does C have a string type?

C does not and never has had a native string type. By convention, the language uses arrays of char terminated with a null char, i.e., with '\0'. Functions and macros in the language's standard libraries provide support for the null-terminated character arrays, e.g., strlen iterates over an array of char until it encounters a '\0' character and strcpy copies from the source string until it encounters a '\0'.

The use of null-terminated strings in C reflects the fact that C was intended to be only a little more high-level than assembly language. Zero-terminated strings were already directly supported at that time in assembly language for the PDP-10 and PDP-11.

It is worth noting that this property of C strings leads to quite a few nasty buffer overrun bugs, including serious security flaws. For example, if you forget to null-terminate a character string passed as the source argument to strcpy, the function will keep copying sequential bytes from whatever happens to be in memory past the end of the source string until it happens to encounter a 0, potentially overwriting whatever valuable information follows the destination string's location in memory.

In your code example, the string literal "Hello, world!" will be compiled into a 14-byte long array of char. The first 13 bytes will hold the letters, comma, space, and exclamation mark and the final byte will hold the null-terminator character '\0', automatically added for you by the compiler. If you were to access the array's last element, you would find it equal to 0. E.g.:

const char foo[] = "Hello, world!";
assert(foo[12] == '!');
assert(foo[13] == '\0');

However, in your example, message is only 10 bytes long. strcpy is going to write all 14 bytes, including the null-terminator, into memory starting at the address of message. The first 10 bytes will be written into the memory allocated on the stack for message and the remaining four bytes will simply be written on to the end of the stack. The consequence of writing those four extra bytes onto the stack is hard to predict in this case (in this simple example, it might not hurt a thing), but in real-world code it usually leads to corrupted data or memory access violation errors.

What should be in my .gitignore for an Android Studio project?

As of Android Studio 0.8.4 .gitignore file is generated automatically when starting new project. By default it contains:

.gradle
/local.properties
/.idea/workspace.xml
/.idea/libraries
.DS_Store
build/
/captures

I agree with this statement, however I modify this file to change /build to build/ (This will include /build and /app/build) So I don't end up with all the files in app/build in my repository.

Note also that if you import a project from Eclipse, the .gitignore won't be copied, or "automagically" created for you.

Android Volley - BasicNetwork.performRequest: Unexpected response code 400

One way of doing this without changing Volley's source code is to check for the response data in the VolleyError and parse it your self.

As of f605da3 commit, Volley throws a ServerError exception that contains the raw network response.

So you can do something similar to this in your error listener:

/* import com.android.volley.toolbox.HttpHeaderParser; */
public void onErrorResponse(VolleyError error) {

    // As of f605da3 the following should work
    NetworkResponse response = error.networkResponse;
    if (error instanceof ServerError && response != null) {
        try {
            String res = new String(response.data,
                       HttpHeaderParser.parseCharset(response.headers, "utf-8"));
            // Now you can use any deserializer to make sense of data
            JSONObject obj = new JSONObject(res);
        } catch (UnsupportedEncodingException e1) {
            // Couldn't properly decode data to string
            e1.printStackTrace();
        } catch (JSONException e2) {
            // returned data is not JSONObject?
            e2.printStackTrace();
        }
    }
}

For future, if Volley changes, one can follow the above approach where you need to check the VolleyError for raw data that has been sent by the server and parse it.

I hope that they implement that TODO mentioned in the source file.

How do you run CMD.exe under the Local System Account?

Found an answer here which seems to solve the problem by adding /k start to the binPath parameter. So that would give you:

sc create testsvc binpath= "cmd /K start" type= own type= interact

However, Ben said that didn't work for him and when I tried it on Windows Server 2008 it did create the cmd.exe process under local system, but it wasn't interactive (I couldn't see the window).

I don't think there is an easy way to do what you ask, but I'm wondering why you're doing it at all? Are you just trying to see what is happening when you run your service? Seems like you could just use logging to determine what is happening instead of having to run the exe as local system...

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

Right-click the assembly reference in the solution explorer, properties, disable the "Specific Version" option.

How to format a phone number with jQuery

To expand on Cruz Nunez code and add continual formatting, plus include some international phone number formats.

    $('#phone').on('input', function() {
      var number = $(this).val().replace(/[^\d]/g, '');
      if (number.length == 3) {
        number = number.replace(/(\d{3})/, "$1-");
      } else if (number.length == 4) {
        number = number.replace(/(\d{3})(\d{1})/, "$1-$2");
      } else if (number.length == 5) {
        number = number.replace(/(\d{3})(\d{2})/, "$1-$2");
      } else if (number.length == 6) {
        number = number.replace(/(\d{3})(\d{3})/, "$1-$2-");
      } else if (number.length == 7) {
        number = number.replace(/(\d{3})(\d{3})(\d{1})/, "$1-$2-$3");
      } else if (number.length == 8) {
        number = number.replace(/(\d{4})(\d{4})/, "$1-$2");
      } else if (number.length == 9) {
        number = number.replace(/(\d{3})(\d{3})(\d{3})/, "$1-$2-$3");
      } else if (number.length == 10) {
        number = number.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
      } else if (number.length == 11) {
        number = number.replace(/(\d{1})(\d{3})(\d{3})(\d{4})/, "$1-$2-$3-$4");
      } else if (number.length == 12) {
        number = number.replace(/(\d{2})(\d{3})(\d{3})(\d{4})/, "$1-$2-$3-$4");
      }
      $(this).val(number);
    });

When saving, how can you check if a field has changed?

If you are using a form, you can use Form's changed_data (docs):

class AliasForm(ModelForm):

    def save(self, commit=True):
        if 'remote_image' in self.changed_data:
            # do things
            remote_image = self.cleaned_data['remote_image']
            do_things(remote_image)
        super(AliasForm, self).save(commit)

    class Meta:
        model = Alias

How to make a gap between two DIV within the same column

You can make use of the first-child selector

<div class="sidebar">
    <div class="box">
        <p> 
            Text is here
         </p>
     </div>
    <div class="box">
        <p> 
            Text is here
         </p>
     </div>
</div>

and in CSS

.box {
    padding: 10px;
    text-align: justify;
    margin-top: 20px;
}
.box:first-child {
    margin-top: none;
}

Example: http://jsbin.com/ozarot/edit#javascript,html,live

How to make an element in XML schema optional?

Set the minOccurs attribute to 0 in the schema like so:

<?xml version="1.0"?>
  <xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
    <xs:element name="request">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="amenity">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="description" type="xs:string" minOccurs="0" />
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element> </xs:schema>

Non-resolvable parent POM using Maven 3.0.3 and relativePath notation

<parent>
        <groupId>com.test.vaquar.khan</groupId>
        <artifactId>vk-parent</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <relativePath>../projectname/pom.xml</relativePath>
    </parent>

Add following line in parent

<relativePath>../projectname/pom.xml</relativePath>

You need relative path if you are building from local parent pom not available in nexsus, add pom in nexus then no need this path

Resolving require paths with webpack

Webpack >2.0

See wtk's answer.

Webpack 1.0

A more straightforward way to do this would be to use resolve.root.

http://webpack.github.io/docs/configuration.html#resolve-root

resolve.root

The directory (absolute path) that contains your modules. May also be an array of directories. This setting should be used to add individual directories to the search path.

In your case:

webpack config

var path = require('path');

// ...

  resolve: {
    root: path.resolve('./mydir'),
    extensions: ['', '.js']
  }

consuming module

require('myfile')

or

require('myfile.js')

see also: http://webpack.github.io/docs/configuration.html#resolve-modulesdirectories

.htaccess: Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration

Just Follow Simple 1-2-3 Steps :

1) Go to Taskbar

2) Click on WAMP icon (Left Click)

enter image description here

3) Now Go to Apache > Services > Apache Module and check Rewrite_module is enable or not ! if its not then click on it ! WAMP will be automatically restarted and you're done !

enter image description here

SQL Server error on update command - "A severe error occurred on the current command"

This seems to happen when there's a generic problem with your data source that it isn't handling.

In my case I had inserted a bunch of data, the indexes had become corrupt on the table, they needed rebuilding. I found a script to rebuild them all, seemed to fix it. To find the error I ran the same query on the database - one that had worked 100+ times previously.

How do I use regular expressions in bash scripts?

It was changed between 3.1 and 3.2:

This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.

Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.

So use it without the quotes thus:

i="test"
if [[ $i =~ 200[78] ]] ; then
    echo "OK"
else
    echo "not OK"
fi

java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject Error

I was working with talend V7.3.1 and I had poi version "4.1.0" and including xml-beans from the list of dependencies didnt fix my problem (i.e: 2.3.0 and 2.6.0).

It was fixed by downloading the jar "xmlbeans-3.0.1.jar" and adding it to the project

enter image description here

Setting Authorization Header of HttpClient

I suggest to you:

HttpClient.DefaultRequestHeaders.Add("Authorization", "Bearer <token>");

And then you can use it like that:

var response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
    responseMessage = await response.Content.ReadAsAsync<ResponseMessage>();
}

How to count rows with SELECT COUNT(*) with SQLAlchemy?

Addition to the Usage from the ORM layer in the accepted answer: count(*) can be done for ORM using the query.with_entities(func.count()), like this:

session.query(MyModel).with_entities(func.count()).scalar()

It can also be used in more complex cases, when we have joins and filters - the important thing here is to place with_entities after joins, otherwise SQLAlchemy could raise the Don't know how to join error.

For example:

  • we have User model (id, name) and Song model (id, title, genre)
  • we have user-song data - the UserSong model (user_id, song_id, is_liked) where user_id + song_id is a primary key)

We want to get a number of user's liked rock songs:

SELECT count(*) 
  FROM user_song
  JOIN song ON user_song.song_id = song.id 
 WHERE user_song.user_id = %(user_id)
   AND user_song.is_liked IS 1
   AND song.genre = 'rock'

This query can be generated in a following way:

user_id = 1

query = session.query(UserSong)
query = query.join(Song, Song.id == UserSong.song_id)
query = query.filter(
    and_(
        UserSong.user_id == user_id, 
        UserSong.is_liked.is_(True),
        Song.genre == 'rock'
    )
)
# Note: important to place `with_entities` after the join
query = query.with_entities(func.count())
liked_count = query.scalar()

Complete example is here.

jQuery .css("margin-top", value) not updating in IE 8 (Standards mode)

try this method

$("your id or class name").css({ 'margin-top': '18px' });  

How can I get the iOS 7 default blue color programmatically?

Adding a category to UIColor the following way will make it available to you anytime you need it or even change its definition accross your code:

@interface UIColor (iOS7Colors)

+ (instancetype)iOS7blueColor;

@end

@implementation UIColor (SpecialColors)

+ (instancetype)iOS7blueColor;
{
    return [UIColor colorWithRed:0.0f green:0.22f blue:122.0/255.0 alpha:1.0f];
}

Once you import the Category in your code you can call the color by using:

UIColor *myBlueColor = [UIColor iOSblueColor];

How to check if a string contains a specific text

http://php.net/manual/en/function.strpos.php I think you are wondiner if 'some text' exists in the string right?

if(strpos( $a , 'some text' ) !== false)

jQuery: Slide left and slide right

If you don't want something bloated like jQuery UI, try my custom animations: https://github.com/yckart/jquery-custom-animations

For you, blindLeftToggle and blindRightToggle is the appropriate choice.

http://jsfiddle.net/ARTsinn/65QsU/

Bash command line and input limit

The limit for the length of a command line is not imposed by the shell, but by the operating system. This limit is usually in the range of hundred kilobytes. POSIX denotes this limit ARG_MAX and on POSIX conformant systems you can query it with

$ getconf ARG_MAX    # Get argument limit in bytes

E.g. on Cygwin this is 32000, and on the different BSDs and Linux systems I use it is anywhere from 131072 to 2621440.

If you need to process a list of files exceeding this limit, you might want to look at the xargs utility, which calls a program repeatedly with a subset of arguments not exceeding ARG_MAX.

To answer your specific question, yes, it is possible to attempt to run a command with too long an argument list. The shell will error with a message along "argument list too long".

Note that the input to a program (as read on stdin or any other file descriptor) is not limited (only by available program resources). So if your shell script reads a string into a variable, you are not restricted by ARG_MAX. The restriction also does not apply to shell-builtins.

What is the size of column of int(11) in mysql in bytes?

According to here, int(11) will take 4 bytes of space that is 32 bits of space with 2^(31) = 2147483648 max value and -2147483648min value. One bit is for sign.

Submit HTML form, perform javascript function (alert then redirect)

Looks like your form is submitting which is the default behaviour, you can stop it with this:

<form action="" method="post" onsubmit="completeAndRedirect();return false;">

What and When to use Tuple?

This msdn article explains it very well with examples, "A tuple is a data structure that has a specific number and sequence of elements".

Tuples are commonly used in four ways:

  1. To represent a single set of data. For example, a tuple can represent a database record, and its components can represent individual fields of the record.

  2. To provide easy access to, and manipulation of, a data set.

  3. To return multiple values from a method without using out parameters (in C#) or ByRef parameters (in Visual Basic).

  4. To pass multiple values to a method through a single parameter. For example, the Thread.Start(Object) method has a single parameter that lets you supply one value to the method that the thread executes at startup time. If you supply a Tuple<T1, T2, T3> object as the method argument, you can supply the thread’s startup routine with three items of data.

Convert String to Float in Swift

to convert string to Float in Xcode 11 as previous methods need modification

func stringToFloat(value : String) -> Float {
    let numberFormatter = NumberFormatter()
    let number = numberFormatter.number(from: value)
    let numberFloatValue = number?.floatValue
    return numberFloatValue!
}

Is JavaScript's "new" keyword considered harmful?

Crockford has done a lot to popularize good JavaScript techniques. His opinionated stance on key elements of the language have sparked many useful discussions. That said, there are far too many people that take each proclamation of "bad" or "harmful" as gospel, refusing to look beyond one man's opinion. It can be a bit frustrating at times.

Use of the functionality provided by the new keyword has several advantages over building each object from scratch:

  1. Prototype inheritance. While often looked at with a mix of suspicion and derision by those accustomed to class-based OO languages, JavaScript's native inheritance technique is a simple and surprisingly effective means of code re-use. And the new keyword is the canonical (and only available cross-platform) means of using it.
  2. Performance. This is a side-effect of #1: if I want to add 10 methods to every object I create, I could just write a creation function that manually assigns each method to each new object... Or, I could assign them to the creation function's prototype and use new to stamp out new objects. Not only is this faster (no code needed for each and every method on the prototype), it avoids ballooning each object with separate properties for each method. On slower machines (or especially, slower JS interpreters) when many objects are being created this can mean a significant savings in time and memory.

And yes, new has one crucial disadvantage, ably described by other answers: if you forget to use it, your code will break without warning. Fortunately, that disadvantage is easily mitigated - simply add a bit of code to the function itself:

function foo()
{
   // if user accidentally omits the new keyword, this will 
   // silently correct the problem...
   if ( !(this instanceof foo) )
      return new foo();

   // constructor logic follows...
}

Now you can have the advantages of new without having to worry about problems caused by accidentally misuse. You could even add an assertion to the check if the thought of broken code silently working bothers you. Or, as some commented, use the check to introduce a runtime exception:

if ( !(this instanceof arguments.callee) ) 
   throw new Error("Constructor called as a function");

(Note that this snippet is able to avoid hard-coding the constructor function name, as unlike the previous example it has no need to actually instantiate the object - therefore, it can be copied into each target function without modification.)

John Resig goes into detail on this technique in his Simple "Class" Instantiation post, as well as including a means of building this behavior into your "classes" by default. Definitely worth a read... as is his upcoming book, Secrets of the JavaScript Ninja, which finds hidden gold in this and many other "harmful" features of the JavaScript language (the chapter on with is especially enlightening for those of us who initially dismissed this much-maligned feature as a gimmick).

How to download Visual Studio Community Edition 2015 (not 2017)

You can use these links to download Visual Studio 2015

Community Edition:

And for anyone in the future who might be looking for the other editions here are the links for them as well:

Professional Edition:

Enterprise Edition:

How can I return NULL from a generic method in C#?

Take the recommendation of the error... and either user default(T) or new T.

You will have to add in a comparison in your code to ensure that it was a valid match if you go that route.

Otherwise, potentially consider an output parameter for "match found".

Where value in column containing comma delimited values

WHERE
      MyColumn LIKE '%,' + @search + ',%' --middle
      OR
      MyColumn LIKE @search + ',%' --start
      OR
      MyColumn LIKE '%,' + @search --end
      OR 
      MyColumn =  @search --single (good point by Cheran S in comment)

capture div into image using html2canvas

You can get the screenshot of a division and save it easily just using the below snippet. Here I'm used the entire body, you can choose the specific image/div elements just by putting the id/class names.

 html2canvas(document.getElementsByClassName("image-div")[0], {
  useCORS: true,
}).then(function (canvas) {
  var imageURL = canvas.toDataURL("image/png");
  let a = document.createElement("a");
  a.href = imageURL;
  a.download = imageURL;
  a.click();
});

"Automatic" vs "Automatic (Delayed start)"

In short, services set to Automatic will start during the boot process, while services set to start as Delayed will start shortly after boot.

Starting your service Delayed improves the boot performance of your server and has security benefits which are outlined in the article Adriano linked to in the comments.

Update: "shortly after boot" is actually 2 minutes after the last "automatic" service has started, by default. This can be configured by a registry key, according to Windows Internals and other sources (3,4).

The registry keys of interest (At least in some versions of windows) are:

  • HKLM\SYSTEM\CurrentControlSet\services\<service name>\DelayedAutostart will have the value 1 if delayed, 0 if not.
  • HKLM\SYSTEM\CurrentControlSet\services\AutoStartDelay or HKLM\SYSTEM\CurrentControlSet\Control\AutoStartDelay (on Windows 10): decimal number of seconds to wait, may need to create this one. Applies globally to all Delayed services.

Where do alpha testers download Google Play Android apps?

You need to publish the app before it becomes available for testing.

if you publish the app and the apk is only in "alpha testing" section then it is NOT available to general public, only for activated testers in the alpha section.

EDIT: One additional note: "normal" users will not find your app on Google Play, but also the activated tester can not find the application by using the search box.

Only the direct link to the application package will work. (only for the activated testers).

How do I include a JavaScript script file in Angular and call a function from that script?

Refer the scripts inside the angular-cli.json (angular.json when using angular 6+) file.

"scripts": [
    "../path" 
 ];

then add in typings.d.ts (create this file in src if it does not already exist)

declare var variableName:any;

Import it in your file as

import * as variable from 'variableName';

How do you run JavaScript script through the Terminal?

You would need a JavaScript engine (such as Mozilla's Rhino) in order to evaluate the script - exactly as you do for Python, though the latter ships with the standard distribution.

If you have Rhino (or alternative) installed and on your path, then running JS can indeed be as simple as

> rhino filename.js

It's worth noting though that while JavaScript is simply a language in its own right, a lot of particular scripts assume that they'll be executing in a browser-like environment - and so try to access global variables such as location.href, and create output by appending DOM objects rather than calling print.

If you've got hold of a script which was written for a web page, you may need to wrap or modify it somewhat to allow it to accept arguments from stdin and write to stdout. (I believe Rhino has a mode to emulate standard browser global vars which helps a lot, though I can't find the docs for this now.)

Find objects between two dates MongoDB

db.collection.find({"createdDate":{$gte:new ISODate("2017-04-14T23:59:59Z"),$lte:new ISODate("2017-04-15T23:59:59Z")}}).count();

Replace collection with name of collection you want to execute query

Passing data to a bootstrap modal

Your code would have worked with correct modal html structure.

_x000D_
_x000D_
$(function(){_x000D_
  $(".open-AddBookDialog").click(function(){_x000D_
     $('#bookId').val($(this).data('id'));_x000D_
    $("#addBookDialog").modal("show");_x000D_
  });_x000D_
});
_x000D_
<html>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
<a data-id="@book.Id" title="Add this item" class="open-AddBookDialog">Open Modal</a>_x000D_
_x000D_
<div id="addBookDialog" class="modal fade" tabindex="-1" role="dialog">_x000D_
  <div class="modal-dialog" role="document">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-body">_x000D_
       <input type="hidden" name="bookId" id="bookId" value=""/>_x000D_
      </div>_x000D_
    _x000D_
    </div><!-- /.modal-content -->_x000D_
  </div><!-- /.modal-dialog -->_x000D_
</div><!-- /.modal -->_x000D_
</html>
_x000D_
_x000D_
_x000D_

Handle Button click inside a row in RecyclerView

Just wanted to add another solution if you already have a recycler touch listener and want to handle all of the touch events in it rather than dealing with the button touch event separately in the view holder. The key thing this adapted version of the class does is return the button view in the onItemClick() callback when it's tapped, as opposed to the item container. You can then test for the view being a button, and carry out a different action. Note, long tapping on the button is interpreted as a long tap on the whole row still.

public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener
{
    public static interface OnItemClickListener
    {
        public void onItemClick(View view, int position);
        public void onItemLongClick(View view, int position);
    }

    private OnItemClickListener mListener;
    private GestureDetector mGestureDetector;

    public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener)
    {
        mListener = listener;

        mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener()
        {
            @Override
            public boolean onSingleTapUp(MotionEvent e)
            {
                // Important: x and y are translated coordinates here
                final ViewGroup childViewGroup = (ViewGroup) recyclerView.findChildViewUnder(e.getX(), e.getY());

                if (childViewGroup != null && mListener != null) {
                    final List<View> viewHierarchy = new ArrayList<View>();
                    // Important: x and y are raw screen coordinates here
                    getViewHierarchyUnderChild(childViewGroup, e.getRawX(), e.getRawY(), viewHierarchy);

                    View touchedView = childViewGroup;
                    if (viewHierarchy.size() > 0) {
                        touchedView = viewHierarchy.get(0);
                    }
                    mListener.onItemClick(touchedView, recyclerView.getChildPosition(childViewGroup));
                    return true;
                }

                return false;
            }

            @Override
            public void onLongPress(MotionEvent e)
            {
                View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());

                if(childView != null && mListener != null)
                {
                    mListener.onItemLongClick(childView, recyclerView.getChildPosition(childView));
                }
            }
        });
    }

    public void getViewHierarchyUnderChild(ViewGroup root, float x, float y, List<View> viewHierarchy) {
        int[] location = new int[2];
        final int childCount = root.getChildCount();

        for (int i = 0; i < childCount; ++i) {
            final View child = root.getChildAt(i);
            child.getLocationOnScreen(location);
            final int childLeft = location[0], childRight = childLeft + child.getWidth();
            final int childTop = location[1], childBottom = childTop + child.getHeight();

            if (child.isShown() && x >= childLeft && x <= childRight && y >= childTop && y <= childBottom) {
                viewHierarchy.add(0, child);
            }
            if (child instanceof ViewGroup) {
                getViewHierarchyUnderChild((ViewGroup) child, x, y, viewHierarchy);
            }
        }
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e)
    {
        mGestureDetector.onTouchEvent(e);

        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView view, MotionEvent motionEvent){}

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }
}

Then using it from activity / fragment:

recyclerView.addOnItemTouchListener(createItemClickListener(recyclerView));

    public RecyclerItemClickListener createItemClickListener(final RecyclerView recyclerView) {
        return new RecyclerItemClickListener (context, recyclerView, new RecyclerItemClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (view instanceof AppCompatButton) {
                    // ... tapped on the button, so go do something
                } else {
                    // ... tapped on the item container (row), so do something different
                }
            }

            @Override
            public void onItemLongClick(View view, int position) {
            }
        });
    }

How to get the list of all installed color schemes in Vim?

Another simpler way is while you are editing a file - tabe ~/.vim/colors/ ENTER Will open all the themes in a new tab within vim window.

You may come back to the file you were editing using - CTRL + W + W ENTER

Note: Above will work ONLY IF YOU HAVE a .vim/colors directory within your home directory for current $USER (I have 70+ themes)

[user@host ~]$ ls -l ~/.vim/colors | wc -l

72

Chrome Extension - Get DOM content

For those who tried gkalpak answer and it did not work,

be aware that chrome will add the content script to a needed page only when your extension enabled during chrome launch and also a good idea restart browser after making these changes

PowerShell: Store Entire Text File Contents in Variable

Get-Content grabs data and dumps it into an array, line by line. Assuming there aren't other special requirements than you listed, you could just save your content into a variable?

$file = Get-Content c:\file\whatever.txt

Running just $file will return the full contents. Then you can just do $file.Count (because arrays already have a count method built in) to get the total # of lines.

Hope this helps! I'm not a scripting wiz, but this seemed easier to me than a lot of the stuff above.

How to right-align form input boxes?

Use some tag, to aligning the input element. So

<form>
   <div>
     <input>
     <br />
     <input>
    </div>
</form>

    .mydiv
     {
        width: 500px;
        height: 250px;
        display: table;
        text-align: right;
     }

Check if cookies are enabled

Here is a very useful and lightweight javascript plugin to accomplish this: js-cookie

Cookies.set('cookieName', 'Value');
      setTimeout(function(){
        var cookieValue =  Cookies.get('cookieName');
        if(cookieValue){
           console.log("Test Cookie is set!");
        } else {
           document.write('<p>Sorry, but cookies must be enabled</p>');
        }
        Cookies.remove('cookieName');
      }, 1000);

Works in all browsers, accepts any character.

Does a `+` in a URL scheme/host/path represent a space?

Space characters may only be encoded as "+" in one context: application/x-www-form-urlencoded key-value pairs.

The RFC-1866 (HTML 2.0 specification), paragraph 8.2.1. subparagraph 1. says: "The form field names and values are escaped: space characters are replaced by `+', and then reserved characters are escaped").

Here is an example of such a string in URL where RFC-1866 allows encoding spaces as pluses: "http://example.com/over/there?name=foo+bar". So, only after "?", spaces can be replaced by pluses (in other cases, spaces should be encoded to %20). This way of encoding form data is also given in later HTML specifications, for example, look for relevant paragraphs about application/x-www-form-urlencoded in HTML 4.01 Specification, and so on.

But, because it's hard to always correctly determine the context, it's the best practice to never encode spaces as "+". It's better to percent-encode all character except "unreserved" defined in RFC-3986, p.2.3. Here is a code example that illustrates what should be encoded. It is given in Delphi (pascal) programming language, but it is very easy to understand how it works for any programmer regardless of the language possessed:

(* percent-encode all unreserved characters as defined in RFC-3986, p.2.3 *)
function UrlEncodeRfcA(const S: AnsiString): AnsiString;
const    
  HexCharArrA: array [0..15] of AnsiChar = '0123456789ABCDEF';
var
  I: Integer;
  c: AnsiChar;
begin
 // percent-encoding, see RFC-3986, p. 2.1
  Result := S;
  for I := Length(S) downto 1 do
  begin
    c := S[I];
    case c of
      'A' .. 'Z', 'a' .. 'z', // alpha
      '0' .. '9',             // digit
      '-', '.', '_', '~':;    // rest of unreserved characters as defined in the RFC-3986, p.2.3
      else
        begin
          Result[I] := '%';
          Insert('00', Result, I + 1);
          Result[I + 1] := HexCharArrA[(Byte(C) shr 4) and $F)];
          Result[I + 2] := HexCharArrA[Byte(C) and $F];
        end;
    end;
  end;
end;

function UrlEncodeRfcW(const S: UnicodeString): AnsiString;
begin
  Result := UrlEncodeRfcA(Utf8Encode(S));
end;

How to remove gaps between subplots in matplotlib?

Without resorting gridspec entirely, the following might also be used to remove the gaps by setting wspace and hspace to zero:

import matplotlib.pyplot as plt

plt.clf()
f, axarr = plt.subplots(4, 4, gridspec_kw = {'wspace':0, 'hspace':0})

for i, ax in enumerate(f.axes):
    ax.grid('on', linestyle='--')
    ax.set_xticklabels([])
    ax.set_yticklabels([])

plt.show()
plt.close()

Resulting in:

.

Check if at least two out of three booleans are true

Not in context of performance but good code(extensible and readable code that can be reused)

     static boolean trueBooleans (int howMany,boolean ... bools)
     {
      int total = 0;

      for (boolean b:bools)
        if (b && (++total == howMany)) return true;


      return false;
    }

In my humble opinion when writing Java, easy handling unexpected changes and no duplicated code are more important than concise (domain of script languages) or fast program.

How do I convert uint to int in C#?

int intNumber = (int)uintNumber;

Depending on what kind of values you are expecting, you may want to check how big uintNumber is before doing the conversion. An int has a max value of about .5 of a uint.

How to check if element has any children in Javascript?

You can check if the element has child nodes element.hasChildNodes(). Beware in Mozilla this will return true if the is whitespace after the tag so you will need to verify the tag type.

https://developer.mozilla.org/En/DOM/Node.hasChildNodes

Input Type image submit form value?

I've found that image-buttons DO return a response, but you should NOT use a value-option. What I see returned are two version of the name="MYNAME" with .X and .Y endings.

For example:

<input type="image" src="/path-to/stop.png" name="STOP" width="25" height="25" align="top" alt="Stop sign">

This is within your <form> to </form>. If you click the image, what's returned are STOP.X and STOP.Y with numeric values. The existence of either indicates the STOP image-button was clicked. You don't need any special code. Just treat it as another kind of "submit" button that returns a pair of augmented NAMEs.

I've tried this on Safari, Firefox and Chrome. The image wasn't displayed with Safari, but where it was supposed to be located, my cursor turned into a finger-icon, and I could click it.

How to get the fragment instance from the FragmentActivity?

You can use use findFragmentById in FragmentManager.

Since you are using the Support library (you are extending FragmentActivity) you can use:

getSupportFragmentManager().findFragmentById(R.id.pageview)

If you are not using the support library (so you are on Honeycomb+ and you don't want to use the support library):

getFragmentManager().findFragmentById(R.id.pageview)

Please consider that using the support library is recommended even on Honeycomb+.

Sort rows in data.table in decreasing order on string key `order(-x,v)` gives error on data.table 1.9.4 or earlier

Update

data.table v1.9.6+ now supports OP's original attempt and the following answer is no longer necessary.


You can use DT[order(-rank(x), y)].

   x y v
1: c 1 7
2: c 3 8
3: c 6 9
4: b 1 1
5: b 3 2
6: b 6 3
7: a 1 4
8: a 3 5
9: a 6 6

Returning Month Name in SQL Server Query

Have you tried DATENAME(MONTH, S0.OrderDateTime) ?

What is sr-only in Bootstrap 3?

As JoshC said, the class .sr-only is used to visually hide the information used for screen readers only. But not only to hide labels. You might consider hiding various other elements such as "skip to main content" link, icons which have an alternative texts etc.

BTW. you can also use .sr-only sr-only-focusable if you need the element to become visible when focused e.g. "skip to main content"

If you want make your website even more accessible I recommend to start here:

Why?

According to the World Health Organization, 285 million people have vision impairments. So making a website accessible is important.

IMPORTANT: Avoid treating disabled users differently. Generally speaking try to avoid developing a different content for different groups of users. Instead try to make accessible the existing content so that it simply works out-of-the-box and for all not specifically targeting e.g. screen readers. In other words don't try to reinvent the wheel. Otherwise the resulting accessibility will often be worse than if there was nothing developed at all. We developers should not assume how those users will use our website. So be very careful when you need to develop such solutions. Obviously a "skip link" is a good example of such content if it's made visible when focused. But there many bad examples too. Such would be hiding from a screen reader a "zoom" button on the map assuming that it has no relevance to blind users. But surprisingly, a zoom function indeed is used among blind users! They like to download images like many other users do (even in high resolution), for sending them to somebody else or for using them in some other context. Source - Read more @ADG: Bad ARIA practices

Determining type of an object in ruby

you could also try: instance_of?

p 1.instance_of? Fixnum    #=> True
p "1".instance_of? String  #=> True
p [1,2].instance_of? Array #=> True

How to show image using ImageView in Android

In res folder select the XML file in which you want to view your images,

<ImageView
        android:id="@+id/image1"
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:src="@drawable/imagep1" />

How can I verify a Google authentication API access token?

For user check, just post get the access token as accessToken and post it and get the response

https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=accessToken

you can try in address bar in browsers too, use httppost and response in java also

response will be like

{
     "issued_to": "xxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
     "audience": "xxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
     "user_id": "xxxxxxxxxxxxxxxxxxxxxxx",
     "scope": "https://www.googleapis.com/auth/userinfo.profile https://gdata.youtube.com",
     "expires_in": 3340,
     "access_type": "offline"
    }

The scope is the given permission of the accessToken. you can check the scope ids in this link

Update: New API post as below

https://oauth2.googleapis.com/tokeninfo?id_token=XYZ123

Response will be as

 {
 // These six fields are included in all Google ID Tokens.
 "iss": "https://accounts.google.com",
 "sub": "110169484474386276334",
 "azp": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
 "aud": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
 "iat": "1433978353",
 "exp": "1433981953",

 // These seven fields are only included when the user has granted the "profile" and
 // "email" OAuth scopes to the application.
 "email": "[email protected]",
 "email_verified": "true",
 "name" : "Test User",
 "picture": "https://lh4.googleusercontent.com/-kYgzyAWpZzJ/ABCDEFGHI/AAAJKLMNOP/tIXL9Ir44LE/s99-c/photo.jpg",
 "given_name": "Test",
 "family_name": "User",
 "locale": "en"
}

For more info, https://developers.google.com/identity/sign-in/android/backend-auth

Return HTML from ASP.NET Web API

ASP.NET Core. Approach 1

If your Controller extends ControllerBase or Controller you can use Content(...) method:

[HttpGet]
public ContentResult Index() 
{
    return base.Content("<div>Hello</div>", "text/html");
}

ASP.NET Core. Approach 2

If you choose not to extend from Controller classes, you can create new ContentResult:

[HttpGet]
public ContentResult Index() 
{
    return new ContentResult 
    {
        ContentType = "text/html",
        Content = "<div>Hello World</div>"
    };
}

Legacy ASP.NET MVC Web API

Return string content with media type text/html:

public HttpResponseMessage Get()
{
    var response = new HttpResponseMessage();
    response.Content = new StringContent("<div>Hello World</div>");
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
    return response;
}

How to Import .bson file format on mongodb

In mongodb 3.0 or above, we can specify database name to restore. Assuming that you are standing at the root directory that contains bson files

./
a.bson
b.metadata.bson
...

The script would be

for FILENAME in *; do mongorestore -d <db_name> -c "${FILENAME%.*}" $FILENAME; done

Best,

Difference between if () { } and if () : endif;

I used to use curly brackets for "if, else" conditions. However, I found "if(xxx): endif;" is more semantic if the code is heavily wrapped and easier to read in any editors.

Of course, lots editors are capable of recognise and highlight chunks of code when curly brackets are selected. Some also do well on "if(xxx): endif" pair (eg, NetBeans)

Personally, I would recommend "if(xxx): endif", but for small condition check (eg, only one line of code), there are not much differences.

Write a file in UTF-8 using FileWriter (Java)?

use OutputStream instead of FileWriter to set encoding type

// file is your File object where you want to write you data 
OutputStream outputStream = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
outputStreamWriter.write(json); // json is your data 
outputStreamWriter.flush();
outputStreamWriter.close();

JAX-RS / Jersey how to customize error handling?

Jersey throws an com.sun.jersey.api.ParamException when it fails to unmarshall the parameters so one solution is to create an ExceptionMapper that handles these types of exceptions:

@Provider
public class ParamExceptionMapper implements ExceptionMapper<ParamException> {
    @Override
    public Response toResponse(ParamException exception) {
        return Response.status(Status.BAD_REQUEST).entity(exception.getParameterName() + " incorrect type").build();
    }
}

Filtering Pandas Dataframe using OR statement

From the docs:

Another common operation is the use of boolean vectors to filter the data. The operators are: | for or, & for and, and ~ for not. These must be grouped by using parentheses.

http://pandas.pydata.org/pandas-docs/version/0.15.2/indexing.html#boolean-indexing

Try:

alldata_balance = alldata[(alldata[IBRD] !=0) | (alldata[IMF] !=0)]

jQuery - Click event on <tr> elements with in a table and getting <td> element values

$("body").on("click", "#tableid tr", function () {
    debugger
    alert($(this).text());
});

$("body").on("click", "#tableid td", function () {
    debugger
    alert($(this).text());
});

What exactly does stringstream do?

From C++ Primer:

The istringstream type reads a string, ostringstream writes a string, and stringstream reads and writes the string.

I come across some cases where it is both convenient and concise to use stringstream.

case 1

It is from one of the solutions for this leetcode problem. It demonstrates a very suitable case where the use of stringstream is efficient and concise.

Suppose a and b are complex numbers expressed in string format, we want to get the result of multiplication of a and b also in string format. The code is as follows:

string a = "1+2i", b = "1+3i";
istringstream sa(a), sb(b);
ostringstream out;

int ra, ia, rb, ib;
char buff;
// only read integer values to get the real and imaginary part of 
// of the original complex number
sa >> ra >> buff >> ia >> buff;
sb >> rb >> buff >> ib >> buff;

out << ra*rb-ia*ib << '+' << ra*ib+ia*rb << 'i';

// final result in string format
string result = out.str() 

case 2

It is also from a leetcode problem that requires you to simplify the given path string, one of the solutions using stringstream is the most elegant that I have seen:

string simplifyPath(string path) {
    string res, tmp;
    vector<string> stk;
    stringstream ss(path);
    while(getline(ss,tmp,'/')) {
        if (tmp == "" or tmp == ".") continue;
        if (tmp == ".." and !stk.empty()) stk.pop_back();
        else if (tmp != "..") stk.push_back(tmp);
    }
    for(auto str : stk) res += "/"+str;
    return res.empty() ? "/" : res; 
 }

Without the use of stringstream, it would be difficult to write such concise code.

document.getElementByID is not a function

I've modified your script to work with jQuery, if you wish to do so.

$(document).ready(function(){
    //To add a task when the user hits the return key
    $('#task-text').keydown(function(evt){
          if(evt.keyCode == 13)
          {
             add_task($(this), evt);
          }
    });
    //To add a task when the user clicks on the submit button
    $("#add-task").click(function(evt){
        add_task($("#task-text"),evt);
    });
});

function add_task(textBox, evt){
  evt.preventDefault();
  var taskText = textBox.val();
  $("<li />").text(taskText).appendTo("#tasks");
  textBox.val("");
};

Convert numpy array to tuple

Another option

tuple([tuple(row) for row in myarray])

If you are passing NumPy arrays to C++ functions, you may also wish to look at using Cython or SWIG.

Splitting a continuous variable into equal sized groups

Without any extra package, 3 being the number of groups:

> findInterval(das$wt, unique(quantile(das$wt, seq(0, 1, length.out = 3 + 1))), rightmost.closed = TRUE)
 [1] 1 1 1 2 2 2 3 1 3 3 3 2 1 3 2

You can speed up the quantile computation by using a representative sample of the values of interest. Double check the documentation of the FindInterval function.

Pros/cons of using redux-saga with ES6 generators vs redux-thunk with ES2017 async/await

An easier way is to use redux-auto.

from the documantasion

redux-auto fixed this asynchronous problem simply by allowing you to create an "action" function that returns a promise. To accompany your "default" function action logic.

  1. No need for other Redux async middleware. e.g. thunk, promise-middleware, saga
  2. Easily allows you to pass a promise into redux and have it managed for you
  3. Allows you to co-locate external service calls with where they will be transformed
  4. Naming the file "init.js" will call it once at app start. This is good for loading data from the server at start

The idea is to have each action in a specific file. co-locating the server call in the file with reducer functions for "pending", "fulfilled" and "rejected". This makes handling promises very easy.

It also automatically attaches a helper object(called "async") to the prototype of your state, allowing you to track in your UI, requested transitions.

Programmatically set image to UIImageView with Xcode 6.1/Swift

OK, got it working with this (creating the UIImageView programmatically):

var imageViewObject :UIImageView

imageViewObject = UIImageView(frame:CGRectMake(0, 0, 600, 600))

imageViewObject.image = UIImage(named:"afternoon")

self.view.addSubview(imageViewObject)

self.view.sendSubviewToBack(imageViewObject)

JSON serialization/deserialization in ASP.Net Core

You can use Newtonsoft.Json, it's a dependency of Microsoft.AspNet.Mvc.ModelBinding which is a dependency of Microsoft.AspNet.Mvc. So, you don't need to add a dependency in your project.json.

#using Newtonsoft.Json
....
JsonConvert.DeserializeObject(json);

Note, using a WebAPI controller you don't need to deal with JSON.

UPDATE ASP.Net Core 3.0

Json.NET has been removed from the ASP.NET Core 3.0 shared framework.

You can use the new JSON serializer layers on top of the high-performance Utf8JsonReader and Utf8JsonWriter. It deserializes objects from JSON and serializes objects to JSON. Memory allocations are kept minimal and includes support for reading and writing JSON with Stream asynchronously.

To get started, use the JsonSerializer class in the System.Text.Json.Serialization namespace. See the documentation for information and samples.

To use Json.NET in an ASP.NET Core 3.0 project:

    services.AddMvc()
        .AddNewtonsoftJson();

Read Json.NET support in Migrate from ASP.NET Core 2.2 to 3.0 Preview 2 for more information.

How to fix a collation conflict in a SQL Server query?

I resolved a similar issue by wrapping the query in another query...

Initial query was working find giving individual columns of output, with some of the columns coming from sub queries with Max or Sum function, and other with "distinct" or case substitutions and such.

I encountered the collation error after attempting to create a single field of output with...

select
rtrim(field1)+','+rtrim(field2)+','+...

The query would execute as I wrote it, but the error would occur after saving the sql and reloading it.

Wound up fixing it with something like...

select z.field1+','+z.field2+','+... as OUTPUT_REC
from (select rtrim(field1), rtrim(field2), ... ) z

Some fields are "max" of a subquery, with a case substitution if null and others are date fields, and some are left joins (might be NULL)...in other words, mixed field types. I believe this is the cause of the issue being caused by OS collation and Database collation being slightly different, but by converting all to trimmed strings before the final select, it sorts it out, all in the SQL.

How can I position my jQuery dialog to center?

I'm getting best results to put jQuery dialog in the center of browser's window with:

position: { my: "center bottom", at: "center center", of: window },

There's probably more accurate way to position it with option "using" as described in the documentation at http://api.jqueryui.com/position/ but I'm in a hurry...

Generate list of all possible permutations of a string

Recursive Solution with driver main() method.

public class AllPermutationsOfString {
public static void stringPermutations(String newstring, String remaining) {
    if(remaining.length()==0)
        System.out.println(newstring);

    for(int i=0; i<remaining.length(); i++) {
        String newRemaining = remaining.replaceFirst(remaining.charAt(i)+"", "");
        stringPermutations(newstring+remaining.charAt(i), newRemaining);
    }
}

public static void main(String[] args) {
    String string = "abc";
    AllPermutationsOfString.stringPermutations("", string); 
}

}

Passing HTML input value as a JavaScript Function Parameter

Firstly an elements ID should always be unique. If your element IDs aren't unique then you would always get conflicting results. Imagine in your case using two different elements with the same ID.

<form>
  a: <input type="number" name="a" id="a"><br>
  b: <input type="number" name="b" id="b"><br>
  <button onclick="add()">Add</button>
</form>

<script>
  function add() {
    var a = document.getElementById('a').value;
    var b = document.getElementById('b').value;

    var sum = parseInt(a) + parseInt(b);
    alert(sum);
  }
</script>

Wait Until File Is Completely Written

From the documentation for FileSystemWatcher:

The OnCreated event is raised as soon as a file is created. If a file is being copied or transferred into a watched directory, the OnCreated event will be raised immediately, followed by one or more OnChanged events.

So, if the copy fails, (catch the exception), add it to a list of files that still need to be moved, and attempt the copy during the OnChanged event. Eventually, it should work.

Something like (incomplete; catch specific exceptions, initialize variables, etc):

public static void listener_Created(object sender, FileSystemEventArgs e)
{
    Console.WriteLine
            (
                "File Created:\n"
               + "ChangeType: " + e.ChangeType
               + "\nName: " + e.Name
               + "\nFullPath: " + e.FullPath
            );
    try {
        File.Copy(e.FullPath, @"D:\levani\FolderListenerTest\CopiedFilesFolder\" + e.Name);
    }
    catch {
        _waitingForClose.Add(e.FullPath);
    }
    Console.Read();
}

public static void listener_Changed(object sender, FileSystemEventArgs e)
{
     if (_waitingForClose.Contains(e.FullPath))
     {
          try {
              File.Copy(...);
              _waitingForClose.Remove(e.FullPath);
          }
          catch {}
     }

}

Difference between @Before, @BeforeClass, @BeforeEach and @BeforeAll

Before and BeforeClass in JUnit

The function @Before annotation will be executed before each of test function in the class having @Test annotation but the function with @BeforeClass will be execute only one time before all the test functions in the class.

Similarly function with @After annotation will be executed after each of test function in the class having @Test annotation but the function with @AfterClass will be execute only one time after all the test functions in the class.

SampleClass

public class SampleClass {
    public String initializeData(){
        return "Initialize";
    }

    public String processDate(){
        return "Process";
    }
 }

SampleTest

public class SampleTest {

    private SampleClass sampleClass;

    @BeforeClass
    public static void beforeClassFunction(){
        System.out.println("Before Class");
    }

    @Before
    public void beforeFunction(){
        sampleClass=new SampleClass();
        System.out.println("Before Function");
    }

    @After
    public void afterFunction(){
        System.out.println("After Function");
    }

    @AfterClass
    public static void afterClassFunction(){
        System.out.println("After Class");
    }

    @Test
    public void initializeTest(){
        Assert.assertEquals("Initailization check", "Initialize", sampleClass.initializeData() );
    }

    @Test
    public void processTest(){
        Assert.assertEquals("Process check", "Process", sampleClass.processDate() );
    }

}

Output

Before Class
Before Function
After Function
Before Function
After Function
After Class

In Junit 5

@Before = @BeforeEach
@BeforeClass = @BeforeAll
@After = @AfterEach
@AfterClass = @AfterAll

Best ways to teach a beginner to program?

Something you should be very mindful of while teaching your brother to program is for him not to rely too heavily on you. Often when I find myself helping others they will begin to think of me as answer book to all of their questions and instead of experimenting to find an answer they simply ask me. Often the best teacher is experimentation and every time your brother has a question like "What will happen if I add 2 to a string?" you should tell him to try it out and see for himself. Also I have noticed that when I cannot get a concept through to someone, it helps to see some sample code where we can look at each segment individually and explain it piece by piece. As a side note people new to programming often have trouble with the idea of object oriented programming, they will say they understand it when you teach it to them but will not get a clear concept of it until actually implementing it.

Docker: How to delete all local Docker images

Adding to techtabu's accepted answer, If you're using docker on windows, you can use the following command

for /F "delims=" %A in ('docker ps -a -q') do docker rm %A

here, the command docker ps -a -q lists all the images and this list is passed to docker rm one by one

see this for more details on how this type of command format works in windows cmd.

Get current date, given a timezone in PHP?

The other answers set the timezone for all dates in your system. This doesn't always work well if you want to support multiple timezones for your users.

Here's the short version:

<?php
$date = new DateTime("now", new DateTimeZone('America/New_York') );
echo $date->format('Y-m-d H:i:s');

Works in PHP >= 5.2.0

List of supported timezones: php.net/manual/en/timezones.php


Here's a version with an existing time and setting timezone by a user setting

<?php

$usersTimezone = 'America/New_York';
$date = new DateTime( 'Thu, 31 Mar 2011 02:05:59 GMT', new DateTimeZone($usersTimezone) );
echo $date->format('Y-m-d H:i:s');

Here is a more verbose version to show the process a little more clearly

<?php

// Date for a specific date/time:
$date = new DateTime('Thu, 31 Mar 2011 02:05:59 GMT');

// Output date (as-is)
echo $date->format('l, F j Y g:i:s A');     

// Output line break (for testing)
echo "\n<br />\n";

// Example user timezone (to show it can be used dynamically)
$usersTimezone = 'America/New_York';

// Convert timezone
$tz = new DateTimeZone($usersTimezone);
$date->setTimeZone($tz);

// Output date after 
echo $date->format('l, F j Y g:i:s A');

Libraries

  • Carbon — A very popular date library.
  • Chronos — A drop-in replacement for Carbon focused on immutability. See below on why that's important.
  • jenssegers/date — An extension of Carbon that adds multi-language support.

I'm sure there are a number of other libraries available, but these are a few I'm familiar with.


Bonus Lesson: Immutable Date Objects

While you're here, let me save you some future headache. Let's say you want to calculate 1 week from today and 2 weeks from today. You might write some code like:

<?php

// Create a datetime (now, in this case 2017-Feb-11)
$today = new DateTime();

echo $today->format('Y-m-d') . "\n<br>";
echo "---\n<br>";

$oneWeekFromToday = $today->add(DateInterval::createFromDateString('7 days'));
$twoWeeksFromToday = $today->add(DateInterval::createFromDateString('14 days'));

echo $today->format('Y-m-d') . "\n<br>";
echo $oneWeekFromToday->format('Y-m-d') . "\n<br>";
echo $twoWeeksFromToday->format('Y-m-d') . "\n<br>";
echo "\n<br>";

The output:

2017-02-11 
--- 
2017-03-04 
2017-03-04 
2017-03-04

Hmmmm... That's not quite what we wanted. Modifying a traditional DateTime object in PHP not only returns the updated date but modifies the original object as well.

This is where DateTimeImmutable comes in.

$today = new DateTimeImmutable();

echo $today->format('Y-m-d') . "\n<br>";
echo "---\n<br>";

$oneWeekFromToday = $today->add(DateInterval::createFromDateString('7 days'));
$twoWeeksFromToday = $today->add(DateInterval::createFromDateString('14 days'));

echo $today->format('Y-m-d') . "\n<br>";
echo $oneWeekFromToday->format('Y-m-d') . "\n<br>";
echo $twoWeeksFromToday->format('Y-m-d') . "\n<br>";

The output:

2017-02-11 
--- 
2017-02-11 
2017-02-18 
2017-02-25 

In this second example, we get the dates we expected back. By using DateTimeImmutable instead of DateTime, we prevent accidental state mutations and prevent potential bugs.

How to downgrade python from 3.7 to 3.6

Create a python virtual environment using conda, and then install the tensorflow:

$ conda create -n [environment-name] python=3.6
# it may ask for installing python-3.6 if you don't have it already. Type "y" to proceed...
$ activate [environment-name]
$ pip install tensorflow

From now on, you can activate the environment whenever you want to use tensorflow.

If you don't have the conda package manager, first download it from here: https://www.anaconda.com/distribution

What is the difference between "word-break: break-all" versus "word-wrap: break-word" in CSS

At least in Firefox (as of v24) and Chrome (as of v30), when applied to content in a table element:

word-wrap:break-word

will not actually cause long words to wrap, which can result in the table exceeding the bounds of its container;

word-break:break-all

will result in words wrapping, and the table fitting within its container.

enter image description here

jsfiddle demo.

Is there an ignore command for git like there is for svn?

Using the answers already provided, you can roll your own git ignore command using an alias. Either add this to your ~/.gitconfig file:

ignore = !sh -c 'echo $1 >> .gitignore' -

Or run this command from the (*nix) shell of your choice:

git config --global alias.ignore '!sh -c "echo $1 >> .gitignore" -'

You can likewise create a git exclude command by replacing ignore with exclude and .gitignore with .git/info/exclude in the above.

(If you don't already understand the difference between these two files having read the answers here, see this question.)

How to get the host name of the current machine as defined in the Ansible hosts file?

This is an alternative:

- name: Install this only for local dev machine
  pip: name=pyramid
  delegate_to: localhost

Set Response Status Code

I don't think you're setting the header correctly, try this:

header('HTTP/1.0 401 Unauthorized');

Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?

Mutable is for marking specific attribute as modifiable from within const methods. That is its only purpose. Think carefully before using it, because your code will probably be cleaner and more readable if you change the design rather than use mutable.

http://www.highprogrammer.com/alan/rants/mutable.html

So if the above madness isn't what mutable is for, what is it for? Here's the subtle case: mutable is for the case where an object is logically constant, but in practice needs to change. These cases are few and far between, but they exist.

Examples the author gives include caching and temporary debugging variables.

Convert string with comma to integer

If someone is looking to sub out more than a comma I'm a fan of:

"1,200".chars.grep(/\d/).join.to_i

dunno about performance but, it is more flexible than a gsub, ie:

"1-200".chars.grep(/\d/).join.to_i

100% height minus header?

If your browser supports CSS3, try using the CSS element Calc()

height: calc(100% - 65px);

you might also want to adding browser compatibility options:

height: -o-calc(100% - 65px); /* opera */
height: -webkit-calc(100% - 65px); /* google, safari */
height: -moz-calc(100% - 65px); /* firefox */

also make sure you have spaces between values, see: https://stackoverflow.com/a/16291105/427622

dynamic_cast and static_cast in C++

dynamic_cast uses RTTI. It can slow down your application, you can use modification of the visitor design pattern to achieve downcasting without RTTI http://arturx64.github.io/programming-world/2016/02/06/lazy-visitor.html

OOP vs Functional Programming vs Procedural

One of my friends is writing a graphics app using NVIDIA CUDA. Application fits in very nicely with OOP paradigm and the problem can be decomposed into modules neatly. However, to use CUDA you need to use C, which doesn't support inheritance. Therefore, you need to be clever.

a) You devise a clever system which will emulate inheritance to a certain extent. It can be done!

i) You can use a hook system, which expects every child C of parent P to have a certain override for function F. You can make children register their overrides, which will be stored and called when required.

ii) You can use struct memory alignment feature to cast children into parents.

This can be neat but it's not easy to come up with future-proof, reliable solution. You will spend lots of time designing the system and there is no guarantee that you won't run into problems half-way through the project. Implementing multiple inheritance is even harder, if not almost impossible.

b) You can use consistent naming policy and use divide and conquer approach to create a program. It won't have any inheritance but because your functions are small, easy-to-understand and consistently formatted you don't need it. The amount of code you need to write goes up, it's very hard to stay focused and not succumb to easy solutions (hacks). However, this ninja way of coding is the C way of coding. Staying in balance between low-level freedom and writing good code. Good way to achieve this is to write prototypes using a functional language. For example, Haskell is extremely good for prototyping algorithms.

I tend towards approach b. I wrote a possible solution using approach a, and I will be honest, it felt very unnatural using that code.

Counter increment in Bash loop not working

COUNTER=1
while [ Your != "done" ]
do
     echo " $COUNTER "
     COUNTER=$[$COUNTER +1]
done

TESTED BASH: Centos, SuSE, RH

Xcode: Could not locate device support files

  1. Download & mount http://adcdownload.apple.com/Developer_Tools/Xcode_7.3.1/Xcode_7.3.1.dmg I was first wandered if it could be mounted directly through hdiutil attach and looks like it could but not for everyone's accounts.

  2. Open to see its content and copy Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/7.1 to same path into Xcode application directory.

  3. Restart Xcode

How to search for an element in a golang slice

With a simple for loop:

for _, v := range myconfig {
    if v.Key == "key1" {
        // Found!
    }
}

Note that since element type of the slice is a struct (not a pointer), this may be inefficient if the struct type is "big" as the loop will copy each visited element into the loop variable.

It would be faster to use a range loop just on the index, this avoids copying the elements:

for i := range myconfig {
    if myconfig[i].Key == "key1" {
        // Found!
    }
}

Notes:

It depends on your case whether multiple configs may exist with the same key, but if not, you should break out of the loop if a match is found (to avoid searching for others).

for i := range myconfig {
    if myconfig[i].Key == "key1" {
        // Found!
        break
    }
}

Also if this is a frequent operation, you should consider building a map from it which you can simply index, e.g.

// Build a config map:
confMap := map[string]string{}
for _, v := range myconfig {
    confMap[v.Key] = v.Value
}

// And then to find values by key:
if v, ok := confMap["key1"]; ok {
    // Found
}

What's your most controversial programming opinion?

1. You should not follow web standards - all the time.

2. You don't need to comment your code.

As long as it's understandable by a stranger.

Error when checking Java version: could not find java.dll

Reinstall JDK and set system variable JAVA_HOME on your JDK. (e.g. C:\tools\jdk7)
And add JAVA_HOME variable to your PATH system variable

Type in command line

echo %JAVA_HOME%

and

java -version

To verify whether your installation was done successfully.


This problem generally occurs in Windows when your "Java Runtime Environment" registry entry is missing or mismatched with the installed JDK. The mismatch can be due to multiple JDKs.

Steps to resolve:

  1. Open the Run window:

    Press windows+R

  2. Open registry window:

    Type regedit and enter.

  3. Go to: \HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\

  4. If Java Runtime Environment is not present inside JavaSoft, then create a new Key and give the name Java Runtime Environment.

  5. For Java Runtime Environment create "CurrentVersion" String Key and give appropriate version as value:

JRE regedit entry

  1. Create a new subkey of 1.8.

  2. For 1.8 create a String Key with name JavaHome with the value of JRE home:

    JRE regedit entry 2

Ref: https://mybindirectory.blogspot.com/2019/05/error-could-not-find-javadll.html

Create a simple HTTP server with Java?

The easiest is Simple there is a tutorial, no WEB-INF not Servlet API no dependencies. Just a simple lightweight HTTP server in a single JAR.

bootstrap button shows blue outline when clicked

Here's my Boostrap 4 solution to remove the button outline

/*
* Boostrap 4
* Remove blue outline from button
*/

.btn:focus,
.btn:active {
  box-shadow: none;
}

How to add Class in <li> using wp_nav_menu() in Wordpress?

How about just using str_replace function, if you just want to "Add Classes":

<?php
    echo str_replace( '<li class="', '<li class="myclass ',
        wp_nav_menu(
            array(
                'theme_location'    => 'main_menu',
                'container'         => false,
                'items_wrap'        => '<ul>%3$s</ul>',
                'depth'             => 1,
                'echo'              => false
            )
        )
    );
?>

Tough it is a quick fix for one-level menus or the menus that you want to add Classes to all of <li> elements and is not recommended for more complex menus

fopen deprecated warning

It looks like Microsoft has deprecated lots of calls which use buffers to improve code security. However, the solutions they're providing aren't portable. Anyway, if you aren't interested in using the secure version of their calls (like fopen_s), you need to place a definition of _CRT_SECURE_NO_DEPRECATE before your included header files. For example:

#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>

The preprocessor directive can also be added to your project settings to effect it on all the files under the project. To do this add _CRT_SECURE_NO_DEPRECATE to Project Properties -> Configuration Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions.

Changing website favicon dynamically

According to WikiPedia, you can specify which favicon file to load using the link tag in the head section, with a parameter of rel="icon".

For example:

 <link rel="icon" type="image/png" href="/path/image.png">

I imagine if you wanted to write some dynamic content for that call, you would have access to cookies so you could retrieve your session information that way and present appropriate content.

You may fall foul of file formats (IE reportedly only supports it's .ICO format, whilst most everyone else supports PNG and GIF images) and possibly caching issues, both on the browser and through proxies. This would be because of the original itention of favicon, specifically, for marking a bookmark with a site's mini-logo.

C - reading command line parameters

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv) {
  int i, parameter = 0;
  if (argc >= 2) {
    /* there is 1 parameter (or more) in the command line used */
    /* argv[0] may point to the program name */
    /* argv[1] points to the 1st parameter */
    /* argv[argc] is NULL */
    parameter = atoi(argv[1]); /* better to use strtol */
    if (parameter > 0) {
      for (i = 0; i < parameter; i++) printf("%d ", i);
    } else {
      fprintf(stderr, "Please use a positive integer.\n");
    }
  }
  return 0;
}

How to do logging in React Native?

enter image description hereUse react native debugger for logging and redux store https://github.com/jhen0409/react-native-debugg

Just download it and run as software then enable Debug mode from the simulator.

It supports other debugging feature just like element in chrome developer tools, which helps to see the styling provided to any component.

Last complete support for redux dev tools

AngularJS Dropdown required validation

You need to add a name attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

HTML:

        <form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
        <input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
          <select name="service_id" class="Sitedropdown" style="width: 220px;"          
                  ng-model="ServiceID" 
                  ng-options="service.ServiceID as service.ServiceName for service in services"
                  required> 
            <option value="">Select Service</option> 
          </select> 
          <span ng-show="myForm.service_id.$error.required">Select service</span>

        </form>

    Controller:

        function Ctrl($scope) {
          $scope.services = [
            {ServiceID: 1, ServiceName: 'Service1'},
            {ServiceID: 2, ServiceName: 'Service2'},
            {ServiceID: 3, ServiceName: 'Service3'}
          ];

    $scope.save = function(myForm) {
    console.log('Selected Value: '+ myForm.service_id.$modelValue);
    alert('Data Saved! without validate');
    };
        }

Here's a working plunker.

How to change Named Range Scope

I found the solution! Just copy the sheet with your named variables. Then delete the original sheet. The copied sheet will now have the same named variables, but with a local scope (scope= the copied sheet).

However, I don't know how to change from local variables to global..

PHP - warning - Undefined property: stdClass - fix?

Error control operator

In case the warning is expected you can use the error control operator @ to suppress thrown messages.

$role_arr = getRole(@$response->records);

While this reduces clutter in your code you should use it with caution as it may make debugging future errors harder. An example where using @ may be useful is when creating an object from user input and running it through a validation method before using it in further logic.


Null Coalesce Operator

Another alternative is using the isset_ternary operator ??. This allows you to avoid warnings and assign default value in a short one line fashion.

$role_arr = getRole($response->records ?? null);

Two's Complement in Python

It's much easier than all that...

for X on N bits: Comp = (-X) & (2**N - 1)

def twoComplement(number, nBits):
    return (-number) & (2**nBits - 1)

Is < faster than <=?

This would be highly dependent on the underlying architecture that the C is compiled to. Some processors and architectures might have explicit instructions for equal to, or less than and equal to, which execute in different numbers of cycles.

That would be pretty unusual though, as the compiler could work around it, making it irrelevant.

SQLRecoverableException: I/O Exception: Connection reset

Solution
Change the setup for your application, so you this parameter[-Djava.security.egd=file:/dev/../dev/urandom] next to the java command:

java -Djava.security.egd=file:/dev/../dev/urandom [your command]

Ref :- https://community.oracle.com/thread/943911

Python List & for-each access (Find/Replace in built-in list)

Python is not Java, nor C/C++ -- you need to stop thinking that way to really utilize the power of Python.

Python does not have pass-by-value, nor pass-by-reference, but instead uses pass-by-name (or pass-by-object) -- in other words, nearly everything is bound to a name that you can then use (the two obvious exceptions being tuple- and list-indexing).

When you do spam = "green", you have bound the name spam to the string object "green"; if you then do eggs = spam you have not copied anything, you have not made reference pointers; you have simply bound another name, eggs, to the same object ("green" in this case). If you then bind spam to something else (spam = 3.14159) eggs will still be bound to "green".

When a for-loop executes, it takes the name you give it, and binds it in turn to each object in the iterable while running the loop; when you call a function, it takes the names in the function header and binds them to the arguments passed; reassigning a name is actually rebinding a name (it can take a while to absorb this -- it did for me, anyway).

With for-loops utilizing lists, there are two basic ways to assign back to the list:

for i, item in enumerate(some_list):
    some_list[i] = process(item)

or

new_list = []
for item in some_list:
    new_list.append(process(item))
some_list[:] = new_list

Notice the [:] on that last some_list -- it is causing a mutation of some_list's elements (setting the entire thing to new_list's elements) instead of rebinding the name some_list to new_list. Is this important? It depends! If you have other names besides some_list bound to the same list object, and you want them to see the updates, then you need to use the slicing method; if you don't, or if you do not want them to see the updates, then rebind -- some_list = new_list.

PHPExcel Make first row bold

This iterates through a variable number of columns of a particular row, which in this case is the 1st row:

$rownumber = 1;
$row = $this->objPHPExcel->getActiveSheet()->getRowIterator($rownumber)->current();

$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);

foreach ($cellIterator as $cell) {
    $cell->getStyle()->getFont()->setBold(true);
}

UICollectionView Self Sizing Cells with Auto Layout

If you implement UICollectionViewDelegateFlowLayout method:

- (CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath*)indexPath

When you call collectionview performBatchUpdates:completion:, the size height will use sizeForItemAtIndexPath instead of preferredLayoutAttributesFittingAttributes.

The rendering process of performBatchUpdates:completion will go through the method preferredLayoutAttributesFittingAttributes but it ignores your changes.

pip installation /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory

I had the same issue. I have both Python 2.7 & 3.6 installed. Python 2.7 had virtualenv working, but after installing Python3, virtualenv kept looking for version 2.7 and couldn't find it. Doing pip install virtualenv installed the Python3 version of virtualenv.

Then, for each command, if I want to use Python2, I would use virtualenv --python=python2.7 somecommand

What's the simplest way of detecting keyboard input in a script from the terminal?

This needs run as root: (Warning, this is a system-wide keylogger)

#!/usr/bin/python3

import signal
import keyboard
import time
import os


if not os.geteuid() == 0:
  print("This script needs to be run as root.")
  exit()

def exitNice(signum, frame):
  global running 
  running = False

def keyEvent(e):
  global running
  if e.event_type == "up":
    print("Key up: " + str(e.name))
  if e.event_type == "down":
    print("Key down: " + str(e.name))
  if e.name == "q":
    exitNice("", "")
    print("Quitting")

running = True
signal.signal(signal.SIGINT, exitNice)
keyboard.hook(keyEvent)

print("Press 'q' to quit")
fps = 1/24
while running:
  time.sleep(fps)

seek() function?

Regarding seek() there's not too much to worry about.

First of all, it is useful when operating over an open file.

It's important to note that its syntax is as follows:

fp.seek(offset, from_what)

where fp is the file pointer you're working with; offset means how many positions you will move; from_what defines your point of reference:

  • 0: means your reference point is the beginning of the file
  • 1: means your reference point is the current file position
  • 2: means your reference point is the end of the file

if omitted, from_what defaults to 0.

Never forget that when managing files, there'll always be a position inside that file where you are currently working on. When just open, that position is the beginning of the file, but as you work with it, you may advance.
seek will be useful to you when you need to walk along that open file, just as a path you are traveling into.

SQL Inner join 2 tables with multiple column conditions and update

You should join T1 and T2 tables using sql joins in order to analyze from two tables. Link for learn joins : https://www.w3schools.com/sql/sql_join.asp

How can I use Python to get the system hostname?

You have to execute this line of code

sock_name = socket.gethostname()

And then you can use the name to find the addr :

print(socket.gethostbyname(sock_name))

Elegant ways to support equivalence ("equality") in Python classes

I think that the two terms you're looking for are equality (==) and identity (is). For example:

>>> a = [1,2,3]
>>> b = [1,2,3]
>>> a == b
True       <-- a and b have values which are equal
>>> a is b
False      <-- a and b are not the same list object

How to restart a single container with docker-compose

Following command

docker-compose restart worker

will just STOP and START the container. i.e without loading any changes from the docker-compose.xml

STOP is similar to hibernating in PC . Hence stop/start will not look for any changes made in configuration file . To reload from the recipe of container (docker-compose.xml) we need to remove and create the container (Similar analogy to rebooting the PC )

So commands will be as following

docker-compose stop worker       // go to hibernate
docker-compose rm worker        // shutdown the PC 
docker-compose create worker     // create the container from image and put it in hibernate

docker-compose start worker //bring container to life from hibernation

jQuery onclick toggle class name

It can even be made dependent to another attribute changes. like this:

$('.classA').toggleClass('classB', $('input').prop('disabled'));

In this case, classB are added each time the input is disabled

How can I get the max (or min) value in a vector?

Let,

 #include <vector>

 vector<int> v {1, 2, 3, -1, -2, -3};

If the vector is sorted in ascending or descending order then you can find it with complexity O(1).

For a vector of ascending order the first element is the smallest element, you can get it by v[0] (0 based indexing) and last element is the largest element, you can get it by v[sizeOfVector-1].

If the vector is sorted in descending order then the last element is the smallest element,you can get it by v[sizeOfVector-1] and first element is the largest element, you can get it by v[0].

If the vector is not sorted then you have to iterate over the vector to get the smallest/largest element.In this case time complexity is O(n), here n is the size of vector.

int smallest_element = v[0]; //let, first element is the smallest one
int largest_element = v[0]; //also let, first element is the biggest one
for(int i = 1; i < v.size(); i++)  //start iterating from the second element
{
    if(v[i] < smallest_element)
    {
       smallest_element = v[i];
    }
    if(v[i] > largest_element)
    {
       largest_element = v[i];
    }
}

You can use iterator,

for (vector<int>:: iterator it = v.begin(); it != v.end(); it++)
{
    if(*it < smallest_element) //used *it (with asterisk), because it's an iterator
    {
      smallest_element = *it;
    }
    if(*it > largest_element)
    {
      largest_element = *it;
    }
}

You can calculate it in input section (when you have to find smallest or largest element from a given vector)

int smallest_element, largest_element, value;
vector <int> v;
int n;//n is the number of elements to enter
cin >> n;
for(int i = 0;i<n;i++)
{
    cin>>value;
    if(i==0)
    {
        smallest_element= value; //smallest_element=v[0];
        largest_element= value; //also, largest_element = v[0]
    }

    if(value<smallest_element and i>0)
    {
        smallest_element = value;
    }

    if(value>largest_element and i>0)
    {
        largest_element = value;
    }
    v.push_back(value);
}

Also you can get smallest/largest element by built in functions

#include<algorithm>

int smallest_element = *min_element(v.begin(),v.end());

int largest_element  = *max_element(v.begin(),v.end());

You can get smallest/largest element of any range by using this functions. such as,

vector<int> v {1,2,3,-1,-2,-3};

cout << *min_element(v.begin(), v.begin() + 3); //this will print 1,smallest element of first three elements

cout << *max_element(v.begin(), v.begin() + 3); //largest element of first three elements

cout << *min_element(v.begin() + 2, v.begin() + 5); // -2, smallest element between third and fifth element (inclusive)

cout << *max_element(v.begin() + 2, v.begin()+5); //largest element between third and first element (inclusive)

I have used asterisk (*), before min_element()/max_element() functions. Because both of them return iterator. All codes are in c++.

How do I find the size of a struct?

I assume you mean struct and not strict, but on a 32-bit system it'll be either 5 or 8 bytes, depending on if the compiler is padding the struct.

How do I return multiple values from a function?

I prefer to use tuples whenever a tuple feels "natural"; coordinates are a typical example, where the separate objects can stand on their own, e.g. in one-axis only scaling calculations, and the order is important. Note: if I can sort or shuffle the items without an adverse effect to the meaning of the group, then I probably shouldn't use a tuple.

I use dictionaries as a return value only when the grouped objects aren't always the same. Think optional email headers.

For the rest of the cases, where the grouped objects have inherent meaning inside the group or a fully-fledged object with its own methods is needed, I use a class.

Anyway to prevent the Blue highlighting of elements in Chrome when clicking quickly?

This works the best for me:

.noSelect:hover {
  background-color: white;
}

.NET NewtonSoft JSON deserialize map to a different property name

I am using JsonProperty attributes when serializing but ignoring them when deserializing using this ContractResolver:

public class IgnoreJsonPropertyContractResolver: DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            var properties = base.CreateProperties(type, memberSerialization);
            foreach (var p in properties) { p.PropertyName = p.UnderlyingName; }
            return properties;
        }
    }

The ContractResolver just sets every property back to the class property name (simplified from Shimmy's solution). Usage:

var airplane= JsonConvert.DeserializeObject<Airplane>(json, 
    new JsonSerializerSettings { ContractResolver = new IgnoreJsonPropertyContractResolver() });

Find current directory and file's directory

For question 1 use os.getcwd() # get working dir and os.chdir(r'D:\Steam\steamapps\common') # set working dir


I recommend using sys.argv[0] for question 2 because sys.argv is immutable and therefore always returns the current file (module object path) and not affected by os.chdir(). Also you can do like this:

import os
this_py_file = os.path.realpath(__file__)

# vvv Below comes your code vvv #

but that snippet and sys.argv[0] will not work or will work wierd when compiled by PyInstaller because magic properties are not set in __main__ level and sys.argv[0] is the way your exe was called (means that it becomes affected by the working dir).

In Java, what purpose do the keywords `final`, `finally` and `finalize` fulfil?

  • "Final" denotes that something cannot be changed. You usually want to use this on static variables that will hold the same value throughout the life of your program.
  • "Finally" is used in conjunction with a try/catch block. Anything inside of the "finally" clause will be executed regardless of if the code in the 'try' block throws an exception or not.
  • "Finalize" is called by the JVM before an object is about to be garbage collected.

Redirect with CodeIgniter

Here is .htacess file that hide index file

#RewriteEngine on
#RewriteCond $1 !^(index\.php|images|robots\.txt)
#RewriteRule ^(.*)$ /index.php/$1 [L]

<IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteBase /

        # Removes index.php from ExpressionEngine URLs
        RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
        RewriteCond %{REQUEST_URI} !/system/.* [NC]
        RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]

        # Directs all EE web requests through the site index file
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

How do I get the title of the current active window using c#?

Use the Windows API. Call GetForegroundWindow().

GetForegroundWindow() will give you a handle (named hWnd) to the active window.

Documentation: GetForegroundWindow function | Microsoft Docs

Getting execute permission to xp_cmdshell

To expand on what has been provided for automatically exporting data as csv to a network share via SQL Server Agent.

(1) Enable the xp_cmdshell procedure:

-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO

-- Enable the xp_cmdshell procedure
EXEC sp_configure 'xp_cmdshell', 1
RECONFIGURE
GO

(2) Create a login 'Domain\TestUser' (windows user) for the non-sysadmin user that has public access to the master database. Done through user mapping

(3) Give log on as batch job: Navigate to Local Security Policy -> Local Policies -> User Rights Assignment. Add user to "Log on as a batch job"

(4) Give read/write permissions to network folder for domain\user

(5) Grant EXEC permission on the xp_cmdshell stored procedure:

GRANT EXECUTE ON xp_cmdshell TO [Domain\TestUser]

(6) Create a proxy account that xp_cmdshell will be run under using sp_xp_cmdshell_proxy_account

EXEC sp_xp_cmdshell_proxy_account 'Domain\TestUser', 'password_for_domain_user'

(7) If the sp_xp_cmdshell_proxy_account command doesn't work, manually create it

create credential ##xp_cmdshell_proxy_account## with identity = 'Domain\DomainUser', secret = 'password'

(8) Enable SQL Server Agent. Open SQL Server Configuration Manager, navigate to SQL Server Services, enable SQL Server Agent.

(9) Create automated job. Open SSMS, select SQL Server Agent, then right-click jobs and click "New Job".

(10) Select "Owner" as your created user. Select "Steps", make "type" = T-SQL. Fill out command field similar to below. Set delimiter as ','

EXEC master..xp_cmdshell 'SQLCMD -q "select * from master" -o file.csv -s "," 

(11) Fill out schedules accordingly.

GridLayout (not GridView) how to stretch all children evenly

Here's an example

enter image description here

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".GridMenuActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#FFFFFF"
            android:orientation="vertical"
            android:weightSum="10">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="200dp"
                android:layout_weight="2"
                android:background="@drawable/oval_background">

                <ImageView
                    android:id="@+id/imageView6"
                    android:layout_width="75dp"
                    android:layout_height="75dp"
                    android:layout_centerInParent="true"
                    android:layout_margin="5dp"
                    app:srcCompat="@mipmap/dmm_logo" />

            </RelativeLayout>

            <GridLayout
                android:id="@+id/mainGrid"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="8"
                android:alignmentMode="alignBounds"
                android:columnCount="2"
                android:columnOrderPreserved="true"
                android:padding="5dp"
                android:rowCount="5">

                <androidx.cardview.widget.CardView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_row="0"
                    android:layout_rowWeight="1"
                    android:layout_column="0"
                    android:layout_columnWeight="1"
                    android:layout_gravity="fill"
                    android:layout_marginLeft="8dp"
                    android:layout_marginTop="8dp"
                    android:layout_marginRight="8dp"
                    android:layout_marginBottom="16dp"
                    android:clickable="true"
                    android:focusable="true"
                    android:foreground="?android:attr/selectableItemBackground"
                    app:cardCornerRadius="8dp"
                    app:cardElevation="3dp">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:layout_margin="16dp"
                        android:orientation="vertical">

                        <ImageView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center_horizontal"
                            android:src="@drawable/ic_dashboard" />

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="Dashboard"
                            android:textAlignment="center"
                            android:textColor="@color/colorPrimary"
                            android:textSize="16sp"
                            android:textStyle="bold" />

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center"
                            android:gravity="center"
                            android:text="Add Entry"
                            android:textSize="10sp" />

                    </LinearLayout>

                </androidx.cardview.widget.CardView>

                <androidx.cardview.widget.CardView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_row="0"
                    android:layout_rowWeight="1"
                    android:layout_column="1"
                    android:layout_columnWeight="1"
                    android:layout_gravity="fill"
                    android:layout_marginLeft="8dp"
                    android:layout_marginTop="8dp"
                    android:layout_marginRight="8dp"
                    android:layout_marginBottom="16dp"
                    android:clickable="true"
                    android:focusable="true"
                    android:foreground="?android:attr/selectableItemBackground"
                    app:cardCornerRadius="8dp"
                    app:cardElevation="3dp">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal|center_vertical"
                        android:layout_margin="16dp"
                        android:orientation="vertical">

                        <ImageView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center_horizontal"
                            android:src="@drawable/ic_sell" />

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center"
                            android:text="Sale Forecast"
                            android:textAlignment="center"
                            android:textColor="@color/colorPrimary"
                            android:textSize="16sp"
                            android:textStyle="bold" />

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center"
                            android:gravity="center"
                            android:text="Upcoming Milk Requirement"
                            android:textSize="10sp" />

                    </LinearLayout>

                </androidx.cardview.widget.CardView>

                <androidx.cardview.widget.CardView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_row="1"
                    android:layout_rowWeight="1"
                    android:layout_column="0"
                    android:layout_columnWeight="1"
                    android:layout_gravity="fill"
                    android:layout_marginLeft="8dp"
                    android:layout_marginRight="8dp"
                    android:layout_marginBottom="16dp"
                    android:clickable="true"
                    android:focusable="true"
                    android:foreground="?android:attr/selectableItemBackground"
                    app:cardCornerRadius="8dp"
                    app:cardElevation="3dp">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal|center_vertical"
                        android:layout_margin="16dp"
                        android:orientation="vertical">

                        <ImageView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center_horizontal"
                            android:src="@drawable/ic_seller" />

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center"
                            android:text="Sellers"
                            android:textAlignment="center"
                            android:textColor="@color/colorPrimary"
                            android:textSize="16sp"
                            android:textStyle="bold" />

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center"
                            android:gravity="center"
                            android:text="Milk Providers"
                            android:textSize="10sp" />

                    </LinearLayout>

                </androidx.cardview.widget.CardView>

                <androidx.cardview.widget.CardView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_row="1"
                    android:layout_rowWeight="1"
                    android:layout_column="1"
                    android:layout_columnWeight="1"
                    android:layout_gravity="fill"
                    android:layout_marginLeft="8dp"
                    android:layout_marginRight="8dp"
                    android:layout_marginBottom="16dp"
                    android:clickable="true"
                    android:focusable="true"
                    android:foreground="?android:attr/selectableItemBackground"
                    app:cardCornerRadius="8dp"
                    app:cardElevation="3dp">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal|center_vertical"
                        android:layout_margin="16dp"
                        android:orientation="vertical">

                        <ImageView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center_horizontal"
                            android:src="@drawable/ic_shopping" />

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center"
                            android:text="Purchasers"
                            android:textColor="@color/colorPrimary"
                            android:textSize="16sp"
                            android:textStyle="bold" />

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center"
                            android:text="Milk Consumers"
                            android:textSize="10sp" />

                    </LinearLayout>

                </androidx.cardview.widget.CardView>


                <!-- Row 2 -->

                <!-- Column 1 -->
                <androidx.cardview.widget.CardView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_row="2"
                    android:layout_rowWeight="1"
                    android:layout_column="0"
                    android:layout_columnWeight="1"
                    android:layout_gravity="fill"
                    android:layout_marginLeft="8dp"
                    android:layout_marginRight="8dp"
                    android:layout_marginBottom="16dp"
                    android:clickable="true"
                    android:focusable="true"
                    android:foreground="?android:attr/selectableItemBackground"
                    app:cardCornerRadius="8dp"
                    app:cardElevation="3dp">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal|center_vertical"
                        android:layout_margin="16dp"
                        android:orientation="vertical">

                        <ImageView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center_horizontal"
                            android:src="@drawable/ic_advance" />

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center"
                            android:text="Advance"
                            android:textColor="@color/colorPrimary"
                            android:textSize="16sp"
                            android:textStyle="bold" />

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center"
                            android:text="Advance Payments"
                            android:textSize="10sp" />

                    </LinearLayout>

                </androidx.cardview.widget.CardView>

                <!-- Column 2 -->
                <androidx.cardview.widget.CardView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_row="2"
                    android:layout_rowWeight="1"
                    android:layout_column="1"
                    android:layout_columnWeight="1"
                    android:layout_gravity="fill"
                    android:layout_marginLeft="8dp"
                    android:layout_marginRight="8dp"
                    android:layout_marginBottom="16dp"
                    android:clickable="true"
                    android:focusable="true"
                    android:foreground="?android:attr/selectableItemBackground"
                    app:cardCornerRadius="8dp"
                    app:cardElevation="3dp">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal|center_vertical"
                        android:layout_margin="16dp"
                        android:orientation="vertical">

                        <ImageView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center_horizontal"
                            android:src="@drawable/ic_reciever" />

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center"
                            android:text="Due"
                            android:textColor="@color/colorPrimary"
                            android:textSize="16sp"
                            android:textStyle="bold" />

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center"
                            android:text="Pending Payments"
                            android:textSize="10sp" />

                    </LinearLayout>

                </androidx.cardview.widget.CardView>

                <androidx.cardview.widget.CardView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_row="3"
                    android:layout_rowWeight="1"
                    android:layout_column="0"
                    android:layout_columnWeight="1"
                    android:layout_gravity="fill"
                    android:layout_marginLeft="8dp"
                    android:layout_marginRight="8dp"
                    android:layout_marginBottom="16dp"
                    android:clickable="true"
                    android:focusable="true"
                    android:foreground="?android:attr/selectableItemBackground"
                    app:cardCornerRadius="8dp"
                    app:cardElevation="3dp">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal|center_vertical"
                        android:layout_margin="16dp"
                        android:orientation="vertical">

                        <ImageView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center_horizontal"
                            android:src="@drawable/ic_transaction" />

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="Transactions"
                            android:layout_gravity="center"
                            android:textColor="@color/colorPrimary"
                            android:textSize="16sp"
                            android:textStyle="bold" />

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center"
                            android:text="Payments Detalis"
                            android:textSize="10sp" />

                    </LinearLayout>

                </androidx.cardview.widget.CardView>

                <androidx.cardview.widget.CardView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_row="3"
                    android:layout_rowWeight="1"
                    android:layout_column="1"
                    android:layout_columnWeight="1"
                    android:layout_gravity="fill"
                    android:layout_marginLeft="8dp"
                    android:layout_marginRight="8dp"
                    android:layout_marginBottom="16dp"
                    android:clickable="true"
                    android:focusable="true"
                    android:foreground="?android:attr/selectableItemBackground"
                    app:cardCornerRadius="8dp"
                    app:cardElevation="3dp">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal|center_vertical"
                        android:layout_margin="16dp"
                        android:orientation="vertical">

                        <ImageView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center_horizontal"
                            android:src="@drawable/ic_sell" />

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="Sell Product"
                            android:layout_gravity="center"
                            android:textColor="@color/colorPrimary"
                            android:textSize="16sp"
                            android:textStyle="bold" />

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center"
                            android:text="Ghee, Curd etc."
                            android:textSize="10sp" />

                    </LinearLayout>

                </androidx.cardview.widget.CardView>

                <androidx.cardview.widget.CardView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_row="4"
                    android:layout_rowWeight="1"
                    android:layout_column="0"
                    android:layout_columnWeight="1"
                    android:layout_gravity="fill"
                    android:layout_marginLeft="8dp"
                    android:layout_marginRight="8dp"
                    android:layout_marginBottom="16dp"
                    android:clickable="true"
                    android:focusable="true"
                    android:foreground="?android:attr/selectableItemBackground"
                    app:cardCornerRadius="8dp"
                    app:cardElevation="3dp">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal|center_vertical"
                        android:layout_margin="16dp"
                        android:orientation="vertical">

                        <ImageView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center_horizontal"
                            android:src="@drawable/ic_purchase_report" />

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="Purchases"
                            android:layout_gravity="center"
                            android:textColor="@color/colorPrimary"
                            android:textSize="16sp"
                            android:textStyle="bold" />

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center"
                            android:text="Milk Purchase Entries"
                            android:textSize="10sp" />

                    </LinearLayout>

                </androidx.cardview.widget.CardView>

                <androidx.cardview.widget.CardView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_row="4"
                    android:layout_rowWeight="1"
                    android:layout_column="1"
                    android:layout_columnWeight="1"
                    android:layout_gravity="fill"
                    android:layout_marginLeft="8dp"
                    android:layout_marginRight="8dp"
                    android:layout_marginBottom="16dp"
                    android:clickable="true"
                    android:focusable="true"
                    android:foreground="?android:attr/selectableItemBackground"
                    app:cardCornerRadius="8dp"
                    app:cardElevation="3dp">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal|center_vertical"
                        android:layout_margin="16dp"
                        android:orientation="vertical">

                        <ImageView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center_horizontal"
                            android:src="@drawable/ic_sale_report" />

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="Sales"
                            android:layout_gravity="center"
                            android:textColor="@color/colorPrimary"
                            android:textSize="16sp"
                            android:textStyle="bold" />

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center"
                            android:text="Milk Sale Entries"
                            android:textSize="10sp" />

                    </LinearLayout>

                </androidx.cardview.widget.CardView>

            </GridLayout>

        </LinearLayout>

    </ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>

Perfect for me. I hope it helps you too

How to Diff between local uncommitted changes and origin

If you want to compare files visually you can use:

git difftool

It will start your diff app automatically for each changed file.

PS: If you did not set a diff app, you can do it like in the example below(I use Winmerge):

git config --global merge.tool winmerge
git config --replace --global mergetool.winmerge.cmd "\"C:\Program Files (x86)\WinMerge\WinMergeU.exe\" -e -u -dl \"Base\" -dr \"Mine\" \"$LOCAL\" \"$REMOTE\" \"$MERGED\""
git config --global mergetool.prompt false

Java Inheritance - calling superclass method

You can do:

super.alphaMethod1();

Note, that super is a reference to the parent, but super() is it's constructor.

Way to create multiline comments in Bash?

I tried the chosen answer, but found when I ran a shell script having it, the whole thing was getting printed to screen (similar to how jupyter notebooks print out everything in '''xx''' quotes) and there was an error message at end. It wasn't doing anything, but: scary. Then I realised while editing it that single-quotes can span multiple lines. So.. lets just assign the block to a variable.

x='
echo "these lines will all become comments."
echo "just make sure you don_t use single-quotes!"

ls -l
date

'

How to grant remote access to MySQL for a whole subnet?

Motivated by @Malvineaus answer I tried it myself and noticed that it didn't work for me.

You can specify subnet masks with '192.168.1.%' or '192.168.1.0/255.255.255.0' but the subnet must always be on complete octets. see https://mariadb.com/kb/en/create-user/#host-name-component. As result the functionality between one way of specification and the other is the same.

For example '192.168.1.0/255.255.255.128' will not work as it is not on a complete octet boundary.

how to check if string contains '+' character

[+]is simpler

    String s = "ddjdjdj+kfkfkf";

    if(s.contains ("+"))
    {
        String parts[] = s.split("[+]");
        s =  parts[0]; // i want to strip part after  +
    }
    System.out.println(s);

Is there a way to cast float as a decimal without rounding and preserving its precision?

cast (field1 as decimal(53,8)
) field 1

The default is: decimal(18,0)

How to include !important in jquery

It is also possible to add more important properties:

inputObj.attr('style', 'color:black !important; background-color:#428bca !important;');

How to check if an object is defined?

If a class type is not defined, you'll get a compiler error if you try to use the class, so in that sense you should have to check.

If you have an instance, and you want to ensure it's not null, simply check for null:

if (value != null)
{
    // it's not null. 
}