Programs & Examples On #First class functions

First-class functions can be assigned to variables, passed to other functions as arguments, or returned from other functions. The ability to return a function enables deferred execution. Functions that accept other functions as arguments are called higher-order functions.

Python - Passing a function into another function

A function name can become a variable name (and thus be passed as an argument) by dropping the parentheses. A variable name can become a function name by adding the parentheses.

In your example, equate the variable rules to one of your functions, leaving off the parentheses and the mention of the argument. Then in your game() function, invoke rules( v ) with the parentheses and the v parameter.

if puzzle == type1:
    rules = Rule1
else:
    rules = Rule2

def Game(listA, listB, rules):
    if rules( v ) == True:
        do...
    else:
        do...

How I could add dir to $PATH in Makefile?

Did you try export directive of Make itself (assuming that you use GNU Make)?

export PATH := bin:$(PATH)

test all:
    x

Also, there is a bug in you example:

test all:
    PATH=bin:${PATH}
    @echo $(PATH)
    x

First, the value being echoed is an expansion of PATH variable performed by Make, not the shell. If it prints the expected value then, I guess, you've set PATH variable somewhere earlier in your Makefile, or in a shell that invoked Make. To prevent such behavior you should escape dollars:

test all:
    PATH=bin:$$PATH
    @echo $$PATH
    x

Second, in any case this won't work because Make executes each line of the recipe in a separate shell. This can be changed by writing the recipe in a single line:

test all:
    export PATH=bin:$$PATH; echo $$PATH; x

'System.Net.Http.HttpContent' does not contain a definition for 'ReadAsAsync' and no extension method

USE This Assembly Referance in your Project

Add a reference to System.Net.Http.Formatting.dll

Mercurial — revert back to old version and continue from there

hg update [-r REV]

If later you commit, you will effectively create a new branch. Then you might continue working only on this branch or eventually merge the existing one into it.

How to set the timeout for a TcpClient?

Set ReadTimeout or WriteTimeout property on the NetworkStream for synchronous reads/writes. Updating OP's code:

try
{
    TcpClient client = new TcpClient("remotehost", this.Port);
    Byte[] data = System.Text.Encoding.Unicode.GetBytes(this.Message);
    NetworkStream stream = client.GetStream();
    stream.WriteTimeout = 1000; //  <------- 1 second timeout
    stream.ReadTimeout = 1000; //  <------- 1 second timeout
    stream.Write(data, 0, data.Length);
    data = new Byte[512];
    Int32 bytes = stream.Read(data, 0, data.Length);
    this.Response = System.Text.Encoding.Unicode.GetString(data, 0, bytes);

    stream.Close();
    client.Close();    

    FireSentEvent();  //Notifies of success
}
catch (Exception ex)
{
    // Throws IOException on stream read/write timeout
    FireFailedEvent(ex); //Notifies of failure
}

How to set the background image of a html 5 canvas to .png image

You can draw the image on the canvas and let the user draw on top of that.

The drawImage() function will help you with that, see https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Using_images

How to replace string in Groovy

You need to escape the backslash \:

println yourString.replace("\\", "/")

PHP - Merging two arrays into one array (also Remove Duplicates)

try to use the array_unique()

this elminates duplicated data inside the list of your arrays..

Android Studio Stuck at Gradle Download on create new project

Solution :

1). Delete the C:\Users\username.gradle folder

2). Download http://downloads.gradle.org/distributions/gradle-2.2.1-all.zip

3). Create a new project in android studio.

4). When this time it stucks at gradle building, Force close the android studio.

5) Now go to C:\Users\username.gradle\wrapper\dists\gradle-2.2.1-all\c64ydeuardnfqctvr1gm30w53 (the end directory name may be different)

6) Delete gradle-2.2.1-all.zip.lck and other files from this directory.

7) Paste the new downloaded gradle-2.2.1-all.zip here.

8) Run the android studio. :)

Index was out of range. Must be non-negative and less than the size of the collection parameter name:index

The error says "The index is out of range". That means you were trying to index an object with a value that was not valid. If you have two books, and I ask you to give me your third book, you will look at me funny. This is the computer looking at you funny. You said - "create a collection". So it did. But initially the collection is empty: not only is there nothing in it - it has no space to hold anything. "It has no hands".

Then you said "the first element of the collection is now 'ItemID'". And the computer says "I never was asked to create space for a 'first item'." I have no hands to hold this item you are giving me.

In terms of your code, you created a view, but never specified the size. You need a

dataGridView1.ColumnCount = 5;

Before trying to access any columns. Modify

DataGridView dataGridView1 = new DataGridView();

dataGridView1.Columns[0].Name = "ItemID";

to

DataGridView dataGridView1 = new DataGridView();
dataGridView1.ColumnCount = 5;
dataGridView1.Columns[0].Name = "ItemID";

See http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.columncount.aspx

Foreach Control in form, how can I do something to all the TextBoxes in my Form?

If you are using C# 3.0 or higher you can do the following

foreach ( TextBox tb in this.Controls.OfType<TextBox>()) {
  ..
}

Without C# 3.0 you can do the following

foreach ( Control c in this.Controls ) {
  TextBox tb = c as TextBox;
  if ( null != tb ) {
    ...
  }
}

Or even better, write OfType in C# 2.0.

public static IEnumerable<T> OfType<T>(IEnumerable e) where T : class { 
  foreach ( object cur in e ) {
    T val = cur as T;
    if ( val != null ) {
      yield return val;
    }
  }
}

foreach ( TextBox tb in OfType<TextBox>(this.Controls)) {
  ..
}

Truncate with condition

You can simply export the table with a query clause using datapump and import it back with table_exists_action=replace clause. Its will drop and recreate your table and take very less time. Please read about it before implementing.

MySQL "WITH" clause

   WITH authorRating as (select aname, rating from book)
   SELECT aname, AVG(quantity)
   FROM authorRating
   GROUP BY aname

Can you do a For Each Row loop using MySQL?

In the link you provided, thats not a loop in sql...

thats a loop in programming language

they are first getting list of all distinct districts, and then for each district executing query again.

Construct pandas DataFrame from items in nested dictionary

pd.concat accepts a dictionary. With this in mind, it is possible to improve upon the currently accepted answer in terms of simplicity and performance by use a dictionary comprehension to build a dictionary mapping keys to sub-frames.

pd.concat({k: pd.DataFrame(v).T for k, v in user_dict.items()}, axis=0)

Or,

pd.concat({
        k: pd.DataFrame.from_dict(v, 'index') for k, v in user_dict.items()
    }, 
    axis=0)

              att_1     att_2
12 Category 1     1  whatever
   Category 2    23   another
15 Category 1    10       foo
   Category 2    30       bar

Get a list of dates between two dates

Borrowing an idea from this answer, you can set up a table with 0 through 9 and use that to generate your list of dates.

CREATE TABLE num (i int);
INSERT INTO num (i) VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);

select adddate('2009-01-01', numlist.id) as `date` from
(SELECT n1.i + n10.i*10 + n100.i*100 AS id
   FROM num n1 cross join num as n10 cross join num as n100) as numlist
where adddate('2009-01-01', numlist.id) <= '2009-01-13';

This will allow you to generate a list of up to 1000 dates. If you need to go larger, you can add another cross join to the inner query.

How to output something in PowerShell

I think in this case you will need Write-Output.

If you have a script like

Write-Output "test1";
Write-Host "test2";
"test3";

then, if you call the script with redirected output, something like yourscript.ps1 > out.txt, you will get test2 on the screen test1\ntest3\n in the "out.txt".

Note that "test3" and the Write-Output line will always append a new line to your text and there is no way in PowerShell to stop this (that is, echo -n is impossible in PowerShell with the native commands). If you want (the somewhat basic and easy in Bash) functionality of echo -n then see samthebest's answer.

If a batch file runs a PowerShell command, it will most likely capture the Write-Output command. I have had "long discussions" with system administrators about what should be written to the console and what should not. We have now agreed that the only information if the script executed successfully or died has to be Write-Host'ed, and everything that is the script's author might need to know about the execution (what items were updated, what fields were set, et cetera) goes to Write-Output. This way, when you submit a script to the system administrator, he can easily runthescript.ps1 >someredirectedoutput.txt and see on the screen, if everything is OK. Then send the "someredirectedoutput.txt" back to the developers.

How to save a plot into a PDF file without a large margin around

It seems to me that all approaches (file exchange solutions unconsidered) here are lacking the essential step, or finally leading to it via some blurry workarounds.

The figure size needs to equal the paper size and the white margins are gone.

A = hgload('myFigure.fig');

% set desired output size
set(A, 'Units','centimeters')
height = 15;
width = 19;

% the last two parameters of 'Position' define the figure size
set(A, 'Position',[25 5 width height],...
       'PaperSize',[width height],...
       'PaperPositionMode','auto',...
       'InvertHardcopy', 'off',...
       'Renderer','painters'...     %recommended if there are no alphamaps
   );

saveas(A,'printout','pdf')

Will give you a pdf output as your figure appears, in exactly the size you want. If you want to get it even tighter you can combine this solution with the answer of b3.

Align text in a table header

Try:

text-align: center;

You may be familiar with the HTML align attribute (which has been discontinued as of HTML 5). The align attribute could be used with tags such as

<table>, <td>, and <img> 

to specify the alignment of these elements. This attribute allowed you to align elements horizontally. HTML also has/had a valign attribute for aligning elements vertically. This has also been discontinued from HTML5.

These attributes were discontinued in favor of using CSS to set the alignment of HTML elements.

There isn't actually a CSS align or CSS valign property. Instead, CSS has the text-align which applies to inline content of block-level elements, and vertical-align property which applies to inline level and table cells.

Python strftime - date without leading 0?

Some platforms may support width and precision specification between % and the letter (such as 'd' for day of month), according to http://docs.python.org/library/time.html -- but it's definitely a non-portable solution (e.g. doesn't work on my Mac;-). Maybe you can use a string replace (or RE, for really nasty format) after the strftime to remedy that? e.g.:

>>> y
(2009, 5, 7, 17, 17, 17, 3, 127, 1)
>>> time.strftime('%Y %m %d', y)
'2009 05 07'
>>> time.strftime('%Y %m %d', y).replace(' 0', ' ')
'2009 5 7'

The import android.support cannot be resolved

Please follow these Steps:

For Eclipse:

  • Go to your Project's Properties
  • Navigate to the Java Build Path
  • Then go to the Libraries tab. There click the Add External JARs Button on the Right pane.
  • Select the android-support-v4.jar file, usually the path for the Jar file is :
    YOUR_DRIVE\android-sdks\extras\android\support\v4\android-support-v4.jar
  • After adding android-support-v4.jar Library, navigate to the Order and Export tab and put check mark on the android-support-v4 Library file.
  • After doing the above, Clean the Project and Build it.
  • Problem Solved.

For Android Studio:

Short Version:

  • Add the following line to your build.gradle file:
    implementation 'com.android.support:support-v4:YOUR_TARGET_VERSION'

Long Version:

  • Go to File -> Project Structure

  • Go to "Dependencies" Tab -> Click on the Plus sign -> Go to "Library dependency"

  • Select the support library "support-v4 (com.android.support:support-v4:YOUR_TARGET_VERSION)"

  • Navigate to your "build.gradle" inside your App Directory and double check if your desired Android Support Library has been added to your dependencies.

  • Rebuild your project and now everything should work.

Further reading regarding this Question:

  1. Support Library - Android Dev
  2. Recent Support Library Revisions
  3. Support Library Packages
  4. What is an Android Support Library?
  5. How Android Support Library work?

I hope this helps.

Check if a String contains a special character

//this is updated version of code that i posted /* The isValidName Method will check whether the name passed as argument should not contain- 1.null value or space 2.any special character 3.Digits (0-9) Explanation--- Here str2 is String array variable which stores the the splited string of name that is passed as argument The count variable will count the number of special character occurs The method will return true if it satisfy all the condition */

public boolean isValidName(String name)
{
    String specialCharacters=" !#$%&'()*+,-./:;<=>?@[]^_`{|}~0123456789";
    String str2[]=name.split("");
    int count=0;
    for (int i=0;i<str2.length;i++)
    {
        if (specialCharacters.contains(str2[i]))
        {
            count++;
        }
    }       

    if (name!=null && count==0 )
    {
        return true;
    }
    else
    {
        return false;
    }
}

How do you use youtube-dl to download live streams (that are live)?

I'll be using this Live Event from NASA TV as an example:

https://www.youtube.com/watch?v=21X5lGlDOfg

First, list the formats for the video:

$  ~ youtube-dl --list-formats https://www.youtube.com/watch\?v\=21X5lGlDOfg
[youtube] 21X5lGlDOfg: Downloading webpage
[youtube] 21X5lGlDOfg: Downloading m3u8 information
[youtube] 21X5lGlDOfg: Downloading MPD manifest
[info] Available formats for 21X5lGlDOfg:
format code  extension  resolution note
91           mp4        256x144    HLS  197k , avc1.42c00b, 30.0fps, mp4a.40.5@ 48k
92           mp4        426x240    HLS  338k , avc1.4d4015, 30.0fps, mp4a.40.5@ 48k
93           mp4        640x360    HLS  829k , avc1.4d401e, 30.0fps, mp4a.40.2@128k
94           mp4        854x480    HLS 1380k , avc1.4d401f, 30.0fps, mp4a.40.2@128k
300          mp4        1280x720   3806k , avc1.4d4020, 60.0fps, mp4a.40.2 (best)

Pick the format you wish to download, and fetch the HLS m3u8 URL of the video from the manifest. I'll be using 94 mp4 854x480 HLS 1380k , avc1.4d401f, 30.0fps, mp4a.40.2@128k for this example:

?  ~ youtube-dl -f 94 -g https://www.youtube.com/watch\?v\=21X5lGlDOfg
https://manifest.googlevideo.com/api/manifest/hls_playlist/expire/1592099895/ei/1y_lXuLOEsnXyQWYs4GABw/ip/81.190.155.248/id/21X5lGlDOfg.3/itag/94/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/goi/160/sgoap/gir%3Dyes%3Bitag%3D140/sgovp/gir%3Dyes%3Bitag%3D135/hls_chunk_host/r5---sn-h0auphxqp5-f5fs.googlevideo.com/playlist_duration/30/manifest_duration/30/vprv/1/playlist_type/DVR/initcwndbps/8270/mh/N8/mm/44/mn/sn-h0auphxqp5-f5fs/ms/lva/mv/m/mvi/4/pl/16/dover/11/keepalive/yes/beids/9466586/mt/1592078245/disable_polymer/true/sparams/expire,ei,ip,id,itag,source,requiressl,ratebypass,live,goi,sgoap,sgovp,playlist_duration,manifest_duration,vprv,playlist_type/sig/AOq0QJ8wRgIhAM2dGSece2shUTgS73Qa3KseLqnf85ca_9u7Laz7IDfSAiEAj8KHw_9xXVS_PV3ODLlwDD-xfN6rSOcLVNBpxKgkRLI%3D/lsparams/hls_chunk_host,initcwndbps,mh,mm,mn,ms,mv,mvi,pl/lsig/AG3C_xAwRQIhAJCO6kSwn7PivqMW7sZaiYFvrultXl6Qmu9wppjCvImzAiA7vkub9JaanJPGjmB4qhLVpHJOb9fZyhMEeh1EUCd-3Q%3D%3D/playlist/index.m3u8

Note that link could be different and it contains expiration timestamp, in this case 1592099895 (about 6 hours).

Now that you have the HLS playlist, you can open this URL in VLC and save it using "Record", or write a small ffmpeg command:

ffmpeg -i \
https://manifest.googlevideo.com/api/manifest/hls_playlist/expire/1592099895/ei/1y_lXuLOEsnXyQWYs4GABw/ip/81.190.155.248/id/21X5lGlDOfg.3/itag/94/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/goi/160/sgoap/gir%3Dyes%3Bitag%3D140/sgovp/gir%3Dyes%3Bitag%3D135/hls_chunk_host/r5---sn-h0auphxqp5-f5fs.googlevideo.com/playlist_duration/30/manifest_duration/30/vprv/1/playlist_type/DVR/initcwndbps/8270/mh/N8/mm/44/mn/sn-h0auphxqp5-f5fs/ms/lva/mv/m/mvi/4/pl/16/dover/11/keepalive/yes/beids/9466586/mt/1592078245/disable_polymer/true/sparams/expire,ei,ip,id,itag,source,requiressl,ratebypass,live,goi,sgoap,sgovp,playlist_duration,manifest_duration,vprv,playlist_type/sig/AOq0QJ8wRgIhAM2dGSece2shUTgS73Qa3KseLqnf85ca_9u7Laz7IDfSAiEAj8KHw_9xXVS_PV3ODLlwDD-xfN6rSOcLVNBpxKgkRLI%3D/lsparams/hls_chunk_host,initcwndbps,mh,mm,mn,ms,mv,mvi,pl/lsig/AG3C_xAwRQIhAJCO6kSwn7PivqMW7sZaiYFvrultXl6Qmu9wppjCvImzAiA7vkub9JaanJPGjmB4qhLVpHJOb9fZyhMEeh1EUCd-3Q%3D%3D/playlist/index.m3u8 \
-c copy output.ts

Defining static const integer members in class definition

My understanding is that C++ allows static const members to be defined inside a class so long as it's an integer type.

You are sort of correct. You are allowed to initialize static const integrals in the class declaration but that is not a definition.

http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=/com.ibm.xlcpp8a.doc/language/ref/cplr038.htm

Interestingly, if I comment out the call to std::min, the code compiles and links just fine (even though test::N is also referenced on the previous line).

Any idea as to what's going on?

std::min takes its parameters by const reference. If it took them by value you'd not have this problem but since you need a reference you also need a definition.

Here's chapter/verse:

9.4.2/4 - If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.

See Chu's answer for a possible workaround.

apache and httpd running but I can't see my website

Did you restart the server after you changed the config file?

Can you telnet to the server from a different machine?

Can you telnet to the server from the server itself?

telnet <ip address> 80

telnet localhost 80

How to hide .php extension in .htaccess

The other option for using PHP scripts sans extension is

Options +MultiViews

Or even just following in the directories .htaccess:

DefaultType application/x-httpd-php

The latter allows having all filenames without extension script being treated as PHP scripts. While MultiViews makes the webserver look for alternatives, when just the basename is provided (there's a performance hit with that however).

Gradle, Android and the ANDROID_HOME SDK location

This works for me:

$ export ANDROID_HOME=/path_to_sdk/
$ ./gradlew

plotting different colors in matplotlib

for color in ['r', 'b', 'g', 'k', 'm']:
    plot(x, y, color=color)

How to capitalize the first letter of word in a string using Java?

public String capitalizeFirstLetter(String original) {
    if (original == null || original.length() == 0) {
        return original;
    }
    return original.substring(0, 1).toUpperCase() + original.substring(1);
}

Just... a complete solution, I see it kind of just ended up combining what everyone else ended up posting =P.

Output in a table format in Java's System.out

I may be very late for the Answer but here a simple and generic solution

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class TableGenerator {

    private int PADDING_SIZE = 2;
    private String NEW_LINE = "\n";
    private String TABLE_JOINT_SYMBOL = "+";
    private String TABLE_V_SPLIT_SYMBOL = "|";
    private String TABLE_H_SPLIT_SYMBOL = "-";

    public String generateTable(List<String> headersList, List<List<String>> rowsList,int... overRiddenHeaderHeight)
    {
        StringBuilder stringBuilder = new StringBuilder();

        int rowHeight = overRiddenHeaderHeight.length > 0 ? overRiddenHeaderHeight[0] : 1; 

        Map<Integer,Integer> columnMaxWidthMapping = getMaximumWidhtofTable(headersList, rowsList);

        stringBuilder.append(NEW_LINE);
        stringBuilder.append(NEW_LINE);
        createRowLine(stringBuilder, headersList.size(), columnMaxWidthMapping);
        stringBuilder.append(NEW_LINE);


        for (int headerIndex = 0; headerIndex < headersList.size(); headerIndex++) {
            fillCell(stringBuilder, headersList.get(headerIndex), headerIndex, columnMaxWidthMapping);
        }

        stringBuilder.append(NEW_LINE);

        createRowLine(stringBuilder, headersList.size(), columnMaxWidthMapping);


        for (List<String> row : rowsList) {

            for (int i = 0; i < rowHeight; i++) {
                stringBuilder.append(NEW_LINE);
            }

            for (int cellIndex = 0; cellIndex < row.size(); cellIndex++) {
                fillCell(stringBuilder, row.get(cellIndex), cellIndex, columnMaxWidthMapping);
            }

        }

        stringBuilder.append(NEW_LINE);
        createRowLine(stringBuilder, headersList.size(), columnMaxWidthMapping);
        stringBuilder.append(NEW_LINE);
        stringBuilder.append(NEW_LINE);

        return stringBuilder.toString();
    }

    private void fillSpace(StringBuilder stringBuilder, int length)
    {
        for (int i = 0; i < length; i++) {
            stringBuilder.append(" ");
        }
    }

    private void createRowLine(StringBuilder stringBuilder,int headersListSize, Map<Integer,Integer> columnMaxWidthMapping)
    {
        for (int i = 0; i < headersListSize; i++) {
            if(i == 0)
            {
                stringBuilder.append(TABLE_JOINT_SYMBOL);   
            }

            for (int j = 0; j < columnMaxWidthMapping.get(i) + PADDING_SIZE * 2 ; j++) {
                stringBuilder.append(TABLE_H_SPLIT_SYMBOL);
            }
            stringBuilder.append(TABLE_JOINT_SYMBOL);
        }
    }


    private Map<Integer,Integer> getMaximumWidhtofTable(List<String> headersList, List<List<String>> rowsList)
    {
        Map<Integer,Integer> columnMaxWidthMapping = new HashMap<>();

        for (int columnIndex = 0; columnIndex < headersList.size(); columnIndex++) {
            columnMaxWidthMapping.put(columnIndex, 0);
        }

        for (int columnIndex = 0; columnIndex < headersList.size(); columnIndex++) {

            if(headersList.get(columnIndex).length() > columnMaxWidthMapping.get(columnIndex))
            {
                columnMaxWidthMapping.put(columnIndex, headersList.get(columnIndex).length());
            }
        }


        for (List<String> row : rowsList) {

            for (int columnIndex = 0; columnIndex < row.size(); columnIndex++) {

                if(row.get(columnIndex).length() > columnMaxWidthMapping.get(columnIndex))
                {
                    columnMaxWidthMapping.put(columnIndex, row.get(columnIndex).length());
                }
            }
        }

        for (int columnIndex = 0; columnIndex < headersList.size(); columnIndex++) {

            if(columnMaxWidthMapping.get(columnIndex) % 2 != 0)
            {
                columnMaxWidthMapping.put(columnIndex, columnMaxWidthMapping.get(columnIndex) + 1);
            }
        }


        return columnMaxWidthMapping;
    }

    private int getOptimumCellPadding(int cellIndex,int datalength,Map<Integer,Integer> columnMaxWidthMapping,int cellPaddingSize)
    {
        if(datalength % 2 != 0)
        {
            datalength++;
        }

        if(datalength < columnMaxWidthMapping.get(cellIndex))
        {
            cellPaddingSize = cellPaddingSize + (columnMaxWidthMapping.get(cellIndex) - datalength) / 2;
        }

        return cellPaddingSize;
    }

    private void fillCell(StringBuilder stringBuilder,String cell,int cellIndex,Map<Integer,Integer> columnMaxWidthMapping)
    {

        int cellPaddingSize = getOptimumCellPadding(cellIndex, cell.length(), columnMaxWidthMapping, PADDING_SIZE);

        if(cellIndex == 0)
        {
            stringBuilder.append(TABLE_V_SPLIT_SYMBOL); 
        }

        fillSpace(stringBuilder, cellPaddingSize);
        stringBuilder.append(cell);
        if(cell.length() % 2 != 0)
        {
            stringBuilder.append(" ");
        }

        fillSpace(stringBuilder, cellPaddingSize);

        stringBuilder.append(TABLE_V_SPLIT_SYMBOL); 

    }

    public static void main(String[] args) {
        TableGenerator tableGenerator = new TableGenerator();

        List<String> headersList = new ArrayList<>(); 
        headersList.add("Id");
        headersList.add("F-Name");
        headersList.add("L-Name");
        headersList.add("Email");

        List<List<String>> rowsList = new ArrayList<>();

        for (int i = 0; i < 5; i++) {
            List<String> row = new ArrayList<>(); 
            row.add(UUID.randomUUID().toString());
            row.add(UUID.randomUUID().toString());
            row.add(UUID.randomUUID().toString());
            row.add(UUID.randomUUID().toString());

            rowsList.add(row);
        }

        System.out.println(tableGenerator.generateTable(headersList, rowsList));
    }
}

With this kind of Output

+----------------------------------------+----------------------------------------+----------------------------------------+----------------------------------------+
|                   Id                   |                F-Name                  |                 L-Name                 |                  Email                 |
+----------------------------------------+----------------------------------------+----------------------------------------+----------------------------------------+
|  70a56f25-d42a-499c-83ac-50188c45a0ac  |  aa04285e-c135-46e2-9f90-988bf7796cd0  |  ac495ba7-d3c7-463c-8c24-9ffde67324bc  |  f6b5851b-41e0-4a4e-a237-74f8e0bff9ab  |
|  6de181ca-919a-4425-a753-78d2de1038ef  |  c4ba5771-ccee-416e-aebd-ef94b07f4fa2  |  365980cb-e23a-4513-a895-77658f130135  |  69e01da1-078e-4934-afb0-5afd6ee166ac  |
|  f3285f33-5083-4881-a8b4-c8ae10372a6c  |  46df25ed-fa0f-42a4-9181-a0528bc593f6  |  d24016bf-a03f-424d-9a8f-9a7b7388fd85  |  4b976794-aac1-441e-8bd2-78f5ccbbd653  |
|  ab799acb-a582-45e7-ba2f-806948967e6c  |  d019438d-0a75-48bc-977b-9560de4e033e  |  8cb2ad11-978b-4a67-a87e-439d0a21ef99  |  2f2d9a39-9d95-4a5a-993f-ceedd5ff9953  |
|  78a68c0a-a824-42e8-b8a8-3bdd8a89e773  |  0f030c1b-2069-4c1a-bf7d-f23d1e291d2a  |  7f647cb4-a22e-46d2-8c96-0c09981773b1  |  0bc944ef-c1a7-4dd1-9eef-915712035a74  |
+----------------------------------------+----------------------------------------+----------------------------------------+----------------------------------------+

Is it possible to set the equivalent of a src attribute of an img tag in CSS?

Some data I would leave in HTML, but it is better to define the src in CSS:

<img alt="Test Alt text" title="Title text" class="logo">

.logo {
    content:url('../images/logo.png');
}

mvn clean install vs. deploy vs. release

The clean, install and deploy phases are valid lifecycle phases and invoking them will trigger all the phases preceding them, and the goals bound to these phases.

mvn clean install

This command invokes the clean phase and then the install phase sequentially:

  • clean: removes files generated at build-time in a project's directory (target by default)
  • install: installs the package into the local repository, for use as a dependency in other projects locally.

mvn deploy

This command invokes the deploy phase:

  • deploy: copies the final package to the remote repository for sharing with other developers and projects.

mvn release

This is not a valid phase nor a goal so this won't do anything. But if refers to the Maven Release Plugin that is used to automate release management. Releasing a project is done in two steps: prepare and perform. As documented:

Preparing a release goes through the following release phases:

  • Check that there are no uncommitted changes in the sources
  • Check that there are no SNAPSHOT dependencies
  • Change the version in the POMs from x-SNAPSHOT to a new version (you will be prompted for the versions to use)
  • Transform the SCM information in the POM to include the final destination of the tag
  • Run the project tests against the modified POMs to confirm everything is in working order
  • Commit the modified POMs
  • Tag the code in the SCM with a version name (this will be prompted for)
  • Bump the version in the POMs to a new value y-SNAPSHOT (these values will also be prompted for)
  • Commit the modified POMs

And then:

Performing a release runs the following release phases:

  • Checkout from an SCM URL with optional tag
  • Run the predefined Maven goals to release the project (by default, deploy site-deploy)

See also

How do I install Eclipse with C++ in Ubuntu 12.10 (Quantal Quetzal)?

http://www.eclipse.org/cdt/ ^Give that a try

I have not used the CDT for eclipse but I do use Eclipse Java for Ubuntu 12.04 and it works wonders.

How to execute a bash command stored as a string with quotes and asterisk

To eliminate the need for the cmd variable, you can do this:

eval 'mysql AMORE -u root --password="password" -h localhost -e "select host from amoreconfig"'

Can't Find Theme.AppCompat.Light for New Android ActionBar Support

I had same problem and waste my 4-5 hours for solution. My problem solved with;

  1. From SDK manager delete packages "Android Support Library" and " Android Support Repository".
  2. Reinstall "Android Support Library" and " Android Support Repository"
  3. Remove "android-support-v7-appcompat" or "appcompat_v7 what else you have in your project.
  4. Import android-support-v7-appcompat from "adt-bundle-windows-x86_64-20140702\sdk\extras\android\support\v7\appcompat"
  5. Select your project and from file choose properties and find Java Build Path and then from "Project" tab delete what else there and then Add. and you must see "android-support-v7-appcompat" , select and add it to Project tab.
  6. Check your project.properties file below your Project files, you will see like this; target=android-21 android.library.reference.1=../android-support-v7-appcompat then check AndroidManifest.xml file if target is 21 or what else you choosed. Also check for library reference same as your library that choosed before.

Hope you will find your solution.

Java - Check Not Null/Empty else assign default value

With guava you can use

MoreObjects.firstNonNull(possiblyNullString, defaultValue);

Convert System.Drawing.Color to RGB and Hex Value

e.g.

 ColorTranslator.ToHtml(Color.FromArgb(Color.Tomato.ToArgb()))

This can avoid the KnownColor trick.

Does C# have extension properties?

No, they don't exist.

I know that the C# team was considering them at one point (or at least Eric Lippert was) - along with extension constructors and operators (those may take a while to get your head around, but are cool...) However, I haven't seen any evidence that they'll be part of C# 4.


EDIT: They didn't appear in C# 5, and as of July 2014 it doesn't look like it's going to be in C# 6 either.

Eric Lippert, the Principal Developer on the C# compiler team at Microsoft thru November 2012, blogged about this in October of 2009:

Post values from a multiple select

You need to add a name attribute.

Since this is a multiple select, at the HTTP level, the client just sends multiple name/value pairs with the same name, you can observe this yourself if you use a form with method="GET": someurl?something=1&something=2&something=3.

In the case of PHP, Ruby, and some other library/frameworks out there, you would need to add square braces ([]) at the end of the name. The frameworks will parse that string and wil present it in some easy to use format, like an array.

Apart from manually parsing the request there's no language/framework/library-agnostic way of accessing multiple values, because they all have different APIs

For PHP you can use:

<select name="something[]" id="inscompSelected" multiple="multiple" class="lstSelected">

ionic build Android | error: No installed build tools found. Please install the Android build tools

The solution for this question is here https://docops.ca.com/devtest-solutions/8-0-2/en/installing/setting-up-the-mobile-testing-environment/preinstallation-steps-for-mobile-testing/

Please follow this steps, and solve your problem.

The Android SDK package contains a component called compile tools. The mobile test requires at least version 19.0.1, 19.1.0 or 20.0.0.

If these versions are not installed with your ADT package, you may receive an error message when creating a mobile asset in the DevTest Workstation:

How do I use NSTimer?

there are a couple of ways of using a timer:

1) scheduled timer & using selector

NSTimer *t = [NSTimer scheduledTimerWithTimeInterval: 2.0
                      target: self
                      selector:@selector(onTick:)
                      userInfo: nil repeats:NO];
  • if you set repeats to NO, the timer will wait 2 seconds before running the selector and after that it will stop;
  • if repeat: YES, the timer will start immediatelly and will repeat calling the selector every 2 seconds;
  • to stop the timer you call the timer's -invalidate method: [t invalidate];

As a side note, instead of using a timer that doesn't repeat and calls the selector after a specified interval, you could use a simple statement like this:

[self performSelector:@selector(onTick:) withObject:nil afterDelay:2.0];

this will have the same effect as the sample code above; but if you want to call the selector every nth time, you use the timer with repeats:YES;

2) self-scheduled timer

NSDate *d = [NSDate dateWithTimeIntervalSinceNow: 60.0];
NSTimer *t = [[NSTimer alloc] initWithFireDate: d
                              interval: 1
                              target: self
                              selector:@selector(onTick:)
                              userInfo:nil repeats:YES];

NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer:t forMode: NSDefaultRunLoopMode];
[t release];
  • this will create a timer that will start itself on a custom date specified by you (in this case, after a minute), and repeats itself every one second

3) unscheduled timer & using invocation

NSMethodSignature *sgn = [self methodSignatureForSelector:@selector(onTick:)];
NSInvocation *inv = [NSInvocation invocationWithMethodSignature: sgn];
[inv setTarget: self];
[inv setSelector:@selector(onTick:)];

NSTimer *t = [NSTimer timerWithTimeInterval: 1.0
                      invocation:inv 
                      repeats:YES];

and after that, you start the timer manually whenever you need like this:

NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer: t forMode: NSDefaultRunLoopMode];



And as a note, onTick: method looks like this:

-(void)onTick:(NSTimer *)timer {
   //do smth
}

Escape invalid XML characters in C#

// Replace invalid characters with empty strings.
   Regex.Replace(inputString, @"[^\w\.@-]", ""); 

The regular expression pattern [^\w.@-] matches any character that is not a word character, a period, an @ symbol, or a hyphen. A word character is any letter, decimal digit, or punctuation connector such as an underscore. Any character that matches this pattern is replaced by String.Empty, which is the string defined by the replacement pattern. To allow additional characters in user input, add those characters to the character class in the regular expression pattern. For example, the regular expression pattern [^\w.@-\%] also allows a percentage symbol and a backslash in an input string.

Regex.Replace(inputString, @"[!@#$%_]", "");

Refer this too :

Removing Invalid Characters from XML Name Tag - RegEx C#

Here is a function to remove the characters from a specified XML string:

using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace XMLUtils
{
    class Standards
    {
        /// <summary>
        /// Strips non-printable ascii characters 
        /// Refer to http://www.w3.org/TR/xml11/#charsets for XML 1.1
        /// Refer to http://www.w3.org/TR/2006/REC-xml-20060816/#charsets for XML 1.0
        /// </summary>
        /// <param name="content">contents</param>
        /// <param name="XMLVersion">XML Specification to use. Can be 1.0 or 1.1</param>
        private void StripIllegalXMLChars(string tmpContents, string XMLVersion)
        {    
            string pattern = String.Empty;
            switch (XMLVersion)
            {
                case "1.0":
                    pattern = @"#x((10?|[2-F])FFF[EF]|FDD[0-9A-F]|7F|8[0-46-9A-F]9[0-9A-F])";
                    break;
                case "1.1":
                    pattern = @"#x((10?|[2-F])FFF[EF]|FDD[0-9A-F]|[19][0-9A-F]|7F|8[0-46-9A-F]|0?[1-8BCEF])";
                    break;
                default:
                    throw new Exception("Error: Invalid XML Version!");
            }

            Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
            if (regex.IsMatch(tmpContents))
            {
                tmpContents = regex.Replace(tmpContents, String.Empty);
            }
            tmpContents = string.Empty;
        }
    }
}

Android - Start service on boot

Looks very similar to mine but I use the full package name for the receiver:

<receiver android:name=".StartupIntentReceiver">

I have:

<receiver android:name="com.your.package.AutoStart"> 

How is a non-breaking space represented in a JavaScript string?

Remember that .text() strips out markup, thus I don't believe you're going to find &nbsp; in a non-markup result.

Made in to an answer....

var p = $('<p>').html('&nbsp;');
if (p.text() == String.fromCharCode(160) && p.text() == '\xA0')
    alert('Character 160');

Shows an alert, as the ASCII equivalent of the markup is returned instead.

batch script - run command on each file in directory

Actually this is pretty easy since Windows Vista. Microsoft added the command FORFILES

in your case

forfiles /p c:\directory /m *.xls /c "cmd /c ssconvert @file @fname.xlsx"

the only weird thing with this command is that forfiles automatically adds double quotes around @file and @fname. but it should work anyway

How to use nan and inf in C?

A compiler independent way, but not processor independent way to get these:

int inf = 0x7F800000;
return *(float*)&inf;

int nan = 0x7F800001;
return *(float*)&nan;

This should work on any processor which uses the IEEE 754 floating point format (which x86 does).

UPDATE: Tested and updated.

SQL Server: SELECT only the rows with MAX(DATE)

select OrderNo,PartCode,Quantity
from dbo.Test t1
WHERE EXISTS(SELECT 1
         FROM dbo.Test t2
         WHERE t2.OrderNo = t1.OrderNo
           AND t2.PartCode = t1.PartCode
         GROUP BY t2.OrderNo,
                  t2.PartCode
         HAVING t1.DateEntered = MAX(t2.DateEntered))

This is the fastest of all the queries supplied above. The query cost came in at 0.0070668.

The preferred answer above, by Mikael Eriksson, has a query cost of 0.0146625

You may not care about the performance for such a small sample, but in large queries, it all adds up.

Android Studio not showing modules in project structure

Please go to Module settings and choose Modules from Project Settings then you need to Select src and gen folders and marked them as Source folders by right-click on them and select Source

Android Studio - ADB Error - "...device unauthorized. Please check the confirmation dialog on your device."

I've got the same message too. In my case, I have changed my dev environment to another notebook pc and my device is samsung galaxy note 2014 edition. My OS is windows 7

My galaxy note condition listed as following

  • developer option activated
  • USB debugging checked

The error message was "device unauthorized. Please check the..."

In general, the location of the default android setting was C:/Users/Your_login_name/.android then I copied and pasted all files in the '.android' folder to my new pc's setting folder.

After that the problem was gone.

I think the problem was adbkey file mismatched. Also, I didn't have any menu name such as revoke adb authorization.

How to check if a string "StartsWith" another string?

Also check out underscore.string.js. It comes with a bunch of useful string testing and manipulation methods, including a startsWith method. From the docs:

startsWith _.startsWith(string, starts)

This method checks whether string starts with starts.

_("image.gif").startsWith("image")
=> true

How do I tell whether my IE is 64-bit? (For that matter, Java too?)

Select Help->About

for 64 bit.. it would say version as 64 bit Edition.

I see this in IE 9.. may be true with lesser versions too..

Display encoded html with razor

Try this:

<div class='content'>    
   @Html.Raw(HttpUtility.HtmlDecode(Model.Content))
</div>

How to implement the --verbose or -v option into a script?

Use the logging module:

import logging as log
…
args = p.parse_args()
if args.verbose:
    log.basicConfig(format="%(levelname)s: %(message)s", level=log.DEBUG)
    log.info("Verbose output.")
else:
    log.basicConfig(format="%(levelname)s: %(message)s")

log.info("This should be verbose.")
log.warning("This is a warning.")
log.error("This is an error.")

All of these automatically go to stderr:

% python myprogram.py
WARNING: This is a warning.
ERROR: This is an error.

% python myprogram.py -v
INFO: Verbose output.
INFO: This should be verbose.
WARNING: This is a warning.
ERROR: This is an error.

For more info, see the Python Docs and the tutorials.

UICollectionView current visible cell index

Just want to add for others : for some reason, I didnt not get the cell that was visible to the user when I was scrolling to previous cell in collectionView with pagingEnabled.

So I insert the code inside dispatch_async to give it some "air" and this works for me.

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    dispatch_async(dispatch_get_main_queue(), ^{
            UICollectionViewCell * visibleCell= [[self.collectionView visibleCells] objectAtIndex:0];


            [visibleCell doSomthing];
        });
}

Get Application Name/ Label via ADB Shell or Terminal

just enter the following command on command prompt after launching the app:

adb shell dumpsys window windows | find "mCurrentFocus"

if executing the command on linux terminal replace find by grep

Python equivalent of a given wget command

I had to do something like this on a version of linux that didn't have the right options compiled into wget. This example is for downloading the memory analysis tool 'guppy'. I'm not sure if it's important or not, but I kept the target file's name the same as the url target name...

Here's what I came up with:

python -c "import requests; r = requests.get('https://pypi.python.org/packages/source/g/guppy/guppy-0.1.10.tar.gz') ; open('guppy-0.1.10.tar.gz' , 'wb').write(r.content)"

That's the one-liner, here's it a little more readable:

import requests
fname = 'guppy-0.1.10.tar.gz'
url = 'https://pypi.python.org/packages/source/g/guppy/' + fname
r = requests.get(url)
open(fname , 'wb').write(r.content)

This worked for downloading a tarball. I was able to extract the package and download it after downloading.

EDIT:

To address a question, here is an implementation with a progress bar printed to STDOUT. There is probably a more portable way to do this without the clint package, but this was tested on my machine and works fine:

#!/usr/bin/env python

from clint.textui import progress
import requests

fname = 'guppy-0.1.10.tar.gz'
url = 'https://pypi.python.org/packages/source/g/guppy/' + fname

r = requests.get(url, stream=True)
with open(fname, 'wb') as f:
    total_length = int(r.headers.get('content-length'))
    for chunk in progress.bar(r.iter_content(chunk_size=1024), expected_size=(total_length/1024) + 1): 
        if chunk:
            f.write(chunk)
            f.flush()

How do I copy an object in Java?

Yes, you are just making a reference to the object. You can clone the object if it implements Cloneable.

Check out this wiki article about copying objects.

Refer here: Object copying

sql use statement with variable

I have the same problem, I overcame it with an ugly -- but useful -- set of GOTOs.

The reason I call the "script runner" before everything is that I want to hide the complexity and ugly approach from any developer that just wants to work with the actual script. At the same time, I can make sure that the script is run in the two (extensible to three and more) databases in the exact same way.

GOTO ScriptRunner

ScriptExecutes:

--------------------ACTUAL SCRIPT--------------------
-------- Will be executed in DB1 and in DB2 ---------
--TODO: Your script right here

------------------ACTUAL SCRIPT ENDS-----------------

GOTO ScriptReturns

ScriptRunner:
    USE DB1
    GOTO ScriptExecutes

ScriptReturns:
    IF (db_name() = 'DB1')
    BEGIN
        USE DB2
        GOTO ScriptExecutes
    END

With this approach you get to keep your variables and SQL Server does not freak out if you happen to go over a DECLARE statement twice.

Javascript Uncaught Reference error Function is not defined

In JSFiddle, when you set the wrapping to "onLoad" or "onDomready", the functions you define are only defined inside that block, and cannot be accessed by outside event handlers.

Easiest fix is to change:

function something(...)

To:

window.something = function(...)

Check input value length

You can add a form onsubmit handler, something like:

<form onsubmit="return validate();">

</form>


<script>function validate() {
 // check if input is bigger than 3
 var value = document.getElementById('titleeee').value;
 if (value.length < 3) {
   return false; // keep form from submitting
 }

 // else form is good let it submit, of course you will 
 // probably want to alert the user WHAT went wrong.

 return true;
}</script>

How to test if a string is JSON or not?

This code is JSON.parse(1234) or JSON.parse(0) or JSON.parse(false) or JSON.parse(null) all will return true.

function isJson(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}

So I rewrote code in this way:

function isJson(item) {
    item = typeof item !== "string"
        ? JSON.stringify(item)
        : item;

    try {
        item = JSON.parse(item);
    } catch (e) {
        return false;
    }

    if (typeof item === "object" && item !== null) {
        return true;
    }

    return false;
}

Testing result:

isJson test result

WPF button click in C# code

Button btn = new Button();
btn.Name = "btn1";
btn.Click += btn1_Click;

private void btn1_Click(object sender, RoutedEventArgs e)
{
    // do something
}

Google maps responsive resize

After few years, I moved to leaflet map and I have fixed this issue completely, the following could be applied to google maps too:

    var headerHeight = $("#navMap").outerHeight();
    var footerHeight = $("footer").outerHeight();
    var windowHeight = window.innerHeight;
    var mapContainerHeight = headerHeight + footerHeight;
    var totalMapHeight = windowHeight - mapContainerHeight;
    $("#map").css("margin-top", headerHeight);
    $("#map").height(totalMapHeight);

    $(window).resize(function(){
        var headerHeight = $("#navMap").outerHeight();
        var footerHeight = $("footer").outerHeight();
        var windowHeight = window.innerHeight;
        var mapContainerHeight = headerHeight + footerHeight;
        var totalMapHeight = windowHeight - mapContainerHeight;
        $("#map").css("margin-top", headerHeight);
        $("#map").height(totalMapHeight);
        map.fitBounds(group1.getBounds());
    });

when I try to open an HTML file through `http://localhost/xampp/htdocs/index.html` it says unable to connect to localhost

htdocs is your default document-root directory, so you have to use localhost/index.html to see that html file. In other words, localhost is mapped to xampp/htdocs, so index.html is at localhost itself. You can change the location of document root by modifying httpd.conf and restarting the server.

Prevent scrolling of parent element when inner element scroll position reaches top/bottom?

M.K. offered a great plugin in his answer. Plugin can be found here. However, for the sake of completion, I thought it'd be a good idea to put it together in one answer for AngularJS.

  1. Start by injecting the bower or npm (whichever is preferred)

    bower install jquery-scrollLock --save
    npm install jquery-scroll-lock --save
    
  2. Add the following directive. I am choosing to add it as an attribute

    (function() {
       'use strict';
    
        angular
           .module('app')
           .directive('isolateScrolling', isolateScrolling);
    
           function isolateScrolling() {
               return {
                   restrict: 'A',
                   link: function(sc, elem, attrs) {
                      $('.scroll-container').scrollLock();
                   }
               }
           }
    })();
    
  3. And the important piece the plugin fails to document in their website is the HTML structure that it must follow.

    <div class="scroll-container locked">
        <div class="scrollable" isolate-scrolling>
             ... whatever ...
        </div>
    </div>
    

The attribute isolate-scrolling must contain the scrollable class and it all needs to be inside the scroll-container class or whatever class you choose and the locked class must be cascaded.

How to track down access violation "at address 00000000"

If you get 'Access violation at address 00000000.', you are calling a function pointer that hasn't been assigned - possibly an event handler or a callback function.

for example

type
TTest = class(TForm);
protected
  procedure DoCustomEvent;
public
  property OnCustomEvent : TNotifyEvent read FOnCustomEvent  write FOnCustomEvent;
end;

procedure TTest.DoCustomEvent;
begin
  FOnCustomEvent(Self);  
end;

Instead of

procedure TTest.DoCustomEvent;
begin
  if Assigned(FOnCustomEvent) then // need to check event handler is assigned!
    FOnCustomEvent(Self);  
end;

If the error is in a third party component, and you can track the offending code down, use an empty event handler to prevent the AV.

How to start Fragment from an Activity

Simple way

  1. Create a new java class

    public class ActivityName extends FragmentActivity {
    @Override
     public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
        if (savedInstanceState == null){
        getSupportFragmentManager().beginTransaction()
                .add(android.R.id.content, new Fragment_name_which_you_wantto_open()).commit();}
     }
    }
    
  2. in your activity where u want to call fragment

     Intent i = new Intent(Currentactivityname.this,ActivityName.class);
     startActivity(i);
    

Another Method

  1. Place frame layout in your activity where u want to open fragment

      <FrameLayout
            android:id="@+id/frameLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        </FrameLayout>
    
  2. Paste this code where u want to open fragment

        Fragment mFragment = null;
            mFragment = new Name_of_fragment_which_you_want_to_open();
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.frameLayout, mFragment).commit();
    

Does a VPN Hide my Location on Android?

Your question can be conveniently divided into several parts:

Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.

How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.

You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):

  1. Download and install a trusted VPN.

  2. Install the VPN on your Android device.

  3. Open the application and connect to a server in a different country.

  4. Your Android location will now be successfully changed!

Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.

Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.

How to use mysql JOIN without ON condition?

MySQL documentation covers this topic.

Here is a synopsis. When using join or inner join, the on condition is optional. This is different from the ANSI standard and different from almost any other database. The effect is a cross join. Similarly, you can use an on clause with cross join, which also differs from standard SQL.

A cross join creates a Cartesian product -- that is, every possible combination of 1 row from the first table and 1 row from the second. The cross join for a table with three rows ('a', 'b', and 'c') and a table with four rows (say 1, 2, 3, 4) would have 12 rows.

In practice, if you want to do a cross join, then use cross join:

from A cross join B

is much better than:

from A, B

and:

from A join B -- with no on clause

The on clause is required for a right or left outer join, so the discussion is not relevant for them.

If you need to understand the different types of joins, then you need to do some studying on relational databases. Stackoverflow is not an appropriate place for that level of discussion.

How to increase request timeout in IIS?

In IIS >= 7, a <webLimits> section has replaced ConnectionTimeout, HeaderWaitTimeout, MaxGlobalBandwidth, and MinFileBytesPerSec IIS 6 metabase settings.

Example Configuration:

<configuration>
   <system.applicationHost>
      <webLimits connectionTimeout="00:01:00"
         dynamicIdleThreshold="150"
         headerWaitTimeout="00:00:30"
         minBytesPerSecond="500"
      />
   </system.applicationHost>
</configuration>

For reference: more information regarding these settings in IIS can be found here. Also, I was unable to add this section to the web.config via the IIS manager's "configuration editor", though it did show up once I added it and searched the configuration.

Modifying Objects within stream in Java8 while iterating

Instead of creating strange things, you can just filter() and then map() your result.

This is much more readable and sure. Streams will make it in only one loop.

starting file download with JavaScript

We do it that way: First add this script.

<script type="text/javascript">
function populateIframe(id,path) 
{
    var ifrm = document.getElementById(id);
    ifrm.src = "download.php?path="+path;
}
</script>

Place this where you want the download button(here we use just a link):

<iframe id="frame1" style="display:none"></iframe>
<a href="javascript:populateIframe('frame1','<?php echo $path; ?>')">download</a>

The file 'download.php' (needs to be put on your server) simply contains:

<?php 
   header("Content-Type: application/octet-stream");
   header("Content-Disposition: attachment; filename=".$_GET['path']);
   readfile($_GET['path']);
?>

So when you click the link, the hidden iframe then gets/opens the sourcefile 'download.php'. With the path as get parameter. We think this is the best solution!

It should be noted that the PHP part of this solution is a simple demonstration and potentially very, very insecure. It allows the user to download any file, not just a pre-defined set. That means they could download parts of the source code of the site itself, possibly containing API credentials etc.

How to show another window from mainwindow in QT

  1. Implement a slot in your QMainWindow where you will open your new Window,
  2. Place a widget on your QMainWindow,
  3. Connect a signal from this widget to a slot from the QMainWindow (for example: if the widget is a QPushButton connect the signal click() to the QMainWindow custom slot you have created).

Code example:

MainWindow.h

// ...
include "newwindow.h"
// ...
public slots:
   void openNewWindow();
// ...
private:
   NewWindow *mMyNewWindow;
// ...
}

MainWindow.cpp

// ...
   MainWindow::MainWindow()
   {
      // ...
      connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
      // ...
   }
// ...
void MainWindow::openNewWindow()
{
   mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
   mMyNewWindow->show();
   // ...
}

This is an example on how display a custom new window. There are a lot of ways to do this.

How to get first and last day of the current week in JavaScript

Be careful with the accepted answer, it does not set the time to 00:00:00 and 23:59:59, so you can have problems.

You can use a third party date library to deal with dates. For example:

var startOfWeek = moment().startOf('week').toDate();
var endOfWeek   = moment().endOf('week').toDate();

EDIT: As of September 2020, using Moment is discouraged for new projects (blog post)

Another popular alternative is date-fns.

Debug vs Release in CMake

A lot of the answers here are out of date/bad. So I'm going to attempt to answer it better. Granted I'm answering this question in 2020, so it's expected things would change.


How do I run CMake for each target type (debug/release)?

First off Debug/Release are called configurations in cmake (nitpick).

If you are using a single configuration generator (Ninja/Unix-Makefiles)

Then you need a build folder for each configuration.

Like this:

# Configure the build
cmake -S . -B build/Debug -D CMAKE_BUILD_TYPE=Release

# Actually build the binaries
cmake --build build/Debug

For multi-configuration generators it's slightly different (Ninja Multi-Config, Visual Studio)

# Configure the build
cmake -S . -B build

# Actually build the binaries
cmake --build build --config Debug

If you are wondering why this is necessary it's because cmake isn't a build system. It's a meta-build system (IE a build system that build's build systems). This is basically the result of handling build systems that support multiple-configurations in 1 build. If you'd like a deeper understanding I'd suggest reading a bit about cmake in Craig Scott's book "Professional CMake: A Practical Guide


How do I specify debug and release C/C++ flags using CMake?

The modern practice is to use target's and properties.

Here is an example:

add_library(foobar)

# Add this compile definition for debug builds, this same logic works for
# target_compile_options, target_link_options, etc.
target_compile_definitions(foobar PRIVATE
    $<$<CONFIG:Debug>:
        FOOBAR_DEBUG=1
    >
)

NOTE: How I'm using generator expressions to specify the configuration! Using CMAKE_BUILD_TYPE will result in bad builds for any multi-configuration generator!

Further more sometimes you need to set things globally and not just for one target. Use add_compile_definitions, add_compile_options, etc. Those functions support generator expressions. Don't use old style cmake unless you have to (that path is a land of nightmares)


How do I express that the main executable will be compiled with g++ and one nested library with gcc?

Your last question really doesn't make sense.

Unescape HTML entities in Javascript?

In case you're looking for it, like me - meanwhile there's a nice and safe JQuery method.

https://api.jquery.com/jquery.parsehtml/

You can f.ex. type this in your console:

var x = "test &amp;";
> undefined
$.parseHTML(x)[0].textContent
> "test &"

So $.parseHTML(x) returns an array, and if you have HTML markup within your text, the array.length will be greater than 1.

How do I use setsockopt(SO_REUSEADDR)?

After :

sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) 
    error("ERROR opening socket");

You can add (with standard C99 compound literal support) :

if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int)) < 0)
    error("setsockopt(SO_REUSEADDR) failed");

Or :

int enable = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0)
    error("setsockopt(SO_REUSEADDR) failed");

Overlay a background-image with an rgba background-color

The solution by PeterVR has the disadvantage that the additional color displays on top of the entire HTML block - meaning that it also shows up on top of div content, not just on top of the background image. This is fine if your div is empty, but if it is not using a linear gradient might be a better solution:

<div class="the-div">Red text</div>

<style type="text/css">
  .the-div
  {
    background-image: url("the-image.png");
    color: #f00;
    margin: 10px;
    width: 200px;
    height: 80px;
  }
  .the-div:hover
  {
    background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1)), url("the-image.png");
    background-image: -moz-linear-gradient(top, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1)), url("the-image.png");
    background-image: -o-linear-gradient(top, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1)), url("the-image.png");
    background-image: -ms-linear-gradient(top, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1)), url("the-image.png");
    background-image: -webkit-gradient(linear, left top, left bottom, from(rgba(0, 0, 0, 0.1)), to(rgba(0, 0, 0, 0.1))), url("the-image.png");
    background-image: -webkit-linear-gradient(top, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1)), url("the-image.png");
  }
</style>

See fiddle. Too bad that gradient specifications are currently a mess. See compatibility table, the code above should work in any browser with a noteworthy market share - with the exception of MSIE 9.0 and older.

Edit (March 2017): The state of the web got far less messy by now. So the linear-gradient (supported by Firefox and Internet Explorer) and -webkit-linear-gradient (supported by Chrome, Opera and Safari) lines are sufficient, additional prefixed versions are no longer necessary.

Calling a Javascript Function from Console

I just discovered this issue. I was able to get around it by using indirection. In each module define a function, lets call it indirect:

function indirect(js) { return eval(js); }

With that function in each module, you can then execute any code in the context of it.

E.g. if you had this import in your module:

import { imported_fn } from "./import.js";

You could then get the results of calling imported_fn from the console by doing this:

indirect("imported_fn()");

Using eval was my first thought, but it doesn't work. My hypothesis is that calling eval from the console remains in the context of console, and we need to execute in the context of the module.

How to fire AJAX request Periodically?

As others have pointed out setInterval and setTimeout will do the trick. I wanted to highlight a bit more advanced technique that I learned from this excellent video by Paul Irish: http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/

For periodic tasks that might end up taking longer than the repeat interval (like an HTTP request on a slow connection) it's best not to use setInterval(). If the first request hasn't completed and you start another one, you could end up in a situation where you have multiple requests that consume shared resources and starve each other. You can avoid this problem by waiting to schedule the next request until the last one has completed:

// Use a named immediately-invoked function expression.
(function worker() {
  $.get('ajax/test.html', function(data) {
    // Now that we've completed the request schedule the next one.
    $('.result').html(data);
    setTimeout(worker, 5000);
  });
})();

For simplicity I used the success callback for scheduling. The down side of this is one failed request will stop updates. To avoid this you could use the complete callback instead:

(function worker() {
  $.ajax({
    url: 'ajax/test.html', 
    success: function(data) {
      $('.result').html(data);
    },
    complete: function() {
      // Schedule the next request when the current one's complete
      setTimeout(worker, 5000);
    }
  });
})();

Unable to start debugging on the web server. Could not start ASP.NET debugging VS 2010, II7, Win 7 x64

I got this same error recently and in my case it turned out that there were duplicate MIME types. I had recently added two that didn't show up in the list initially. IIS let me add them and it was only when I decided to check the MIME types for the site again as part of my diagnostic process that I got an error in IIS as well. It referenced duplicates in web.config. Once I went back into the web.config file I noticed that a new section called had been added, which included the two recently-added MIME types. Deleted that section and life is good again! Hoping this may help others who haven't managed to fix the issue with any of the other suggestions.

"cannot be used as a function error"

#include "header.h"

int estimatedPopulation (int currentPopulation, float growthRate)
{
    return currentPopulation + currentPopulation * growthRate  / 100;
}

Converting a String to DateTime

Nobody seems to implemented an extension method. With the help of @CMS's answer:

Working and improved full source example is here: Gist Link

namespace ExtensionMethods {
    using System;
    using System.Globalization;

    public static class DateTimeExtensions {
        public static DateTime ToDateTime(this string s, 
                  string format = "ddMMyyyy", string cultureString = "tr-TR") {
            try {
                var r = DateTime.ParseExact(
                    s: s,
                    format: format,
                    provider: CultureInfo.GetCultureInfo(cultureString));
                return r;
            } catch (FormatException) {
                throw;
            } catch (CultureNotFoundException) {
                throw; // Given Culture is not supported culture
            }
        }

        public static DateTime ToDateTime(this string s, 
                    string format, CultureInfo culture) {
            try {
                var r = DateTime.ParseExact(s: s, format: format, 
                                        provider: culture);
                return r;
            } catch (FormatException) {
                throw;
            } catch (CultureNotFoundException) {
                throw; // Given Culture is not supported culture
            }

        }

    }
}

namespace SO {
    using ExtensionMethods;
    using System;
    using System.Globalization;

    class Program {
        static void Main(string[] args) {
            var mydate = "29021996";
            var date = mydate.ToDateTime(format: "ddMMyyyy"); // {29.02.1996 00:00:00}

            mydate = "2016 3";
            date = mydate.ToDateTime("yyyy M"); // {01.03.2016 00:00:00}

            mydate = "2016 12";
            date = mydate.ToDateTime("yyyy d"); // {12.01.2016 00:00:00}

            mydate = "2016/31/05 13:33";
            date = mydate.ToDateTime("yyyy/d/M HH:mm"); // {31.05.2016 13:33:00}

            mydate = "2016/31 Ocak";
            date = mydate.ToDateTime("yyyy/d MMMM"); // {31.01.2016 00:00:00}

            mydate = "2016/31 January";
            date = mydate.ToDateTime("yyyy/d MMMM", cultureString: "en-US"); 
            // {31.01.2016 00:00:00}

            mydate = "11/?????/1437";
            date = mydate.ToDateTime(
                culture: CultureInfo.GetCultureInfo("ar-SA"),
                format: "dd/MMMM/yyyy"); 
         // Weird :) I supposed dd/yyyy/MMMM but that did not work !?$^&*

            System.Diagnostics.Debug.Assert(
               date.Equals(new DateTime(year: 2016, month: 5, day: 18)));
        }
    }
}

How to debug (only) JavaScript in Visual Studio?

First open Visual studio ..select your project in solution explorer..Right click and choose option "browse with" then set IE as default browser.

enter image description here Now open IE ..go to
Tools >> Internet option >> Advance>> uncheck the checkbox having "Disable Script Debugging (Internet Explorer). and then click Apply and OK and you are done ..

Now you can set breakpoints in your JS file and then hit the debug button in VS..

enter image description here

EDIT:- For asp.net web application right click on the page which is your startup page(say default.aspx) and perform the same steps. :)

How to redirect stderr to null in cmd.exe

Your DOS command 2> nul

Read page Using command redirection operators. Besides the "2>" construct mentioned by Tanuki Software, it lists some other useful combinations.

How to get the top position of an element?

If you want the position relative to the document then:

$("#myTable").offset().top;

but often you will want the position relative to the closest positioned parent:

$("#myTable").position().top;

How to get the wsdl file from a webservice's URL

Its only possible to get the WSDL if the webservice is configured to deliver it. Therefor you have to specify a serviceBehavior and enable httpGetEnabled:

<serviceBehaviors>
    <behavior name="BindingBehavior">
        <serviceMetadata httpGetEnabled="true" />
        <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
</serviceBehaviors>

In case the webservice is only accessible via https you have to enable httpsGetEnabled instead of httpGetEnabled.

jQuery.css() - marginLeft vs. margin-left?

jQuery is simply supporting the way CSS is written.

Also, it ensures that no matter how a browser returns a value, it will be understood

jQuery can equally interpret the CSS and DOM formatting of multiple-word properties. For example, jQuery understands and returns the correct value for both .css('background-color') and .css('backgroundColor').

Creating a UITableView Programmatically

sample table

 #import "StartreserveViewController.h"
 #import "CollectionViewController.h"
 #import "TableViewCell1.h"
@interface StartreserveViewController ()


{
NSArray *name;
NSArray *images;
NSInteger selectindex;

}

@end

@implementation StartreserveViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.

self.view.backgroundColor = [UIColor blueColor];
_startReservetable.backgroundColor = [UIColor blueColor];


name = [[NSArray alloc]initWithObjects:@"Mobiles",@"Costumes",@"Shoes", 
nil];
images = [[NSArray 
 alloc]initWithObjects:@"mobilestitle.jpg",@"costumetitle.jpeg", 
 @"shoestitle.png",nil];



  }

 - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

pragma mark - UiTableview Datasource

 -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
 {
return 1;
 }

 -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
 (NSInteger)section
 {
return 3;
 }

 - (UITableViewCell *)tableView:(UITableView *)tableView 
  cellForRowAtIndexPath:(NSIndexPath *)indexPath
 {


static NSString *cellId = @"tableview";

TableViewCell1  *cell =[tableView dequeueReusableCellWithIdentifier:cellId];


cell.cellTxt .text = [name objectAtIndex:indexPath.row];

cell.cellImg.image = [UIImage imageNamed:[images 
objectAtIndex:indexPath.row]];

return cell;



 }


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:
(NSIndexPath *)indexPath
 {
selectindex = indexPath.row;
[self performSegueWithIdentifier:@"second" sender:self];
}



   #pragma mark - Navigation

 // In a storyboard-based application, you will often want to do a little     
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

if ([segue.identifier isEqualToString:@"second"])

  {
    CollectionViewController *obj = segue.destinationViewController;
           obj.receivename = [name objectAtIndex:selectindex];

  }



// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}

 @end

.h

#import <UIKit/UIKit.h>

@interface StartreserveViewController :      
UIViewController<UITableViewDelegate,UITableViewDataSource>    
@property (strong, nonatomic) IBOutlet UITableView *startReservetable;

 @end

Echo a blank (empty) line to the console from a Windows batch file

There is often the tip to use 'echo.'

But that is slow, and it could fail with an error message, as cmd.exe will search first for a file named 'echo' (without extension) and only when the file doesn't exists it outputs an empty line.

You could use echo(. This is approximately 20 times faster, and it works always. The only drawback could be that it looks odd.

More about the different ECHO:/\ variants is at DOS tips: ECHO. FAILS to give text or blank line.

CSS styling in Django forms

Styling widget instances

If you want to make one widget instance look different from another, you will need to specify additional attributes at the time when the widget object is instantiated and assigned to a form field (and perhaps add some rules to your CSS files).

https://docs.djangoproject.com/en/2.2/ref/forms/widgets/

To do this, you use the Widget.attrs argument when creating the widget:

class CommentForm(forms.Form):
    name = forms.CharField(widget=forms.TextInput(attrs={'class': 'special'}))
    url = forms.URLField()
    comment = forms.CharField(widget=forms.TextInput(attrs={'size': '40'}))

You can also modify a widget in the form definition:

class CommentForm(forms.Form):
    name = forms.CharField()
    url = forms.URLField()
    comment = forms.CharField()

    name.widget.attrs.update({'class': 'special'})
    comment.widget.attrs.update(size='40')

Or if the field isn’t declared directly on the form (such as model form fields), you can use the Form.fields attribute:

class CommentForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['name'].widget.attrs.update({'class': 'special'})
        self.fields['comment'].widget.attrs.update(size='40')

Django will then include the extra attributes in the rendered output:

>>> f = CommentForm(auto_id=False)
>>> f.as_table()
<tr><th>Name:</th><td><input type="text" name="name" class="special" required></td></tr>
<tr><th>Url:</th><td><input type="url" name="url" required></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" size="40" required></td></tr>

Get all messages from Whatsapp

You can get access to the WhatsApp data base located on the SD card only as a root user I think. if you open "\data\data\com.whatsapp" you will see that "databases" is linked to "\firstboot\sqlite\com.whatsapp\"

TextView Marquee not working

I've encountered the same problem. Amith GC's answer(the first answer checked as accepted) is right, but sometimes textview.setSelected(true); doesn't work when the text view can't get the focus all the time. So, to ensure TextView Marquee working, I had to use a custom TextView.

public class CustomTextView extends TextView {
    public CustomTextView(Context context) {
        super(context);
    }
    public CustomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);

    }

    public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

    }


    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        if(focused)
            super.onFocusChanged(focused, direction, previouslyFocusedRect);
    }

    @Override
    public void onWindowFocusChanged(boolean focused) {
        if(focused)
            super.onWindowFocusChanged(focused);
    }


    @Override
    public boolean isFocused() {
        return true;
    }
}

And then, you can use the custom TextView as the scrolling text view in your layout .xml file like this:

<com.example.myapplication.CustomTextView
            android:id="@+id/tvScrollingMessage"
            android:text="@string/scrolling_message_main_wish_list"
            android:singleLine="true"
            android:ellipsize="marquee"
            android:marqueeRepeatLimit ="marquee_forever"
            android:focusable="true"
            android:focusableInTouchMode="true"
            android:scrollHorizontally="true"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:background="@color/black"
            android:gravity="center"
            android:textColor="@color/white"
            android:textSize="15dp"
            android:freezesText="true"/>

NOTE: in the above code snippet com.example.myapplication is an example package name and should be replaced by your own package name.

Hope this will help you. Cheers!

Convert Long into Integer

long visitors =1000;

int convVisitors =(int)visitors;

"The Controls collection cannot be modified because the control contains code blocks"

I had the same issue with my system, I removed the JavaScript code from the of my page and put it at body just before closing body tag

Error to run Android Studio

The error is self explanatory, you need to set your environment variable to JDK path instead of JRE here is it

JDK_HOME: C:\Program Files\Java\jdk1.7.0_07

check the path for linux

and here is possible duplicate Android Studio not working

How to forward declare a template class in namespace std?

The problem is not that you can't forward-declare a template class. Yes, you do need to know all of the template parameters and their defaults to be able to forward-declare it correctly:

namespace std {
  template<class T, class Allocator = std::allocator<T>>
  class list;
}

But to make even such a forward declaration in namespace std is explicitly prohibited by the standard: the only thing you're allowed to put in std is a template specialisation, commonly std::less on a user-defined type. Someone else can cite the relevant text if necessary.

Just #include <list> and don't worry about it.

Oh, incidentally, any name containing double-underscores is reserved for use by the implementation, so you should use something like TEST_H instead of __TEST__. It's not going to generate a warning or an error, but if your program has a clash with an implementation-defined identifier, then it's not guaranteed to compile or run correctly: it's ill-formed. Also prohibited are names beginning with an underscore followed by a capital letter, among others. In general, don't start things with underscores unless you know what magic you're dealing with.

Xcode 6 iPhone Simulator Application Support location

The simulators are located under:

~/Library/Developer/CoreSimulator/

Here, they are listed as directories with UUID names. Use sort by 'Date modified' to find the latest one. Inside navigate to:

/data/Containers/Data/Application/

Here you will get a list of all the applications on that device. You can again sort this to get the latest app.

NOTE: Xcode changes the directory name every time you run the app, so don't rely on making alias/short cuts on desktop.

The easiest way is to use the app here, which does everything automatically.

MVC Razor Hidden input and passing values

You are doing it wrong since you try to map WebForms in the MVC application.

There are no server side controlls in MVC. Only the View and the Controller on the back-end. You send the data from server to the client by means of initialization of the View with your model.

This is happening on the HTTP GET request to your resource.

[HttpGet]
public ActionResult Home() 
{
  var model = new HomeModel { Greeatings = "Hi" };
  return View(model);
}

You send data from client to server by means of posting data to server. To make that happen, you create a form inside your view and [HttpPost] handler in your controller.

// View

@using (Html.BeginForm()) {
  @Html.TextBoxFor(m => m.Name)
  @Html.TextBoxFor(m => m.Password)
}

// Controller

[HttpPost]
public ActionResult Home(LoginModel model) 
{
  // do auth.. and stuff
  return Redirect();
}

Fastest way to count exact number of rows in a very large table?

Well, late by 5 years and unsure if it helps :

I was trying to count the no. of rows in a SQL Server table using MS SQL Server Management Studio and ran into some overflow error, then I used the below :

select count_big(1) FROM [dbname].[dbo].[FactSampleValue];

The result :

24296650578 rows

passing form data to another HTML page

Use "Get" Method to send the value of a particular field through the browser:

<form action="display.html" method="GET">
    <input type="text" name="serialNumber" />
    <input type="submit" value="Submit" />
</form>

Import mysql DB with XAMPP in command LINE

here is my try to import database from cmd in xampp server the correct command for me is this you can change it with your requirements.and i also attached Errors that i face first time importing db from command line.you can see last command that i use and i paste it here also its working fro me.

mysql -h localhost -u root ovxsolut_windhs < C:\Users\eee\Downloads\ovxsolut_windhs.sql

d enter image description here

Html- how to disable <a href>?

I created a button...

This is where you've gone wrong. You haven't created a button, you've created an anchor element. If you had used a button element instead, you wouldn't have this problem:

<button type="button" data-toggle="modal" data-target="#myModal" data-role="disabled">
    Connect
</button>

If you are going to continue using an a element instead, at the very least you should give it a role attribute set to "button" and drop the href attribute altogether:

<a role="button" ...>

Once you've done that you can introduce a piece of JavaScript which calls event.preventDefault() - here with event being your click event.

How to create a new column in a select query

select A, B, 'c' as C
from MyTable

How to put a UserControl into Visual Studio toolBox

I found that the user control must have a parameterless constructor or it won't show up in the list. at least that was true in vs2005.

Keytool is not recognized as an internal or external command

Execute following command:

set PATH="C:\Program Files (x86)\Java\jre7"

(whichever JRE exists in case of 64bit).

Because your Java Path is not set so you can just do this at command line and then execute the keytool import command.

Specifying maxlength for multiline textbox

I tried different approaches but every one had some weak points (i.e. with cut and paste or browser compatibility). This is the solution I'm using right now:

function multilineTextBoxKeyUp(textBox, e, maxLength) {
    if (!checkSpecialKeys(e)) {
        var length = parseInt(maxLength);
        if (textBox.value.length > length) {
            textBox.value = textBox.value.substring(0, maxLength);
        }
    }
}

function multilineTextBoxKeyDown(textBox, e, maxLength) {
    var selectedText = document.selection.createRange().text;
    if (!checkSpecialKeys(e) && !e.ctrlKey && selectedText.length == 0) {
        var length = parseInt(maxLength);
        if (textBox.value.length > length - 1) {
            if (e.preventDefault) {
                e.preventDefault();
            }
            else {
                e.returnValue = false;
            }
        }
    }
}

function checkSpecialKeys(e) {
    if (e.keyCode != 8 && e.keyCode != 9 && e.keyCode != 33 && e.keyCode != 34 && e.keyCode != 35 && e.keyCode != 36 && e.keyCode != 37 && e.keyCode != 38 && e.keyCode != 39 && e.keyCode != 40) {
        return false;
    } else {
        return true;
    }
}

In this case, I'm calling multilineTextBoxKeyUp on key up and multilineTextBoxKeyDown on key down:

myTextBox.Attributes.Add("onkeyDown", "multilineTextBoxKeyDown(this, event, '" + maxLength + "');");
myTextBox.Attributes.Add("onkeyUp", "multilineTextBoxKeyUp(this, event, '" + maxLength + "');");

Array.Add vs +=

The most common idiom for creating an array without using the inefficient += is something like this, from the output of a loop:

$array = foreach($i in 1..10) { 
  $i
}
$array

Yii2 data provider default sorting

if you have CRUD (index) and you need set default sorting your controller for GridView, or ListView, or more... Example

public function actionIndex()
{
    $searchModel = new NewsSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    // set default sorting
    $dataProvider->sort->defaultOrder = ['id' => SORT_DESC];

    return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
    ]);
}

you need add

$dataProvider->sort->defaultOrder = ['id' => SORT_DESC];

how to execute a scp command with the user name and password in one line

Thanks for your feed back got it to work I used the sshpass tool.

sshpass -p 'password' scp [email protected]:sys_config /var/www/dev/

Showing all errors and warnings

I was able to get all errors via the below code:

ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);

Javascript, viewing [object HTMLInputElement]

<input type="text" />
<script>
$("input:text").change(function() {
    var value=$("input:text").val();
    alert(value);
});
</script>

use .val() to get value of the element (jquery method), $("input:text") this selector to select your input, .change() to bind an event handler to the "change" JavaScript event.

C - Convert an uppercase letter to lowercase

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

int main()
{
    char string[] = "Strlwr in C";

    printf("%s\n",strlwr(string));

    return  0;
}

use strlwr for lowering the case

Which Ruby version am I really running?

Run this command:

rvm get stable --auto-dotfiles

and make sure to read all the output. RVM will tell you if something is wrong, which in your case might be because GEM_HOME is set to something different then PATH.

Read file As String

You can use org.apache.commons.io.IOUtils.toString(InputStream is, Charset chs) to do that.

e.g.

IOUtils.toString(context.getResources().openRawResource(<your_resource_id>), StandardCharsets.UTF_8)

For adding the correct library:

Add the following to your app/build.gradle file:

dependencies {
    compile 'org.apache.directory.studio:org.apache.commons.io:2.4'
}

or for the Maven repo see -> this link

For direct jar download see-> https://commons.apache.org/proper/commons-io/download_io.cgi

Create a shortcut on Desktop

URL shortcut

private void urlShortcutToDesktop(string linkName, string linkUrl)
{
    string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

    using (StreamWriter writer = new StreamWriter(deskDir + "\\" + linkName + ".url"))
    {
        writer.WriteLine("[InternetShortcut]");
        writer.WriteLine("URL=" + linkUrl);
    }
}

Application shortcut

private void appShortcutToDesktop(string linkName)
{
    string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

    using (StreamWriter writer = new StreamWriter(deskDir + "\\" + linkName + ".url"))
    {
        string app = System.Reflection.Assembly.GetExecutingAssembly().Location;
        writer.WriteLine("[InternetShortcut]");
        writer.WriteLine("URL=file:///" + app);
        writer.WriteLine("IconIndex=0");
        string icon = app.Replace('\\', '/');
        writer.WriteLine("IconFile=" + icon);
    }
}

Also check this example.

If you want to use some API specific functions then you will want to use the IShellLink interface as well as the IPersistFile interface (through COM interop).

Here is an article that goes into detail what you need to do it, as well as sample code.

How to find out which package version is loaded in R?

Use the R method packageDescription to get the installed package description and for version just use $Version as:

packageDescription("AppliedPredictiveModeling")$Version
[1] "1.1-6"

Add 10 seconds to a Date

Try this

a = new Date();
a.setSeconds(a.getSeconds() + 10);

Converting Python dict to kwargs?

Here is a complete example showing how to use the ** operator to pass values from a dictionary as keyword arguments.

>>> def f(x=2):
...     print(x)
... 
>>> new_x = {'x': 4}
>>> f()        #    default value x=2
2
>>> f(x=3)     #   explicit value x=3
3
>>> f(**new_x) # dictionary value x=4 
4

CSS z-index not working (position absolute)

JSFiddle

You have to put the second div on top of the first one because the both have an z-index of zero so that the order in the dom will decide which is on top. This also affects the relative positioned div because its z-index relates to elements inside the parent div.

<div class="absolute" style="top: 54px"></div>
<div class="absolute">
    <div id="relative"></div>
</div>

Css stays the same.

$(document).ready shorthand

This is not a shorthand for $(document).ready().

The code you posted boxes the inside code and makes jQuery available as $ without polluting the global namespace. This can be used when you want to use both prototype and jQuery on one page.

Documented here: http://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/#use-an-immediately-invoked-function-expression

Is if(document.getElementById('something')!=null) identical to if(document.getElementById('something'))?

jquery will provide you with this and more ...

if($("#something").val()){ //do stuff}

It took me a couple of days to pick it up, but it provides you with you with so much more functionality. An example below.

jQuery(document).ready(function() {
    /* finds closest element with class divright/left and 
    makes all checkboxs inside that div class the same as selectAll...
    */
        $("#selectAll").click(function() {
        $(this).closest('.divright').find(':checkbox').attr('checked', this.checked);
    });
});

SSH -L connection successful, but localhost port forwarding not working "channel 3: open failed: connect failed: Connection refused"

Note: localhost is the hostname for an address using the local (loopback) network interface, and 127.0.0.1 is its IP in the IPv4 network standard (it's ::1 in IPv6). 0.0.0.0 is the IPv4 standard "current network" IP address.

I experienced this error with a Docker setup. I had a Docker container running on an external server, and I'd (correctly) mapped its ports out as 127.0.0.1:9232:9232. By port-forwarding ssh remote -L 9232:127.0.0.1:9232, I'd expected to be able to communicate with the remote server's port 9232 as if it were my own local port.

It turned out that the Docker container was internally running its process on 127.0.0.1:9232 rather than 0.0.0.0:9232, and so even though I'd specified the container's port-mappings correctly, they weren't on the correct interface for being mapped out.

The POM for project is missing, no dependency information available

Change:

<!-- ANT4X -->
<dependency>
  <groupId>net.sourceforge</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

To:

<!-- ANT4X -->
<dependency>
  <groupId>net.sourceforge.ant4x</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

The groupId of net.sourceforge was incorrect. The correct value is net.sourceforge.ant4x.

How do I center text horizontally and vertically in a TextView?

Try this:

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center" />

Conflict with dependency 'com.android.support:support-annotations'. Resolved versions for app (23.1.0) and test app (23.0.1) differ

I was getting the same error today:

Error:Execution failed for task ':app:preDebugAndroidTestBuild'.> Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.

What I did:

  • I simply updated all my dependencies to 27.1.1 instead of 26.1.0
  • Also, updated my compileSdkVersion 27 and targetSdkVersion 27 which were 26 earlier

And com.android.support:support-annotations error was gone!

For Ref:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0'
    implementation 'com.android.support:design:27.1.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

Detecting IE11 using CSS Capability/Feature Detection

To target IE10 and IE11 only (and not Edge):

@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {  
   /* add your IE10-IE11 css here */   
}

Stacked Tabs in Bootstrap 3

To get left and right tabs (now also with sideways) support for Bootstrap 3, bootstrap-vertical-tabs component can be used.

https://github.com/dbtek/bootstrap-vertical-tabs

Hibernate problem - "Use of @OneToMany or @ManyToMany targeting an unmapped class"

If you are using Java configuration in a spring-data-jpa project, make sure you are scanning the package that the entity is in. For example, if the entity lived com.foo.myservice.things then the following configuration annotation below would not pick it up.

You could fix it by loosening it up to just com.foo.myservice (of course, keep in mind any other effects of broadening your scope to scan for entities).

@Configuration
@EnableJpaAuditing
@EnableJpaRepositories("com.foo.myservice.repositories")
public class RepositoryConfiguration {
}

git-diff to ignore ^M

TL;DR

Change the core.pager to "tr -d '\r' | less -REX", not the source code

This is why

Those pesky ^M shown are an artifact of the colorization and the pager. enter image description here It is caused by less -R, a default git pager option. (git's default pager is less -REX)

The first thing to note is that git diff -b will not show changes in white space (e.g. the \r\n vs \n)

setup:

git clone https://github.com/CipherShed/CipherShed
cd CipherShed

A quick test to create a unix file and change the line endings will show no changes with git diff -b:

echo -e 'The quick brown fox\njumped over the lazy\ndogs.' > test.txt
git add test.txt
unix2dos.exe test.txt
git diff -b test.txt

We note that forcing a pipe to less does not show the ^M, but enabling color and less -R does:

git diff origin/v0.7.4.0 origin/v0.7.4.1 | less
git -c color.ui=always diff origin/v0.7.4.0 origin/v0.7.4.1 | less -R

The fix is shown by using a pipe to strip the \r (^M) from the output:

git diff origin/v0.7.4.0 origin/v0.7.4.1
git -c core.pager="tr -d '\r' | less -REX"  diff origin/v0.7.4.0 origin/v0.7.4.1

An unwise alternative is to use less -r, because it will pass through all control codes, not just the color codes.

If you want to just edit your git config file directly, this is the entry to update/add:

[core]
        pager = tr -d '\\r' | less -REX

How can I convince IE to simply display application/json rather than offer to download it?

I just had the same issue with an XMLHttpRequest. The site functions flawlessly in Chrome and FF, and in dozens upon dozens of Internet Explorer browsers in production. This ONE machine (the one our company is setting up to be a demo machine, of course) decided that it was going to prompt to save the json response to an ajax request.

The accepted regedit solution below fixed it. Thanks.

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

For inserting a separator:

df$x <- paste(df$n, "-", df$s)

Changing image size in Markdown

Maybe this has recently changed but the Kramdown docs show a simple solution.

From the docs

Here is an inline ![smiley](smiley.png){:height="36px" width="36px"}.

And here is a referenced ![smile]

[smile]: smile.png
{: height="36px" width="36px"}

Works on github with Jekyll and Kramdown.

How to append multiple items in one line in Python

use for loop. like this:

for x in [1,2,7,8,9,10,13,14,19,20,21,22]:
    new_list.append(my_list[i + x])

Error: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported

Building on what is mentioned in the comments, the simplest solution would be:

@RequestMapping(method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Collection<BudgetDTO> updateConsumerBudget(@RequestBody SomeDto someDto) throws GeneralException, ParseException {

    //whatever

}

class SomeDto {

   private List<WhateverBudgerPerDateDTO> budgetPerDate;


  //getters setters
}

The solution assumes that the HTTP request you are creating actually has

Content-Type:application/json instead of text/plain

Java 11 package javax.xml.bind does not exist

According to the release-notes, Java 11 removed the Java EE modules:

java.xml.bind (JAXB) - REMOVED
  • Java 8 - OK
  • Java 9 - DEPRECATED
  • Java 10 - DEPRECATED
  • Java 11 - REMOVED

See JEP 320 for more info.

You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:

<dependency>
  <groupId>javax.xml.bind</groupId>
  <artifactId>jaxb-api</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-core</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.0</version>
</dependency>

Jakarta EE 8 update (Mar 2020)

Instead of using old JAXB modules you can fix the issue by using Jakarta XML Binding from Jakarta EE 8:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>2.3.3</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.3</version>
  <scope>runtime</scope>
</dependency>

Jakarta EE 9 update (Nov 2020)

Use latest release of Eclipse Implementation of JAXB 3.0.0:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>3.0.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>3.0.0</version>
  <scope>runtime</scope>
</dependency>

Note: Jakarta EE 9 adopts new API package namespace jakarta.xml.bind.*, so update import statements:

javax.xml.bind -> jakarta.xml.bind

How to reduce the space between <p> tags?

I'll suggest to set padding and margin to 0.

If this does not solve your problem you can try playing with line-height even if not reccomended.

Create an ArrayList of unique values

Just Override the boolean equals() method of custom object. Say you have an ArrayList with custom field f1, f2, ... override

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof CustomObject)) return false;

    CustomObject object = (CustomObject) o;

    if (!f1.equals(object.dob)) return false;
    if (!f2.equals(object.fullName)) return false;
    ...
    return true;
}

and check using ArrayList instance's contains() method. That's it.

what is the difference between json and xml

They are two formats of representation of information. While JSON was designed to be more compact, XML was design to be more readable.

Jquery Value match Regex

  • Pass a string to RegExp or create a regex using the // syntax
  • Call regex.test(string), not string.test(regex)

So

jQuery(function () {
    $(".mail").keyup(function () {
        var VAL = this.value;

        var email = new RegExp('^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$');

        if (email.test(VAL)) {
            alert('Great, you entered an E-Mail-address');
        }
    });
});

How do you write a migration to rename an ActiveRecord model and its table in Rails?

You also need to replace your indexes:

class RenameOldTableToNewTable< ActiveRecord:Migration
  def self.up
    remove_index :old_table_name, :column_name
    rename_table :old_table_name, :new_table_name
    add_index :new_table_name, :column_name
  end 

  def self.down
    remove_index :new_table_name, :column_name
    rename_table :new_table_name, :old_table_name
    add_index :old_table_name, :column_name
  end
end

And rename your files etc, manually as other answers here describe.

See: http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

Make sure you can rollback and roll forward after you write this migration. It can get tricky if you get something wrong and get stuck with a migration that tries to effect something that no longer exists. Best trash the whole database and start again if you can't roll back. So be aware you might need to back something up.

Also: check schema_db for any relevant column names in other tables defined by a has_ or belongs_to or something. You'll probably need to edit those too.

And finally, doing this without a regression test suite would be nuts.

MySQL string replace

You can simply use replace() function,

with where clause-

update tabelName set columnName=REPLACE(columnName,'from','to') where condition;

without where clause-

update tabelName set columnName=REPLACE(columnName,'from','to');

Note: The above query if for update records directly in table, if you want on select query and the data should not be affected in table then can use the following query-

select REPLACE(columnName,'from','to') as updateRecord;

Insert node at a certain position in a linked list C++

Just have something like this where you traverse till the given position and then insert:

void addNodeAtPos(int data, int pos)
{
  Node* prev = new Node();
  Node* curr = new Node();
  Node* newNode = new Node();
  newNode->data = data;

  int tempPos = 0;   // Traverses through the list

  curr = head;      // Initialize current to head;
  if(head != NULL)
  {
    while(curr->next != NULL && tempPos != pos)
    {
        prev = curr;
        curr = curr->next;
        tempPos++;
    }
    if(pos==0)
    {
       cout << "Adding at Head! " << endl;
       // Call function to addNode from head;
    }
    else if(curr->next == NULL && pos == tempPos+1)
    {
      cout << "Adding at Tail! " << endl;
      // Call function to addNode at tail;
    }
    else if(pos > tempPos+1)
      cout << " Position is out of bounds " << endl;
     //Position not valid

    else
    {
        prev->next = newNode;
        newNode->next = curr;
        cout << "Node added at position: " << pos << endl;
    }
 }
 else
 {
    head = newNode;
    newNode->next=NULL;
    cout << "Added at head as list is empty! " << endl;
 }
}

Capture screenshot of active window?

A little tweak to method static void ImageSave() will grant you the option where to save it. Credit goes to Microsoft (http://msdn.microsoft.com/en-us/library/sfezx97z.aspx)

static void ImageSave(string filename, ImageFormat format, Image image, SaveFileDialog saveFileDialog1)
    { 
        saveFileDialog1.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
        saveFileDialog1.Title = "Enregistrer un image";
        saveFileDialog1.ShowDialog();

        // If the file name is not an empty string open it for saving.
        if (saveFileDialog1.FileName != "")
        {
            // Saves the Image via a FileStream created by the OpenFile method.
            System.IO.FileStream fs =
               (System.IO.FileStream)saveFileDialog1.OpenFile();
            // Saves the Image in the appropriate ImageFormat based upon the
            // File type selected in the dialog box.
            // NOTE that the FilterIndex property is one-based.
            switch (saveFileDialog1.FilterIndex)
            {
                case 1:
                    image.Save(fs,
                       System.Drawing.Imaging.ImageFormat.Jpeg);
                    break;

                case 2:
                    image.Save(fs,
                       System.Drawing.Imaging.ImageFormat.Bmp);
                    break;

                case 3:
                    image.Save(fs,
                       System.Drawing.Imaging.ImageFormat.Gif);
                    break;
            }

            fs.Close();
        }



    }

Your button_click event should be coded something like this...

private void btnScreenShot_Click(object sender, EventArgs e)
    {

        SaveFileDialog saveFileDialog1 = new SaveFileDialog();


        ScreenCapturer.CaptureAndSave(filename, mode, format, saveFileDialog1);

    }//

Allow only numbers and dot in script

Use Jquery instead. Add a decimal class to your textbox:

<input type="text" class="decimal" value="" />

Use this code in your JS. It checks for multiple decimals and also restrict users to type only numbers.

$('.decimal').keyup(function(){
    var val = $(this).val();
    if(isNaN(val)){
         val = val.replace(/[^0-9\.]/g,'');
         if(val.split('.').length>2) 
             val =val.replace(/\.+$/,"");
    }
    $(this).val(val); 
});?

Check this fiddle: http://jsfiddle.net/2YW8g/

Hope it helps.

Axios having CORS issue

This work out for me :

in javascript :

Axios({
            method: 'post',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            url: 'https://localhost:44346/Order/Order/GiveOrder',
            data: order
          }).then(function (response) {
            console.log(response.data);
          });

and in the backend (.net core) : in startup:

 #region Allow-Orgin
            services.AddCors(c =>
            {
                c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
            });
            #endregion

and in controller before action

[EnableCors("AllowOrigin")]

Could not find module "@angular-devkit/build-angular"

npm install Just type npm install and run.Then the project will run without errors. Or you can use npm install --save-dev @angular-devkit/build-angular

Copying sets Java

The copy constructor given by @Stephen C is the way to go when you have a Set you created (or when you know where it comes from). When it comes from a Map.entrySet(), it will depend on the Map implementation you're using:

findbugs says

The entrySet() method is allowed to return a view of the underlying Map in which a single Entry object is reused and returned during the iteration. As of Java 1.6, both IdentityHashMap and EnumMap did so. When iterating through such a Map, the Entry value is only valid until you advance to the next iteration. If, for example, you try to pass such an entrySet to an addAll method, things will go badly wrong.

As addAll() is called by the copy constructor, you might find yourself with a Set of only one Entry: the last one.

Not all Map implementations do that though, so if you know your implementation is safe in that regard, the copy constructor definitely is the way to go. Otherwise, you'd have to create new Entry objects yourself:

Set<K,V> copy = new HashSet<K,V>(map.size());
for (Entry<K,V> e : map.entrySet())
    copy.add(new java.util.AbstractMap.SimpleEntry<K,V>(e));

Edit: Unlike tests I performed on Java 7 and Java 6u45 (thanks to Stephen C), the findbugs comment does not seem appropriate anymore. It might have been the case on earlier versions of Java 6 (before u45) but I don't have any to test.

Get query string parameters url values with jQuery / Javascript (querystring)

Building on @Rob Neild's answer above, here is a pure JS adaptation that returns a simple object of decoded query string params (no %20's, etc).

function parseQueryString () {
  var parsedParameters = {},
    uriParameters = location.search.substr(1).split('&');

  for (var i = 0; i < uriParameters.length; i++) {
    var parameter = uriParameters[i].split('=');
    parsedParameters[parameter[0]] = decodeURIComponent(parameter[1]);
  }

  return parsedParameters;
}

MS Excel showing the formula in a cell instead of the resulting value

I had the same problem and solved with below:

Range("A").Formula = Trim(CStr("the formula"))

Jupyter notebook not running code. Stuck on In [*]

Upgrading ipykernel, notebook and then downgrading tornado to 4.2.0 solved the issue for me.

My current package versions related to jupyter:

jupyter==1.0.0
jupyter-client==5.2.2
jupyter-console==6.1.0
jupyter-core==4.4.0
jupyterlab==2.2.5
jupyterlab-server==1.2.0
ipykernel==5.3.4
notebook==5.2.2
tornado==4.2
pyparsing==2.4.2
ipython==5.5.0
ipython-genutils==0.2.0
prompt-toolkit==1.0.15

Github

The storage engine for the table doesn't support repair. InnoDB or MyISAM?

You have the wrong table set on the command. You should use the following on your setup:

ALTER TABLE scode_tracker.ap_visits ENGINE=MyISAM;

Entity Framework - "An error occurred while updating the entries. See the inner exception for details"

I had same problem about SaveChanges() in EF but in my case I forget to update my sql table then after I used migration my problem solved so maybe updating your tables will solve problem.

How to Use -confirm in PowerShell

write-host does not have a -confirm parameter.

You can do it something like this instead:

    $caption = "Please Confirm"    
    $message = "Are you Sure You Want To Proceed:"
    [int]$defaultChoice = 0
    $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Do the job."
    $no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "Do not do the job."
    $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
    $choiceRTN = $host.ui.PromptForChoice($caption,$message, $options,$defaultChoice)

if ( $choiceRTN -ne 1 )
{
   "Your Choice was Yes"
}
else
{
   "Your Choice was NO"
}

How do I use the lines of a file as arguments of a command?

command `< file`

will pass file contents to the command on stdin, but will strip newlines, meaning you couldn't iterate over each line individually. For that you could write a script with a 'for' loop:

for line in `cat input_file`; do some_command "$line"; done

Or (the multi-line variant):

for line in `cat input_file`
do
    some_command "$line"
done

Or (multi-line variant with $() instead of ``):

for line in $(cat input_file)
do
    some_command "$line"
done

References:

  1. For loop syntax: https://www.cyberciti.biz/faq/bash-for-loop/

while-else-loop

Am I missing something?

Doesn't this hypothetical code

while(rowIndex >= dataColLinker.size()) {
    dataColLinker.add(value);
} else {
    dataColLinker.set(rowIndex, value);
}

mean the same thing as this?

while(rowIndex >= dataColLinker.size()) {
    dataColLinker.add(value);
}
dataColLinker.set(rowIndex, value);

or this?

if (rowIndex >= dataColLinker.size()) {
    do {
        dataColLinker.add(value);
    } while(rowIndex >= dataColLinker.size());
} else {
    dataColLinker.set(rowIndex, value);
}

(The latter makes more sense ... I guess). Either way, it is obvious that you can rewrite the loop so that the "else test" is not repeated inside the loop ... as I have just done.


FWIW, this is most likely a case of premature optimization. That is, you are probably wasting your time optimizing code that doesn't need to be optimized:

  • For all you know, the JIT compiler's optimizer may have already moved the code around so that the "else" part is no longer in the loop.

  • Even if it hasn't, the chances are that the particular thing you are trying to optimize is not a significant bottleneck ... even if it might be executed 600,000 times.

My advice is to forget this problem for now. Get the program working. When it is working, decide if it runs fast enough. If it doesn't then profile it, and use the profiler output to decide where it is worth spending your time optimizing.

What are the applications of binary trees?

A binary tree is a tree data structure in which each node has at most two child nodes, usually distinguished as "left" and "right". Nodes with children are parent nodes, and child nodes may contain references to their parents. Outside the tree, there is often a reference to the "root" node (the ancestor of all nodes), if it exists. Any node in the data structure can be reached by starting at root node and repeatedly following references to either the left or right child. In a binary tree a degree of every node is maximum two.

Binary Tree

Binary trees are useful, because as you can see in the picture, if you want to find any node in the tree, you only have to look a maximum of 6 times. If you wanted to search for node 24, for example, you would start at the root.

  • The root has a value of 31, which is greater than 24, so you go to the left node.
  • The left node has a value of 15, which is less than 24, so you go to the right node.
  • The right node has a value of 23, which is less than 24, so you go to the right node.
  • The right node has a value of 27, which is greater than 24, so you go to the left node.
  • The left node has a value of 25, which is greater than 24, so you go to the left node.
  • The node has a value of 24, which is the key we are looking for.

This search is illustrated below: Tree search

You can see that you can exclude half of the nodes of the entire tree on the first pass. and half of the left subtree on the second. This makes for very effective searches. If this was done on 4 billion elements, you would only have to search a maximum of 32 times. Therefore, the more elements contained in the tree, the more efficient your search can be.

Deletions can become complex. If the node has 0 or 1 child, then it's simply a matter of moving some pointers to exclude the one to be deleted. However, you can not easily delete a node with 2 children. So we take a short cut. Let's say we wanted to delete node 19.

Delete 1

Since trying to determine where to move the left and right pointers to is not easy, we find one to substitute it with. We go to the left sub-tree, and go as far right as we can go. This gives us the next greatest value of the node we want to delete.

Delete 3

Now we copy all of 18's contents, except for the left and right pointers, and delete the original 18 node.

Delete 4


To create these images, I implemented an AVL tree, a self balancing tree, so that at any point in time, the tree has at most one level of difference between the leaf nodes (nodes with no children). This keeps the tree from becoming skewed and maintains the maximum O(log n) search time, with the cost of a little more time required for insertions and deletions.

Here is a sample showing how my AVL tree has kept itself as compact and balanced as possible.

enter image description here

In a sorted array, lookups would still take O(log(n)), just like a tree, but random insertion and removal would take O(n) instead of the tree's O(log(n)). Some STL containers use these performance characteristics to their advantage so insertion and removal times take a maximum of O(log n), which is very fast. Some of these containers are map, multimap, set, and multiset.

Example code for an AVL tree can be found at http://ideone.com/MheW8

Switch on ranges of integers in JavaScript

This does not require a switch statement. It is clearer, more concise, faster, and optimises better, to use if else statements...

var d = this.dealer;
if (1 <= d && d <= 11) { // making sure in range 1..11
    if (d <= 4) {
        alert("1 to 4");
    } else if (d <= 8) {
        alert("5 to 8");
    } else {
        alert("9 to 11");
    }
} else {
    alert("not in range");
}

Speed test

I was curious about the overhead of using a switch instead of the simpler if...else..., so I put together a jsFiddle to examine it... http://jsfiddle.net/17x9w1eL/

  • Chrome: switch was around 70% slower than if else

  • Firefox: switch was around 5% slower than if else

  • IE: switch was around 5% slower than if else

  • Safari: switch was around 95% slower than if else

Notes:

Assigning to the local variable is optional, especially if your code is going to be automatically optimised later.

For numeric ranges, I like to use this kind of construction...

if (1 <= d && d <= 11) {...}

... because to me it reads closer to the way you would express a range in maths (1 <= d <= 11), and when I'm reading the code, I can read that as "if d is between 1 and 11".

Clearer

A few people don't think this is clearer. I'd say it is not less clear as the structure is close to identical to the switch option. The main reason it is clearer is that every part of it is readable and makes simple intuitive sense.

My concern, with "switch (true)", is that it can appear to be a meaningless line of code. Many coders, reading that will not know what to make of it.

For my own code, I'm more willing to use obscure structures from time to time, but if anyone else will look at it, I try to use clearer constructs. I think it is better to use the constructs for what they are intended.

Optimisation

In a modern environment, code is often going to be minified for production, so you can write clear concise code, with readable variable names and helpful comments. There's no clear reason to use switch in this way.

I also tried putting both constructs through a minifier. The if/else structure compresses well, becoming a single short expression using nested ternary operators. The switch statement when minified remains a switch, complete with "switch", "case" and "break" tokens, and as a result is considerably longer in code.

How switch(true) works

I think "switch(true) is obscure, but it seems some people just want to use it, so here's an explanation of why it works...

A switch/case statement works by matching the part in the switch with each case, and then executing the code on the first match. In most use cases, we have a variable or non-constant expression in the switch, and then match it.

With "switch(true), we will find the first expression in the case statements that is true. If you read "switch (true)" as "find the first expression that is true", the code feels more readable.

How do I remove the "extended attributes" on a file in Mac OS X?


Answer (Individual Files)


1. Showcase keys to use in selection.

xattr ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png
    # com.apple.FinderInfo
    # com.apple.lastuseddate#PS
    # com.apple.metadata:kMDItemIsScreenCapture
    # com.apple.metadata:kMDItemScreenCaptureGlobalRect
    # com.apple.metadata:kMDItemScreenCaptureType

2. Pick a Key to delete.

xattr -d com.apple.lastuseddate#PS ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png
xattr -d kMDItemIsScreenCapture ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png

3. Showcase keys again to see they have been removed.

xattr -l ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png
    # com.apple.FinderInfo
    # com.apple.metadata:kMDItemScreenCaptureGlobalRect
    # com.apple.metadata:kMDItemScreenCaptureType

4. Lastly, REMOVE ALL keys for a particular file

xattr -c ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png

Answer (All Files In A Directory)


1. Showcase keys to use in selection.

xattr -r ~/Desktop

2. Remove a Specific Key for EVERY FILE in a directory

xattr -rd com.apple.FinderInfo ~/Desktop

3. Remove ALL keys on EVERY FILE in a directory

xattr -rc ~/Desktop

WARN: Once you delete these you DON'T get them back!
FAULT ERROR: There is NO UNDO.


Errors


I wanted to address the error's people are getting. Because the errors drove me nuts too... On a mac if you install xattr in python, then your environment may have an issue.

There are two different paths on my mac for xattr

type -a xattr

    # xattr is /usr/local/bin/xattr    # PYTHON Installed Version
    # xattr is /usr/bin/xattr          # Mac OSX Installed Version

So in one of the example's where -c will not work in xargs is because in bash you default to the non-python version.

Works with -c

/usr/bin/xattr -c

Does NOT Work with -c

/usr/local/bin/xattr -c
    # option -c not recognized

My Shell/Terminal defaults to /usr/local/bin/xattr because my $PATH /usr/local/bin: is before /usr/bin: which I believe is the default.

I can prove this because, if you try to uninstall the python xattr you will see:

pip3 uninstall xattr
Uninstalling xattr-0.9.6:
  Would remove:
    /usr/local/bin/xattr
    /usr/local/lib/python3.7/site-packages/xattr-0.9.6.dist-info/*
    /usr/local/lib/python3.7/site-packages/xattr/*
Proceed (y/n)?

Workarounds


To Fix option -c not recognized Errors.

  1. Uninstall any Python xattr you may have: pip3 uninstall xattr
  2. Close all Terminal windows & quit Terminal
  3. Reopen a new Terminal window.
  4. ReRun xattr command and it should now work.

OR

If you want to keep the Python xattr then use

/usr/bin/xattr

for any Shell commands in Terminal


Example:


Python's version of xattr doesn't handle images at all:

Good-Mac:~ JayRizzo$ xattr ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png
    # com.apple.FinderInfo
    # Traceback (most recent call last):
    #   File "/usr/local/bin/xattr", line 8, in <module>
    #     sys.exit(main())
    #   File "/usr/local/lib/python3.7/site-packages/xattr/tool.py", line 196, in main
    #     attr_value = attr_value.decode('utf-8')
    # UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb0 in position 2: invalid start byte

Good-Mac:~ JayRizzo$ /usr/bin/xattr ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png
    # com.apple.FinderInfo
    # com.apple.lastuseddate#PS
    # com.apple.metadata:kMDItemIsScreenCapture
    # com.apple.metadata:kMDItemScreenCaptureGlobalRect
    # com.apple.metadata:kMDItemScreenCaptureType

Man Pages

MAN PAGE for OSX xattr

MAN PAGE for Python xattr VERSION 0.6.4

NOTE: I could not find the python help page for current VERSION 0.9.6

Thanks for Reading!

Eclipse cannot load SWT libraries

SOLVED:

Because I had installed the Oracle Java 7 it had changed the default Java to Oracle Java 7, however it needed to be the Open JDK.

To fix, open up terminal and type

sudo update-alternatives --config java

This brings up a list of the different types of Java. Simply select the Open JDK.

Using an attribute of the current class instance as a default value for method's parameter

It's written as:

def my_function(self, param_one=None): # Or custom sentinel if None is vaild
    if param_one is None:
        param_one = self.one_of_the_vars

And I think it's safe to say that will never happen in Python due to the nature that self doesn't really exist until the function starts... (you can't reference it, in its own definition - like everything else)

For example: you can't do d = {'x': 3, 'y': d['x'] * 5}

Reading int values from SqlDataReader

you can use

reader.GetInt32(3);

to read an 32 bit int from the data reader.

If you know the type of your data I think its better to read using the Get* methods which are strongly typed rather than just reading an object and casting.

Have you considered using

reader.GetInt32(reader.GetOrdinal(columnName)) 

rather than accessing by position. This makes your code less brittle and will not break if you change the query to add new columns before the existing ones. If you are going to do this in a loop, cache the ordinal first.

Best design for a changelog / auditing database table?

We also log old and new values and the column they are from as well as the primary key of the table being audited in an audit detail table. Think what you need the audit table for? Not only do you want to know who made a change and when, but when a bad change happens, you want a fast way to put the data back.

While you are designing, you should write the code to recover data. When you need to recover, it is usually in a hurry, best to already be prepared.

Print second last column/field in awk

If you have many columns and want to print all but not the three cloumns in the last, then this might help

awk '{ $NF="";$(NF-1)="";$(NF-2)="" ; print $0 }'

cmake - find_library - custom library location

I saw that two people put that question to their favorites so I will try to answer the solution which works for me: Instead of using find modules I'm writing configuration files for all libraries which are installed. Those files are extremly simple and can also be used to set non-standard variables. CMake will (at least on windows) search for those configuration files in

CMAKE_PREFIX_PATH/<<package_name>>-<<version>>/<<package_name>>-config.cmake

(which can be set through an environment variable). So for example the boost configuration is in the path

CMAKE_PREFIX_PATH/boost-1_50/boost-config.cmake

In that configuration you can set variables. My config file for boost looks like that:

set(boost_INCLUDE_DIRS ${boost_DIR}/include)
set(boost_LIBRARY_DIR ${boost_DIR}/lib)
foreach(component ${boost_FIND_COMPONENTS}) 
    set(boost_LIBRARIES ${boost_LIBRARIES} debug ${boost_LIBRARY_DIR}/libboost_${component}-vc110-mt-gd-1_50.lib)
    set(boost_LIBRARIES ${boost_LIBRARIES} optimized ${boost_LIBRARY_DIR}/libboost_${component}-vc110-mt-1_50.lib)
endforeach()
add_definitions( -D_WIN32_WINNT=0x0501 )

Pretty straight forward + it's possible to shrink the size of the config files even more when you write some helper functions. The only issue I have with this setup is that I havn't found a way to give config files a priority over find modules - so you need to remove the find modules.

Hope this this is helpful for other people.

Angular 5 ngHide ngShow [hidden] not working

2019 Update: I realize that this is somewhat bad advice. As the first comment states, this heavily depends on the situation, and it is not a bad practice to use the [hidden] attribute: see the comments for some of the cases where you need to use it and not *ngIf

Original answer:

You should always try to use *ngIf instead of [hidden].

 <input *ngIf="!isHidden" class="txt" type="password" [(ngModel)]="input_pw" >

There are several blog posts about that topics, but the bottom line is, that Hidden usually means you do not want the browser to render the object - using angular you still waste resource on rendering it, and it will end up in the DOM anyway (and tricky users can see it with basic browser manipulation).

What is the keyguard in Android?

Keyguard basically refers to the code that handles the unlocking of the phone. it's like the keypad lock on your nokia phone a few years back just with the utility on a touchscreen.

you can find more info it you look in android/app or com\android\internal\policy\impl

Good Luck !

how to get the last character of a string?

You can get the last char like this :

var lastChar=yourString.charAt(yourString.length-1);

Use CSS to remove the space between images

The best solution I've found for this is to contain them in a parent div, and give that div a font-size of 0.

Checking if a character is a special character in Java

You can use regular expressions.

String input = ...
if (input.matches("[^a-zA-Z0-9 ]"))

If your definition of a 'special character' is simply anything that doesn't apply to your other filters that you already have, then you can simply add an else. Also note that you have to use else if in this case:

if(c == ' ') {
    blankCount++;
} else if (Character.isDigit(c)) {
    digitCount++;
} else if (Character.isLetter(c)) {
    letterCount++;
} else { 
  specialcharCount++;
}

How to list running screen sessions?

The command screen -list may be what you want.

See the man

case in sql stored procedure on SQL Server

CASE isn't used for flow control... for this, you would need to use IF...

But, there's a set-based solution to this problem instead of the procedural approach:

UPDATE tblEmployee
SET 
  InOffice = CASE WHEN @NewStatus = 'InOffice' THEN -1 ELSE InOffice END,
  OutOffice = CASE WHEN @NewStatus = 'OutOffice' THEN -1 ELSE OutOffice END,
  Home = CASE WHEN @NewStatus = 'Home' THEN -1 ELSE Home END
WHERE EmpID = @EmpID

Note that the ELSE will preserves the original value if the @NewStatus condition isn't met.

After installing with pip, "jupyter: command not found"

After installation of Jupyter Notebook on Ubuntu I got below error:

Exception: Jupyter command 'jupyter-notebook' not found.

I used simple command it's working for me

pip install --upgrade --force-reinstall --no-cache-dir jupyter

Source: http://commandstech.com/how-to-install-jupyter-on-ubuntu16-04-with-pictures-commands-errors-solution/

After exit from root user then execute :

jupyter notebook

Git - Ignore node_modules folder everywhere

Try doing something like this

**/node_modules

** is used for a recursive call in the whole project

Two consecutive asterisks ** in patterns matched against full pathname may have special meaning:

A leading ** followed by a slash means match in all directories. For example, **/foo matches file or directory foo anywhere, the same as pattern foo. **/foo/bar matches file or directory bar anywhere that is directly under directory foo.

A trailing /** matches everything inside. For example, abc/** matches all files inside directory abc, relative to the location of the .gitignore file, with infinite depth.

A slash followed by two consecutive asterisks then a slash matches zero or more directories. For example, a/\**/b matches a/b, a/x/b, a/x/y/b and so on.

Other consecutive asterisks are considered invalid.

Reference

Setting WPF image source in code

var uriSource = new Uri(@"/WpfApplication1;component/Images/Untitled.png", UriKind.Relative);
foo.Source = new BitmapImage(uriSource);

This will load a image called "Untitled.png" in a folder called "Images" with its "Build Action" set to "Resource" in an assembly called "WpfApplication1".

javascript get child by id

document.getElementById('child') should return you the correct element - remember that id's need to be unique across a document to make it valid anyway.

edit : see this page - ids MUST be unique.

edit edit : alternate way to solve the problem :

<div onclick="test('child1')">
    Test
    <div id="child1">child</div>
</div>

then you just need the test() function to look up the element by id that you passed in.

fitting data with numpy

Note that you can use the Polynomial class directly to do the fitting and return a Polynomial instance.

from numpy.polynomial import Polynomial

p = Polynomial.fit(x, y, 4)
plt.plot(*p.linspace())

p uses scaled and shifted x values for numerical stability. If you need the usual form of the coefficients, you will need to follow with

pnormal = p.convert(domain=(-1, 1))

Restart pods when configmap updates in Kubernetes?

I also banged my head around this problem for some time and wished to solve this in an elegant but quick way.

Here are my 20 cents:

  • The answer using labels as mentioned here won't work if you are updating labels. But would work if you always add labels. More details here.

  • The answer mentioned here is the most elegant way to do this quickly according to me but had the problem of handling deletes. I am adding on to this answer:

Solution

I am doing this in one of the Kubernetes Operator where only a single task is performed in one reconcilation loop.

  • Compute the hash of the config map data. Say it comes as v2.
  • Create ConfigMap cm-v2 having labels: version: v2 and product: prime if it does not exist and RETURN. If it exists GO BELOW.
  • Find all the Deployments which have the label product: prime but do not have version: v2, If such deployments are found, DELETE them and RETURN. ELSE GO BELOW.
  • Delete all ConfigMap which has the label product: prime but does not have version: v2 ELSE GO BELOW.
  • Create Deployment deployment-v2 with labels product: prime and version: v2 and having config map attached as cm-v2 and RETURN, ELSE Do nothing.

That's it! It looks long, but this could be the fastest implementation and is in principle with treating infrastructure as Cattle (immutability).

Also, the above solution works when your Kubernetes Deployment has Recreate update strategy. Logic may require little tweaks for other scenarios.

Pan & Zoom Image

One addition to the superb solution provided by @Wieslaw Šoltés answer above

The existing code resets the image position using right click, but I am more accustomed to doing that with a double click. Just replace the existing child_MouseLeftButtonDown handler:

private void child_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        if (child != null)
        {
            var tt = GetTranslateTransform(child);
            start = e.GetPosition(this);
            origin = new Point(tt.X, tt.Y);
            this.Cursor = Cursors.Hand;
            child.CaptureMouse();
        }
    }

With this:

private void child_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        if ((e.ChangedButton == MouseButton.Left && e.ClickCount == 1))
        {
            if (child != null)
            {
                var tt = GetTranslateTransform(child);
                start = e.GetPosition(this);
                origin = new Point(tt.X, tt.Y);
                this.Cursor = Cursors.Hand;
                child.CaptureMouse();
            }
        }

        if ((e.ChangedButton == MouseButton.Left && e.ClickCount == 2))
        {
            this.Reset();
        }
    }

How can I represent 'Authorization: Bearer <token>' in a Swagger Spec (swagger.json)

By using the requestInterceptor, it worked for me:

const ui = SwaggerUIBundle({
  ...
  requestInterceptor: (req) => {
    req.headers.Authorization = "Bearer " + req.headers.Authorization;
    return req;
  },
  ...
});

Angular ng-if="" with multiple arguments

Yes, it's possible. for example checkout:

<div class="singleMatch" ng-if="match.date | date:'ddMMyyyy' === main.date &&  match.team1.code === main.team1code && match.team2.code === main.team2code">
    //Do something here
    </div>

Android studio- "SDK tools directory is missing"

I had this problem on a Mac due to a corporate proxy blocking the installer's call to the internet. The phase in which the Android Studio installer is supposed to install the SDK did not happen and the install process just went straight to the "SDK tools directory is missing" message. Sadly, there was no message stating that a connection could not be made.

To fix the problem, it was required that I list the path to my corporate PAC file by using Configure -> "Appearance and Behavior" -> System Settings -> HTTP Proxy. I selected "Automatic proxy configuration url:" and entered the correct URL for the PAC file.

Make Iframe to fit 100% of container's remaining height

Why not do this (with minor adjustment for body padding/margins)

<script>
  var oF = document.getElementById("iframe1");
  oF.style.height = document.body.clientHeight - oF.offsetTop - 0;
</script>

Way to insert text having ' (apostrophe) into a SQL table

try this

INSERT INTO exampleTbl VALUES('he doesn''t work for me')

(13: Permission denied) while connecting to upstream:[nginx]

13-permission-denied-while-connecting-to-upstreamnginx on centos server -

setsebool -P httpd_can_network_connect 1

Simple Digit Recognition OCR in OpenCV-Python

OCR which stands for Optical Character Recognition is a computer vision technique used to identify the different types of handwritten digits that are used in common mathematics. To perform OCR in OpenCV we will use the KNN algorithm which detects the nearest k neighbors of a particular data point and then classifies that data point based on the class type detected for n neighbors.

Data Used


This data contains 5000 handwritten digits where there are 500 digits for every type of digit. Each digit is of 20×20 pixel dimensions. We will split the data such that 250 digits are for training and 250 digits are for testing for every class.

Below is the implementation.




import numpy as np
import cv2
   
      
# Read the image
image = cv2.imread('digits.png')
  
# gray scale conversion
gray_img = cv2.cvtColor(image,
                        cv2.COLOR_BGR2GRAY)
  
# We will divide the image
# into 5000 small dimensions 
# of size 20x20
divisions = list(np.hsplit(i,100) for i in np.vsplit(gray_img,50))
  
# Convert into Numpy array
# of size (50,100,20,20)
NP_array = np.array(divisions)
   
# Preparing train_data
# and test_data.
# Size will be (2500,20x20)
train_data = NP_array[:,:50].reshape(-1,400).astype(np.float32)
  
# Size will be (2500,20x20)
test_data = NP_array[:,50:100].reshape(-1,400).astype(np.float32)
  
# Create 10 different labels 
# for each type of digit
k = np.arange(10)
train_labels = np.repeat(k,250)[:,np.newaxis]
test_labels = np.repeat(k,250)[:,np.newaxis]
   
# Initiate kNN classifier
knn = cv2.ml.KNearest_create()
  
# perform training of data
knn.train(train_data,
          cv2.ml.ROW_SAMPLE, 
          train_labels)
   
# obtain the output from the
# classifier by specifying the
# number of neighbors.
ret, output ,neighbours,
distance = knn.findNearest(test_data, k = 3)
   
# Check the performance and
# accuracy of the classifier.
# Compare the output with test_labels
# to find out how many are wrong.
matched = output==test_labels
correct_OP = np.count_nonzero(matched)
   
#Calculate the accuracy.
accuracy = (correct_OP*100.0)/(output.size)
   
# Display accuracy.
print(accuracy)


Output

91.64


Well, I decided to workout myself on my question to solve the above problem. What I wanted is to implement a simple OCR using KNearest or SVM features in OpenCV. And below is what I did and how. (it is just for learning how to use KNearest for simple OCR purposes).

1) My first question was about letter_recognition.data file that comes with OpenCV samples. I wanted to know what is inside that file.

It contains a letter, along with 16 features of that letter.

And this SOF helped me to find it. These 16 features are explained in the paper Letter Recognition Using Holland-Style Adaptive Classifiers. (Although I didn't understand some of the features at the end)

2) Since I knew, without understanding all those features, it is difficult to do that method. I tried some other papers, but all were a little difficult for a beginner.

So I just decided to take all the pixel values as my features. (I was not worried about accuracy or performance, I just wanted it to work, at least with the least accuracy)

I took the below image for my training data:

enter image description here

(I know the amount of training data is less. But, since all letters are of the same font and size, I decided to try on this).

To prepare the data for training, I made a small code in OpenCV. It does the following things:

  1. It loads the image.
  2. Selects the digits (obviously by contour finding and applying constraints on area and height of letters to avoid false detections).
  3. Draws the bounding rectangle around one letter and wait for key press manually. This time we press the digit key ourselves corresponding to the letter in the box.
  4. Once the corresponding digit key is pressed, it resizes this box to 10x10 and saves all 100 pixel values in an array (here, samples) and corresponding manually entered digit in another array(here, responses).
  5. Then save both the arrays in separate .txt files.

At the end of the manual classification of digits, all the digits in the training data (train.png) are labeled manually by ourselves, image will look like below:

enter image description here

Below is the code I used for the above purpose (of course, not so clean):

import sys

import numpy as np
import cv2

im = cv2.imread('pitrain.png')
im3 = im.copy()

gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)

#################      Now finding Contours         ###################

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

samples =  np.empty((0,100))
responses = []
keys = [i for i in range(48,58)]

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            cv2.imshow('norm',im)
            key = cv2.waitKey(0)

            if key == 27:  # (escape to quit)
                sys.exit()
            elif key in keys:
                responses.append(int(chr(key)))
                sample = roismall.reshape((1,100))
                samples = np.append(samples,sample,0)

responses = np.array(responses,np.float32)
responses = responses.reshape((responses.size,1))
print "training complete"

np.savetxt('generalsamples.data',samples)
np.savetxt('generalresponses.data',responses)

Now we enter in to training and testing part.

For the testing part, I used the below image, which has the same type of letters I used for the training phase.

enter image description here

For training we do as follows:

  1. Load the .txt files we already saved earlier
  2. create an instance of the classifier we are using (it is KNearest in this case)
  3. Then we use KNearest.train function to train the data

For testing purposes, we do as follows:

  1. We load the image used for testing
  2. process the image as earlier and extract each digit using contour methods
  3. Draw a bounding box for it, then resize it to 10x10, and store its pixel values in an array as done earlier.
  4. Then we use KNearest.find_nearest() function to find the nearest item to the one we gave. ( If lucky, it recognizes the correct digit.)

I included last two steps (training and testing) in single code below:

import cv2
import numpy as np

#######   training part    ############### 
samples = np.loadtxt('generalsamples.data',np.float32)
responses = np.loadtxt('generalresponses.data',np.float32)
responses = responses.reshape((responses.size,1))

model = cv2.KNearest()
model.train(samples,responses)

############################# testing part  #########################

im = cv2.imread('pi.png')
out = np.zeros(im.shape,np.uint8)
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            roismall = roismall.reshape((1,100))
            roismall = np.float32(roismall)
            retval, results, neigh_resp, dists = model.find_nearest(roismall, k = 1)
            string = str(int((results[0][0])))
            cv2.putText(out,string,(x,y+h),0,1,(0,255,0))

cv2.imshow('im',im)
cv2.imshow('out',out)
cv2.waitKey(0)

And it worked, below is the result I got:

enter image description here


Here it worked with 100% accuracy. I assume this is because all the digits are of the same kind and the same size.

But anyway, this is a good start to go for beginners (I hope so).

How do I query for all dates greater than a certain date in SQL Server?

We can use like below as well

SELECT * 
FROM dbo.March2010 A
WHERE CAST(A.Date AS Date) >= '2017-03-22';

SELECT * 
    FROM dbo.March2010 A
    WHERE CAST(A.Date AS Datetime) >= '2017-03-22 06:49:53.840';

What is the use of hashCode in Java?

From the Javadoc:

Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable.

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.

  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java programming language.)

Dynamically add data to a javascript map

Well any Javascript object functions sort-of like a "map"

randomObject['hello'] = 'world';

Typically people build simple objects for the purpose:

var myMap = {};

// ...

myMap[newKey] = newValue;

edit — well the problem with having an explicit "put" function is that you'd then have to go to pains to avoid having the function itself look like part of the map. It's not really a Javascripty thing to do.

13 Feb 2014 — modern JavaScript has facilities for creating object properties that aren't enumerable, and it's pretty easy to do. However, it's still the case that a "put" property, enumerable or not, would claim the property name "put" and make it unavailable. That is, there's still only one namespace per object.

Allow multi-line in EditText view in Android?

Another neat thing to do is to use android:minHeight along with android:layout_height="wrap_content". This way you can set the size of the edit when it's empty, and when the user inputs stuff, it stretches according to how much the user inputs, including multiple lines.

How can I see the current value of my $PATH variable on OS X?

By entering $PATH on its own at the command prompt, you're trying to run it. This isn't like Windows where you can get your path output by simply typing path.

If you want to see what the path is, simply echo it:

echo $PATH

How to add Apache HTTP API (legacy) as compile-time dependency to build.grade for Android M?

Note for Android 9 (Pie).

Additionally to useLibrary 'org.apache.http.legacy' you have to add in AndroidManifest.xml:

<uses-library android:name="org.apache.http.legacy" android:required="false"/>

Source: https://developer.android.com/about/versions/pie/android-9.0-changes-28

Reversing a string in C

#include <stdio.h>

int main()    
{

    char string[100];
    int i;

    printf("Enter a string:\n");
    gets(string);
    printf("\n");
    for(i=strlen(string)-1;i>-1;i--)

    printf("%c",string[i]);
}

Writing new lines to a text file in PowerShell

`n is a line feed character. Notepad (prior to Windows 10) expects linebreaks to be encoded as `r`n (carriage return + line feed, CR-LF). Open the file in some useful editor (SciTE, Notepad++, UltraEdit-32, Vim, ...) and convert the linebreaks to CR-LF. Or use PowerShell:

(Get-Content $logpath | Out-String) -replace "`n", "`r`n" | Out-File $logpath

How do ACID and database transactions work?

I slightly modified the printer example to make it more explainable

1 document which had 2 pages content was sent to printer

Transaction - document sent to printer

  • atomicity - printer prints 2 pages of a document or none
  • consistency - printer prints half page and the page gets stuck. The printer restarts itself and prints 2 pages with all content
  • isolation - while there were too many print outs in progress - printer prints the right content of the document
  • durability - while printing, there was a power cut- printer again prints documents without any errors

Hope this helps someone to get the hang of the concept of ACID

Where to download Microsoft Visual c++ 2003 redistributable

Another way:

using Unofficial (Full Size: 26.1 MB) VC++ All in one that contained your needed files:

http://www.wincert.net/forum/topic/9790-aio-microsoft-visual-bcfj-redistributable-x86x64/

OR (Smallest 5.10 MB) Microsoft Visual Basic/C++ Runtimes 1.1.1 RePacked Here:

http://www.wincert.net/forum/topic/9794-bonus-microsoft-visual-basicc-runtimes-111/

In Flask, What is request.args and how is it used?

According to the flask.Request.args documents.

flask.Request.args
A MultiDict with the parsed contents of the query string. (The part in the URL after the question mark).

So the args.get() is method get() for MultiDict, whose prototype is as follows:

get(key, default=None, type=None)

Update:
In newer version of flask (v1.0.x and v1.1.x), flask.Request.args is an ImmutableMultiDict(an immutable MultiDict), so the prototype and specific method above is still valid.