Programs & Examples On #Nfs

NFS is an acronym for Network File System, a network file system developed by Sun Microsystems most often associated with the Unix family of operating systems.

C# int to byte[]

using static System.Console;

namespace IntToBits
{
    class Program
    {
        static void Main()
        {
            while (true)
            {
                string s = Console.ReadLine();
                Clear();
                uint i;
                bool b = UInt32.TryParse(s, out i);
                if (b) IntPrinter(i);
            }
        }

        static void IntPrinter(uint i)
        {
            int[] iarr = new int [32];
            Write("[");
            for (int j = 0; j < 32; j++)
            {
                uint tmp = i & (uint)Math.Pow(2, j);

                iarr[j] = (int)(tmp >> j);
            }
            for (int j = 32; j > 0; j--)
            {
                if(j%8==0 && j != 32)Write("|");
                if(j%4==0 && j%8 !=0) Write("'");
                Write(iarr[j-1]);
            }
            WriteLine("]");
        }
    }
}```

Vagrant error : Failed to mount folders in Linux guest

I was running Vagrant with VirtualBox 5.1.X, and had to downgrade to VirtualBox 5.0.40, and install the vbguest plugin to solve this problem.

My steps were:

  • Uninstall VirtualBox 5.1.X
  • Install Vagrant 5.0.40
  • Reboot my machine
  • Run vagrant up for my vagrant. It'll fail.
  • Run vagrant plugin install vagrant-vbguest while my VM is running, to install the vagrant plugin. This manages syncing VirtualBox Guest versions between host and guest.
  • Run vagrant reload to reload my virtual machine
  • Magic!

Force unmount of NFS-mounted directory

I had the same problem, and neither umount /path -f, neither umount.nfs /path -f, neither fuser -km /path, works

finally I found a simple solution >.<

sudo /etc/init.d/nfs-common restart, then lets do the simple umount ;-)

Getting the text from a drop-down box

Please try the below this is the easiest way and it works perfectly

var newSkill_Text = document.getElementById("newSkill")[document.getElementById("newSkill").selectedIndex];

Merge two Excel tables Based on matching data in Columns

Teylyn's answer worked great for me, but I had to modify it a bit to get proper results. I want to provide an extended explanation for whoever would need it.

My setup was as follows:

  • Sheet1: full data of 2014
  • Sheet2: updated rows for 2015 in A1:D50, sorted by first column
  • Sheet3: merged rows
  • My data does not have a header row

I put the following formula in cell A1 of Sheet3:

=iferror(vlookup(Sheet1!A$1;Sheet2!$A$1:$D$50;column(A1);false);Sheet1!A1)

Read this as follows: Take the value of the first column in Sheet1 (old data). Look up in Sheet2 (updated rows). If present, output the value from the indicated column in Sheet2. On error, output the value for the current column of Sheet1.

Notes:

  • In my version of the formula, ";" is used as parameter separator instead of ",". That is because I am located in Europe and we use the "," as decimal separator. Change ";" back to "," if you live in a country where "." is the decimal separator.

  • A$1: means always take column 1 when copying the formula to a cell in a different column. $A$1 means: always take the exact cell A1, even when copying the formula to a different row or column.

After pasting the formula in A1, I extended the range to columns B, C, etc., until the full width of my table was reached. Because of the $-signs used, this gives the following formula's in cells B1, C1, etc.:

=IFERROR(VLOOKUP('Sheet1'!$A1;'Sheet2'!$A$1:$D$50;COLUMN(B1);FALSE);'Sheet1'!B1)
=IFERROR(VLOOKUP('Sheet1'!$A1;'Sheet2'!$A$1:$D$50;COLUMN(C1);FALSE);'Sheet1'!C1)

and so forth. Note that the lookup is still done in the first column. This is because VLOOKUP needs the lookup data to be sorted on the column where the lookup is done. The output column is however the column where the formula is pasted.

Next, select a rectangle in Sheet 3 starting at A1 and having the size of the data in Sheet1 (same number of rows and columns). Press Ctrl-D to copy the formulas of the first row to all selected cells.

Cells A2, A3, etc. will get these formulas:

=IFERROR(VLOOKUP('Sheet1'!$A2;'Sheet2'!$A$1:$D$50;COLUMN(A2);FALSE);'Sheet1'!A2)
=IFERROR(VLOOKUP('Sheet1'!$A3;'Sheet2'!$A$1:$D$50;COLUMN(A3);FALSE);'Sheet1'!A3)

Because of the use of $-signs, the lookup area is constant, but input data is used from the current row.

How can I use grep to show just filenames on Linux?

The standard option grep -l (that is a lowercase L) could do this.

From the Unix standard:

-l
    (The letter ell.) Write only the names of files containing selected
    lines to standard output. Pathnames are written once per file searched.
    If the standard input is searched, a pathname of (standard input) will
    be written, in the POSIX locale. In other locales, standard input may be
    replaced by something more appropriate in those locales.

You also do not need -H in this case.

SQL grouping by month and year

If I understand correctly. In order to group your results as requested, your Group By clause needs to have the same expression as your select statement.

GROUP BY MONTH(date) + '.' + YEAR(date)

To display the date as "month-date" format change the '.' to '-' The full syntax would be something like this.

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

python requests get cookies

Alternatively, you can use requests.Session and observe cookies before and after a request:

>>> import requests
>>> session = requests.Session()
>>> print(session.cookies.get_dict())
{}
>>> response = session.get('http://google.com')
>>> print(session.cookies.get_dict())
{'PREF': 'ID=5514c728c9215a9a:FF=0:TM=1406958091:LM=1406958091:S=KfAG0U9jYhrB0XNf', 'NID': '67=TVMYiq2wLMNvJi5SiaONeIQVNqxSc2RAwVrCnuYgTQYAHIZAGESHHPL0xsyM9EMpluLDQgaj3db_V37NjvshV-eoQdA8u43M8UwHMqZdL-S2gjho8j0-Fe1XuH5wYr9v'}

pyplot axes labels for subplots

# list loss and acc are your data
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)

ax1.plot(iteration1, loss)
ax2.plot(iteration2, acc)

ax1.set_title('Training Loss')
ax2.set_title('Training Accuracy')

ax1.set_xlabel('Iteration')
ax1.set_ylabel('Loss')

ax2.set_xlabel('Iteration')
ax2.set_ylabel('Accuracy')

How to set my phpmyadmin user session to not time out so quickly?

Once you're logged into phpmyadmin look on the top navigation for "Settings" and click that then:

"Features" >

...and you'll find "Login cookie validity" which is typically set to 1440.

Unfortunately changing it through the UI means that the changes don't persist between logins.

how to get html content from a webview?

Why not get the html first then pass it to the web view?

private String getHtml(String url){
    HttpGet pageGet = new HttpGet(url);

    ResponseHandler<String> handler = new ResponseHandler<String>() {
        public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            HttpEntity entity = response.getEntity();
            String html; 

            if (entity != null) {
                html = EntityUtils.toString(entity);
                return html;
            } else {
                return null;
            }
        }
    };

    pageHTML = null;
    try {
        while (pageHTML==null){
            pageHTML = client.execute(pageGet, handler);
        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return pageHTML;
}

@Override
public void customizeWebView(final ServiceCommunicableActivity activity, final WebView webview, final SearchResult mRom) {
    mRom.setFileSize(getFileSize(mRom.getURLSuffix()));
    webview.getSettings().setJavaScriptEnabled(true);
    WebViewClient anchorWebViewClient = new WebViewClient()
    {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);

            //Do what you want to with the html
            String html = getHTML(url);

            if( html!=null && !url.equals(lastLoadedURL)){
                lastLoadedURL = url;
                webview.loadDataWithBaseURL(url, html, null, "utf-8", url);
            }
}

This should roughly do what you want to do. It is adapted from Is it possible to get the HTML code from WebView and shout out to https://stackoverflow.com/users/325081/aymon-fournier for his answer.

is it possible to add colors to python output?

being overwhelmed by being VERY NEW to python i missed some very simple and useful commands given here: Print in terminal with colors using Python? -

eventually decided to use CLINT as an answer that was given there by great and smart people

How to create checkbox inside dropdown?

Multiple drop downs with checkbox's and jQuery.

<div id="list3" class="dropdown-check-list" tabindex="100">
<span class="anchor">Which development(s) are you interested in?</span>
  <ul class="items">
      <li><input id="answers_2529_the-lawns" name="answers[2529][answers][]" type="checkbox" value="The Lawns"/><label for="answers_2529_the-lawns">The Lawns</label></li>
      <li><input id="answers_2529_the-residence" name="answers[2529][answers][]" type="checkbox" value="The Residence"/><label for="answers_2529_the-residence">The Residence</label></li>
  </ul>
</div>

<style>
.dropdown-check-list{
display: inline-block;
width: 100%;
}
.dropdown-check-list:focus{
outline:0;
}
.dropdown-check-list .anchor {
width: 98%;
position: relative;
cursor: pointer;
display: inline-block;
padding-top:5px;
padding-left:5px;
padding-bottom:5px;
border:1px #ccc solid;
}
.dropdown-check-list .anchor:after {
position: absolute;
content: "";
border-left: 2px solid black;
border-top: 2px solid black;
padding: 5px;
right: 10px;
top: 20%;
-moz-transform: rotate(-135deg);
-ms-transform: rotate(-135deg);
-o-transform: rotate(-135deg);
-webkit-transform: rotate(-135deg);
transform: rotate(-135deg);
}
.dropdown-check-list .anchor:active:after {
right: 8px;
top: 21%;
}
.dropdown-check-list ul.items {
padding: 2px;
display: none;
margin: 0;
border: 1px solid #ccc;
border-top: none;
}
.dropdown-check-list ul.items li {
list-style: none;
}
.dropdown-check-list.visible .anchor {
color: #0094ff;
}
.dropdown-check-list.visible .items {
display: block;
}
</style>

<script>
jQuery(function ($) {
        var checkList = $('.dropdown-check-list');
        checkList.on('click', 'span.anchor', function(event){
            var element = $(this).parent();

            if ( element.hasClass('visible') )
            {
                element.removeClass('visible');
            }
            else
            {
                element.addClass('visible');
            }
        });
    });
</script>

MS-DOS Batch file pause with enter key

pause command is what you looking for. If you looking ONLY the case when enter is hit you can abuse the runas command:

runas /user:# "" >nul 2>&1

the screen will be frozen until enter is hit.What I like more than set/p= is that if you press other buttons than enter they will be not displayed.

The difference between Classes, Objects, and Instances

A class is basically a definition, and contains the object's code. An object is an instance of a class

for example if you say

String word = new String();

the class is the String class, which describes the object (instance) word.

When a class is declared, no memory is allocated so class is just a template.

When the object of the class is declared, memory is allocated.

Fastest way to zero out a 2d array in C?

How was your 2D array declared?

If it something like:

int arr[20][30];

You can zero it by doing:

memset(arr, sizeof(int)*20*30);

How to use jQuery Plugin with Angular 4?

You should not use jQuery in Angular. While it is possible (see other answers for this question), it is discouraged. Why?

Angular holds an own representation of the DOM in its memory and doesn't use query-selectors (functions like document.getElementById(id)) like jQuery. Instead all the DOM-manipulation is done by Renderer2 (and Angular-directives like *ngFor and *ngIf accessing that Renderer2 in the background/framework-code). If you manipulate DOM with jQuery yourself you will sooner or later...

  1. Run into synchronization problems and have things wrongly appearing or not disappearing at the right time from your screen
  2. Have performance issues in more complex components, as Angular's internal DOM-representation is bound to zone.js and its change detection-mechanism - so updating the DOM manually will always block the thread your app is running on.
  3. Have other confusing errors you don't know the origin of.
  4. Not being able to test the application correctly (Jasmine requires you to know when elements have been rendered)
  5. Not being able to use Angular Universal or WebWorkers

If you really want to include jQuery (for duck-taping some prototype that you will 100% definitively throw away), I recommend to at least include it in your package.json with npm install --save jquery instead of getting it from google's CDN.

TLDR: For learning how to manipulate the DOM in the Angular way please go through the official tour-of heroes tutorial first: https://angular.io/tutorial/toh-pt2 If you need to access elements higher up in the DOM hierarchy (parent or document body) or for some other reason directives like *ngIf, *ngFor, custom directives, pipes and other angular utilities like [style.background], [class.myOwnCustomClass] don't satisfy your needs, use Renderer2: https://www.concretepage.com/angular-2/angular-4-renderer2-example

Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740]

I got the same error message on GraphQL mutation input object then I found the problem, Actually in my case mutation expecting an object array as input but I'm trying to insert a single object as input. For example:

First try

const mutationName = await apolloClient.mutate<insert_mutation, insert_mutationVariables>({
      mutation: MUTATION,
      variables: {
        objects: {id: 1, name: "John Doe"},
      },
    });

Corrected mutation call as an array

const mutationName = await apolloClient.mutate<insert_mutation, insert_mutationVariables>({
      mutation: MUTATION,
      variables: {
        objects: [{id: 1, name: "John Doe"}],
      },
    });

Sometimes simple mistakes like this can cause the problems. Hope this'll help someone.

Maven: How to change path to target directory from command line?

You should use profiles.

<profiles>
    <profile>
        <id>otherOutputDir</id>
        <build>
            <directory>yourDirectory</directory>
        </build>
    </profile>
</profiles>

And start maven with your profile

mvn compile -PotherOutputDir

If you really want to define your directory from the command line you could do something like this (NOT recommended at all) :

<properties>
    <buildDirectory>${project.basedir}/target</buildDirectory>
</properties>

<build>
    <directory>${buildDirectory}</directory>
</build>

And compile like this :

mvn compile -DbuildDirectory=test

That's because you can't change the target directory by using -Dproject.build.directory

What does it mean with bug report captured in android tablet?

It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.

Edit: This is what the forums say:

By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.

To disable:

/system/bin/bugmailer.sh must be deleted/renamed.

There should be a folder on your SD card called "bug reports".

Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948

And this one: http://forum.xda-developers.com/showthread.php?t=1405639

How to check the extension of a filename in a bash script?

Make

if [ "$file" == "*.txt" ]

like this:

if [[ $file == *.txt ]]

That is, double brackets and no quotes.

The right side of == is a shell pattern. If you need a regular expression, use =~ then.

Fatal error: Call to undefined function socket_create()

Open the php.ini file in your server environment and remove ; from ;extension=sockets. if it's doesn't work, you have to download the socket extension for PHP and put it into ext directory in the php installation path. Restart your http server and everything should work.

Remote origin already exists on 'git push' to a new repository

Step:1

git remote rm origin

Step:2

git remote add origin enter_your_repository_url

Example:

git remote add origin https://github.com/my_username/repository_name.git

jquery save json data object in cookie

use JSON.stringify(userData) to coverty json object to string.

var dataStore = $.cookie("basket-data", JSON.stringify($("#ArticlesHolder").data()));

and for getting back from cookie use JSON.parse()

var data=JSON.parse($.cookie("basket-data"))

What's the difference between equal?, eql?, ===, and ==?

I wrote a simple test for all the above.

def eq(a, b)
  puts "#{[a, '==',  b]} : #{a == b}"
  puts "#{[a, '===', b]} : #{a === b}"
  puts "#{[a, '.eql?', b]} : #{a.eql?(b)}"
  puts "#{[a, '.equal?', b]} : #{a.equal?(b)}"
end

eq("all", "all")
eq(:all, :all)
eq(Object.new, Object.new)
eq(3, 3)
eq(1, 1.0)

Python Prime number checker

max=int(input("Find primes upto what numbers?"))
primeList=[]
for x in range(2,max+1):
    isPrime=True
    for y in range(2,int(x**0.5)+1) :
        if x%y==0:
            isPrime=False
            break

    if isPrime:
        primeList.append(x)
print(primeList)

How do I see what character set a MySQL database / table / column is?

For tables and columns:

show create table your_table_name

What does template <unsigned int N> mean?

It's perfectly possible to template a class on an integer rather than a type. We can assign the templated value to a variable, or otherwise manipulate it in a way we might with any other integer literal:

unsigned int x = N;

In fact, we can create algorithms which evaluate at compile time (from Wikipedia):

template <int N>
struct Factorial 
{
     enum { value = N * Factorial<N - 1>::value };
};

template <>
struct Factorial<0> 
{
    enum { value = 1 };
};

// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
    int x = Factorial<4>::value; // == 24
    int y = Factorial<0>::value; // == 1
}

How can I check if PostgreSQL is installed or not via Linux script?

Well, all answersabove are good but not in all cases.

Basically check the folder /etc/postgresql/

in most cases there will be one subfolder eg. /etc/postgresql/11/ (or /etc/postgresql/12) which means that you have installed 11 (or 12) version, however in many cases you may have many of such subfolders, so having them all means that all those versions had been ever installed and could be in use ... so be aware of this important trace.

ps using Ubuntu 18.04

Make ABC Ordered List Items Have Bold Style

Are you sure you correctly applied the styles, or that there isn't another stylesheet interfering with your lists? I tried this:

<ol type="A">
<li><span class="label">Text</span></li>
<li><span class="label">Text</span></li>
<li><span class="label">Text</span></li>
</ol>

Then in the stylesheet:

ol {font-weight: bold;}
ol li span.label {font-weight:normal;}

And it bolded the A, B, C etc and not the text.

(Tested it in Opera 9.6, FF 3, Safari 3.2 and IE 7)

ALTER TABLE DROP COLUMN failed because one or more objects access this column

As already written in answers you need to drop constraints (created automatically by sql) related to all columns that you are trying to delete.

Perform followings steps to do the needful.

  1. Get Name of all Constraints using sp_helpconstraint which is a system stored procedure utility - execute following exec sp_helpconstraint '<your table name>'
  2. Once you get the name of the constraint then copy that constraint name and execute next statement i.e alter table <your_table_name> drop constraint <constraint_name_that_you_copied_in_1> (It'll be something like this only or similar format)
  3. Once you delete the constraint then you can delete 1 or more columns by using conventional method i.e Alter table <YourTableName> Drop column column1, column2 etc

JavaScript Array Push key value

You have to use bracket notation:

var obj = {};
obj[a[i]] = 0;
x.push(obj);

The result will be:

x = [{left: 0}, {top: 0}];

Maybe instead of an array of objects, you just want one object with two properties:

var x = {};

and

x[a[i]] = 0;

This will result in x = {left: 0, top: 0}.

How to use a variable for the database name in T-SQL?

You cannot use a variable in a create table statement. The best thing I can suggest is to write the entire query as a string and exec that.

Try something like this:

declare @query varchar(max);
set @query = 'create database TEST...';

exec (@query);

java: HashMap<String, int> not working

int is a primitive type, you can read what does mean a primitive type in java here, and a Map is an interface that has to objects as input:

public interface Map<K extends Object, V extends Object>

object means a class, and it means also that you can create an other class that exends from it, but you can not create a class that exends from int. So you can not use int variable as an object. I have tow solutions for your problem:

Map<String, Integer> map = new HashMap<>();

or

Map<String, int[]> map = new HashMap<>();
int x = 1;

//put x in map
int[] x_ = new int[]{x};
map.put("x", x_);

//get the value of x
int y = map.get("x")[0];

SyntaxError: multiple statements found while compiling a single statement

In the shell, you can't execute more than one statement at a time:

>>> x = 5
y = 6
SyntaxError: multiple statements found while compiling a single statement

You need to execute them one by one:

>>> x = 5
>>> y = 6
>>>

When you see multiple statements are being declared, that means you're seeing a script, which will be executed later. But in the interactive interpreter, you can't do more than one statement at a time.

maven compilation failure

Try to use:

mvn clean package install

This command should install your artifacts in you local maven repo.

PS: I see that this is an old question, but it may be helpful for somebody in the future.

Text not wrapping inside a div element

That's because there are no spaces in that long string so it has to break out of its container. Add word-break:break-all; to your .title rules to force a break.

#calendar_container > #events_container > .event_block > .title {
    width:400px;
    font-size:12px;
    word-break:break-all;
}

jsFiddle example

Getting Image from URL (Java)

You can try the this class to displays an image read from a URL within a JFrame.

public class ShowImageFromURL {

    public static void show(String urlLocation) {
        Image image = null;
        try {
            URL url = new URL(urlLocation);
            URLConnection conn = url.openConnection();
            conn.setRequestProperty("User-Agent", "Mozilla/5.0");

            conn.connect();
            InputStream urlStream = conn.getInputStream();
            image = ImageIO.read(urlStream);

            JFrame frame = new JFrame();
            JLabel lblimage = new JLabel(new ImageIcon(image));
            frame.getContentPane().add(lblimage, BorderLayout.CENTER);
            frame.setSize(image.getWidth(null) + 50, image.getHeight(null) + 50);
            frame.setVisible(true);

        } catch (IOException e) {
            System.out.println("Something went wrong, sorry:" + e.toString());
            e.printStackTrace();
        }
    }
}

Ref : https://gist.github.com/aslamanver/92af3ac67406cfd116b7e4e177156926

Matching an empty input box using CSS

input[value=""], input:not([value])

works with:

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

But the style will not change as soon as someone will start typing (you need JS for that).

Vertically align text within a div

Try this:

HTML

<div><span>Text</span></div>

CSS

div {
    height: 100px;
}

span {
    height: 100px;
    display: table-cell;
    vertical-align: middle;
}

.NET String.Format() to add commas in thousands place for a number

just simple as this:

float num = 23658; // for example 
num = num.ToString("N0"); // Returns 23,658

more info is in Here

Is there a macro to conditionally copy rows to another worksheet?

The way I would do this manually is:

  • Use Data - AutoFilter
  • Apply a custom filter based on a date range
  • Copy the filtered data to the relevant month sheet
  • Repeat for every month

Listed below is code to do this process via VBA.

It has the advantage of handling monthly sections of data rather than individual rows. Which can result in quicker processing for larger sets of data.

    Sub SeperateData()

    Dim vMonthText As Variant
    Dim ExcelLastCell As Range
    Dim intMonth As Integer

   vMonthText = Array("January", "February", "March", "April", "May", _
 "June", "July", "August", "September", "October", "November", "December")

        ThisWorkbook.Worksheets("Sharepoint").Select
        Range("A1").Select

    RowCount = ThisWorkbook.Worksheets("Sharepoint").UsedRange.Rows.Count
'Forces excel to determine the last cell, Usually only done on save
    Set ExcelLastCell = ThisWorkbook.Worksheets("Sharepoint"). _
     Cells.SpecialCells(xlLastCell)
'Determines the last cell with data in it


        Selection.EntireColumn.Insert
        Range("A1").FormulaR1C1 = "Month No."
        Range("A2").FormulaR1C1 = "=MONTH(RC[1])"
        Range("A2").Select
        Selection.Copy
        Range("A3:A" & ExcelLastCell.Row).Select
        ActiveSheet.Paste
        Application.CutCopyMode = False
        Calculate
    'Insert a helper column to determine the month number for the date

        For intMonth = 1 To 12
            Range("A1").CurrentRegion.Select
            Selection.AutoFilter Field:=1, Criteria1:="" & intMonth
            Selection.Copy
            ThisWorkbook.Worksheets("" & vMonthText(intMonth - 1)).Select
            Range("A1").Select
            ActiveSheet.Paste
            Columns("A:A").Delete Shift:=xlToLeft
            Cells.Select
            Cells.EntireColumn.AutoFit
            Range("A1").Select
            ThisWorkbook.Worksheets("Sharepoint").Select
            Range("A1").Select
            Application.CutCopyMode = False
        Next intMonth
    'Filter the data to a particular month
    'Convert the month number to text
    'Copy the filtered data to the month sheet
    'Delete the helper column
    'Repeat for each month

        Selection.AutoFilter
        Columns("A:A").Delete Shift:=xlToLeft
 'Get rid of the auto-filter and delete the helper column

    End Sub

When do you use Git rebase instead of Git merge?

Before merge/rebase:

A <- B <- C    [master]
^
 \
  D <- E       [branch]

After git merge master:

A <- B <- C
^         ^
 \         \
  D <- E <- F

After git rebase master:

A <- B <- C <- D' <- E'

(A, B, C, D, E and F are commits)

This example and much more well illustrated information about Git can be found in Git The Basics Tutorial.

Set a default font for whole iOS app?

For Xamarin.iOS inside AppDelegate's FinishedLaunching() put code like this :-

UILabel.Appearance.Font= UIFont.FromName("Lato-Regular", 14);

set font for the entire application and Add 'UIAppFonts' key on Info.plist , the path should be the path where your font file .ttf is situated .For me it was inside 'fonts' folder in my project.

<key>UIAppFonts</key>
    <array>
        <string>fonts/Lato-Regular.ttf</string>
    </array>

How to get the current user in ASP.NET MVC

In order to reference a user ID created using simple authentication built into ASP.NET MVC 4 in a controller for filtering purposes (which is helpful if you are using database first and Entity Framework 5 to generate code-first bindings and your tables are structured so that a foreign key to the userID is used), you can use

WebSecurity.CurrentUserId

once you add a using statement

using System.Web.Security;

Can I make a <button> not submit a form?

<form onsubmit="return false;">
   ...
</form>

How to create a GUID / UUID

You can use node-uuid (https://github.com/kelektiv/node-uuid)

Simple, fast generation of RFC4122 UUIDS.

Features:

  • Generate RFC4122 version 1 or version 4 UUIDs
  • Runs in node.js and browsers.
  • Cryptographically strong random # generation on supporting platforms.
  • Small footprint (Want something smaller? Check this out!)

Install Using NPM:

npm install uuid

Or Using uuid via browser:

Download Raw File (uuid v1): https://raw.githubusercontent.com/kelektiv/node-uuid/master/v1.js Download Raw File (uuid v4): https://raw.githubusercontent.com/kelektiv/node-uuid/master/v4.js


Want even smaller? Check this out: https://gist.github.com/jed/982883


Usage:

// Generate a v1 UUID (time-based)
const uuidV1 = require('uuid/v1');
uuidV1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a'

// Generate a v4 UUID (random)
const uuidV4 = require('uuid/v4');
uuidV4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1'

// Generate a v5 UUID (namespace)
const uuidV5 = require('uuid/v5');

// ... using predefined DNS namespace (for domain names)
uuidV5('hello.example.com', v5.DNS)); // -> 'fdda765f-fc57-5604-a269-52a7df8164ec'

// ... using predefined URL namespace (for, well, URLs)
uuidV5('http://example.com/hello', v5.URL); // -> '3bbcee75-cecc-5b56-8031-b6641c1ed1f1'

// ... using a custom namespace
const MY_NAMESPACE = '(previously generated unique uuid string)';
uuidV5('hello', MY_NAMESPACE); // -> '90123e1c-7512-523e-bb28-76fab9f2f73d'

ES6:

import uuid from 'uuid/v4';
const id = uuid();

How to change the ROOT application?

In Tomcat 7 (under Windows server) I didn't add or edit anything to any configuration file. I just renamed the ROOT folder to something else and renamed my application folder to ROOT and it worked fine.

Using git commit -a with vim

Try ZZ to save and close. Here is a bit more info on using vim with Git

vertical divider between two columns in bootstrap

I have tested it. It works fine.

.row.vdivide [class*='col-']:not(:last-child):after {
      background: #e0e0e0;
      width: 1px;
      content: "";
      display:block;
      position: absolute;
      top:0;
      bottom: 0;
      right: 0;
      min-height: 70px;
    }

    <div class="container">
      <div class="row vdivide">
        <div class="col-sm-3 text-center"><h1>One</h1></div>
        <div class="col-sm-3 text-center"><h1>Two</h1></div>
        <div class="col-sm-3 text-center"><h1>Three</h1></div>
        <div class="col-sm-3 text-center"><h1>Four</h1></div>
      </div>
    </div>

Windows batch script launch program and exit console

The simplest way ist just to start it with start

start notepad.exe

Here you can find more information about start

Zip lists in Python

It's worth adding here as it is such a highly ranking question on zip. zip is great, idiomatic Python - but it doesn't scale very well at all for large lists.

Instead of:

books = ['AAAAAAA', 'BAAAAAAA', ... , 'ZZZZZZZ']
words = [345, 567, ... , 672]

for book, word in zip(books, words):
   print('{}: {}'.format(book, word))

Use izip. For modern processing, it stores it in L1 Cache memory and is far more performant for larger lists. Use it as simply as adding an i:

for book, word in izip(books, words):
   print('{}: {}'.format(book, word))

Checking for empty result (php, pdo, mysql)

what I'm doing wrong here?

Almost everything.

$today = date('Y-m-d'); // no need for strtotime

$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");

$sth->bindParam(':today',$today); // no need for PDO::PARAM_STR

$sth->execute(); // no need for if
$this->id_email = $sth->fetchAll(PDO::FETCH_COLUMN); // no need for while

return count($this->id_email); // no need for the everything else

effectively, you always have your fetched data (in this case in $this->id_email variable) to tell whether your query returned anything or not. Read more in my article on PDO.

Force youtube embed to start in 720p

(This answer was updated, as the previous method using vq isn't recognized anymore.)

Specifying the height of the video will change the quality accordingly. example for html 5;

<iframe style='width:100%; height:800px;' src='https://www.youtube.com/embed/xxxxxxxx'></iframe>

If you don't want to hardcode the width and height you can add a class to the iframe for css media queries.

Tested on a working server + passes the w3.org nuhtml validator.

Git: copy all files in a directory from another branch

If there are no spaces in paths, and you are interested, like I was, in files of specific extension only, you can use

git checkout otherBranch -- $(git ls-tree --name-only -r otherBranch | egrep '*.java')

Meaning of Open hashing and Closed hashing

The use of "closed" vs. "open" reflects whether or not we are locked in to using a certain position or data structure (this is an extremely vague description, but hopefully the rest helps).

For instance, the "open" in "open addressing" tells us the index (aka. address) at which an object will be stored in the hash table is not completely determined by its hash code. Instead, the index may vary depending on what's already in the hash table.

The "closed" in "closed hashing" refers to the fact that we never leave the hash table; every object is stored directly at an index in the hash table's internal array. Note that this is only possible by using some sort of open addressing strategy. This explains why "closed hashing" and "open addressing" are synonyms.

Contrast this with open hashing - in this strategy, none of the objects are actually stored in the hash table's array; instead once an object is hashed, it is stored in a list which is separate from the hash table's internal array. "open" refers to the freedom we get by leaving the hash table, and using a separate list. By the way, "separate list" hints at why open hashing is also known as "separate chaining".

In short, "closed" always refers to some sort of strict guarantee, like when we guarantee that objects are always stored directly within the hash table (closed hashing). Then, the opposite of "closed" is "open", so if you don't have such guarantees, the strategy is considered "open".

What does it mean when Statement.executeUpdate() returns -1?

As the statement executed is not actually DML (eg UPDATE, INSERT or EXECUTE), but a piece of T-SQL which contains DML, I suspect it is not treated as an update-query.

Section 13.1.2.3 of the JDBC 4.1 specification states something (rather hard to interpret btw):

When the method execute returns true, the method getResultSet is called to retrieve the ResultSet object. When execute returns false, the method getUpdateCount returns an int. If this number is greater than or equal to zero, it indicates the update count returned by the statement. If it is -1, it indicates that there are no more results.

Given this information, I guess that executeUpdate() internally does an execute(), and then - as execute() will return false - it will return the value of getUpdateCount(), which in this case - in accordance with the JDBC spec - will return -1.

This is further corroborated by the fact 1) that the Javadoc for Statement.executeUpdate() says:

Returns: either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing

And 2) that the Javadoc for Statement.getUpdateCount() specifies:

the current result as an update count; -1 if the current result is a ResultSet object or there are no more results

Just to clarify: given the Javadoc for executeUpdate() the behavior is probably wrong, but it can be explained.

Also as I commented elsewhere, the -1 might just indicate: maybe something was changed, but we simply don't know, or we can't give an accurate number of changes (eg because in this example it is a piece of T-SQL that is executed).

C++ preprocessor __VA_ARGS__ number of arguments

this works with 0 arguments with gcc/llvm. [links are dumb]

/*
 * we need a comma at the start for ##_VA_ARGS__ to consume then
 * the arguments are pushed out in such a way that 'cnt' ends up with
 * the right count.  
 */
#define COUNT_ARGS(...) COUNT_ARGS_(,##__VA_ARGS__,6,5,4,3,2,1,0)
#define COUNT_ARGS_(z,a,b,c,d,e,f,cnt,...) cnt

#define C_ASSERT(test) \
    switch(0) {\
      case 0:\
      case test:;\
    }

int main() {
   C_ASSERT(0 ==  COUNT_ARGS());
   C_ASSERT(1 ==  COUNT_ARGS(a));
   C_ASSERT(2 ==  COUNT_ARGS(a,b));
   C_ASSERT(3 ==  COUNT_ARGS(a,b,c));
   C_ASSERT(4 ==  COUNT_ARGS(a,b,c,d));
   C_ASSERT(5 ==  COUNT_ARGS(a,b,c,d,e));
   C_ASSERT(6 ==  COUNT_ARGS(a,b,c,d,e,f));
   return 0;
}

Visual Studio seems to be ignoring the ## operator used to consume the empty argument. You can probably get around that with something like

#define CNT_ COUNT_ARGS
#define PASTE(x,y) PASTE_(x,y)
#define PASTE_(x,y) x ## y
#define CNT(...) PASTE(ARGVS,PASTE(CNT_(__VA_ARGS__),CNT_(1,##__VA_ARGS__)))
//you know its 0 if its 11 or 01
#define ARGVS11 0
#define ARGVS01 0
#define ARGVS12 1
#define ARGVS23 2
#define ARGVS34 3

Check for false

Checking if something isn't false... So it's true, just if you're doing something that is quantum physics.

if(!(borrar() === false))

or

if(borrar() === true)

MVC Razor Hidden input and passing values

As you may have already figured, Asp.Net MVC is a different paradigm than Asp.Net (webforms). Accessing form elements between the server and client take a different approach in Asp.Net MVC.

You can google more reading material on this on the web. For now, I would suggest using Ajax to get or post data to the server. You can still employ input type="hidden", but initialize it with a value from the ViewData or for Razor, ViewBag.

For example, your controller may look like this:

public ActionResult Index()
{
     ViewBag.MyInitialValue = true;
     return View();
} 

In your view, you can have an input elemet that is initialized by the value in your ViewBag:

<input type="hidden" name="myHiddenInput" id="myHiddenInput" value="@ViewBag.MyInitialValue" />

Then you can pass data between the client and server via ajax. For example, using jQuery:

$.get('GetMyNewValue?oldValue=' + $('#myHiddenInput').val(), function (e) {
   // blah
});

You can alternatively use $.ajax, $.getJSON, $.post depending on your requirement.

Retrieving Property name from lambda expression

This might be optimal

public static string GetPropertyName<TResult>(Expression<Func<TResult>> expr)
{
    var memberAccess = expr.Body as MemberExpression;
    var propertyInfo = memberAccess?.Member as PropertyInfo;
    var propertyName = propertyInfo?.Name;

    return propertyName;
}

Shorthand for if-else statement

You can use an object as a map:

  var hasName = ({
        "true"  : "Y",
        "false" : "N"
  })[name];

This also scales nicely for many options

  var hasName = ({
        "true"          : "Y",
        "false"         : "N",
        "fileNotFound"  : "O"
  })[name];

(Bonus point for people getting the reference)

Note: you should use actual booleans instead of the string value "true" for your variables indicating truth values.

Convert UTC dates to local time in PHP

PHP's strtotime function will interpret timezone codes, like UTC. If you get the date from the database/client without the timezone code, but know it's UTC, then you can append it.

Assuming you get the date with timestamp code (like "Fri Mar 23 2012 22:23:03 GMT-0700 (PDT)", which is what Javascript code ""+(new Date()) gives):

$time = strtotime($dateWithTimeZone);
$dateInLocal = date("Y-m-d H:i:s", $time);

Or if you don't, which is likely from MySQL, then:

$time = strtotime($dateInUTC.' UTC');
$dateInLocal = date("Y-m-d H:i:s", $time);

How to concatenate two IEnumerable<T> into a new IEnumerable<T>?

// The answer that I was looking for when searching
public void Answer()
{
    IEnumerable<YourClass> first = this.GetFirstIEnumerableList();
    // Assign to empty list so we can use later
    IEnumerable<YourClass> second = new List<YourClass>();

    if (IwantToUseSecondList)
    {
        second = this.GetSecondIEnumerableList();  
    }
    IEnumerable<SchemapassgruppData> concatedList = first.Concat(second);
}

An internal error occurred during: "Updating Maven Project". Unsupported IClasspathEntry kind=4

Your command line mvn eclipse project generator may not be the same version as that of your eclipse, and eclipse doesn't understand for your command line tool is generating. Just use eclipse's in this case:

  • remove the project from eclipse (including all modules if multi-module)
  • run: rm -rf .settings/ .project .classpath to delete eclipse project files, also from modules
  • import your project as an existing maven project

Time complexity of Euclid's Algorithm

Gabriel Lame's Theorem bounds the number of steps by log(1/sqrt(5)*(a+1/2))-2, where the base of the log is (1+sqrt(5))/2. This is for the the worst case scenerio for the algorithm and it occurs when the inputs are consecutive Fibanocci numbers.

A slightly more liberal bound is: log a, where the base of the log is (sqrt(2)) is implied by Koblitz.

For cryptographic purposes we usually consider the bitwise complexity of the algorithms, taking into account that the bit size is given approximately by k=loga.

Here is a detailed analysis of the bitwise complexity of Euclid Algorith:

Although in most references the bitwise complexity of Euclid Algorithm is given by O(loga)^3 there exists a tighter bound which is O(loga)^2.

Consider; r0=a, r1=b, r0=q1.r1+r2 . . . ,ri-1=qi.ri+ri+1, . . . ,rm-2=qm-1.rm-1+rm rm-1=qm.rm

observe that: a=r0>=b=r1>r2>r3...>rm-1>rm>0 ..........(1)

and rm is the greatest common divisor of a and b.

By a Claim in Koblitz's book( A course in number Theory and Cryptography) is can be proven that: ri+1<(ri-1)/2 .................(2)

Again in Koblitz the number of bit operations required to divide a k-bit positive integer by an l-bit positive integer (assuming k>=l) is given as: (k-l+1).l ...................(3)

By (1) and (2) the number of divisons is O(loga) and so by (3) the total complexity is O(loga)^3.

Now this may be reduced to O(loga)^2 by a remark in Koblitz.

consider ki= logri +1

by (1) and (2) we have: ki+1<=ki for i=0,1,...,m-2,m-1 and ki+2<=(ki)-1 for i=0,1,...,m-2

and by (3) the total cost of the m divisons is bounded by: SUM [(ki-1)-((ki)-1))]*ki for i=0,1,2,..,m

rearranging this: SUM [(ki-1)-((ki)-1))]*ki<=4*k0^2

So the bitwise complexity of Euclid's Algorithm is O(loga)^2.

Case-insensitive search in Rails model

You can also use scopes like this below and put them in a concern and include in models you may need them:

scope :ci_find, lambda { |column, value| where("lower(#{column}) = ?", value.downcase).first }

Then use like this: Model.ci_find('column', 'value')

Windows batch command(s) to read first line from text file

Try this

@echo off
setlocal enableextensions enabledelayedexpansion
set firstLine=1
for /f "delims=" %%i in (yourfilename.txt) do (
    if !firstLine!==1 echo %%i
    set firstLine=0
)
endlocal

What is std::move(), and when should it be used?

"What is it?" and "What does it do?" has been explained above.

I will give a example of "when it should be used".

For example, we have a class with lots of resource like big array in it.

class ResHeavy{ //  ResHeavy means heavy resource
    public:
        ResHeavy(int len=10):_upInt(new int[len]),_len(len){
            cout<<"default ctor"<<endl;
        }

        ResHeavy(const ResHeavy& rhs):_upInt(new int[rhs._len]),_len(rhs._len){
            cout<<"copy ctor"<<endl;
        }

        ResHeavy& operator=(const ResHeavy& rhs){
            _upInt.reset(new int[rhs._len]);
            _len = rhs._len;
            cout<<"operator= ctor"<<endl;
        }

        ResHeavy(ResHeavy&& rhs){
            _upInt = std::move(rhs._upInt);
            _len = rhs._len;
            rhs._len = 0;
            cout<<"move ctor"<<endl;
        }

    // check array valid
    bool is_up_valid(){
        return _upInt != nullptr;
    }

    private:
        std::unique_ptr<int[]> _upInt; // heavy array resource
        int _len; // length of int array
};

Test code:

void test_std_move2(){
    ResHeavy rh; // only one int[]
    // operator rh

    // after some operator of rh, it becomes no-use
    // transform it to other object
    ResHeavy rh2 = std::move(rh); // rh becomes invalid

    // show rh, rh2 it valid
    if(rh.is_up_valid())
        cout<<"rh valid"<<endl;
    else
        cout<<"rh invalid"<<endl;

    if(rh2.is_up_valid())
        cout<<"rh2 valid"<<endl;
    else
        cout<<"rh2 invalid"<<endl;

    // new ResHeavy object, created by copy ctor
    ResHeavy rh3(rh2);  // two copy of int[]

    if(rh3.is_up_valid())
        cout<<"rh3 valid"<<endl;
    else
        cout<<"rh3 invalid"<<endl;
}

output as below:

default ctor
move ctor
rh invalid
rh2 valid
copy ctor
rh3 valid

We can see that std::move with move constructor makes transform resource easily.

Where else is std::move useful?

std::move can also be useful when sorting an array of elements. Many sorting algorithms (such as selection sort and bubble sort) work by swapping pairs of elements. Previously, we’ve had to resort to copy-semantics to do the swapping. Now we can use move semantics, which is more efficient.

It can also be useful if we want to move the contents managed by one smart pointer to another.

Cited:

How to enable core dump in my Linux C++ program

You need to set ulimit -c. If you have 0 for this parameter a coredump file is not created. So do this: ulimit -c unlimited and check if everything is correct ulimit -a. The coredump file is created when an application has done for example something inappropriate. The name of the file on my system is core.<process-pid-here>.

Android camera intent

private static final int TAKE_PICTURE = 1;    
private Uri imageUri;

public void takePhoto(View view) {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File photo = new File(Environment.getExternalStorageDirectory(),  "Pic.jpg");
    intent.putExtra(MediaStore.EXTRA_OUTPUT,
            Uri.fromFile(photo));
    imageUri = Uri.fromFile(photo);
    startActivityForResult(intent, TAKE_PICTURE);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
    case TAKE_PICTURE:
        if (resultCode == Activity.RESULT_OK) {
            Uri selectedImage = imageUri;
            getContentResolver().notifyChange(selectedImage, null);
            ImageView imageView = (ImageView) findViewById(R.id.ImageView);
            ContentResolver cr = getContentResolver();
            Bitmap bitmap;
            try {
                 bitmap = android.provider.MediaStore.Images.Media
                 .getBitmap(cr, selectedImage);

                imageView.setImageBitmap(bitmap);
                Toast.makeText(this, selectedImage.toString(),
                        Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
                        .show();
                Log.e("Camera", e.toString());
            }
        }
    }
}

Using crontab to execute script every minute and another every 24 hours

This is the format of /etc/crontab:

# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed

I recommend copy & pasting that into the top of your crontab file so that you always have the reference handy. RedHat systems are setup that way by default.

To run something every minute:

* * * * * username /var/www/html/a.php

To run something at midnight of every day:

0 0 * * * username /var/www/html/reset.php

You can either include /usr/bin/php in the command to run, or you can make the php scripts directly executable:

chmod +x file.php

Start your php file with a shebang so that your shell knows which interpreter to use:

#!/usr/bin/php
<?php
// your code here

Find unique lines

uniq has the option you need:

   -u, --unique
          only print unique lines
$ cat file.txt
1
1
2
3
5
5
7
7
$ uniq -u file.txt
2
3

Better way to set distance between flexbox items

I posted my flexbox approach here:

One idea I rejected was to remove the padding from the outer columns with something like this:

div:nth-child(#{$col-number}n+1) { padding-left: 0; }
div:nth-child(#{$col-number}n+#{$col-number}) { padding-left: 0; }

But, like other posters here, I prefer the negative margin trick. My fiddle also has responsiveness for anyone is looking for a Sass-based solution. I basically use this approach in place of a grid.

https://jsfiddle.net/x3jvfrg1/

Get full query string in C# ASP.NET

just a moment ago, i came across with the same issue. and i resolve it in the following manner.

Response.Redirect("../index.aspx?Name="+this.textName.Text+"&LastName="+this.textlName.Text);

with reference to the this

Find most frequent value in SQL column

Let us consider table name as tblperson and column name as city. I want to retrieve the most repeated city from the city column:

 select city,count(*) as nor from tblperson
        group by city
          having count(*) =(select max(nor) from 
            (select city,count(*) as nor from tblperson group by city) tblperson)

Here nor is an alias name.

Get folder name of the file in Python

You could get the full path as a string then split it into a list using your operating system's separator character. Then you get the program name, folder name etc by accessing the elements from the end of the list using negative indices.

Like this:

import os
strPath = os.path.realpath(__file__)
print( f"Full Path    :{strPath}" )
nmFolders = strPath.split( os.path.sep )
print( "List of Folders:", nmFolders )
print( f"Program Name :{nmFolders[-1]}" )
print( f"Folder Name  :{nmFolders[-2]}" )
print( f"Folder Parent:{nmFolders[-3]}" )

The output of the above was this:

Full Path    :C:\Users\terry\Documents\apps\environments\dev\app_02\app_02.py
List of Folders: ['C:', 'Users', 'terry', 'Documents', 'apps', 'environments', 'dev', 'app_02', 'app_02.py']
Program Name :app_02.py
Folder Name  :app_02
Folder Parent:dev

How to reload a page after the OK click on the Alert Page

Try this:

alert("Successful Message");
location.reload();

jQuery date/time picker

@David, thanks for the recommendation! @fluid_chelsea, I've just released Any+Time(TM) version 3.x which uses jQuery instead of Prototype and has a much-improved interface, so I hope it now meets your needs:

http://www.ama3.com/anytime/

Any problems, please let me know via the comment link on my website!

Import regular CSS file in SCSS file?

It is now possible using:

@import 'CSS:directory/filename.css';

How to redirect to Login page when Session is expired in Java web application?

i found this posible solution:

public void logout() {
    ExternalContext ctx = FacesContext.getCurrentInstance().getExternalContext();
    String ctxPath = ((ServletContext) ctx.getContext()).getContextPath();
    try {
        //Use the context of JSF for invalidate the session,
        //without servlet
        ((HttpSession) ctx.getSession(false)).invalidate();
        //redirect with JSF context.
        ctx.redirect(ctxPath + "absolute/path/index.jsp");
    } catch (IOException ex) {
        System.out.println(ex.getMessage());
    }
}

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query

hope this may help you:

SELECT  CAST(LoginTime AS DATE)
         FROM    AuditTrail 

If you want to have some filters over this datetime or it's different parts, you can use built-in functions such as Year and Month

Double border with different color

You can use outline with outline offset

<div class="double-border"></div>
.double-border{
background-color:#ccc;
outline: 1px solid #f00;
outline-offset: 3px;
}

What is the difference between parseInt(string) and Number(string) in JavaScript?

Addendum to @sjngm's answer:

They both also ignore whitespace:

var foo = " 3 "; console.log(parseInt(foo)); // 3 console.log(Number(foo)); // 3

It is not exactly correct. As sjngm wrote parseInt parses string to first number. It is true. But the problem is when you want to parse number separated with whitespace ie. "12 345". In that case
parseInt("12 345") will return 12 instead of 12345. So to avoid that situation you must trim whitespaces before parsing to number. My solution would be:

     var number=parseInt("12 345".replace(/\s+/g, ''),10);

Notice one extra thing I used in parseInt() function. parseInt("string",10) will set the number to decimal format. If you would parse string like "08" you would get 0 because 8 is not a octal number.Explanation is here

SSL certificate rejected trying to access GitHub over HTTPS behind firewall

Improve RouMao's solution by temporarily disabling GIT/curl ssl verification in Windows cmd:

set GIT_SSL_NO_VERIFY=true
git config --global http.proxy http://<your-proxy>:443

The good thing about this solution is that it only takes effect in the current cmd window.

matplotlib does not show my drawings although I call pyplot.show()

For me the problem happens if I simply create an empty matplotlibrc file under ~/.matplotlib on macOS. Adding "backend: macosx" in it fixes the problem.

I think it is a bug: if backend is not specified in my matplotlibrc it should take the default value.

How to select option in drop down protractorjs e2e tests

----------
element.all(by.id('locregion')).then(function(Item)
{
 // Item[x] = > // x is [0,1,2,3]element you want to click
  Item[0].click(); //first item

  Item[3].click();     // fourth item
  expect(Item[0].getText()).toEqual('Ranjans Mobile Testing')


});

How to pass "Null" (a real surname!) to a SOAP web service in ActionScript 3

As a hack, you could consider having a special handling on the client side, converting 'Null' string to something that will never occur, for example, XXNULLXX and converting back on the server.

It is not pretty, but it may solve the issue for such a boundary case.

Finding all possible combinations of numbers to reach a given sum

function solve(n){
    let DP = [];

     DP[0] = DP[1] = DP[2] = 1;
     DP[3] = 2;

    for (let i = 4; i <= n; i++) {
      DP[i] = DP[i-1] + DP[i-3] + DP[i-4];
    }
    return DP[n]
}

console.log(solve(5))

This is a Dynamic Solution for JS to tell how many ways anyone can get the certain sum. This can be the right solution if you think about time and space complexity.

Accessing dictionary value by index in python

While you can do

value = d.values()[index]

It should be faster to do

value = next( v for i, v in enumerate(d.itervalues()) if i == index )

edit: I just timed it using a dict of len 100,000,000 checking for the index at the very end, and the 1st/values() version took 169 seconds whereas the 2nd/next() version took 32 seconds.

Also, note that this assumes that your index is not negative

Replace all occurrences of a string in a data frame

late to the party. but if you only want to get rid of leading/trailing white space, R base has a function trimws

For example:

data <- apply(X = data, MARGIN = 2, FUN = trimws) %>% as.data.frame()

How to read values from the querystring with ASP.NET Core?

Some of the comments mention this as well, but asp net core does all this work for you.

If you have a query string that matches the name it will be available in the controller.

https://myapi/some-endpoint/123?someQueryString=YayThisWorks

[HttpPost]
[Route("some-endpoint/{someValue}")]
public IActionResult SomeEndpointMethod(int someValue, string someQueryString)
    {
        Debug.WriteLine(someValue);
        Debug.WriteLine(someQueryString);
        return Ok();
    }

Ouputs:

123

YayThisWorks

Create a basic matrix in C (input by user !)

You need to dynamically allocate your matrix. For instance:

int* mat;
int dimx,dimy;
scanf("%d", &dimx);
scanf("%d", &dimy);
mat = malloc(dimx * dimy * sizeof(int));

This creates a linear array which can hold the matrix. At this point you can decide whether you want to access it column or row first. I would suggest making a quick macro which calculates the correct offset in the matrix.

PHP check if file is an image

Using file extension and getimagesize function to detect if uploaded file has right format is just the entry level check and it can simply bypass by uploading a file with true extension and some byte of an image header but wrong content.

for being secure and safe you may make thumbnail/resize (even with original image sizes) the uploaded picture and save this version instead the uploaded one. Also its possible to get uploaded file content and search it for special character like <?php to find the file is image or not.

How can I have two fixed width columns with one flexible column in the center?

Instead of using width (which is a suggestion when using flexbox), you could use flex: 0 0 230px; which means:

  • 0 = don't grow (shorthand for flex-grow)
  • 0 = don't shrink (shorthand for flex-shrink)
  • 230px = start at 230px (shorthand for flex-basis)

which means: always be 230px.

See fiddle, thanks @TylerH

Oh, and you don't need the justify-content and align-items here.

img {
    max-width: 100%;
}
#container {
    display: flex;
    x-justify-content: space-around;
    x-align-items: stretch;
    max-width: 1200px;
}
.column.left {
    width: 230px;
    flex: 0 0 230px;
}
.column.right {
    width: 230px;
    flex: 0 0 230px;
    border-left: 1px solid #eee;
}
.column.center {
    border-left: 1px solid #eee;
}

How to scroll to the bottom of a RecyclerView? scrollToPosition doesn't work

Just set setStackFromEnd=true or setReverseLayout=true so that LLM will layout items from end.

The difference between these two is that setStackFromEnd will set the view to show the last element, the layout direction will remain the same. (So, in an left-to-right horizontal Recycler View, the last element will be shown and scrolling to the left will show the earlier elements)

Whereas setReverseLayout will change the order of the elements added by the Adapter. The layout will start from the last element, which will be the left-most in an LTR Recycler View and then, scrolling to the right will show the earlier elements.

Sample:

final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setReverseLayout(true);
_listView.setLayoutManager(linearLayoutManager);

See documentation for details.

SQL - HAVING vs. WHERE

  1. WHERE clause can be used with SELECT, INSERT, and UPDATE statements, whereas HAVING can be used only with SELECT statement.

  2. WHERE filters rows before aggregation (GROUP BY), whereas HAVING filter groups after aggregations are performed.

  3. Aggregate function cannot be used in WHERE clause unless it is in a subquery contained in HAVING clause, whereas aggregate functions can be used in HAVING clause.

Source

How to set the authorization header using curl

http://curl.haxx.se/docs/httpscripting.html

See part 6. HTTP Authentication

HTTP Authentication

HTTP Authentication is the ability to tell the server your username and password so that it can verify that you're allowed to do the request you're doing. The Basic authentication used in HTTP (which is the type curl uses by default) is plain text based, which means it sends username and password only slightly obfuscated, but still fully readable by anyone that sniffs on the network between you and the remote server.

To tell curl to use a user and password for authentication:

curl --user name:password http://www.example.com

The site might require a different authentication method (check the headers returned by the server), and then --ntlm, --digest, --negotiate or even --anyauth might be options that suit you.

Sometimes your HTTP access is only available through the use of a HTTP proxy. This seems to be especially common at various companies. A HTTP proxy may require its own user and password to allow the client to get through to the Internet. To specify those with curl, run something like:

curl --proxy-user proxyuser:proxypassword curl.haxx.se

If your proxy requires the authentication to be done using the NTLM method, use --proxy-ntlm, if it requires Digest use --proxy-digest.

If you use any one these user+password options but leave out the password part, curl will prompt for the password interactively.

Do note that when a program is run, its parameters might be possible to see when listing the running processes of the system. Thus, other users may be able to watch your passwords if you pass them as plain command line options. There are ways to circumvent this.

It is worth noting that while this is how HTTP Authentication works, very many web sites will not use this concept when they provide logins etc. See the Web Login chapter further below for more details on that.

How do I center a window onscreen in C#?

A single line:

this.Location = new Point((Screen.PrimaryScreen.WorkingArea.Width - this.Width) / 2,
                          (Screen.PrimaryScreen.WorkingArea.Height - this.Height) / 2);

Javascript format date / time

You can do that:

function formatAMPM(date) { // This is to display 12 hour format like you asked
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var ampm = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0'+minutes : minutes;
  var strTime = hours + ':' + minutes + ' ' + ampm;
  return strTime;
}

var myDate = new Date();
var displayDate = myDate.getMonth()+ '/' +myDate.getDate()+ '/' +myDate.getFullYear()+ ' ' +formatAMPM(myDate);
console.log(displayDate);

Fiddle

Android - Share on Facebook, Twitter, Mail, ecc

Paresh Mayani's answer is mostly correct. Simply use a Broadcast Intent to let the system and all the other apps choose in what way the content is going to be shared.

To share text use the following code:

String message = "Text I want to share.";
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
share.putExtra(Intent.EXTRA_TEXT, message);

startActivity(Intent.createChooser(share, "Title of the dialog the system will open"));

Opening XML page shows "This XML file does not appear to have any style information associated with it."

This XML file does not appear to have any style information associated with it. The document tree is shown below.

You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml instead of text/html and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.

In case of JSF/Facelets files which have the default extension of .xhtml, that can in turn happen if the HTTP request hasn't invoked the FacesServlet and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml file extension which is in your Firefox configuration apparently by default interpreted as text/xml.

You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern> of the FacesServlet as registered in webapp's web.xml, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf, then you need to open the page by /some.jsf instead of /some.xhtml. Alternatively, you can also just change the <url-pattern> to *.xhtml. This way you never need to fiddle with virtual URLs.

See also:


Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.

How to change the font size and color of x-axis and y-axis label in a scatterplot with plot function in R?

Taking DWins example.

What I often do, particularly when I use many, many different plots with the same colours or size information, is I store them in variables I otherwise never use. This helps me keep my code a little cleaner AND I can change it "globally".

E.g.

clab = 1.5
cmain = 2
caxis = 1.2

plot(1, 1 ,xlab="x axis", ylab="y axis",  pch=19,
           col.lab="red", cex.lab=clab,    
           col="green", main = "Testing scatterplots", cex.main =cmain, cex.axis=caxis) 

You can also write a function, doing something similar. But for a quick shot this is ideal. You can also store that kind of information in an extra script, so you don't have a messy plot script:

which you then call with setwd("") source("plotcolours.r")

in a file say called plotcolours.r you then store all the e.g. colour or size variables

clab = 1.5
cmain = 2
caxis = 1.2 

for colours could use

darkred<-rgb(113,28,47,maxColorValue=255)

as your variable 'darkred' now has the colour information stored, you can access it in your actual plotting script.

plot(1,1,col=darkred) 

How to set only time part of a DateTime variable in C#

Use the constructor that allows you to specify the year, month, day, hours, minutes, and seconds:

var dateNow = DateTime.Now;
var date = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day, 4, 5, 6);

iOS 7 - Failing to instantiate default view controller

So this also happened to me too. I checked 50 times and my "Is Initial View Controller" was checked, believe me. It happened out of the blue. So how did I fix it?

  1. Create a new Storyboard in your project, name it something like Main_iPhoneV2 (or iPadV2 depending on your original storyboard style)
  2. Open the broken storyboard, click anywhere in the white area and press command-a, then command-c (select all and copy)
  3. Open your new storyboard and press command-v to paste the same exact setup
  4. Go to your project settings, change your "Main Interface" to the new Main_iPhoneV2 (If it's your iPad and you're writing a universal app, you'll have to edit the -Info.plist and look for the value "Main storyboard file base name (iPad)
  5. Recompile, and stop pulling your hair out

Setting the value of checkbox to true or false with jQuery

You can do (jQuery 1.6 onwards):

$('#idCheckbox').prop('checked', true);
$('#idCheckbox').prop('checked', false);

to remove you can also use:

$('#idCheckbox').removeProp('checked');

with jQuery < 1.6 you must do

$('#idCheckbox').attr('checked', true);
$('#idCheckbox').removeAttr('checked');

jQuery-- Populate select from json

I would do something like this:

$.each(temp,function(key, value) 
{
    $select.append('<option value=' + key + '>' + value + '</option>');
});

JSON structure would be appreciated. At first you can experiment with find('element') - it depends on JSON.

Enable the display of line numbers in Visual Studio

Options -> Text Editor -> All Languages -> Line Number checkbox enter image description here

Example to use shared_ptr?

#include <memory>
#include <iostream>

class SharedMemory {
    public: 
        SharedMemory(int* x):_capture(x){}
        int* get() { return (_capture.get()); }
    protected:
        std::shared_ptr<int> _capture;
};

int main(int , char**){
    SharedMemory *_obj1= new SharedMemory(new int(10));
    SharedMemory *_obj2 = new SharedMemory(*_obj1);
    std::cout << " _obj1: " << *_obj1->get() << " _obj2: " << *_obj2->get()
    << std::endl;
    delete _obj2;

    std::cout << " _obj1: " << *_obj1->get() << std::endl;
    delete _obj1;
    std::cout << " done " << std::endl;
}

This is an example of shared_ptr in action. _obj2 was deleted but pointer is still valid. output is, ./test _obj1: 10 _obj2: 10 _obj2: 10 done

How can I position my jQuery dialog to center?

Because the dialog need a position, You need to include the js position

<script src="jquery.ui.position.js"></script>

What integer hash function are good that accepts an integer hash key?

There's a nice overview over some hash algorithms at Eternally Confuzzled. I'd recommend Bob Jenkins' one-at-a-time hash which quickly reaches avalanche and therefore can be used for efficient hash table lookup.

Replacing objects in array

Considering that the accepted answer is probably inefficient for large arrays, O(nm), I usually prefer this approach, O(2n + 2m):

function mergeArrays(arr1 = [], arr2 = []){
    //Creates an object map of id to object in arr1
    const arr1Map = arr1.reduce((acc, o) => {
        acc[o.id] = o;
        return acc;
    }, {});
    //Updates the object with corresponding id in arr1Map from arr2, 
    //creates a new object if none exists (upsert)
    arr2.forEach(o => {
        arr1Map[o.id] = o;
    });

    //Return the merged values in arr1Map as an array
    return Object.values(arr1Map);
}

Unit test:

it('Merges two arrays using id as the key', () => {
   var arr1 = [{id:'124',name:'qqq'}, {id:'589',name:'www'}, {id:'45',name:'eee'}, {id:'567',name:'rrr'}];
   var arr2 = [{id:'124',name:'ttt'}, {id:'45',name:'yyy'}];
   const actual = mergeArrays(arr1, arr2);
   const expected = [{id:'124',name:'ttt'}, {id:'589',name:'www'}, {id:'45',name:'yyy'}, {id:'567',name:'rrr'}];
   expect(actual.sort((a, b) => (a.id < b.id)? -1: 1)).toEqual(expected.sort((a, b) => (a.id < b.id)? -1: 1));
})

Disable Copy or Paste action for text box?

Try This

 $( "#email,#confirmEmail " ).on( "copy cut paste drop", function() {
                return false;
        });

PHP unable to load php_curl.dll extension

Insert to file httpd.conf

LoadFile "D:/DevKit/PHP7.1/libeay32.dll"
LoadFile "D:/DevKit/PHP7.1/libssh2.dll"
LoadFile "D:/DevKit/PHP7.1/ssleay32.dll"

Xcode 6.1 Missing required architecture X86_64 in file

I tried using all the above, nothing worked in my case.

I used the SumUp library which was causing this issue.

I fixed it by:

  1. Removing the -ObjC parameters (all of them); in previous SumUp libs they required to have the -ObjC populated with parameters to make it work, however the latest version (xc v4.0.1 at the time of my answer here), the docs says remove it.

That still didn't fix the issue, I was still seeing errors all over the place hence coming to this thread,... however, after playing around with the settings the following fixed it:

  1. Going into "Build Settings" for your project and then changing "Build Active Architectures Only" to "YES", cleaned, Rebuilt, no errors, Finally!...

I hope this helps for people using SumUP integration, it took the whole day to find out...

Cheers,

H

Increasing the Command Timeout for SQL command

Since it takes 2 mins to respond, you can increase the timeout to 3 mins by adding the below code

scGetruntotals.CommandTimeout = 180;

Note : the parameter value is in seconds.

How do I pass options to the Selenium Chrome driver using Python?

This is how I did it.

from selenium import webdriver

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--disable-extensions')

chrome = webdriver.Chrome(chrome_options=chrome_options)

How to force Hibernate to return dates as java.util.Date instead of Timestamp?

There are some classes in the Java platform libraries that do extend an instantiable class and add a value component. For example, java.sql.Timestamp extends java.util.Date and adds a nanoseconds field. The equals implementation for Timestamp does violate symmetry and can cause erratic behavior if Timestamp and Date objects are used in the same collection or are otherwise intermixed. The Timestamp class has a disclaimer cautioning programmers against mixing dates and timestamps. While you won’t get into trouble as long as you keep them separate, there’s nothing to prevent you from mixing them, and the resulting errors can be hard to debug. This behavior of the Timestamp class was a mistake and should not be emulated.

check out this link

http://blogs.sourceallies.com/2012/02/hibernate-date-vs-timestamp/

What is an index in SQL?

An index is an on-disk structure associated with a table or view that speeds retrieval of rows from the table or view. An index contains keys built from one or more columns in the table or view. These keys are stored in a structure (B-tree) that enables SQL Server to find the row or rows associated with the key values quickly and efficiently.

Indexes are automatically created when PRIMARY KEY and UNIQUE constraints are defined on table columns. For example, when you create a table with a UNIQUE constraint, Database Engine automatically creates a nonclustered index.

If you configure a PRIMARY KEY, Database Engine automatically creates a clustered index, unless a clustered index already exists. When you try to enforce a PRIMARY KEY constraint on an existing table and a clustered index already exists on that table, SQL Server enforces the primary key using a nonclustered index.

Please refer to this for more information about indexes (clustered and non clustered): https://docs.microsoft.com/en-us/sql/relational-databases/indexes/clustered-and-nonclustered-indexes-described?view=sql-server-ver15

Hope this helps!

How to upgrade Angular CLI project?

Remove :

npm uninstall -g angular-cli

Reinstall (with yarn)

# npm install --global yarn
yarn global add @angular/cli@latest
ng set --global packageManager=yarn  # This will help ng-cli to use yarn

Reinstall (with npm)

npm install --global @angular/cli@latest

Another way is to not use global install, and add /node_modules/.bin folder in the PATH, or use npm scripts. It will be softer to upgrade.

How to trigger Jenkins builds remotely and to pass parameters

curl -H "Jenkins-Crumb: <your_crumb_data>" -u "<username>:<password>" "http://<your_jenkins_url>?buildWithParameters?token=<your_remote_api_name>?<parameterA>=<val_parameter_A>&<parameterB>=<val_parameterB>"

You can change following parameters as you want:

<your_crumb_data>
<username>
<password>
<your_jenkins_url>
<your_remote_api_name>
<parameterA>
<parameterB>
<val_parameter_A>
<val_parameter_B>

Note: Placing double quotes may be critical. Pay attention, please.

Difference between Build Solution, Rebuild Solution, and Clean Solution in Visual Studio?

I have a a blank solution BuildRebuildClean and three class library Models,Repository,Notification.

I use Models and Repository in Notification class library.

Then:

  • Build solution Incremental build and compiles only the files that are changed. If an assembly has no changes, it won’t be re-built. Also, it will not delete any intermediate files. If Modify some code in Models library project, then BUILD solution. In the below screen shot, refer to the time stamp of DLL, EXE is updated in Models and Notification library.

enter image description here

  • Rebuild solution Deletes all compiled files and compiles all irrespective of changes, ignoring anything it’s done before. Right click on the solution name BuildRebuildClean. What it does is deletes all the assemblies, EXEs and referred files to compile again.

enter image description here

  • Clean Solution Deletes all compiled, intermediate files (i.e., EXEs and DLLs) from the bin/obj directory.

enter image description here

How do the post increment (i++) and pre increment (++i) operators work in Java?

I believe however if you combine all of your statements and run it in Java 8.1 you will get a different answer, at least that's what my experience says.

The code will work like this:

int a=5,i;

i=++a + ++a + a++;            /*a = 5;
                                i=++a + ++a + a++; =>
                                i=6 + 7 + 7; (a=8); i=20;*/

i=a++ + ++a + ++a;           /*a = 5;
                                i=a++ + ++a + ++a; =>
                                i=8 + 10 + 11; (a=11); i=29;*/

a=++a + ++a + a++;            /*a=5;
                                a=++a + ++a + a++; =>
                                a=12 + 13 + 13;  a=38;*/

System.out.println(a);        //output: 38
System.out.println(i);         //output: 29

CREATE FILE encountered operating system error 5(failed to retrieve text for this error. Reason: 15105)

Opening SSMS as Administrator and running as SQL Auth vs Windows Auth did not work.

What worked was to just change my filename to the same location where the LDF and MDF files are located.

alter database MyDB
add file ( name = N'FileStreamName', 
filename = N'D:\SQL Databases\FileStreamSpace' ) 
to filegroup DocumentFiles;

Invalid argument supplied for foreach()

What about defining an empty array as fallback if get_value() is empty?
I can't think of a shortest way.

$values = get_values() ?: [];

foreach ($values as $value){
  ...
}

OS X Bash, 'watch' command

With Homebrew installed:

brew install watch

Javascript Array inside Array - how can I call the child array name?

I would create an object like this:

var options = { 
    size: ["S", "M", "L", "XL", "XXL"],
    color: ["Red", "Blue", "Green", "White", "Black"]
};


alert(Object.keys(options));

To access the keys individualy:

for (var key in options) {
    alert(key);
}

P.S.: when you create a new array object do not use new Array use [] instead.

XMLHttpRequest blocked by CORS Policy

I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer

How is the default max Java heap size determined?

Java 8 takes more than 1/64th of your physical memory for your Xmssize (Minimum HeapSize) and less than 1/4th of your physical memory for your -Xmxsize (Maximum HeapSize).

You can check the default Java heap size by:

In Windows:

java -XX:+PrintFlagsFinal -version | findstr /i "HeapSize PermSize ThreadStackSize"

In Linux:

java -XX:+PrintFlagsFinal -version | grep -iE 'HeapSize|PermSize|ThreadStackSize'

What system configuration settings influence the default value?

The machine's physical memory & Java version.

Getting the screen resolution using PHP

You can try RESS (RESponsive design + Server side components), see this tutorial:

http://www.lukew.com/ff/entry.asp?1392

Remove the last three characters from a string

myString = myString.Remove(myString.Length - 3, 3);

How to get the previous url using PHP

But you could make an own link for every from url.

Example: http://example.com?auth=holasite

In this example your site is: example.com

If somebody open that link it's give you the holasite value for the auth variable.

Then just $_GET['auth'] and you have the variable. But you should have a database to store it, and to authorize.

Like: $holasite = http://holasite.com (You could use mysql too..)

And just match it, and you have the url.

This method is a little bit more complicated, but it works. This method is good for a referral system authentication. But where is the site name, you should write an id, and works with that id.

How to access my localhost from another PC in LAN?

Actualy you don't need an internet connection to use ip address. Each computer in LAN has an internal IP address you can discover by runing

ipconfig /all

in cmd.

You can use the ip address of the server (probabily something like 192.168.0.x or 10.0.0.x) to access the website remotely.

If you found the ip and still cannot access the website, it means WAMP is not configured to respond to that name ( what did you call me? 192.168.0.3? That's not my name. I'm Localhost ) and you have to modify ....../apache/config/httpd.conf

Listen *:80

Java - get the current class name?

Try using this this.getClass().getCanonicalName() or this.getClass().getSimpleName(). If it's an anonymous class, use this.getClass().getSuperclass().getName()

How do I create a right click context menu in Java Swing?

The following code implements a default context menu known from Windows with copy, cut, paste, select all, undo and redo functions. It also works on Linux and Mac OS X:

import javax.swing.*;
import javax.swing.text.JTextComponent;
import javax.swing.undo.UndoManager;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class DefaultContextMenu extends JPopupMenu
{
    private Clipboard clipboard;

    private UndoManager undoManager;

    private JMenuItem undo;
    private JMenuItem redo;
    private JMenuItem cut;
    private JMenuItem copy;
    private JMenuItem paste;
    private JMenuItem delete;
    private JMenuItem selectAll;

    private JTextComponent textComponent;

    public DefaultContextMenu()
    {
        undoManager = new UndoManager();
        clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

        addPopupMenuItems();
    }

    private void addPopupMenuItems()
    {
        undo = new JMenuItem("Undo");
        undo.setEnabled(false);
        undo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        undo.addActionListener(event -> undoManager.undo());
        add(undo);

        redo = new JMenuItem("Redo");
        redo.setEnabled(false);
        redo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        redo.addActionListener(event -> undoManager.redo());
        add(redo);

        add(new JSeparator());

        cut = new JMenuItem("Cut");
        cut.setEnabled(false);
        cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        cut.addActionListener(event -> textComponent.cut());
        add(cut);

        copy = new JMenuItem("Copy");
        copy.setEnabled(false);
        copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        copy.addActionListener(event -> textComponent.copy());
        add(copy);

        paste = new JMenuItem("Paste");
        paste.setEnabled(false);
        paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        paste.addActionListener(event -> textComponent.paste());
        add(paste);

        delete = new JMenuItem("Delete");
        delete.setEnabled(false);
        delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        delete.addActionListener(event -> textComponent.replaceSelection(""));
        add(delete);

        add(new JSeparator());

        selectAll = new JMenuItem("Select All");
        selectAll.setEnabled(false);
        selectAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        selectAll.addActionListener(event -> textComponent.selectAll());
        add(selectAll);
    }

    private void addTo(JTextComponent textComponent)
    {
        textComponent.addKeyListener(new KeyAdapter()
        {
            @Override
            public void keyPressed(KeyEvent pressedEvent)
            {
                if ((pressedEvent.getKeyCode() == KeyEvent.VK_Z)
                        && ((pressedEvent.getModifiersEx() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0))
                {
                    if (undoManager.canUndo())
                    {
                        undoManager.undo();
                    }
                }

                if ((pressedEvent.getKeyCode() == KeyEvent.VK_Y)
                        && ((pressedEvent.getModifiersEx() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0))
                {
                    if (undoManager.canRedo())
                    {
                        undoManager.redo();
                    }
                }
            }
        });

        textComponent.addMouseListener(new MouseAdapter()
        {
            @Override
            public void mousePressed(MouseEvent releasedEvent)
            {
                handleContextMenu(releasedEvent);
            }

            @Override
            public void mouseReleased(MouseEvent releasedEvent)
            {
                handleContextMenu(releasedEvent);
            }
        });

        textComponent.getDocument().addUndoableEditListener(event -> undoManager.addEdit(event.getEdit()));
    }

    private void handleContextMenu(MouseEvent releasedEvent)
    {
        if (releasedEvent.getButton() == MouseEvent.BUTTON3)
        {
            processClick(releasedEvent);
        }
    }

    private void processClick(MouseEvent event)
    {
        textComponent = (JTextComponent) event.getSource();
        textComponent.requestFocus();

        boolean enableUndo = undoManager.canUndo();
        boolean enableRedo = undoManager.canRedo();
        boolean enableCut = false;
        boolean enableCopy = false;
        boolean enablePaste = false;
        boolean enableDelete = false;
        boolean enableSelectAll = false;

        String selectedText = textComponent.getSelectedText();
        String text = textComponent.getText();

        if (text != null)
        {
            if (text.length() > 0)
            {
                enableSelectAll = true;
            }
        }

        if (selectedText != null)
        {
            if (selectedText.length() > 0)
            {
                enableCut = true;
                enableCopy = true;
                enableDelete = true;
            }
        }

        if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor) && textComponent.isEnabled())
        {
            enablePaste = true;
        }

        undo.setEnabled(enableUndo);
        redo.setEnabled(enableRedo);
        cut.setEnabled(enableCut);
        copy.setEnabled(enableCopy);
        paste.setEnabled(enablePaste);
        delete.setEnabled(enableDelete);
        selectAll.setEnabled(enableSelectAll);

        // Shows the popup menu
        show(textComponent, event.getX(), event.getY());
    }

    public static void addDefaultContextMenu(JTextComponent component)
    {
        DefaultContextMenu defaultContextMenu = new DefaultContextMenu();
        defaultContextMenu.addTo(component);
    }
}

Usage:

JTextArea textArea = new JTextArea();
DefaultContextMenu.addDefaultContextMenu(textArea);

Now the textArea will have a context menu when it is right-clicked on.

What is the difference between 'E', 'T', and '?' for Java generics?

Well there's no difference between the first two - they're just using different names for the type parameter (E or T).

The third isn't a valid declaration - ? is used as a wildcard which is used when providing a type argument, e.g. List<?> foo = ... means that foo refers to a list of some type, but we don't know what.

All of this is generics, which is a pretty huge topic. You may wish to learn about it through the following resources, although there are more available of course:

A field initializer cannot reference the nonstatic field, method, or property

You need to put that code into the constructor of your class:

private Reminders reminder = new Reminders();
private dynamic defaultReminder;

public YourClass()
{
    defaultReminder = reminder.TimeSpanText[TimeSpan.FromMinutes(15)];
}

The reason is that you can't use one instance variable to initialize another one using a field initializer.

How do you get a directory listing in C?

opendir/readdir are POSIX. If POSIX is not enough for the portability you want to achieve, check Apache Portable Runtime

How to create an on/off switch with Javascript/CSS?

You can achieve this using HTML and CSS and convert a checkbox into a HTML Switch.

HTML

      <div class="switch">
        <input id="cmn-toggle-1" class="cmn-toggle cmn-toggle-round"  type="checkbox">
        <label for="cmn-toggle-1"></label>
      </div>

CSS

input.cmn-toggle-round + label {
  padding: 2px;
  width: 100px;
  height: 30px;
  background-color: #dddddd;
  -webkit-border-radius: 30px;
  -moz-border-radius: 30px;
  -ms-border-radius: 30px;
  -o-border-radius: 30px;
  border-radius: 30px;
}
input.cmn-toggle-round + label:before, input.cmn-toggle-round + label:after {
  display: block;
  position: absolute;
  top: 1px;
  left: 1px;
  bottom: 1px;
  content: "";
}
input.cmn-toggle-round + label:before {
  right: 1px;
  background-color: #f1f1f1;
  -webkit-border-radius: 30px;
  -moz-border-radius: 30px;
  -ms-border-radius: 30px;
  -o-border-radius: 30px;
  border-radius: 30px;
  -webkit-transition: background 0.4s;
  -moz-transition: background 0.4s;
  -o-transition: background 0.4s;
  transition: background 0.4s;
}
input.cmn-toggle-round + label:after {
  width: 40px;
  background-color: #fff;
  -webkit-border-radius: 100%;
  -moz-border-radius: 100%;
  -ms-border-radius: 100%;
  -o-border-radius: 100%;
  border-radius: 100%;
  -webkit-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
  -moz-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
  -webkit-transition: margin 0.4s;
  -moz-transition: margin 0.4s;
  -o-transition: margin 0.4s;
  transition: margin 0.4s;
}
input.cmn-toggle-round:checked + label:before {
  background-color: #8ce196;
}
input.cmn-toggle-round:checked + label:after {
  margin-left: 60px;
}

.cmn-toggle {
  position: absolute;
  margin-left: -9999px;
  visibility: hidden;
}
.cmn-toggle + label {
  display: block;
  position: relative;
  cursor: pointer;
  outline: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

DEMO

Transposing a 2D-array in JavaScript

Neat and pure:

[[0, 1], [2, 3], [4, 5]].reduce((prev, next) => next.map((item, i) =>
    (prev[i] || []).concat(next[i])
), []); // [[0, 2, 4], [1, 3, 5]]

Previous solutions may lead to failure in case an empty array is provided.

Here it is as a function:

function transpose(array) {
    return array.reduce((prev, next) => next.map((item, i) =>
        (prev[i] || []).concat(next[i])
    ), []);
}

console.log(transpose([[0, 1], [2, 3], [4, 5]]));

Update. It can be written even better with spread operator:

const transpose = matrix => matrix.reduce(
    ($, row) => row.map((_, i) => [...($[i] || []), row[i]]), 
    []
)

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

Answer in short: (search your situation)

  • 1.compareTo(0) (return: 1)
  • 1.compareTo(1) (return: 0)
  • 0.comapreTo(1) (return: -1)

Are the decimal places in a CSS width respected?

Although fractional pixels may appear to round up on individual elements (as @SkillDrick demonstrates very well) it's important to know that the fractional pixels are actually respected in the actual box model.

This can best be seen when elements are stacked next to (or on top of) each other; in other words, if I were to place 400 0.5 pixel divs side by side, they would have the same width as a single 200 pixel div. If they all actually rounded up to 1px (as looking at individual elements would imply) we'd expect the 200px div to be half as long.

This can be seen in this runnable code snippet:

_x000D_
_x000D_
body {_x000D_
  color:            white;_x000D_
  font-family:      sans-serif;_x000D_
  font-weight:      bold;_x000D_
  background-color: #334;_x000D_
}_x000D_
_x000D_
.div_house div {_x000D_
  height:           10px;_x000D_
  background-color: orange;_x000D_
  display:          inline-block;_x000D_
}_x000D_
_x000D_
div#small_divs div {_x000D_
  width:            0.5px;_x000D_
}_x000D_
_x000D_
div#large_div div {_x000D_
  width:            200px;_x000D_
}
_x000D_
<div class="div_house" id="small_divs">_x000D_
  <p>0.5px div x 400</p>_x000D_
  <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>_x000D_
</div>_x000D_
<br>_x000D_
<div class="div_house" id="large_div">_x000D_
  <p>200px div x 1</p>_x000D_
  <div></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to get first and last day of week in Oracle?

I think this is just a simple select statement. I hope it works, because I couldn't test it at home, because I don't have a Oracle database here ;-)

select to_date('201118', 'YYYYWW'), to_date('201118', 'YYYYWW')+7 from dual;

You have to be carefully because there is a difference between WW and IW. Here is an article which explains the difference: http://rwijk.blogspot.com/2008/01/date-format-element-ww.html

How to query SOLR for empty fields?

One caveat! If you want to compose this via OR or AND you cannot use it in this form:

-myfield:*

but you must use

(*:* NOT myfield:*)

This form is perfectly composable. Apparently SOLR will expand the first form to the second, but only when it is a top node. Hope this saves you some time!

Error:(1, 0) Plugin with id 'com.android.application' not found

Make sure your two build.gradle and settings.gradle files are in the correct directories as stated in https://developer.android.com/studio/build/index.html

Then open "as existing project" in Visual Studio

Gradle is very finicky about this.

How can I run a program from a batch file without leaving the console open after the program starts?

Look at the START command, you can do this:

START rest-of-your-program-name

For instance, this batch-file will wait until notepad exits:

@echo off
notepad c:\test.txt

However, this won't:

@echo off
start notepad c:\test.txt

How to monitor network calls made from iOS Simulator

Personally, I use Charles for that kind of stuff.
When enabled, it will monitor every network request, displaying extended request details, including support for SSL and various request/reponse format, like JSON, etc...

You can also configure it to sniff only requests to specific servers, not the whole traffic.

It's commercial software, but there is a trial, and IMHO it's definitively a great tool.

Find the unique values in a column and then sort them

Came across the question myself today. I think the reason that your code returns 'None' (exactly what I got by using the same method) is that

a.sort()

is calling the sort function to mutate the list a. In my understanding, this is a modification command. To see the result you have to use print(a).

My solution, as I tried to keep everything in pandas:

pd.Series(df['A'].unique()).sort_values()

jquery-ui-dialog - How to hook into dialog close event

$( "#dialogueForm" ).dialog({
              autoOpen: false,
              height: "auto",
              width: "auto",
              modal: true,
                my: "center",
                at: "center",
                of: window,
              close : function(){
                  // functionality goes here
              }  
              });

"close" property of dialog gives the close event for the same.

Is there a better way to refresh WebView?

The best solution is to just do webView.loadUrl( "javascript:window.location.reload( true )" );. This should work on all versions and doesn't introduce new history entries.

What is the correct way to restore a deleted file from SVN?

I always seem to use svn copy as a server operation so not sure if it works with two working paths.

Here is an example of restoring a deleted file into a local working copy of the project:

svn copy https://repos/project/modules/module.js@3502 modules/module.js

While being inside the project directory. This works as well for restoring entire directories.

How can you use optional parameters in C#?

I had to do this in a VB.Net 2.0 Web Service. I ended up specifying the parameters as strings, then converting them to whatever I needed. An optional parameter was specified with an empty string. Not the cleanest solution, but it worked. Just be careful that you catch all the exceptions that can occur.

How to load a text file into a Hive table stored as sequence files

You cannot directly create a table stored as a sequence file and insert text into it. You must do this:

  1. Create a table stored as text
  2. Insert the text file into the text table
  3. Do a CTAS to create the table stored as a sequence file.
  4. Drop the text table if desired

Example:

CREATE TABLE test_txt(field1 int, field2 string)
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t';

LOAD DATA INPATH '/path/to/file.tsv' INTO TABLE test_txt;

CREATE TABLE test STORED AS SEQUENCEFILE
AS SELECT * FROM test_txt;

DROP TABLE test_txt;

error::make_unique is not a member of ‘std’

1.gcc version >= 5
2.CXXFLAGS += -std=c++14
3. #include <memory>

How can I put a ListView into a ScrollView without it collapsing?

All these answers are wrong!!! If you are trying to put a listview in a scroll view you should re-think your design. You are trying to put a ScrollView in a ScrollView. Interfering with the list will hurt list performance. It was designed to be like this by Android.

If you really want the list to be in the same scroll as the other elements, all you have to do is add the other items into the top of the list using a simple switch statement in your adapter:

class MyAdapter extends ArrayAdapter{

    public MyAdapter(Context context, int resource, List objects) {
        super(context, resource, objects);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
         ViewItem viewType = getItem(position);

        switch(viewType.type){
            case TEXTVIEW:
                convertView = layouteInflater.inflate(R.layout.textView1, parent, false);

                break;
            case LISTITEM:
                convertView = layouteInflater.inflate(R.layout.listItem, parent, false);

                break;            }


        return convertView;
    }


}

The list adapter can handle everything since it only renders what is visible.

Difference between $(window).load() and $(document).ready() functions

document.ready (jQuery) document.ready will execute right after the HTML document is loaded property, and the DOM is ready.

DOM: The Document Object Model (DOM) is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents.

$(document).ready(function()
{
   // executes when HTML-Document is loaded and DOM is ready
   alert("(document).ready was called - document is ready!");
});

window.load (Built-in JavaScript) The window.load however will wait for the page to be fully loaded, this includes inner frames, images etc. * window.load is a built-in JavaScript method, it is known to have some quirks in old browsers (IE6, IE8, old FF and Opera versions) but will generally work in all of them.

window.load can be used in the body's onload event like this (but I would strongly suggest you avoid mixing code like this in the HTML, as it is a source for confusion later on):

$(window).load(function() 
{
   // executes when complete page is fully loaded, including all frames, objects and images
   alert("(window).load was called - window is loaded!");
});

Efficient Algorithm for Bit Reversal (from MSB->LSB to LSB->MSB) in C

NOTE: All algorithms below are in C, but should be portable to your language of choice (just don't look at me when they're not as fast :)

Options

Low Memory (32-bit int, 32-bit machine)(from here):

unsigned int
reverse(register unsigned int x)
{
    x = (((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1));
    x = (((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2));
    x = (((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4));
    x = (((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8));
    return((x >> 16) | (x << 16));

}

From the famous Bit Twiddling Hacks page:

Fastest (lookup table):

static const unsigned char BitReverseTable256[] = 
{
  0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0, 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0, 
  0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8, 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8, 
  0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4, 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4, 
  0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC, 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC, 
  0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2, 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2, 
  0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA, 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6, 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6, 
  0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE, 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1, 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9, 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9, 
  0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5, 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED, 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3, 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3, 
  0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB, 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7, 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7, 
  0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF, 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
};

unsigned int v; // reverse 32-bit value, 8 bits at time
unsigned int c; // c will get v reversed

// Option 1:
c = (BitReverseTable256[v & 0xff] << 24) | 
    (BitReverseTable256[(v >> 8) & 0xff] << 16) | 
    (BitReverseTable256[(v >> 16) & 0xff] << 8) |
    (BitReverseTable256[(v >> 24) & 0xff]);

// Option 2:
unsigned char * p = (unsigned char *) &v;
unsigned char * q = (unsigned char *) &c;
q[3] = BitReverseTable256[p[0]]; 
q[2] = BitReverseTable256[p[1]]; 
q[1] = BitReverseTable256[p[2]]; 
q[0] = BitReverseTable256[p[3]];

You can extend this idea to 64-bit ints, or trade off memory for speed (assuming your L1 Data Cache is large enough), and reverse 16 bits at a time with a 64K-entry lookup table.


Others

Simple

unsigned int v;     // input bits to be reversed
unsigned int r = v & 1; // r will be reversed bits of v; first get LSB of v
int s = sizeof(v) * CHAR_BIT - 1; // extra shift needed at end

for (v >>= 1; v; v >>= 1)
{   
  r <<= 1;
  r |= v & 1;
  s--;
}
r <<= s; // shift when v's highest bits are zero

Faster (32-bit processor)

unsigned char b = x;
b = ((b * 0x0802LU & 0x22110LU) | (b * 0x8020LU & 0x88440LU)) * 0x10101LU >> 16; 

Faster (64-bit processor)

unsigned char b; // reverse this (8-bit) byte
b = (b * 0x0202020202ULL & 0x010884422010ULL) % 1023;

If you want to do this on a 32-bit int, just reverse the bits in each byte, and reverse the order of the bytes. That is:

unsigned int toReverse;
unsigned int reversed;
unsigned char inByte0 = (toReverse & 0xFF);
unsigned char inByte1 = (toReverse & 0xFF00) >> 8;
unsigned char inByte2 = (toReverse & 0xFF0000) >> 16;
unsigned char inByte3 = (toReverse & 0xFF000000) >> 24;
reversed = (reverseBits(inByte0) << 24) | (reverseBits(inByte1) << 16) | (reverseBits(inByte2) << 8) | (reverseBits(inByte3);

Results

I benchmarked the two most promising solutions, the lookup table, and bitwise-AND (the first one). The test machine is a laptop w/ 4GB of DDR2-800 and a Core 2 Duo T7500 @ 2.4GHz, 4MB L2 Cache; YMMV. I used gcc 4.3.2 on 64-bit Linux. OpenMP (and the GCC bindings) were used for high-resolution timers.

reverse.c

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

unsigned int
reverse(register unsigned int x)
{
    x = (((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1));
    x = (((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2));
    x = (((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4));
    x = (((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8));
    return((x >> 16) | (x << 16));

}

int main()
{
    unsigned int *ints = malloc(100000000*sizeof(unsigned int));
    unsigned int *ints2 = malloc(100000000*sizeof(unsigned int));
    for(unsigned int i = 0; i < 100000000; i++)
      ints[i] = rand();

    unsigned int *inptr = ints;
    unsigned int *outptr = ints2;
    unsigned int *endptr = ints + 100000000;
    // Starting the time measurement
    double start = omp_get_wtime();
    // Computations to be measured
    while(inptr != endptr)
    {
      (*outptr) = reverse(*inptr);
      inptr++;
      outptr++;
    }
    // Measuring the elapsed time
    double end = omp_get_wtime();
    // Time calculation (in seconds)
    printf("Time: %f seconds\n", end-start);

    free(ints);
    free(ints2);

    return 0;
}

reverse_lookup.c

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

static const unsigned char BitReverseTable256[] = 
{
  0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0, 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0, 
  0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8, 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8, 
  0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4, 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4, 
  0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC, 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC, 
  0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2, 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2, 
  0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA, 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6, 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6, 
  0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE, 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1, 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9, 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9, 
  0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5, 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED, 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3, 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3, 
  0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB, 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7, 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7, 
  0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF, 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
};

int main()
{
    unsigned int *ints = malloc(100000000*sizeof(unsigned int));
    unsigned int *ints2 = malloc(100000000*sizeof(unsigned int));
    for(unsigned int i = 0; i < 100000000; i++)
      ints[i] = rand();

    unsigned int *inptr = ints;
    unsigned int *outptr = ints2;
    unsigned int *endptr = ints + 100000000;
    // Starting the time measurement
    double start = omp_get_wtime();
    // Computations to be measured
    while(inptr != endptr)
    {
    unsigned int in = *inptr;  

    // Option 1:
    //*outptr = (BitReverseTable256[in & 0xff] << 24) | 
    //    (BitReverseTable256[(in >> 8) & 0xff] << 16) | 
    //    (BitReverseTable256[(in >> 16) & 0xff] << 8) |
    //    (BitReverseTable256[(in >> 24) & 0xff]);

    // Option 2:
    unsigned char * p = (unsigned char *) &(*inptr);
    unsigned char * q = (unsigned char *) &(*outptr);
    q[3] = BitReverseTable256[p[0]]; 
    q[2] = BitReverseTable256[p[1]]; 
    q[1] = BitReverseTable256[p[2]]; 
    q[0] = BitReverseTable256[p[3]];

      inptr++;
      outptr++;
    }
    // Measuring the elapsed time
    double end = omp_get_wtime();
    // Time calculation (in seconds)
    printf("Time: %f seconds\n", end-start);

    free(ints);
    free(ints2);

    return 0;
}

I tried both approaches at several different optimizations, ran 3 trials at each level, and each trial reversed 100 million random unsigned ints. For the lookup table option, I tried both schemes (options 1 and 2) given on the bitwise hacks page. Results are shown below.

Bitwise AND

mrj10@mjlap:~/code$ gcc -fopenmp -std=c99 -o reverse reverse.c
mrj10@mjlap:~/code$ ./reverse
Time: 2.000593 seconds
mrj10@mjlap:~/code$ ./reverse
Time: 1.938893 seconds
mrj10@mjlap:~/code$ ./reverse
Time: 1.936365 seconds
mrj10@mjlap:~/code$ gcc -fopenmp -std=c99 -O2 -o reverse reverse.c
mrj10@mjlap:~/code$ ./reverse
Time: 0.942709 seconds
mrj10@mjlap:~/code$ ./reverse
Time: 0.991104 seconds
mrj10@mjlap:~/code$ ./reverse
Time: 0.947203 seconds
mrj10@mjlap:~/code$ gcc -fopenmp -std=c99 -O3 -o reverse reverse.c
mrj10@mjlap:~/code$ ./reverse
Time: 0.922639 seconds
mrj10@mjlap:~/code$ ./reverse
Time: 0.892372 seconds
mrj10@mjlap:~/code$ ./reverse
Time: 0.891688 seconds

Lookup Table (option 1)

mrj10@mjlap:~/code$ gcc -fopenmp -std=c99 -o reverse_lookup reverse_lookup.c
mrj10@mjlap:~/code$ ./reverse_lookup
Time: 1.201127 seconds              
mrj10@mjlap:~/code$ ./reverse_lookup
Time: 1.196129 seconds              
mrj10@mjlap:~/code$ ./reverse_lookup
Time: 1.235972 seconds              
mrj10@mjlap:~/code$ gcc -fopenmp -std=c99 -O2 -o reverse_lookup reverse_lookup.c
mrj10@mjlap:~/code$ ./reverse_lookup
Time: 0.633042 seconds              
mrj10@mjlap:~/code$ ./reverse_lookup
Time: 0.655880 seconds              
mrj10@mjlap:~/code$ ./reverse_lookup
Time: 0.633390 seconds              
mrj10@mjlap:~/code$ gcc -fopenmp -std=c99 -O3 -o reverse_lookup reverse_lookup.c
mrj10@mjlap:~/code$ ./reverse_lookup
Time: 0.652322 seconds              
mrj10@mjlap:~/code$ ./reverse_lookup
Time: 0.631739 seconds              
mrj10@mjlap:~/code$ ./reverse_lookup
Time: 0.652431 seconds  

Lookup Table (option 2)

mrj10@mjlap:~/code$ gcc -fopenmp -std=c99 -o reverse_lookup reverse_lookup.c
mrj10@mjlap:~/code$ ./reverse_lookup
Time: 1.671537 seconds
mrj10@mjlap:~/code$ ./reverse_lookup
Time: 1.688173 seconds
mrj10@mjlap:~/code$ ./reverse_lookup
Time: 1.664662 seconds
mrj10@mjlap:~/code$ gcc -fopenmp -std=c99 -O2 -o reverse_lookup reverse_lookup.c
mrj10@mjlap:~/code$ ./reverse_lookup
Time: 1.049851 seconds
mrj10@mjlap:~/code$ ./reverse_lookup
Time: 1.048403 seconds
mrj10@mjlap:~/code$ ./reverse_lookup
Time: 1.085086 seconds
mrj10@mjlap:~/code$ gcc -fopenmp -std=c99 -O3 -o reverse_lookup reverse_lookup.c
mrj10@mjlap:~/code$ ./reverse_lookup
Time: 1.082223 seconds
mrj10@mjlap:~/code$ ./reverse_lookup
Time: 1.053431 seconds
mrj10@mjlap:~/code$ ./reverse_lookup
Time: 1.081224 seconds

Conclusion

Use the lookup table, with option 1 (byte addressing is unsurprisingly slow) if you're concerned about performance. If you need to squeeze every last byte of memory out of your system (and you might, if you care about the performance of bit reversal), the optimized versions of the bitwise-AND approach aren't too shabby either.

Caveat

Yes, I know the benchmark code is a complete hack. Suggestions on how to improve it are more than welcome. Things I know about:

  • I don't have access to ICC. This may be faster (please respond in a comment if you can test this out).
  • A 64K lookup table may do well on some modern microarchitectures with large L1D.
  • -mtune=native didn't work for -O2/-O3 (ld blew up with some crazy symbol redefinition error), so I don't believe the generated code is tuned for my microarchitecture.
  • There may be a way to do this slightly faster with SSE. I have no idea how, but with fast replication, packed bitwise AND, and swizzling instructions, there's got to be something there.
  • I know only enough x86 assembly to be dangerous; here's the code GCC generated on -O3 for option 1, so somebody more knowledgable than myself can check it out:

32-bit

.L3:
movl    (%r12,%rsi), %ecx
movzbl  %cl, %eax
movzbl  BitReverseTable256(%rax), %edx
movl    %ecx, %eax
shrl    $24, %eax
mov     %eax, %eax
movzbl  BitReverseTable256(%rax), %eax
sall    $24, %edx
orl     %eax, %edx
movzbl  %ch, %eax
shrl    $16, %ecx
movzbl  BitReverseTable256(%rax), %eax
movzbl  %cl, %ecx
sall    $16, %eax
orl     %eax, %edx
movzbl  BitReverseTable256(%rcx), %eax
sall    $8, %eax
orl     %eax, %edx
movl    %edx, (%r13,%rsi)
addq    $4, %rsi
cmpq    $400000000, %rsi
jne     .L3

EDIT: I also tried using uint64_t types on my machine to see if there was any performance boost. Performance was about 10% faster than 32-bit, and was nearly identical whether you were just using 64-bit types to reverse bits on two 32-bit int types at a time, or whether you were actually reversing bits in half as many 64-bit values. The assembly code is shown below (for the former case, reversing bits for two 32-bit int types at a time):

.L3:
movq    (%r12,%rsi), %rdx
movq    %rdx, %rax
shrq    $24, %rax
andl    $255, %eax
movzbl  BitReverseTable256(%rax), %ecx
movzbq  %dl,%rax
movzbl  BitReverseTable256(%rax), %eax
salq    $24, %rax
orq     %rax, %rcx
movq    %rdx, %rax
shrq    $56, %rax
movzbl  BitReverseTable256(%rax), %eax
salq    $32, %rax
orq     %rax, %rcx
movzbl  %dh, %eax
shrq    $16, %rdx
movzbl  BitReverseTable256(%rax), %eax
salq    $16, %rax
orq     %rax, %rcx
movzbq  %dl,%rax
shrq    $16, %rdx
movzbl  BitReverseTable256(%rax), %eax
salq    $8, %rax
orq     %rax, %rcx
movzbq  %dl,%rax
shrq    $8, %rdx
movzbl  BitReverseTable256(%rax), %eax
salq    $56, %rax
orq     %rax, %rcx
movzbq  %dl,%rax
shrq    $8, %rdx
movzbl  BitReverseTable256(%rax), %eax
andl    $255, %edx
salq    $48, %rax
orq     %rax, %rcx
movzbl  BitReverseTable256(%rdx), %eax
salq    $40, %rax
orq     %rax, %rcx
movq    %rcx, (%r13,%rsi)
addq    $8, %rsi
cmpq    $400000000, %rsi
jne     .L3

Use nginx to serve static files from subdirectories of a given directory

It should work, however http://nginx.org/en/docs/http/ngx_http_core_module.html#alias says:

When location matches the last part of the directive’s value: it is better to use the root directive instead:

which would yield:

server {
  listen        8080;
  server_name   www.mysite.com mysite.com;
  error_log     /home/www-data/logs/nginx_www.error.log;
  error_page    404    /404.html;

  location /public/doc/ {
    autoindex on;
    root  /home/www-data/mysite;
  } 

  location = /404.html {
    root /home/www-data/mysite/static/html;
  }       
}

Read JSON data in a shell script

There is jq for parsing json on the command line:

 jq '.Body'

Visit this for jq: https://stedolan.github.io/jq/

How to validate GUID is a GUID

When I'm just testing a string to see if it is a GUID, I don't really want to create a Guid object that I don't need. So...

public static class GuidEx
{
    public static bool IsGuid(string value)
    {
        Guid x;
        return Guid.TryParse(value, out x);
    }
}

And here's how you use it:

string testMe = "not a guid";
if (GuidEx.IsGuid(testMe))
{
...
}

Select an Option from the Right-Click Menu in Selenium Webdriver - Java

You might have to move the mouse to any particular location after context click() like this -

Actions action = new Actions(driver);
actions.contextClick(link).moveByOffset(x,y).click().build().perform();

To understand how moveByOffset(x,y) works look here;

I hope this works. You will have to calculate the offset values for x and y;

best way would be to find the size of each option button after right clicking and then if you click on the 2nd option .

x = width of option button/2

y = 2*(size of each option button)

What is the best way to update the entity in JPA

It depends on number of entities which are going to be updated, if you have large number of entities using JPA Query Update statement is better as you dont have to load all the entities from database, if you are going to update just one entity then using find and update is fine.

How to force a checkbox and text on the same line?

Try this. The following considers checkbox and label as a unique element:

<style>
  .item {white-space: nowrap;display:inline  }
</style>
<fieldset>
<div class="item">
    <input type="checkbox" id="a">
    <label for="a">aaaaaaaaaaaa aaaa a a a a a a aaaaaaaaaaaaa</label>
</div>
<div class="item">
   <input type="checkbox" id="b">
<!-- depending on width, a linebreak NEVER occurs here. -->
    <label for="b">bbbbbbbbbbbb bbbbbbbbbbbbbbbbb  b b b b  bb</label>
</div>
<div class="item">
    <input type="checkbox" id="c">
    <label for="c">ccccc c c c c ccccccccccccccc  cccc</label>
</div>
</fieldset>

How do I add options to a DropDownList using jQuery?

Add item to list in the begining

$("#ddlList").prepend('<option selected="selected" value="0"> Select </option>');

Add item to list in the end

$('<option value="6">Java Script</option>').appendTo("#ddlList");

Common Dropdown operation (Get, Set, Add, Remove) using jQuery

In Angular, how do you determine the active route?

Below is the method using RouteData to style menuBar items depending of the current route:

RouteConfig includes data with tab (current route):

@RouteConfig([
  {
    path: '/home',    name: 'Home',    component: HomeComponent,
    data: {activeTab: 'home'},  useAsDefault: true
  }, {
    path: '/jobs',    name: 'Jobs',    data: {activeTab: 'jobs'},
    component: JobsComponent
  }
])

A piece of layout:

  <li role="presentation" [ngClass]="{active: isActive('home')}">
    <a [routerLink]="['Home']">Home</a>
  </li>
  <li role="presentation" [ngClass]="{active: isActive('jobs')}">
    <a [routerLink]="['Jobs']">Jobs</a>
  </li>

Class:

export class MainMenuComponent {
  router: Router;

  constructor(data: Router) {
    this.router = data;
  }

  isActive(tab): boolean {
    if (this.router.currentInstruction && this.router.currentInstruction.component.routeData) {
      return tab == this.router.currentInstruction.component.routeData.data['activeTab'];
    }
    return false;
  }
}

How to make Sonar ignore some classes for codeCoverage metric?

Sometimes, Clover is configured to provide code coverage reports for all non-test code. If you wish to override these preferences, you may use configuration elements to exclude and include source files from being instrumented:

<plugin>
    <groupId>com.atlassian.maven.plugins</groupId>
    <artifactId>maven-clover2-plugin</artifactId>
    <version>${clover-version}</version>
    <configuration> 
        <excludes> 
            <exclude>**/*Dull.java</exclude> 
        </excludes> 
    </configuration>
</plugin>

Also, you can include the following Sonar configuration:

<properties>
    <sonar.exclusions>
        **/domain/*.java,
        **/transfer/*.java
    </sonar.exclusions>
</properties> 

Grep and Python

  1. use sys.argv to get the command-line parameters
  2. use open(), read() to manipulate file
  3. use the Python re module to match lines

how to bold words within a paragraph in HTML/CSS?

<p><b> BOLD TEXT </b> not in bold </p>;

Include the text you want to be in bold between <b>...</b>

How do I change tab size in Vim?

As a one-liner into vim:

:set tabstop=4 shiftwidth=4

For permanent setup, add these lines to ~/.vimrc:

set tabstop=4
set shiftwidth=4

NOTE: Add set expandtab if you prefer 4-spaces indentation, instead of a tab indentation.

CSS Custom Dropdown Select that works across all browsers IE7+ FF Webkit

This is very simple, you just need to add a background image to the select element and position it where you need to, but don't forget to add:

-webkit-appearance: none;
-moz-appearance: none;
appearance: none;

According to http://shouldiprefix.com/#appearance

Microsoft Edge and IE mobile support this property with the -webkit- prefix rather than -ms- for interop reasons.

I just made this fiddle http://jsfiddle.net/drjorgepolanco/uxxvayqe/

In Android EditText, how to force writing uppercase?

You can used two way.

First Way:

Set android:inputType="textCapSentences" on your EditText.

Second Way:

When user enter the number you have to used text watcher and change small to capital letter.

edittext.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {            

    }
        @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                    int arg3) {             
    }
    @Override
    public void afterTextChanged(Editable et) {
          String s=et.toString();
      if(!s.equals(s.toUpperCase()))
      {
         s=s.toUpperCase();
         edittext.setText(s);
         edittext.setSelection(edittext.length()); //fix reverse texting
      }
    }
});  

Count specific character occurrences in a string

I use the following function. It is not the most memory efficient but it is very simple to understand, supports multiple compare methods, is only 4 lines, is fast, mostly works in VBA too, will find not just individual characters but any search string (I often search for VbCrLf (s)).

Only thing missing is the ability to start search from a different "Start"

    Function inStC(myInput As String, Search As String, Optional myCompareMethod As Long = CompareMethod.Text) As Long
        If InStr(1, myInput, Search, myCompareMethod) = 0 Then Return 0
        Return UBound(Split(myInput, Search,, myCompareMethod))
    End Function

One thing I like is that it is compact to use example.

str="the little red hen"
count=inStC(str,"e") 'count should equal 4
count=inStC(str,"t") 'count should equal 3

While I am here, I would like to shill my inStB function, which, instead of returning a count of a string, it will simply return a boolean if the search string is present. I need this function often and this makes my code cleaner.

Function inStB(myInput As String, Search As String, Optional Start As Long = 1, Optional myCompareMethod As Long = CompareMethod.Text) As Boolean
    If InStr(Start, myInput, Search, myCompareMethod) > 0 Then Return True
    Return False
End Function

psql: FATAL: database "<user>" does not exist

had the problem with using the JDBC driver, so one just has to add the database (maybe redundantly depending on the tool you may use) after the host name in the URL, e.g. jdbc:postgres://<host(:port)>/<db-name>

further details are documented here: http://www.postgresql.org/docs/7.4/static/jdbc-use.html#JDBC-CONNECT

Return string Input with parse.string

You don't need to parse the string, it's defined as a string already.

Just do:

    private static String getStringInput (String prompt) {
     String input = EZJ.getUserInput(prompt);
     return input;
    }

Cannot read property 'addEventListener' of null

Thanks to @Rob M. for his help. This is what the final block of code looked like:

function swapper() {
  toggleClass(document.getElementById('overlay'), 'open');
}

var el = document.getElementById('overlayBtn');
if (el){
  el.addEventListener('click', swapper, false);

  var text = document.getElementById('overlayBtn');
  text.onclick = function(){
    this.innerHTML = (this.innerHTML === "Menu") ? "Close" : "Menu";
    return false;
  };
}

How can I perform a str_replace in JavaScript, replacing text in JavaScript?

You would use the replace method:

text = text.replace('old', 'new');

The first argument is what you're looking for, obviously. It can also accept regular expressions.

Just remember that it does not change the original string. It only returns the new value.

Concatenate two string literals

The difference between a string (or to be precise, std::string) and a character literal is that for the latter there is no + operator defined. This is why the second example fails.

In the first case, the compiler can find a suitable operator+ with the first argument being a string and the second a character literal (const char*) so it used that. The result of that operation is again a string, so it repeats the same trick when adding "!" to it.

T-SQL Cast versus Convert

To expand on the above answercopied by Shakti, I have actually been able to measure a performance difference between the two functions.

I was testing performance of variations of the solution to this question and found that the standard deviation and maximum runtimes were larger when using CAST.

Runtimes in milliseconds *Times in milliseconds, rounded to nearest 1/300th of a second as per the precision of the DateTime type

TortoiseGit-git did not exit cleanly (exit code 1)

Following this guide I had the same issue. To expand on Eric Moore's ridiculously vague answer,

Right click > TortoiseGit > Settings > Network

Down the bottom in the "SSH" section, hit Browse and find your TortoiseGit\bin\TortoisePlink.exe file. In my case the path was under Programs as opposed to Program Files

How to find a whole word in a String in java

You can use regular expressions. Use Matcher and Pattern methods to get the desired output

500 internal server error, how to debug

Try writing all the errors to a file.

error_reporting(-1); // reports all errors
ini_set("display_errors", "1"); // shows all errors
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");

Something like that.

C++ style cast from unsigned char * to const char *

char * and const unsigned char * are considered unrelated types. So you want to use reinterpret_cast.

But if you were going from const unsigned char* to a non const type you'd need to use const_cast first. reinterpret_cast cannot cast away a const or volatile qualification.

HTTP Range header

It's a syntactically valid request, but not a satisfiable request. If you look further in that section you see:

If a syntactically valid byte-range-set includes at least one byte- range-spec whose first-byte-pos is less than the current length of the entity-body, or at least one suffix-byte-range-spec with a non- zero suffix-length, then the byte-range-set is satisfiable. Otherwise, the byte-range-set is unsatisfiable. If the byte-range-set is unsatisfiable, the server SHOULD return a response with a status of 416 (Requested range not satisfiable). Otherwise, the server SHOULD return a response with a status of 206 (Partial Content) containing the satisfiable ranges of the entity-body.

So I think in your example, the server should return a 416 since it's not a valid byte range for that file.

Round number to nearest integer

Isn't just Python doing round half to even, as prescribed by IEEE 754?

Be careful redefining, or using "non-standard" rounding…

(See also https://stackoverflow.com/a/33019948/109839)

Copy file or directories recursively in Python

The python shutil.copytree method its a mess. I've done one that works correctly:

def copydirectorykut(src, dst):
    os.chdir(dst)
    list=os.listdir(src)
    nom= src+'.txt'
    fitx= open(nom, 'w')

    for item in list:
        fitx.write("%s\n" % item)
    fitx.close()

    f = open(nom,'r')
    for line in f.readlines():
        if "." in line:
            shutil.copy(src+'/'+line[:-1],dst+'/'+line[:-1])
        else:
            if not os.path.exists(dst+'/'+line[:-1]):
                os.makedirs(dst+'/'+line[:-1])
                copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
            copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
    f.close()
    os.remove(nom)
    os.chdir('..')

CSS file not refreshing in browser

I always use Ctrl+Shift+F5 out of habit, it should force a full-refresh including by-passing any http proxies you may be going through.

Check if a string has a certain piece of text

Here you go: ES5

var test = 'Hello World';
if( test.indexOf('World') >= 0){
  // Found world
}

With ES6 best way would be to use includes function to test if the string contains the looking work.

const test = 'Hello World';
if (test.includes('World')) { 
  // Found world
}

ES6 Class Multiple inheritance

use extent with custom function to handle multiple inheritance with es6

_x000D_
_x000D_
var aggregation = (baseClass, ...mixins) => {_x000D_
    let base = class _Combined extends baseClass {_x000D_
        constructor (...args) {_x000D_
            super(...args)_x000D_
            mixins.forEach((mixin) => {_x000D_
                mixin.prototype.initializer.call(this)_x000D_
            })_x000D_
        }_x000D_
    }_x000D_
    let copyProps = (target, source) => {_x000D_
        Object.getOwnPropertyNames(source)_x000D_
            .concat(Object.getOwnPropertySymbols(source))_x000D_
            .forEach((prop) => {_x000D_
            if (prop.match(/^(?:constructor|prototype|arguments|caller|name|bind|call|apply|toString|length)$/))_x000D_
                return_x000D_
            Object.defineProperty(target, prop, Object.getOwnPropertyDescriptor(source, prop))_x000D_
        })_x000D_
    }_x000D_
    mixins.forEach((mixin) => {_x000D_
        copyProps(base.prototype, mixin.prototype)_x000D_
        copyProps(base, mixin)_x000D_
    })_x000D_
    return base_x000D_
}_x000D_
_x000D_
class Colored {_x000D_
    initializer ()     { this._color = "white" }_x000D_
    get color ()       { return this._color }_x000D_
    set color (v)      { this._color = v }_x000D_
}_x000D_
_x000D_
class ZCoord {_x000D_
    initializer ()     { this._z = 0 }_x000D_
    get z ()           { return this._z }_x000D_
    set z (v)          { this._z = v }_x000D_
}_x000D_
_x000D_
class Shape {_x000D_
    constructor (x, y) { this._x = x; this._y = y }_x000D_
    get x ()           { return this._x }_x000D_
    set x (v)          { this._x = v }_x000D_
    get y ()           { return this._y }_x000D_
    set y (v)          { this._y = v }_x000D_
}_x000D_
_x000D_
class Rectangle extends aggregation(Shape, Colored, ZCoord) {}_x000D_
_x000D_
var rect = new Rectangle(7, 42)_x000D_
rect.z     = 1000_x000D_
rect.color = "red"_x000D_
console.log(rect.x, rect.y, rect.z, rect.color)
_x000D_
_x000D_
_x000D_

How to cast DATETIME as a DATE in mysql?

Use DATE() function:

select * from follow_queue group by DATE(follow_date)

Should I put input elements inside a label element?

I prefer

<label>
  Firstname
  <input name="firstname" />
</label>

<label>
  Lastname
  <input name="lastname" />
</label>

over

<label for="firstname">Firstname</label>
<input name="firstname" id="firstname" />

<label for="lastname">Lastname</label>
<input name="lastname" id="lastname" />

Mainly because it makes the HTML more readable. And I actually think my first example is easier to style with CSS, as CSS works very well with nested elements.

But it's a matter of taste I suppose.


If you need more styling options, add a span tag.

<label>
  <span>Firstname</span>
  <input name="firstname" />
</label>

<label>
  <span>Lastname</span>
  <input name="lastname" />
</label>

Code still looks better in my opinion.

How to find rows that have a value that contains a lowercase letter

for search all rows in lowercase

SELECT *
FROM Test
WHERE col1 
LIKE '%[abcdefghijklmnopqrstuvwxyz]%'
collate Latin1_General_CS_AS

Thanks Manesh Joseph

A hex viewer / editor plugin for Notepad++?

Is a completely different (but still free) application an option? I use HxD, and it serves me better than the Notepad++ plugin. It can calculate hashes, open memory of a process, it is fast at opening files of any size, and it works exceptionally well with the clipboard.

I used to use the Notepad++ plugin, but not anymore.

Auto select file in Solution Explorer from its open tab

In Visual Studio 2012, the same can be done using the "Sync With Active Document" option in Solution Explorer

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

I had the same issue, I could solve it by switching fom JDK 11 to JDK 8.

How to "flatten" a multi-dimensional array to simple one in PHP?

Simple approach..See it via recursion..

<?php

function flatten_array($simple){
static $outputs=array();
foreach ( $simple as $value)
{
if(is_array($value)){
    flatten_array($value);
}
else{
    $outputs[]=$value;
}

}
return $outputs;
}

$eg=['s'=>['p','n'=>['t']]];
$out=flatten_array($eg);
print_r($out);

?>

Installing OpenCV 2.4.3 in Visual C++ 2010 Express

1. Installing OpenCV 2.4.3

First, get OpenCV 2.4.3 from sourceforge.net. Its a self-extracting so just double click to start the installation. Install it in a directory, say C:\.

OpenCV self-extractor

Wait until all files get extracted. It will create a new directory C:\opencv which contains OpenCV header files, libraries, code samples, etc.

Now you need to add the directory C:\opencv\build\x86\vc10\bin to your system PATH. This directory contains OpenCV DLLs required for running your code.

Open Control PanelSystemAdvanced system settingsAdvanced Tab → Environment variables...

enter image description here

On the System Variables section, select Path (1), Edit (2), and type C:\opencv\build\x86\vc10\bin; (3), then click Ok.

On some computers, you may need to restart your computer for the system to recognize the environment path variables.

This will completes the OpenCV 2.4.3 installation on your computer.


2. Create a new project and set up Visual C++

Open Visual C++ and select FileNewProject...Visual C++Empty Project. Give a name for your project (e.g: cvtest) and set the project location (e.g: c:\projects).

New project dialog

Click Ok. Visual C++ will create an empty project.

VC++ empty project

Make sure that "Debug" is selected in the solution configuration combobox. Right-click cvtest and select PropertiesVC++ Directories.

Project property dialog

Select Include Directories to add a new entry and type C:\opencv\build\include.

Include directories dialog

Click Ok to close the dialog.

Back to the Property dialog, select Library Directories to add a new entry and type C:\opencv\build\x86\vc10\lib.

Library directories dialog

Click Ok to close the dialog.

Back to the property dialog, select LinkerInputAdditional Dependencies to add new entries. On the popup dialog, type the files below:

opencv_calib3d243d.lib
opencv_contrib243d.lib
opencv_core243d.lib
opencv_features2d243d.lib
opencv_flann243d.lib
opencv_gpu243d.lib
opencv_haartraining_engined.lib
opencv_highgui243d.lib
opencv_imgproc243d.lib
opencv_legacy243d.lib
opencv_ml243d.lib
opencv_nonfree243d.lib
opencv_objdetect243d.lib
opencv_photo243d.lib
opencv_stitching243d.lib
opencv_ts243d.lib
opencv_video243d.lib
opencv_videostab243d.lib

Note that the filenames end with "d" (for "debug"). Also note that if you have installed another version of OpenCV (say 2.4.9) these filenames will end with 249d instead of 243d (opencv_core249d.lib..etc).

enter image description here

Click Ok to close the dialog. Click Ok on the project properties dialog to save all settings.

NOTE:

These steps will configure Visual C++ for the "Debug" solution. For "Release" solution (optional), you need to repeat adding the OpenCV directories and in Additional Dependencies section, use:

opencv_core243.lib
opencv_imgproc243.lib
...

instead of:

opencv_core243d.lib
opencv_imgproc243d.lib
...

You've done setting up Visual C++, now is the time to write the real code. Right click your project and select AddNew Item...Visual C++C++ File.

Add new source file

Name your file (e.g: loadimg.cpp) and click Ok. Type the code below in the editor:

#include <opencv2/highgui/highgui.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main()
{
    Mat im = imread("c:/full/path/to/lena.jpg");
    if (im.empty()) 
    {
        cout << "Cannot load image!" << endl;
        return -1;
    }
    imshow("Image", im);
    waitKey(0);
}

The code above will load c:\full\path\to\lena.jpg and display the image. You can use any image you like, just make sure the path to the image is correct.

Type F5 to compile the code, and it will display the image in a nice window.

First OpenCV program

And that is your first OpenCV program!


3. Where to go from here?

Now that your OpenCV environment is ready, what's next?

  1. Go to the samples dir → c:\opencv\samples\cpp.
  2. Read and compile some code.
  3. Write your own code.

Android AudioRecord example

Here is an end to end solution I implemented for streaming Android microphone audio to a server for playback: Android AudioRecord to Server over UDP Playback Issues

How do I get a YouTube video thumbnail from the YouTube API?

Use:

https://www.googleapis.com/youtube/v3/videoCategories?part=snippet,id&maxResults=100&regionCode=us&key=**Your YouTube ID**

Above is the link. Using that, you can find the YouTube characteristics of videos. After finding characteristics, you can get videos of the selected category. After then you can find selected video images using Asaph's answer.

Try the above approach and you can parse everything from the YouTube API.

powerpoint loop a series of animation

Unfortunately you're probably done with the animation and presentation already. In the hopes this answer can help future questioners, however, this blog post has a walkthrough of steps that can loop a single slide as a sort of sub-presentation.

First, click Slide Show > Set Up Show.

Put a checkmark to Loop continuously until 'Esc'.

Click Ok. Now, Click Slide Show > Custom Shows. Click New.

Select the slide you are looping, click Add. Click Ok and Close.

Click on the slide you are looping. Click Slide Show > Slide Transition. Under Advance slide, put a checkmark to Automatically After. This will allow the slide to loop automatically. Do NOT Apply to all slides.

Right click on the thumbnail of the current slide, select Hide Slide.

Now, you will need to insert a new slide just before the slide you are looping. On the new slide, insert an action button. Set the hyperlink to the custom show you have created. Put a checkmark on "Show and Return"

This has worked for me.

Removing header column from pandas dataframe

Haven't seen this solution yet so here's how I did it without using read_csv:

df.rename(columns={'A':'','B':''})

If you rename all your column names to empty strings your table will return without a header.

And if you have a lot of columns in your table you can just create a dictionary first instead of renaming manually:

df_dict = dict.fromkeys(df.columns, '')
df.rename(columns = df_dict)

Want to show/hide div based on dropdown box selection

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
    $('#purpose').on('change', function() {
      if ( this.value == '1')
      //.....................^.......
      {
           $("#business_new").hide();
        $("#business").show();
      }
      else  if ( this.value == '2')
      {
          $("#business").hide();
        $("#business_new").show();
      }
       else  
      {
        $("#business").hide();
      }
    });
});
</script>
<body>
<select id='purpose'>
<option value="0">Personal use</option>
<option value="1">Business use</option>
<option value="2">Passing on to a client</option>
</select>
<div style='display:none;' id='business'>Business Name<br/>&nbsp;
<br/>&nbsp;
    <input type='text' class='text' name='business' value size='20' />
    <input type='text' class='text' name='business' value size='20' />
    <br/>
</div>
<div style='display:none;' id='business_new'>Business Name<br/>&nbsp;
<br/>&nbsp;
    <input type='text' class='text' name='business' value="1254" size='20' />
    <input type='text' class='text' name='business' value size='20' />
    <br/>
</div>
</body>