Programs & Examples On #Short filenames

How to determine if OpenSSL and mod_ssl are installed on Apache2

to verify in php command lie

 $php -i | grep openssl

How to count the number of true elements in a NumPy bool array

You have multiple options. Two options are the following.

numpy.sum(boolarr)
numpy.count_nonzero(boolarr)

Here's an example:

>>> import numpy as np
>>> boolarr = np.array([[0, 0, 1], [1, 0, 1], [1, 0, 1]], dtype=np.bool)
>>> boolarr
array([[False, False,  True],
       [ True, False,  True],
       [ True, False,  True]], dtype=bool)

>>> np.sum(boolarr)
5

Of course, that is a bool-specific answer. More generally, you can use numpy.count_nonzero.

>>> np.count_nonzero(boolarr)
5

Loop Through Each HTML Table Column and Get the Data using jQuery

When you create your table, put your td with class = "suma"

$(function(){   

   //funcion suma todo

   var sum = 0;
   $('.suma').each(function(x,y){
       sum += parseInt($(this).text());                                   
   })           
   $('#lblTotal').text(sum);   

   // funcion suma por check                                           

    $( "input:checkbox").change(function(){
    if($(this).is(':checked')){     
        $(this).parent().parent().find('td:last').addClass('suma2');
   }else{       
        $(this).parent().parent().find('td:last').removeClass('suma2');
   }    
   suma2Total();                                                           
   })                                                      

   function suma2Total(){
      var sum2 = 0;
      $('.suma2').each(function(x,y){
        sum2 += parseInt($(this).text());       
      })
      $('#lblTotal2').text(sum2);                                              
   }                                                                      
});

Ejemplo completo

Regex how to match an optional character

You have to mark the single letter as optional too:

([A-Z]{1})? +.*? +

or make the whole part optional

(([A-Z]{1}) +.*? +)?

Simplest way to download and unzip files in Node.js cross-platform?

I found success with the following, works with .zip
(Simplified here for posting: no error checking & just unzips all files to current folder)

function DownloadAndUnzip(URL){
    var unzip = require('unzip');
    var http = require('http');
    var request = http.get(URL, function(response) {
        response.pipe(unzip.Extract({path:'./'}))
    });
}

Am I trying to connect to a TLS-enabled daemon without TLS?

I tried the solutions here, and boot2docker didn't work.

My solution: Uninstall boot2docker on the Mac, install a Centos 7 VM in VirtualBox, and work with Docker inside that VM.

AJAX in Chrome sending OPTIONS instead of GET/POST/PUT/DELETE?

If it is possible pass the params through regular GET/POST with a different name and let your server side code handles it.

I had a similar issue with my own proxy to bypass CORS and I got the same error of POST->OPTION in Chrome. It was the Authorization header in my case ("x-li-format" and "X-UserName" here in your case.) I ended up passing it in a dummy format (e.g. AuthorizatinJack in GET) and I changed the code for my proxy to turn that into a header when making the call to the destination. Here it is in PHP:

if (isset($_GET['AuthorizationJack'])) {
    $request_headers[] = "Authorization: Basic ".$_GET['AuthorizationJack'];
}

Download a div in a HTML page as pdf using javascript

Yes, it's possible to To capture div as PDFs in JS. You can can check the solution provided by https://grabz.it. They have nice and clean JavaScript API which will allow you to capture the content of a single HTML element such as a div or a span.

So, yo use it you will need and app+key and the free SDK. The usage of it is as following:

Let's say you have a HTML:

<div id="features">
    <h4>Acme Camera</h4>
    <label>Price</label>$399<br />
    <label>Rating</label>4.5 out of 5
</div>
<p>Cras ut velit sed purus porttitor aliquam. Nulla tristique magna ac libero tempor, ac vestibulum felisvulput ate. Nam ut velit eget
risus porttitor tristique at ac diam. Sed nisi risus, rutrum a metus suscipit, euismod tristique nulla. Etiam venenatis rutrum risus at
blandit. In hac habitasse platea dictumst. Suspendisse potenti. Phasellus eget vehicula felis.</p>

To capture what is under the features id you will need to:

//add the sdk
<script type="text/javascript" src="grabzit.min.js"></script>
<script type="text/javascript">
//login with your key and secret. 
GrabzIt("KEY", "SECRET").ConvertURL("http://www.example.com/my-page.html",
{"target": "#features", "format": "pdf"}).Create();
</script>

You need to replace the http://www.example.com/my-page.html with your target url and #feature per your CSS selector.

That's all. Now, when the page is loaded an image screenshot will now be created in the same location as the script tag, which will contain all of the contents of the features div and nothing else.

The are other configuration and customization you can do to the div-screenshot mechanism, please check them out here

How to trim a string after a specific character in java

Assuming you just want everything before \n (or any other literal string/char), you should use indexOf() with substring():

result = result.substring(0, result.indexOf('\n'));

If you want to extract the portion before a certain regular expression, you can use split():

result = result.split(regex, 2)[0];

String result = "34.1 -118.33\n<!--ABCDEFG-->";

System.out.println(result.substring(0, result.indexOf('\n')));
System.out.println(result.split("\n", 2)[0]);
34.1 -118.33
34.1 -118.33

(Obviously \n isn't a meaningful regular expression, I just used it to demonstrate that the second approach also works.)

$_SERVER['HTTP_REFERER'] missing

From the documentation:

The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.

http://php.net/manual/en/reserved.variables.server.php

Remap values in pandas column with a dict

Adding to this question if you ever have more than one columns to remap in a data dataframe:

def remap(data,dict_labels):
    """
    This function take in a dictionnary of labels : dict_labels 
    and replace the values (previously labelencode) into the string.

    ex: dict_labels = {{'col1':{1:'A',2:'B'}}

    """
    for field,values in dict_labels.items():
        print("I am remapping %s"%field)
        data.replace({field:values},inplace=True)
    print("DONE")

    return data

Hope it can be useful to someone.

Cheers

Object creation on the stack/heap?

The two forms are the same with one exception: temporarily, the new (Object *) has an undefined value when the creation and assignment are separate. The compiler may combine them back together, since the undefined pointer is not particularly useful. This does not relate to global variables (unless the declaration is global, in which case it's still true for both forms).

Clean out Eclipse workspace metadata

One of the things that you might want to try out is starting eclipse with the -clean option. If you have chosen to have eclipse use the same workspace every time then there is nothing else you need to do after that. With that option in place the workspace should be cleaned out.

However, if you don't have a default workspace chosen, when opening up eclipse you will be prompted to choose the workspace. At this point, choose the workspace you want cleaned up.

See "How to run eclipse in clean mode" and "Keeping Eclipse running clean" for more details.

How do I clone a range of array elements to a new array?

You can do this fairly easially;

    object[] foo = new object[10];
    object[] bar = new object[7];   
    Array.Copy(foo, 3, bar, 0, 7);  

Can comments be used in JSON?

DISCLAIMER: YOUR WARRANTY IS VOID

As has been pointed out, this hack takes advantage of the implementation of the spec. Not all JSON parsers will understand this sort of JSON. Streaming parsers in particular will choke.

It's an interesting curiosity, but you should really not be using it for anything at all. Below is the original answer.


I've found a little hack that allows you to place comments in a JSON file that will not affect the parsing, or alter the data being represented in any way.

It appears that when declaring an object literal you can specify two values with the same key, and the last one takes precedence. Believe it or not, it turns out that JSON parsers work the same way. So we can use this to create comments in the source JSON that will not be present in a parsed object representation.

({a: 1, a: 2});
// => Object {a: 2}
Object.keys(JSON.parse('{"a": 1, "a": 2}')).length; 
// => 1

If we apply this technique, your commented JSON file might look like this:

{
  "api_host" : "The hostname of your API server. You may also specify the port.",
  "api_host" : "hodorhodor.com",

  "retry_interval" : "The interval in seconds between retrying failed API calls",
  "retry_interval" : 10,

  "auth_token" : "The authentication token. It is available in your developer dashboard under 'Settings'",
  "auth_token" : "5ad0eb93697215bc0d48a7b69aa6fb8b",

  "favorite_numbers": "An array containing my all-time favorite numbers",
  "favorite_numbers": [19, 13, 53]
}

The above code is valid JSON. If you parse it, you'll get an object like this:

{
    "api_host": "hodorhodor.com",
    "retry_interval": 10,
    "auth_token": "5ad0eb93697215bc0d48a7b69aa6fb8b",
    "favorite_numbers": [19,13,53]
}

Which means there is no trace of the comments, and they won't have weird side-effects.

Happy hacking!

Your content must have a ListView whose id attribute is 'android.R.id.list'

Rename the id of your ListView like this,

<ListView android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"/>

Since you are using ListActivity your xml file must specify the keyword android while mentioning to a ID.

If you need a custom ListView then instead of Extending a ListActivity, you have to simply extend an Activity and should have the same id without the keyword android.

HRESULT: 0x800A03EC on Worksheet.range

I don't understand the issue. But here is the thing that solved my issue.

Go to Excel Options > Save > Save Files in this format > Select "Excel Workbook(*.xlsx)". Previously, my WorkBooks were opening in [Compatibuility Mode] And now they are opening in normal mode. Range function works fine with that.

QComboBox - set selected item based on the item's data

You can also have a look at the method findText(const QString & text) from QComboBox; it returns the index of the element which contains the given text, (-1 if not found). The advantage of using this method is that you don't need to set the second parameter when you add an item.

Here is a little example :

/* Create the comboBox */
QComboBox   *_comboBox = new QComboBox;

/* Create the ComboBox elements list (here we use QString) */
QList<QString> stringsList;
stringsList.append("Text1");
stringsList.append("Text3");
stringsList.append("Text4");
stringsList.append("Text2");
stringsList.append("Text5");

/* Populate the comboBox */
_comboBox->addItems(stringsList);

/* Create the label */
QLabel *label = new QLabel;

/* Search for "Text2" text */
int index = _comboBox->findText("Text2");
if( index == -1 )
    label->setText("Text2 not found !");
else
    label->setText(QString("Text2's index is ")
                   .append(QString::number(_comboBox->findText("Text2"))));

/* setup layout */
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(_comboBox);
layout->addWidget(label);

angularjs directive call function specified in attribute and pass an argument to it

You can create a directive that executes a function call with params by using the attrName: "&" to reference the expression in the outer scope.

We want to replace the ng-click directive with ng-click-x:

<button ng-click-x="add(a,b)">Add</button>

If we had this scope:

$scope.a = 2;
$scope.b = 2;

$scope.add = function (a, b) {
  $scope.result = parseFloat(a) + parseFloat(b);
}

We could write our directive like so:

angular.module("ng-click-x", [])

.directive('ngClickX', [function () {

  return {

    scope: {

      // Reference the outer scope
      fn: "&ngClickX",

    },

    restrict: "A",

    link: function(scope, elem) {

      function callFn () {
        scope.$apply(scope.fn());
      }

      elem[0].addEventListener('click', callFn);
    }
  };
}]);

Here is a live demo: http://plnkr.co/edit/4QOGLD?p=info

How to add empty spaces into MD markdown readme on GitHub?

I'm surprised no one mentioned the HTML entities &ensp; and &emsp; which produce horizontal white space equivalent to the characters n and m, respectively. If you want to accumulate horizontal white space quickly, those are more efficient than &nbsp;.

  1. no space
  2.  &nbsp;
  3. &ensp;
  4. &emsp;

Along with <space> and &thinsp;, these are the five entities HTML provides for horizontal white space.

Note that except for &nbsp;, all entities allow breaking. Whatever text surrounds them will wrap to a new line if it would otherwise extend beyond the container boundary. With &nbsp; it would wrap to a new line as a block even if the text before &nbsp; could fit on the previous line.

Depending on your use case, that may be desired or undesired. For me, unless I'm dealing with things like names (John&nbsp;Doe), addresses or references (see eq.&nbsp;5), breaking as a block is usually undesired.

Best timestamp format for CSV/Excel?

The earlier suggestion to use "yyyy-MM-dd HH:mm:ss" is fine, though I believe Excel has much finer time resolution than that. I find this post rather credible (follow the thread and you'll see lots of arithmetic and experimenting with Excel), and if it's correct, you'll have your milliseconds. You can just tack on decimal places at the end, i.e. "yyyy-mm-dd hh:mm:ss.000".

You should be aware that Excel may not necessarily format the data (without human intervention) in such a way that you will see all of that precision. On my computer at work, when I set up a CSV with "yyyy-mm-dd hh:mm:ss.000" data (by hand using Notepad), I get "mm:ss.0" in the cell and "m/d/yyyy  hh:mm:ss AM/PM" in the formula bar.

For maximum information[1] conveyed in the cells without human intervention, you may want to split up your timestamp into a date portion and a time portion, with the time portion only to the second. It looks to me like Excel wants to give you at most three visible "levels" (where fractions of a second are their own level) in any given cell, and you want seven: years, months, days, hours, minutes, seconds, and fractions of a second.

Or, if you don't need the timestamp to be human-readable but you want it to be as accurate as possible, you might prefer just to store a big number (internally, Excel is just using the number of days, including fractional days, since an "epoch" date).


[1]That is, numeric information. If you want to see as much information as possible but don't care about doing calculations with it, you could make up some format which Excel will definitely parse as a string, and thus leave alone; e.g. "yyyymmdd.hhmmss.000".

Angular 2: Can't bind to 'ngModel' since it isn't a known property of 'input'

import {FormControl,FormGroup} from '@angular/forms';

import {FormsModule,ReactiveFormsModule} from '@angular/forms';

You should also add the missing ones.

Pointer arithmetic for void pointer in C

cast it to a char pointer an increment your pointer forward x bytes ahead.

String.Format for Hex

The number 0 in {0:X} refers to the position in the list or arguments. In this case 0 means use the first value, which is Blue. Use {1:X} for the second argument (Green), and so on.

colorstring = String.Format("#{0:X}{1:X}{2:X}{3:X}", Blue, Green, Red, Space);

The syntax for the format parameter is described in the documentation:

Format Item Syntax

Each format item takes the following form and consists of the following components:

{ index[,alignment][:formatString]}

The matching braces ("{" and "}") are required.

Index Component

The mandatory index component, also called a parameter specifier, is a number starting from 0 that identifies a corresponding item in the list of objects. That is, the format item whose parameter specifier is 0 formats the first object in the list, the format item whose parameter specifier is 1 formats the second object in the list, and so on.

Multiple format items can refer to the same element in the list of objects by specifying the same parameter specifier. For example, you can format the same numeric value in hexadecimal, scientific, and number format by specifying a composite format string like this: "{0:X} {0:E} {0:N}".

Each format item can refer to any object in the list. For example, if there are three objects, you can format the second, first, and third object by specifying a composite format string like this: "{1} {0} {2}". An object that is not referenced by a format item is ignored. A runtime exception results if a parameter specifier designates an item outside the bounds of the list of objects.

Alignment Component

The optional alignment component is a signed integer indicating the preferred formatted field width. If the value of alignment is less than the length of the formatted string, alignment is ignored and the length of the formatted string is used as the field width. The formatted data in the field is right-aligned if alignment is positive and left-aligned if alignment is negative. If padding is necessary, white space is used. The comma is required if alignment is specified.

Format String Component

The optional formatString component is a format string that is appropriate for the type of object being formatted. Specify a standard or custom numeric format string if the corresponding object is a numeric value, a standard or custom date and time format string if the corresponding object is a DateTime object, or an enumeration format string if the corresponding object is an enumeration value. If formatString is not specified, the general ("G") format specifier for a numeric, date and time, or enumeration type is used. The colon is required if formatString is specified.

Note that in your case you only have the index and the format string. You have not specified (and do not need) an alignment component.

How to use struct timeval to get the execution time?

Change:

struct timeval, tvalBefore, tvalAfter; /* Looks like an attempt to
                                          delcare a variable with
                                          no name. */

to:

struct timeval tvalBefore, tvalAfter;

It is less likely (IMO) to make this mistake if there is a single declaration per line:

struct timeval tvalBefore;
struct timeval tvalAfter;

It becomes more error prone when declaring pointers to types on a single line:

struct timeval* tvalBefore, tvalAfter;

tvalBefore is a struct timeval* but tvalAfter is a struct timeval.

How to find substring from string?

Use std::string and find.

std::string str = "/user/desktop/abc/post/";
bool exists = str.find("/abc/") != std::string::npos;

How do you append an int to a string in C++?

printf("Player %d", i);

(Downvote my answer all you like; I still hate the C++ I/O operators.)

:-P

How to check if memcache or memcached is installed for PHP?

this is my test function that I use to check Memcache on the server

<?php     
public function test()
 {
    // memcache test - make sure you have memcache extension installed and the deamon is up and running
    $memcache = new Memcache;
    $memcache->connect('localhost', 11211) or die ("Could not connect");

    $version = $memcache->getVersion();
    echo "Server's version: ".$version."<br/>\n";

    $tmp_object = new stdClass;
    $tmp_object->str_attr = 'test';
    $tmp_object->int_attr = 123;

    $memcache->set('key', $tmp_object, false, 10) or die ("Failed to save data at the server");
    echo "Store data in the cache (data will expire in 10 seconds)<br/>\n";

    $get_result = $memcache->get('key');
    echo "Data from the cache:<br/>\n";

    var_dump($get_result);
 }

if you see something like this

    Server's version: 1.4.5_4_gaa7839e
    Store data in the cache (data will expire in 10 seconds)
    Data from the cache:
    object(stdClass)#3 (2) { ["str_attr"]=> string(4) "test" ["int_attr"]=> int(123) }

it means that everything is okay

Cheers!

Changing background color of selected cell?

// animate between regular and selected state
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {

    [super setSelected:selected animated:animated];

    if (selected) {
        self.backgroundColor = [UIColor colorWithRed:234.0f/255 green:202.0f/255 blue:255.0f/255 alpha:1.0f];
    }
    else {
        self.backgroundColor = [UIColor clearColor];
    }
}

How to add an empty column to a dataframe?

an even simpler solution is:

df = df.reindex(columns = header_list)                

where "header_list" is a list of the headers you want to appear.

any header included in the list that is not found already in the dataframe will be added with blank cells below.

so if

header_list = ['a','b','c', 'd']

then c and d will be added as columns with blank cells

How to align linearlayout to vertical center?

For a box that appears in the center - horizontal & vertical - I got this to work with just one LinearLayout. The answer from Viswanath L was very helpful

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:background="@drawable/layout_bg"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="20dp">

    <TextView
        android:id="@+id/dialog_header"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:padding="10dp"
        android:text="Error"
        android:textColor="#000" />

    <TextView
        android:id="@+id/message_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:padding="10dp"
        android:text="Error-Message"
        android:textColor="#000" />


    <Button
        android:id="@+id/dialogButtonOK"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/message_text"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="5dp"
        android:text="Ok" />


</LinearLayout>

How can I find the length of a number?

A way for integers without banal converting to string:

var num = 9999999999; // your number
var length = 1;
while (num >= 10) {
   num /= 10;
   length++;
}
alert(length);

Android file chooser

EDIT (02 Jan 2012):

I created a small open source Android Library Project that streamlines this process, while also providing a built-in file explorer (in case the user does not have one present). It's extremely simple to use, requiring only a few lines of code.

You can find it at GitHub: aFileChooser.


ORIGINAL

If you want the user to be able to choose any file in the system, you will need to include your own file manager, or advise the user to download one. I believe the best you can do is look for "openable" content in an Intent.createChooser() like this:

private static final int FILE_SELECT_CODE = 0;

private void showFileChooser() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
    intent.setType("*/*"); 
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        startActivityForResult(
                Intent.createChooser(intent, "Select a File to Upload"),
                FILE_SELECT_CODE);
    } catch (android.content.ActivityNotFoundException ex) {
        // Potentially direct the user to the Market with a Dialog
        Toast.makeText(this, "Please install a File Manager.", 
                Toast.LENGTH_SHORT).show();
    }
}

You would then listen for the selected file's Uri in onActivityResult() like so:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case FILE_SELECT_CODE:
        if (resultCode == RESULT_OK) {
            // Get the Uri of the selected file 
            Uri uri = data.getData();
            Log.d(TAG, "File Uri: " + uri.toString());
            // Get the path
            String path = FileUtils.getPath(this, uri);
            Log.d(TAG, "File Path: " + path);
            // Get the file instance
            // File file = new File(path);
            // Initiate the upload
        }
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

The getPath() method in my FileUtils.java is:

public static String getPath(Context context, Uri uri) throws URISyntaxException {
    if ("content".equalsIgnoreCase(uri.getScheme())) {
        String[] projection = { "_data" };
        Cursor cursor = null;

        try {
            cursor = context.getContentResolver().query(uri, projection, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow("_data");
            if (cursor.moveToFirst()) {
                return cursor.getString(column_index);
            }
        } catch (Exception e) {
            // Eat it
        }
    }
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
} 

Unable to copy a file from obj\Debug to bin\Debug

After seeing a similar error in visual studios 2012 out of no where. I have found that that going to the root folder of the project and right clicking on it I unchecked read only and this error went away. Apparently TFS sometimes will made a folder read only. Hopefully this will help anyone with a similar issue. Thanks

Why can't I use a list as a dict key in python?

Just found you can change List into tuple, then use it as keys.

d = {tuple([1,2,3]): 'value'}

How to get last items of a list in Python?

a negative index will count from the end of the list, so:

num_list[-9:]

wait until all threads finish their work in java

I had similar situation , where i had to wait till all child threads complete its execution then only i could get the status result for each of them .. hence i needed to wait till all child thread completed.

below is my code where i did multi-threading using

 public static void main(String[] args) {
        List<RunnerPojo> testList = ExcelObject.getTestStepsList();//.parallelStream().collect(Collectors.toList());
        int threadCount = ConfigFileReader.getInstance().readConfig().getParallelThreadCount();
        System.out.println("Thread count is : =========  " + threadCount); // 5

        ExecutorService threadExecutor = new DriverScript().threadExecutor(testList, threadCount);


        boolean isProcessCompleted = waitUntilCondition(() -> threadExecutor.isTerminated()); // Here i used waitUntil condition 

        if (isProcessCompleted) {
            testList.forEach(x -> {
                System.out.println("Test Name: " + x.getTestCaseId());
                System.out.println("Test Status : " + x.getStatus());
                System.out.println("======= Test Steps ===== ");

                x.getTestStepsList().forEach(y -> {
                    System.out.println("Step Name: " + y.getDescription());
                    System.out.println("Test caseId : " + y.getTestCaseId());
                    System.out.println("Step Status: " + y.getResult());
                    System.out.println("\n ============ ==========");
                });
            });
        }

Below method is for distribution of list with parallel proccessing

// This method will split my list and run in a parallel process with mutliple threads
    private ExecutorService threadExecutor(List<RunnerPojo> testList, int threadSize) {
        ExecutorService exec = Executors.newFixedThreadPool(threadSize);
        testList.forEach(tests -> {
            exec.submit(() -> {
                driverScript(tests);
            });
        });
        exec.shutdown();
        return exec;
    }

This is my wait until method: here you can wait till your condition satisfies within do while loop . in my case i waited for some max timeout . this will keep checking until your threadExecutor.isTerminated() is true with polling period of 5 sec.

    static boolean waitUntilCondition(Supplier<Boolean> function) {
        Double timer = 0.0;
        Double maxTimeOut = 20.0;

        boolean isFound;
        do {
            isFound = function.get();
            if (isFound) {
                break;
            } else {
                try {
                    Thread.sleep(5000); // Sleeping for 5 sec (main thread will sleep for 5 sec)
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                timer++;
                System.out.println("Waiting for condition to be true .. waited .." + timer * 5 + " sec.");
            }
        } while (timer < maxTimeOut + 1.0);

        return isFound;
    }

Determining complexity for recursive functions (Big O notation)

One of the best ways I find for approximating the complexity of the recursive algorithm is drawing the recursion tree. Once you have the recursive tree:

Complexity = length of tree from root node to leaf node * number of leaf nodes
  1. The first function will have length of n and number of leaf node 1 so complexity will be n*1 = n
  2. The second function will have the length of n/5 and number of leaf nodes again 1 so complexity will be n/5 * 1 = n/5. It should be approximated to n

  3. For the third function, since n is being divided by 5 on every recursive call, length of recursive tree will be log(n)(base 5), and number of leaf nodes again 1 so complexity will be log(n)(base 5) * 1 = log(n)(base 5)

  4. For the fourth function since every node will have two child nodes, the number of leaf nodes will be equal to (2^n) and length of the recursive tree will be n so complexity will be (2^n) * n. But since n is insignificant in front of (2^n), it can be ignored and complexity can be only said to be (2^n).

  5. For the fifth function, there are two elements introducing the complexity. Complexity introduced by recursive nature of function and complexity introduced by for loop in each function. Doing the above calculation, the complexity introduced by recursive nature of function will be ~ n and complexity due to for loop n. Total complexity will be n*n.

Note: This is a quick and dirty way of calculating complexity(nothing official!). Would love to hear feedback on this. Thanks.

ClassCastException, casting Integer to Double

Well the code you've shown doesn't actually include adding any Integers to the ArrayList - but if you do know that you've got integers, you can use:

sum = (double) ((Integer) marks.get(i)).intValue();

That will convert it to an int, which can then be converted to double. You can't just cast directly between the boxed classes.

Note that if you can possibly use generics for your ArrayList, your code will be clearer.

Execute a large SQL script (with GO commands)

The "GO" batch separator keyword is actually used by SQL Management Studio itself, so that it knows where to terminate the batches it is sending to the server, and it is not passed to SQL server. You can even change the keyword in Management Studio, should you so desire.

T-SQL to list all the user mappings with database roles/permissions for a Login

Did you sort this? I just found this code here:

http://www.pythian.com/news/29665/httpconsultingblogs-emc-comjamiethomsonarchive20070209sql-server-2005_3a00_-view-all-permissions-_2800_2_2900_-aspx/

I think I'll need to do a bit of tweaking, but essentially this has sorted it for me!

I hope it does for you too!

J

OS X cp command in Terminal - No such file or directory

I know this question has already been answered, but another option is simply to open the destination and source folders in Finder and then drag and drop them into the terminal. The paths will automatically be copied and properly formatted (thus negating the need to actually figure out proper file names/extensions).

I have to do over-network copies between Mac and Windows machines, sometimes fairly deep down in filetrees, and have found this the most effective way to do so.

So, as an example:

cp -r [drag and drop source folder from finder] [drag and drop destination folder from finder]

What is the documents directory (NSDocumentDirectory)?

Your app only (on a non-jailbroken device) runs in a "sandboxed" environment. This means that it can only access files and directories within its own contents. For example Documents and Library.

See the iOS Application Programming Guide.

To access the Documents directory of your applications sandbox, you can use the following:

iOS 8 and newer, this is the recommended method

+ (NSURL *)applicationDocumentsDirectory
{
     return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

if you need to support iOS 7 or earlier

+ (NSString *) applicationDocumentsDirectory 
{    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = paths.firstObject;
    return basePath;
}

This Documents directory allows you to store files and subdirectories your app creates or may need.

To access files in the Library directory of your apps sandbox use (in place of paths above):

[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0]

NodeJS w/Express Error: Cannot GET /

Where is your get method for "/"?

Also you cant serve static html directly in Express.First you need to configure it.

app.configure(function(){
  app.set('port', process.env.PORT || 3000);  
  app.set("view options", {layout: false});  //This one does the trick for rendering static html
  app.engine('html', require('ejs').renderFile); 
  app.use(app.router);

});

Now add your get method.

app.get('/', function(req, res) {
  res.render('default.htm');
});

Android - Back button in the title bar

I saw so much complexes answer, so this is my code. Working here. You can achieve this in two ways.

1) Stardard android compatiblity

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.NavUtils;

import android.view.MenuItem;
import android.view.View;

public class EditDiscoveryActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_discovery);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        /*toolbar.setNavigationIcon(R.drawable.ic_arrow_white_24dp);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });*/
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }

}

2) Use a custom icon

If you want to use code in comments you just have to add this file in drawable, called ic_arrow_white_24dp.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24.0"
    android:viewportHeight="24.0">
    <path
        android:fillColor="#ffffff"
        android:pathData="M20,11H7.83l5.59,-5.59L12,4l-8,8 8,8 1.41,-1.41L7.83,13H20v-2z"/>
    </vector>

With this code.

toolbar.setNavigationIcon(R.drawable.ic_arrow_white_24dp);
            toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    finish();
                }
            });

Hope it will helps some people here !

Select entries between dates in doctrine 2

I believe the correct way of doing it would be to use query builder expressions:

$now = new DateTimeImmutable();
$thirtyDaysAgo = $now->sub(new \DateInterval("P30D"));
$qb->select('e')
   ->from('Entity','e')
   ->add('where', $qb->expr()->between(
            'e.datefield',
            ':from',
            ':to'
        )
    )
   ->setParameters(array('from' => $thirtyDaysAgo, 'to' => $now));

http://docs.doctrine-project.org/en/latest/reference/query-builder.html#the-expr-class

Edit: The advantage this method has over any of the other answers here is that it's database software independent - you should let Doctrine handle the date type as it has an abstraction layer for dealing with this sort of thing.

If you do something like adding a string variable in the form 'Y-m-d' it will break when it goes to a database platform other than MySQL, for example.

How do I generate a stream from a string?

I used a mix of answers like this:

public static Stream ToStream(this string str, Encoding enc = null)
{
    enc = enc ?? Encoding.UTF8;
    return new MemoryStream(enc.GetBytes(str ?? ""));
}

And then I use it like this:

String someStr="This is a Test";
Encoding enc = getEncodingFromSomeWhere();
using (Stream stream = someStr.ToStream(enc))
{
    // Do something with the stream....
}

Fastest way to check a string contain another substring in JavaScript?

You have three possibilites:

  1. Regular expression:

     (new RegExp('word')).test(str)
     // or
     /word/.test(str)
    
  2. indexOf:

     str.indexOf('word') !== -1
    
  3. includes:

     str.includes('word')
    

Regular expressions seem to be faster (at least in Chrome 10).

Performance test - short haystack
Performance test - long haystack


**Update 2011:**

It cannot be said with certainty which method is faster. The differences between the browsers is enormous. While in Chrome 10 indexOf seems to be faster, in Safari 5, indexOf is clearly slower than any other method.

You have to see and try for your self. It depends on your needs. For example a case-insensitive search is way faster with regular expressions.


Update 2018:

Just to save people from running the tests themselves, here are the current results for most common browsers, the percentages indicate performance increase over the next fastest result (which varies between browsers):

Chrome: indexOf (~98% faster) <-- wow
Firefox: cached RegExp (~18% faster)
IE11: cached RegExp(~10% faster)
Edge: indexOf (~18% faster)
Safari: cached RegExp(~0.4% faster)

Note that cached RegExp is: var r = new RegExp('simple'); var c = r.test(str); as opposed to: /simple/.test(str)

Java: Local variable mi defined in an enclosing scope must be final or effectively final

As I can see the array is of String only.For each loop can be used to get individual element of the array and put them in local inner class for use.

Below is the code snippet for it :

     //WorkAround 
    for (String color : colors ){

String pos = Character.toUpperCase(color.charAt(0)) + color.substring(1);
JMenuItem Jmi =new JMenuItem(pos);
Jmi.setIcon(new IconA(color));

Jmi.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JMenuItem item = (JMenuItem) e.getSource();
            IconA icon = (IconA) item.getIcon();
            // HERE YOU USE THE String color variable and no errors!!!
            Color kolorIkony = getColour(color); 
            textArea.setForeground(kolorIkony);
        }
    });

    mnForeground.add(Jmi);
}

}

how to make log4j to write to the console as well

Write the root logger as below for logging on both console and FILE

log4j.rootLogger=ERROR,console,FILE

And write the respective definitions like Target, Layout, and ConversionPattern (MaxFileSize for file etc).

Core Data: Quickest way to delete all instances of an entity

    func deleteAll(entityName: String) {

    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
    deleteRequest.resultType = .resultTypeObjectIDs
    guard let context = self.container?.viewContext
        else { print("error in deleteAll")
            return }

    do {
        let result = try context.execute(deleteRequest) as? NSBatchDeleteResult
        let objectIDArray = result?.result as? [NSManagedObjectID]
        let changes: [AnyHashable : Any] = [NSDeletedObjectsKey : objectIDArray as Any]
        NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes, into: [context])
    } catch {
        print(error.localizedDescription)
    }
}

Invalid application of sizeof to incomplete type with a struct

Your error is also shown when trying to access the sizeof() of an non-initialized extern array:

extern int a[];
sizeof(a);
>> error: invalid application of 'sizeof' to incomplete type 'int[]'

Note that you would get an array size missing error without the extern keyword.

What are the Android SDK build-tools, platform-tools and tools? And which version should be used?

The right answer is

Decoupled the build-specific components of the Android SDK from the platform-tools component, so that the build tools can be updated independently of the integrated development environment (IDE) components.

link (expand Revision 17)

convert streamed buffers to utf8-string

var fs = require("fs");

function readFileLineByLine(filename, processline) {
    var stream = fs.createReadStream(filename);
    var s = "";
    stream.on("data", function(data) {
        s += data.toString('utf8');
        var lines = s.split("\n");
        for (var i = 0; i < lines.length - 1; i++)
            processline(lines[i]);
        s = lines[lines.length - 1];
    });

    stream.on("end",function() {
        var lines = s.split("\n");
        for (var i = 0; i < lines.length; i++)
            processline(lines[i]);
    });
}

var linenumber = 0;
readFileLineByLine(filename, function(line) {
    console.log(++linenumber + " -- " + line);
});

Uninstall all installed gems, in OSX?

Rubygems >= 2.1.0

gem uninstall -aIx

a removes all versions
I ignores dependencies
x includes executables

Rubgems < 2.1.0

for i in `gem list --no-versions`; do gem uninstall -aIx $i; done

Django request get parameters

You can use [] to extract values from a QueryDict object like you would any ordinary dictionary.

# HTTP POST variables
request.POST['section'] # => [39]
request.POST['MAINS'] # => [137]

# HTTP GET variables
request.GET['section'] # => [39]
request.GET['MAINS'] # => [137]

# HTTP POST and HTTP GET variables (Deprecated since Django 1.7)
request.REQUEST['section'] # => [39]
request.REQUEST['MAINS'] # => [137]

c# dictionary How to add multiple values for single key?

You could use my implementation of a multimap, which derives from a Dictionary<K, List<V>>. It is not perfect, however it does a good job.

/// <summary>
/// Represents a collection of keys and values.
/// Multiple values can have the same key.
/// </summary>
/// <typeparam name="TKey">Type of the keys.</typeparam>
/// <typeparam name="TValue">Type of the values.</typeparam>
public class MultiMap<TKey, TValue> : Dictionary<TKey, List<TValue>>
{

    public MultiMap()
        : base()
    {
    }

    public MultiMap(int capacity)
        : base(capacity)
    {
    }

    /// <summary>
    /// Adds an element with the specified key and value into the MultiMap. 
    /// </summary>
    /// <param name="key">The key of the element to add.</param>
    /// <param name="value">The value of the element to add.</param>
    public void Add(TKey key, TValue value)
    {
        List<TValue> valueList;

        if (TryGetValue(key, out valueList)) {
            valueList.Add(value);
        } else {
            valueList = new List<TValue>();
            valueList.Add(value);
            Add(key, valueList);
        }
    }

    /// <summary>
    /// Removes first occurence of an element with a specified key and value.
    /// </summary>
    /// <param name="key">The key of the element to remove.</param>
    /// <param name="value">The value of the element to remove.</param>
    /// <returns>true if the an element is removed;
    /// false if the key or the value were not found.</returns>
    public bool Remove(TKey key, TValue value)
    {
        List<TValue> valueList;

        if (TryGetValue(key, out valueList)) {
            if (valueList.Remove(value)) {
                if (valueList.Count == 0) {
                    Remove(key);
                }
                return true;
            }
        }
        return false;
    }

    /// <summary>
    /// Removes all occurences of elements with a specified key and value.
    /// </summary>
    /// <param name="key">The key of the elements to remove.</param>
    /// <param name="value">The value of the elements to remove.</param>
    /// <returns>Number of elements removed.</returns>
    public int RemoveAll(TKey key, TValue value)
    {
        List<TValue> valueList;
        int n = 0;

        if (TryGetValue(key, out valueList)) {
            while (valueList.Remove(value)) {
                n++;
            }
            if (valueList.Count == 0) {
                Remove(key);
            }
        }
        return n;
    }

    /// <summary>
    /// Gets the total number of values contained in the MultiMap.
    /// </summary>
    public int CountAll
    {
        get
        {
            int n = 0;

            foreach (List<TValue> valueList in Values) {
                n += valueList.Count;
            }
            return n;
        }
    }

    /// <summary>
    /// Determines whether the MultiMap contains an element with a specific
    /// key / value pair.
    /// </summary>
    /// <param name="key">Key of the element to search for.</param>
    /// <param name="value">Value of the element to search for.</param>
    /// <returns>true if the element was found; otherwise false.</returns>
    public bool Contains(TKey key, TValue value)
    {
        List<TValue> valueList;

        if (TryGetValue(key, out valueList)) {
            return valueList.Contains(value);
        }
        return false;
    }

    /// <summary>
    /// Determines whether the MultiMap contains an element with a specific value.
    /// </summary>
    /// <param name="value">Value of the element to search for.</param>
    /// <returns>true if the element was found; otherwise false.</returns>
    public bool Contains(TValue value)
    {
        foreach (List<TValue> valueList in Values) {
            if (valueList.Contains(value)) {
                return true;
            }
        }
        return false;
    }

}

Note that the Add method looks if a key is already present. If the key is new, a new list is created, the value is added to the list and the list is added to the dictionary. If the key was already present, the new value is added to the existing list.

How to print object array in JavaScript?

You can just use the following syntax and the object will be fully shown in the console:

console.log('object evt: %O', object);

I use Chrome browser don't know if this is adaptable for other browsers.

Running Windows batch file commands asynchronously

Combining a couple of the previous answers, you could try start /b cmd /c foo.exe.

For a trivial example, if you wanted to print out the versions of java/groovy/grails/gradle, you could do this in a batch file:

@start /b cmd /c java -version
@start /b cmd /c gradle -version
@start /b cmd /c groovy -version
@start /b cmd /c grails -version

If you have something like Process Explorer (Sysinternals), you will see a few child cmd.exe processes each with a java process (as per the above commands). The output will print to the screen in whatever order they finish.

start /b :  Start application without creating a new window. The
             application has ^C handling ignored. Unless the application
             enables ^C processing, ^Break is the only way to interrupt
             the application

cmd /c : Carries out the command specified by string and then terminates

Declaring multiple variables in JavaScript

The maintainability issue can be pretty easily overcome with a little formatting, like such:

let
  my_var1 = 'foo',
  my_var2 = 'bar',
  my_var3 = 'baz'
;

I use this formatting strictly as a matter of personal preference. I skip this format for single declarations, of course, or where it simply gums up the works.

Socket.IO - how do I get a list of connected sockets/clients?

I think we can access the socket object from the server, and you can assign the nickname, and point its socket id,

io.sockets.on('connection',function(socket){ 
    io.sockets.sockets['nickname'] = socket.id;
    client.on("chat", function(data) {      
        var sock_id = io.sockets.sockets['nickname']
        io.sockets.sockets[sock_id].emit("private", "message");
    });    
});

On disconnect please remove the nickname from io.sockets.sockets.

C# Creating and using Functions

static void Main(string[] args)
    {
        Console.WriteLine("geef een leeftijd");
        int a = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("geef een leeftijd");
        int b = Convert.ToInt32(Console.ReadLine());

        int einde = Sum(a, b);
        Console.WriteLine(einde);
    }
    static int Sum(int x, int y)
    {
        int result = x + y;
        return result;

How to Troubleshoot Intermittent SQL Timeout Errors

Performance problems boil down to CPU, IO, or Lock contention. It sounds like you have ruled out IO. I would guess CPU is not a problem since this is a database, not a number cruncher. So, that leaves lock contention.

If you can execute a sp_who2 while the queries are timing out, you can use the BlkBy column to trace back to the holding the lock that everyone else is waiting on. Since this is only happening a few times a day, you may have trouble catching enough data if you are running this manually, so I suggest you rig up an automated system to dump this output on a regular basis, or maybe to be triggered by the application timeout exceptions. You can also use the Activity Monitor to watch the degradation of query responsiveness in real-time, as suggested by peer.

Once you find the long-running query and the application that executes it, you can immediately resolve the domino of timeouts by reducing the timeout for that single application below all the others (right now, it must be longer). Then, you should inspect the code to determine a better solution. You could reduce the time the lock is held by committing the transaction sooner within a sproc, or reduce the lock required by the reading query with hints such as NOLOCK or UPDLOCK.

Here's some more reading on sp_who2: http://sqlserverplanet.com/dba/using-sp_who2/

And query hints: http://msdn.microsoft.com/en-us/library/ms181714.aspx http://msdn.microsoft.com/en-us/library/ms187373.aspx

sqlite copy data from one table to another

If you have data already present in both the tables and you want to update a table column values based on some condition then use this

UPDATE Table1 set Name=(select t2.Name from Table2 t2 where t2.id=Table1.id)

Equivalent of LIMIT for DB2

@elcool's solution is a smart idea, but you need to know total number of rows (which can even change while you are executing the query!). So I propose a modified version, which unfortunately needs 3 subqueries instead of 2:

select * from (
    select * from (
        select * from MYLIB.MYTABLE
        order by MYID asc 
        fetch first {last} rows only 
        ) I 
    order by MYID desc
    fetch first {length} rows only
    ) II
order by MYID asc

where {last} should be replaced with row number of the last record I need and {length} should be replaced with the number of rows I need, calculated as last row - first row + 1.

E.g. if I want rows from 10 to 25 (totally 16 rows), {last} will be 25 and {length} will be 25-10+1=16.

No resource found that matches the given name '@style/ Theme.Holo.Light.DarkActionBar'

You can change this one parent attribute ="android:style/Theme.Holo.Light.DarkActionBar"

I can't access http://localhost/phpmyadmin/

I had the same problem. Couldn't access http://localhost/joomla neither.
and I did not quite understand the other answers.
The simple solution for me:

  1. stop all actions in xampp (I had apache and mysql running. apache on port 80 and 7000something)
  2. quit firefox
  3. restart the actions (apache and mysql)
  4. restart firefox.
  5. open http://localhost/phpmyadmin (or http://localhost/joomla - whatever it be)
  6. voila!

Now apache runs on port 80 and 443 and mysql on 3306.

concatenate char array in C

First copy the current string to a larger array with strcpy, then use strcat.

For example you can do:

char* str = "Hello";
char dest[12];

strcpy( dest, str );
strcat( dest, ".txt" );

How can I use nohup to run process as a background process in linux?

  • Use screen: Start screen, start your script, press Ctrl+A, D. Reattach with screen -r.

  • Make a script that takes your "1" as a parameter, run nohup yourscript:

    #!/bin/bash
    (time bash executeScript $1 input fileOutput $> scrOutput) &> timeUse.txt
    

Are there bookmarks in Visual Studio Code?

Both VS Code extensions can be used:

  1. 'Bookmarks'
  2. 'Numbered Bookmarks'

Personally, I'm suggesting: Numbered Bookmarks, with 'navigate through all files' option:

  1. ctrl + Shift + P in VS Code
  2. In newly open field, type: Open User Settings
  3. Paste this key/value: "numberedBookmarks.navigateThroughAllFiles": "allowDuplicates" (allow duplicates of bookmarks),
  4. Or, paste this key/value: "numberedBookmarks.navigateThroughAllFiles": "replace"

NOTE

Either way, be careful with shortcuts (Ctrl+1, Ctrl+Shift+1,..) that are already assigned.

Personally, mine were in 2 conflicts, with:

  1. VS Code shortcuts, that already exists,
  2. Ditto clipboard (I've got paste on each call of bookmark)

Google Play app description formatting

As a matter of fact, HTML character entites also work : http://www.w3.org/TR/html4/sgml/entities.html.

It lets you insert special characters like bullets '•' (&bull;), '™' (&trade;), ... the HTML way.

Note that you can also (and probably should) type special characters directly in the form fields if you can enter international characters.

=> one consideration here is whether or not you care about third-party sites that collect data on your app from Google Play : some might simply take it as HTML content, others might insert it in a native application that just understand plain Unicode...

How do I get the month and day with leading 0's in SQL? (e.g. 9 => 09)

select right('0000' + cast(datepart(year, GETDATE()) as varchar(4)), 4) + '-'+ + right('00' + cast(datepart(month, GETDATE()) as varchar(2)), 2) + '-'+ + right('00' + cast(datepart(day, getdate()) as varchar(2)), 2) as YearMonthDay

Differences between key, superkey, minimal superkey, candidate key and primary key

I have always found it difficult to remember all the keys; so I keep the below notes handy, hope they help someone! Let me know if it can be improved.

  • Key: An attribute or combination of attributes that uniquely identify an entity/record in a relational table.

  • PK: A single key that is unique and not-null. It is one of the candidate keys.

  • Foreign Key: FK is a key in one table (child) that uniquely identifies a row of another table (parent). A FK is not-unique in the child table. It is a candidate key in the parent table. Referential integrity is maintained as the value in FK is present as a value in PK in parent table else it is NULL.

  • Unique Key: A unique key that may or may not be NULL

  • Natural key: PK in OLTP. It may be a PK in OLAP.

  • Surrogate Key: It is the Surrogate PK in OLAP acting as the substitute of the PK in OLTP. Artificial key generated internally in OLAP.

  • Composite Key: PK made up of multiple attributes

  • SuperKey: A key that can be uniquely used to identify a database record, that may contain extra attributes that are not necessary to uniquely identify records.

  • Candidate Key: A candidate key can be uniquely used to identify a database record without any extraneous data. They are Not Null and unique. It is a minimal super-key.

  • Alternate Key: A candidate key that is not the primary key is called an alternate key.

  • Candidate Key/s with Extraneous data: Consider that can be used to identify a record in the Employee table but candidate key alone is sufficient for this task. So becomes the extraneous data.

Note that the PK, Foreign Key, Unique Key, Natural key, Surrogate Key, Composite Key are defined as Database objects; where the Natural key is a PK in the OLTP and could be a PK in the target OLAP. For the rest of the keys, it's up to the DB designer/architect to decide whether unique/not-null/referential integrity constraints need to enforced or not.

Below I have tried to use set theory to simplify the representation of the membership of the keys w.r.t. each other.

key = { All of the below keys   }
PK  = { PK  }
Foreign Key = { Key with Not Null constraint    }
Unique Key  = { {Candidate Key/s}, {attributes containing NULL} }
Natural key = { PK  }
Surrogate Key   = { PK  }
Composite Key   = { PK  }
Super Key   = { {Candidate Key/s}, {Candidate Key/s with Extraneous data}   }
Candidate Key   = { PK, {Alternate Key/s}   }
Alternate Key   = { {Candidate Keys} - PK   }
Candidate Key/s with Extraneous data    = {     }

I have summarized it below:

Database Keys

Notes: an-overview-of-the-database-keys-primary-key-composite-key-surrogate-key-et-al

How To: Execute command line in C#, get STD OUT results

Just for fun, here's my completed solution for getting PYTHON output - under a button click - with error reporting. Just add a button called "butPython" and a label called "llHello"...

    private void butPython(object sender, EventArgs e)
    {
        llHello.Text = "Calling Python...";
        this.Refresh();
        Tuple<String,String> python = GoPython(@"C:\Users\BLAH\Desktop\Code\Python\BLAH.py");
        llHello.Text = python.Item1; // Show result.
        if (python.Item2.Length > 0) MessageBox.Show("Sorry, there was an error:" + Environment.NewLine + python.Item2);
    }

    public Tuple<String,String> GoPython(string pythonFile, string moreArgs = "")
    {
        ProcessStartInfo PSI = new ProcessStartInfo();
        PSI.FileName = "py.exe";
        PSI.Arguments = string.Format("\"{0}\" {1}", pythonFile, moreArgs);
        PSI.CreateNoWindow = true;
        PSI.UseShellExecute = false;
        PSI.RedirectStandardError = true;
        PSI.RedirectStandardOutput = true;
        using (Process process = Process.Start(PSI))
            using (StreamReader reader = process.StandardOutput)
            {
                string stderr = process.StandardError.ReadToEnd(); // Error(s)!!
                string result = reader.ReadToEnd(); // What we want.
                return new Tuple<String,String> (result,stderr); 
            }
    }

CSS property to pad text inside of div

I see a lot of answers here that have you subtracting from the width of the div and/or using box-sizing, but all you need to do is apply the padding the child elements of the div in question. So, for example, if you have some markup like this:

<div id="container">
    <p id="text">Find Agents</p>
</div>

All you need to do is apply this CSS:

#text {
    padding: 10px;
}

Here is a fiddle showing the difference: http://jsfiddle.net/CHCVF/2/

Or, better yet, if you have multiple elements and don't feel like giving them all the same class, you can do something like this:

.container * {
    padding: 5px 10px;
}

Which will select all of the child elements and assign them the padding you want. Here is a fiddle of that in action: http://jsfiddle.net/CHCVF/3/

Linux Script to check if process is running and act on the result

The 'pidof' command will not display pids of shell/perl/python scripts. So to find the process id’s of my Perl script I had to use the -x option i.e. 'pidof -x perlscriptname'

Impact of Xcode build options "Enable bitcode" Yes/No

From the docs

  • can I use the above method without any negative impact and without compromising a future appstore submission?

Bitcode will allow apple to optimise the app without you having to submit another build. But, you can only enable this feature if all frameworks and apps in the app bundle have this feature enabled. Having it helps, but not having it should not have any negative impact.

  • What does the ENABLE_BITCODE actually do, will it be a non-optional requirement in the future?

For iOS apps, bitcode is the default, but optional. If you provide bitcode, all apps and frameworks in the app bundle need to include bitcode. For watchOS apps, bitcode is required.

  • Are there any performance impacts if I enable / disable it?

The App Store and operating system optimize the installation of iOS and watchOS apps by tailoring app delivery to the capabilities of the user’s particular device, with minimal footprint. This optimization, called app thinning, lets you create apps that use the most device features, occupy minimum disk space, and accommodate future updates that can be applied by Apple. Faster downloads and more space for other apps and content provides a better user experience.

There should not be any performance impacts.

MySQL Orderby a number, Nulls last

Why don't you order by NULLS LAST?

SELECT * 
FROM tablename
WHERE visible = 1 
ORDER BY position ASC NULLS LAST, id DESC 

What is the best way to implement nested dictionaries?

I find setdefault quite useful; It checks if a key is present and adds it if not:

d = {}
d.setdefault('new jersey', {}).setdefault('mercer county', {})['plumbers'] = 3

setdefault always returns the relevant key, so you are actually updating the values of 'd' in place.

When it comes to iterating, I'm sure you could write a generator easily enough if one doesn't already exist in Python:

def iterateStates(d):
    # Let's count up the total number of "plumbers" / "dentists" / etc.
    # across all counties and states
    job_totals = {}

    # I guess this is the annoying nested stuff you were talking about?
    for (state, counties) in d.iteritems():
        for (county, jobs) in counties.iteritems():
            for (job, num) in jobs.iteritems():
                # If job isn't already in job_totals, default it to zero
                job_totals[job] = job_totals.get(job, 0) + num

    # Now return an iterator of (job, number) tuples
    return job_totals.iteritems()

# Display all jobs
for (job, num) in iterateStates(d):
    print "There are %d %s in total" % (job, num)

How to print multiple variable lines in Java

Suppose we have variable date , month and year then we can write it in the java like this.

int date=15,month=4,year=2016;
System.out.println(date+ "/"+month+"/"+year);

output of this will be like below:

15/4/2016

Mysql Compare two datetime fields

Your query apparently returned all correct dates, even considering the time.

If you're still not happy with the results, give DATEDIFF a shot and look for negaive/positive results between the two dates.

Make sure your mydate column is a datetime type.

How to execute a command prompt command from python

how about simply:

import os
os.system('dir c:\\')

Is it possible to remove inline styles with jQuery?

The easiest way to remove inline styles (generated by jQuery) would be:

$(this).attr("style", "");

The inline code should disappear and your object should adapt the style predefined in your CSS files.

Worked for me!

Why is document.write considered a "bad practice"?

Pro:

  • It's the easiest way to embed inline content from an external (to your host/domain) script.
  • You can overwrite the entire content in a frame/iframe. I used to use this technique a lot for menu/navigation pieces before more modern Ajax techniques were widely available (1998-2002).

Con:

  • It serializes the rendering engine to pause until said external script is loaded, which could take much longer than an internal script.
  • It is usually used in such a way that the script is placed within the content, which is considered bad-form.

multiple plot in one figure in Python

This is very simple to do:

import matplotlib.pyplot as plt

plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.legend(loc='best')
plt.show()

You can keep adding plt.plot as many times as you like. As for line type, you need to first specify the color. So for blue, it's b. And for a normal line it's -. An example would be:

plt.plot(total_lengths, sort_times_heap, 'b-', label="Heap")

Concatenate a NumPy array to another NumPy array

I had the same issue, and I couldn't comment on @Sven Marnach answer (not enough rep, gosh I remember when Stackoverflow first started...) anyway.

Adding a list of random numbers to a 10 X 10 matrix.

myNpArray = np.zeros([1, 10])
for x in range(1,11,1):
    randomList = [list(np.random.randint(99, size=10))]
    myNpArray = np.vstack((myNpArray, randomList))
myNpArray = myNpArray[1:]

Using np.zeros() an array is created with 1 x 10 zeros.

array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])

Then a list of 10 random numbers is created using np.random and assigned to randomList. The loop stacks it 10 high. We just have to remember to remove the first empty entry.

myNpArray

array([[31., 10., 19., 78., 95., 58.,  3., 47., 30., 56.],
       [51., 97.,  5., 80., 28., 76., 92., 50., 22., 93.],
       [64., 79.,  7., 12., 68., 13., 59., 96., 32., 34.],
       [44., 22., 46., 56., 73., 42., 62.,  4., 62., 83.],
       [91., 28., 54., 69., 60., 95.,  5., 13., 60., 88.],
       [71., 90., 76., 53., 13., 53., 31.,  3., 96., 57.],
       [33., 87., 81.,  7., 53., 46.,  5.,  8., 20., 71.],
       [46., 71., 14., 66., 68., 65., 68., 32.,  9., 30.],
       [ 1., 35., 96., 92., 72., 52., 88., 86., 94., 88.],
       [13., 36., 43., 45., 90., 17., 38.,  1., 41., 33.]])

So in a function:

def array_matrix(random_range, array_size):
    myNpArray = np.zeros([1, array_size])
    for x in range(1, array_size + 1, 1):
        randomList = [list(np.random.randint(random_range, size=array_size))]
        myNpArray = np.vstack((myNpArray, randomList))
    return myNpArray[1:]

a 7 x 7 array using random numbers 0 - 1000

array_matrix(1000, 7)

array([[621., 377., 931., 180., 964., 885., 723.],
       [298., 382., 148., 952., 430., 333., 956.],
       [398., 596., 732., 422., 656., 348., 470.],
       [735., 251., 314., 182., 966., 261., 523.],
       [373., 616., 389.,  90., 884., 957., 826.],
       [587., 963.,  66., 154., 111., 529., 945.],
       [950., 413., 539., 860., 634., 195., 915.]])

List all column except for one in R

You can index and use a negative sign to drop the 3rd column:

data[,-3]

Or you can list only the first 2 columns:

data[,c("c1", "c2")]
data[,1:2]

Don't forget the comma and referencing data frames works like this: data[row,column]

Angularjs -> ng-click and ng-show to show a div

remove class hideByDefault. Div will remain hidden itself till value of myvalue is false.

Iterating over a numpy array

If you only need the indices, you could try numpy.ndindex:

>>> a = numpy.arange(9).reshape(3, 3)
>>> [(x, y) for x, y in numpy.ndindex(a.shape)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

How to make a launcher

They're examples provided by the Android team, if you've already loaded Samples, you can import Home screen replacement sample by following these steps.

File > New > Other >Android > Android Sample Project > Android x.x > Home > Finish

But if you do not have samples loaded, then download it using the below steps

Windows > Android SDK Manager > chooses "Sample for SDK" for SDK you need it > Install package > Accept License > Install

Converting dd/mm/yyyy formatted string to Datetime

use DateTime.ParseExact

string strDate = "24/01/2013";
DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", null)

null will use the current culture, which is somewhat dangerous. Try to supply a specific culture

DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", CultureInfo.InvariantCulture)

Preserve line breaks in angularjs

It's so simple with CSS (it works, I swear).

.angular-with-newlines {
  white-space: pre;
}
  • Look ma! No extra HTML tags!

take(1) vs first()

It turns out there's a very important distinction between the two methods: first() will emit an error if the stream completes before a value is emitted. Or, if you've provided a predicate (i.e. first(value => value === 'foo')), it will emit an error if the stream completes before a value that passes the predicate is emitted.

take(1), on the other hand, will happily carry on if a value is never emitted from the stream. Here's a simple example:

const subject$ = new Subject();

// logs "no elements in sequence" when the subject completes
subject$.first().subscribe(null, (err) => console.log(err.message));

// never does anything
subject$.take(1).subscribe(console.log);

subject$.complete();

Another example, using a predicate:

const observable$ = of(1, 2, 3);

// logs "no elements in sequence" when the observable completes
observable$
 .first((value) => value > 5)
 .subscribe(null, (err) => console.log(err.message));

// the above can also be written like this, and will never do
// anything because the filter predicate will never return true
observable$
 .filter((value) => value > 5);
 .take(1)
 .subscribe(console.log);

As a newcomer to RxJS, this behavior was very confusing to me, although it was my own fault because I made some incorrect assumptions. If I had bothered to check the docs, I would have seen that the behavior is clearly documented:

Throws an error if defaultValue was not provided and a matching element is not found.

The reason I've run into this so frequently is a fairly common Angular 2 pattern where observables are cleaned up manually during the OnDestroy lifecycle hook:

class MyComponent implements OnInit, OnDestroy {
  private stream$: Subject = someDelayedStream();
  private destroy$ = new Subject();

  ngOnInit() {
    this.stream$
      .takeUntil(this.destroy$)
      .first()
      .subscribe(doSomething);
  }

  ngOnDestroy() {
    this.destroy$.next(true);
  }
}

The code looks harmless at first, but problems arise when the component in destroyed before stream$ can emit a value. Because I'm using first(), an error is thrown when the component is destroyed. I'm usually only subscribing to a stream to get a value that is to be used within the component, so I don't care if the component gets destroyed before the stream emits. Because of this, I've started using take(1) in almost all places where I would have previously used first().

filter(fn).take(1) is a bit more verbose than first(fn), but in most cases I prefer a little more verbosity over handling errors that ultimately have no impact on the application.

Also important to note: The same applies for last() and takeLast(1).

reference

UILabel is not auto-shrinking text to fit label size

Coming late to the party, but since I had the additional requirement of having one word per line, this one addition did the trick for me:

label.numberOfLines = [labelString componentsSeparatedByString:@" "].count;

Apple Docs say:

Normally, the label text is drawn with the font you specify in the font property. If this property is set to YES, however, and the text in the text property exceeds the label’s bounding rectangle, the receiver starts reducing the font size until the string fits or the minimum font size is reached. In iOS 6 and earlier, this property is effective only when the numberOfLines property is set to 1.

But this is a lie. A lie I tell you! It's true for all iOS versions. Specifically, this is true when using a UILabel within a UICollectionViewCell for which the size is determined by constraints adjusted dynamically at runtime via custom layout (ex. self.menuCollectionViewLayout.itemSize = size).

So when used in conjunction with adjustsFontSizeToFitWidth and minimumScaleFactor, as mentioned in previous answers, programmatically setting numberOfLines based on word count solved the autoshrink problem. Doing something similar based on word count or even character count might produce a "close enough" solution.

Using pg_dump to only get insert statements from one table within database

If you want to DUMP your inserts into an .sql file:

  1. cd to the location which you want to .sql file to be located
  2. pg_dump --column-inserts --data-only --table=<table> <database> > my_dump.sql

Note the > my_dump.sql command. This will put everything into a sql file named my_dump

What's the difference between 'r+' and 'a+' when open file in python?

If you have used them in C, then they are almost same as were in C.

From the manpage of fopen() function : -

  • r+ : - Open for reading and writing. The stream is positioned at the beginning of the file.

  • a+ : - Open for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subse- quent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar.

CreateProcess error=2, The system cannot find the file specified

My recomendation is to keep the getRuntime().exec because exec uses the ProcessBuilder.

Try

 p=r.exec(new String[] {"winrar", "x", "h:\\myjar.jar", "*.*", "h:\\new"}, null, dir);

Find the nth occurrence of substring in a string

Simplest way?

text = "This is a test from a test ok" 

firstTest = text.find('test')

print text.find('test', firstTest + 1)

Easy pretty printing of floats in python?

You could use pandas.

Here is an example with a list:

In: import pandas as P
In: P.set_option('display.precision',3)
In: L = [3.4534534, 2.1232131, 6.231212, 6.3423423, 9.342342423]
In: P.Series(data=L)
Out: 
0    3.45
1    2.12
2    6.23
3    6.34
4    9.34
dtype: float64

If you have a dict d, and you want its keys as rows:

In: d
Out: {1: 0.453523, 2: 2.35423234234, 3: 3.423432432, 4: 4.132312312}

In: P.DataFrame(index=d.keys(), data=d.values())
Out:  
    0
1   0.45
2   2.35
3   3.42
4   4.13

And another way of giving dict to a DataFrame:

P.DataFrame.from_dict(d, orient='index')

How to do a non-greedy match in grep?

Actualy the .*? only works in perl. I am not sure what the equivalent grep extended regexp syntax would be. Fortunately you can use perl syntax with grep so grep -P would work but grep -E which is same as egrep would not work (it would be greedy).

See also: http://blog.vinceliu.com/2008/02/non-greedy-regular-expression-matching.html

jQuery's .on() method combined with the submit event

The problem here is that the "on" is applied to all elements that exists AT THE TIME. When you create an element dynamically, you need to run the on again:

$('form').on('submit',doFormStuff);

createNewForm();

// re-attach to all forms
$('form').off('submit').on('submit',doFormStuff);

Since forms usually have names or IDs, you can just attach to the new form as well. If I'm creating a lot of dynamic stuff, I'll include a setup or bind function:

function bindItems(){
    $('form').off('submit').on('submit',doFormStuff); 
    $('button').off('click').on('click',doButtonStuff);
}   

So then whenever you create something (buttons usually in my case), I just call bindItems to update everything on the page.

createNewButton();
bindItems();

I don't like using 'body' or document elements because with tabs and modals they tend to hang around and do things you don't expect. I always try to be as specific as possible unless its a simple 1 page project.

Converting a number with comma as decimal point to float

If you're using PHP5.3 or above, you can use numfmt_parse to do "a reversed number_format". If you're not, you stuck with replacing the occurrances with preg_replace/str_replace.

How to get a vCard (.vcf file) into Android contacts from website

AFAIK Android doesn't support vCard files out of the Box at least not until 2.2.

You could use the app vCardIO to read vcf files from your SD card and save to you contacts. So you have to save them on your SD card in the first place and import them afterwards.

vCardIO is also available trough the market.

Two color borders

Not possible, but you should check to see if border-style values like inset, outset or some other, accomplished the effect you want.. (i doubt it though..)

CSS3 has the border-image properties, but i do not know about support from browsers yet (more info at http://www.css3.info/preview/border-image/)..

How to generate components in a specific folder with Angular CLI?

The ng g component plainsight/some-name makes a new directory when we use it.

The final output will be:

plainsight/some-name/some-name.component.ts

To avoid that, make use of the flat option ng g component plainsight/some-name --flat and it will generate the files without making a new folder

plainsight/some-name.component.ts

How to restart a rails server on Heroku?

The answer was:

heroku restart -a app_name

# The -a is the same as --app

Easily aliased with alias hra='heroku restart --app '
Which you can make a permanent alias by adding it to your .bashrc or .bash_aliases file as described at: https://askubuntu.com/questions/17536/how-do-i-create-a-permanent-bash-alias and
Creating permanent executable aliases
Then you can just type hra app_name

You can restart a specific remote, e.g. "staging" with:

heroku restart -a app_name -r remote_name

Alternatively if you are in the root directory of your rails application you can just type

heroku restart

to restart that app and and you can create an easy alias for that with

alias hr='heroku restart'`

You can place these aliases in your .bashrc file or (preferred) in a .bash_aliases file which is called from .bashrc

How to compare two JSON have the same properties without order?

In VueJs function you can use this as well... A working solution using recursion. Base credits Samadhan Sakhale

     check_objects(obj1, obj2) {
            try {
                var flag = true;

                if (Object.keys(obj1).length == Object.keys(obj2).length) {
                    for (let key in obj1) {

                        if(typeof (obj1[key]) != typeof (obj2[key]))
                        {
                            return false;
                        }

                        if (obj1[key] == obj2[key]) {
                            continue;
                        }

                        else if(typeof (obj1[key]) == typeof (new Object()))
                        {
                            if(!this.check_objects(obj1[key], obj2[key])) {
                                return false;
                            }
                        }
                        else {
                            return false;
                        }
                    }
                }
                else {
                    return false
                }
            }
            catch {

                return false;
            }

            return flag;
        },

Create a unique number with javascript time

From investigating online I came up with the following object that creates a unique id per session:

        window.mwUnique ={
        prevTimeId : 0,
        prevUniqueId : 0,
        getUniqueID : function(){
            try {
                var d=new Date();
                var newUniqueId = d.getTime();
                if (newUniqueId == mwUnique.prevTimeId)
                    mwUnique.prevUniqueId = mwUnique.prevUniqueId + 1;
                else {
                    mwUnique.prevTimeId = newUniqueId;
                    mwUnique.prevUniqueId = 0;
                }
                newUniqueId = newUniqueId + '' + mwUnique.prevUniqueId;
                return newUniqueId;                     
            }
            catch(e) {
                mwTool.logError('mwUnique.getUniqueID error:' + e.message + '.');
            }
        }            
    }

It maybe helpful to some people.

Cheers

Andrew

Recommended method for escaping HTML in Java

There is a newer version of the Apache Commons Lang library and it uses a different package name (org.apache.commons.lang3). The StringEscapeUtils now has different static methods for escaping different types of documents (http://commons.apache.org/proper/commons-lang/javadocs/api-3.0/index.html). So to escape HTML version 4.0 string:

import static org.apache.commons.lang3.StringEscapeUtils.escapeHtml4;

String output = escapeHtml4("The less than sign (<) and ampersand (&) must be escaped before using them in HTML");

Express-js wildcard routing to cover everything under and including a path

In array you also can use variables passing to req.params:

app.get(["/:foo", "/:foo/:bar"], /* function */);

Material UI and Grid system

Here is example of grid system with material-ui which is similar to bootstrap:

<Grid container>
    <Grid item xs={12} sm={4} md={4} lg={4}>
    </Grid>
    <Grid item xs={12} sm={4} md={4} lg={4}>
    </Grid>
 </Grid>

Dealing with HTTP content in HTTPS pages

Simply: DO NOT DO IT. Http Content within a HTTPS page is inherently insecure. Point. This is why IE shows a warning. Getting rid of the warning is a stupid hogwash approach.

Instead, a HTTPS page should only have HTTPS content. Make sure the content can be loaded via HTTPS, too, and reference it via https if the page is loaded via https. For external content this will mean loading and caching the elements locally so that they are available via https - sure. No way around that, sadly.

The warning is there for a good reason. Seriously. Spend 5 minutes thinking how you could take over a https shown page with custom content - you will be surprised.

Reduce left and right margins in matplotlib plot

The problem with matplotlibs subplots_adjust is that the values you enter are relative to the x and y figsize of the figure. This example is for correct figuresizing for printing of a pdf:

For that, I recalculate the relative spacing to absolute values like this:

pyplot.subplots_adjust(left = (5/25.4)/figure.xsize, bottom = (4/25.4)/figure.ysize, right = 1 - (1/25.4)/figure.xsize, top = 1 - (3/25.4)/figure.ysize)

for a figure of 'figure.xsize' inches in x-dimension and 'figure.ysize' inches in y-dimension. So the whole figure has a left margin of 5 mm, bottom margin of 4 mm, right of 1 mm and top of 3 mm within the labels are placed. The conversion of (x/25.4) is done because I needed to convert mm to inches.

Note that the pure chart size of x will be "figure.xsize - left margin - right margin" and the pure chart size of y will be "figure.ysize - bottom margin - top margin" in inches

Other sniplets (not sure about these ones, I just wanted to provide the other parameters)

pyplot.figure(figsize = figureSize, dpi = None)

and

pyplot.savefig("outputname.eps", dpi = 100)

How to send a stacktrace to log4j?

Just because it happened to me and can be useful. If you do this

try {
   ...
} catch (Exception e) {
    log.error( "failed! {}", e );
}

you will get the header of the exception and not the whole stacktrace. Because the logger will think that you are passing a String. Do it without {} as skaffman said

Finding the average of an array using JS

You calculate an average by adding all the elements and then dividing by the number of elements.

var total = 0;
for(var i = 0; i < grades.length; i++) {
    total += grades[i];
}
var avg = total / grades.length;

The reason you got 68 as your result is because in your loop, you keep overwriting your average, so the final value will be the result of your last calculation. And your division and multiplication by grades.length cancel each other out.

Django - taking values from POST request

If you need to do something on the front end you can respond to the onsubmit event of your form. If you are just posting to admin/start you can access post variables in your view through the request object. request.POST which is a dictionary of post variables

Select all text inside EditText when it gets focus

SelectAllOnFocus works the first time the EditText gets focus, but if you want to select the text every time the user clicks on it, you need to call editText.clearFocus() in between times.

For example, if your app has one EditText and one button, clicking the button after changing the EditText leaves the focus in the EditText. Then the user has to use the cursor handle and the backspace key to delete what's in the EditText before they can enter a new value. So call editText.clearFocus() in the Button's onClick method.

How to open PDF file in a new tab or window instead of downloading it (using asp.net)?

Instead of loading a stream into a byte array and writing it to the response stream, you should have a look at HttpResponse.TransmitFile

Response.ContentType = "Application/pdf";
Response.TransmitFile(pathtofile);

If you want the PDF to open in a new window you would have to open the downloading page in a new window, for example like this:

<a href="viewpdf.aspx" target="_blank">View PDF</a>

Which HTML elements can receive focus?

$focusable:
  'a[href]',
  'area[href]',
  'button',
  'details',
  'input',
  'iframe',
  'select',
  'textarea',

  // these are actually case sensitive but i'm not listing out all the possible variants
  '[contentEditable=""]',
  '[contentEditable="true"]',
  '[contentEditable="TRUE"]',

  '[tabindex]:not([tabindex^="-"])',
  ':not([disabled])';

I'm creating a SCSS list of all focusable elements and I thought this might help someone due to this question's Google rank.

A few things to note:

  • I changed :not([tabindex="-1"]) to :not([tabindex^="-"]) because it's perfectly plausible to generate -2 somehow. Better safe than sorry right?
  • Adding :not([tabindex^="-"]) to all the other focusable selectors is completely pointless. When using [tabindex]:not([tabindex^="-"]) it already includes all elements that you'd be negating with :not!
  • I included :not([disabled]) because disabled elements can never be focusable. So again it's useless to add it to every single element.

JavaScript: What are .extend and .prototype used for?

The extend method for example in jQuery or PrototypeJS, copies all properties from the source to the destination object.

Now about the prototype property, it is a member of function objects, it is part of the language core.

Any function can be used as a constructor, to create new object instances. All functions have this prototype property.

When you use the new operator with on a function object, a new object will be created, and it will inherit from its constructor prototype.

For example:

function Foo () {
}
Foo.prototype.bar = true;

var foo = new Foo();

foo.bar; // true
foo instanceof Foo; // true
Foo.prototype.isPrototypeOf(foo); // true

Selecting a row in DataGridView programmatically

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

android: data binding error: cannot find symbol class

this is your code

ContactListActivityBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_contact_list);

Replace this code

ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_contact_list);

ASP.NET MVC: Html.EditorFor and multi-line text boxes

Use data type 'MultilineText':

[DataType(DataType.MultilineText)]
public string Text { get; set; }

See ASP.NET MVC3 - textarea with @Html.EditorFor

Trying Gradle build - "Task 'build' not found in root project"

You didn't do what you're being asked to do.

What is asked:

I have to execute ../gradlew build

What you do

cd ..
gradlew build

That's not the same thing.

The first one will use the gradlew command found in the .. directory (mdeinum...), and look for the build file to execute in the current directory, which is (for example) chapter1-bookstore.

The second one will execute the gradlew command found in the current directory (mdeinum...), and look for the build file to execute in the current directory, which is mdeinum....

So the build file executed is not the same.

Python SQL query string formatting

Sorry for posting to such an old thread -- but as someone who also shares a passion for pythonic 'best', I thought I'd share our solution.

The solution is to build SQL statements using python's String Literal Concatenation (http://docs.python.org/), which could be qualified a somewhere between Option 2 and Option 4

Code Sample:

sql = ("SELECT field1, field2, field3, field4 "
       "FROM table "
       "WHERE condition1=1 "
       "AND condition2=2;")

Works as well with f-strings:

fields = "field1, field2, field3, field4"
table = "table"
conditions = "condition1=1 AND condition2=2"

sql = (f"SELECT {fields} "
       f"FROM {table} "
       f"WHERE {conditions};")

Pros:

  1. It retains the pythonic 'well tabulated' format, but does not add extraneous space characters (which pollutes logging).
  2. It avoids the backslash continuation ugliness of Option 4, which makes it difficult to add statements (not to mention white-space blindness).
  3. And further, it's really simple to expand the statement in VIM (just position the cursor to the insert point, and press SHIFT-O to open a new line).

Iterate through dictionary values?

You can just look for the value that corresponds with the key and then check if the input is equal to the key.

for key in PIX0:
    NUM = input("Which standard has a resolution of %s " % PIX0[key])
    if NUM == key:

Also, you will have to change the last line to fit in, so it will print the key instead of the value if you get the wrong answer.

print("I'm sorry but thats wrong. The correct answer was: %s." % key )

Also, I would recommend using str.format for string formatting instead of the % syntax.

Your full code should look like this (after adding in string formatting)

PIX0 = {"QVGA":"320x240", "VGA":"640x480", "SVGA":"800x600"}

for key in PIX0:
    NUM = input("Which standard has a resolution of {}".format(PIX0[key]))
    if NUM == key:
        print ("Nice Job!")
        count = count + 1
    else:
        print("I'm sorry but that's wrong. The correct answer was: {}.".format(key))

Variable number of arguments in C++?

in c++11 you can do:

void foo(const std::list<std::string> & myArguments) {
   //do whatever you want, with all the convenience of lists
}

foo({"arg1","arg2"});

list initializer FTW!

Createuser: could not connect to database postgres: FATAL: role "tom" does not exist

If you don't want to change the authentication method (ident) and mess with pg_hba.conf use this:

First login as the default user

 sudo su - posgres

then access psql and create a user with the same name as the one you are login in

postgres=# CREATE USER userOS WITH PASSWORD 'garbage' CREATEDB;

you can verify your user with the corresponding roles with

postgres=#  \du

Afer this you can create your database and verify it with

psql -d dbName
\l
\q

How to set $_GET variable

For the form, use:

<form name="form1" action="<?=$_SERVER['PHP_SELF'];?>" method="get">

and for getting the value, use the get method as follows:

$value = $_GET['name_to_send_using_get'];

This IP, site or mobile application is not authorized to use this API key

I had the same issue and I found this.

On the url, it requires the server key in the end and not the api key for the app.

So Basically, you just add the server key in the end of the URL like this:

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=yourlatitude,yourlongitude&radius=5000&sensor=true&key=SERVERKEY

Now, to obtain the server key, just follow these steps:

1) Go to Developer Console https://code.google.com/apis/console/

2) In the Credentials, under Public API Access, Create New key

3) Select the server key from the option.

4) Enter your IP Address on the field and if you have more ip addresses, you can just add on every single line.NOTE: Enter the IP Address only when you want to use it for your testing purpose. Else leave the IP Address section blank.

5) Once you are done, click create and your new Server Key will be generated and you can then add that server key to your URL.

Last thing is that, instead of putting the sensor=true in the middle of the URL, you can add it in the end like this:

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=yourlatitude,yourlongitude&radius=5000&key=SERVERKEY&sensor=true

This will definitely solve the issue and just remember to use the server key for Places API.

EDIT

I believe the web URL has changed in the past years. You can access developers console from here now - https://console.developers.google.com/apis/dashboard

  • Navigate to developers console - https://console.developers.google.com/ or use the link from details to navigate directly to API dashboard.
  • Under developer console, find Label from the left navigation panel
  • Select project
  • Choose Credentials from the left Navigation panel
  • You could create credentials type from the Top nav bar as required.

Hope this answer will help you and other viewers. Good Luck .. :)

pandas read_csv and filter columns with usecols

import csv first and use csv.DictReader its easy to process...

Prevent redirect after form is submitted

I found this page 10 years (!) after the original post, and needed the answer as vanilla js instead of AJAX. I figured it out with the help of @gargAman's answer.

Use an appropriate selector to assign your button to a variable, e.g.

document.getElementById('myButton')

then

myButton.addEventListener('click', function(e) {
    e.preventDefault();
    // do cool stuff
});

I should note that my html looks like this (specifically, I am not using type="Submit" in my button and action="" in my form:

  <form method="POST" action="" id="myForm">
    <!-- form fields -->
    <button id="myButton" class="btn-submit">Submit</button>
  </form>

What is a Subclass

It is a class that extends another class.

example taken from https://www.java-tips.org/java-se-tips-100019/24-java-lang/784-what-is-a-java-subclass.html, Cat is a sub class of Animal :-)

public class Animal {

    public static void hide() {
        System.out.println("The hide method in Animal.");
    }

    public void override() {
        System.out.println("The override method in Animal.");
    }
}

public class Cat extends Animal {

    public static void hide() {
        System.out.println("The hide method in Cat.");
    }

    public void override() {
        System.out.println("The override method in Cat.");
    }

    public static void main(String[] args) {
        Cat myCat = new Cat();
        Animal myAnimal = (Animal)myCat;
        myAnimal.hide();
        myAnimal.override();
    }
}

scale fit mobile web content using viewport meta tag

In the head add this

//Include jQuery
<meta id="Viewport" name="viewport" content="initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">

<script type="text/javascript">
$(function(){
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
  var ww = ( $(window).width() < window.screen.width ) ? $(window).width() : window.screen.width; //get proper width
  var mw = 480; // min width of site
  var ratio =  ww / mw; //calculate ratio
  if( ww < mw){ //smaller than minimum size
   $('#Viewport').attr('content', 'initial-scale=' + ratio + ', maximum-scale=' + ratio + ', minimum-scale=' + ratio + ', user-scalable=yes, width=' + ww);
  }else{ //regular size
   $('#Viewport').attr('content', 'initial-scale=1.0, maximum-scale=2, minimum-scale=1.0, user-scalable=yes, width=' + ww);
  }
}
});
</script>

Returning value that was passed into a method

Even more useful, if you have multiple parameters you can access any/all of them with:

_mock.Setup(x => x.DoSomething(It.IsAny<string>(),It.IsAny<string>(),It.IsAny<string>())
     .Returns((string a, string b, string c) => string.Concat(a,b,c));

You always need to reference all the arguments, to match the method's signature, even if you're only going to use one of them.

How to stop the Timer in android?

I had a similar problem and it was caused by the placement of the Timer initialisation.

It was placed in a method that was invoked oftener.

Try this:

Timer waitTimer;

  void exampleMethod() {

   if (waitTimer == null ) {
    //initialize your Timer here
    ...
   }

The "cancel()" method only canceled the latest Timer. The older ones were ignored an didn't stop running.

Could not find or load main class with a Jar File

I got it working like this:

TestClass.Java

package classes;

public class TestClass {

    public static void main(String[] args) {
        System.out.println("Test");
    }

}

Use javac on the command line to produce TestClass.class. Put TestClass.class in a folder classes/.

MANIFEST.MF

Manifest-Version: 1.0
Main-Class: classes.TestClass

Then run

jar cfm test.jar MANIFEST.MF classes/

Then run it as

java -jar test.jar

How to handle click event in Button Column in Datagridview?

You've added a button to your DataGridView and you want to run some code when it's clicked.
Easy peasy - just follow these steps:

Don'ts:

First, here's what NOT to do:

I would avoid the suggestions in some of the other answers here and even provided by the documentation at MSDN to hardcode the column index or column name in order to determine if a button was clicked. The click event registers for the entire grid, so somehow you need to determine that a button was clicked, but you should not do so by assuming that your button lives in a particular column name or index... there's an easier way...

Also, be careful which event you want to handle. Again, the documentation and many examples get this wrong. Most examples handle the CellClick event which will fire:

when any part of a cell is clicked.

...but will also fire whenever the row header is clicked. This necessitates adding extra code simply to determine if the e.RowIndex value is less than 0

Instead handle the CellContentClick which only occurs:

when the content within a cell is clicked

For whatever reason, the column header is also considered 'content' within a cell, so we'll still have to check for that below.

Dos:

So here's what you should do:

First, cast the sender to type DataGridView to expose it's internal properties at design time. You can modify the type on the parameter, but that can sometimes make adding or removing handlers tricky.

Next, to see if a button was clicked, just check to make sure that the column raising the event is of type DataGridViewButtonColumn. Because we already cast the sender to type DataGridView, we can get the Columns collection and select the current column using e.ColumnIndex. Then check if that object is of type DataGridViewButtonColumn.

Of course, if you need to distinguish between multiple buttons per grid, you can then select based on the column name or index, but that shouldn't be your first check. Always make sure a button was clicked first and then handle anything else appropriately. In most cases where you only have a single button per grid, you can jump right off to the races.

Putting it all together:

C#:

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    var senderGrid = (DataGridView)sender;

    if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn &&
        e.RowIndex >= 0)
    {
        //TODO - Button Clicked - Execute Code Here
    }
}

VB:

Private Sub DataGridView1_CellContentClick(sender As System.Object, e As DataGridViewCellEventArgs) _
                                           Handles DataGridView1.CellContentClick
    Dim senderGrid = DirectCast(sender, DataGridView)

    If TypeOf senderGrid.Columns(e.ColumnIndex) Is DataGridViewButtonColumn AndAlso
       e.RowIndex >= 0 Then
        'TODO - Button Clicked - Execute Code Here
    End If

End Sub

Update 1 - Custom Event

If you wanted to have a little bit of fun, you can add your own event to be raised whenever a button is clicked on the DataGrid. You can't add it to the DataGrid itself, without getting messy with inheritance etc., but you can add a custom event to your form and fire it when appropriate. It's a little more code, but the upside is that you've separated out what you want to do when a button is clicked with how to determine if a button was clicked.

Just declare an event, raise it when appropriate, and handle it. It will look like this:

Event DataGridView1ButtonClick(sender As DataGridView, e As DataGridViewCellEventArgs)

Private Sub DataGridView1_CellContentClick(sender As System.Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
    Dim senderGrid = DirectCast(sender, DataGridView)
    If TypeOf senderGrid.Columns(e.ColumnIndex) Is DataGridViewButtonColumn AndAlso e.RowIndex >= 0 Then
        RaiseEvent DataGridView1ButtonClick(senderGrid, e)
    End If
End Sub

Private Sub DataGridView1_ButtonClick(sender As DataGridView, e As DataGridViewCellEventArgs) Handles Me.DataGridView1ButtonClick
    'TODO - Button Clicked - Execute Code Here
End Sub

Update 2 - Extended Grid

What would be great is if we were working with a grid that just did these things for us. We could answer the initial question easily: you've added a button to your DataGridView and you want to run some code when it's clicked. Here's an approach that extends the DataGridView. It might not be worth the hassle of having to deliver a custom control with every library, but at least it maximally reuses the code used for determining if a button was clicked.

Just add this to your assembly:

Public Class DataGridViewExt : Inherits DataGridView

    Event CellButtonClick(sender As DataGridView, e As DataGridViewCellEventArgs)

    Private Sub CellContentClicked(sender As System.Object, e As DataGridViewCellEventArgs) Handles Me.CellContentClick
        If TypeOf Me.Columns(e.ColumnIndex) Is DataGridViewButtonColumn AndAlso e.RowIndex >= 0 Then
            RaiseEvent CellButtonClick(Me, e)
        End If
    End Sub

End Class

That's it. Never touch it again. Make sure your DataGrid is of type DataGridViewExt which should work exactly the same as a DataGridView. Except it will also raise an extra event that you can handle like this:

Private Sub DataGridView1_ButtonClick(sender As DataGridView, e As DataGridViewCellEventArgs) _
                                      Handles DataGridView1.CellButtonClick
    'TODO - Button Clicked - Execute Code Here
End Sub

How to Set user name and Password of phpmyadmin

You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.

How can I check whether a variable is defined in Node.js?

If your variable is not declared nor defined:

if ( typeof query !== 'undefined' ) { ... }

If your variable is declared but undefined. (assuming the case here is that the variable might not be defined but it can be any other falsy value like false or "")

if ( query ) { ... }

If your variable is declared but can be undefined or null:

if ( query != null ) { ... } // undefined == null

Error: Main method not found in class Calculate, please define the main method as: public static void main(String[] args)

Where you have written the code

public class Main {
    public static void main(String args[])
    {
        Calculate obj = new Calculate(1,2,'+');
        obj.getAnswer();
    }
}

Here you have to run the class "Main" instead of the class you created at the start of the program. To do so pls go to Run Configuration and search for this class name"Main" which is having the main method inside this(public static void main(String args[])). And you will get your output.

How to import Angular Material in project?

The MaterialModule was deprecated in the beta3 version with the goal that developers should only import into their applications what they are going to use and thus improve the bundle size.

The developers have now 2 options:

  • Create a custom MyMaterialModule which imports/exports the components that your application requires and can be imported by other (feature) modules in your application.
  • Import directly the individual material modules that a module requires into it.

Take the following as example (extracted from material page)

First approach:

import {MdButtonModule, MdCheckboxModule} from '@angular/material';

@NgModule({
  imports: [MdButtonModule, MdCheckboxModule],
  exports: [MdButtonModule, MdCheckboxModule],
})
export class MyOwnCustomMaterialModule { }

Then you can import this module into any of yours.

Second approach:

import {MdButtonModule, MdCheckboxModule} from '@angular/material';

@NgModule({
  ...
  imports: [MdButtonModule, MdCheckboxModule],
  ...
})
export class PizzaPartyAppModule { }

Now you can use the respective material components in all the components declared in PizzaPartyAppModule

It is worth mentioning the following:

  • With the latest version of material, you need to import BrowserAnimationsModule into your main module if you want the animations to work
  • With the latest version developers now need to add @angular/cdk to their package.json (material dependency)
  • Import the material modules always after BrowserModule, as stated by the docs:

Whichever approach you use, be sure to import the Angular Material modules after Angular's BrowserModule, as the import order matters for NgModules.

How to install psycopg2 with "pip" on Python?

Make sure Postgres is installed and PATH is updated before running pip install psycopg2

export PATH="$PATH:/Applications/Postgres.app/Contents/Versions/12/bin"

What is the difference between an int and a long in C++?

As Kevin Haines points out, ints have the natural size suggested by the execution environment, which has to fit within INT_MIN and INT_MAX.

The C89 standard states that UINT_MAX should be at least 2^16-1, USHRT_MAX 2^16-1 and ULONG_MAX 2^32-1 . That makes a bit-count of at least 16 for short and int, and 32 for long. For char it states explicitly that it should have at least 8 bits (CHAR_BIT). C++ inherits those rules for the limits.h file, so in C++ we have the same fundamental requirements for those values. You should however not derive from that that int is at least 2 byte. Theoretically, char, int and long could all be 1 byte, in which case CHAR_BIT must be at least 32. Just remember that "byte" is always the size of a char, so if char is bigger, a byte is not only 8 bits any more.

How to make EditText not editable through XML in Android?

They made "editable" deprecated but didn't provide a working corresponding one in inputType.

By the way, does inputType="none" has any effect? Using it or not does not make any difference as far as I see.

For example, the default editText is said to be single line. But you have to select an inputType for it to be single line. And if you select "none", it is still multiline.

Search an array for matching attribute

let restaurant = restaurants.find(element => element.restaurant.food == "chicken");

The find() method returns the value of the first element in the provided array that satisfies the provided testing function.

in: https://developer.mozilla.org/pt-PT/docs/Web/JavaScript/Reference/Global_Objects/Array/find

Simple PHP calculator

Personally I would do a switch instead of all this if, else if, else

$first = $_POST['first'] + 0;//a small "hack" to make sure its an int but allow negs!!
$second= $_POST['second'] + 0;
$operator = $_POST["group1"];
switch($operator)
{
    case "add"
    echo "Answer is: " .$first + $second;
    break; 
    case "subtract"
    echo "Answer is: " .$first - $second;
    break;
    case "times"
    echo "Answer is: " .$first * $second;
    break; 
    case "divide"
    echo "Answer is: " .$first / $second;
    break;
}

Check string for palindrome

Code Snippet:

import java.util.Scanner;

 class main
 {
    public static void main(String []args)
    {
       Scanner sc = new Scanner(System.in);
       String str = sc.next();
       String reverse = new StringBuffer(str).reverse().toString();

        if(str.equals(reverse))
            System.out.println("Pallindrome");
        else
            System.out.println("Not Pallindrome");
     }
}

How to comment out a block of code in Python

At least in VIM you can select the first column of text you want to insert using Block Visual mode (CTRL+V in non-windows VIMs) and then prepend a # before each line using this sequence:

I#<esc>

In Block Visual mode I moves to insert mode with the cursor before the block on its first line. The inserted text is copied before each line in the block.

How to select label for="XYZ" in CSS?

If the label immediately follows a specified input element:

input#example + label { ... }
input:checked + label { ... }

How to store Emoji Character in MySQL Database

Step 1, change your database's default charset:

ALTER DATABASE database_name CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;

if the db is not created yet, create it with correct encodings:

CREATE DATABASE database_name DEFAULT CHARSET = utf8mb4 DEFAULT COLLATE = utf8mb4_unicode_ci;

Step 2, set charset when creating table:

CREATE TABLE IF NOT EXISTS table_name (
...
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_unicode_ci;

or alter table

ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE table_name MODIFY field_name TEXT CHARSET utf8mb4;

What is the T-SQL syntax to connect to another SQL Server?

on my C drive I first create a txt file to create a new table. You can use what ever you want in this text file

in this case the text file is called "Bedrijf.txt"

the content:

Print 'START(A) create table'

GO 1

If not EXISTS
(
    SELECT *
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_NAME = 'Bedrijf'
)
BEGIN
CREATE TABLE [dbo].[Bedrijf] (
[IDBedrijf] [varchar] (38)   NOT NULL ,
[logo] [varbinary] (max) NULL ,
[VolledigeHandelsnaam] [varchar] (100)  NULL 
) ON [PRIMARY]

save it

then I create an other txt file with the name "Bedrijf.bat" and the extension bat. It's content:

OSQL.EXE  -U Username -P Password -S IPaddress -i C:Bedrijf.txt -o C:Bedrijf.out -d myDatabaseName

save it and from explorer double click to execute

The results will be saved in a txt file on your C drive with the name "Bedrijf.out"

it shows

1> 2> 3> START(A) create table

if all goes well

That's it

Show diff between commits

I use gitk to see the difference:

gitk k73ud..dj374

It has a GUI mode so that reviewing is easier.

IN vs OR in the SQL WHERE Clause

I assume you want to know the performance difference between the following:

WHERE foo IN ('a', 'b', 'c')
WHERE foo = 'a' OR foo = 'b' OR foo = 'c'

According to the manual for MySQL if the values are constant IN sorts the list and then uses a binary search. I would imagine that OR evaluates them one by one in no particular order. So IN is faster in some circumstances.

The best way to know is to profile both on your database with your specific data to see which is faster.

I tried both on a MySQL with 1000000 rows. When the column is indexed there is no discernable difference in performance - both are nearly instant. When the column is not indexed I got these results:

SELECT COUNT(*) FROM t_inner WHERE val IN (1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000);
1 row fetched in 0.0032 (1.2679 seconds)

SELECT COUNT(*) FROM t_inner WHERE val = 1000 OR val = 2000 OR val = 3000 OR val = 4000 OR val = 5000 OR val = 6000 OR val = 7000 OR val = 8000 OR val = 9000;
1 row fetched in 0.0026 (1.7385 seconds)

So in this case the method using OR is about 30% slower. Adding more terms makes the difference larger. Results may vary on other databases and on other data.

How to check if matching text is found in a string in Lua?

There are 2 options to find matching text; string.match or string.find.

Both of these perform a regex search on the string to find matches.


string.find()

string.find(subject string, pattern string, optional start position, optional plain flag)

Returns the startIndex & endIndex of the substring found.

The plain flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger) being interpreted as a regex capture group matching for tiger, it instead looks for (tiger) within a string.

Going the other way, if you want to regex match but still want literal special characters (such as .()[]+- etc.), you can escape them with a percentage; %(tiger%).

You will likely use this in combination with string.sub

Example

str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

string.match()

string.match(s, pattern, optional index)

Returns the capture groups found.

Example

str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

How do I output coloured text to a Linux terminal?

I wrote a cross-platform library color_ostream for this, with the support of ANSI color, 256 color and true color, all you have to do is directly including it and changing cout to rd_cout like this.
| std | basic color | 256 color | true color | | :----: | :----: | :----: | :----: | | std::cout | color_ostream::rd_cout | color_ostream::rd256_cout | color_ostream::rdtrue_cout | | std::wcout | color_ostream::rd_wcout | color_ostream::rd256_wcout | color_ostream::rdtrue_wcout | | std::cerr | color_ostream::rd_cerr | color_ostream::rd256_cerr | color_ostream::rdtrue_cerr | | std::wcerr | color_ostream::rd_wcerr | color_ostream::rd256_wcerr | color_ostream::rdtrue_wcerr | | std::clog | color_ostream::rd_clog | color_ostream::rd256_clog | color_ostream::rdtrue_clog | | std::wclog | color_ostream::rd_wclog | color_ostream::rd256_wclog | color_ostream::rdtrue_wclog |
Here is an simple example:

//hello.cpp
#include "color_ostream.h"

using namespace color_ostream;

int main([[maybe_unused]] int argc, [[maybe_unused]] char *argv[]) {
    rd_wcout.imbue(std::locale(std::locale(),"",LC_CTYPE));
    rd_wcout << L"Hello world\n";
    rd_wcout << L"Hola Mundo\n";
    rd_wcout << L"Bonjour le monde\n";

    rd256_wcout << L"\n256 color" << std::endl;
    rd256_wcout << L"Hello world\n";
    rd256_wcout << L"Hola Mundo\n";
    rd256_wcout << L"Bonjour le monde\n";

    rdtrue_wcout << L"\ntrue color" << std::endl;
    rdtrue_wcout << L"Hello world\n";
    rdtrue_wcout << L"Hola Mundo\n";
    rdtrue_wcout << L"Bonjour le monde\n";
    return 0;
}

Making a <button> that's a link in HTML

You have three options:

  • Style links to look like buttons using CSS.

    Just look at the light blue "tags" under your question.

    It is possible, even to give them a depressed appearance when clicked (using pseudo-classes like :active), without any scripting. Lots of major sites, such as Google, are starting to make buttons out of CSS styles these days anyway, scripting or not.

  • Put a separate <form> element around each one.

    As you mentioned in the question. Easy and will definitely work without Javascript (or even CSS). But it adds a little extra code which may look untidy.

  • Rely on Javascript.

    Which is what you said you didn't want to do.

Why does my sorting loop seem to append an element where it shouldn't?

Starting from Java 8, you can also use parallelSort which is useful if you have arrays containing a lot of elements.

Example:

public static void main(String[] args) {
    String[] strings = { "x", "a", "c", "b", "y" };
    Arrays.parallelSort(strings);
    System.out.println(Arrays.toString(strings));   // [a, b, c, x, y]
}

If you want to ignore the case, you can use:

public static void main(String[] args) {
    String[] strings = { "x", "a", "c", "B", "y" };
    Arrays.parallelSort(strings, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {              
            return o1.compareToIgnoreCase(o2);
        }
    });
    System.out.println(Arrays.toString(strings));   // [a, B, c, x, y]
}

otherwise B will be before a.

If you want to ignore the trailing spaces during the comparison, you can use trim():

public static void main(String[] args) {
    String[] strings = { "x", "  a", "c ", " b", "y" };
    Arrays.parallelSort(strings, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {              
            return o1.trim().compareTo(o2.trim());
        }
    });
    System.out.println(Arrays.toString(strings)); // [  a,  b, c , x, y]
}

See:

Postgresql query between date ranges

SELECT user_id 
FROM user_logs 
WHERE login_date BETWEEN '2014-02-01' AND '2014-03-01'

Between keyword works exceptionally for a date. it assumes the time is at 00:00:00 (i.e. midnight) for dates.

Allow only numbers to be typed in a textbox

With HTML5 you can do

<input type="number">

You can also use a regex pattern to limit the input text.

<input type="text" pattern="^[0-9]*$" />

How to get the sign, mantissa and exponent of a floating point number

  1. Don't make functions that do multiple things.
  2. Don't mask then shift; shift then mask.
  3. Don't mutate values unnecessarily because it's slow, cache-destroying and error-prone.
  4. Don't use magic numbers.
/* NaNs, infinities, denormals unhandled */
/* assumes sizeof(float) == 4 and uses ieee754 binary32 format */
/* assumes two's-complement machine */
/* C99 */
#include <stdint.h>

#define SIGN(f) (((f) <= -0.0) ? 1 : 0)

#define AS_U32(f) (*(const uint32_t*)&(f))
#define FLOAT_EXPONENT_WIDTH 8
#define FLOAT_MANTISSA_WIDTH 23
#define FLOAT_BIAS ((1<<(FLOAT_EXPONENT_WIDTH-1))-1) /* 2^(e-1)-1 */
#define MASK(width)  ((1<<(width))-1) /* 2^w - 1 */
#define FLOAT_IMPLICIT_MANTISSA_BIT (1<<FLOAT_MANTISSA_WIDTH)

/* correct exponent with bias removed */
int float_exponent(float f) {
  return (int)((AS_U32(f) >> FLOAT_MANTISSA_WIDTH) & MASK(FLOAT_EXPONENT_WIDTH)) - FLOAT_BIAS;
}

/* of non-zero, normal floats only */
int float_mantissa(float f) {
  return (int)(AS_U32(f) & MASK(FLOAT_MANTISSA_BITS)) | FLOAT_IMPLICIT_MANTISSA_BIT;
}

/* Hacker's Delight book is your friend. */

Why do we use volatile keyword?

Consider this code,

int some_int = 100;

while(some_int == 100)
{
   //your code
}

When this program gets compiled, the compiler may optimize this code, if it finds that the program never ever makes any attempt to change the value of some_int, so it may be tempted to optimize the while loop by changing it from while(some_int == 100) to something which is equivalent to while(true) so that the execution could be fast (since the condition in while loop appears to be true always). (if the compiler doesn't optimize it, then it has to fetch the value of some_int and compare it with 100, in each iteration which obviously is a little bit slow.)

However, sometimes, optimization (of some parts of your program) may be undesirable, because it may be that someone else is changing the value of some_int from outside the program which compiler is not aware of, since it can't see it; but it's how you've designed it. In that case, compiler's optimization would not produce the desired result!

So, to ensure the desired result, you need to somehow stop the compiler from optimizing the while loop. That is where the volatile keyword plays its role. All you need to do is this,

volatile int some_int = 100; //note the 'volatile' qualifier now!

In other words, I would explain this as follows:

volatile tells the compiler that,

"Hey compiler, I'm volatile and, you know, I can be changed by some XYZ that you're not even aware of. That XYZ could be anything. Maybe some alien outside this planet called program. Maybe some lightning, some form of interrupt, volcanoes, etc can mutate me. Maybe. You never know who is going to change me! So O you ignorant, stop playing an all-knowing god, and don't dare touch the code where I'm present. Okay?"

Well, that is how volatile prevents the compiler from optimizing code. Now search the web to see some sample examples.


Quoting from the C++ Standard ($7.1.5.1/8)

[..] volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation.[...]

Related topic:

Does making a struct volatile make all its members volatile?

Convert the values in a column into row names in an existing data frame

You can execute this in 2 simple statements:

row.names(samp) <- samp$names
samp[1] <- NULL

SVN- How to commit multiple files in a single shot

I've had no issues committing a few files like this:

svn commit fileDir1/ fileDir2/ -m "updated!"

Javascript window.print() in chrome, closing new window or tab instead of cancelling print leaves javascript blocked in parent window

Use this code to return and reload the current window:

function printpost() {
  if (window.print()) {
    return false;
  } else {
    location.reload();
  }
}

DateTime and CultureInfo

You may try the following:

System.Globalization.CultureInfo cultureinfo =
        new System.Globalization.CultureInfo("nl-NL");
DateTime dt = DateTime.Parse(date, cultureinfo);

Fill Combobox from database

void Fillcombobox()
{

    con.Open();
    cmd = new SqlCommand("select ID From Employees",con);
    Sdr = cmd.ExecuteReader();
    while (Sdr.Read())
    {
        for (int i = 0; i < Sdr.FieldCount; i++)
        {
           comboID.Items.Add( Sdr.GetString(i));

        }
    }
    Sdr.Close();
    con.Close();

}

How to install OpenSSL for Python

SSL development libraries have to be installed

CentOS:

$ yum install openssl-devel libffi-devel

Ubuntu:

$ apt-get install libssl-dev libffi-dev

OS X (with Homebrew installed):

$ brew install openssl

How to check the multiple permission at single request in Android M?

I faced the same problem and below is the workaround I came up with:

public boolean checkForPermission(final String[] permissions, final int permRequestCode, int msgResourceId) {
        final List<String> permissionsNeeded = new ArrayList<>();
        for (int i = 0; i < permissions.length; i++) {
            final String perm = permissions[i];
            if (ContextCompat.checkSelfPermission(getActivity(), permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                if (shouldShowRequestPermissionRationale(permissions[i])) {
                    final AlertDialog dialog = AlertDialog.newInstance( getResources().getString(R.string.permission_title), getResources().getString(msgResourceId) );
                    dialog.setPositiveButton("OK", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            // add the request.
                            permissionsNeeded.add(perm);
                            dialog.dismiss();
                        }
                    });
                    dialog.show( getActivity().getSupportFragmentManager(), "HCFAlertDialog" );
                } else {
                    // add the request.
                    permissionsNeeded.add(perm);
                }
            }
        }

        if (permissionsNeeded.size() > 0) {
            // go ahead and request permissions
            requestPermissions(permissionsNeeded.toArray(new String[permissionsNeeded.size()]), permRequestCode);
            return false;
        } else {
            // no permission need to be asked so all good...we have them all.
            return true;
        }
    }

And you call the above method like this:

if ( checkForPermission( new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, 
Manifest.permission.CAMERA}, REQUEST_PERMISSION_EXTERNAL_STORAGE_RESULT, R.string.permission_image) ) {
                        // DO YOUR STUFF

                    }

echo key and value of an array without and with loop

for the first question

$key = 'Home';
echo $key." is at ".$page[$key];

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

I was facing the similar type of issue: Code Snippet :

<c:forEach items="${orderList}" var="xx"> ${xx.id} <br>
</c:forEach>

There was a space after orderlist like this : "${orderList} " because of which the xx variable was getting coverted into String and was not able to call xx.id.

So make sure about space. They play crucial role sometimes. :p

How to specify the private SSH-key to use when executing shell command on Git?

With git 2.10+ (Q3 2016: released Sept. 2d, 2016), you have the possibility to set a config for GIT_SSH_COMMAND (and not just an environment variable as described in Rober Jack Will's answer)

See commit 3c8ede3 (26 Jun 2016) by Nguy?n Thái Ng?c Duy (pclouds).
(Merged by Junio C Hamano -- gitster -- in commit dc21164, 19 Jul 2016)

A new configuration variable core.sshCommand has been added to specify what value for GIT_SSH_COMMAND to use per repository.

core.sshCommand:

If this variable is set, git fetch and git push will use the specified command instead of ssh when they need to connect to a remote system.
The command is in the same form as the GIT_SSH_COMMAND environment variable and is overridden when the environment variable is set.

It means the git pull can be:

cd /path/to/my/repo/already/cloned
git config core.sshCommand 'ssh -i private_key_file' 
# later on
git pull

You can even set it for just one command like git clone:

git -c core.sshCommand="ssh -i private_key_file" clone host:repo.git

This is easier than setting a GIT_SSH_COMMAND environment variable, which, on Windows, as noted by Mátyás Kuti-Kreszács, would be

set "GIT_SSH_COMMAND=ssh -i private_key_file"

SQL SERVER, SELECT statement with auto generate row id

Select (Select count(y.au_lname) from dbo.authors y
where y.au_lname + y.au_fname <= x.au_lname + y.au_fname) as Counterid,
x.au_lname,x.au_fname from authors x group by au_lname,au_fname
order by Counterid --Alternatively that can be done which is equivalent as above..

How do I convert a Python program to a runnable .exe Windows program?

There is another way to convert Python scripts to .exe files. You can compile Python programs into C++ programs, which can be natively compiled just like any other C++ program.

jQuery - Uncaught RangeError: Maximum call stack size exceeded

your fadeIn() function calls the fadeOut() function, which calls the fadeIn() function again. the recursion is in the JS.

What size should TabBar images be?

30x30 is points, which means 30px @1x, 60px @2x, not somewhere in-between. Also, it's not a great idea to embed the title of the tab into the image—you're going to have pretty poor accessibility and localization results like that.

SQL Server 100% CPU Utilization - One database shows high CPU usage than others

According to this article on sqlserverstudymaterial;

Remember that "%Privileged time" is not based on 100%.It is based on number of processors.If you see 200 for sqlserver.exe and the system has 8 CPU then CPU consumed by sqlserver.exe is 200 out of 800 (only 25%).

If "% Privileged Time" value is more than 30% then it's generally caused by faulty drivers or anti-virus software. In such situations make sure the BIOS and filter drives are up to date and then try disabling the anti-virus software temporarily to see the change.

If "% User Time" is high then there is something consuming of SQL Server. There are several known patterns which can be caused high CPU for processes running in SQL Server including

How do I sort a dictionary by value?

As simple as: sorted(dict1, key=dict1.get)

Well, it is actually possible to do a "sort by dictionary values". Recently I had to do that in a Code Golf (Stack Overflow question Code golf: Word frequency chart). Abridged, the problem was of the kind: given a text, count how often each word is encountered and display a list of the top words, sorted by decreasing frequency.

If you construct a dictionary with the words as keys and the number of occurrences of each word as value, simplified here as:

from collections import defaultdict
d = defaultdict(int)
for w in text.split():
    d[w] += 1

then you can get a list of the words, ordered by frequency of use with sorted(d, key=d.get) - the sort iterates over the dictionary keys, using the number of word occurrences as a sort key .

for w in sorted(d, key=d.get, reverse=True):
    print(w, d[w])

I am writing this detailed explanation to illustrate what people often mean by "I can easily sort a dictionary by key, but how do I sort by value" - and I think the original post was trying to address such an issue. And the solution is to do sort of list of the keys, based on the values, as shown above.

Npm install cannot find module 'semver'

Start fresh.

brew uninstall --force node
brew install node

Unable to begin a distributed transaction

OK, so services are started, there is an ethernet path between them, name resolution works, linked servers work, and you disabled transaction authentication.

My gut says firewall issue, but a few things come to mind...

  1. Are the machines in the same domain? (yeah, shouldn't matter with disabled authentication)
  2. Are firewalls running on the the machines? DTC can be a bit of pain for firewalls as it uses a range of ports, see http://support.microsoft.com/kb/306843 For the time being, I would disable firewalls for the sake of identifying the problem
  3. What does DTC ping say? http://www.microsoft.com/download/en/details.aspx?id=2868
  4. What account is the SQL Service running as ?

How do you check current view controller class in Swift?

Swift 4, Swift 5

let viewController = UIApplication.shared.keyWindow?.rootViewController
if viewController is MyViewController {

}

How do I put text on ProgressBar?

I have written a no blinking/flickering TextProgressBar

You can find the source code here: https://github.com/ukushu/TextProgressBar

enter image description here

WARNING: It's a little bit buggy! But still, I think it's better than another answers here. As I have no time for fixes, if you will do sth with them, please send me update by some way:) Thanks.

Samples:

enter image description here enter image description here no blinking/flickering TextProgressBar

no blinking/flickering TextProgressBar enter image description here enter image description here

What is the difference between gravity and layout_gravity in Android?

Short Answer: use android:gravity or setGravity() to control gravity of all child views of a container; use android:layout_gravity or setLayoutParams() to control gravity of an individual view in a container.

Long story: to control gravity in a linear layout container such as LinearLayout or RadioGroup, there are two approaches:

1) To control the gravity of ALL child views of a LinearLayout container (as you did in your book), use android:gravity (not android:layout_gravity) in layout XML file or setGravity() method in code.

2) To control the gravity of a child view in its container, use android:layout_gravity XML attribute. In code, one needs to get the LinearLayout.LayoutParams of the view and set its gravity. Here is a code example that set a button to bottom in a horizontally oriented container:

import android.widget.LinearLayout.LayoutParams;
import android.view.Gravity;
...

Button button = (Button) findViewById(R.id.MyButtonId);
// need to cast to LinearLayout.LayoutParams to access the gravity field
LayoutParams params = (LayoutParams)button.getLayoutParams(); 
params.gravity = Gravity.BOTTOM;
button.setLayoutParams(params);

For horizontal LinearLayout container, the horizontal gravity of its child view is left-aligned one after another and cannot be changed. Setting android:layout_gravity to center_horizontal has no effect. The default vertical gravity is center (or center_vertical) and can be changed to top or bottom. Actually the default layout_gravity value is -1 but Android put it center vertically.

To change the horizontal positions of child views in a horizontal linear container, one can use layout_weight, margin and padding of the child view.

Similarly, for vertical View Group container, the vertical gravity of its child view is top-aligned one below another and cannot be changed. The default horizontal gravity is center (or center_horizontal) and can be changed to left or right.

Actually, a child view such as a button also has android:gravity XML attribute and the setGravity() method to control its child views -- the text in it. The Button.setGravity(int) is linked to this developer.android.com entry.

ASP.NET MVC Page Won't Load and says "The resource cannot be found"

I found the solution for this problem, you don't have to delete the global.asax, as it contains some valuable info for your proyect to run smoothly, instead have a look at your controller's name, in my case, my controller was named something as MyController.cs and in the global.asax it's trying to reference a Home Controller.

Look for this lines in the global asax

routes.MapRoute(
   "Default", // Route name
   "{controller}/{action}/{id}", // URL with parameters
   new { controller = "Home", action = "Index", id = UrlParameter.Optional } 

in my case i had to get like this to work

    new { controller = "My", action = "Index", id = UrlParameter.Optional }

C# Java HashMap equivalent

I just wanted to give my two cents.
This is according to @Powerlord 's answer.

Puts "null" instead of null strings.

private static Dictionary<string, string> map = new Dictionary<string, string>();

public static void put(string key, string value)
{
    if (value == null) value = "null";
    map[key] = value;
}

public static string get(string key, string defaultValue)
{
    try
    {
        return map[key];
    }
    catch (KeyNotFoundException e)
    {
        return defaultValue;
    }
}

public static string get(string key)
{
    return get(key, "null");
}

Can't open config file: /usr/local/ssl/openssl.cnf on Windows

SOLUTION!

just set -config parameter location correctly, i.e :

openssl ....................  -config C:\bin\apache\apache2.4.9\conf\openssl.cnf

Import existing source code to GitHub

  1. Open your GitHub dashboard (it's at https://github.com/ if you're logged in)
  2. Click on New Repository
  3. Fill in the blanks; click on Create Repository
  4. Follow instructions on the page that appears then

AngularJS ng-repeat handle empty list case

And if you want to use this with a filtered list here's a neat trick:

<ul>
    <li ng-repeat="item in filteredItems  = (items | filter:keyword)">
        ...
    </li>
</ul>
<div ng-hide="filteredItems.length">No items found</div>

SQL 'LIKE' query using '%' where the search criteria contains '%'

Escape the percent sign \% to make it part of your comparison value.

Trees in Twitter Bootstrap

If someone wants expandable/collapsible version of the treeview from Vitaliy Bychik's answer, you can save some time :)

http://jsfiddle.net/mehmetatas/fXzHS/2/

$(function () {
    $('.tree li').hide();
    $('.tree li:first').show();
    $('.tree li').on('click', function (e) {
        var children = $(this).find('> ul > li');
        if (children.is(":visible")) children.hide('fast');
        else children.show('fast');
        e.stopPropagation();
    });
});

Batch file to run a command in cmd within a directory

CMD.EXE will not execute internal commands contained inside the string. Only actual files can be launched with that string.

You will need to actually call a batch file to do what you want.

BAT1.bat

start cmd.exe /k bat2.bat

BAT2.bat

cd C:\activiti-5.9\setup
ant demo.start

You may want to create a folder called BAT, and add it's location to your path. So if you create C:\BAT, add C:\BAT\; to the path. The path is located at:

    click -> Start -> right-click Computer -> Properties ->
    click -> Avanced System Settings -> Environment Variables
   select -> Path (From either list. User Variables are specific to 
                   your profile, System Variables are, duh, system-wide.)
    Click -> Edit
Press the -> the [END] or [HOME] key.
     Type -> C:\BAT\;
    Click -> OK -> OK

Now place all your batch files in C:\BAT and they will be found, regardless of the current directory.

How to do a regular expression replace in MySQL?

My brute force method to get this to work was just:

  1. Dump the table - mysqldump -u user -p database table > dump.sql
  2. Find and replace a couple patterns - find /path/to/dump.sql -type f -exec sed -i 's/old_string/new_string/g' {} \;, There are obviously other perl regeular expressions you could perform on the file as well.
  3. Import the table - mysqlimport -u user -p database table < dump.sql

If you want to make sure the string isn't elsewhere in your dataset, run a few regular expressions to make sure they all occur in a similar environment. It's also not that tough to create a backup before you run a replace, in case you accidentally destroy something that loses depth of information.

how to make window.open pop up Modal?

I was able to make parent window disable. However making the pop-up always keep raised didn't work. Below code works even for frame tags. Just add id and class property to frame tag and it works well there too.

In parent window use:

<head>    
<style>
.disableWin{
     pointer-events: none;
}
</style>
<script type="text/javascript">
    function openPopUp(url) {
      disableParentWin(); 
      var win = window.open(url);
      win.focus();
      checkPopUpClosed(win);
    }
    /*Function to detect pop up is closed and take action to enable parent window*/
   function checkPopUpClosed(win) {
         var timer = setInterval(function() {
              if(win.closed) {
                  clearInterval(timer);                  
                  enableParentWin();
              }
          }, 1000);
     }
     /*Function to enable parent window*/ 
     function enableParentWin() {
          window.document.getElementById('mainDiv').class="";
     }
     /*Function to enable parent window*/ 
     function disableParentWin() {
          window.document.getElementById('mainDiv').class="disableWin";
     }

</script>
</head>

<body>
<div id="mainDiv class="">
</div>
</body>    

Change color of Label in C#

You can try this with Color.FromArgb:

Random rnd = new Random();
lbl.ForeColor = Color.FromArgb(rnd.Next(255), rnd.Next(255), rnd.Next(255));

Perform commands over ssh with Python

Have a look at spurplus, a wrapper we developed around spur that provides type annotations and some minor gimmicks (reconnecting SFTP, md5 etc.): https://pypi.org/project/spurplus/

how to change any data type into a string in python

myvariable = 4
mystring = str(myvariable)  # '4'

also, alternatively try repr:

mystring = repr(myvariable) # '4'

This is called "conversion" in python, and is quite common.

How do I add an integer value with javascript (jquery) to a value that's returning a string?

The integer is being converted into a string rather than vice-versa. You want:

var newValue = parseInt(currentValue) + 1