Programs & Examples On #Search multiple words

How to view the SQL queries issued by JPA?

If you are using Spring framework. Modify your application.properties file as below

#Logging JPA Queries, 1st line Log Query. 2nd line Log parameters of prepared statements 
logging.level.org.hibernate.SQL=DEBUG  
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE  

#Logging JdbcTemplate Queries, 1st line Log Query. 2nd line Log parameters of prepared statements 
logging.level.org.springframework.jdbc.core.JdbcTemplate=DEBUG  
logging.level.org.springframework.jdbc.core.StatementCreatorUtils=TRACE  

Remove privileges from MySQL database

As a side note, the reason revoke usage on *.* from 'phpmyadmin'@'localhost'; does not work is quite simple : There is no grant called USAGE.

The actual named grants are in the MySQL Documentation

The grant USAGE is a logical grant. How? 'phpmyadmin'@'localhost' has an entry in mysql.user where user='phpmyadmin' and host='localhost'. Any row in mysql.user semantically means USAGE. Running DROP USER 'phpmyadmin'@'localhost'; should work just fine. Under the hood, it's really doing this:

DELETE FROM mysql.user WHERE user='phpmyadmin' and host='localhost';
DELETE FROM mysql.db   WHERE user='phpmyadmin' and host='localhost';
FLUSH PRIVILEGES;

Therefore, the removal of a row from mysql.user constitutes running REVOKE USAGE, even though REVOKE USAGE cannot literally be executed.

Deleting Elements in an Array if Element is a Certain value VBA

An array is a structure with a certain size. You can use dynamic arrays in vba that you can shrink or grow using ReDim but you can't remove elements in the middle. It's not clear from your sample how your array functionally works or how you determine the index position (eachHdr) but you basically have 3 options

(A) Write a custom 'delete' function for your array like (untested)

Public Sub DeleteElementAt(Byval index As Integer, Byref prLst as Variant)
       Dim i As Integer

        ' Move all element back one position
        For i = index + 1 To UBound(prLst)
            prLst(i - 1) = prLst(i)
        Next

        ' Shrink the array by one, removing the last one
        ReDim Preserve prLst(Len(prLst) - 1)
End Sub

(B) Simply set a 'dummy' value as the value instead of actually deleting the element

If prLst(eachHdr) = "0" Then        
   prLst(eachHdr) = "n/a"
End If

(C) Stop using an array and change it into a VBA.Collection. A collection is a (unique)key/value pair structure where you can freely add or delete elements from

Dim prLst As New Collection

Replacing H1 text with a logo image: best method for SEO and accessibility?

A new (Keller) method is supposed to improve speed over the -9999px method:

.hide-text {
text-indent: 100%;
white-space: nowrap;
overflow: hidden;
}

recommended here:http://www.zeldman.com/2012/03/01/replacing-the-9999px-hack-new-image-replacement/

Change Git repository directory location.

I use Github Desktop for Windows and I wanted to move location of a repository. No problem if you move your directory and choose the new location in the software. But if you set a bad directory, you get a fatal error and no second chance to make a relocation to the good one. So to repair that. You must copy project files in the bad directory, make its reconize by Github Desktop, after that, you can move again your project in another folder and make a relocate in the software. No need to close Github Desktop for that, it will check folders in live.

Hoping this will help someone.

C# Select elements in list as List of string

List<string> empnames = (from e in emplist select e.Enaame).ToList();

Or

string[] empnames = (from e in emplist select e.Enaame).ToArray();

Etc...

Calling remove in foreach loop in Java

It's better to use an Iterator when you want to remove element from a list

because the source code of remove is

if (numMoved > 0)
    System.arraycopy(elementData, index+1, elementData, index,
             numMoved);
elementData[--size] = null;

so ,if you remove an element from the list, the list will be restructure ,the other element's index will be changed, this can result something that you want to happened.

Can I redirect the stdout in python into some sort of string buffer?

There is contextlib.redirect_stdout() function in Python 3.4:

import io
from contextlib import redirect_stdout

with io.StringIO() as buf, redirect_stdout(buf):
    print('redirected')
    output = buf.getvalue()

Here's code example that shows how to implement it on older Python versions.

How do I print out the contents of a vector?

This answer is based on the answer from Zorawar, but I couldn't leave a comment there.

You can make the auto (C++11)/typedef version const by using cbegin and cend instead

for (auto i = path.cbegin(); i != path.cend(); ++i)
    std::cout << *i << ' ';

How to POST form data with Spring RestTemplate?

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

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

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

import com.ituple.common.dto.ServiceResponse;

   public class PostRequestMain {

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

        headers.setAll(map);

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

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

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

}

Windows path in Python

In case you'd like to paste windows path from other source (say, File Explorer) - you can do so via input() call in python console:

>>> input()
D:\EP\stuff\1111\this_is_a_long_path\you_dont_want\to_type\or_edit_by_hand
'D:\\EP\\stuff\\1111\\this_is_a_long_path\\you_dont_want\\to_type\\or_edit_by_hand'

Then just copy the result

How to check if a scope variable is undefined in AngularJS template?

<p ng-show="angular.isUndefined(foo)">Show this if $scope.foo === undefined</p>

How to fix apt-get: command not found on AWS EC2?

I guess you are actually using Amazon Linux AMI 2013.03.1 instead of Ubuntu Server 12.x reason why you don't have apt-get tool installed.

Java - Check if JTextField is empty or not

The following will return true if the JTextField "name" does not contain text:

name.getText().isEmpty

Find and Replace string in all files recursive using grep and sed

sed expression needs to be quoted

sed -i "s/$oldstring/$newstring/g"

Does Java have a complete enum for HTTP response codes?

Another option is to use HttpStatus class from the Apache commons-httpclient which provides you the various Http statuses as constants.

How to get the difference between two dictionaries in Python?

You were right to look at using a set, we just need to dig in a little deeper to get your method to work.

First, the example code:

test_1 = {"foo": "bar", "FOO": "BAR"}
test_2 = {"foo": "bar", "f00": "b@r"}

We can see right now that both dictionaries contain a similar key/value pair:

{"foo": "bar", ...}

Each dictionary also contains a completely different key value pair. But how do we detect the difference? Dictionaries don't support that. Instead, you'll want to use a set.

Here is how to turn each dictionary into a set we can use:

set_1 = set(test_1.items())
set_2 = set(test_2.items())

This returns a set containing a series of tuples. Each tuple represents one key/value pair from your dictionary.

Now, to find the difference between set_1 and set_2:

print set_1 - set_2
>>> {('FOO', 'BAR')}

Want a dictionary back? Easy, just:

dict(set_1 - set_2)
>>> {'FOO': 'BAR'}

C/C++ Struct vs Class

C++ uses structs primarily for 1) backwards compatibility with C and 2) POD types. C structs do not have methods, inheritance or visibility.

How to add minutes to my Date

you can use DateUtils class in org.apache.commons.lang3.time package

int addMinuteTime = 5;
Date targetTime = new Date(); //now
targetTime = DateUtils.addMinutes(targetTime, addMinuteTime); //add minute

Calling a function from a string in C#

Yes. You can use reflection. Something like this:

Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);

How can I get the current date and time in the terminal and set a custom command in the terminal for it?

You can use date to get time and date of a day:

[pengyu@GLaDOS ~]$date
Tue Aug 27 15:01:27 CST 2013

Also hwclock would do:

[pengyu@GLaDOS ~]$hwclock
Tue 27 Aug 2013 03:01:29 PM CST  -0.516080 seconds

For customized output, you can either redirect the output of date to something like awk, or write your own program to do that.

Remember to put your own executable scripts/binary into your PATH (e.g. /usr/bin) to make it invokable anywhere.

Cleanest way to write retry logic?

Allowing for functions and retry messages

public static T RetryMethod<T>(Func<T> method, int numRetries, int retryTimeout, Action onFailureAction)
{
 Guard.IsNotNull(method, "method");            
 T retval = default(T);
 do
 {
   try
   {
     retval = method();
     return retval;
   }
   catch
   {
     onFailureAction();
      if (numRetries <= 0) throw; // improved to avoid silent failure
      Thread.Sleep(retryTimeout);
   }
} while (numRetries-- > 0);
  return retval;
}

How to remove border of drop down list : CSS

You could simply use:

select {
    border: none;
    outline: none;
    scroll-behavior: smooth;
}

As the drop down list border is non editable you can not do anything with that but surely this will fix your initial outlook.

configure Git to accept a particular self-signed server certificate for a particular https remote

Briefly:

  1. Get the self signed certificate
  2. Put it into some (e.g. ~/git-certs/cert.pem) file
  3. Set git to trust this certificate using http.sslCAInfo parameter

In more details:

Get self signed certificate of remote server

Assuming, the server URL is repos.sample.com and you want to access it over port 443.

There are multiple options, how to get it.

Get certificate using openssl

$ openssl s_client -connect repos.sample.com:443

Catch the output into a file cert.pem and delete all but part between (and including) -BEGIN CERTIFICATE- and -END CERTIFICATE-

Content of resulting file ~/git-certs/cert.pem may look like this:

-----BEGIN CERTIFICATE-----
MIIDnzCCAocCBE/xnXAwDQYJKoZIhvcNAQEFBQAwgZMxCzAJBgNVBAYTAkRFMRUw
EwYDVQQIEwxMb3dlciBTYXhvbnkxEjAQBgNVBAcTCVdvbGZzYnVyZzEYMBYGA1UE
ChMPU2FhUy1TZWN1cmUuY29tMRowGAYDVQQDFBEqLnNhYXMtc2VjdXJlLmNvbTEj
MCEGCSqGSIb3DQEJARYUaW5mb0BzYWFzLXNlY3VyZS5jb20wHhcNMTIwNzAyMTMw
OTA0WhcNMTMwNzAyMTMwOTA0WjCBkzELMAkGA1UEBhMCREUxFTATBgNVBAgTDExv
d2VyIFNheG9ueTESMBAGA1UEBxMJV29sZnNidXJnMRgwFgYDVQQKEw9TYWFTLVNl
Y3VyZS5jb20xGjAYBgNVBAMUESouc2Fhcy1zZWN1cmUuY29tMSMwIQYJKoZIhvcN
AQkBFhRpbmZvQHNhYXMtc2VjdXJlLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEP
ADCCAQoCggEBAMUZ472W3EVFYGSHTgFV0LR2YVE1U//sZimhCKGFBhH3ZfGwqtu7
mzOhlCQef9nqGxgH+U5DG43B6MxDzhoP7R8e1GLbNH3xVqMHqEdcek8jtiJvfj2a
pRSkFTCVJ9i0GYFOQfQYV6RJ4vAunQioiw07OmsxL6C5l3K/r+qJTlStpPK5dv4z
Sy+jmAcQMaIcWv8wgBAxdzo8UVwIL63gLlBz7WfSB2Ti5XBbse/83wyNa5bPJPf1
U+7uLSofz+dehHtgtKfHD8XpPoQBt0Y9ExbLN1ysdR9XfsNfBI5K6Uokq/tVDxNi
SHM4/7uKNo/4b7OP24hvCeXW8oRyRzpyDxMCAwEAATANBgkqhkiG9w0BAQUFAAOC
AQEAp7S/E1ZGCey5Oyn3qwP4q+geQqOhRtaPqdH6ABnqUYHcGYB77GcStQxnqnOZ
MJwIaIZqlz+59taB6U2lG30u3cZ1FITuz+fWXdfELKPWPjDoHkwumkz3zcCVrrtI
ktRzk7AeazHcLEwkUjB5Rm75N9+dOo6Ay89JCcPKb+tNqOszY10y6U3kX3uiSzrJ
ejSq/tRyvMFT1FlJ8tKoZBWbkThevMhx7jk5qsoCpLPmPoYCEoLEtpMYiQnDZgUc
TNoL1GjoDrjgmSen4QN5QZEGTOe/dsv1sGxWC+Tv/VwUl2GqVtKPZdKtGFqI8TLn
/27/jIdVQIKvHok2P/u9tvTUQA==
-----END CERTIFICATE-----

Get certificate using your web browser

I use Redmine with Git repositories and I access the same URL for web UI and for git command line access. This way, I had to add exception for that domain into my web browser.

Using Firefox, I went to Options -> Advanced -> Certificates -> View Certificates -> Servers, found there the selfsigned host, selected it and using Export button I got exactly the same file, as created using openssl.

Note: I was a bit surprised, there is no name of the authority visibly mentioned. This is fine.

Having the trusted certificate in dedicated file

Previous steps shall result in having the certificate in some file. It does not matter, what file it is as long as it is visible to your git when accessing that domain. I used ~/git-certs/cert.pem

Note: If you need more trusted selfsigned certificates, put them into the same file:

-----BEGIN CERTIFICATE-----
MIIDnzCCAocCBE/xnXAwDQYJKoZIhvcNAQEFBQAwgZMxCzAJBgNVBAYTAkRFMRUw
...........
/27/jIdVQIKvHok2P/u9tvTUQA==
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
AnOtHeRtRuStEdCeRtIfIcAtEgOeShErExxxxxxxxxxxxxxxxxxxxxxxxxxxxxxw
...........
/27/jIdVQIKvHok2P/u9tvTUQA==
-----END CERTIFICATE-----

This shall work (but I tested it only with single certificate).

Configure git to trust this certificate

$ git config --global http.sslCAInfo /home/javl/git-certs/cert.pem

You may also try to do that system wide, using --system instead of --global.

And test it: You shall now be able communicating with your server without resorting to:

$ git config --global http.sslVerify false #NO NEED TO USE THIS

If you already set your git to ignorance of ssl certificates, unset it:

$ git config --global --unset http.sslVerify

and you may also check, that you did it all correctly, without spelling errors:

$ git config --global --list

what should list all variables, you have set globally. (I mispelled http to htt).

Fastest way to Remove Duplicate Value from a list<> by lambda

You can use this extension method for enumerables containing more complex types:

IEnumerable<Foo> distinctList = sourceList.DistinctBy(x => x.FooName);

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector)
{
    var knownKeys = new HashSet<TKey>();
    return source.Where(element => knownKeys.Add(keySelector(element)));
}

AssertionError: View function mapping is overwriting an existing endpoint function: main

There is a fix for Flask issue #570 introduced recenty (flask 0.10) that causes this exception to be raised.

See https://github.com/mitsuhiko/flask/issues/796

So if you go to flask/app.py and comment out the 4 lines 948..951, this may help until the issue is resovled fully in a new version.

The diff of that change is here: http://github.com/mitsuhiko/flask/commit/661ee54bc2bc1ea0763ac9c226f8e14bb0beb5b1

Is this a good way to clone an object in ES6?

You can do it like this as well,

let copiedData = JSON.parse(JSON.stringify(data));

json Uncaught SyntaxError: Unexpected token :

I have spent the last few days trying to figure this out myself. Using the old json dataType gives you cross origin problems, while setting the dataType to jsonp makes the data "unreadable" as explained above. So there are apparently two ways out, the first hasn't worked for me but seems like a potential solution and that I might be doing something wrong. This is explained here [ https://learn.jquery.com/ajax/working-with-jsonp/ ].

The one that worked for me is as follows: 1- download the ajax cross origin plug in [ http://www.ajax-cross-origin.com/ ]. 2- add a script link to it just below the normal jQuery link. 3- add the line "crossOrigin: true," to your ajax function.

Good to go! here is my working code for this:

_x000D_
_x000D_
  $.ajax({_x000D_
      crossOrigin: true,_x000D_
      url : "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.86,151.195&radius=5000&type=ATM&keyword=ATM&key=MyKey",_x000D_
      type : "GET",_x000D_
      success:function(data){_x000D_
         console.log(data);_x000D_
      }_x000D_
    })
_x000D_
_x000D_
_x000D_

How can I make a button have a rounded border in Swift?

This class is based from all the comments and suggestions in answers, and also can be designable directly from xcode. Copy to your project and insert any UIButton and change to use custom class, now just select border or background color from xcode for normal and/or highlighted states.

//
//  RoundedButton.swift
//

import UIKit

@IBDesignable
class RoundedButton:UIButton {

    @IBInspectable var borderWidth: CGFloat = 0 {
        didSet {
            layer.borderWidth = borderWidth
        }
    }
    //Normal state bg and border
    @IBInspectable var normalBorderColor: UIColor? {
        didSet {
            layer.borderColor = normalBorderColor?.CGColor
        }
    }

    @IBInspectable var normalBackgroundColor: UIColor? {
        didSet {
            setBgColorForState(normalBackgroundColor, forState: .Normal)
        }
    }


    //Highlighted state bg and border
    @IBInspectable var highlightedBorderColor: UIColor?

    @IBInspectable var highlightedBackgroundColor: UIColor? {
        didSet {
            setBgColorForState(highlightedBackgroundColor, forState: .Highlighted)
        }
    }


    private func setBgColorForState(color: UIColor?, forState: UIControlState){
        if color != nil {
            setBackgroundImage(UIImage.imageWithColor(color!), forState: forState)

        } else {
            setBackgroundImage(nil, forState: forState)
        }
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        layer.cornerRadius = layer.frame.height / 2
        clipsToBounds = true

        if borderWidth > 0 {
            if state == .Normal && !CGColorEqualToColor(layer.borderColor, normalBorderColor?.CGColor) {
                layer.borderColor = normalBorderColor?.CGColor
            } else if state == .Highlighted && highlightedBorderColor != nil{
                layer.borderColor = highlightedBorderColor!.CGColor
            }
        }
    }

}

//Extension Required by RoundedButton to create UIImage from UIColor
extension UIImage {
    class func imageWithColor(color: UIColor) -> UIImage {
        let rect: CGRect = CGRectMake(0, 0, 1, 1)
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(1, 1), false, 1.0)
        color.setFill()
        UIRectFill(rect)
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

How do you plot bar charts in gnuplot?

plot "data.dat" using 2: xtic(1) with histogram

Here data.dat contains data of the form

title 1
title2 3
"long title" 5

Getting the current date in visual Basic 2008

Try this:

Dim regDate as Date = Date.Now()
Dim strDate as String = regDate.ToString("ddMMMyyyy")

strDate will look like so: 07Feb2012

SQL Server: Best way to concatenate multiple columns?

SELECT CONCAT(LOWER(LAST_NAME), UPPER(LAST_NAME)
       INITCAP(LAST_NAME), HIRE DATE AS ‘up_low_init_hdate’)
FROM EMPLOYEES
WHERE HIRE DATE = 1995

How to create a readonly textbox in ASP.NET MVC3 Razor

@Html.TextBoxFor(model => model.IsActive, new { readonly= "readonly" })

This is just fine for text box. However, if you try to do same for the checkbox then try using this if you are using it:

@Html.CheckBoxFor(model => model.IsActive, new { onclick = "return false" })

But don't use disable, because disable always sends the default value false to the server - either it was in the checked or unchecked state. And the readonly does not work for checkbox and radio button. readonly only works for text fields.

Create a OpenSSL certificate on Windows

If you're on windows and using apache, maybe via WAMP or the Drupal stack installer, you can additionally download the git for windows package, which includes many useful linux command line tools, one of which is openssl.

The following command creates the self signed certificate and key needed for apache and works fine in windows:

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout privatekey.key -out certificate.crt

CMake error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found

This works for me in Ubuntu 17.10 (Artful Aardvark):

apt-get update
apt-get install build-essential

How to remove specific object from ArrayList in Java?

This helped me:

        card temperaryCardFour = theDeck.get(theDeck.size() - 1);
        theDeck.remove(temperaryCardFour);    

instead of

theDeck.remove(numberNeededRemoved);

I got a removal conformation on the first snippet of code and an un removal conformation on the second.

Try switching your code with the first snippet I think that is your problem.

Nathan Nelson

import sun.misc.BASE64Encoder results in error compiled in Eclipse

I know this is very Old post. Since we don't have any thing sun.misc in maven we can easily use

StringUtils.newStringUtf8(Base64.encodeBase64(encVal)); From org.apache.commons.codec.binary.Base64

How do I use arrays in C++?

Array creation and initialization

As with any other kind of C++ object, arrays can be stored either directly in named variables (then the size must be a compile-time constant; C++ does not support VLAs), or they can be stored anonymously on the heap and accessed indirectly via pointers (only then can the size be computed at runtime).

Automatic arrays

Automatic arrays (arrays living "on the stack") are created each time the flow of control passes through the definition of a non-static local array variable:

void foo()
{
    int automatic_array[8];
}

Initialization is performed in ascending order. Note that the initial values depend on the element type T:

  • If T is a POD (like int in the above example), no initialization takes place.
  • Otherwise, the default-constructor of T initializes all the elements.
  • If T provides no accessible default-constructor, the program does not compile.

Alternatively, the initial values can be explicitly specified in the array initializer, a comma-separated list surrounded by curly brackets:

    int primes[8] = {2, 3, 5, 7, 11, 13, 17, 19};

Since in this case the number of elements in the array initializer is equal to the size of the array, specifying the size manually is redundant. It can automatically be deduced by the compiler:

    int primes[] = {2, 3, 5, 7, 11, 13, 17, 19};   // size 8 is deduced

It is also possible to specify the size and provide a shorter array initializer:

    int fibonacci[50] = {0, 1, 1};   // 47 trailing zeros are deduced

In that case, the remaining elements are zero-initialized. Note that C++ allows an empty array initializer (all elements are zero-initialized), whereas C89 does not (at least one value is required). Also note that array initializers can only be used to initialize arrays; they cannot later be used in assignments.

Static arrays

Static arrays (arrays living "in the data segment") are local array variables defined with the static keyword and array variables at namespace scope ("global variables"):

int global_static_array[8];

void foo()
{
    static int local_static_array[8];
}

(Note that variables at namespace scope are implicitly static. Adding the static keyword to their definition has a completely different, deprecated meaning.)

Here is how static arrays behave differently from automatic arrays:

  • Static arrays without an array initializer are zero-initialized prior to any further potential initialization.
  • Static POD arrays are initialized exactly once, and the initial values are typically baked into the executable, in which case there is no initialization cost at runtime. This is not always the most space-efficient solution, however, and it is not required by the standard.
  • Static non-POD arrays are initialized the first time the flow of control passes through their definition. In the case of local static arrays, that may never happen if the function is never called.

(None of the above is specific to arrays. These rules apply equally well to other kinds of static objects.)

Array data members

Array data members are created when their owning object is created. Unfortunately, C++03 provides no means to initialize arrays in the member initializer list, so initialization must be faked with assignments:

class Foo
{
    int primes[8];

public:

    Foo()
    {
        primes[0] = 2;
        primes[1] = 3;
        primes[2] = 5;
        // ...
    }
};

Alternatively, you can define an automatic array in the constructor body and copy the elements over:

class Foo
{
    int primes[8];

public:

    Foo()
    {
        int local_array[] = {2, 3, 5, 7, 11, 13, 17, 19};
        std::copy(local_array + 0, local_array + 8, primes + 0);
    }
};

In C++0x, arrays can be initialized in the member initializer list thanks to uniform initialization:

class Foo
{
    int primes[8];

public:

    Foo() : primes { 2, 3, 5, 7, 11, 13, 17, 19 }
    {
    }
};

This is the only solution that works with element types that have no default constructor.

Dynamic arrays

Dynamic arrays have no names, hence the only means of accessing them is via pointers. Because they have no names, I will refer to them as "anonymous arrays" from now on.

In C, anonymous arrays are created via malloc and friends. In C++, anonymous arrays are created using the new T[size] syntax which returns a pointer to the first element of an anonymous array:

std::size_t size = compute_size_at_runtime();
int* p = new int[size];

The following ASCII art depicts the memory layout if the size is computed as 8 at runtime:

             +---+---+---+---+---+---+---+---+
(anonymous)  |   |   |   |   |   |   |   |   |
             +---+---+---+---+---+---+---+---+
               ^
               |
               |
             +-|-+
          p: | | |                               int*
             +---+

Obviously, anonymous arrays require more memory than named arrays due to the extra pointer that must be stored separately. (There is also some additional overhead on the free store.)

Note that there is no array-to-pointer decay going on here. Although evaluating new int[size] does in fact create an array of integers, the result of the expression new int[size] is already a pointer to a single integer (the first element), not an array of integers or a pointer to an array of integers of unknown size. That would be impossible, because the static type system requires array sizes to be compile-time constants. (Hence, I did not annotate the anonymous array with static type information in the picture.)

Concerning default values for elements, anonymous arrays behave similar to automatic arrays. Normally, anonymous POD arrays are not initialized, but there is a special syntax that triggers value-initialization:

int* p = new int[some_computed_size]();

(Note the trailing pair of parenthesis right before the semicolon.) Again, C++0x simplifies the rules and allows specifying initial values for anonymous arrays thanks to uniform initialization:

int* p = new int[8] { 2, 3, 5, 7, 11, 13, 17, 19 };

If you are done using an anonymous array, you have to release it back to the system:

delete[] p;

You must release each anonymous array exactly once and then never touch it again afterwards. Not releasing it at all results in a memory leak (or more generally, depending on the element type, a resource leak), and trying to release it multiple times results in undefined behavior. Using the non-array form delete (or free) instead of delete[] to release the array is also undefined behavior.

Mapping composite keys using EF code first

I thought I would add to this question as it is the top google search result.

As has been noted in the comments, in EF Core there is no support for using annotations (Key attribute) and it must be done with fluent.

As I was working on a large migration from EF6 to EF Core this was unsavoury and so I tried to hack it by using Reflection to look for the Key attribute and then apply it during OnModelCreating

// get all composite keys (entity decorated by more than 1 [Key] attribute
foreach (var entity in modelBuilder.Model.GetEntityTypes()
    .Where(t => 
        t.ClrType.GetProperties()
            .Count(p => p.CustomAttributes.Any(a => a.AttributeType == typeof(KeyAttribute))) > 1))
{
    // get the keys in the appropriate order
    var orderedKeys = entity.ClrType
        .GetProperties()
        .Where(p => p.CustomAttributes.Any(a => a.AttributeType == typeof(KeyAttribute)))
        .OrderBy(p => 
            p.CustomAttributes.Single(x => x.AttributeType == typeof(ColumnAttribute))?
                .NamedArguments?.Single(y => y.MemberName == nameof(ColumnAttribute.Order))
                .TypedValue.Value ?? 0)
        .Select(x => x.Name)
        .ToArray();

    // apply the keys to the model builder
    modelBuilder.Entity(entity.ClrType).HasKey(orderedKeys);
}

I haven't fully tested this in all situations, but it works in my basic tests. Hope this helps someone

How to get Activity's content view?

There is no "isContentViewSet" method. You may put some dummy requestWindowFeature call into try/catch block before setContentView like this:

try {
  requestWindowFeature(Window.FEATURE_CONTEXT_MENU);
  setContentView(...)
} catch (AndroidRuntimeException e) {
  // do smth or nothing
}

If content view was already set, requestWindowFeature will throw an exception.

Warp \ bend effect on a UIView?

What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.

I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)

Codeigniter's `where` and `or_where`

$this->db->where('(a = 1 or a = 2)');

Hive load CSV with commas in quoted fields

ORG.APACHE.HADOOP.HIVE.SERDE2.OPENCSVSERDE Serde worked for me. My delimiter was '|' and one of the columns is enclosed in double quotes.

Query:

CREATE EXTERNAL TABLE EMAIL(MESSAGE_ID STRING, TEXT STRING, TO_ADDRS STRING, FROM_ADDRS STRING, SUBJECT STRING, DATE STRING)
ROW FORMAT SERDE 'ORG.APACHE.HADOOP.HIVE.SERDE2.OPENCSVSERDE'
WITH SERDEPROPERTIES (
     "SEPARATORCHAR" = "|",
     "QUOTECHAR"     = "\"",
     "ESCAPECHAR"    = "\""
)    
STORED AS TEXTFILE location '/user/abc/csv_folder';

HttpWebRequest using Basic authentication

First thing, for me ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 worked instead of Ssl3.

Secondly, I had to send the Basic Auth request along with some data (form-urlencoded). Here is the complete sample which worked for me perfectly, after trying many solutions.

Disclaimer: The code below is a mixture of solutions found on this link and some other stackoverflow links, thanks for the useful information.

        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        String username = "user_name";
        String password = "password";
        String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));

        //Form Data
        var formData = "var1=val1&var2=val2";
        var encodedFormData = Encoding.ASCII.GetBytes(formData);

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("THE_URL");
        request.ContentType = "application/x-www-form-urlencoded";
        request.Method = "POST";
        request.ContentLength = encodedFormData.Length;
        request.Headers.Add("Authorization", "Basic " + encoded);
        request.PreAuthenticate = true;

        using (var stream = request.GetRequestStream())
        {
            stream.Write(encodedFormData, 0, encodedFormData.Length);
        }

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

Adjusting and image Size to fit a div (bootstrap)

Just a heads up that Bootstrap 4 now uses img-fluid instead of img-responsive, so double check which version you're using if you're having problems.

How to trigger event in JavaScript?

I searched for firing click, mousedown and mouseup event on mouseover using JavaScript. I found an answer provided by Juan Mendes. For the answer click here.

Click here is the live demo and below is the code:

function fireEvent(node, eventName) {
    // Make sure we use the ownerDocument from the provided node to avoid cross-window problems
    var doc;
    if (node.ownerDocument) {
        doc = node.ownerDocument;
    } else if (node.nodeType == 9) {
        // the node may be the document itself, nodeType 9 = DOCUMENT_NODE
        doc = node;
    } else {
        throw new Error("Invalid node passed to fireEvent: " + node.id);
    }

    if (node.dispatchEvent) {
        // Gecko-style approach (now the standard) takes more work
        var eventClass = "";

        // Different events have different event classes.
        // If this switch statement can't map an eventName to an eventClass,
        // the event firing is going to fail.
        switch (eventName) {
        case "click": // Dispatching of 'click' appears to not work correctly in Safari. Use 'mousedown' or 'mouseup' instead.
        case "mousedown":
        case "mouseup":
            eventClass = "MouseEvents";
            break;

        case "focus":
        case "change":
        case "blur":
        case "select":
            eventClass = "HTMLEvents";
            break;

        default:
            throw "fireEvent: Couldn't find an event class for event '" + eventName + "'.";
            break;
        }
        var event = doc.createEvent(eventClass);

        var bubbles = eventName == "change" ? false : true;
        event.initEvent(eventName, bubbles, true); // All events created as bubbling and cancelable.

        event.synthetic = true; // allow detection of synthetic events
        // The second parameter says go ahead with the default action
        node.dispatchEvent(event, true);
    } else if (node.fireEvent) {
        // IE-old school style
        var event = doc.createEventObject();
        event.synthetic = true; // allow detection of synthetic events
        node.fireEvent("on" + eventName, event);
    }
};

Remove an item from array using UnderscoreJS

Please exercise care if you are filtering strings and looking for case insensitive filters. _.without() is case sensitive. You can also use _.reject() as shown below.

var arr = ["test","test1","test2"];

var filtered = _.filter(arr, function(arrItem) {
    return arrItem.toLowerCase() !== "TEST".toLowerCase();
});
console.log(filtered);
// ["test1", "test2"]

var filtered1 = _.without(arr,"TEST");
console.log(filtered1);
// ["test", "test1", "test2"]

var filtered2 = _.reject(arr, function(arrItem){ 
    return arrItem.toLowerCase() === "TEST".toLowerCase();
});
console.log(filtered2);
// ["test1", "test2"]

Git reset single file in feature branch to be the same as in master

If you want to revert the file to its state in master:

git checkout origin/master [filename]

syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING

You have extra spaces after END; that cause the heredoc not terminated.

Convert character to Date in R

You may be overcomplicating things, is there any reason you need the stringr package?

 df <- data.frame(Date = c("10/9/2009 0:00:00", "10/15/2009 0:00:00"))
 as.Date(df$Date, "%m/%d/%Y %H:%M:%S")

[1] "2009-10-09" "2009-10-15"

More generally and if you need the time component as well, use strptime:

strptime(df$Date, "%m/%d/%Y %H:%M:%S")

I'm guessing at what your actual data might look at from the partial results you give.

Comparing two NumPy arrays for equality, element-wise

Usually two arrays will have some small numeric errors,

You can use numpy.allclose(A,B), instead of (A==B).all(). This returns a bool True/False

stdlib and colored output in C

#include <stdio.h>

#define BLUE(string) "\x1b[34m" string "\x1b[0m"
#define RED(string) "\x1b[31m" string "\x1b[0m"

int main(void)
{
    printf("this is " RED("red") "!\n");

    // a somewhat more complex ...
    printf("this is " BLUE("%s") "!\n","blue");

    return 0;
}

reading Wikipedia:

  • \x1b[0m resets all attributes
  • \x1b[31m sets foreground color to red
  • \x1b[44m would set the background to blue.
  • both : \x1b[31;44m
  • both but inversed : \x1b[31;44;7m
  • remember to reset afterwards \x1b[0m ...

How to set the env variable for PHP?

It depends on your OS, but if you are on Windows XP, you need to go to Systems Properties, then Advanced, then Environment Variables, and include the php binary path to the %PATH% variable.

Locate it by browsing your WAMP directory. It's called php.exe

How to set the first option on a select box using jQuery?

Here's how to handle it with a random option element defined as the default value (in this case Text 2 is the default):

<select id="name2" >
   <option value="">select all</option>
   <option value="1">Text 1</option>
   <option value="2" selected="selected">Text 2</option>
   <option value="3">Text 3</option>
</select>
<script>
    $('#name2 option[selected]').prop('selected', true);
</script>

Using TortoiseSVN via the command line

To use command support you should follow this steps:

  1. Define Path in Environment Variables:

    • open 'System Properties';
    • on the tab 'Advanced' click on the 'Environment Variables' button
    • in the section 'System variables' select 'Path' option and click 'edit'
    • append variable value with the path to TortoiseProc.exe file, for example:

      C:\Program Files\TortoiseSVN\bin

  2. Since you have registered TortoiseProc, you can use it in according to TortoiseSVN documentation.

    Examples:

    TortoiseProc.exe /command:commit /path:"c:\svn_wc\file1.txt*c:\svn_wc\file2.txt" /logmsg:"test log message" /closeonend:0

    TortoiseProc.exe /command:update /path:"c:\svn_wc\" /closeonend:0

    TortoiseProc.exe /command:log /path:"c:\svn_wc\file1.txt" /startrev:50 /endrev:60 /closeonend:0

P.S. To use friendly name like 'svn' instead of 'TortoiseProc', place 'svn.bat' file in the directory of 'TortoiseProc.exe'. There is an example of svn.bat:

TortoiseProc.exe %1 %2 %3

Java, looping through result set

The problem with your code is :

     String  show[]= {rs4.getString(1)};
     String actuate[]={rs4.getString(2)};

This will create a new array every time your loop (an not append as you might be assuming) and hence in the end you will have only one element per array.

Here is one more way to solve this :

    StringBuilder sids = new StringBuilder ();
    StringBuilder lids = new StringBuilder ();

    while (rs4.next()) {
        sids.append(rs4.getString(1)).append(" ");
        lids.append(rs4.getString(2)).append(" ");
    }

    String show[] = sids.toString().split(" "); 
    String actuate[] = lids.toString().split(" ");

These arrays will have all the required element.

Clear variable in python

What's wrong with self.left = None?

Jackson serialization: ignore empty values (or null)

You can also set the global option:

objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

How to check if an integer is within a range?

Most of the given examples assume that for the test range [$a..$b], $a <= $b, i.e. the range extremes are in lower - higher order and most assume that all are integer numbers.
But I needed a function to test if $n was between $a and $b, as described here:

Check if $n is between $a and $b even if:
    $a < $b  
    $a > $b
    $a = $b

All numbers can be real, not only integer.

There is an easy way to test.
I base the test it in the fact that ($n-$a) and ($n-$b) have different signs when $n is between $a and $b, and the same sign when $n is outside the $a..$b range.
This function is valid for testing increasing, decreasing, positive and negative numbers, not limited to test only integer numbers.

function between($n, $a, $b)
{
    return (($a==$n)&&($b==$n))? true : ($n-$a)*($n-$b)<0;
}

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

If you are using Sqlserver 2005 or above, using REVERSE function many times is detrimental to performance, below code is more efficient.

DECLARE @FilePath VARCHAR(50) = 'My\Super\Long\String\With\Long\Words'
DECLARE @FindChar VARCHAR(1) = '\'

-- Shows text before last slash
SELECT LEFT(@FilePath, LEN(@FilePath) - CHARINDEX(@FindChar,REVERSE(@FilePath))) AS Before
-- Shows text after last slash
SELECT RIGHT(@FilePath, CHARINDEX(@FindChar,REVERSE(@FilePath))-1) AS After
-- Shows the position of the last slash
SELECT LEN(@FilePath) - CHARINDEX(@FindChar,REVERSE(@FilePath)) AS LastOccuredAt

Get URL of ASP.Net Page in code-behind

Request.Url.GetLeftPart(UriPartial.Authority) + Request.FilePath + "?theme=blue";

that will give you the full path to the page you are sitting on. I added in the querystring.

How to return a value from __init__ in Python?

init() return none value solved perfectly

class Solve:
def __init__(self,w,d):
    self.value=w
    self.unit=d
def __str__(self):
    return str("my speed is "+str(self.value)+" "+str(self.unit))
ob=Solve(21,'kmh')
print (ob)

output: my speed is 21 kmh

Allow click on twitter bootstrap dropdown toggle link?

Since there is not really an answer that works (selected answer disables dropdown), or overrides using javascript, here goes.

This is all html and css fix (uses two <a> tags):

<ul class="nav">
 <li class="dropdown dropdown-li">
    <a class="dropdown-link" href="http://google.com">Dropdown</a>
    <a class="dropdown-caret dropdown-toggle"><b class="caret"></b></a>
    <ul class="dropdown-menu">
        <li><a href="#">Link 1</a></li>
        <li><a href="#">Link 2</a></li>
    </ul>
 </li>
</ul>

Now here's the CSS you need.

.dropdown-li {
    display:inline-block !important;
}
.dropdown-link {
    display:inline-block !important; 
    padding-right:4px !important;
}
.dropdown-caret {
    display:inline-block !important; 
    padding-left:4px !important;
}

Assuming you will want the both <a> tags to highlight on hover of either one, you will also need to override bootstrap, you might play around with the following:

.nav > li:hover {
    background-color: #f67a47; /*hover background color*/
}
.nav > li:hover > a {
    color: white; /*hover text color*/
}
.nav > li:hover > ul > a {
    color: black; /*dropdown item text color*/
}

Eclipse cannot load SWT libraries

In my case, I was missing the /usr/lib/jni directory entirely. Fixed by

sudo apt-get install libswt-gtk-3-jni libswt-gtk-3-java

No need to symlink afterwards. Eclipse started normally.

USB Debugging option greyed out

This worked for me:

  1. Changing USB connection to File Transfer
  2. Turn off developer options
  3. Turn it back on
  4. USB Debugging option came back to life

C# string replace

You need to escape the double-quotes inside the search string, like this:

string orig = "\"Text\",\"Text\",\"Text\"";
string res = orig.Replace("\",\"", ";");

Note that the replacement does not occur "in place", because .NET strings are immutable. The original string will remain the same after the call; only the returned string res will have the replacements.

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

Behe's answer with sorting plugins did not work on my Jenkins machine. I received the error java.lang.UnsupportedOperationException due to trying to sort an immutable collection i.e. Jenkins.instance.pluginManager.plugins. Simple fix for the code:

List<String> jenkinsPlugins = new ArrayList<String>(Jenkins.instance.pluginManager.plugins);
jenkinsPlugins.sort { it.displayName }
              .each { plugin ->
                   println ("${plugin.shortName}:${plugin.version}")
              }

Use the http://<jenkins-url>/script URL to run the code.

Difference between & and && in Java?

&& == logical AND

& = bitwise AND

SQL keys, MUL vs PRI vs UNI

UNI: For UNIQUE:

  • It is a set of one or more columns of a table to uniquely identify the record.
  • A table can have multiple UNIQUE key.
  • It is quite like primary key to allow unique values but can accept one null value which primary key does not.

PRI: For PRIMARY:

  • It is also a set of one or more columns of a table to uniquely identify the record.
  • A table can have only one PRIMARY key.
  • It is quite like UNIQUE key to allow unique values but does not allow any null value.

MUL: For MULTIPLE:

  • It is also a set of one or more columns of a table which does not identify the record uniquely.
  • A table can have more than one MULTIPLE key.
  • It can be created in table on index or foreign key adding, it does not allow null value.
  • It allows duplicate entries in column.
  • If we do not specify MUL column type then it is quite like a normal column but can allow null entries too hence; to restrict such entries we need to specify it.
  • If we add indexes on column or add foreign key then automatically MUL key type added.

Removing time from a Date object?

The correct class to use for a date without time of day is LocalDate. LocalDate is a part of java.time, the modern Java date and time API.

So the best thing you can do is if you can modify the getStartDate method you are using to return a LocalDate:

    DateTimeFormatter dateFormatter = DateTimeFormatter
            .ofLocalizedDate(FormatStyle.SHORT)
            .withLocale(Locale.forLanguageTag("en-IE"));

    LocalDate d = eventList.get(0).getStartDate(); // We’re now getting a LocalDate using this method
    String dateString = d.format(dateFormatter);
    System.out.println(dateString);

Example output:

21/03/2012

If you cannot change the getStartDate, you may still be able to add a new method returning the type that we want. However, if you cannot afford to do that just now, convert the old-fashioned Date that you get (I assume java.util.Date):

    d = eventList.get(0).getStartDate(); // I'm getting the old-fashioned Date using this method
    LocalDate dateWithoutTime = d.toInstant()
            .atZone(ZoneId.of("Asia/Kolkata"))
            .toLocalDate();

Please insert the time zone that was assumed for the Date. You may use ZoneId.systemDefault() for the JVM’s time zone setting, only this setting can be changed at any time from other parts of your program or other programs running in the same JVM.

The java.util.Date class was what we were all using when this question was asked 6 years ago (no, not all; I was, and we were many). java.time came out a couple of years later and has replaced the old Date, Calendar, SimpleDateFormat and DateFormat. Recognizing that they were poorly designed. Furthermore, a Date despite its name cannot represent a date. It’s a point in time. What the other answers do is they round down the time to the start of the day (“midnight”) in the JVM’s default time zone. It doesn’t remove the time of day, only sets it, typically to 00:00. Change your default time zone — as I said, even another program running in the same JVM may do that at any time without notice — and everything will break (often).

Link: Oracle tutorial: Date Time explaining how to use java.time.

How SID is different from Service name in Oracle tnsnames.ora

As per Oracle Glossary :

SID is a unique name for an Oracle database instance. ---> To switch between Oracle databases, users must specify the desired SID <---. The SID is included in the CONNECT DATA parts of the connect descriptors in a TNSNAMES.ORA file, and in the definition of the network listener in the LISTENER.ORA file. Also known as System ID. Oracle Service Name may be anything descriptive like "MyOracleServiceORCL". In Windows, You can your Service Name running as a service under Windows Services.

You should use SID in TNSNAMES.ORA as a better approach.

Labeling file upload button

I could achieve a button using jQueryMobile with following code:

<label for="ppt" data-role="button" data-inline="true" data-mini="true" data-corners="false">Upload</label>
<input id="ppt" type="file" name="ppt" multiple data-role="button" data-inline="true" data-mini="true" data-corners="false" style="opacity: 0;"/>

Above code creates a "Upload" button (custom text). On click of upload button, file browse is launched. Tested with Chrome 25 & IE9.

Using jQuery's ajax method to retrieve images as a blob

A big thank you to @Musa and here is a neat function that converts the data to a base64 string. This may come handy to you when handling a binary file (pdf, png, jpeg, docx, ...) file in a WebView that gets the binary file but you need to transfer the file's data safely into your app.

// runs a get/post on url with post variables, where:
// url ... your url
// post ... {'key1':'value1', 'key2':'value2', ...}
//          set to null if you need a GET instead of POST req
// done ... function(t) called when request returns
function getFile(url, post, done)
{
   var postEnc, method;
   if (post == null)
   {
      postEnc = '';
      method = 'GET';
   }
   else
   {
      method = 'POST';
      postEnc = new FormData();
      for(var i in post)
         postEnc.append(i, post[i]);
   }
   var xhr = new XMLHttpRequest();
   xhr.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200)
      {
         var res = this.response;
         var reader = new window.FileReader();
         reader.readAsDataURL(res); 
         reader.onloadend = function() { done(reader.result.split('base64,')[1]); }
      }
   }
   xhr.open(method, url);
   xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
   xhr.send('fname=Henry&lname=Ford');
   xhr.responseType = 'blob';
   xhr.send(postEnc);
}

Password encryption/decryption code in .NET

 string clearText = txtPassword.Text;
        string EncryptionKey = "MAKV2SPBNI99212";
        byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                }
                clearText = Convert.ToBase64String(ms.ToArray());
            }
        }

How to use CURL via a proxy?

Here is a working version with your bugs removed.

$url = 'http://dynupdate.no-ip.com/ip.php';
$proxy = '127.0.0.1:8888';
//$proxyauth = 'user:password';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
//curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyauth);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$curl_scraped_page = curl_exec($ch);
curl_close($ch);

echo $curl_scraped_page;

I have added CURLOPT_PROXYUSERPWD in case any of your proxies require a user name and password. I set CURLOPT_RETURNTRANSFER to 1, so that the data will be returned to $curl_scraped_page variable.

I removed a second extra curl_exec($ch); which would stop the variable being returned. I consolidated your proxy IP and port into one setting.

I also removed CURLOPT_HTTPPROXYTUNNEL and CURLOPT_CUSTOMREQUEST as it was the default.

If you don't want the headers returned, comment out CURLOPT_HEADER.

To disable the proxy simply set it to null.

curl_setopt($ch, CURLOPT_PROXY, null);

Any questions feel free to ask, I work with cURL every day.

Center icon in a div - horizontally and vertically

Here is a way to center content both vertically and horizontally in any situation, which is useful when you do not know the width or height or both:

CSS

#container {
    display: table;
    width: 300px; /* not required, just for example */
    height: 400px; /* not required, just for example */
}

#update {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

HTML

<div id="container">
    <a id="update" href="#">
        <i class="icon-refresh"></i>
    </a>
</div>

JSFiddle

Note that the width and height values are just for demonstration here, you can change them to anything you want (or remove them entirely) and it will still work because the vertical centering here is a product of the way the table-cell display property works.

Where is array's length property defined?

Arrays are special objects in java, they have a simple attribute named length which is final.

There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.

10.7. Array Members

The members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array. length may be positive or zero.
  • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].

    A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.

Resources:

How to check for an empty struct?

Here are 3 more suggestions or techniques:

With an Additional Field

You can add an additional field to tell if the struct has been populated or it is empty. I intentionally named it ready and not empty because the zero value of a bool is false, so if you create a new struct like Session{} its ready field will be automatically false and it will tell you the truth: that the struct is not-yet ready (it's empty).

type Session struct {
    ready bool

    playerId string
    beehive string
    timestamp time.Time
}

When you initialize the struct, you have to set ready to true. Your isEmpty() method isn't needed anymore (although you can create one if you want to) because you can just test the ready field itself.

var s Session

if !s.ready {
    // do stuff (populate s)
}

Significance of this one additional bool field increases as the struct grows bigger or if it contains fields which are not comparable (e.g. slice, map and function values).

Using the Zero Value of an Existing Field

This is similar to the previous suggestion, but it uses the zero value of an existing field which is considered invalid when the struct is not empty. Usability of this is implementation dependant.

For example if in your example your playerId cannot be the empty string "", you can use it to test if your struct is empty like this:

var s Session

if s.playerId == "" {
    // do stuff (populate s, give proper value to playerId)
}

In this case it's worth incorporating this check into an isEmpty() method because this check is implementation dependant:

func (s Session) isEmpty() bool {
    return s.playerId == ""
}

And using it:

if s.isEmpty() {
    // do stuff (populate s, give proper value to playerId)
}

Use Pointer to your struct

The second suggestion is to use a Pointer to your struct: *Session. Pointers can have nil values, so you can test for it:

var s *Session

if s == nil {
    s = new(Session)
    // do stuff (populate s)
}

Java: Instanceof and Generics

I had the same problem and here is my solution (very humble, @george: this time compiling AND working ...).

My probem was inside an abstract class that implements Observer. The Observable fires method update(...) with Object class that can be any kind of Object.

I only want to handler Objects of type T

The solution is to pass the class to the constructor in order to be able to compare types at runtime.

public abstract class AbstractOne<T> implements Observer {

  private Class<T> tClass;
    public AbstractOne(Class<T> clazz) {
    tClass = clazz;
  }

  @Override
  public void update(Observable o, Object arg) {
    if (tClass.isInstance(arg)) {
      // Here I am, arg has the type T
      foo((T) arg);
    }
  }

  public abstract foo(T t);

}

For the implementation we just have to pass the Class to the constructor

public class OneImpl extends AbstractOne<Rule> {
  public OneImpl() {
    super(Rule.class);
  }

  @Override
  public void foo(Rule t){
  }
}

How to use JavaScript to change the form action

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

$('form').attr('action', 'myNewActionTarget.html');

Basic example of using .ajax() with JSONP?

There is even easier way how to work with JSONP using jQuery

$.getJSON("http://example.com/something.json?callback=?", function(result){
   //response data are now in the result variable
   alert(result);
});

The ? on the end of the URL tells jQuery that it is a JSONP request instead of JSON. jQuery registers and calls the callback function automatically.

For more detail refer to the jQuery.getJSON documentation.

How can I exclude $(this) from a jQuery selector?

You can use the not function rather than the :not selector:

$(".content a").not(this).hide("slow")

How to set a binding in Code?

Replace:

myBinding.Source = ViewModel.SomeString;

with:

myBinding.Source = ViewModel;

Example:

Binding myBinding = new Binding();
myBinding.Source = ViewModel;
myBinding.Path = new PropertyPath("SomeString");
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
BindingOperations.SetBinding(txtText, TextBox.TextProperty, myBinding);

Your source should be just ViewModel, the .SomeString part is evaluated from the Path (the Path can be set by the constructor or by the Path property).

Execution sequence of Group By, Having and Where clause in SQL Server?

In Oracle 12c, you can run code both in either sequence below:

Where
Group By
Having

Or

Where 
Having
Group by

android get real path by Uri.getPath()

@Rene Juuse - above in comments... Thanks for this link !

. the code to get the real path is a bit different from one SDK to another so below we have three methods that deals with different SDKs.

getRealPathFromURI_API19(): returns real path for API 19 (or above but not tested) getRealPathFromURI_API11to18(): returns real path for API 11 to API 18 getRealPathFromURI_below11(): returns real path for API below 11

public class RealPathUtil {

@SuppressLint("NewApi")
public static String getRealPathFromURI_API19(Context context, Uri uri){
    String filePath = "";
    String wholeID = DocumentsContract.getDocumentId(uri);

     // Split at colon, use second item in the array
     String id = wholeID.split(":")[1];

     String[] column = { MediaStore.Images.Media.DATA };     

     // where id is equal to             
     String sel = MediaStore.Images.Media._ID + "=?";

     Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
                               column, sel, new String[]{ id }, null);

     int columnIndex = cursor.getColumnIndex(column[0]);

     if (cursor.moveToFirst()) {
         filePath = cursor.getString(columnIndex);
     }   
     cursor.close();
     return filePath;
}


@SuppressLint("NewApi")
public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
      String[] proj = { MediaStore.Images.Media.DATA };
      String result = null;

      CursorLoader cursorLoader = new CursorLoader(
              context, 
        contentUri, proj, null, null, null);        
      Cursor cursor = cursorLoader.loadInBackground();

      if(cursor != null){
       int column_index = 
         cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
       cursor.moveToFirst();
       result = cursor.getString(column_index);
      }
      return result;  
}

public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){
           String[] proj = { MediaStore.Images.Media.DATA };
           Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
           int column_index
      = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
           cursor.moveToFirst();
           return cursor.getString(column_index);
}

font: http://hmkcode.com/android-display-selected-image-and-its-real-path/


UPDATE 2016 March

To fix all problems with path of images i try create a custom gallery as facebook and other apps. This is because you can use just local files ( real files, not virtual or temporary) , i solve all problems with this library.

https://github.com/nohana/Laevatein (this library is to take photo from camera or choose from galery , if you choose from gallery he have a drawer with albums and just show local files)

Generate Controller and Model

Make resource controller with Model.

php artisan make:controller PostController --model=Post

SELECT with LIMIT in Codeigniter

I don't know what version of CI you were using back in 2013, but I am using CI3 and I just tested with two null parameters passed to limit() and there was no LIMIT or OFFSET in the rendered query (I checked by using get_compiled_select()).

This means that -- assuming your have correctly posted your coding attempt -- you don't need to change anything (or at least the old issue is no longer a CI issue).

If this was my project, this is how I would write the method to return an indexed array of objects or an empty array if there are no qualifying rows in the result set.

function nationList($limit = null, $start = null) {
    // assuming the language value is sanitized/validated/whitelisted
    return $this->db
        ->select('nation.id, nation.name_' . $this->session->userdata('language') . ' AS name')
        ->from('nation')
        ->order_by("name")
        ->limit($limit, $start)
        ->get()
        ->result();
}

These refinements remove unnecessary syntax, conditions, and the redundant loop.

For reference, here is the CI core code:

/**
 * LIMIT
 *
 * @param   int $value  LIMIT value
 * @param   int $offset OFFSET value
 * @return  CI_DB_query_builder
 */
public function limit($value, $offset = 0)
{
    is_null($value) OR $this->qb_limit = (int) $value;
    empty($offset) OR $this->qb_offset = (int) $offset;

    return $this;
}

So the $this->qb_limit and $this->qb_offset class objects are not updated because null evaluates as true when fed to is_null() or empty().

How to show Bootstrap table with sort icon

You could try using FontAwesome. It contains a sort-icon (http://fontawesome.io/icon/sort/).

To do so, you would

  1. need to include fontawesome:

    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
    
  2. and then simply use the fontawesome-icon instead of the default-bootstrap-icons in your th's:

    <th><b>#</b> <i class="fa fa-fw fa-sort"></i></th>
    

Hope that helps.

HTTP get with headers using RestTemplate

Take a look at the JavaDoc for RestTemplate.

There is the corresponding getForObject methods that are the HTTP GET equivalents of postForObject, but they doesn't appear to fulfil your requirements of "GET with headers", as there is no way to specify headers on any of the calls.

Looking at the JavaDoc, no method that is HTTP GET specific allows you to also provide header information. There are alternatives though, one of which you have found and are using. The exchange methods allow you to provide an HttpEntity object representing the details of the request (including headers). The execute methods allow you to specify a RequestCallback from which you can add the headers upon its invocation.

Why do access tokens expire?

In addition to the other responses:

Once obtained, Access Tokens are typically sent along with every request from Clients to protected Resource Servers. This induce a risk for access token stealing and replay (assuming of course that access tokens are of type "Bearer" (as defined in the initial RFC6750).

Examples of those risks, in real life:

  • Resource Servers generally are distributed application servers and typically have lower security levels compared to Authorization Servers (lower SSL/TLS config, less hardening, etc.). Authorization Servers on the other hand are usually considered as critical Security infrastructure and are subject to more severe hardening.

  • Access Tokens may show up in HTTP traces, logs, etc. that are collected legitimately for diagnostic purposes on the Resource Servers or clients. Those traces can be exchanged over public or semi-public places (bug tracers, service-desk, etc.).

  • Backend RS applications can be outsourced to more or less trustworthy third-parties.

The Refresh Token, on the other hand, is typically transmitted only twice over the wires, and always between the client and the Authorization Server: once when obtained by client, and once when used by client during refresh (effectively "expiring" the previous refresh token). This is a drastically limited opportunity for interception and replay.

Last thought, Refresh Tokens offer very little protection, if any, against compromised clients.

How to format a number 0..9 to display with 2 digits (it's NOT a date)

The String class comes with the format abilities:

System.out.println(String.format("%02d", 5));

for full documentation, here is the doc

How to check if another instance of my shell script is running

Someone please shoot me down if I'm wrong here

I understand that the mkdir operation is atomic, so you could create a lock directory

#!/bin/sh
lockdir=/tmp/AXgqg0lsoeykp9L9NZjIuaqvu7ANILL4foeqzpJcTs3YkwtiJ0
mkdir $lockdir  || {
    echo "lock directory exists. exiting"
    exit 1
}
# take pains to remove lock directory when script terminates
trap "rmdir $lockdir" EXIT INT KILL TERM

# rest of script here

How to shrink temp tablespace in oracle?

Temporary tablespaces are used for database sorting and joining operations and for storing global temporary tables. It may grow in size over a period of time and thus either we need to recreate temporary tablespace or shrink it to release the unused space.

Steps to shrink TEMP Tablespace

When to use a View instead of a Table?

According to Wikipedia,

Views can provide many advantages over tables:

  • Views can represent a subset of the data contained in a table.
  • Views can limit the degree of exposure of the underlying tables to the outer world: a given user may have permission to query the view, while denied access to the rest of the base table.

  • Views can join and simplify multiple tables into a single virtual table.

  • Views can act as aggregated tables, where the database engine aggregates data (sum, average, etc.) and presents the calculated results as part of the data.

  • Views can hide the complexity of data. For example, a view could appear as Sales2000 or Sales2001, transparently partitioning the actual underlying table.

  • Views take very little space to store; the database contains only the definition of a view, not a copy of all the data that it presents.

  • Views can provide extra security, depending on the SQL engine used.

How do I run PHP code when a user clicks on a link?

I know this post is old but I just wanted to add my answer!

You said to log a user out WITHOUT directing... this method DOES redirect but it returns the user to the page they were on! here's my implementation:

// every page with logout button
<?php
        // get the full url of current page
        $page = $_SERVER['PHP_SELF'];
        // find position of the last '/'
        $file_name_begin_pos = strripos($page, "/");
        // get substring from position to end 
        $file_name = substr($page, ++$fileNamePos);
    }
?>

// the logout link in your html
<a href="logout.php?redirect_to=<?=$file_name?>">Log Out</a>

// logout.php page
<?php
    session_start();
    $_SESSION = array();
    session_destroy();
    $page = "index.php";
    if(isset($_GET["redirect_to"])){
        $file = $_GET["redirect_to"];
        if ($file == "user.php"){
            // if redirect to is a restricted page, redirect to index
            $file = "index.php";
        }
    }
    header("Location: $file");
?>

and there we go!

the code that gets the file name from the full url isn't bug proof. for example if query strings are involved with un-escaped '/' in them, it will fail.

However there are many scripts out there to get the filename from url!

Happy Coding!

Alex

How to catch segmentation fault in Linux?

For portability, one should probably use std::signal from the standard C++ library, but there is a lot of restriction on what a signal handler can do. Unfortunately, it is not possible to catch a SIGSEGV from within a C++ program without introducing undefined behavior because the specification says:

  1. it is undefined behavior to call any library function from within the handler other than a very narrow subset of the standard library functions (abort, exit, some atomic functions, reinstall current signal handler, memcpy, memmove, type traits, `std::move, std::forward, and some more).
  2. it is undefined behavior if handler use a throw expression.
  3. it is undefined behavior if the handler returns when handling SIGFPE, SIGILL, SIGSEGV

This proves that it is impossible to catch SIGSEGV from within a program using strictly standard and portable C++. SIGSEGV is still caught by the operating system and is normally reported to the parent process when a wait family function is called.

You will probably run into the same kind of trouble using POSIX signal because there is a clause that says in 2.4.3 Signal Actions:

The behavior of a process is undefined after it returns normally from a signal-catching function for a SIGBUS, SIGFPE, SIGILL, or SIGSEGV signal that was not generated by kill(), sigqueue(), or raise().

A word about the longjumps. Assuming we are using POSIX signals, using longjump to simulate stack unwinding won't help:

Although longjmp() is an async-signal-safe function, if it is invoked from a signal handler which interrupted a non-async-signal-safe function or equivalent (such as the processing equivalent to exit() performed after a return from the initial call to main()), the behavior of any subsequent call to a non-async-signal-safe function or equivalent is undefined.

This means that the continuation invoked by the call to longjump cannot reliably call usually useful library function such as printf, malloc or exit or return from main without inducing undefined behavior. As such, the continuation can only do a restricted operations and may only exit through some abnormal termination mechanism.

To put things short, catching a SIGSEGV and resuming execution of the program in a portable is probably infeasible without introducing UB. Even if you are working on a Windows platform for which you have access to Structured exception handling, it is worth mentioning that MSDN suggest to never attempt to handle hardware exceptions: Hardware Exceptions.

At last but not least, whether any SIGSEGV would be raised when dereferencing a null valued pointer (or invalid valued pointer) is not a requirement from the standard. Because indirection through a null valued pointer or any invalid valued pointer is an undefined behaviour, which means the compiler assumes your code will never attempt such a thing at runtime, the compiler is free to make code transformation that would elide such undefined behavior. For example, from cppreference,

int foo(int* p) {
    int x = *p;
    if(!p)
        return x; // Either UB above or this branch is never taken
    else
        return 0;
}
 
int main() {
    int* p = nullptr;
    std::cout << foo(p);
}

Here the true path of the if could be completely elided by the compiler as an optimization; only the else part could be kept. Said otherwise, the compiler infers foo() will never receive a null valued pointer at runtime since it would lead to an undefined behaviour. Invoking it with a null valued pointer, you may observe the value 0 printed to standard output and no crash, you may observe a crash with SIGSEG, in fact you could observe anything since no sensible requirements are imposed on programs that are not free of undefined behaviors.

Undefined symbols for architecture x86_64 on Xcode 6.1

Same error when I copied/pasted a class and forgot to rename it in .m file.

How to add new item to hash

It's as simple as:

irb(main):001:0> hash = {:item1 => 1}
=> {:item1=>1}
irb(main):002:0> hash[:item2] = 2
=> 2
irb(main):003:0> hash
=> {:item1=>1, :item2=>2}

How do I center content in a div using CSS?

Update 2020:

There are several options available*:

*Disclaimer: This list may not be complete.

Using Flexbox
Nowadays, we can use flexbox. It is quite a handy alternative to the css-transform option. I would use this solution almost always. If it is just one element maybe not, but for example if I had to support an array of data e.g. rows and columns and I want them to be relatively centered in the very middle.

_x000D_
_x000D_
.flexbox {
  display: flex;
  height: 100px;
  flex-flow: row wrap;
  align-items: center;
  justify-content: center;
  background-color: #eaeaea;
  border: 1px dotted #333;
}

.item {
  /* default => flex: 0 1 auto */
  background-color: #fff;
  border: 1px dotted #333;
  box-sizing: border-box;
}
_x000D_
<div class="flexbox">
  <div class="item">I am centered in the middle.</div>
  <div class="item">I am centered in the middle, too.</div>
</div>
_x000D_
_x000D_
_x000D_


Using CSS 2D-Transform
This is still a good option, was also the accepted solution back in 2015. It is very slim and simple to apply and does not mess with the layouting of other elements.

_x000D_
_x000D_
.boxes {
  position: relative;
}

.box {
  position: relative;
  display: inline-block;
  float: left;
  width: 200px;
  height: 200px;
  font-weight: bold;
  color: #333;
  margin-right: 10px;
  margin-bottom: 10px;
  background-color: #eaeaea;
}

.h-center {
  text-align: center;
}

.v-center span {
  position: absolute;
  left: 0;
  right: 0;
  top: 50%;
  transform: translate(0, -50%);
}
_x000D_
<div class="boxes">
  <div class="box h-center">horizontally centered lorem ipsun dolor sit amet</div>
  <div class="box v-center"><span>vertically centered lorem ipsun dolor sit amet lorem ipsun dolor sit amet</span></div>
  <div class="box h-center v-center"><span>horizontally and vertically centered lorem ipsun dolor sit amet</span></div>
</div>
_x000D_
_x000D_
_x000D_

Note: This does also work with :after and :before pseudo-elements.


Using Grid
This might just be an overkill, but it depends on your DOM. If you want to use grid anyway, then why not. It is very powerful alternative and you are really maximum flexible with the design.

Note: To align the items vertically we use flexbox in combination with grid. But we could also use display: grid on the items.

_x000D_
_x000D_
.grid {
  display: grid;
  width: 400px;
  grid-template-rows: 100px;
  grid-template-columns: 100px 100px 100px;
  grid-gap: 3px;
  align-items: center;
  justify-content: center;
  background-color: #eaeaea;
  border: 1px dotted #333;
}

.item {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px dotted #333;
  box-sizing: border-box;
}

.item-large {
  height: 80px;
}
_x000D_
<div class="grid">
  <div class="item">Item 1</div>
  <div class="item item-large">Item 2</div>
  <div class="item">Item 3</div>
</div>
_x000D_
_x000D_
_x000D_


Further reading:

CSS article about grid
CSS article about flexbox
CSS article about centering without flexbox or grid

Java Class that implements Map and keeps insertion order?

You can maintain a Map (for fast lookup) and List (for order) but a LinkedHashMap may be the simplest. You can also try a SortedMap e.g. TreeMap, which an have any order you specify.

Basic authentication for REST API using spring restTemplate

(maybe) the easiest way without importing spring-boot.

restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor("user", "password"));

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

try:
    try:
        int('a')
    except ValueError as e:
        raise ValueError('There is a problem: {0}'.format(e))
except ValueError as err:
    print err

prints:

There is a problem: invalid literal for int() with base 10: 'a'

How to quickly form groups (quartiles, deciles, etc) by ordering column(s) in a data frame

You can use the quantile() function, but you need to handle rounding/precision when using cut(). So

set.seed(123)
temp <- data.frame(name=letters[1:12], value=rnorm(12), quartile=rep(NA, 12))
brks <- with(temp, quantile(value, probs = c(0, 0.25, 0.5, 0.75, 1)))
temp <- within(temp, quartile <- cut(value, breaks = brks, labels = 1:4, 
                                     include.lowest = TRUE))

Giving:

> head(temp)
  name       value quartile
1    a -0.56047565        1
2    b -0.23017749        2
3    c  1.55870831        4
4    d  0.07050839        2
5    e  0.12928774        3
6    f  1.71506499        4

Run PHP Task Asynchronously

I've used Beanstalkd for one project, and planned to again. I've found it to be an excellent way to run asynchronous processes.

A couple of things I've done with it are:

  • Image resizing - and with a lightly loaded queue passing off to a CLI-based PHP script, resizing large (2mb+) images worked just fine, but trying to resize the same images within a mod_php instance was regularly running into memory-space issues (I limited the PHP process to 32MB, and the resizing took more than that)
  • near-future checks - beanstalkd has delays available to it (make this job available to run only after X seconds) - so I can fire off 5 or 10 checks for an event, a little later in time

I wrote a Zend-Framework based system to decode a 'nice' url, so for example, to resize an image it would call QueueTask('/image/resize/filename/example.jpg'). The URL was first decoded to an array(module,controller,action,parameters), and then converted to JSON for injection to the queue itself.

A long running cli script then picked up the job from the queue, ran it (via Zend_Router_Simple), and if required, put information into memcached for the website PHP to pick up as required when it was done.

One wrinkle I did also put in was that the cli-script only ran for 50 loops before restarting, but if it did want to restart as planned, it would do so immediately (being run via a bash-script). If there was a problem and I did exit(0) (the default value for exit; or die();) it would first pause for a couple of seconds.

jQuery hyperlinks - href value?

Wonder why nobody said it here earlier: to prevent <a href="#"> from scrolling document position to the top, simply use <a href="#/"> instead. That's mere HTML, no JQuery needed. Using event.preventDefault(); is just too much!

Initialize/reset struct to zero/null

 struct x myX;
 ...
 memset(&x, 0, sizeof(myX));

Yii2 data provider default sorting

defaultOrder contain a array where key is a column name and value is a SORT_DESC or SORT_ASC that's why below code not working.

$dataProvider = new ActiveDataProvider([
        'query' => $query,
        'sort' => ['defaultOrder'=>'topic_order asc']
    ]);

Correct Way

$dataProvider = new ActiveDataProvider([
    'query' => $query,
    'sort' => [
        'defaultOrder' => [
            'topic_order' => SORT_ASC,
        ]
    ],
]);

Note: If a query already specifies the orderBy clause, the new ordering instructions given by end users (through the sort configuration) will be appended to the existing orderBy clause. Any existing limit and offset clauses will be overwritten by the pagination request from end users (through the pagination configuration).

You can detail learn from Yii2 Guide of Data Provider

Sorting By passing Sort object in query

 $sort = new Sort([
        'attributes' => [
            'age',
            'name' => [
                'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
                'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
                'default' => SORT_DESC,
                'label' => 'Name',
            ],
        ],
    ]);

    $models = Article::find()
        ->where(['status' => 1])
        ->orderBy($sort->orders)
        ->all();

How to override and extend basic Django admin templates?

I agree with Chris Pratt. But I think it's better to create the symlink to original Django folder where the admin templates place in:

ln -s /usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/admin/ templates/django_admin

and as you can see it depends on python version and the folder where the Django installed. So in future or on a production server you might need to change the path.

How to dynamically build a JSON object with Python?

You can use EasyDict library (doc):

EasyDict allows to access dict values as attributes (works recursively). A Javascript-like properties dot notation for python dicts.

USEAGE

>>> from easydict import EasyDict as edict
>>> d = edict({'foo':3, 'bar':{'x':1, 'y':2}})
>>> d.foo
3
>>> d.bar.x
1

>>> d = edict(foo=3)
>>> d.foo
3

[INSTALLATION]:

  • pip install easydict

When is a timestamp (auto) updated?

Add a trigger in database:

DELIMITER //
CREATE TRIGGER update_user_password 
  BEFORE UPDATE ON users
  FOR EACH ROW
    BEGIN
      IF OLD.password <> NEW.password THEN
        SET NEW.password_changed_on = NOW();
      END IF;
    END //
DELIMITER ;

The password changed time will update only when password column is changed.

How to set base url for rest in spring boot?

You can create a base class with @RequestMapping("rest") annotations and extend all you other classes with this base class.

@RequestMapping("rest")
public abstract class BaseController {}

Now all classes that extend this base class will be accessible at rest/**.

Hidden TextArea

Set CSS display to none for textarea

<textarea name="hide" style="display:none;"></textarea>

SVN (Subversion) Problem "File is scheduled for addition, but is missing" - Using Versions

Avoid using Xcode to rename files in a folder reference. If you rename a file using Xcode, it will be marked for commit. If you later delete it before the commit, you will end up with this error.

Getting "net::ERR_BLOCKED_BY_CLIENT" error on some AJAX calls

I've discovered that if the filename has 300 in it, AdBlock blocks the page and throws a ERR_BLOCKED_BY_CLIENT error.

How to prove that a problem is NP complete?

You need to reduce an NP-Complete problem to the problem you have. If the reduction can be done in polynomial time then you have proven that your problem is NP-complete, if the problem is already in NP, because:

It is not easier than the NP-complete problem, since it can be reduced to it in polynomial time which makes the problem NP-Hard.

See the end of http://www.ics.uci.edu/~eppstein/161/960312.html for more.

'AND' vs '&&' as operator

Since and has lower precedence than = you can use it in condition assignment:

if ($var = true && false) // Compare true with false and assign to $var
if ($var = true and false) // Assign true to $var and compare $var to false

How to include files outside of Docker's build context?

The best way to work around this is to specify the Dockerfile independently of the build context, using -f.

For instance, this command will give the ADD command access to anything in your current directory.

docker build -f docker-files/Dockerfile .

Update: Docker now allows having the Dockerfile outside the build context (fixed in 18.03.0-ce, https://github.com/docker/cli/pull/886). So you can also do something like

docker build -f ../Dockerfile .

public static const in TypeScript

Here's what's this TS snippet compiled into (via TS Playground):

define(["require", "exports"], function(require, exports) {
    var Library = (function () {
        function Library() {
        }
        Library.BOOK_SHELF_NONE = "None";
        Library.BOOK_SHELF_FULL = "Full";
        return Library;
    })();
    exports.Library = Library;
});

As you see, both properties defined as public static are simply attached to the exported function (as its properties); therefore they should be accessible as long as you properly access the function itself.

postgresql - sql - count of `true` values

In MySQL, you can do this as well:

SELECT count(*) AS total
     , sum(myCol) AS countTrue --yes, you can add TRUEs as TRUE=1 and FALSE=0 !!
FROM yourTable
;

I think that in Postgres, this works:

SELECT count(*) AS total
     , sum(myCol::int) AS countTrue --convert Boolean to Integer
FROM yourTable
;

or better (to avoid :: and use standard SQL syntax):

SELECT count(*) AS total
     , sum(CAST(myCol AS int)) AS countTrue --convert Boolean to Integer
FROM yourTable
;

A transport-level error has occurred when receiving results from the server

Try the following command on the command prompt:

netsh interface tcp set global autotuning=disabled

This turns off the auto scaling abilities of the network stack

how to delete installed library form react native project

From react-native --help

uninstall [options] uninstall and unlink native dependencies

Ex: react-native uninstall react-native-vector-icons

It will uninstall and unlink its dependencies.

How to add a custom Ribbon tab using VBA?

The answers on here are specific to using the custom UI Editor. I spent some time creating the interface without that wonderful program, so I am documenting the solution here to help anyone else decide if they need that custom UI editor or not.

I came across the following microsoft help webpage - https://msdn.microsoft.com/en-us/library/office/ff861787.aspx. This shows how to set up the interface manually, but I had some trouble when pointing to my custom add-in code.

To get the buttons to work with your custom macros, setup the macro in your .xlam subs to be called as described in this SO answer - Calling an excel macro from the ribbon. Basically, you'll need to add that "control As IRibbonControl" paramter to any module pointed from your ribbon xml. Also, your ribbon xml should have the onAction="myaddin!mymodule.mysub" syntax to properly call any modules loaded by the add in.

Using those instructions I was able to create an excel add in (.xlam file) that has a custom tab loaded when my VBA gets loaded into Excel along with the add in. The buttons execute code from the add in and the custom tab uninstalls when I remove the add in.

Emulate a 403 error page

http_response_code was introduced in PHP 5.4 and made the things a lot easier!

http_response_code(403);
die('Forbidden');

Maven home (M2_HOME) not being picked up by IntelliJ IDEA

Mac OS apps cannot read bash environment variables. Look at this question Setting environment variables in OS X? to expose M2_HOME to all applications including IntelliJ. You do need to restart after doing this.

Difference between Method and Function?

well, in some programming languages they are called functions others call it methods, the fact is they are the same thing. It just represents an abstractized form of reffering to a mathematical function:

f -> f(N:N).

meaning its a function with values from natural numbers (just an example). So besides the name Its exactly the same thing, representing a block of code containing instructions in resolving your purpose.

Explaining Python's '__enter__' and '__exit__'

try adding my answers (my thought of learning) :

__enter__ and [__exit__] both are methods that are invoked on entry to and exit from the body of "the with statement" (PEP 343) and implementation of both is called context manager.

the with statement is intend to hiding flow control of try finally clause and make the code inscrutable.

the syntax of the with statement is :

with EXPR as VAR:
    BLOCK

which translate to (as mention in PEP 343) :

mgr = (EXPR)
exit = type(mgr).__exit__  # Not calling it yet
value = type(mgr).__enter__(mgr)
exc = True
try:
    try:
        VAR = value  # Only if "as VAR" is present
        BLOCK
    except:
        # The exceptional case is handled here
        exc = False
        if not exit(mgr, *sys.exc_info()):
            raise
        # The exception is swallowed if exit() returns true
finally:
    # The normal and non-local-goto cases are handled here
    if exc:
        exit(mgr, None, None, None)

try some code:

>>> import logging
>>> import socket
>>> import sys

#server socket on another terminal / python interpreter
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> s.listen(5)
>>> s.bind((socket.gethostname(), 999))
>>> while True:
>>>    (clientsocket, addr) = s.accept()
>>>    print('get connection from %r' % addr[0])
>>>    msg = clientsocket.recv(1024)
>>>    print('received %r' % msg)
>>>    clientsocket.send(b'connected')
>>>    continue

#the client side
>>> class MyConnectionManager:
>>>     def __init__(self, sock, addrs):
>>>         logging.basicConfig(level=logging.DEBUG, format='%(asctime)s \
>>>         : %(levelname)s --> %(message)s')
>>>         logging.info('Initiating My connection')
>>>         self.sock = sock
>>>         self.addrs = addrs
>>>     def __enter__(self):
>>>         try:
>>>             self.sock.connect(addrs)
>>>             logging.info('connection success')
>>>             return self.sock
>>>         except:
>>>             logging.warning('Connection refused')
>>>             raise
>>>     def __exit__(self, type, value, tb):
>>>             logging.info('CM suppress exception')
>>>             return False
>>> addrs = (socket.gethostname())
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> with MyConnectionManager(s, addrs) as CM:
>>>     try:
>>>         CM.send(b'establishing connection')
>>>         msg = CM.recv(1024)
>>>         print(msg)
>>>     except:
>>>         raise
#will result (client side) :
2018-12-18 14:44:05,863         : INFO --> Initiating My connection
2018-12-18 14:44:05,863         : INFO --> connection success
b'connected'
2018-12-18 14:44:05,864         : INFO --> CM suppress exception

#result of server side
get connection from '127.0.0.1'
received b'establishing connection'

and now try manually (following translate syntax):

>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #make new socket object
>>> mgr = MyConnection(s, addrs)
2018-12-18 14:53:19,331         : INFO --> Initiating My connection
>>> ext = mgr.__exit__
>>> value = mgr.__enter__()
2018-12-18 14:55:55,491         : INFO --> connection success
>>> exc = True
>>> try:
>>>     try:
>>>         VAR = value
>>>         VAR.send(b'establishing connection')
>>>         msg = VAR.recv(1024)
>>>         print(msg)
>>>     except:
>>>         exc = False
>>>         if not ext(*sys.exc_info()):
>>>             raise
>>> finally:
>>>     if exc:
>>>         ext(None, None, None)
#the result:
b'connected'
2018-12-18 15:01:54,208         : INFO --> CM suppress exception

the result of the server side same as before

sorry for my bad english and my unclear explanations, thank you....

Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' } js-bson: Failed to load c++ bson extension, using pure JS version

I had this issue today (Feb 19th, 2016) and I solved it just by installing the latest version of Mongoose. Try putting this in your package.json:

"mongoose": "~4.4"

Hope that helps. Solved it for me!

Running AngularJS initialization code when view is loaded

When your view loads, so does its associated controller. Instead of using ng-init, simply call your init() method in your controller:

$scope.init = function () {
    if ($routeParams.Id) {
        //get an existing object
    } else {
        //create a new object
    }
    $scope.isSaving = false;
}
...
$scope.init();

Since your controller runs before ng-init, this also solves your second issue.

Fiddle


As John David Five mentioned, you might not want to attach this to $scope in order to make this method private.

var init = function () {
    // do something
}
...
init();

See jsFiddle


If you want to wait for certain data to be preset, either move that data request to a resolve or add a watcher to that collection or object and call your init method when your data meets your init criteria. I usually remove the watcher once my data requirements are met so the init function doesnt randomly re-run if the data your watching changes and meets your criteria to run your init method.

var init = function () {
    // do something
}
...
var unwatch = scope.$watch('myCollecitonOrObject', function(newVal, oldVal){
                    if( newVal && newVal.length > 0) {
                        unwatch();
                        init();
                    }
                });

How to install/start Postman native v4.10.3 on Ubuntu 16.04 LTS 64-bit?

Download latest version of postman from https://www.postman.com/downloads/ then after tar.gz file gets downloaded follow below commands

$ tar -xvzf Postman-linux-x64-7.27.1.tar.gz
$ cd Postman
$ ./Postman

Regular Expression for matching parentheses

The solution consists in a regex pattern matching open and closing parenthesis

String str = "Your(String)";
// parameter inside split method is the pattern that matches opened and closed parenthesis, 
// that means all characters inside "[ ]" escaping parenthesis with "\\" -> "[\\(\\)]"
String[] parts = str.split("[\\(\\)]");
for (String part : parts) {
   // I print first "Your", in the second round trip "String"
   System.out.println(part);
}

Writing in Java 8's style, this can be solved in this way:

Arrays.asList("Your(String)".split("[\\(\\)]"))
    .forEach(System.out::println);

I hope it is clear.

Should I set max pool size in database connection string? What happens if I don't?

Currently your application support 100 connections in pool. Here is what conn string will look like if you want to increase it to 200:

public static string srConnectionString = 
                "server=localhost;database=mydb;uid=sa;pwd=mypw;Max Pool Size=200;";

You can investigate how many connections with database your application use, by executing sp_who procedure in your database. In most cases default connection pool size will be enough.

System.Runtime.InteropServices.COMException (0x800A03EC)

It 'a permission problem when IIS is running I had this problem and I solved it in this way

I went on folders

C:\Windows\ System32\config\SystemProfile

and

C:\Windows\SysWOW64\config\SystemProfile

are protected system folders, they usually have the lock.

Right-click-> Card security-> Click on Edit-> Add untente "Autenticadet User" and assign permissions.

At this point everything is solved, if you still have problems try to give all permissions to "Everyone"

Setting Environment Variables for Node to retrieve

Came across a nice tool for doing this.

node-env-file

Parses and loads environment files (containing ENV variable exports) into Node.js environment, i.e. process.env - Uses this style:

.env

# some env variables

FOO=foo1
BAR=bar1
BAZ=1
QUX=
# QUUX=

How do I speed up the gwt compiler?

If you run the GWT compiler with the -localWorkers flag, the compiler will compile multiple permutations in parallel. This lets you use all the cores of a multi-core machine, for example -localWorkers 2 will tell the compiler to do compile two permutations in parallel. You won't get order of magnitudes differences (not everything in the compiler is parallelizable) but it is still a noticable speedup if you are compiling multiple permutations.

If you're willing to use the trunk version of GWT, you'll be able to use hosted mode for any browser (out of process hosted mode), which alleviates most of the current issues with hosted mode. That seems to be where the GWT is going - always develop with hosted mode, since compiles aren't likely to get magnitudes faster.

Updating state on props change in React Form

componentWillReceiveProps is depcricated since react 16: use getDerivedStateFromProps instead

If I understand correctly, you have a parent component that is passing start_time down to the ModalBody component which assigns it to its own state? And you want to update that time from the parent, not a child component.

React has some tips on dealing with this scenario. (Note, this is an old article that has since been removed from the web. Here's a link to the current doc on component props).

Using props to generate state in getInitialState often leads to duplication of "source of truth", i.e. where the real data is. This is because getInitialState is only invoked when the component is first created.

Whenever possible, compute values on-the-fly to ensure that they don't get out of sync later on and cause maintenance trouble.

Basically, whenever you assign parent's props to a child's state the render method isn't always called on prop update. You have to invoke it manually, using the componentWillReceiveProps method.

componentWillReceiveProps(nextProps) {
  // You don't have to do this check first, but it can help prevent an unneeded render
  if (nextProps.startTime !== this.state.startTime) {
    this.setState({ startTime: nextProps.startTime });
  }
}

Cross-Origin Read Blocking (CORB)

Try to install "Moesif CORS" extension if you are facing issue in google chrome. As it is cross origin request, so chrome is not accepting a response even when the response status code is 200

How to always show scrollbar

Simple and easy. Add this attribute to the ScrollBar:

android:fadeScrollbars="false"

Or you can do this in :

scrollView.setScrollbarFadingEnabled(false);

Or in :

scrollView.isScrollbarFadingEnabled = false

Bash: Echoing a echo command with a variable in bash

You just need to use single quotes:

$ echo "$TEST"
test
$ echo '$TEST'
$TEST

Inside single quotes special characters are not special any more, they are just normal characters.

Invisible characters - ASCII

I just went through the character map to get these. They are all in Calibri.

Number    Name                   HTML Code    Appearance
------    --------------------   ---------    ----------
U+2000    En Quad                &#8192;      " "
U+2001    Em Quad                &#8193;      " "
U+2002    En Space               &#8194;      " "
U+2003    Em Space               &#8195;      " "
U+2004    Three-Per-Em Space     &#8196;      " "
U+2005    Four-Per-Em Space      &#8197;      " "
U+2006    Six-Per-Em Space       &#8198;      " "
U+2007    Figure Space           &#8199;      " "
U+2008    Punctuation Space      &#8200;      " "
U+2009    Thin Space             &#8201;      " "
U+200A    Hair Space             &#8202;      " "
U+200B    Zero-Width Space       &#8203;      "​"
U+200C    Zero Width Non-Joiner  &#8204;      "‌"
U+200D    Zero Width Joiner      &#8205;      "‍"
U+200E    Left-To-Right Mark     &#8206;      "‎"
U+200F    Right-To-Left Mark     &#8207;      "‏"
U+202F    Narrow No-Break Space  &#8239;      " "

WinError 2 The system cannot find the file specified (Python)

I believe you need to .f file as a parameter, not as a command-single-string. same with the "--domain "+i, which i would split in two elements of the list. Assuming that:

  • you have the path set for FORTRAN executable,
  • the ~/ is indeed the correct way for the FORTRAN executable

I would change this line:

subprocess.Popen(["FORTRAN ~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain "+i])

to

subprocess.Popen(["FORTRAN", "~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain", i])

If that doesn't work, you should do a os.path.exists() for the .f file, and check that you can launch the FORTRAN executable without any path, and set the path or system path variable accordingly

[EDIT 6-Mar-2017]

As the exception, detailed in the original post, is a python exception from subprocess; it is likely that the WinError 2 is because it cannot find FORTRAN

I highly suggest that you specify full path for your executable:

for i in input:
    exe = r'c:\somedir\fortrandir\fortran.exe'
    fortran_script = r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f'
    subprocess.Popen([exe, fortran_script, "--domain", i])

if you need to convert the forward-slashes to backward-slashes, as suggested in one of the comments, you can do this:

for i in input:
    exe = os.path.normcase(r'c:\somedir\fortrandir\fortran.exe')
    fortran_script = os.path.normcase(r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
    i = os.path.normcase(i)
    subprocess.Popen([exe, fortran_script, "--domain", i])

[EDIT 7-Mar-2017]

The following line is incorrect:

exe = os.path.normcase(r'~/C:/Program Files (x86)/Silverfrost/ftn95.exe'

I am not sure why you have ~/ as a prefix for every path, don't do that.

for i in input:
    exe = os.path.normcase(r'C:/Program Files (x86)/Silverfrost/ftn95.exe'
    fortran_script = os.path.normcase(r'C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
    i = os.path.normcase(i)
    subprocess.Popen([exe, fortran_script, "--domain", i])

[2nd EDIT 7-Mar-2017]

I do not know this FORTRAN or ftn95.exe, does it need a shell to function properly?, in which case you need to launch as follows:

subprocess.Popen([exe, fortran_script, "--domain", i], shell = True)

You really need to try to launch the command manually from the working directory which your python script is operating from. Once you have the command which is actually working, then build up the subprocess command.

Adding days to $Date in PHP

Using a variable for Number of days

$myDate = "2014-01-16";
$nDays = 16;
$newDate = strtotime($myDate . '+ '.$nDays.'days');
echo new Date('d/m/Y', $soma); //format new date 

How do I enable logging for Spring Security?

You can easily enable debugging support using an option for the @EnableWebSecurity annotation:

@EnableWebSecurity(debug = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    …
}

If you need profile-specific control the in your application-{profile}.properties file

org.springframework.security.config.annotation.web.builders.WebSecurity.debugEnabled=false

Get Detailed Post: http://www.bytefold.com/enable-disable-profile-specific-spring-security-debug-flag/

mysqli::mysqli(): (HY000/2002): Can't connect to local MySQL server through socket 'MySQL' (2)

Please check the following file

%SystemRoot%\system32\drivers\etc\host

The line which bind the host name with ip is probably missing a line which bind them togather

127.0.0.1  localhost

If the given line is missing. Add the line in the file


Could you also check your MySQL database's user table and tell us the host column value for the user which you are using. You should have user privilege for both the host "127.0.0.1" and "localhost" and use % as it is a wild char for generic host name.

disable a hyperlink using jQuery

function EnableHyperLink(id) {
        $('#' + id).attr('onclick', 'Pagination("' + id + '")');//onclick event which u 
        $('#' + id).addClass('enable-link');
        $('#' + id).removeClass('disable-link');
    }

    function DisableHyperLink(id) {
        $('#' + id).addClass('disable-link');
        $('#' + id).removeClass('enable-link');
        $('#' + id).removeAttr('onclick');
    }

.disable-link
{
    text-decoration: none !important;
    color: black !important;
    cursor: default;
}
.enable-link
{
    text-decoration: underline !important;
    color: #075798 !important;
    cursor: pointer !important;
}

Fastest way to flatten / un-flatten nested JSON objects

This code recursively flattens out JSON objects.

I included my timing mechanism in the code and it gives me 1ms but I'm not sure if that's the most accurate one.

            var new_json = [{
              "name": "fatima",
              "age": 25,
              "neighbour": {
                "name": "taqi",
                "location": "end of the street",
                "property": {
                  "built in": 1990,
                  "owned": false,
                  "years on market": [1990, 1998, 2002, 2013],
                  "year short listed": [], //means never
                }
              },
              "town": "Mountain View",
              "state": "CA"
            },
            {
              "name": "qianru",
              "age": 20,
              "neighbour": {
                "name": "joe",
                "location": "opposite to the park",
                "property": {
                  "built in": 2011,
                  "owned": true,
                  "years on market": [1996, 2011],
                  "year short listed": [], //means never
                }
              },
              "town": "Pittsburgh",
              "state": "PA"
            }]

            function flatten(json, flattened, str_key) {
                for (var key in json) {
                  if (json.hasOwnProperty(key)) {
                    if (json[key] instanceof Object && json[key] != "") {
                      flatten(json[key], flattened, str_key + "." + key);
                    } else {
                      flattened[str_key + "." + key] = json[key];
                    }
                  }
                }
            }

        var flattened = {};
        console.time('flatten'); 
        flatten(new_json, flattened, "");
        console.timeEnd('flatten');

        for (var key in flattened){
          console.log(key + ": " + flattened[key]);
        }

Output:

flatten: 1ms
.0.name: fatima
.0.age: 25
.0.neighbour.name: taqi
.0.neighbour.location: end of the street
.0.neighbour.property.built in: 1990
.0.neighbour.property.owned: false
.0.neighbour.property.years on market.0: 1990
.0.neighbour.property.years on market.1: 1998
.0.neighbour.property.years on market.2: 2002
.0.neighbour.property.years on market.3: 2013
.0.neighbour.property.year short listed: 
.0.town: Mountain View
.0.state: CA
.1.name: qianru
.1.age: 20
.1.neighbour.name: joe
.1.neighbour.location: opposite to the park
.1.neighbour.property.built in: 2011
.1.neighbour.property.owned: true
.1.neighbour.property.years on market.0: 1996
.1.neighbour.property.years on market.1: 2011
.1.neighbour.property.year short listed: 
.1.town: Pittsburgh
.1.state: PA

Getting the closest string match

The problem is hard to implement if the input data is too large (say millions of strings). I used elastic search to solve this.

Quick start : https://www.elastic.co/guide/en/elasticsearch/client/net-api/6.x/elasticsearch-net.html

Just insert all the input data into DB and you can search any string based on any edit distance quickly. Here is a C# snippet which will give you a list of results sorted by edit distance (smaller to higher)

var res = client.Search<ClassName>(s => s
    .Query(q => q
    .Match(m => m
        .Field(f => f.VariableName)
        .Query("SAMPLE QUERY")
        .Fuzziness(Fuzziness.EditDistance(5))
    )
));

Execute and get the output of a shell command in node.js

Requirements

This will require Node.js 7 or later with a support for Promises and Async/Await.

Solution

Create a wrapper function that leverage promises to control the behavior of the child_process.exec command.

Explanation

Using promises and an asynchronous function, you can mimic the behavior of a shell returning the output, without falling into a callback hell and with a pretty neat API. Using the await keyword, you can create a script that reads easily, while still be able to get the work of child_process.exec done.

Code sample

const childProcess = require("child_process");

/**
 * @param {string} command A shell command to execute
 * @return {Promise<string>} A promise that resolve to the output of the shell command, or an error
 * @example const output = await execute("ls -alh");
 */
function execute(command) {
  /**
   * @param {Function} resolve A function that resolves the promise
   * @param {Function} reject A function that fails the promise
   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
   */
  return new Promise(function(resolve, reject) {
    /**
     * @param {Error} error An error triggered during the execution of the childProcess.exec command
     * @param {string|Buffer} standardOutput The result of the shell command execution
     * @param {string|Buffer} standardError The error resulting of the shell command execution
     * @see https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback
     */
    childProcess.exec(command, function(error, standardOutput, standardError) {
      if (error) {
        reject();

        return;
      }

      if (standardError) {
        reject(standardError);

        return;
      }

      resolve(standardOutput);
    });
  });
}

Usage

async function main() {
  try {
    const passwdContent = await execute("cat /etc/passwd");

    console.log(passwdContent);
  } catch (error) {
    console.error(error.toString());
  }

  try {
    const shadowContent = await execute("cat /etc/shadow");

    console.log(shadowContent);
  } catch (error) {
    console.error(error.toString());
  }
}

main();

Sample Output

root:x:0:0::/root:/bin/bash
[output trimmed, bottom line it succeeded]

Error: Command failed: cat /etc/shadow
cat: /etc/shadow: Permission denied

Try it online.

Repl.it.

External resources

Promises.

child_process.exec.

Node.js support table.

ImportError: No module named pandas

If you are running python version 3.9 pandas wont work as of now. So install python version 3.7 or below to mitigate this issue. Or else if you want to stick with python 3.9 try install pandas by compiling the library

how to get current month and year

using System.Globalization;

LblMonth.Text = DateTime.Now.Month.ToString();

DateTimeFormatInfo dinfo = new DateTimeFormatInfo();
int month = Convert.ToInt16(LblMonth.Text);

LblMonth.Text = dinfo.GetMonthName(month);

Saving lists to txt file

@Jon's answer is great and will get you where you need to go. So why is your code printing out what it is. The answer: You're not writing out the contents of your list, but the String representation of your list itself, by an implicit call to Lists.verbList.ToString(). Object.ToString() defines the default behavior you're seeing here.

How to break out from a ruby block?

If you want your block to return a useful value (e.g. when using #map, #inject, etc.), next and break also accept an argument.

Consider the following:

def contrived_example(numbers)
  numbers.inject(0) do |count, x|
    if x % 3 == 0
      count + 2
    elsif x.odd?
      count + 1
    else 
      count
    end
  end
end

The equivalent using next:

def contrived_example(numbers)
  numbers.inject(0) do |count, x|
    next count if x.even?
    next (count + 2) if x % 3 == 0
    count + 1
  end
end

Of course, you could always extract the logic needed into a method and call that from inside your block:

def contrived_example(numbers)
  numbers.inject(0) { |count, x| count + extracted_logic(x) }
end

def extracted_logic(x)
  return 0 if x.even?
  return 2 if x % 3 == 0
  1
end

How to get object size in memory?

OK, this question has been answered and answer accepted but someone asked me to put my answer so there you go.

First of all, it is not possible to say for sure. It is an internal implementation detail and not documented. However, based on the objects included in the other object. Now, how do we calculate the memory requirement for our cached objects?

I had previously touched this subject in this article:

Now, how do we calculate the memory requirement for our cached objects? Well, as most of you would know, Int32 and float are four bytes, double and DateTime 8 bytes, char is actually two bytes (not one byte), and so on. String is a bit more complex, 2*(n+1), where n is the length of the string. For objects, it will depend on their members: just sum up the memory requirement of all its members, remembering all object references are simply 4 byte pointers on a 32 bit box. Now, this is actually not quite true, we have not taken care of the overhead of each object in the heap. I am not sure if you need to be concerned about this, but I suppose, if you will be using lots of small objects, you would have to take the overhead into consideration. Each heap object costs as much as its primitive types, plus four bytes for object references (on a 32 bit machine, although BizTalk runs 32 bit on 64 bit machines as well), plus 4 bytes for the type object pointer, and I think 4 bytes for the sync block index. Why is this additional overhead important? Well, let’s imagine we have a class with two Int32 members; in this case, the memory requirement is 16 bytes and not 8.

JAVA_HOME does not point to the JDK

I met this issue in rhel, my "JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk"(which is a symbolic link), and ant complains.

MY solution for this is to use the real jdk path in JAVA_HOME, like:

JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.161-0.b14.el7_4.x86_64

It works for me.

Reload activity in Android

I don't think that's a good idea... it'd be better to implement a cleaner method. For instance, if your activity holds a form, the cleaner method could just clear each widget in the form and delete all temporary data. I guess that's what you want: restore the activity to its initial state.

Converting string to Date and DateTime

You need to be careful with m/d/Y and m-d-Y formats. PHP considers / to mean m/d/Y and - to mean d-m-Y. I would explicitly describe the input format in this case:

$ymd = DateTime::createFromFormat('m-d-Y', '10-16-2003')->format('Y-m-d');

That way you are not at the whims of a certain interpretation.

char initial value in Java

As you will see in linked discussion there is no need for initializing char with special character as it's done for us and is represented by '\u0000' character code.

So if we want simply to check if specified char was initialized just write:

if(charVariable != '\u0000'){
 actionsOnInitializedCharacter();
}

Link to question: what's the default value of char?

Reading a file line by line in Go

bufio.Reader.ReadLine() works well. But if you want to read each line by a string, try to use ReadString('\n'). It doesn't need to reinvent the wheel.

Access maven properties defined in the pom

This can be done with standard java properties in combination with the maven-resource-plugin with enabled filtering on properties.

For more info see http://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html

This will work for standard maven project as for plugin projects

ListBox vs. ListView - how to choose for data binding

A ListView is a specialized ListBox (that is, it inherits from ListBox). It allows you to specify different views rather than a straight list. You can either roll your own view, or use GridView (think explorer-like "details view"). It's basically the multi-column listbox, the cousin of windows form's listview.

If you don't need the additional capabilities of ListView, you can certainly use ListBox if you're simply showing a list of items (Even if the template is complex).

Angular.js: set element height on page load

Combining matty-j suggestion with the snippet of the question, I ended up with this code focusing on resizing the grid after the data was loaded.

The HTML:

<div ng-grid="gridOptions" class="gridStyle"></div>

The directive:

angular.module('myApp.directives', [])
    .directive('resize', function ($window) {
        return function (scope, element) {

            var w = angular.element($window);
            scope.getWindowDimensions = function () {
                return { 'h': w.height(), 'w': w.width() };
            };
            scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) {

                // resize Grid to optimize height
                $('.gridStyle').height(newValue.h - 250);
            }, true);

            w.bind('resize', function () {
                scope.$apply();
            });
        }
    });

The controller:

angular.module('myApp').controller('Admin/SurveyCtrl', function ($scope, $routeParams, $location, $window, $timeout, Survey) {

    // Retrieve data from the server
    $scope.surveys = Survey.query(function(data) {

        // Trigger resize event informing elements to resize according to the height of the window.
        $timeout(function () {
            angular.element($window).resize();
        }, 0)
    });

    // Configure ng-grid.
    $scope.gridOptions = {
        data: 'surveys',
        ...
    };
}

Python setup.py develop vs install

python setup.py install is used to install (typically third party) packages that you're not going to develop/modify/debug yourself.

For your own stuff, you want to first install your package and then be able to frequently edit the code without having to re-install the package every time — and that is exactly what python setup.py develop does: it installs the package (typically just a source folder) in a way that allows you to conveniently edit your code after it’s installed to the (virtual) environment, and have the changes take effect immediately.

Note that it is highly recommended to use pip install . (install) and pip install -e . (developer install) to install packages, as invoking setup.py directly will do the wrong things for many dependencies, such as pull prereleases and incompatible package versions, or make the package hard to uninstall with pip.

Parsing string as JSON with single quotes?

The JSON standard requires double quotes and will not accept single quotes, nor will the parser.

If you have a simple case with no escaped single quotes in your strings (which would normally be impossible, but this isn't JSON), you can simple str.replace(/'/g, '"') and you should end up with valid JSON.

Laravel Migration table already exists, but I want to add new not the older

Drop all database table and run this line in your project path via CMD

php artisan migrate

How can I recover a lost commit in Git?

This happened to me just today, so I am writing what came out as a lifesaver for me. My answer is very similar to @Amber 's answer.

First, I did a git reflog and searched for that particular commit's hash, then just copied that hash and did a git cherry-pick <hash> from that branch. This brought all the change from that lost commit to my current branch, and restored my faith on GIT.

Have a nice day!

Mockito matcher and array of primitives

I would rather use Matchers.<byte[]>any(). This worked for me.

Can I catch multiple Java exceptions in the same catch clause?

Yes. Here's the way using pipe( | ) separator,

try
{
    .......
}    
catch
{
    catch(IllegalArgumentException | SecurityException | IllegalAccessException | NoSuchFieldException e)
}

Separating class code into a header and cpp file

Usually you put only declarations and really short inline functions in the header file:

For instance:

class A {
 public:
  A(); // only declaration in the .h unless only a short initialization list is used.

  inline int GetA() const {
    return a_;
  }

  void DoSomethingCoplex(); // only declaration
  private:
   int a_;
 };

What I can do to resolve "1 commit behind master"?

If the branch is behind master, then delete the remote branch. Then go to local branch and run :

git pull origin master --rebase

Then, again push the branch to origin:

git push -u origin <branch-name>

Set a div width, align div center and text align left

Set auto margins on the inner div:

<div id="header" style="width:864px;">
    <div id="centered" style="margin: 0 auto; width:855px;"></div>
</div>

Alternatively, text align center the parent, and force text align left on the inner div:

<div id="header" style="width:864px;text-align: center;">
    <div id="centered" style="text-align: left; width:855px;"></div>
</div>

How to programmatically open the Permission Screen for a specific app on Android Marshmallow?

Xamarin Forms Android:

//---------------------------------------------------------
public void OpenSettings()
//---------------------------------------------------------
{
    var intent = new Intent(Android.Provider.Settings.ActionApplicationDetailsSettings,
        Android.Net.Uri.Parse("package:" + Forms.Context.PackageName));
    Forms.Context.StartActivity(intent);
}

Extending an Object in Javascript

If you haven't yet figured out a way, use the associative property of JavaScript objects to add an extend function to the Object.prototype as shown below.

Object.prototype.extend = function(obj) {
   for (var i in obj) {
      if (obj.hasOwnProperty(i)) {
         this[i] = obj[i];
      }
   }
};

You can then use this function as shown below.

var o = { member: "some member" };
var x = { extension: "some extension" };

o.extend(x);

What does %5B and %5D in POST requests stand for?

[] is replaced by %5B%5D at URL encoding time.

How to interpret "loss" and "accuracy" for a machine learning model

The lower the loss, the better a model (unless the model has over-fitted to the training data). The loss is calculated on training and validation and its interperation is how well the model is doing for these two sets. Unlike accuracy, loss is not a percentage. It is a summation of the errors made for each example in training or validation sets.

In the case of neural networks, the loss is usually negative log-likelihood and residual sum of squares for classification and regression respectively. Then naturally, the main objective in a learning model is to reduce (minimize) the loss function's value with respect to the model's parameters by changing the weight vector values through different optimization methods, such as backpropagation in neural networks.

Loss value implies how well or poorly a certain model behaves after each iteration of optimization. Ideally, one would expect the reduction of loss after each, or several, iteration(s).

The accuracy of a model is usually determined after the model parameters are learned and fixed and no learning is taking place. Then the test samples are fed to the model and the number of mistakes (zero-one loss) the model makes are recorded, after comparison to the true targets. Then the percentage of misclassification is calculated.

For example, if the number of test samples is 1000 and model classifies 952 of those correctly, then the model's accuracy is 95.2%.

enter image description here

There are also some subtleties while reducing the loss value. For instance, you may run into the problem of over-fitting in which the model "memorizes" the training examples and becomes kind of ineffective for the test set. Over-fitting also occurs in cases where you do not employ a regularization, you have a very complex model (the number of free parameters W is large) or the number of data points N is very low.

Regex for quoted string with escaping quotes

This one comes from nanorc.sample available in many linux distros. It is used for syntax highlighting of C style strings

\"(\\.|[^\"])*\"

Split function equivalent in T-SQL?

CREATE Function [dbo].[CsvToInt] ( @Array varchar(4000)) 
returns @IntTable table 
(IntValue int)
AS
begin
declare @separator char(1)
set @separator = ','
declare @separator_position int 
declare @array_value varchar(4000) 

set @array = @array + ','

while patindex('%,%' , @array) <> 0 
begin

select @separator_position = patindex('%,%' , @array)
select @array_value = left(@array, @separator_position - 1)

Insert @IntTable
Values (Cast(@array_value as int))
select @array = stuff(@array, 1, @separator_position, '')
end

Sorting Python list based on the length of the string

When you pass a lambda to sort, you need to return an integer, not a boolean. So your code should instead read as follows:

xs.sort(lambda x,y: cmp(len(x), len(y)))

Note that cmp is a builtin function such that cmp(x, y) returns -1 if x is less than y, 0 if x is equal to y, and 1 if x is greater than y.

Of course, you can instead use the key parameter:

xs.sort(key=lambda s: len(s))

This tells the sort method to order based on whatever the key function returns.

EDIT: Thanks to balpha and Ruslan below for pointing out that you can just pass len directly as the key parameter to the function, thus eliminating the need for a lambda:

xs.sort(key=len)

And as Ruslan points out below, you can also use the built-in sorted function rather than the list.sort method, which creates a new list rather than sorting the existing one in-place:

print(sorted(xs, key=len))

Git clone without .git directory

Use

git clone --depth=1 --branch=master git://someserver/somerepo dirformynewrepo
rm -rf ./dirformynewrepo/.git
  • The depth option will make sure to copy the least bit of history possible to get that repo.
  • The branch option is optional and if not specified would get master.
  • The second line will make your directory dirformynewrepo not a Git repository any more.
  • If you're doing recursive submodule clone, the depth and branch parameter don't apply to the submodules.

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

Try this:

string selected = this.ComboBox.GetItemText(this.ComboBox.SelectedItem);
MessageBox.Show(selected);

Get Android Phone Model programmatically

you can use the following code for getting the brand name and brand model of the device.

 String brand = Build.BRAND; // for getting BrandName
 String model = Build.MODEL; // for getting Model of the device

How do I multiply each element in a list by a number?

You can just use a list comprehension:

my_list = [1, 2, 3, 4, 5]
my_new_list = [i * 5 for i in my_list]

>>> print(my_new_list)
[5, 10, 15, 20, 25]

Note that a list comprehension is generally a more efficient way to do a for loop:

my_new_list = []
for i in my_list:
    my_new_list.append(i * 5)

>>> print(my_new_list)
[5, 10, 15, 20, 25]

As an alternative, here is a solution using the popular Pandas package:

import pandas as pd

s = pd.Series(my_list)

>>> s * 5
0     5
1    10
2    15
3    20
4    25
dtype: int64

Or, if you just want the list:

>>> (s * 5).tolist()
[5, 10, 15, 20, 25]

Android: ScrollView vs NestedScrollView

Other than the advantages listed in the answers given, one more advantage of NestedScrollView over ScrollView is its compatibility with CoordinatorLayout. The ScrollView does not cooperate with the CoordinatorLayout. You have to use NestedScrollView to get "scroll off-screen" behaviour for the toolbar.

Toolbar will not collapse with Scrollview as child of CoordinatorLayout

Java Enum return Int

Font.PLAIN is not an enum. It is just an int. If you need to take the value out of an enum, you can't avoid calling a method or using a .value, because enums are actually objects of its own type, not primitives.

If you truly only need an int, and you are already to accept that type-safety is lost the user may pass invalid values to your API, you may define those constants as int also:

public final class DownloadType {
    public static final int AUDIO = 0;
    public static final int VIDEO = 1;
    public static final int AUDIO_AND_VIDEO = 2;

    // If you have only static members and want to simulate a static
    // class in Java, then you can make the constructor private.
    private DownloadType() {}
}

By the way, the value field is actually redundant because there is also an .ordinal() method, so you could define the enum as:

enum DownloadType { AUDIO, VIDEO, AUDIO_AND_VIDEO }

and get the "value" using

DownloadType.AUDIO_AND_VIDEO.ordinal()

Edit: Corrected the code.. static class is not allowed in Java. See this SO answer with explanation and details on how to define static classes in Java.

How to call a View Controller programmatically?

You need to instantiate the view controller from the storyboard and then show it:

ViewControllerInfo* infoController = [self.storyboard instantiateViewControllerWithIdentifier:@"ViewControllerInfo"];
[self.navigationController pushViewController:infoController animated:YES];

This example assumes that you have a navigation controller in order to return to the previous view. You can of course also use presentViewController:animated:completion:. The main point is to have your storyboard instantiate your target view controller using the target view controller's ID.

Error:(23, 17) Failed to resolve: junit:junit:4.12

I had the same problem. Solved by adding url for missing repository in the build.gradle file:

android {
    [...]
    repositories {
        maven { url 'http://repo1.maven.org/maven2' }
    }
    [...]
}

That's it.

Drop-down menu that opens up/upward with pure css

Add bottom:100% to your #menu:hover ul li:hover ul rule

Demo 1

#menu:hover ul li:hover ul {
    position: absolute;
    margin-top: 1px;
    font: 10px;
    bottom: 100%; /* added this attribute */
}

Or better yet to prevent the submenus from having the same effect, just add this rule

Demo 2

#menu>ul>li:hover>ul { 
    bottom:100%;
}

Demo 3

source: http://jsfiddle.net/W5FWW/4/

And to get back the border you can add the following attribute

#menu>ul>li:hover>ul { 
    bottom:100%;
    border-bottom: 1px solid transparent
}

Git diff --name-only and copy that list

The following should work fine:

git diff -z --name-only commit1 commit2 | xargs -0 -IREPLACE rsync -aR REPLACE /home/changes/protected/

To explain further:

  • The -z to with git diff --name-only means to output the list of files separated with NUL bytes instead of newlines, just in case your filenames have unusual characters in them.

  • The -0 to xargs says to interpret standard input as a NUL-separated list of parameters.

  • The -IREPLACE is needed since by default xargs would append the parameters to the end of the rsync command. Instead, that says to put them where the later REPLACE is. (That's a nice tip from this Server Fault answer.)

  • The -a parameter to rsync means to preserve permissions, ownership, etc. if possible. The -R means to use the full relative path when creating the files in the destination.

Update: if you have an old version of xargs, you'll need to use the -i option instead of -I. (The former is deprecated in later versions of findutils.)

Set session variable in laravel

in Laravel 5.4

use this method:

Session::put('variableName', $value);

Extracting first n columns of a numpy matrix

I know this is quite an old question -

A = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

Let's say, you want to extract the first 2 rows and first 3 columns

A_NEW = A[0:2, 0:3]
A_NEW = [[1, 2, 3],
         [4, 5, 6]]

Understanding the syntax

A_NEW = A[start_index_row : stop_index_row, 
          start_index_column : stop_index_column)]

If one wants row 2 and column 2 and 3

A_NEW = A[1:2, 1:3]

Reference the numpy indexing and slicing article - Indexing & Slicing

jQuery check if Cookie exists, if not create it

Try this very simple:

            var cookieExist = $.cookie("status");
            if(cookieExist == "null" ){
                alert("Cookie Is Null");

            }

How to list the properties of a JavaScript object?

Object.getOwnPropertyNames(obj)

This function also shows non-enumerable properties in addition to those shown by Object.keys(obj).

In JS, every property has a few properties, including a boolean enumerable.

In general, non-enumerable properties are more "internalish" and less often used, but it is insightful to look into them sometimes to see what is really going on.

Example:

var o = Object.create({base:0})
Object.defineProperty(o, 'yes', {enumerable: true})
Object.defineProperty(o, 'not', {enumerable: false})

console.log(Object.getOwnPropertyNames(o))
// [ 'yes', 'not' ]

console.log(Object.keys(o))
// [ 'yes' ]

for (var x in o)
    console.log(x)
// yes, base

Also note how:

  • Object.getOwnPropertyNames and Object.keys don't go up the prototype chain to find base
  • for in does

More about the prototype chain here: https://stackoverflow.com/a/23877420/895245

How can I find the length of a number?

There are three way to do it.

var num = 123;
alert(num.toString().length);

better performance one (best performance in ie11)

var num = 123;
alert((num + '').length);

Math (best performance in Chrome, firefox but slowest in ie11)

var num = 123
alert(Math.floor( Math.log(num) / Math.LN10 ) + 1)

there is a jspref here http://jsperf.com/fastest-way-to-get-the-first-in-a-number/2

Python IndentationError: unexpected indent

Simply copy your script and put under """ your entire code """ ...

specify this line in a variable.. like,

a = """ your entire code """
print a.replace('    ','    ') # first 4 spaces tab second four space from space bar

print a.replace('here please press tab button it will insert some space"," here simply press space bar four times")
# here we replacing tab space by four char space as per pep 8 style guide..

now execute this code, in sublime using ctrl+b, now it will print indented code in console. that's it

How do you properly use WideCharToMultiByte

Elaborating on the answer provided by Brian R. Bondy: Here's an example that shows why you can't simply size the output buffer to the number of wide characters in the source string:

#include <windows.h>
#include <stdio.h>
#include <wchar.h>
#include <string.h>

/* string consisting of several Asian characters */
wchar_t wcsString[] = L"\u9580\u961c\u9640\u963f\u963b\u9644";

int main() 
{

    size_t wcsChars = wcslen( wcsString);

    size_t sizeRequired = WideCharToMultiByte( 950, 0, wcsString, -1, 
                                               NULL, 0,  NULL, NULL);

    printf( "Wide chars in wcsString: %u\n", wcsChars);
    printf( "Bytes required for CP950 encoding (excluding NUL terminator): %u\n",
             sizeRequired-1);

    sizeRequired = WideCharToMultiByte( CP_UTF8, 0, wcsString, -1,
                                        NULL, 0,  NULL, NULL);
    printf( "Bytes required for UTF8 encoding (excluding NUL terminator): %u\n",
             sizeRequired-1);
}

And the output:

Wide chars in wcsString: 6
Bytes required for CP950 encoding (excluding NUL terminator): 12
Bytes required for UTF8 encoding (excluding NUL terminator): 18

How to use a FolderBrowserDialog from a WPF application

VB.net translation

Module MyWpfExtensions

Public Function GetIWin32Window(this As Object, visual As System.Windows.Media.Visual) As System.Windows.Forms.IWin32Window

    Dim source As System.Windows.Interop.HwndSource = System.Windows.PresentationSource.FromVisual(Visual)
    Dim win As System.Windows.Forms.IWin32Window = New OldWindow(source.Handle)
    Return win
End Function

Private Class OldWindow
    Implements System.Windows.Forms.IWin32Window

    Public Sub New(handle As System.IntPtr)
        _handle = handle
    End Sub


    Dim _handle As System.IntPtr
    Public ReadOnly Property Handle As IntPtr Implements Forms.IWin32Window.Handle
        Get

        End Get
    End Property


End Class

End Module

Wi-Fi Direct and iOS Support

It took me a while to find out what is going on, but here is the summary. I hope this save people a lot of time.

Apple are not playing nice with Wi-Fi Direct, not in the same way that Android is. The Multipeer Connectivity Framework that Apple provides combines both BLE and WiFi Direct together and will only work with Apple devices and not any device that is using Wi-Fi Direct.

https://developer.apple.com/library/ios/documentation/MultipeerConnectivity/Reference/MultipeerConnectivityFramework/index.html

It states the following in this documentation - "The Multipeer Connectivity framework provides support for discovering services provided by nearby iOS devices using infrastructure Wi-Fi networks, peer-to-peer Wi-Fi, and Bluetooth personal area networks and subsequently communicating with those services by sending message-based data, streaming data, and resources (such as files)."

Additionally, Wi-Fi direct in this mode between i-Devices will need iPhone 5 and above.

There are apps that use a form of Wi-Fi Direct on the App Store, but these are using their own libraries.

How to drop columns using Rails migration

remove_column :table_name, :column_name

For instance:

remove_column :users, :hobby

would remove the hobby Column from the users table.

how to realize countifs function (excel) in R

Given a dataset

df <- data.frame( sex = c('M', 'M', 'F', 'F', 'M'), 
                  occupation = c('analyst', 'dentist', 'dentist', 'analyst', 'cook') )

you can subset rows

df[df$sex == 'M',] # To get all males
df[df$occupation == 'analyst',] # All analysts

etc.

If you want to get number of rows, just call the function nrow such as

nrow(df[df$sex == 'M',])