Programs & Examples On #Nsfilehandle

The NSFileHandle class is an object-oriented wrapper for a file descriptor. You use file handle objects to access data associated with files, sockets, pipes, and devices. For files, you can read, write, and seek within the file. For sockets, pipes, and devices, you can use a file handle object to monitor the device and process data asynchronously.

Why use pip over easy_install?

From Ian Bicking's own introduction to pip:

pip was originally written to improve on easy_install in the following ways

  • All packages are downloaded before installation. Partially-completed installation doesn’t occur as a result.
  • Care is taken to present useful output on the console.
  • The reasons for actions are kept track of. For instance, if a package is being installed, pip keeps track of why that package was required.
  • Error messages should be useful.
  • The code is relatively concise and cohesive, making it easier to use programmatically.
  • Packages don’t have to be installed as egg archives, they can be installed flat (while keeping the egg metadata).
  • Native support for other version control systems (Git, Mercurial and Bazaar)
  • Uninstallation of packages.
  • Simple to define fixed sets of requirements and reliably reproduce a set of packages.

Getting "java.nio.file.AccessDeniedException" when trying to write to a folder

I was getting the same error when trying to copy a file. Closing a channel associated with the target file solved the problem.

Path destFile = Paths.get("dest file");
SeekableByteChannel destFileChannel = Files.newByteChannel(destFile);
//...
destFileChannel.close();  //removing this will throw java.nio.file.AccessDeniedException:
Files.copy(Paths.get("source file"), destFile);

How can I jump to class/method definition in Atom text editor?

Here are the shortcuts for both mac and windows:

For Mac: command + G

For Windows: CTRL+ALT+G

binning data in python with scipy/numpy

It's probably faster and easier to use numpy.digitize():

import numpy
data = numpy.random.random(100)
bins = numpy.linspace(0, 1, 10)
digitized = numpy.digitize(data, bins)
bin_means = [data[digitized == i].mean() for i in range(1, len(bins))]

An alternative to this is to use numpy.histogram():

bin_means = (numpy.histogram(data, bins, weights=data)[0] /
             numpy.histogram(data, bins)[0])

Try for yourself which one is faster... :)

How to copy selected lines to clipboard in vim

First check if your vim installation has clipboard support.

vim --version

If clipboard support is installed you will see:

+clipboard
+X11
+xterm_clipboard

If clipboard support is not installed you will see:

-clipboard
-X11
-xterm_clipboard

To install clipboard support:

apt-get install vim-gnome

Once you have verified that clipboard support is installed do the following:

  1. Position your cursor to the first line you want to copy.
  2. Press Shiftv to enter visual mode.
  3. Press ? to select multiple lines
  4. Press "+y to copy the selected text to system clipboard.
  5. Now you can copy the selected text to browser, text editor etc.
  6. Press "+p if you want to copy system clipboard text to vim.

Above steps might get tedious if you have to repeatedly copy from vim to system clipboard and vice versa. You can create vim shortcuts so that when you press Ctrlc selected text will be copied to system clipboard. And when you press Ctrlp system clipboard text is copied to vim. To create shortcuts :

  1. Open .vimrc file and add following text at the end of file:

     nnoremap <C-c> "+y
     vnoremap <C-c> "+y
     nnoremap <C-p> "+p
     vnoremap <C-p> "+p
    
  2. Save and reload your .vimrc to apply the new changes.

  3. Position your cursor to the first line you want to copy.

  4. Press Shiftv to enter visual mode.

  5. Press ? to select multiple lines

  6. Press Ctrlc to copy the selected text to system clipboard.

  7. Now you can copy the selected text to browser, text editor etc.

  8. Press Ctrlp if you want to copy system clipboard text to vim.

Note: This is for ubuntu systems.

origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

if You use spring boot , you should add origin link in the @CrossOrigin annotation

@CrossOrigin(origins = "http://localhost:4200")
@GetMapping("/yourPath")

You can find detailed instruction in the https://spring.io/guides/gs/rest-service-cors/

CSS Box Shadow - Top and Bottom Only

As Kristian has pointed out, good control over z-values will often solve your problems.

If that does not work you can take a look at CSS Box Shadow Bottom Only on using overflow hidden to hide excess shadow.

I would also have in mind that the box-shadow property can accept a comma-separated list of shadows like this:

box-shadow: 0px 10px 5px #888, 0px -10px 5px #888;

This will give you some control over the "amount" of shadow in each direction.

Have a look at http://www.css3.info/preview/box-shadow/ for more information about box-shadow.

Hope this was what you were looking for!

"Could not find Developer Disk Image"

Xcode 7.0.1 and iOS 9.1 are incompatible. You will need to update your version of Xcode via the Mac app store.

If your iOS version is lower then the Xcode version on the other hand, you can change the deployment target for a lower version of iOS by going to the General Settings and under Deployment set your Deployment Target:

enter image description here

Note:

Xcode 7.1 does not include iOS 9.2 beta SDK. Upgraded to Xcode to 7.2 beta by downloading it from the Xcode website.

How to run a SQL query on an Excel table?

If you have GDAL/OGR compiled with the against the Expat library, you can use the XLSX driver to read .xlsx files, and run SQL expressions from a command prompt. For example, from a osgeo4w shell in the same directory as the spreadsheet, use the ogrinfo utility:

ogrinfo -dialect sqlite -sql "SELECT name, count(*) FROM sheet1 GROUP BY name" Book1.xlsx

will run a SQLite query on sheet1, and output the query result in an unusual form:

INFO: Open of `Book1.xlsx'
      using driver `XLSX' successful.

Layer name: SELECT
Geometry: None
Feature Count: 36
Layer SRS WKT:
(unknown)
name: String (0.0)
count(*): Integer (0.0)
OGRFeature(SELECT):0
  name (String) = Red
  count(*) (Integer) = 849

OGRFeature(SELECT):1
  name (String) = Green
  count(*) (Integer) = 265
...

Or run the same query using ogr2ogr to make a simple CSV file:

$ ogr2ogr -f CSV out.csv -dialect sqlite \
          -sql "SELECT name, count(*) FROM sheet1 GROUP BY name" Book1.xlsx

$ cat out.csv
name,count(*)
Red,849
Green,265
...

To do similar with older .xls files, you would need the XLS driver, built against the FreeXL library, which is not really common (e.g. not from OSGeo4w).

How can I delete an item from an array in VB.NET?

That depends on what you mean by delete. An array has a fixed size, so deleting doesn't really make sense.

If you want to remove element i, one option would be to move all elements j > i one position to the left (a[j - 1] = a[j] for all j, or using Array.Copy) and then resize the array using ReDim Preserve.

So, unless you are forced to use an array by some external constraint, consider using a data structure more suitable for adding and removing items. List<T>, for example, also uses an array internally but takes care of all the resizing issues itself: For removing items, it uses the algorithm mentioned above (without the ReDim), which is why List<T>.RemoveAt is an O(n) operation.

There's a whole lot of different collection classes in the System.Collections.Generic namespace, optimized for different use cases. If removing items frequently is a requirement, there are lots of better options than an array (or even List<T>).

Why dict.get(key) instead of dict[key]?

get takes a second optional value. If the specified key does not exist in your dictionary, then this value will be returned.

dictionary = {"Name": "Harry", "Age": 17}
dictionary.get('Year', 'No available data')
>> 'No available data'

If you do not give the second parameter, None will be returned.

If you use indexing as in dictionary['Year'], nonexistent keys will raise KeyError.

Kotlin's List missing "add", "remove", Map missing "put", etc?

Confining Mutability to Builders

The top answers here correctly speak to the difference in Kotlin between read-only List (NOTE: it's read-only, not "immutable"), and MutableList.

In general, one should strive to use read-only lists, however, mutability is still often useful at construction time, especially when dealing with third-party libraries with non-functional interfaces. For cases in which alternate construction techniques are not available, such as using listOf directly, or applying a functional construct like fold or reduce, a simple "builder function" construct like the following nicely produces a read-only list from a temporary mutable one:

val readonlyList = mutableListOf<...>().apply {
  // manipulate your list here using whatever logic you need
  // the `apply` function sets `this` to the `MutableList`
  add(foo1)
  addAll(foos)
  // etc.
}.toList()

and this can be nicely encapsulated into a re-usable inline utility function:

inline fun <T> buildList(block: MutableList<T>.() -> Unit) = 
  mutableListOf<T>().apply(block).toList()

which can be called like this:

val readonlyList = buildList<String> {
  add("foo")
  add("bar")
}

Now, all of the mutability is isolated to one block scope used for construction of the read-only list, and the rest of your code uses the read-only list that is output from the builder.

UPDATE: As of Kotlin 1.3.70, the exact buildList function above is available in the standard library as an experimental function, along with its analogues buildSet and buildMap. See https://blog.jetbrains.com/kotlin/2020/03/kotlin-1-3-70-released/.

Explain ExtJS 4 event handling

One more trick for controller event listeners.

You can use wildcards to watch for an event from any component:

this.control({
   '*':{ 
       myCustomEvent: this.doSomething
   }
});

Uncaught ReferenceError: React is not defined

Adding to Santosh :

You can load React by

import React from 'react'

How to send a simple string between two programs using pipes?

First, have program 1 write the string to stdout (as if you'd like it to appear in screen). Then the second program should read a string from stdin, as if a user was typing from a keyboard. then you run:

$ program_1 | program_2

push() a two-dimensional array

Iterating over two dimensions means you'll need to check over two dimensions.

assuming you're starting with:

var myArray = [
    [1,1,1,1,1],
    [1,1,1,1,1],
    [1,1,1,1,1]
]; //don't forget your semi-colons

You want to expand this two-dimensional array to become:

var myArray = [
    [1,1,1,1,1,0,0],
    [1,1,1,1,1,0,0],
    [1,1,1,1,1,0,0],
    [0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0],
];

Which means you need to understand what the difference is.

Start with the outer array:

var myArray = [
    [...],
    [...],
    [...]
];

If you want to make this array longer, you need to check that it's the correct length, and add more inner arrays to make up the difference:

var i,
    rows,
    myArray;
rows = 8;
myArray = [...]; //see first example above
for (i = 0; i < rows; i += 1) {
    //check if the index exists in the outer array
    if (!(i in myArray)) {
        //if it doesn't exist, we need another array to fill
        myArray.push([]);
    }
}

The next step requires iterating over every column in every array, we'll build on the original code:

var i,
    j,
    row,
    rows,
    cols,
    myArray;
rows = 8;
cols = 7; //adding columns in this time
myArray = [...]; //see first example above
for (i = 0; i < rows; i += 1) {
    //check if the index exists in the outer array (row)
    if (!(i in myArray)) {
        //if it doesn't exist, we need another array to fill
        myArray[i] = [];
    }
    row = myArray[i];
    for (j = 0; j < cols; j += 1) {
        //check if the index exists in the inner array (column)
        if (!(i in row)) {
            //if it doesn't exist, we need to fill it with `0`
            row[j] = 0;
        }
    }
}

Show a popup/message box from a Windows batch file

Here's a PowerShell variant that doesn't require loading assemblies prior to creating the window, however it runs noticeably slower (~+50%) than the PowerShell MessageBox command posted here by @npocmaka:

powershell (New-Object -ComObject Wscript.Shell).Popup("""Operation Completed""",0,"""Done""",0x0)

You can change the last parameter from "0x0" to a value below to display icons in the dialog (see Popup Method for further reference):

        Stop 0x10 Stop
        Question Mark 0x20 Question Mark
        Exclamation Mark 0x30 Exclamation Mark
        Information Mark 0x40 Information Mark

Adapted from the Microsoft TechNet article PowerTip: Use PowerShell to Display Pop-Up Window.

How do I call Objective-C code from Swift?

  1. Create a .h file from NewFile -> Source -> header file
  2. Then save the name of file Your_Target_Name-Bridging-Header.h People here gets common mistake by taking their project name but it should be the Project's Target's name if in case both are different, generally they are same.
  3. Then in build settings search for Objective-C Bridging Header flag and put the address of your newly created bridging file, you can do it right click on the file -> show in finder -> drag the file in the text area then the address will be populated.
  4. Using #import Your_Objective-C_file.h
  5. In the swift file you can access the ObjC file but in swift language only.

How can I start pagenumbers, where the first section occurs in LaTex?

You can also reset page number counter:

\setcounter{page}{1}

However, with this technique you get wrong page numbers in Acrobat in the top left page numbers field:

\maketitle: 1
\tableofcontents: 2
\setcounter{page}{1}
\section{Introduction}: 1
...

Detecting touch screen devices with Javascript

return (('ontouchstart' in window)
      || (navigator.maxTouchPoints > 0)
      || (navigator.msMaxTouchPoints > 0));

Reason for using maxTouchPoints alongwith msMaxTouchPoints:

Microsoft has stated that starting with Internet Explorer 11, Microsoft vendor prefixed version of this property (msMaxTouchPoints) may be removed and recommends using maxTouchPoints instead.

Source : http://ctrlq.org/code/19616-detect-touch-screen-javascript

How can I set a custom date time format in Oracle SQL Developer?

Goto to Tools > Preferences. In the tree, select Database > NLS. There are three Date/Time formats available: Date, Timestamp and Timestamp TZ. Editing the Date format gives the desired effect.

Like I have said above; this approach has not given me a permanent change.

Access iframe elements in JavaScript

this code worked for me:

window.frames['myIFrame'].contentDocument.getElementById('myIFrameElemId');

How do I do an OR filter in a Django query?

You want to make filter dynamic then you have to use Lambda like

from django.db.models import Q

brands = ['ABC','DEF' , 'GHI']

queryset = Product.objects.filter(reduce(lambda x, y: x | y, [Q(brand=item) for item in brands]))

reduce(lambda x, y: x | y, [Q(brand=item) for item in brands]) is equivalent to

Q(brand=brands[0]) | Q(brand=brands[1]) | Q(brand=brands[2]) | .....

How to select last one week data from today's date

  1. The query is correct

2A. As far as last seven days have much less rows than whole table an index can help

2B. If you are interested only in Created_Date you can try using some group by and count, it should help with the result set size

Loop through the rows of a particular DataTable

Dim row As DataRow
For Each row In dtDataTable.Rows
    Dim strDetail As String
    strDetail = row("Detail")
    Console.WriteLine("Processing Detail {0}", strDetail)
Next row

Labels for radio buttons in rails form

If you want the object_name prefixed to any ID you should call form helpers on the form object:

- form_for(@message) do |f|
  = f.label :email

This also makes sure any submitted data is stored in memory should there be any validation errors etc.

If you can't call the form helper method on the form object, for example if you're using a tag helper (radio_button_tag etc.) you can interpolate the name using:

= radio_button_tag "#{f.object_name}[email]", @message.email

In this case you'd need to specify the value manually to preserve any submissions.

Opposite of %in%: exclude rows with values specified in a vector

Another solution could be using setdiff

D1 = c("A",..., "Z") ; D0 = c("B","N","T")

D2 = setdiff(D1, D0)

D2 is your desired subset.

MySQL - Operand should contain 1 column(s)

In my case, the problem was that I sorrounded my columns selection with parenthesis by mistake:

SELECT (p.column1, p.colum2, p.column3) FROM table1 p where p.column1 = 1;

And has to be:

SELECT p.column1, p.colum2, p.column3 FROM table1 p where p.column1 = 1;

Sounds silly, but it was causing this error and it took some time to figure it out.

How to safely upgrade an Amazon EC2 instance from t1.micro to large?

Using the AWS Management Console

  • Go to "Volumes" and create a Snapshot of your instance's volume.
  • Go to "Snapshots" and select "Create Image from Snapshot".
  • Go to "AMIs" and select "Launch Instance" and choose your "Instance Type" etc.

How does one sum only those rows in excel not filtered out?

When you use autofilter to filter results, Excel doesn't even bother to hide them: it just sets the height of the row to zero (up to 2003 at least, not sure on 2007).

So the following custom function should give you a starter to do what you want (tested with integers, haven't played with anything else):

Function SumVis(r As Range)
    Dim cell As Excel.Range
    Dim total As Variant

    For Each cell In r.Cells
        If cell.Height <> 0 Then
            total = total + cell.Value
        End If
    Next

    SumVis = total
End Function

Edit:

You'll need to create a module in the workbook to put the function in, then you can just call it on your sheet like any other function (=SumVis(A1:A14)). If you need help setting up the module, let me know.

Datatables on-the-fly resizing

might be late also like the other answer but I did this early this year and the solution I came up with is using css.

    $(window).bind('resize', function () {
        /*the line below was causing the page to keep loading.
        $('#tableData').dataTable().fnAdjustColumnSizing();
        Below is a workaround. The above should automatically work.*/
        $('#tableData').css('width', '100%');
    } );

What jsf component can render a div tag?

I think we can you use verbatim tag, as in this tag we use any of the HTML tags

Spark Dataframe distinguish columns with duplicated name

After digging into the Spark API, I found I can first use alias to create an alias for the original dataframe, then I use withColumnRenamed to manually rename every column on the alias, this will do the join without causing the column name duplication.

More detail can be refer to below Spark Dataframe API:

pyspark.sql.DataFrame.alias

pyspark.sql.DataFrame.withColumnRenamed

However, I think this is only a troublesome workaround, and wondering if there is any better way for my question.

command/usr/bin/codesign failed with exit code 1- code sign error

Rebooting didn't work for me.

Just try with downloading and adding the Certificate again to keyChain. That worked for me. When I checked Keychain Access the respective certificate was missing. Got the problem solve when I reinstalled the certificate.

How to get everything after a certain character?

Here is the method by using explode:

$text = explode('_', '233718_This_is_a_string', 2)[1]; // Returns This_is_a_string

or:

$text = @end((explode('_', '233718_This_is_a_string', 2)));

By specifying 2 for the limit parameter in explode(), it returns array with 2 maximum elements separated by the string delimiter. Returning 2nd element ([1]), will give the rest of string.


Here is another one-liner by using strpos (as suggested by @flu):

$needle = '233718_This_is_a_string';
$text = substr($needle, (strpos($needle, '_') ?: -1) + 1); // Returns This_is_a_string

Best way to find the intersection of multiple sets?

If you don't have Python 2.6 or higher, the alternative is to write an explicit for loop:

def set_list_intersection(set_list):
  if not set_list:
    return set()
  result = set_list[0]
  for s in set_list[1:]:
    result &= s
  return result

set_list = [set([1, 2]), set([1, 3]), set([1, 4])]
print set_list_intersection(set_list)
# Output: set([1])

You can also use reduce:

set_list = [set([1, 2]), set([1, 3]), set([1, 4])]
print reduce(lambda s1, s2: s1 & s2, set_list)
# Output: set([1])

However, many Python programmers dislike it, including Guido himself:

About 12 years ago, Python aquired lambda, reduce(), filter() and map(), courtesy of (I believe) a Lisp hacker who missed them and submitted working patches. But, despite of the PR value, I think these features should be cut from Python 3000.

So now reduce(). This is actually the one I've always hated most, because, apart from a few examples involving + or *, almost every time I see a reduce() call with a non-trivial function argument, I need to grab pen and paper to diagram what's actually being fed into that function before I understand what the reduce() is supposed to do. So in my mind, the applicability of reduce() is pretty much limited to associative operators, and in all other cases it's better to write out the accumulation loop explicitly.

How to display Oracle schema size with SQL query?

SELECT table_name as Table_Name, row_cnt as Row_Count, SUM(mb) as Size_MB
FROM
  (SELECT in_tbl.table_name,   to_number(extractvalue(xmltype(dbms_xmlgen.getxml('select count(*) c from ' ||ut.table_name)),'/ROWSET/ROW/C')) AS row_cnt , mb
FROM
(SELECT CASE WHEN lob_tables IS NULL THEN table_name WHEN lob_tables IS NOT NULL THEN lob_tables END AS table_name , mb
FROM (SELECT ul.table_name AS lob_tables, us.segment_name AS table_name , us.bytes/1024/1024 MB FROM user_segments us
LEFT JOIN user_lobs ul ON us.segment_name = ul.segment_name ) ) in_tbl INNER JOIN user_tables ut ON in_tbl.table_name = ut.table_name ) GROUP BY table_name, row_cnt ORDER BY 3 DESC;``

Above query will give, Table_name, Row_count, Size_in_MB(includes lob column size) of specific user.

How to create a library project in Android Studio and an application project that uses the library project

Had the same question and solved it the following way:

Start situation:

FrigoShare (root)
|-Modules:    frigoshare,   frigoShare-backend

Target: want to add a module named dataformats

  1. Add a new module (e.g.: Java Library)
  2. Make sure your settings.gradle look like this (normally automatically):

    include ':frigoshare', ':frigoShare-backend', ':dataformats'

  3. Make sure (manually) that the build.gradle files of the modules that need to use your library have the following dependency:

    dependencies { ... compile project(':dataformats') }

Checking if a variable is an integer in PHP

I had a similar problem just now!

You can use the filter_input() function with FILTER_VALIDATE_INT and FILTER_NULL_ON_FAILURE to filter only integer values out of the $_GET variable. Works pretty accurately! :)

Check out my question here: How to check whether a variable in $_GET Array is an integer?

Does Java support structs?

Java doesn't have an analog to C++'s structs, but you can use classes with all public members.

wkhtmltopdf: cannot connect to X server

Just made it:

1- To download wkhtmltopdf dependencies

# apt-get install wkhtmltopdf

2- Download from source

# wget http://downloads.sourceforge.net/project/wkhtmltopdf/xxx.deb

# dpkg -i xxx.deb

3- Try

# wkhtmltopdf http://google.com google.pdf

Its working fine

It works!

How can I disable the Maven Javadoc plugin from the command line?

It seems, that the simple way

-Dmaven.javadoc.skip=true

does not work with the release-plugin. in this case you have to pass the parameter as an "argument"

mvn release:perform -Darguments="-Dmaven.javadoc.skip=true"

How do you use NSAttributedString?

Super easy way to do this.

let text = "This is a colorful attributed string"
let attributedText = 
NSMutableAttributedString.getAttributedString(fromString: text)
attributedText.apply(color: .red, subString: "This")
//Apply yellow color on range
attributedText.apply(color: .yellow, onRange: NSMakeRange(5, 4))

For more detail click here; https://github.com/iOSTechHub/AttributedString

test if display = none

Use like this:

if( $('#foo').is(':visible') ) {
    // it's visible, do something
}
else {
    // it's not visible so do something else
}

Hope it helps!

How to check list A contains any value from list B?

For faster and short solution you can use HashSet instead of List.

a.Overlaps(b);

Overlaps documentation

This method is an O(n) instead of O(n^2) with two lists.

C# Encoding a text string with line breaks

Try this :

string myStr = ...
myStr = myStr.Replace("\n", Environment.NewLine)

How to get the nth occurrence in a string?

Because recursion is always the answer.

function getPosition(input, search, nth, curr, cnt) {
    curr = curr || 0;
    cnt = cnt || 0;
    var index = input.indexOf(search);
    if (curr === nth) {
        if (~index) {
            return cnt;
        }
        else {
            return -1;
        }
    }
    else {
        if (~index) {
            return getPosition(input.slice(index + search.length),
              search,
              nth,
              ++curr,
              cnt + index + search.length);
        }
        else {
            return -1;
        }
    }
}

CSS display: inline vs inline-block

Inline elements:

  1. respect left & right margins and padding, but not top & bottom
  2. cannot have a width and height set
  3. allow other elements to sit to their left and right.
  4. see very important side notes on this here.

Block elements:

  1. respect all of those
  2. force a line break after the block element
  3. acquires full-width if width not defined

Inline-block elements:

  1. allow other elements to sit to their left and right
  2. respect top & bottom margins and padding
  3. respect height and width

From W3Schools:

  • An inline element has no line break before or after it, and it tolerates HTML elements next to it.

  • A block element has some whitespace above and below it and does not tolerate any HTML elements next to it.

  • An inline-block element is placed as an inline element (on the same line as adjacent content), but it behaves as a block element.

When you visualize this, it looks like this:

CSS block vs inline vs inline-block

The image is taken from this page, which also talks some more about this subject.

How to get post slug from post in WordPress?

Wordpress: Get post/page slug

<?php 
// Custom function to return the post slug
function the_slug($echo=true){
  $slug = basename(get_permalink());
  do_action('before_slug', $slug);
  $slug = apply_filters('slug_filter', $slug);
  if( $echo ) echo $slug;
  do_action('after_slug', $slug);
  return $slug;
}
?>
<?php if (function_exists('the_slug')) { the_slug(); } ?>

Increasing Google Chrome's max-connections-per-server limit to more than 6

IE is even worse with 2 connection per domain limit. But I wouldn't rely on fixing client browsers. Even if you have control over them, browsers like chrome will auto update and a future release might behave differently than you expect. I'd focus on solving the problem within your system design.

Your choices are to:

  1. Load the images in sequence so that only 1 or 2 XHR calls are active at a time (use the success event from the previous image to check if there are more images to download and start the next request).

  2. Use sub-domains like serverA.myphotoserver.com and serverB.myphotoserver.com. Each sub domain will have its own pool for connection limits. This means you could have 2 requests going to 5 different sub-domains if you wanted to. The downfall is that the photos will be cached according to these sub-domains. BTW, these don't need to be "mirror" domains, you can just make additional DNS pointers to the exact same website/server. This means you don't have the headache of administrating many servers, just one server with many DNS records.

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

Here a small working conversion/appending example, with some code I needed before.

#include <string>
#include <sstream>
#include <iostream>

using namespace std;

int main(){
string str;
int i = 321;
std::stringstream ss;
ss << 123;
str = "/dev/video";
cout << str << endl;
cout << str << 456 << endl;
cout << str << i << endl;
str += ss.str();
cout << str << endl;
}

the output will be:

/dev/video
/dev/video456
/dev/video321
/dev/video123

Note that in the last two lines you save the modified string before it's actually printed out, and you could use it later if needed.

How to add elements to a list in R (loop)

The following adds elements to a list in a loop.

l<-c()
i=1

while(i<100) {

    b<-i
    l<-c(l,b)
    i=i+1
}

Creating a div element inside a div element in javascript

'b' should be in capital letter in document.getElementById modified code jsfiddle

function test()
{

var element = document.createElement("div");
element.appendChild(document.createTextNode('The man who mistook his wife for a hat'));
document.getElementById('lc').appendChild(element);
 //document.body.appendChild(element);
 }

Reading multiple Scanner inputs

If every input asks the same question, you should use a for loop and an array of inputs:

Scanner dd = new Scanner(System.in);
int[] vars = new int[3];

for(int i = 0; i < vars.length; i++) {
  System.out.println("Enter next var: ");
  vars[i] = dd.nextInt();
}

Or as Chip suggested, you can parse the input from one line:

Scanner in = new Scanner(System.in);
int[] vars = new int[3];

System.out.println("Enter "+vars.length+" vars: ");
for(int i = 0; i < vars.length; i++)
  vars[i] = in.nextInt();

You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.

How do I populate a JComboBox with an ArrayList?

DefaultComboBoxModel dml= new DefaultComboBoxModel();
for (int i = 0; i < <ArrayList>.size(); i++) {
  dml.addElement(<ArrayList>.get(i).getField());
}

<ComboBoxName>.setModel(dml);

Understandable code.Edit<> with type as required.

How to solve java.lang.NullPointerException error?

This error occures when you try to refer to a null object instance. I can`t tell you what causes this error by your given information, but you can debug it easily in your IDE. I strongly recommend you that use exception handling to avoid unexpected program behavior.

How do I set a JLabel's background color?

For the Background, make sure you have imported java.awt.Color into your package.

In your main method, i.e. public static void main(String[] args), call the already imported method:

JLabel name_of_your_label=new JLabel("the title of your label");
name_of_your_label.setBackground(Color.the_color_you_wish);
name_of_your_label.setOpaque(true);

NB: Setting opaque will affect its visibility. Remember the case sensitivity in Java.

How do I use a regex in a shell script?

the problem is you're trying to use regex features not supported by grep. namely, your \d won't work. use this instead:

REGEX_DATE="^[[:digit:]]{2}[-/][[:digit:]]{2}[-/][[:digit:]]{4}$"
echo "$1" | grep -qE "${REGEX_DATE}"
echo $?

you need the -E flag to get ERE in order to use {#} style.

Get the Id of current table row with Jquery

Your code would be more like so:

$('tr input[type=button]').click(function(){
    id = $(this).closest('tr').attr('id');
});

Git Ignores and Maven targets

I ignore all classes residing in target folder from git. add following line in open .gitignore file:

/.class

OR

*/target/**

It is working perfectly for me. try it.

Serializing to JSON in jQuery

Works on IE8+

No need for jQuery, use:

JSON.stringify(countries); 

Count all values in a matrix greater than a value

The numpy.where function is your friend. Because it's implemented to take full advantage of the array datatype, for large images you should notice a speed improvement over the pure python solution you provide.

Using numpy.where directly will yield a boolean mask indicating whether certain values match your conditions:

>>> data
array([[1, 8],
       [3, 4]])
>>> numpy.where( data > 3 )
(array([0, 1]), array([1, 1]))

And the mask can be used to index the array directly to get the actual values:

>>> data[ numpy.where( data > 3 ) ]
array([8, 4])

Exactly where you take it from there will depend on what form you'd like the results in.

Your password does not satisfy the current policy requirements

The problem is that your password wont match the password validation rules. You can simple follow below steps to solve your problem.

You can simply see password validation configuration matrix by typing below code.

mysql-> SHOW VARIABLES LIKE 'validate_password%';

Then in your matrix you can find below variables with corresponding values and in there you have to check validate_password_length , validate_password_number_count and validate_password_policy.

Check the values used for those variables. Make sure your validate_password_length should not be greater than 6. You can set that to 6 by using below code.

SET GLOBAL validate_password_length = 6;

And after that you need to set validate_password_number_count to 0. Do it by using below code.

SET GLOBAL validate_password_number_count = 0;

Finally you have to set you validate_password_policy to low. Having that as Medium or High wont allow your less secure passwords. Set that to low by below code.

SET GLOBAL validate_password_policy=LOW;

How to change Oracle default data pump directory to import dumpfile?

With the directory parameter:

impdp system/password@$ORACLE_SID schemas=USER_SCHEMA directory=MY_DIR \
  dumpfile=mydumpfile.dmp logfile=impdpmydumpfile.log

The default directory is DATA_PUMP_DIR, which is presumably set to /u01/app/oracle/admin/mydatabase/dpdump on your system.

To use a different directory you (or your DBA) will have to create a new directory object in the database, which points to the Oracle-visible operating system directory you put the file into, and assign privileges to the user doing the import.

Best way to do a split pane in HTML

I wrote simple code for it without any third-party library. This code is only for a horizontal splitter (vertical is the same).

_x000D_
_x000D_
function onload()
{
    dragElement( document.getElementById("separator"), "H" );
}

// This function is used for dragging and moving
function dragElement( element, direction, handler )
{
  // Two variables for tracking positions of the cursor
  const drag = { x : 0, y : 0 };
  const delta = { x : 0, y : 0 };
  /* If present, the handler is where you move the DIV from
     otherwise, move the DIV from anywhere inside the DIV */
  handler ? ( handler.onmousedown = dragMouseDown ): ( element.onmousedown = dragMouseDown );

  // A function that will be called whenever the down event of the mouse is raised
  function dragMouseDown( e )
  {
    drag.x = e.clientX;
    drag.y = e.clientY;
    document.onmousemove = onMouseMove;
    document.onmouseup = () => { document.onmousemove = document.onmouseup = null; }
  }

  // A function that will be called whenever the up event of the mouse is raised
  function onMouseMove( e )
  {
    const currentX = e.clientX;
    const currentY = e.clientY;

    delta.x = currentX - drag.x;
    delta.y = currentY - drag.y;

    const offsetLeft = element.offsetLeft;
    const offsetTop = element.offsetTop;


    const first = document.getElementById("first");
    const second = document.getElementById("second");
    let firstWidth = first.offsetWidth;
    let secondWidth = second.offsetWidth;
    if (direction === "H" ) // Horizontal
    {
        element.style.left = offsetLeft + delta.x + "px";
        firstWidth += delta.x;
        secondWidth -= delta.x;
    }
    drag.x = currentX;
    drag.y = currentY;
    first.style.width = firstWidth + "px";
    second.style.width = secondWidth + "px";
  }
}
_x000D_
.splitter {
    width: 500px;
    height: 100px;
    display: flex;
}

#separator {
    cursor: col-resize;
    background: url(https://raw.githubusercontent.com/RickStrahl/jquery-resizable/master/assets/vsizegrip.png) center center no-repeat #535353;
    width: 10px;
    height: 100px;
    min-width: 10px;
}

#first {
    background-color: green;
    width: 100px;
    height: 100px;
    min-width: 10px;
}

#second {
    background-color: red;
    width: 390px;
    height: 100px;
    min-width: 10px;
}
_x000D_
<html>

    <head>
        <link rel="stylesheet" href="T10-Splitter.css">
        <script src="T10-Splitter.js"></script>
    </head>

    <body onload="onload()">
        <div class="splitter">
            <div id="first"></div>
            <div id="separator"></div>
            <div id="second"></div>
        </div>
    </body>

</html>
_x000D_
_x000D_
_x000D_

How to set the title of UIButton as left alignment?

Set the contentHorizontalAlignment:

emailBtn.contentHorizontalAlignment = .left;

You might also want to adjust the content left inset otherwise the text will touch the left border:

emailBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);

// Swift 3 and up:
emailBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0);

Better way to sort array in descending order

You may specify a comparer(IComparer implementation) as a parameter in Array.Sort, the order of sorting actually depends on comparer. The default comparer is used in ascending sorting

How exactly does <script defer="defer"> work?

The defer attribute is a boolean attribute.

When present, it specifies that the script is executed when the page has finished parsing.

Note: The defer attribute is only for external scripts (should only be used if the src attribute is present).

Note: There are several ways an external script can be executed:

If async is present: The script is executed asynchronously with the rest of the page (the script will be executed while the page continues the parsing) If async is not present and defer is present: The script is executed when the page has finished parsing If neither async or defer is present: The script is fetched and executed immediately, before the browser continues parsing the page

ASP.NET page life cycle explanation

This acronym might help you to remember the ASP.NET life cycle stages which I wrote about in the below blog post.

R-SIL-VP-RU

  1. Request
  2. Start
  3. Initialization
  4. Load
  5. Validation
  6. Post back handling
  7. Rendering
  8. Unload

From my blog: Understand ASP.NET Page life cycle and remember stages in easy way
18 May 2014

Undoing accidental git stash pop

If your merge was not too complicated another option would be to:

  1. Move all the changes including the merge changes back to stash using "git stash"
  2. Run the merge again and commit your changes (without the changes from the dropped stash)
  3. Run a "git stash pop" which should ignore all the changes from your previous merge since the files are identical now.

After that you are left with only the changes from the stash you dropped too early.

CSS Always On Top

Assuming that your markup looks like:

<div id="header" style="position: fixed;"></div>
<div id="content" style="position: relative;"></div>

Now both elements are positioned; in which case, the element at the bottom (in source order) will cover element above it (in source order).

Add a z-index on header; 1 should be sufficient.

PHP sessions that have already been started

Simply use if statement

 if(!isset($_SESSION)) 
     { 
         session_start(); 
     }

or

check the session status with session_status that Returns the current session status and if current session is already working then return with nothing else if session not working start the session


session_status() === PHP_SESSION_ACTIVE ?: session_start();

Add new value to an existing array in JavaScript

There are several ways:

Instantiating the array:

var arr;

arr = new Array(); // empty array

// ---

arr = [];          // empty array

// ---

arr = new Array(3);
alert(arr.length);  // 3
alert(arr[0]); // undefined

// ---

arr = [3];
alert(arr.length);  // 1
alert(arr[0]); // 3

Pushing to the array:

arr = [3];     // arr == [3]
arr[1] = 4;    // arr == [3, 4]
arr[2] = 5;    // arr == [3, 4, 5]
arr[4] = 7;    // arr == [3, 4, 5, undefined, 7]

// ---

arr = [3];
arr.push(4);        // arr == [3, 4]
arr.push(5);        // arr == [3, 4, 5]
arr.push(6, 7, 8);  // arr == [3, 4, 5, 6, 7, 8]

Using .push() is the better way to add to an array, since you don't need to know how many items are already there, and you can add many items in one function call.

What is the best way to dump entire objects to a log in C#?

ServiceStack.Text has a T.Dump() extension method that does exactly this, recursively dumps all properties of any type in a nice readable format.

Example usage:

var model = new TestModel();
Console.WriteLine(model.Dump());

and output:

{
    Int: 1,
    String: One,
    DateTime: 2010-04-11,
    Guid: c050437f6fcd46be9b2d0806a0860b3e,
    EmptyIntList: [],
    IntList:
    [
        1,
        2,
        3
    ],
    StringList:
    [
        one,
        two,
        three
    ],
    StringIntMap:
    {
        a: 1,
        b: 2,
        c: 3
    }
}

Internet Explorer cache location

By default, the locations of Temporary Internet Files (for Internet Explorer) are:

Windows 95, Windows 98, and Windows ME

c:\WINDOWS\Temporary Internet Files

Windows 2000 and Windows XP

C:\Documents and Settings\\[User]\Local Settings\Temporary Internet Files

Windows Vista and Windows 7

%userprofile%\AppData\Local\Microsoft\Windows\Temporary Internet Files

%userprofile%\AppData\Local\Microsoft\Windows\Temporary Internet Files\Low

Windows 8

%userprofile%\AppData\Local\Microsoft\Windows\INetCache

Windows 10

%localappdata%\Microsoft\Windows\INetCache\IE

Some information came from The Windows Club.

How to change line-ending settings

For me what did the trick was running the command

git config auto.crlf false

inside the folder of the project, I wanted it specifically for one project.

That command changed the file in path {project_name}/.git/config (fyi .git is a hidden folder) by adding the lines

[auto]
    crlf = false

at the end of the file. I suppose changing the file does the same trick as well.

What is the difference between class and instance methods?

class methods

are methods which are declared as static. The method can be called without creating an instance of the class. Class methods can only operate on class members and not on instance members as class methods are unaware of instance members. Instance methods of the class can also not be called from within a class method unless they are being called on an instance of that class.

Instance methods

on the other hand require an instance of the class to exist before they can be called, so an instance of a class needs to be created by using the new keyword. Instance methods operate on specific instances of classes. Instance methods are not declared as static.

Find mouse position relative to element

There is no answer in pure javascript that returns relative coordinates when the reference element is nested inside others which can be with absolute positioning. Here is a solution to this scenario:

function getRelativeCoordinates (event, referenceElement) {

  const position = {
    x: event.pageX,
    y: event.pageY
  };

  const offset = {
    left: referenceElement.offsetLeft,
    top: referenceElement.offsetTop
  };

  let reference = referenceElement.offsetParent;

  while(reference){
    offset.left += reference.offsetLeft;
    offset.top += reference.offsetTop;
    reference = reference.offsetParent;
  }

  return { 
    x: position.x - offset.left,
    y: position.y - offset.top,
  }; 

}

Change text from "Submit" on input tag

The value attribute on submit-type <input> elements controls the text displayed.

<input type="submit" class="like" value="Like" />

How to bind a List to a ComboBox?

public class Country
{
    public string Name { get; set; }
    public IList<City> Cities { get; set; }

    public Country()
    {
        Cities = new List<City>();
    }
}

public class City 
{
    public string Name { get; set; } 
}

List<Country> Countries = new List<Country>
{
    new Country
    {
        Name = "Germany",
        Cities =
        {
            new City {Name = "Berlin"},
            new City {Name = "Hamburg"}
        }
    },
    new Country
    {
        Name = "England",
        Cities =
        {
            new City {Name = "London"},
            new City {Name = "Birmingham"}
        }
    }
};
bindingSource1.DataSource = Countries;
member_CountryComboBox.DataSource = bindingSource1.DataSource;
member_CountryComboBox.DisplayMember = "Name";
member_CountryCombo

Box.ValueMember = "Name";

This is the code I am using now.

MySQL date formats - difficulty Inserting a date

Put the date in single quotes and move the parenthesis (after the 'yes') to the end:

INSERT INTO custorder 
  VALUES ('Kevin', 'yes' , STR_TO_DATE('1-01-2012', '%d-%m-%Y') ) ;
                        ^                                     ^
---parenthesis removed--|                and added here ------|

But you can always use dates without STR_TO_DATE() function, just use the (Y-m-d) '20120101' or '2012-01-01' format. Check the MySQL docs: Date and Time Literals

INSERT INTO custorder 
  VALUES ('Kevin', 'yes', '2012-01-01') ;

How to Change color of Button in Android when Clicked?

To deal properly for how long you want to have your button stay in your other color I would advise this version:

button.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch(event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        button.setBackground(getResources().getDrawable(R.drawable.on_click_drawable));
                        break;
                    case MotionEvent.ACTION_UP:
                        new java.util.Timer().schedule(
                                new java.util.TimerTask() {
                                    @Override
                                    public void run() {
                                        ((Activity) (getContext())).runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                button.setBackground(getResources().getDrawable(R.drawable.not_clicked_drawable));
                                            }
                                        });
                                    }
                                }, BUTTON_CLICK_TIME_AFTER_RELEASE_ANIMATION);
                        break;
                    default:
                }
                return false;
            }
        });

BUTTON_CLICK_TIME_AFTER_RELEASE_ANIMATION indicates after how much time [ms] the button will reset to the previous state (however you might want to use some boolean to check that the button hadn't been used in between, depending on what you want to achieve...).

Does swift have a trim method on String?

extension String {
    /// EZSE: Trims white space and new line characters
    public mutating func trim() {
         self = self.trimmed()
    }

    /// EZSE: Trims white space and new line characters, returns a new string
    public func trimmed() -> String {
        return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
    }
}

Taken from this repo of mine: https://github.com/goktugyil/EZSwiftExtensions/commit/609fce34a41f98733f97dfd7b4c23b5d16416206

How can I generate Unix timestamps?

In Haskell...

To get it back as a POSIXTime type:

import Data.Time.Clock.POSIX
getPOSIXTime

As an integer:

import Data.Time.Clock.POSIX
round `fmap` getPOSIXTime

Import a custom class in Java

Import by using the import keyword:

import package.myclass;

But since it's the default package and same, you just create a new instance like:

elf ob = new elf(); //Instance of elf class

Nested Recycler view height doesn't wrap its content

Based on the work of Denis Nek, it works well if the sum of item's widths is smaller than the size of the container. other than that, it will make the recyclerview non scrollable and only will show subset of the data.

to solve this problem, i modified the solution alittle so that it choose the min of the provided size and calculated size. see below:

package com.linkdev.gafi.adapters;

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import com.linkdev.gafi.R;

public class MyLinearLayoutManager extends LinearLayoutManager {

    public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout)    {
        super(context, orientation, reverseLayout);
        this.c = context;
    }


    private Context c;
    private int[] mMeasuredDimension = new int[2];


    @Override
    public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
                          int widthSpec, int heightSpec) {
        final int widthMode = View.MeasureSpec.getMode(widthSpec);
        final int heightMode = View.MeasureSpec.getMode(heightSpec);
        final int widthSize = View.MeasureSpec.getSize(widthSpec);
        final int heightSize = View.MeasureSpec.getSize(heightSpec);



        int width = 0;
        int height = 0;
        for (int i = 0; i < getItemCount(); i++) {
            measureScrapChild(recycler, i,
                    View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                    View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                    mMeasuredDimension);

            if (getOrientation() == HORIZONTAL) {
                width = width + mMeasuredDimension[0];
                if (i == 0) {
                    height = mMeasuredDimension[1];
                }
            } else {
                height = height + mMeasuredDimension[1];
                if (i == 0) {
                    width = mMeasuredDimension[0];
                }
            }
        }


        switch (widthMode) {
            case View.MeasureSpec.EXACTLY:
                width = widthSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        switch (heightMode) {
            case View.MeasureSpec.EXACTLY:
                height = heightSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        int widthDesired = Math.min(widthSize,width);
        setMeasuredDimension(widthDesired, height);
    }

    private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
                                   int heightSpec, int[] measuredDimension) {
        View view = recycler.getViewForPosition(position);
        if (view != null) {
            RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
            int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
                    getPaddingLeft() + getPaddingRight(), p.width);
            int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
                    getPaddingTop() + getPaddingBottom(), p.height);
            view.measure(childWidthSpec, childHeightSpec);
            measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
            measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
            recycler.recycleView(view);
        }
    }}

"Connect failed: Access denied for user 'root'@'localhost' (using password: YES)" from php function

Try initializing your variables and use them in your connection object:

$username ="root";
$password = "password";
$host = "localhost";
$table = "shop";
$conn = new mysqli("$host", "$username", "$password", "$table");

Getting first and last day of the current month

DateTime now = DateTime.Now;
var startDate = new DateTime(now.Year, now.Month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);

What is VanillaJS?

"Vanilla JS” is an expression that got popular after the publishing of a satire website in 2012 (http://vanilla-js.com/). There’s a section covering its story/meaning in this post.

So why the joke? It kind of came as a modern response to the old school knee-jerk reflex of relying on jQuery and additional JS libraries. With the ECMAScript spec and modern browsers capabilities, the need to bypass plain JS with external libraries to maintain consistency across browsers just isn’t there anymore. Here’s a site that shows you how true this is with concrete examples: http://youmightnotneedjquery.com/

Detect if HTML5 Video element is playing

Here is what we are using at http://www.develop.com/webcasts to keep people from accidentally leaving the page while a video is playing or paused.

$(document).ready(function() {

    var video = $("video#webcast_video");
    if (video.length <= 0) {
        return;
    }

    window.onbeforeunload = function () {
        var htmlVideo = video[0];
        if (htmlVideo.currentTime < 0.01 || htmlVideo.ended) {
            return null;
        }

        return "Leaving this page will stop your video.";
    };
}

Javascript Regular Expression Remove Spaces

This works just as well: http://jsfiddle.net/maniator/ge59E/3/

var reg = new RegExp(" ","g"); //<< just look for a space.

Check orientation on Android phone

Just simple two line code

if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
    // do something in landscape
} else {
    //do in potrait
}

What is the difference between MacVim and regular Vim?

MacVim is just Vim. Anything you are used to do in Vim will work exactly the same way in MacVim.

MacVim is more integrated in the whole OS than Vim in the Terminal or even GVim in Linux, it follows a lot of Mac OS X's conventions.

If you work mainly with GUI apps (YummyFTP + GitX + Charles, for example) you may prefer MacVim.

If you work mainly with CLI apps (ssh + svn + tcpdump, for example) you may prefer vim in the terminal.

Entering and leaving one realm (CLI) for the other (GUI) and vice-versa can be "expensive".

I use both MacVim and Vim depending on the task and the context: if I'm in CLI-land I'll just type vim filename and if I'm in GUI-land I'll just invoke Quicksilver and launch MacVim.

When I switched from TextMate I kind of liked the fact that MacVim supported almost all of the regular shortcuts Mac users are accustomed to. I added some of my own, mimiking TextMate but, since I was working in multiple environments I forced my self to learn the vim way. Now I use both MacVim and Vim almost exactly the same way. Using one or the other is just a question of context for me.

Also, like El Isra said, the default vim (CLI) in OS X is slightly outdated. You may install an up-to-date version via MacPorts or you can install MacVim and add an alias to your .profile:

alias vim='/path/to/MacVim.app/Contents/MacOS/Vim'

to have the same vim in MacVim and Terminal.app.

Another difference is that many great colorschemes out there work out of the box in MacVim but look terrible in the Terminal.app which only supports 8 colors (+ highlights) but you can use iTerm — which can be set up to support 256 colors — instead of Terminal.

So… basically my advice is to just use both.

EDIT: I didn't try it but the latest version of Terminal.app (in 10.7) is supposed to support 256 colors. I'm still on 10.6.x at work so I'll still use iTerm2 for a while.

EDIT: An even better way to use MacVim's CLI executable in your shell is to move the mvim script bundled with MacVim somewhere in your $PATH and use this command:

$ mvim -v

EDIT: Yes, Terminal.app now supports 256 colors. So if you don't need iTerm2's advanced features you can safely use the default terminal emulator.

How do I debug Windows services in Visual Studio?

You can also try this.

  1. Create your Windows service and install and start…. That is, Windows services must be running in your system.
  2. While your service is running, go to the Debug menu, click on Attach Process (or process in old Visual Studio)
  3. Find your running service, and then make sure the Show process from all users and Show processes in all sessions is selected, if not then select it.

enter image description here

  1. Click the Attach button
  2. Click OK
  3. Click Close
  4. Set a break point to your desirable location and wait for execute. It will debug automatic whenever your code reaches to that point.
  5. Remember, put your breakpoint at reachable place, if it is onStart(), then stop and start the service again

(After a lot of googling, I found this in "How to debug the Windows Services in Visual Studio".)

Verilog: How to instantiate a module

Be sure to check out verilog-mode and especially verilog-auto. http://www.veripool.org/wiki/verilog-mode/ It is a verilog mode for emacs, but plugins exist for vi(m?) for example.

An instantiation can be automated with AUTOINST. The comment is expanded with M-x verilog-auto and can afterwards be manually edited.

subcomponent subcomponent_instance_name(/*AUTOINST*/);

Expanded

subcomponent subcomponent_instance_name (/*AUTOINST*/
  //Inputs
  .clk,         (clk)           
  .rst_n,       (rst_n)
  .data_rx      (data_rx_1[9:0]),
  //Outputs
  .data_tx      (data_tx[9:0])
);

Implicit wires can be automated with /*AUTOWIRE*/. Check the link for further information.

C++ float array initialization

You only initialize the first N positions to the values in braces and all others are initialized to 0. In this case, N is the number of arguments you passed to the initialization list, i.e.,

float arr1[10] = { };       // all elements are 0
float arr2[10] = { 0 };     // all elements are 0
float arr3[10] = { 1 };     // first element is 1, all others are 0
float arr4[10] = { 1, 2 };  // first element is 1, second is 2, all others are 0

Nesting queries in SQL

Query below should help you achieve what you want.

select scountry, headofstate from data 
where data.scountry like 'a%'and ttlppl>=100000

How can I see CakePHP's SQL dump in the controller?

What worked finally for me and also compatible with 2.0 is to add in my layout (or in model)

<?php echo $this->element('sql_dump');?>

It is also depending on debug variable setted into Config/core.php

make image( not background img) in div repeat?

(DEMO)
Codes:

.backimage {width:99%;  height:98%;  position:absolute;    background:transparent url("http://upload.wikimedia.org/wikipedia/commons/4/41/Brickwall_texture.jpg") repeat scroll 0% 0%;  }

and

<div>
    <div class="backimage"></div>
    YOUR OTHER CONTENTTT
</div>

Origin http://localhost is not allowed by Access-Control-Allow-Origin

This approach resolved my issue to allow multiple domain

app.use(function(req, res, next) {
      var allowedOrigins = ['http://127.0.0.1:8020', 'http://localhost:8020', 'http://127.0.0.1:9000', 'http://localhost:9000'];
      var origin = req.headers.origin;
      if(allowedOrigins.indexOf(origin) > -1){
           res.setHeader('Access-Control-Allow-Origin', origin);
      }
      //res.header('Access-Control-Allow-Origin', 'http://127.0.0.1:8020');
      res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
      res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
      res.header('Access-Control-Allow-Credentials', true);
      return next();
    });

javascript setTimeout() not working

Use:

setTimeout(startTimer,startInterval); 

You're calling startTimer() and feed it's result (which is undefined) as an argument to setTimeout().

How to close <img> tag properly?

The best use of tags you should use:

<img src="" alt=""/>

Also you can use in HTML5:

<img src="" alt="">

These two are completely valid in HTML5 Pick one of them and stick with that.

Convert Go map to json

It actually tells you what's wrong, but you ignored it because you didn't check the error returned from json.Marshal.

json: unsupported type: map[int]main.Foo

JSON spec doesn't support anything except strings for object keys, while javascript won't be fussy about it, it's still illegal.

You have two options:

1 Use map[string]Foo and convert the index to string (using fmt.Sprint for example):

datas := make(map[string]Foo, N)

for i := 0; i < 10; i++ {
    datas[fmt.Sprint(i)] = Foo{Number: 1, Title: "test"}
}
j, err := json.Marshal(datas)
fmt.Println(string(j), err)

2 Simply just use a slice (javascript array):

datas2 := make([]Foo, N)
for i := 0; i < 10; i++ {
    datas2[i] = Foo{Number: 1, Title: "test"}
}
j, err = json.Marshal(datas2)
fmt.Println(string(j), err)

playground

JUnit 4 compare Sets

I like the solution of Hans-Peter Störr... But I think it is not quite correct. Sadly containsInAnyOrder does not accept a Collection of objetcs to compare to. So it has to be a Collection of Matchers:

assertThat(set1, containsInAnyOrder(set2.stream().map(IsEqual::equalTo).collect(toList())))

The import are:

import static java.util.stream.Collectors.toList;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.Assert.assertThat;

how to set default method argument values?

If your arguments are the same type you could use varargs:

public int something(int... args) {
    int a = 0;
    int b = 0;
    if (args.length > 0) {
      a = args[0];
    }
    if (args.length > 1) {
      b = args[1];
    }
    return a + b
}

but this way you lose the semantics of the individual arguments, or

have a method overloaded which relays the call to the parametered version

public int something() {
  return something(1, 2);
}

or if the method is part of some kind of initialization procedure, you could use the builder pattern instead:

class FoodBuilder {
   int saltAmount;
   int meatAmount;
   FoodBuilder setSaltAmount(int saltAmount) {
       this.saltAmount = saltAmount;
       return this;
   }
   FoodBuilder setMeatAmount(int meatAmount) {
       this.meatAmount = meatAmount;
       return this;
   }
   Food build() {
       return new Food(saltAmount, meatAmount);
   }
}

Food f = new FoodBuilder().setSaltAmount(10).build();
Food f2 = new FoodBuilder().setSaltAmount(10).setMeatAmount(5).build();

Then work with the Food object

int doSomething(Food f) {
    return f.getSaltAmount() + f.getMeatAmount();
}

The builder pattern allows you to add/remove parameters later on and you don't need to create new overloaded methods for them.

How to convert int to NSString?

NSString *string = [NSString stringWithFormat:@"%d", theinteger];

How to check if a Constraint exists in Sql server?

Just something to watch out for......

In SQL Server 2008 R2 SSMS, the "Script Constraint as -> DROP And CREATE To" command produces T-SQL like below

USE [MyDatabase]
GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DEF_Detail_IsDeleted]') AND type = 'D')
BEGIN
ALTER TABLE [Patient].[Detail] DROP CONSTRAINT [DEF_Detail_IsDeleted]
END

GO

USE [MyDatabase]
GO

ALTER TABLE [Patient].[Detail] ADD  CONSTRAINT [DEF_Detail_IsDeleted]  DEFAULT ((0)) FOR [IsDeleted]
GO

Out of the box, this script does NOT drop the constraint because the SELECT returns 0 rows. (see post Microsoft Connect).

The name of the default constraint is wrong but I gather it also has something to do with the OBJECT_ID function because changing the name doesn't fix the problem.

To fix this, I removed the usage of OBJECT_ID and used the default constraint name instead.

(SELECT * FROM dbo.sysobjects WHERE [name] = (N'DEF_Detail_IsDeleted') AND type = 'D')

php: Get html source code with cURL

Try http://php.net/manual/en/curl.examples-basic.php :)

<?php

$ch = curl_init("http://www.example.com/");
$fp = fopen("example_homepage.txt", "w");

curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

$output = curl_exec($ch);
curl_close($ch);
fclose($fp);
?>

As the documentation says:

The basic idea behind the cURL functions is that you initialize a cURL session using the curl_init(), then you can set all your options for the transfer via the curl_setopt(), then you can execute the session with the curl_exec() and then you finish off your session using the curl_close().

How do you add input from user into list in Python

code below allows user to input items until they press enter key to stop:

In [1]: items=[]
   ...: i=0
   ...: while 1:
   ...:     i+=1
   ...:     item=input('Enter item %d: '%i)
   ...:     if item=='':
   ...:         break
   ...:     items.append(item)
   ...: print(items)
   ...: 

Enter item 1: apple

Enter item 2: pear

Enter item 3: #press enter here
['apple', 'pear']

In [2]: 

How to prevent background scrolling when Bootstrap 3 modal open on mobile browsers?

I've found a simple javascript/jquery solution which utilizes the bootstrap modal events.

My solution also fixes the position:fixed problem where it scrolls the background page all the way back to the top instead of staying in place when modal window is opened/closed.

See details here

File Not Found when running PHP with Nginx

I had been having the same issues, And during my tests, I have faced both problems:

1º: "File not found"

and

2º: 404 Error page

And I found out that, in my case:

I had to mount volumes for my public folders both on the Nginx volumes and the PHP volumes.

If it's mounted in Nginx and is not mounted in PHP, it will give: "File not found"

Examples (Will show "File not found error"):


services:
  php-fpm:
    build:
      context: ./docker/php-fpm
  nginx:
    build:
      context: ./docker/nginx
    volumes:
        #Nginx Global Configurations
      - ./docker/nginx/nginx.conf:/etc/nginx/nginx.conf
      - ./docker/nginx/conf.d/:/etc/nginx/conf.d

        #Nginx Configurations for you Sites:

        # - Nginx Server block
      - ./sites/example.com/site.conf:/etc/nginx/sites-available/example.com.conf
        # - Copy Public Folder:
      - ./sites/example.com/root/public/:/var/www/example.com/public
    ports:
      - "80:80"
      - "443:443"
    depends_on:
      - php-fpm
    restart: always

If it's mounted in PHP and is not mounted in Nginx, it will give a 404 Page Not Found error.

Example (Will throw 404 Page Not Found Error):

version: '3'

services:
  php-fpm:
    build:
      context: ./docker/php-fpm
    volumes:
      - ./sites/example.com/root/public/:/var/www/example.com/public
  nginx:
    build:
      context: ./docker/nginx
    volumes:
        #Nginx Global Configurations
      - ./docker/nginx/nginx.conf:/etc/nginx/nginx.conf
      - ./docker/nginx/conf.d/:/etc/nginx/conf.d

        #Nginx Configurations for you Sites:

        # - Nginx Server block
      - ./sites/example.com/site.conf:/etc/nginx/sites-available/example.com.conf
    ports:
      - "80:80"
      - "443:443"
    depends_on:
      - php-fpm
    restart: always

And this would work just fine (mounting on both sides) (Assuming everything else is well configured and you're facing the same problem as me):

version: '3'

services:
  php-fpm:
    build:
      context: ./docker/php-fpm
    volumes:
      # Mount PHP for Public Folder
      - ./sites/example.com/root/public/:/var/www/example.com/public
  nginx:
    build:
      context: ./docker/nginx
    volumes:
        #Nginx Global Configurations
      - ./docker/nginx/nginx.conf:/etc/nginx/nginx.conf
      - ./docker/nginx/conf.d/:/etc/nginx/conf.d

        #Nginx Configurations for you Sites:

        # - Nginx Server block
      - ./sites/example.com/site.conf:/etc/nginx/sites-available/example.com.conf
        # - Copy Public Folder:
      - ./sites/example.com/root/public/:/var/www/example.com/public
    ports:
      - "80:80"
      - "443:443"
    depends_on:
      - php-fpm
    restart: always

Also here's a Full working example project using Nginx/Php, for serving multiple sites: https://github.com/Pablo-Camara/simple-multi-site-docker-compose-nginx-alpine-php-fpm-alpine-https-ssl-certificates

I hope this helps someone, And if anyone knows more about this please let me know, Thanks!

while installing vc_redist.x64.exe, getting error "Failed to configure per-machine MSU package."

I would like to give you a background on Universal CRT this would help you in understanding as to why the system should be updated before installing vc_redist.x64.exe.

  1. A large portion of the C-runtime moved into the OS in Windows 10 (ucrtbase.dll) and is serviced just like any other OS DLL (e.g. kernel32.dll). It is no longer serviced by Visual Studio directly. MSU packages are the file type for Windows Updates.
  2. In order to get the Windows 10 Universal CRT to earlier OSes, Windows Update packages were created to bring this OS component downlevel. KB2999226 brings the Windows 10 RTM Universal CRT to downlevel platforms (Windows Vista through Windows 8.1). KB3118401 brings Windows 10 November Update to the Universal CRT to downlevel platforms.
    • Windows XP (latest SP) is an exception here. Windows Servicing does not provide downlevel packages for that OS, so Visual Studio (Visual C++) provides a mechanism to install the UCRT into System32 via the VCRedist and MSMs.
  3. The Windows Universal Runtime is included in the VC Redist exe package as it has dependency on the Windows Universal Runtime (KB2999226).
  4. Windows 10 is the only OS that ships the UCRT in-box. All prior OSes obtain the UCRT via Windows Update only. This applies to all Vista->8.1 and associated Server SKUs.

For Windows 7, 8, and 8.1 the Windows Universal Runtime must be installed via KB2999226. However it has a prerequisite update KB2919355 which contains updates that facilitate installing the KB2999226 package.

Why does KB2999226 not always install when the runtime is installed from the redistributable? What could prevent KB2999226 from installing as part of the runtime?

The UCRT MSU included in the VCRedist is installed by making a call into the Windows Update service and the KB can fail to install based upon Windows Update service activity/state:

  1. If the machine has not updated to the required servicing baseline, the UCRT MSU will be viewed as being “Not Applicable”. Ensure KB2919355 is installed. Also, there were known issues with KB2919355 so before this the following hotfix should be installed. KB2939087 KB2975061
  2. If the Windows Update service is installing other updates when the VCRedist installs, you can either see long delays or errors indicating the machine is busy.
    • This one can be resolved by waiting and trying again later (which may be why installing via Windows Update UI at a later time succeeds).
  3. If the Windows Update service is in a non-ready state, you can see errors reflecting that.

    • We recently investigated a failure with an error code indicating the WUSA service was shutting down.
  4. To identify if the prerequisite KB2919355 is installed there are 2 options:

    1. Registry key: 64bit hive

      HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\Packages\Package_for_KB2919355~31bf3856ad364e35~amd64~~6.3.1.14
      CurrentState = 112
      

      32bit hive

      HKLM\SOFTWARE\[WOW6432Node\]Microsoft\Windows\CurrentVersion\Component Based Servicing\Packages\Package_for_KB2919355~31bf3856ad364e35~x86~~6.3.1.14
      CurrentState = 112
      
    2. Or check the file version of:

      C:\Windows\SysWOW64\wuaueng.dll
      C:\Windows\System32\wuaueng.dll
      

      is 7.9.9600.17031 or later

How to embed a Facebook page's feed into my website

Correct me if I am wrong, but it seems that Facebook deprecated the Activity Feed plugin. Additionally there does not seem to be any substitute plugin for activity anymore.

Here is the link: https://developers.facebook.com/docs/plugins/activity

Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes

By process (in the JSF specification it's called execute) you tell JSF to limit the processing to component that are specified every thing else is just ignored.

update indicates which element will be updated when the server respond back to you request.

@all : Every component is processed/rendered.

@this: The requesting component with the execute attribute is processed/rendered.

@form : The form that contains the requesting component is processed/rendered.

@parent: The parent that contains the requesting component is processed/rendered.

With Primefaces you can even use JQuery selectors, check out this blog: http://blog.primefaces.org/?p=1867

Set bootstrap modal body height by percentage

This worked for me

.modal-dialog,
.modal-content {
    /* 80% of window height */
    height: 80%;
}

.modal-body {
    /* 100% = dialog height, 120px = header + footer */
    max-height: calc(100% - 120px);
    overflow-y: scroll;
}

Fiddle: http://jsfiddle.net/mehmetatas/18dpgqpb/2/

c++ array - expression must have a constant value

The standard requires the array length to be a value that is computable at compile time so that the compiler is able to allocate enough space on the stack. In your case, you are trying to set the array length to a value that is unknown at compile time. Yes, i know that it seems obvious that it should be known to the compiler, but this is not the case here. The compiler cannot make any assumptions about the contents of non-constant variables. So go with:

const int row = 8;
const int col= 8;
int a[row][col];

UPD: some compilers will actually allow you to pull this off. IIRC, g++ has this feature. However, never use it because your code will become un-portable across compilers.

PHP: How to handle <![CDATA[ with SimpleXMLElement?

You're probably not accessing it correctly. You can output it directly or cast it as a string. (in this example, the casting is superfluous, as echo automatically does it anyway)

$content = simplexml_load_string(
    '<content><![CDATA[Hello, world!]]></content>'
);
echo (string) $content;

// or with parent element:

$foo = simplexml_load_string(
    '<foo><content><![CDATA[Hello, world!]]></content></foo>'
);
echo (string) $foo->content;

You might have better luck with LIBXML_NOCDATA:

$content = simplexml_load_string(
    '<content><![CDATA[Hello, world!]]></content>'
    , null
    , LIBXML_NOCDATA
);

Can I compile all .cpp files in src/ to .o's in obj/, then link to binary in ./?

Wildcard works for me also, but I'd like to give a side note for those using directory variables. Always use slash for folder tree (not backslash), otherwise it will fail:

BASEDIR = ../..
SRCDIR = $(BASEDIR)/src
INSTALLDIR = $(BASEDIR)/lib

MODULES = $(wildcard $(SRCDIR)/*.cpp)
OBJS = $(wildcard *.o)

WinForms DataGridView font size

I too experienced same problem in the DataGridView but figured out that the DefaultCell style was inheriting the font of the groupbox (Datagrid is placed in groupbox). So changing the font of the groupbox changed the DefaultCellStyle too.

Regards

How to get a jqGrid cell value when editing

I have a solution: 1. Using this.value to get the current editing value in the editing row. 2. Save the cell value to a hidden field when the cell lost its focus. 3. Read the hidden field when you need.

The code:

 colModel="[
       { name: 'Net', index: 'Net', editable:true, editoptions: { dataEvents: [ { type: 'focusout', fn: function(e) {$('#HiddenNet').val(this.value);} }] }, editrules:{custom:true,}},
       { name: 'Tax', index: 'Tax', editable:true, editoptions: { dataEvents: [ { type: 'focus', fn: function(e) {this.value=$('#HiddenNet').val(); } }] }, editrules:{custom:true}}
    ]" 

Good Luck

Remove quotes from a character vector in R

If:

> char<-c("one", "two", "three")

You can:

> print(char[1],quote = FALSE)

Your result should be:

[1] one

Java URL encoding of query string parameters

I would not use URLEncoder. Besides being incorrectly named (URLEncoder has nothing to do with URLs), inefficient (it uses a StringBuffer instead of Builder and does a couple of other things that are slow) Its also way too easy to screw it up.

Instead I would use URIBuilder or Spring's org.springframework.web.util.UriUtils.encodeQuery or Commons Apache HttpClient. The reason being you have to escape the query parameters name (ie BalusC's answer q) differently than the parameter value.

The only downside to the above (that I found out painfully) is that URL's are not a true subset of URI's.

Sample code:

import org.apache.http.client.utils.URIBuilder;

URIBuilder ub = new URIBuilder("http://example.com/query");
ub.addParameter("q", "random word £500 bank \$");
String url = ub.toString();

// Result: http://example.com/query?q=random+word+%C2%A3500+bank+%24

Since I'm just linking to other answers I marked this as a community wiki. Feel free to edit.

How to serialize Joda DateTime with Jackson JSON processor?

https://stackoverflow.com/a/10835114/1113510

Although you can put an annotation for each date field, is better to do a global configuration for your object mapper. If you use jackson you can configure your spring as follow:

<bean id="jacksonObjectMapper" class="com.company.CustomObjectMapper" />

<bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"
    factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" >
</bean>

For CustomObjectMapper:

public class CustomObjectMapper extends ObjectMapper {

    public CustomObjectMapper() {
        super();
        configure(Feature.WRITE_DATES_AS_TIMESTAMPS, false);
        setDateFormat(new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'ZZZ (z)"));
    }
}

Of course, SimpleDateFormat can use any format you need.

What are the differences between .so and .dylib on osx?

Just an observation I just made while building naive code on OSX with cmake:

cmake ... -DBUILD_SHARED_LIBS=OFF ...

creates .so files

while

cmake ... -DBUILD_SHARED_LIBS=ON ...

creates .dynlib files.

Perhaps this helps anyone.

Edit a text file on the console using Powershell

Bit of a resurrect but for anyone else coming to this question, take a look at the Micro editor. It's a small standalone EXE with no dependencies and with native Windows 32\64 versions. Works well in both PowerShell and CMD.EXE.

enter image description here

python date of the previous month

With the Pendulum very complete library, we have the subtract method (and not "subStract"):

import pendulum
today = pendulum.datetime.today()  # 2020, january
lastmonth = today.subtract(months=1)
lastmonth.strftime('%Y%m')
# '201912'

We see that it handles jumping years.

The reverse equivalent is add.

https://pendulum.eustace.io/docs/#addition-and-subtraction

Php artisan make:auth command is not defined

In Laravel 6.0 make:auth no longer exists. Read more here

A- Shorthand:

Update Nov 18th: Taylor just released Laravel Installer 2.3.0 added a new "--auth" flag to create a new project with the authentication scaffolding installed!

To update laravel installer read here

It means we can do:

laravel new project --auth

cd project

php artisan migrate

npm install
npm run dev

Which is a shorthand of commands in the Section B. Also read more here


B - Details:

Follow these three steps

Step 1 - First do this:

laravel new project

cd project

composer require laravel/ui --dev

Note: Laravel UI Composer package is a new first-party package that extracts the UI portion of a Laravel project ( frontend scaffolding typically provided with previous releases of Laravel ) into a separate laravel/ui package. The separate package enables the Laravel team to update, develop and version UI scaffolding package separately from the primary framework and the main Laravel codebase.

Step 2 - Then do this:

php artisan ui bootstrap --auth
php artisan migrate

or

php artisan ui vue --auth
php artisan migrate

instead of

php artisan make:auth  ( which works for Laravel 5.8 and older versions )

More Options here

php artisan ui:auth

The above command will generate only the auth routes, a HomeController, auth views, and a app.blade.php layout file.

You can also generate the views only with:

php artisan ui:auth --views

The console command will prompt you to confirm overwriting auth files if you've already run the command before.

// Generate basic scaffolding...
php artisan ui vue
php artisan ui react

and also:

// Generate login / registration scaffolding...
php artisan ui vue --auth
php artisan ui react --auth

To see differences read this article

Step 3 - Then you need to do:

npm install
npm run dev

The program can't start because cygwin1.dll is missing... in Eclipse CDT

You can compile with either Cygwin's g++ or MinGW (via stand-alone or using Cygwin package). However, in order to run it, you need to add the Cygwin1.dll (and others) PATH to the system Windows PATH, before any cygwin style paths.

Thus add: ;C:\cygwin64\bin to the end of your Windows system PATH variable.

Also, to compile for use in CMD or PowerShell, you may need to use:

x86_64-w64-mingw32-g++.exe -static -std=c++11 prog_name.cc -o prog_name.exe

(This invokes the cross-compiler, if installed.)

Responsive web design is working on desktop but not on mobile device

Though it is answered above and it is right to use

<meta name="viewport" content="width=device-width, initial-scale=1">

but if you are using React and webpack then don't forget to close the element tag

<meta name="viewport" content="width=device-width, initial-scale=1" />

Changing file extension in Python

As AnaPana mentioned pathlib is more new and easier in python 3.4 and there is new with_suffix method that can handle this problem easily:

from pathlib import Path
new_filename = Path(mysequence.fasta).with_suffix('.aln')

jQuery and AJAX response header

UPDATE 2018 FOR JQUERY 3 AND LATER

I know this is an old question but none of the above solutions worked for me. Here is the solution that worked:

//I only created this function as I am making many ajax calls with different urls and appending the result to different divs
function makeAjaxCall(requestType, urlTo, resultAreaId){
        var jqxhr = $.ajax({
            type: requestType,
            url: urlTo
        });
        //this section is executed when the server responds with no error 
        jqxhr.done(function(){

        });
        //this section is executed when the server responds with error
        jqxhr.fail(function(){

        })
        //this section is always executed
        jqxhr.always(function(){
            console.log("getting header " + jqxhr.getResponseHeader('testHeader'));
        });
    }

How to add Tomcat Server in eclipse

There are different eclipse plugins available to manage Tomcat server and create war file.

For example you can use tomcatPlugin. It permits to start/stop and build the war simply. You can read this tutorial.

To prevent a memory leak, the JDBC Driver has been forcibly unregistered

I was having a similar problem, but additionally I was getting a Java Heap Space error anytime I modified/saved JSP pages with Tomcat server running, therefore the context were not fully recharged.

My versions were Apache Tomcat 6.0.29 and JDK 6u12.

Upgrading JDK to 6u21 as suggested in References section of URL http://wiki.apache.org/tomcat/MemoryLeakProtection solved the Java Heap Space problem (context now reloads OK) although JDBC Driver error still appears.

Read file from resources folder in Spring Boot

stuck in the same issue, this helps me

URL resource = getClass().getClassLoader().getResource("jsonschema.json");
JsonNode jsonNode = JsonLoader.fromURL(resource);

How to implement infinity in Java?

The Double and Float types have the POSITIVE_INFINITY constant.

Angular 2 - Using 'this' inside setTimeout

You need to use Arrow function ()=> ES6 feature to preserve this context within setTimeout.

// var that = this;                             // no need of this line
this.messageSuccess = true;

setTimeout(()=>{                           //<<<---using ()=> syntax
      this.messageSuccess = false;
 }, 3000);

powershell - extract file name and extension

Check the BaseName and Extension properties of the FileInfo object.

jQuery window scroll event does not fire up

In my case you should put the function in $(document).ready

$(document).ready(function () {
    $('div#page').on('scroll', function () {
     ...
    });
});

How to remove duplicate white spaces in string using Java?

You can also try using String Tokeniser, for any space, tab, newline, and all. A simple way is,

String s = "Your Text Here";        
StringTokenizer st = new StringTokenizer( s, " " );
while(st.hasMoreTokens())
{
    System.out.print(st.nextToken());
}

Adding a module (Specifically pymorph) to Spyder (Python IDE)

just use '!' before the pip command in spyder terminal and it will be fine

Eg:

!pip install imutils

How can I programmatically check whether a keyboard is present in iOS app?

This is my solution, it encapsulates everything into a single static method, and you can call it anywhere to check:

+(BOOL)isKeyboardVisible{
    static id tokenKeyboardWillShow = nil;
    static id tokenKeyboardWillHide = nil;
    static BOOL isKbVisible = NO;
    @synchronized (self) {
        if (tokenKeyboardWillShow == nil){
            tokenKeyboardWillShow = [[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillShowNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
                @synchronized (self) {
                    isKbVisible = YES;
                }
            }];
        }

        if (tokenKeyboardWillHide == nil){
            tokenKeyboardWillHide = [[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillHideNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
                @synchronized (self) {
                    isKbVisible = NO;
                }
            }];
        }
    }

    return isKbVisible;
}

Large WCF web service request failing with (400) HTTP Bad Request

Just want to point out

Apart from MaxRecivedMessageSize, there are also attributes under ReaderQuotas, you might hit number of items limit instead of size limit. MSDN link is here

error CS0103: The name ' ' does not exist in the current context

Simply move the declaration outside of the if block.

@{
string currentstore=HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
string imgsrc="";
if (currentstore == "www.mydomain.com")
    {
    <link href="/path/to/my/stylesheets/styles1-print.css" rel="stylesheet" type="text/css" />
    imgsrc="/content/images/uploaded/store1_logo.jpg";
    }
else
    {
    <link href="/path/to/my/stylesheets/styles2-print.css" rel="stylesheet" type="text/css" />
    imgsrc="/content/images/uploaded/store2_logo.gif";
    }
}

<a href="@Url.RouteUrl("HomePage")" class="logo"><img  alt="" src="@imgsrc"></a>

You could make it a bit cleaner.

@{
string currentstore=HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
string imgsrc="/content/images/uploaded/store2_logo.gif";
if (currentstore == "www.mydomain.com")
    {
    <link href="/path/to/my/stylesheets/styles1-print.css" rel="stylesheet" type="text/css" />
    imgsrc="/content/images/uploaded/store1_logo.jpg";
    }
else
    {
    <link href="/path/to/my/stylesheets/styles2-print.css" rel="stylesheet" type="text/css" />
    }
}

Perform debounce in React.js

a little late here but this should help. create this class(its written in typescript but its easy to convert it to javascript)

export class debouncedMethod<T>{
  constructor(method:T, debounceTime:number){
    this._method = method;
    this._debounceTime = debounceTime;
  }
  private _method:T;
  private _timeout:number;
  private _debounceTime:number;
  public invoke:T = ((...args:any[])=>{
    this._timeout && window.clearTimeout(this._timeout);
    this._timeout = window.setTimeout(()=>{
      (this._method as any)(...args);
    },this._debounceTime);
  }) as any;
}

and to use

var foo = new debouncedMethod((name,age)=>{
 console.log(name,age);
},500);
foo.invoke("john",31);

Add a background image to shape in XML Android

I used the following for a drawable image with a circular background.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">
            <solid android:color="@color/colorAccent"/>
        </shape>
    </item>
    <item
        android:drawable="@drawable/ic_select"
        android:bottom="20dp"
        android:left="20dp"
        android:right="20dp"
        android:top="20dp"/>
</layer-list>

Here is what it looks like

enter image description here

Hope that helps someone out.

Index of element in NumPy array

You can convert a numpy array to list and get its index .

for example:

tmp = [1,2,3,4,5] #python list
a = numpy.array(tmp) #numpy array
i = list(a).index(2) # i will return index of 2, which is 1

this is just what you wanted.

JavaScript hard refresh of current page

window.location.href = window.location.href

How to take MySQL database backup using MySQL Workbench?

In Workbench 6.3 it is supereasy:

  1. On the "HOME"-view select one of the MySQL Connections: (localhost)
  2. In the "Localhost" view click on "Server"--> "Data export"
  3. In the "Data Export" view select the table(s) and whether you want to export only their structure, or structure and data,...
  4. Click "Start Export"

chrome : how to turn off user agent stylesheet settings?

https://developers.google.com/chrome-developer-tools/docs/settings

  1. Open Chrome dev tools
  2. Click gear icon on bottom right
  3. In General section, check or uncheck "Show user agent styles".

Iterating through populated rows

It looks like you just hard-coded the row and column; otherwise, a couple of small tweaks, and I think you're there:

Dim sh As Worksheet
Dim rw As Range
Dim RowCount As Integer

RowCount = 0

Set sh = ActiveSheet
For Each rw In sh.Rows

  If sh.Cells(rw.Row, 1).Value = "" Then
    Exit For
  End If

  RowCount = RowCount + 1

Next rw

MsgBox (RowCount)

MySQL: View with Subquery in the FROM Clause Limitation

You can work around this by creating a separate VIEW for any subquery you want to use and then join to that in the VIEW you're creating. Here's an example: http://blog.gruffdavies.com/2015/01/25/a-neat-mysql-hack-to-create-a-view-with-subquery-in-the-from-clause/

This is quite handy as you'll very likely want to reuse it anyway and helps you keep your SQL DRY.

Undefined reference to vtable

In my case I'm using Qt and had defined a QObject subclass in a foo.cpp (not .h) file. The fix was to add #include "foo.moc" at the end of foo.cpp.

Getting all types in a namespace via reflection

You won't be able to get all types in a namespace, because a namespace can bridge multiple assemblies, but you can get all classes in an assembly and check to see if they belong to that namespace.

Assembly.GetTypes() works on the local assembly, or you can load an assembly first then call GetTypes() on it.

RSA: Get exponent and modulus given a public key

I manage to find the answer for this solution, have to do javascript injection for this to install atob

const atob:any = require('atob');
asn1(pem: any){
      asn1parser.Enc.base64ToBuf = function (b64:any) {
    return asn1parser.Enc.binToBuf(atob(b64));
  };
  const dertest = asn1parser.PEM.parseBlock(pem).der;
   var hex = asn1parser.Enc.bufToHex(asn1parser.PEM.parseBlock(pem).der)
   var buf = asn1parser.ASN1.parse(dertest);
  var asn1 = JSON.stringify(asn1parser.ASN1.parse(dertest), asn1parser.ASN1._replacer, 2 );

Importing Maven project into Eclipse

I find the m2eclipse plugin to be more useful. This provides nice tools like the POM editor and creating a Maven project from within Eclipse.

Text-decoration: none not working

if you want a nav bar do

ul{ list-style-type: none; } li{text-decoration: none;
  • This will make it want to make the style of the list type to None or nothing

with the < a > tag:

a:link {text-decoration: none}

How can I play sound in Java?

I created a game framework sometime ago to work on Android and Desktop, the desktop part that handle sound maybe can be used as inspiration to what you need.

https://github.com/hamilton-lima/jaga/blob/master/jaga%20desktop/src-desktop/com/athanazio/jaga/desktop/sound/Sound.java

Here is the code for reference.

package com.athanazio.jaga.desktop.sound;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

public class Sound {

    AudioInputStream in;

    AudioFormat decodedFormat;

    AudioInputStream din;

    AudioFormat baseFormat;

    SourceDataLine line;

    private boolean loop;

    private BufferedInputStream stream;

    // private ByteArrayInputStream stream;

    /**
     * recreate the stream
     * 
     */
    public void reset() {
        try {
            stream.reset();
            in = AudioSystem.getAudioInputStream(stream);
            din = AudioSystem.getAudioInputStream(decodedFormat, in);
            line = getLine(decodedFormat);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void close() {
        try {
            line.close();
            din.close();
            in.close();
        } catch (IOException e) {
        }
    }

    Sound(String filename, boolean loop) {
        this(filename);
        this.loop = loop;
    }

    Sound(String filename) {
        this.loop = false;
        try {
            InputStream raw = Object.class.getResourceAsStream(filename);
            stream = new BufferedInputStream(raw);

            // ByteArrayOutputStream out = new ByteArrayOutputStream();
            // byte[] buffer = new byte[1024];
            // int read = raw.read(buffer);
            // while( read > 0 ) {
            // out.write(buffer, 0, read);
            // read = raw.read(buffer);
            // }
            // stream = new ByteArrayInputStream(out.toByteArray());

            in = AudioSystem.getAudioInputStream(stream);
            din = null;

            if (in != null) {
                baseFormat = in.getFormat();

                decodedFormat = new AudioFormat(
                        AudioFormat.Encoding.PCM_SIGNED, baseFormat
                                .getSampleRate(), 16, baseFormat.getChannels(),
                        baseFormat.getChannels() * 2, baseFormat
                                .getSampleRate(), false);

                din = AudioSystem.getAudioInputStream(decodedFormat, in);
                line = getLine(decodedFormat);
            }
        } catch (UnsupportedAudioFileException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (LineUnavailableException e) {
            e.printStackTrace();
        }
    }

    private SourceDataLine getLine(AudioFormat audioFormat)
            throws LineUnavailableException {
        SourceDataLine res = null;
        DataLine.Info info = new DataLine.Info(SourceDataLine.class,
                audioFormat);
        res = (SourceDataLine) AudioSystem.getLine(info);
        res.open(audioFormat);
        return res;
    }

    public void play() {

        try {
            boolean firstTime = true;
            while (firstTime || loop) {

                firstTime = false;
                byte[] data = new byte[4096];

                if (line != null) {

                    line.start();
                    int nBytesRead = 0;

                    while (nBytesRead != -1) {
                        nBytesRead = din.read(data, 0, data.length);
                        if (nBytesRead != -1)
                            line.write(data, 0, nBytesRead);
                    }

                    line.drain();
                    line.stop();
                    line.close();

                    reset();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

Watch multiple $scope attributes

You can use functions in $watchGroup to select fields of an object in scope.

        $scope.$watchGroup(
        [function () { return _this.$scope.ViewModel.Monitor1Scale; },   
         function () { return _this.$scope.ViewModel.Monitor2Scale; }],  
         function (newVal, oldVal, scope) 
         {
             if (newVal != oldVal) {
                 _this.updateMonitorScales();
             }
         });

Command line tool to dump Windows DLL version?

and one way with makecab:

; @echo off
;;goto :end_help
;;setlocal DsiableDelayedExpansion
;;;
;;;
;;; fileinf /l list of full file paths separated with ;
;;; fileinf /f text file with a list of files to be processed ( one on each line )
;;; fileinf /? prints the help
;;;
;;:end_help

; REM Creating a Newline variable (the two blank lines are required!)
; set NLM=^


; set NL=^^^%NLM%%NLM%^%NLM%%NLM%
; if "%~1" equ "/?" type "%~f0" | find ";;;" | find /v "find" && exit /b 0
; if "%~2" equ "" type "%~f0" | find ";;;" | find /v "find" && exit /b 0
; setlocal enableDelayedExpansion
; if "%~1" equ "/l" (
;  set "_files=%~2"
;  echo !_files:;=%NL%!>"%TEMP%\file.paths"
;  set _process_file="%TEMP%\file.paths"
;  goto :get_info
; )

; if "%~1" equ "/f" if exist "%~2" (
;  set _process_file="%~2"
;  goto :get_info
; )

; echo incorect parameters & exit /b 1
; :get_info
; set "file_info="

; makecab /d InfFileName=%TEMP%\file.inf /d "DiskDirectory1=%TEMP%" /f "%~f0"  /f %_process_file% /v0>nul

; for /f "usebackq skip=4 delims=" %%f in ("%TEMP%\file.inf") do (
;  set "file_info=%%f"
;  echo !file_info:,=%nl%!
; )

; endlocal
;endlocal
; del /q /f %TEMP%\file.inf 2>nul
; del /q /f %TEMP%\file.path 2>nul
; exit /b 0

.set DoNotCopyFiles=on
.set DestinationDir=;
.set RptFileName=nul
.set InfFooter=;
.set InfHeader=;
.Set ChecksumWidth=8
.Set InfDiskLineFormat=;
.Set Cabinet=off
.Set Compress=off
.Set GenerateInf=ON
.Set InfDiskHeader=;
.Set InfFileHeader=;
.set InfCabinetHeader=;
.Set InfFileLineFormat=",file:*file*,date:*date*,size:*size*,csum:*csum*,time:*time*,vern:*ver*,vers:*vers*,lang:*lang*"

example output (it has a string version which is a small addition to wmic method :) ):

c:> fileinfo.bat /l C:\install.exe
    file:install.exe
    date:11/07/07
    size:562688
    csum:380ef239
    time:07:03:18a
    vern:9.0.21022.8
    vers:9.0.21022.8 built by: RTM
    lang:1033

and one more Using shell.application and hybrid batch\jscript.Here's tooptipInfo.bat :

@if (@X)==(@Y) @end /* JScript comment
    @echo off

    rem :: the first argument is the script name as it will be used for proper help message
    cscript //E:JScript //nologo "%~f0" %*

    exit /b %errorlevel%

@if (@X)==(@Y) @end JScript comment */

////// 
FSOObj = new ActiveXObject("Scripting.FileSystemObject");
var ARGS = WScript.Arguments;
if (ARGS.Length < 1 ) {
 WScript.Echo("No file passed");
 WScript.Quit(1);
}
var filename=ARGS.Item(0);
var objShell=new ActiveXObject("Shell.Application");
/////


//fso
ExistsItem = function (path) {
    return FSOObj.FolderExists(path)||FSOObj.FileExists(path);
}

getFullPath = function (path) {
    return FSOObj.GetAbsolutePathName(path);
}
//

//paths
getParent = function(path){
    var splitted=path.split("\\");
    var result="";
    for (var s=0;s<splitted.length-1;s++){
        if (s==0) {
            result=splitted[s];
        } else {
            result=result+"\\"+splitted[s];
        }
    }
    return result;
}


getName = function(path){
    var splitted=path.split("\\");
    return splitted[splitted.length-1];
}
//

function main(){
    if (!ExistsItem(filename)) {
        WScript.Echo(filename + " does not exist");
        WScript.Quit(2);
    }
    var fullFilename=getFullPath(filename);
    var namespace=getParent(fullFilename);
    var name=getName(fullFilename);
    var objFolder=objShell.NameSpace(namespace);
    var objItem=objFolder.ParseName(name);
    //https://msdn.microsoft.com/en-us/library/windows/desktop/bb787870(v=vs.85).aspx
    WScript.Echo(fullFilename + " : ");
    WScript.Echo(objFolder.GetDetailsOf(objItem,-1));

}

main();

used against cmd.exe :

C:\Windows\System32\cmd.exe :
File description: Windows Command Processor
Company: Microsoft Corporation
File version: 6.3.9600.16384
Date created: ?22-?Aug-?13 ??13:03
Size: 347 KB

Could not resolve '...' from state ''

Had the same issue with Ionic routing.

Simple solution is to use the name of the state - basically state.go(state name)

.state('tab.search', {
    url: '/search',
    views: {
      'tab-search': {
        templateUrl: 'templates/search.html',
        controller: 'SearchCtrl'
      }
    }
  })

And in controller you can use $state.go('tab.search');

Having a UITextField in a UITableViewCell

I ran into the same problem. It seems that setting the cell.textlabel.text property brings the UILabel to the front of the contentView of the cell. Add the textView after setting textLabel.text, or (if that's not possible) call this:

[cell.contentView bringSubviewToFront:textField]

How to expand textarea width to 100% of parent (or how to expand any HTML element to 100% of parent width)?

_x000D_
_x000D_
<div>_x000D_
  <div style="width: 20%; float: left;">_x000D_
    <p>Some Contentsssssssssss</p>_x000D_
  </div>_x000D_
  <div style="float: left; width: 80%;">_x000D_
    <textarea style="width: 100%; max-width: 100%;"></textarea>_x000D_
  </div>_x000D_
  <div style="clear: both;"></div>_x000D_
</div>_x000D_
_x000D_
 
_x000D_
_x000D_
_x000D_

what is the use of "response.setContentType("text/html")" in servlet

It means what type of response you want to send to client, some content types like :

 res.setContentType("image/gif");
 res.setContentType("application/pdf");
 res.setContentType("application/zip");

How to split a number into individual digits in c#?

Here is some code that might help you out. Strings can be treated as an array of characters

string numbers = "12345";
int[] intArray = new int[numbers.Length];
for (int i=0; i < numbers.Length; i++)
{
   intArray[i] = int.Parse(numbers[i]);
}

jquery equivalent for JSON.stringify

There is no such functionality in jQuery. Use JSON.stringify or alternatively any jQuery plugin with similar functionality (e.g jquery-json).

Remove last item from array

var arr = [1,0,2];
arr.length--; 

// removes the last element // need to check if arr.length > 0

Perl - If string contains text?

For case-insensitive string search, use index (or rindex) in combination with fc. This example expands on the answer by Eugene Yarmash:

use feature qw( fc ); 
my $str = "Abc"; 
my $substr = "aB"; 

print "found" if index( fc $str, fc $substr ) != -1;
# Prints: found

print "found" if rindex( fc $str, fc $substr ) != -1;
# Prints: found

$str = "Abc";
$substr = "bA";

print "found" if index( fc $str, fc $substr ) != -1;
# Prints nothing

print "found" if rindex( fc $str, fc $substr ) != -1;
# Prints nothing

Both index and rindex return -1 if the substring is not found.
And fc returns a casefolded version of its string argument, and should be used here instead of the (more familiar) uc or lc. Remember to enable this function, for example with use feature qw( fc );.

How to start Spyder IDE on Windows

After pip install spyder give this command

pip install --upgrade spyder

This command will update all Spyder dependencies.

Now in command prompt(cmd) navigate to the scripts folder in your python directory. In my system the path is C:\Users\win10\AppData\Local\Programs\Python\Python36-32\Scripts so i use the following command in command prompt.

cd C:\Users\win10\AppData\Local\Programs\Python\Python36-32\Scripts

once you are inside scripts directory type spyder3 and press enter and spyder ide starts.

C:\Users\win10\AppData\Local\Programs\Python\Python36-32\Scripts>spyder3

PHP Array to CSV

It worked for me.

 $f=fopen('php://memory','w');
 $header=array("asdf ","asdf","asd","Calasdflee","Start Time","End Time" );      
 fputcsv($f,$header);
 fputcsv($f,$header);
 fputcsv($f,$header); 
 fseek($f,0);
 header('content-type:text/csv'); 
 header('Content-Disposition: attachment; filename="' . $filename . '";');
 fpassthru($f);```

How do relative file paths work in Eclipse?

A project's build path defines which resources from your source folders are copied to your output folders. Usually this is set to Include all files.

New run configurations default to using the project directory for the working directory, though this can also be changed.

This code shows the difference between the working directory, and the location of where the class was loaded from:

public class TellMeMyWorkingDirectory {
    public static void main(String[] args) {
        System.out.println(new java.io.File("").getAbsolutePath());
        System.out.println(TellMeMyWorkingDirectory.class.getClassLoader().getResource("").getPath());
    }
}

The output is likely to be something like:

C:\your\project\directory
/C:/your/project/directory/bin/

How can I check if a command exists in a shell script?

which <cmd>

also see options which supports for aliases if applicable to your case.

Example

$ which foobar
which: no foobar in (/usr/local/bin:/usr/bin:/cygdrive/c/Program Files (x86)/PC Connectivity Solution:/cygdrive/c/Windows/system32/System32/WindowsPowerShell/v1.0:/cygdrive/d/Program Files (x86)/Graphviz 2.28/bin:/cygdrive/d/Program Files (x86)/GNU/GnuPG
$ if [ $? -eq 0 ]; then echo "foobar is found in PATH"; else echo "foobar is NOT found in PATH, of course it does not mean it is not installed."; fi
foobar is NOT found in PATH, of course it does not mean it is not installed.
$

PS: Note that not everything that's installed may be in PATH. Usually to check whether something is "installed" or not one would use installation related commands relevant to the OS. E.g. rpm -qa | grep -i "foobar" for RHEL.

.gitignore and "The following untracked working tree files would be overwritten by checkout"

I just went to the file system and deleted the file directly, then continued with git checkout and it worked.

I've had the problem occur several times and it may be related to developers doing delete, push, re-add, push or some such thing.

Apache shows PHP code instead of executing it

Add following configuration to /etc/apache2/apache2.conf

<FilesMatch "\.php$">
    SetHandler application/x-httpd-php
</FilesMatch>

And restart the apache via sudo service apache2 restart

Child with max-height: 100% overflows parent

Maybe someone else can explain the reasons behind your problem but you can solve it by specifying the height of the container and then setting the height of the image to be 100%. It is important that the width of the image appears before the height.

<html>
    <head>
        <style>
            .container {  
                background: blue; 
                padding: 10px;
                height: 100%;
                max-height: 200px; 
                max-width: 300px; 
            }

            .container img {
                width: 100%;
                height: 100%
            }
        </style>
    </head>
    <body>
        <div class="container">
            <img src="http://placekitten.com/400/500" />
        </div>
    </body>
</html>

XAMPP installation on Win 8.1 with UAC Warning

As ivan.sim writes in his answer

  1. Ensure that your user account has administrator privilege.
  2. Disable UAC(User Account Control) as it restricts certain administrative function needed to run a web server.
  3. Install in C://xampp.

Problem with the correct answer is in the explanation of point 2., and magicandre1981 writes more about it

Moving the slider down doesn't completely disable UAC since Windows 8. This is changed compared to Windows 7, because the new Store apps require an active UAC. With UAC off, they no longer run.


How can we then disable UAC and install XAMPP?

Easy. Go to Registry Editor and navigate to

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System

Registry Editor

Right click EnableLUA and modify the Value data to 0.

EnableLUA

Then restart your computer and you're ready to install XAMPP.

Installing XAMPP

XAMPP installed

XAMPP Control Panel

key_load_public: invalid format

It seems that ssh cannot read your public key. But that doesn't matter.

You upload your public key to github, but you authenticate using your private key. See e.g. the FILES section in ssh(1).

How can I get query string values in JavaScript?

I use regular expressions a lot, but not for that.

It seems easier and more efficient to me to read the query string once in my application, and build an object from all the key/value pairs like:

var search = function() {
  var s = window.location.search.substr(1),
    p = s.split(/\&/), l = p.length, kv, r = {};
  if (l === 0) {return false;}
  while (l--) {
    kv = p[l].split(/\=/);
    r[kv[0]] = decodeURIComponent(kv[1] || '') || true;
  }
  return r;
}();

For a URL like http://domain.com?param1=val1&param2=val2 you can get their value later in your code as search.param1 and search.param2.

How to clear basic authentication details in chrome

I am using Chrome Version 83 and this is how I did it. Before following the steps make sure the tab of the site, whose Auth Details you want to delete is closed.

First, go to Settings >> Privacy and security.

enter image description here



Then click on Site settings option
enter image description here



Then click on View permissions and data stored across sites option
enter image description here



Search for the site whose Auth info you want to delete. In this example, I am using Stack Overflow. enter image description here



Now click on the site and then click the Clear data button.
enter image description here



Now restart your browser and you will be asked for a fresh login. For restarting you can type chrome://restart in the address bar.

Eclipse Generate Javadoc Wizard: what is "Javadoc Command"?

Yes, presumably it wants the path to the javadoc command line tool that comes with the JDK (in the bin directory, same as java and javac).

Eclipse should be able to find it automatically; are you perhaps running it on a JRE? That would explain the request.

How to get build time stamp from Jenkins build variables?

Try use Build Timestamp Plugin and use BUILD_TIMESTAMP variable.

Installing Apple's Network Link Conditioner Tool

For Xcode 8 you gotta download a package named Additional Tools for Xcode 8

For other versions (8.1, 8.2) get the package here

Double click and open the dmg and go to Hardware directory. Double click on Network Link Conditioner.prefPane.

enter image description here

Click on install

enter image description here

Now Network Link Conditioner will be available in System Preferences.

For versions older than Xcode 8, the package to be downloaded is called Hardware IO Tools for Xcode. Get it from this page

How to check whether a string is a valid HTTP URL?

Uri uri = null;
if (!Uri.TryCreate(url, UriKind.Absolute, out uri) || null == uri)
    return false;
else
    return true;

Here url is the string you have to test.

How to display data from database into textbox, and update it

Wrap your all statements in !IsPostBack condition on page load.

protected void Page_Load(object sender, EventArgs e)
{
   if(!IsPostBack)
   {
      // all statements
   }
}

This will fix your issue.

How to disable compiler optimizations in gcc?

For gcc you want to omit any -O1 -O2 or -O3 options passed to the compiler or if you already have them you can append the -O0 option to turn it off again. It might also help you to add -g for debug so that you can see the c source and disassembled machine code in your debugger.

See also: http://sourceware.org/gdb/onlinedocs/gdb/Optimized-Code.html

Why this line xmlns:android="http://schemas.android.com/apk/res/android" must be the first in the layout xml file?

  • Xmlns means xml namespace.
  • It is created to avoid naming conflicts in the xml’s.
  • In order to avoid naming conflicts by any other way we need to provide each element with a prefix.
  • to avoid repetitive usage of the prefix in each xml tag we use xmlns at the root of the xml. Hence we have the tag xmlns:android=”http://schemas.android.com/apk/res/android
  • Now android here simply means we are assigning the namespace “http://schemas.android.com/apk/res/android” to it.
  • This namespace is not a URL but a URI also known as URN(universal resource name) which is rarely used in place of URI.
  • Due to this android will be responsible to identify the android related elements in the xml document which would be android:xxxxxxx etc. Without this namespace android:xxxxxxx will be not recognized.

To put in layman’s term :

without xmlns:android=”http://schemas.android.com/apk/res/android” android related tags wont be recognized in the xml document of our layout.

Detect when an HTML5 video finishes

Here is a simple approach which triggers when the video ends.

<html>
<body>

    <video id="myVideo" controls="controls">
        <source src="video.mp4" type="video/mp4">
        etc ...
    </video>

</body>
<script type='text/javascript'>

    document.getElementById('myVideo').addEventListener('ended', function(e) {

        alert('The End');

    })

</script>
</html> 

In the 'EventListener' line substitute the word 'ended' with 'pause' or 'play' to capture those events as well.

Show Console in Windows Application?

Resurrecting a very old thread yet again, since none of the answers here worked very well for me.

I found a simple way that seems pretty robust and simple. It worked for me. The idea:

  • Compile your project as a Windows Application. There might be a parent console when your executable starts, but maybe not. The goal is to re-use the existing console if one exists, or create a new one if not.
  • AttachConsole(-1) will look for the console of the parent process. If there is one, it attaches to it and you're finished. (I tried this and it worked properly when calling my application from cmd)
  • If AttachConsole returned false, there is no parent console. Create one with AllocConsole.

Example:

static class Program
{
    [DllImport( "kernel32.dll", SetLastError = true )]
    static extern bool AllocConsole();

    [DllImport( "kernel32", SetLastError = true )]
    static extern bool AttachConsole( int dwProcessId );

    static void Main(string[] args)
    {
        bool consoleMode = Boolean.Parse(args[0]);
        if (consoleMode)
        {
           if (!AttachConsole(-1))
              AllocConsole();
           Console.WriteLine("consolemode started");
           // ...
        } 
        else
        {
           Application.EnableVisualStyles();
           Application.SetCompatibleTextRenderingDefault(false);
           Application.Run(new Form1());
        }
    }
}

A word of caution : it seems that if you try writing to the console prior to attaching or allocing a console, this approach doesn't work. My guess is the first time you call Console.Write/WriteLine, if there isn't already a console then Windows automatically creates a hidden console somewhere for you. (So perhaps Anthony's ShowConsoleWindow answer is better after you've already written to the console, and my answer is better if you've not yet written to the console). The important thing to note is that this doesn't work:

static void Main(string[] args)
    {
        Console.WriteLine("Welcome to the program");   //< this ruins everything
        bool consoleMode = Boolean.Parse(args[0]);
        if (consoleMode)
        {
           if (!AttachConsole(-1))
              AllocConsole();
           Console.WriteLine("consolemode started");   //< this doesn't get displayed on the parent console
           // ...
        } 
        else
        {
           Application.EnableVisualStyles();
           Application.SetCompatibleTextRenderingDefault(false);
           Application.Run(new Form1());
        }
    }

How can I display a messagebox in ASP.NET?

@freelancer If you are using ScriptManager then try this code for message..

string script = "alert(\"Hello!\");";
ScriptManager.RegisterStartupScript(this, GetType(), 
                      "ServerControlScript", script, true);

Error: Cannot invoke an expression whose type lacks a call signature

It means you're trying to call something that isn't a function

const foo = 'string'
foo() // error

How to convert SQL Query result to PANDAS Data Structure?

Here is mine. Just in case if you are using "pymysql":

import pymysql
from pandas import DataFrame

host   = 'localhost'
port   = 3306
user   = 'yourUserName'
passwd = 'yourPassword'
db     = 'yourDatabase'

cnx    = pymysql.connect(host=host, port=port, user=user, passwd=passwd, db=db)
cur    = cnx.cursor()

query  = """ SELECT * FROM yourTable LIMIT 10"""
cur.execute(query)

field_names = [i[0] for i in cur.description]
get_data = [xx for xx in cur]

cur.close()
cnx.close()

df = DataFrame(get_data)
df.columns = field_names

Why is my CSS style not being applied?

Have you tried forcing the selectors to be in the front of the class?

p span label.fancify {

    font-size: 1.5em;
    font-weight: 800;
    font-family: Consolas, "Segoe UI", Calibri, sans-serif;
    font-style: italic;
}

Usually it will add more weight to your CSS declaration. My mistake ... There should be no space between the selector and the class. The same goes for the ID. If you have for example:

<div id="first">
    <p id="myParagraph">Hello <span class="bolder">World</span></p>
</div>

You would style it like this:

div#first p#myParagraph {
     color : #ff0000;
}

Just to make a complete example using a class:

div#first p#myParagraph span.bolder{
    font-weight:900;
}

For more information about pseudo-selectors and child selectors : http://www.w3.org/TR/CSS2/selector.html

CSS is a whole science :) Beware that some browsers can have incompatibilities and will not show you the proper results. For more information check this site: http://www.caniuse.com/

HTML Drag And Drop On Mobile Devices

The Sortable JS library is compatible with touch screens and does not require jQuery.

The way it handles touch screens it that you need to touch the screen for about 1 second to start dragging an item.

Also, they present a video test showing that this library is running faster than JQuery UI Sortable.

Psexec "run as (remote) admin"

Simply add a -h after adding your credentials using a -u -p, and it will run with elevated privileges.