Programs & Examples On #Global scope

Font is not available to the JVM with Jasper Reports

sudo apt-get install msttcorefonts works (on our Ubuntu development environment), but is not a very good solution.

Instead, we bundled the fonts with our application based on this tip. Their JAR file bundles the following fonts,

  • Arial
  • Times New Roman
  • Courier New
  • Comic Sans MS
  • Georgia
  • Verdana
  • Monospaced

Direct Link to download jar: Maven ver 1.0. DynamicFonts

How to use adb command to push a file on device without sd card

In my case, I had an already removed SDCard still registered in Android. So I longpressed the entry for my old SDCard under:

Settings | Storage & USB

and selected "Forget".

Afterwards a normal

adb push myfile.zip /sdcard/

worked fine.

How to randomly pick an element from an array

Take a look at this question:

How do I generate random integers within a specific range in Java?

You will want to generate a random number from 0 to your integers length - 1. Then simply get your int from your array:

myArray[myRandomNumber];

HTML - how can I show tooltip ONLY when ellipsis is activated

This was my solution, works as a charm!

    $(document).on('mouseover', 'input, span', function() {
      var needEllipsis = $(this).css('text-overflow') && (this.offsetWidth < this.scrollWidth);
      var hasNotTitleAttr = typeof $(this).attr('title') === 'undefined';
      if (needEllipsis === true) {
          if(hasNotTitleAttr === true){
            $(this).attr('title', $(this).val());
          }
      }
      if(needEllipsis === false && hasNotTitleAttr == false){
        $(this).removeAttr('title');
      }
  });

Java code To convert byte to Hexadecimal

Here is a simple function to convert byte to Hexadecimal

   private static String convertToHex(byte[] data) {
    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < data.length; i++) {
        int halfbyte = (data[i] >>> 4) & 0x0F;
        int two_halfs = 0;
        do {
            if ((0 <= halfbyte) && (halfbyte <= 9))
                buf.append((char) ('0' + halfbyte));
            else
                buf.append((char) ('a' + (halfbyte - 10)));
            halfbyte = data[i] & 0x0F;
        } while(two_halfs++ < 1);
    }
    return buf.toString();
}

how to check if a form is valid programmatically using jQuery Validation Plugin

@mikemaccana answer is useful.

And I also used https://github.com/ryanseddon/H5F. Found on http://microjs.com. It's some kind of polyfill and you can use it as follows (jQuery is used in example):

if ( $('form')[0].checkValidity() ) {
    // the form is valid
}

"string could not resolved" error in Eclipse for C++ (Eclipse can't resolve standard library)

I've just replied to the related question given by Vanuan (Eclipse CDT: Unresolved inclusion of stl header), and this is my answer :

You could also try use "CDT GCC Built-in Compiler Settings". Go to the project properties > C/C++ General > Preprocessor Include Path > Providers tab then check "CDT GCC Built-in Compiler Settings" if it is not.

None of the other solutions (play with include path, etc) worked for me for the type 'string', but this one fixed it.

Handling onchange event in HTML.DropDownList Razor MVC

The way of dknaack does not work for me, I found this solution as well:

@Html.DropDownList("Chapters", ViewBag.Chapters as SelectList, 
                    "Select chapter", new { @onchange = "location = this.value;" })

where

@Html.DropDownList(controlName, ViewBag.property + cast, "Default value", @onchange event)

In the controller you can add:

DbModel db = new DbModel();    //entity model of Entity Framework

ViewBag.Chapters = new SelectList(db.T_Chapter, "Id", "Name");

What Content-Type value should I send for my XML sitemap?

As a rule of thumb, the safest bet towards making your document be treated properly by all web servers, proxies, and client browsers, is probably the following:

  1. Use the application/xml content type
  2. Include a character encoding in the content type, probably UTF-8
  3. Include a matching character encoding in the encoding attribute of the XML document itself.

In terms of the RFC 3023 spec, which some browsers fail to implement properly, the major difference in the content types is in how clients are supposed to treat the character encoding, as follows:

For application/xml, application/xml-dtd, application/xml-external-parsed-entity, or any one of the subtypes of application/xml such as application/atom+xml, application/rss+xml or application/rdf+xml, the character encoding is determined in this order:

  1. the encoding given in the charset parameter of the Content-Type HTTP header
  2. the encoding given in the encoding attribute of the XML declaration within the document,
  3. utf-8.

For text/xml, text/xml-external-parsed-entity, or a subtype like text/foo+xml, the encoding attribute of the XML declaration within the document is ignored, and the character encoding is:

  1. the encoding given in the charset parameter of the Content-Type HTTP header, or
  2. us-ascii.

Most parsers don't implement the spec; they ignore the HTTP Context-Type and just use the encoding in the document. With so many ill-formed documents out there, that's unlikely to change any time soon.

Run git pull over all subdirectories

Original answer 2010:

If all of those directories are separate git repo, you should reference them as submodules.

That means your "origin" would be that remote repo 'plugins' which only contains references to subrepos 'cms', 'admin', 'chart'.

A git pull followed by a git submodule update would achieve what your are looking for.


Update January 2016:

With Git 2.8 (Q1 2016), you will be able to fetch submodules in parallel (!) with git fetch --recurse-submodules -j2.
See "How to speed up / parallelize downloads of git submodules using git clone --recursive?"

Using %s in C correctly - very basic level

%s is the representation of an array of char

char string[10] // here is a array of chars, they max length is 10;
char character; // just a char 1 letter/from the ascii map

character = 'a'; // assign 'a' to character
printf("character %c  ",a); //we will display 'a' to stout

so string is an array of char we can assign multiple character per space of memory

string[0]='h';
string[1]='e';
string[2]='l';
string[3]='l';
string[4]='o';
string[5]=(char) 0;//asigning the last element of the 'word' a mark so the string ends

this assignation can be done at initialization like char word="this is a word" // the word array of chars got this string now and is statically defined

toy can also assign values to the array of chars assigning it with functions like strcpy;

strcpy(string,"hello" );

this do the same as the example and automatically add the (char) 0 at the end

so if you print it with %S printf("my string %s",string);

and how string is a array we can just display part of it

//                         the array    one char
printf("first letter of wrd %s     is    :%c ",string,string[1]  );

MongoDB distinct aggregation

You can use $addToSet with the aggregation framework to count distinct objects.

For example:

db.collectionName.aggregate([{
    $group: {_id: null, uniqueValues: {$addToSet: "$fieldName"}}
}])

How can I count the number of matches for a regex?

From Java 9, you can use the stream provided by Matcher.results()

long matches = matcher.results().count();

Resizing an iframe based on content

I have an easy solution and requires you to determine the width and height in the link, please try (It works with most browsers):

<a href='#' onClick=" document.getElementById('myform').src='t2.htm';document.getElementById('myform').width='500px'; document.getElementById('myform').height='400px'; return false">500x400</a>

How to stretch a fixed number of horizontal navigation items evenly and fully across a specified container

<!DOCTYPE html>
<html lang="en">
<head>
<style>
#container { width: 100%; border: 1px solid black; display: block; text-align: justify; }
object, span { display: inline-block; }
span { width: 100%; }
</style>
</head>

  <div id="container">
    <object>
      <div>
      alpha
      </div>
    </object>
    <object>
      <div>
      beta
      </div>
    </object>
    <object>
      <div>
      charlie
      </div>
    </object>
    <object>
      <div>
      delta
      </div>
    </object>
    <object>
      <div>
      epsilon
      </div>
    </object>
    <object>
      <div>
      foxtrot
      </div>
    </object>
    <span></span>
  </div>
</html>

Remove space above and below <p> tag HTML

In case anyone wishes to do this with bootstrap, version 4 offers the following:

The classes are named using the format {property}{sides}-{size} for xs and {property}{sides}-{breakpoint}-{size} for sm, md, lg, and xl.

Where property is one of:

m - for classes that set margin
p - for classes that set padding

Where sides is one of:

t - for classes that set margin-top or padding-top
b - for classes that set margin-bottom or padding-bottom
l - for classes that set margin-left or padding-left
r - for classes that set margin-right or padding-right
x - for classes that set both *-left and *-right
y - for classes that set both *-top and *-bottom
blank - for classes that set a margin or padding on all 4 sides of the element

Where size is one of:

0 - for classes that eliminate the margin or padding by setting it to 0
1 - (by default) for classes that set the margin or padding to $spacer * .25
2 - (by default) for classes that set the margin or padding to $spacer * .5
3 - (by default) for classes that set the margin or padding to $spacer
4 - (by default) for classes that set the margin or padding to $spacer * 1.5
5 - (by default) for classes that set the margin or padding to $spacer * 3
auto - for classes that set the margin to auto

For example:

.mt-0 {
  margin-top: 0 !important;
}

.ml-1 {
  margin-left: ($spacer * .25) !important;
}

.px-2 {
  padding-left: ($spacer * .5) !important;
  padding-right: ($spacer * .5) !important;
}

.p-3 {
  padding: $spacer !important;
}

Reference: https://getbootstrap.com/docs/4.0/utilities/spacing/

How can I include css files using node, express, and ejs?

the order of registering routes is important . register 404 routes after static files.

correct order:

app.use("/admin", admin);
...

app.use(express.static(join(__dirname, "public")));

app.use((req, res) => {
  res.status(404);
  res.send("404");
});

otherwise everything which is not in routes , like css files etc.. , will become 404 .

How to use BufferedReader in Java

Try this to read a file:

BufferedReader reader = null;

try {
    File file = new File("sample-file.dat");
    reader = new BufferedReader(new FileReader(file));

    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }

} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

gdb: "No symbol table is loaded"

First of all, what you have is a fully compiled program, not an object file, so drop the .o extension. Now, pay attention to what the error message says, it tells you exactly how to fix your problem: "No symbol table is loaded. Use the "file" command."

(gdb) exec-file test
(gdb) b 2
No symbol table is loaded.  Use the "file" command.
(gdb) file test
Reading symbols from /home/user/test/test...done.
(gdb) b 2
Breakpoint 1 at 0x80483ea: file test.c, line 2.
(gdb) 

Or just pass the program on the command line.

$ gdb test
GNU gdb (GDB) 7.4
Copyright (C) 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
[...]
Reading symbols from /home/user/test/test...done.
(gdb) b 2
Breakpoint 1 at 0x80483ea: file test.c, line 2.
(gdb) 

ActionBarActivity is deprecated

android developers documentation says : "Updated the AppCompatActivity as the base class for activities that use the support library action bar features. This class replaces the deprecated ActionBarActivity."

checkout changes for Android Support Library, revision 22.1.0 (April 2015)

What is the most "pythonic" way to iterate over a list in chunks?

There doesn't seem to be a pretty way to do this. Here is a page that has a number of methods, including:

def split_seq(seq, size):
    newseq = []
    splitsize = 1.0/size*len(seq)
    for i in range(size):
        newseq.append(seq[int(round(i*splitsize)):int(round((i+1)*splitsize))])
    return newseq

'this' vs $scope in AngularJS controllers

I just read a pretty interesting explanation on the difference between the two, and a growing preference to attach models to the controller and alias the controller to bind models to the view. http://toddmotto.com/digging-into-angulars-controller-as-syntax/ is the article.

NOTE: The original link still exists, but changes in formatting have made it hard to read. It's easier to view in the original.

He doesn't mention it but when defining directives, if you need to share something between multiple directives and don't want a service (there are legitimate cases where services are a hassle) then attach the data to the parent directive's controller.

The $scope service provides plenty of useful things, $watch being the most obvious, but if all you need to bind data to the view, using the plain controller and 'controller as' in the template is fine and arguably preferable.

mysql: SOURCE error 2?

Remove spaces in the folder names of the path, It worked for my mac path.

(Eg: change the folder name MySQL Server 5.1 to MySQLServer5.1)

What are libtool's .la file for?

According to http://blog.flameeyes.eu/2008/04/14/what-about-those-la-files, they're needed to handle dependencies. But using pkg-config may be a better option:

In a perfect world, every static library needing dependencies would have its own .pc file for pkg-config, and every package trying to statically link to that library would be using pkg-config --static to get the libraries to link to.

How to get row count in sqlite using Android?

Do you see what the DatabaseUtils.queryNumEntries() does? It's awful! I use this.

public int getRowNumberByArgs(Object... args) {
    String where = compileWhere(args);
    String raw = String.format("SELECT count(*) FROM %s WHERE %s;", TABLE_NAME, where);
    Cursor c = getWriteableDatabase().rawQuery(raw, null);
    try {
        return (c.moveToFirst()) ? c.getInt(0) : 0;
    } finally {
        c.close();
    }
}

Angular 2 Scroll to bottom (Chat style)

In angular using material design sidenav I had to use the following:

let ele = document.getElementsByClassName('md-sidenav-content');
    let eleArray = <Element[]>Array.prototype.slice.call(ele);
    eleArray.map( val => {
        val.scrollTop = val.scrollHeight;
    });

Best way to check that element is not present using Selenium WebDriver with java

public boolean isDisplayed(WebElement element) {
        try {
            return element.isDisplayed();
        } catch (NoSuchElementException e) {
            return false;
        }
    }

If you wan t to check that element is displayed on the page your check should be:

if(isDisplayed(yourElement){
...
}
else{
...
}

Posting parameters to a url using the POST method without using a form

Using jQuery.post

$.post(
  "http://theurl.com",
  { key1: "value1", key2: "value2" },
  function(data) {
    alert("Response: " + data);
  }
);

How to convert string to string[]?

You can create a string[] (string array) that contains your string like :

string someString = "something";
string[] stringArray = new string[]{ someString };

The variable stringArray will now have a length of 1 and contain someString.

How to define Typescript Map of key value pair. where key is a number and value is an array of objects

you can also skip creating dictionary altogether. i used below approach to same problem .

 mappedItems: {};
 items.forEach(item => {     
        if (mappedItems[item.key]) {
           mappedItems[item.key].push({productId : item.productId , price : item.price , discount : item.discount});
        } else {
          mappedItems[item.key] = [];
          mappedItems[item.key].push({productId : item.productId , price : item.price , discount : item.discount}));
        }
    });

how to set length of an column in hibernate with maximum length

Use @Column annotation and define its length attribute. Check Hibernate's documentation for references (section 2.2.2.3).

C# Help reading foreign characters using StreamReader

Try a different encoding such as Encoding.UTF8. You can also try letting StreamReader find the encoding itself:

    StreamReader reader = new StreamReader(inputFilePath, System.Text.Encoding.UTF8, true)

Edit: Just saw your update. Try letting StreamReader do the guessing.

Convert Java String to sql.Timestamp

You could use Timestamp.valueOf(String). The documentation states that it understands timestamps in the format yyyy-mm-dd hh:mm:ss[.f...], so you might need to change the field separators in your incoming string.

Then again, if you're going to do that then you could just parse it yourself and use the setNanos method to store the microseconds.

Why is AJAX returning HTTP status code 0?

We had similar problem - status code 0 on jquery ajax call - and it took us whole day to diagnose it. Since no one had mentioned this reason yet, I thought I'll share.

In our case the problem was HTTP server crash. Some bug in PHP was blowing Apache, so on client end it looked like this:

mirek@toccata:~$ telnet our.server.com 80
Trying 180.153.xxx.xxx...
Connected to our.server.com.
Escape character is '^]'.
GET /test.php HTTP/1.0
Host: our.server.com

Connection closed by foreign host.
mirek@toccata:~$ 

where test.php contained the crashing code. No data returned from the server (not even headers) => ajax call was aborted with status 0.

What Process is using all of my disk IO

You're looking for iotop (assuming you've got kernel >2.6.20 and Python 2.5). Failing that, you're looking into hooking into the filesystem. I recommend the former.

Excel Date Conversion from yyyymmdd to mm/dd/yyyy

Do you have ROWS of data (horizontal) as you stated or COLUMNS (vertical)?

If it's the latter you can use "Text to columns" functionality to convert a whole column "in situ" - to do that:

Select column > Data > Text to columns > Next > Next > Choose "Date" under "column data format" and "YMD" from dropdown > Finish

....otherwise you can convert with a formula by using

=TEXT(A1,"0000-00-00")+0

and format in required date format

pip installs packages successfully, but executables not found from command line

Solution

Based on other answers, for linux and mac you can run the following:

echo "export PATH=\"`python3 -m site --user-base`/bin:$PATH\"" >> ~/.bashrc
source ~/.bashrc

instead of python3 you can use any other link to python version: python, python2.7, python3.6, python3.9, etc.

Explanation

In order to know where the user packages are installed in the current OS (win, mac, linux), we run:

python3 -m site --user-base

We know that the scripts go to the bin/ folder where the packages are installed.

So we concatenate the paths:

echo `python3 -m site --user-base`/bin

Then we export that to an environment variable.

export PATH=\"`python3 -m site --user-base`/bin:$PATH\"

Finally, in order to avoid repeating the export command we add it to our .bashrc file and we run source to run the new changes, giving us the suggested solution mentioned at the beginning.

Button Width Match Parent

RaisedButton( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [Text('Submit')], ) ) It works for me.

How can I edit javascript in my browser like I can use Firebug to edit CSS/HTML?

I know that you can modify a javascript file when using Google Chrome.

  1. Open up Chrome Inspector, go to the "Scripts" tab.
  2. Press the drop-down menu and select the javascript file that you want to edit.
  3. Double click in the text field, type in what ever you want and delete whatever you want.
  4. Then all you have to do is press Ctrl + S to save the file.

Warning: If you refresh the page, all changes will go back to original file. I recommend to copy/paste the code somewhere else if you want to use it again.

Hope this helps!

How to calculate the median of an array?

And nobody paying attention when list contains only one element (list.size == 1). All your answers will crash with index out of bound exception, because integer division returns zero (1 / 2 = 0). Correct answer (in Kotlin):

MEDIAN("MEDIAN") {

        override fun calculate(values: List<BigDecimal>): BigDecimal? {
            if (values.size == 1) {
                return values.first()
            }
            if (values.size > 1) {
                val valuesSorted = values.sorted()
                val mid = valuesSorted.size / 2
                return if (valuesSorted.size % 2 != 0) {
                    valuesSorted[mid]
                } else {
                    AVERAGE.calculate(listOf(valuesSorted[mid - 1], valuesSorted[mid]))
                }
            }
            return null
        }
    },

Truncate string in Laravel blade templates

Laravel 6 Update:

@php
$value = 'Artificial Intelligence';
$var = Str::limit($value, $limit = 15, $end = '');
print_r($var);
@endphp

<p class="card-text">{{ Illuminate\Support\Str::limit($value, 7) }}</p>
<h2 class="main-head">{!! Str::limit($value, 5) !!}</h2>

java.io.StreamCorruptedException: invalid stream header: 54657374

Clearly you aren't sending the data with ObjectOutputStream: you are just writing the bytes.

  • If you read with readObject() you must write with writeObject().
  • If you read with readUTF() you must write with writeUTF().
  • If you read with readXXX() you must write with writeXXX(), for most values of XXX.

Running Python in PowerShell?

Using CMD you can run your python scripts as long as the installed python is added to the path with the following line:

C: \ Python27;

The (27) is example referring to version 2.7, add as per your version.

Path to system path:

Control Panel => System and Security => System => Advanced Settings => Advanced => Environment Variables.

Under "User Variables," append the PATH variable to the path of the Python installation directory (As above).

Once this is done, you can open a CMD where your scripts are saved, or manually navigate through the CMD.

To run the script enter:

C: \ User \ X \ MyScripts> python ScriptName.py

Select distinct using linq

myList.GroupBy(i => i.id).Select(group => group.First())

CreateProcess: No such file or directory

Although post is old I had the same problem with mingw32 vers 4.8.1 on 2015/02/13. Compiling using Eclipse CDT failed with this message. Trying from command line with -v option also failed. I was also missing the cc1plus executable.

The cause: I downloaded the command line and graphical installer from the mingw32 site. I used this to do my initial install of mingw32. Using the GUI I selected the base tools, selecting both the c and c++ compilers.

This installer did an incomplete install of the 32 bit c++ compiler. I had the g++ and cpp files but not the cc1plus executable. Trying to do an 'update' failed because the installer assumed I had everything installed.

To fix I found these sites: http://mingw-w64.sourceforge.net/ http://sourceforge.net/projects/mingw-w64/ I downloaded and ran this 'online install'. Sure enough this one contained the missing files. I modified my PATH variable and pointed to the 'bin' folder containing the g++ executable. Rebooted. Installed 64 bit Eclipse. Opened Eclipse and the 'Hello World' c++ program compiled, executed, and debugged properly.

Note: the 64bit installer seems to default to UNIX settings. Why can't an installer determine the OS??? Make sure to change them.

I spent an entire evening dealing with this. Hope this helps someone.

Convert date to UTC using moment.js

I use this method and it works. ValueOf does not work for me.

moment.utc(yourDate).format()

T-SQL: How to Select Values in Value List that are NOT IN the Table?

You need to somehow create a table with these values and then use NOT IN. This can be done with a temporary table, a CTE (Common Table Expression) or a Table Values Constructor (available in SQL-Server 2008):

SELECT email
FROM
    ( VALUES 
        ('email1')
      , ('email2')
      , ('email3')
    ) AS Checking (email)
WHERE email NOT IN 
      ( SELECT email 
        FROM Users
      ) 

The second result can be found with a LEFT JOIN or an EXISTS subquery:

SELECT email
     , CASE WHEN EXISTS ( SELECT * 
                          FROM Users u
                          WHERE u.email = Checking.email
                        ) 
            THEN 'Exists'
            ELSE 'Not exists'
       END AS status 
FROM
    ( VALUES 
        ('email1')
      , ('email2')
      , ('email3')
    ) AS Checking (email)

C# removing items from listbox

protected void lbAddtoDestination_Click(object sender, EventArgs e)
        {
            AddRemoveItemsListBox(lstSourceSkills, lstDestinationSkills);
        }
        protected void lbRemovefromDestination_Click(object sender, EventArgs e)
        {
            AddRemoveItemsListBox(lstDestinationSkills, lstSourceSkills);
        }
        private void AddRemoveItemsListBox(ListBox source, ListBox destination)
        {
            List<ListItem> toBeRemoved = new List<ListItem>();
            foreach (ListItem item in source.Items)
            {
                if (item.Selected)
                {
                    toBeRemoved.Add(item);
                    destination.Items.Add(item);
                }
            }
            foreach (ListItem item in toBeRemoved) source.Items.Remove(item);
        }

How to mount the android img file under linux?

See the answer at: http://omappedia.org/wiki/Android_eMMC_Booting#Modifying_.IMG_Files

First you need to "uncompress" userdata.img with simg2img, then you can mount it via the loop device.

How to fix the height of a <div> element?

You can try max-height: 70px; See if that works.

How can I remove the string "\n" from within a Ruby string?

When you want to remove a string, rather than replace it you can use String#delete (or its mutator equivalent String#delete!), e.g.:

x = "foo\nfoo"
x.delete!("\n")

x now equals "foofoo"

In this specific case String#delete is more readable than gsub since you are not actually replacing the string with anything.

Can I make dynamic styles in React Native?

I know there are several answers, but i think the best and most simple is using a state "To change" is the state purpose.

export default class App extends Component {
    constructor(props) {
      super(props);
      this.state = {
          style: {
              backgroundColor: "white"
          }
      };
    }
    onPress = function() {
      this.setState({style: {backgroundColor: "red"}});
    }
    render() {
       return (
          ...
          <View style={this.state.style}></View>
          ...
       )
    }

}

How can I get a list of all values in select box?

You had two problems:

1) The order in which you included the HTML. Try changing the dropdown from "onLoad" to "no wrap - head" in the JavaScript settings of your fiddle.

2) Your function prints the values. What you're actually after is the text

x.options[i].text; instead of x.options[i].value;

http://jsfiddle.net/WfBRr/5/

What do hjust and vjust do when making a plot using ggplot?

The value of hjust and vjust are only defined between 0 and 1:

  • 0 means left-justified
  • 1 means right-justified

Source: ggplot2, Hadley Wickham, page 196

(Yes, I know that in most cases you can use it beyond this range, but don't expect it to behave in any specific way. This is outside spec.)

hjust controls horizontal justification and vjust controls vertical justification.

An example should make this clear:

td <- expand.grid(
    hjust=c(0, 0.5, 1),
    vjust=c(0, 0.5, 1),
    angle=c(0, 45, 90),
    text="text"
)

ggplot(td, aes(x=hjust, y=vjust)) + 
    geom_point() +
    geom_text(aes(label=text, angle=angle, hjust=hjust, vjust=vjust)) + 
    facet_grid(~angle) +
    scale_x_continuous(breaks=c(0, 0.5, 1), expand=c(0, 0.2)) +
    scale_y_continuous(breaks=c(0, 0.5, 1), expand=c(0, 0.2))

enter image description here


To understand what happens when you change the hjust in axis text, you need to understand that the horizontal alignment for axis text is defined in relation not to the x-axis, but to the entire plot (where this includes the y-axis text). (This is, in my view, unfortunate. It would be much more useful to have the alignment relative to the axis.)

DF <- data.frame(x=LETTERS[1:3],y=1:3)
p <- ggplot(DF, aes(x,y)) + geom_point() + 
    ylab("Very long label for y") +
    theme(axis.title.y=element_text(angle=0))


p1 <- p + theme(axis.title.x=element_text(hjust=0)) + xlab("X-axis at hjust=0")
p2 <- p + theme(axis.title.x=element_text(hjust=0.5)) + xlab("X-axis at hjust=0.5")
p3 <- p + theme(axis.title.x=element_text(hjust=1)) + xlab("X-axis at hjust=1")

library(ggExtra)
align.plots(p1, p2, p3)

enter image description here


To explore what happens with vjust aligment of axis labels:

DF <- data.frame(x=c("a\na","b","cdefghijk","l"),y=1:4)
p <- ggplot(DF, aes(x,y)) + geom_point()

p1 <- p + theme(axis.text.x=element_text(vjust=0, colour="red")) + 
        xlab("X-axis labels aligned with vjust=0")
p2 <- p + theme(axis.text.x=element_text(vjust=0.5, colour="red")) + 
        xlab("X-axis labels aligned with vjust=0.5")
p3 <- p + theme(axis.text.x=element_text(vjust=1, colour="red")) + 
        xlab("X-axis labels aligned with vjust=1")


library(ggExtra)
align.plots(p1, p2, p3)

enter image description here

Getting a list of files in a directory with a glob

Unix has a library that can perform file globbing operations for you. The functions and types are declared in a header called glob.h, so you'll need to #include it. If open up a terminal an open the man page for glob by typing man 3 glob you'll get all of the information you need to know to use the functions.

Below is an example of how you could populate an array the files that match a globbing pattern. When using the glob function there are a few things you need to keep in mind.

  1. By default, the glob function looks for files in the current working directory. In order to search another directory you'll need to prepend the directory name to the globbing pattern as I've done in my example to get all of the files in /bin.
  2. You are responsible for cleaning up the memory allocated by glob by calling globfree when you're done with the structure.

In my example I use the default options and no error callback. The man page covers all of the options in case there's something in there you want to use. If you're going to use the above code, I'd suggest adding it as a category to NSArray or something like that.

NSMutableArray* files = [NSMutableArray array];
glob_t gt;
char* pattern = "/bin/*";
if (glob(pattern, 0, NULL, &gt) == 0) {
    int i;
    for (i=0; i<gt.gl_matchc; i++) {
        [files addObject: [NSString stringWithCString: gt.gl_pathv[i]]];
    }
}
globfree(&gt);
return [NSArray arrayWithArray: files];

Edit: I've created a gist on github that contains the above code in a category called NSArray+Globbing.

Bootstrap Datepicker - Months and Years Only

Why not call the $('.input-group.date').datepicker("remove"); when the select statement is changed then set your datepicker view then call the $('.input-group.date').datepicker("update");

Function to Calculate Median in SQL Server

My original quick answer was:

select  max(my_column) as [my_column], quartile
from    (select my_column, ntile(4) over (order by my_column) as [quartile]
         from   my_table) i
--where quartile = 2
group by quartile

This will give you the median and interquartile range in one fell swoop. If you really only want one row that is the median then uncomment the where clause.

When you stick that into an explain plan, 60% of the work is sorting the data which is unavoidable when calculating position dependent statistics like this.

I've amended the answer to follow the excellent suggestion from Robert Ševcík-Robajz in the comments below:

;with PartitionedData as
  (select my_column, ntile(10) over (order by my_column) as [percentile]
   from   my_table),
MinimaAndMaxima as
  (select  min(my_column) as [low], max(my_column) as [high], percentile
   from    PartitionedData
   group by percentile)
select
  case
    when b.percentile = 10 then cast(b.high as decimal(18,2))
    else cast((a.low + b.high)  as decimal(18,2)) / 2
  end as [value], --b.high, a.low,
  b.percentile
from    MinimaAndMaxima a
  join  MinimaAndMaxima b on (a.percentile -1 = b.percentile) or (a.percentile = 10 and b.percentile = 10)
--where b.percentile = 5

This should calculate the correct median and percentile values when you have an even number of data items. Again, uncomment the final where clause if you only want the median and not the entire percentile distribution.

How can I get the console logs from the iOS Simulator?

I can open the log directly via the iOS simulator: Debug -> Open System Log... Not sure when this was introduced, so it might not be available for earlier versions.

Locking a file in Python

Coordinating access to a single file at the OS level is fraught with all kinds of issues that you probably don't want to solve.

Your best bet is have a separate process that coordinates read/write access to that file.

Change Twitter Bootstrap Tooltip content on click

you can use this code to hide the tool tip change its title and show the tooltip again, when the ajax request returns successfully.

$(element).tooltip('hide');
$(element).attr('title','this is new title');
$(element).tooltip('fixTitle');
setTimeout(function() {  $(element).tooltip('show');}, 500);

python: restarting a loop

You may want to consider using a different type of loop where that logic is applicable, because it is the most obvious answer.

perhaps a:

i=2
while i < n:
    if something:
       do something
       i += 1
    else: 
       do something else  
       i = 2 #restart the loop  

How do I set the background color of Excel cells using VBA?

This is a perfect example of where you should use the macro recorder. Turn on the recorder and set the color of the cells through the UI. Stop the recorder and review the macro. It will generate a bunch of extraneous code, but it will also show you syntax that works for what you are trying to accomplish. Strip out what you don't need and modify (if you need to) what's left.

Where is Java Installed on Mac OS X?

If you install just the JRE, it seems to be put at:

/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home

Hide Text with CSS, Best Practice?

Add .hide-text class to your span that has the text

.hide-text{
display:none;
 }

or make the text transparent

.hide-text{
 color:rgba(0,0,0,0);
 }

use according to your use case.

How to detect browser using angularjs?

So, you can declare more utilities for angular by create file with content (I follow RGraph Library)

(function(window, angular, undefined) {'use strict';
    var agl = angular || {};
    var ua  = navigator.userAgent;

    agl.ISFF     = ua.indexOf('Firefox') != -1;
    agl.ISOPERA  = ua.indexOf('Opera') != -1;
    agl.ISCHROME = ua.indexOf('Chrome') != -1;
    agl.ISSAFARI = ua.indexOf('Safari') != -1 && !agl.ISCHROME;
    agl.ISWEBKIT = ua.indexOf('WebKit') != -1;

    agl.ISIE   = ua.indexOf('Trident') > 0 || navigator.userAgent.indexOf('MSIE') > 0;
    agl.ISIE6  = ua.indexOf('MSIE 6') > 0;
    agl.ISIE7  = ua.indexOf('MSIE 7') > 0;
    agl.ISIE8  = ua.indexOf('MSIE 8') > 0;
    agl.ISIE9  = ua.indexOf('MSIE 9') > 0;
    agl.ISIE10 = ua.indexOf('MSIE 10') > 0;
    agl.ISOLD  = agl.ISIE6 || agl.ISIE7 || agl.ISIE8; // MUST be here

    agl.ISIE11UP = ua.indexOf('MSIE') == -1 && ua.indexOf('Trident') > 0;
    agl.ISIE10UP = agl.ISIE10 || agl.ISIE11UP;
    agl.ISIE9UP  = agl.ISIE9 || agl.ISIE10UP;

})(window, window.angular);

after that, in your function use can use it like

function SampleController($scope){
    $scope.click = function () {
        if(angular.ISCHROME) {
        alert("is chrome");
    }
}

How do I align a number like this in C?

So, you want an 8-character wide field with spaces as the padding? Try "%8d". Here's a reference.

EDIT: What you're trying to do is not something that can be handled by printf alone, because it will not know what the longest number you are writing is. You will need to calculate the largest number before doing any printfs, and then figure out how many digits to use as the width of your field. Then you can use snprintf or similar to make a printf format on the spot.

char format[20];
snprintf(format, 19, "%%%dd\\n", max_length);
while (got_output) {
    printf(format, number);
    got_output = still_got_output();
}

Best way of invoking getter by reflection

You can use Reflections framework for this

import static org.reflections.ReflectionUtils.*;
Set<Method> getters = ReflectionUtils.getAllMethods(someClass,
      withModifier(Modifier.PUBLIC), withPrefix("get"), withAnnotation(annotation));

How can I interrupt a running code in R with a keyboard command?

Try out Ctrl + z But it will kill the process, not suspend it.

How can I validate google reCAPTCHA v2 using javascript/jQuery?

The Google reCAPTCHA version 2 ASP.Net allows validating the Captcha response on the client side using its Callback functions. In this example, the Google new reCAPTCHA will be validated using ASP.Net RequiredField Validator.

<script type="text/javascript">
    var onloadCallback = function () {
        grecaptcha.render('dvCaptcha', {
            'sitekey': '<%=ReCaptcha_Key %>',
            'callback': function (response) {
                $.ajax({
                    type: "POST",
                    url: "Demo.aspx/VerifyCaptcha",
                    data: "{response: '" + response + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (r) {
                        var captchaResponse = jQuery.parseJSON(r.d);
                        if (captchaResponse.success) {
                            $("[id*=txtCaptcha]").val(captchaResponse.success);
                            $("[id*=rfvCaptcha]").hide();
                        } else {
                            $("[id*=txtCaptcha]").val("");
                            $("[id*=rfvCaptcha]").show();
                            var error = captchaResponse["error-codes"][0];
                            $("[id*=rfvCaptcha]").html("RECaptcha error. " + error);
                        }
                    }
                });
            }
        });
    };
</script>


    <asp:TextBox ID="txtCaptcha" runat="server" Style="display: none" />
    <asp:RequiredFieldValidator ID="rfvCaptcha" ErrorMessage="The CAPTCHA field is required." ControlToValidate="txtCaptcha"
        runat="server" ForeColor="Red" Display="Dynamic" />

    <br />
    <asp:Button ID="btnSubmit" Text="Submit" runat="server" />

How to convert date format to DD-MM-YYYY in C#

Here we go:

DateTime time = DateTime.Now;
Console.WriteLine(time.Day + "-" + time.Month + "-" + time.Year);

WORKS! :)

Cannot construct instance of - Jackson

You cannot instantiate an abstract class, Jackson neither. You should give Jackson information on how to instantiate MyAbstractClass with a concrete type.

See this answer on stackoverflow: Jackson JSON library: how to instantiate a class that contains abstract fields

And maybe also see Jackson Polymorphic Deserialization

Counting unique / distinct values by group in a data frame

my.1 <- table(myvec)

my.1[my.1 != 0] <- 1

rowSums(my.1)

Gradle: Could not determine java version from '11.0.2'

tl;dr: downgrade java by running update-alternatives


My system gradle version was 4.4.1, and the gradle wrapper version was 4.0. After running the command given by several other answers:

gradle wrapper --gradle-version 4.4.1

I still had the same error:

FAILURE: Build failed with an exception.

* What went wrong:
Could not determine java version from '11.0.4'.

It turns out java 11 wasn't supported until gradle 4.8, and my software repositories only had 4.4.1. (Also, upgrading to newer gradle version might have been incompatible with the package I was trying to compile.)

The answer was to downgrade java. My system actually had java8 already installed, and it was easy to switch between java versions by running this command and following the instructions:

sudo update-alternatives --config java

Why does only the first line of this Windows batch file execute but all three lines execute in a command shell?

Having call helps. However today it didn't.

This is how I solved it:

Bat file contents (if you want to stop batch when one of cmds errors)

cmd1 && ^
cmd2 && ^
cmd3 && ^
cmd4

Bat file contents (if you want to continue batch when one of cmds errors)

cmd1 & ^
cmd2 & ^
cmd3 & ^
cmd4

How does "FOR" work in cmd batch file?

FOR is essentially iterating over the "lines" in the data set. In this case, there is one line that contains the path. The "delims=;" is just telling it to separate on semi-colons. If you change the body to echo %%g,%%h,%%i,%%j,%%k you'll see that it is treating the input as a single line and breaking it into multiple tokens.

jQuery delete confirmation box

$(document).ready(function(){
  $(".del").click(function(){
    if (!confirm("Do you want to delete")){
      return false;
    }
  });
});

How to trigger an event in input text after I stop typing/writing?

SOLUTION:

Here is the solution. Executing a function after the user has stopped typing for a specified amount of time:

var delay = (function(){
  var timer = 0;
  return function(callback, ms){
  clearTimeout (timer);
  timer = setTimeout(callback, ms);
 };
})();

Usage

$('input').keyup(function() {
  delay(function(){
    alert('Hi, func called');
  }, 1000 );
});

How do you query for "is not null" in Mongo?

Thanks for providing a solution, I noticed in MQL, sometimes $ne:null doesn't work instead we need to use syntax $ne:"" i.e. in the context of above example we would need to use db.mycollection.find({"IMAGE URL":{"$ne":""}}) - Not sure why this occurs, I have posted this question in the MongoDB forum.

following is the snapshot showing example:

enter image description here

What is the difference between bottom-up and top-down?

Dynamic Programming is often called Memoization!

1.Memoization is the top-down technique(start solving the given problem by breaking it down) and dynamic programming is a bottom-up technique(start solving from the trivial sub-problem, up towards the given problem)

2.DP finds the solution by starting from the base case(s) and works its way upwards. DP solves all the sub-problems, because it does it bottom-up

Unlike Memoization, which solves only the needed sub-problems

  1. DP has the potential to transform exponential-time brute-force solutions into polynomial-time algorithms.

  2. DP may be much more efficient because its iterative

On the contrary, Memoization must pay for the (often significant) overhead due to recursion.

To be more simple, Memoization uses the top-down approach to solve the problem i.e. it begin with core(main) problem then breaks it into sub-problems and solve these sub-problems similarly. In this approach same sub-problem can occur multiple times and consume more CPU cycle, hence increase the time complexity. Whereas in Dynamic programming same sub-problem will not be solved multiple times but the prior result will be used to optimize the solution.

What does character set and collation mean exactly?

From MySQL docs:

A character set is a set of symbols and encodings. A collation is a set of rules for comparing characters in a character set. Let's make the distinction clear with an example of an imaginary character set.

Suppose that we have an alphabet with four letters: 'A', 'B', 'a', 'b'. We give each letter a number: 'A' = 0, 'B' = 1, 'a' = 2, 'b' = 3. The letter 'A' is a symbol, the number 0 is the encoding for 'A', and the combination of all four letters and their encodings is a character set.

Now, suppose that we want to compare two string values, 'A' and 'B'. The simplest way to do this is to look at the encodings: 0 for 'A' and 1 for 'B'. Because 0 is less than 1, we say 'A' is less than 'B'. Now, what we've just done is apply a collation to our character set. The collation is a set of rules (only one rule in this case): "compare the encodings." We call this simplest of all possible collations a binary collation.

But what if we want to say that the lowercase and uppercase letters are equivalent? Then we would have at least two rules: (1) treat the lowercase letters 'a' and 'b' as equivalent to 'A' and 'B'; (2) then compare the encodings. We call this a case-insensitive collation. It's a little more complex than a binary collation.

In real life, most character sets have many characters: not just 'A' and 'B' but whole alphabets, sometimes multiple alphabets or eastern writing systems with thousands of characters, along with many special symbols and punctuation marks. Also in real life, most collations have many rules: not just case insensitivity but also accent insensitivity (an "accent" is a mark attached to a character as in German 'ö') and multiple-character mappings (such as the rule that 'ö' = 'OE' in one of the two German collations).

How can I add a string to the end of each line in Vim?

Even shorter than the :search command:

:%norm A*

This is what it means:

 %       = for every line
 norm    = type the following commands
 A*      = append '*' to the end of current line

jQuery DataTables: control table width

Check this solution too. this solved my DataTable column width issue easily

JQuery DataTables 1.10.20 introduces columns.adjust() method which fix Bootstrap toggle tab issue

 $('a[data-toggle="tab"]').on( 'shown.bs.tab', function (e) {
    $.fn.dataTable.tables( {visible: true, api: true} ).columns.adjust();
} );

Please refer the documentation : Scrolling and Bootstrap tabs

How to concat a string to xsl:value-of select="...?

The easiest way to concat a static text string to a selected value is to use element.

<a>
  <xsl:attribute name="href"> 
    <xsl:value-of select="/*/properties/property[@name='report']/@value" />
    <xsl:text>staticIconExample.png</xsl:text>
  </xsl:attribute>
</a>

Android ADB devices unauthorized

Try deleting the adbkey file from C/.android folder

and then run the commands as mentioned above i.e.

adb kill-server, adb start-server and adb devices

.

-bash: syntax error near unexpected token `newline'

The characters '<', and '>', are to indicate a place-holder, you should remove them to read:

php /usr/local/solusvm/scripts/pass.php --type=admin --comm=change --username=ADMINUSERNAME

How to have a a razor action link open in a new tab?

Looks like you are confusing Html.ActionLink() for Url.Action(). Url.Action has no parameters to set the Target, because it only returns a URL.

Based on your current code, the anchor should probably look like:

<a href="@Url.Action("RunReport", "Performance", new { reportView = Model.ReportView.ToString() })" 
   type="submit" 
   id="runReport" 
   target="_blank"
   class="button Secondary">
     @Reports.RunReport
</a>

Proper use of errors

Don't forget about switch statements:

  • Ensure handling with default.
  • instanceof can match on superclass.
  • ES6 constructor will match on the exact class.
  • Easier to read.

_x000D_
_x000D_
function handleError() {_x000D_
    try {_x000D_
        throw new RangeError();_x000D_
    }_x000D_
    catch (e) {_x000D_
        switch (e.constructor) {_x000D_
            case Error:      return console.log('generic');_x000D_
            case RangeError: return console.log('range');_x000D_
            default:         return console.log('unknown');_x000D_
        }_x000D_
    }_x000D_
}_x000D_
_x000D_
handleError();
_x000D_
_x000D_
_x000D_

ASP.NET jQuery Ajax Calling Code-Behind Method

This hasn't solved my problem too, so I changed the parameters slightly.
This code worked for me:

var dataValue = "{ name: 'person', isGoing: 'true', returnAddress: 'returnEmail' }";

$.ajax({
    type: "POST",
    url: "Default.aspx/OnSubmit",
    data: dataValue,
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
    },
    success: function (result) {
        alert("We returned: " + result.d);
    }
});

Detect if the device is iPhone X

#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
#define IS_IPHONE_X (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 812.0f)

Debugging "Element is not clickable at point" error

I am facing the same issue and I used delay and it is working fine my side. Page was getting refresh and getting the other locators.

Thread.sleep(2000);
        Click(By.xpath("//*[@id='instructions_container']/a"));

Selenium IDE - Command to wait for 5 seconds

This will do what you are looking for in C# (WebDriver/Selenium 2.0)

var browser = new FirefoxDriver();
var overallTimeout = Timespan.FromSeconds(10);
var sleepCycle = TimeSpan.FromMiliseconds(50);
var wait = new WebDriverWait(new SystemClock(), browser, overallTimeout, sleepCycle);
var hasTimedOut = wait.Until(_ => /* here goes code that looks for the map */);

And never use Thread.Sleep because it makes your tests unreliable

Is there any JSON Web Token (JWT) example in C#?

After all these months have passed after the original question, it's now worth pointing out that Microsoft has devised a solution of their own. See http://blogs.msdn.com/b/vbertocci/archive/2012/11/20/introducing-the-developer-preview-of-the-json-web-token-handler-for-the-microsoft-net-framework-4-5.aspx for details.

Vagrant ssh authentication failure

also could not get beyond:

default: SSH auth method: private key

When I used the VirtualBox GUI, it told me there was an OS processor mismatch.

To get vagrant up progressing further, in the BIOS settings I had to counter-intuitively:

Disable: Virtualisation

Enable: VT-X

Try toggling these setting in your BIOS.

"Line contains NULL byte" in CSV reader (Python)

A tricky way:

If you develop under Lunux, you can use all the power of sed:

from subprocess import check_call, CalledProcessError

PATH_TO_FILE = '/home/user/some/path/to/file.csv'

try:
    check_call("sed -i -e 's|\\x0||g' {}".format(PATH_TO_FILE), shell=True)
except CalledProcessError as err:
    print(err)    

The most efficient solution for huge files.

Checked for Python3, Kubuntu

Location of the mongodb database on mac

The default data directory for MongoDB is /data/db.

This can be overridden by a dbpath option specified on the command line or in a configuration file.

If you install MongoDB via a package manager such as Homebrew or MacPorts these installs typically create a default data directory other than /data/db and set the dbpath in a configuration file.

If a dbpath was provided to mongod on startup you can check the value in the mongo shell:

db.serverCmdLineOpts()

You would see a value like:

"parsed" : {
    "dbpath" : "/usr/local/data"
},

Run a single migration file

If you want to run it from console, this is what you are looking for:

$ rails console
irb(main)> require "#{Rails.root.to_s}/db/migrate/XXXXX_my_migration.rb"
irb(main)> AddFoo.migrate(:up)

I tried the other answers, but requiring without Rails.root didnt work for me.

Also, .migrate(:up) part forces the migration to rerun regardless if it has already run or not. This is useful for when you already ran a migration, have kinda undone it by messing around with the db and want a quick solution to have it up again.

Difference between Spring MVC and Struts MVC

The main difference between struts & spring MVC is about the difference between Aspect Oriented Programming (AOP) & Object oriented programming (OOP).

Spring makes application loosely coupled by using Dependency Injection.The core of the Spring Framework is the IoC container.

OOP can do everything that AOP does but different approach. In other word, AOP complements OOP by providing another way of thinking about program structure.

Practically, when you want to apply same changes for many files. It should be exhausted work with Struts to add same code for tons of files. Instead Spring write new changes somewhere else and inject to the files.

Some related terminologies of AOP is cross-cutting concerns, Aspect, Dependency Injection...

Ansible - Save registered variable to file

---
- hosts: all
  tasks:
  - name: Gather Version
    debug:
     msg: "The server Operating system is {{ ansible_distribution }} {{ ansible_distribution_major_version }}"
  - name: Write  Version
    local_action: shell echo "This is  {{ ansible_distribution }} {{ ansible_distribution_major_version }}" >> /tmp/output

Postgresql: password authentication failed for user "postgres"

As a rule of thumb: YOU SHOULD NEVER EVER SET A PASSWORD FOR THE POSTGRES USER.

If you need a superuser access from pgAdmin, make another superuser. That way, if the credentials for that superuser is compromised, you can always ssh into the actual database host and manually delete the superuser using

sudo -u postgres -c "DROP ROLE superuser;"

How to escape JSON string?

Yep, just add the following function to your Utils class or something:

    public static string cleanForJSON(string s)
    {
        if (s == null || s.Length == 0) {
            return "";
        }

        char         c = '\0';
        int          i;
        int          len = s.Length;
        StringBuilder sb = new StringBuilder(len + 4);
        String       t;

        for (i = 0; i < len; i += 1) {
            c = s[i];
            switch (c) {
                case '\\':
                case '"':
                    sb.Append('\\');
                    sb.Append(c);
                    break;
                case '/':
                    sb.Append('\\');
                    sb.Append(c);
                    break;
                case '\b':
                    sb.Append("\\b");
                    break;
                case '\t':
                    sb.Append("\\t");
                    break;
                case '\n':
                    sb.Append("\\n");
                    break;
                case '\f':
                    sb.Append("\\f");
                    break;
                case '\r':
                    sb.Append("\\r");
                    break;
                default:
                    if (c < ' ') {
                        t = "000" + String.Format("X", c);
                        sb.Append("\\u" + t.Substring(t.Length - 4));
                    } else {
                        sb.Append(c);
                    }
                    break;
            }
        }
        return sb.ToString();
    }

What does "javascript:void(0)" mean?

You should always have an href on your a tags. Calling a JavaScript function that returns 'undefined' will do just fine. So will linking to '#'.

Anchor tags in Internet Explorer 6 without an href do not get the a:hover style applied.

Yes, it is terrible and a minor crime against humanity, but then again so is Internet Explorer 6 in general.

I hope this helps.

Internet Explorer 6 is actually a major crime against humanity.

Iptables setting multiple multiports in one rule

As far as i know, writing multiple matches is logical AND operation; so what your rule means is if the destination port is "59100" AND "3000" then reject connection with tcp-reset; Workaround is using -mport option. Look out for the man page.

Keep a line of text as a single line - wrap the whole line or none at all

You can use white-space: nowrap; to define this behaviour:

// HTML:

_x000D_
_x000D_
.nowrap {_x000D_
  white-space: nowrap ;_x000D_
}
_x000D_
<p>_x000D_
      <span class="nowrap">How do I wrap this line of text</span>_x000D_
      <span class="nowrap">- asked by Peter 2 days ago</span>_x000D_
    </p>
_x000D_
_x000D_
_x000D_

// CSS:
.nowrap {
  white-space: nowrap ;
}

HTML text input field with currency symbol

Since you can't do ::before with content: '$' on inputs and adding an absolutely positioned element adds extra html - I like do to a background SVG inline css.

It goes something like this:

input {
    width: 85px;
    background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' height='16px' width='85px'><text x='2' y='13' fill='gray' font-size='12' font-family='arial'>$</text></svg>");
    padding-left: 12px;
}

It outputs the following:

svg dollar sign background css

Note: the code must all be on a single line. Support is pretty good in modern browsers, but be sure to test.

Convert INT to FLOAT in SQL

In oracle db there is a trick for casting int to float (I suppose, it should also work in mysql):

select myintfield + 0.0 as myfloatfield from mytable

While @Heximal's answer works, I don't personally recommend it.

This is because it uses implicit casting. Although you didn't type CAST, either the SUM() or the 0.0 need to be cast to be the same data-types, before the + can happen. In this case the order of precedence is in your favour, and you get a float on both sides, and a float as a result of the +. But SUM(aFloatField) + 0 does not yield an INT, because the 0 is being implicitly cast to a FLOAT.

I find that in most programming cases, it is much preferable to be explicit. Don't leave things to chance, confusion, or interpretation.

If you want to be explicit, I would use the following.

CAST(SUM(sl.parts) AS FLOAT) * cp.price
-- using MySQL CAST FLOAT  requires 8.0

I won't discuss whether NUMERIC or FLOAT *(fixed point, instead of floating point)* is more appropriate, when it comes to rounding errors, etc. I'll just let you google that if you need to, but FLOAT is so massively misused that there is a lot to read about the subject already out there.

You can try the following to see what happens...

CAST(SUM(sl.parts) AS NUMERIC(10,4)) * CAST(cp.price AS NUMERIC(10,4))

Google Maps how to Show city or an Area outline

From what I searched, at this moment there is no option from Google in the Maps API v3 and there is an issue on the Google Maps API going back to 2008. There are some older questions - Add "Search Area" outline onto google maps result , Google has started highlighting search areas in Pink color. Is this feature available in Google Maps API 3? and you might find some newer answers here with updated information, but this is not a feature.

What you can do is draw shapes on your map - but for this you need to have the coordinates of the borders of your region.

Now, in order to get the administrative area boundaries, you will have to do a little work: http://www.gadm.org/country (if you are lucky and there is enough level of detail available there).

On this website you can locally download a file (there are many formats available) with the .kmz extension. Unzip it and you will have a .kml file which contains most administrative areas (cities, villages).

  <?xml version="1.0" encoding="utf-8" ?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document id="root_doc">
<Schema name="x" id="x">
    <SimpleField name="ID_0" type="int"></SimpleField>
    <SimpleField name="ISO" type="string"></SimpleField>
    <SimpleField name="NAME_0" type="string"></SimpleField>
    <SimpleField name="ID_1" type="string"></SimpleField>
    <SimpleField name="NAME_1" type="string"></SimpleField>
    <SimpleField name="ID_2" type="string"></SimpleField>
    <SimpleField name="NAME_2" type="string"></SimpleField>
    <SimpleField name="TYPE_2" type="string"></SimpleField>
    <SimpleField name="ENGTYPE_2" type="string"></SimpleField>
    <SimpleField name="NL_NAME_2" type="string"></SimpleField>
    <SimpleField name="VARNAME_2" type="string"></SimpleField>
    <SimpleField name="Shape_Length" type="float"></SimpleField>
    <SimpleField name="Shape_Area" type="float"></SimpleField>
</Schema>
<Folder><name>x</name>
  <Placemark>
    <Style><LineStyle><color>ff0000ff</color></LineStyle><PolyStyle><fill>0</fill></PolyStyle></Style>
    <ExtendedData><SchemaData schemaUrl="#x">
        <SimpleData name="ID_0">186</SimpleData>
        <SimpleData name="ISO">ROU</SimpleData>
        <SimpleData name="NAME_0">Romania</SimpleData>
        <SimpleData name="ID_1">1</SimpleData>
        <SimpleData name="NAME_1">Alba</SimpleData>
        <SimpleData name="ID_2">1</SimpleData>
        <SimpleData name="NAME_2">Abrud</SimpleData>
        <SimpleData name="TYPE_2">Comune</SimpleData>
        <SimpleData name="ENGTYPE_2">Commune</SimpleData>
        <SimpleData name="VARNAME_2">Oras Abrud</SimpleData>
        <SimpleData name="Shape_Length">0.2792904164402</SimpleData>
        <SimpleData name="Shape_Area">0.00302673357146115</SimpleData>
    </SchemaData></ExtendedData>
      <MultiGeometry><Polygon><outerBoundaryIs><LinearRing><coordinates>23.117561340332031,46.269237518310547 23.108898162841797,46.265365600585937 23.107486724853629,46.264305114746207 23.104681015014762,46.260105133056641 23.101633071899471,46.250000000000114 23.100803375244254,46.249053955078239 23.097520828247184,46.246582031250114 23.0965576171875,46.245487213134822 23.095674514770508,46.244930267334098 23.092174530029354,46.243438720703182 23.088010787963924,46.240383148193473 23.083366394043082,46.238204956054801 23.075212478637809,46.234935760498047 23.071325302123967,46.239696502685547 23.070602416992131,46.241668701171875 23.069700241088924,46.242824554443416 23.068435668945369,46.243541717529354 23.066627502441406,46.244037628173771 23.064964294433651,46.246234893798885 23.062850952148437,46.247486114501953 23.0626220703125,46.248153686523438 23.062761306762752,46.250873565673942 23.061862945556697,46.255172729492301 23.061449050903434,46.256267547607422 23.05998420715332,46.258060455322322 23.057676315307674,46.259838104248161 23.055141448974666,46.262714385986442 23.053401947021484,46.264244079589901 23.049621582031193,46.266674041748161 23.043565750122013,46.268516540527457 23.041521072387695,46.269458770751953 23.034791946411076,46.270542144775334 23.027051925659293,46.27105712890625 23.025453567504826,46.271255493164063 23.022710800170898,46.272083282470703 23.020351409912053,46.271331787109432 23.018688201904297,46.270687103271598 23.015596389770508,46.270793914794922 23.014116287231502,46.271579742431697 23.009817123413143,46.275333404541016 23.006668090820426,46.277061462402401 23.004106521606445,46.279254913330135 23.001775741577205,46.282882690429688 23.005559921264648,46.283077239990348 23.009967803955135,46.28415679931652 23.014947891235465,46.286224365234489 23.019996643066463,46.28900146484375 23.024263381958121,46.292709350586051 23.027633666992301,46.295299530029411 23.028041839599609,46.295692443847656 23.032444000244197,46.294342041015625 23.03491401672369,46.293315887451229 23.044847488403434,46.290401458740234 23.047790527343807,46.28928375244152 23.053009033203239,46.288627624511719 23.057231903076229,46.288341522216797 23.064565658569393,46.287548065185547 23.070388793945426,46.286254882812614 23.075139999389592,46.284847259521428 23.075983047485465,46.284801483154411 23.085800170898494,46.28253173828125 23.098115921020451,46.280982971191406 23.099718093872127,46.280590057373104 23.105833053588981,46.278388977050838 23.112155914306641,46.274082183837947 23.116207122802791,46.270610809326172 23.117561340332031,46.269237518310547</coordinates></LinearRing></outerBoundaryIs></Polygon></MultiGeometry>
  </Placemark>
</Folder>
</Document></kml>

From this point on, when the user searches for a city/village, you simply retrieve the boundaries and draw around those coordinates on the map - https://developers.google.com/maps/documentation/javascript/overlays#Polygons

I hope this helps you! Good luck!

border on Google Map using the above coordinates UPDATE: I made the borders of this city using the coordinates above

                   var ctaLayer = new google.maps.KmlLayer({
                       url: 'https://www.dropbox.com/s/0grhlim3q4572jp/ROU_adm2%20-%20Copy.kml?dl=1'
  });
  ctaLayer.setMap(map);

(I put a small kml file on my Dropbox containing the borders of a single city)

Note that this uses the Google built in KML system, in which it their server gets the file, computes the view and spits it back to you - it has limited usage and I used it to show you how the borders look. In your application you should be able to parse the coordinates from the kml file, put them in an array (as the polygon documentation tells you - https://developers.google.com/maps/documentation/javascript/examples/polygon-arrays ) and display them.

Note that there will be differences between the borders that Google sets on http://www.google.com/maps and the borders that you will get with this data.

Good luck! enter image description here

UPDATE: http://pastebin.com/x2V1aarJ , http://pastebin.com/Gh55EDW5 These are the javascript files (they were minified, so I used an online tool to make them readable) from the website. If you are not fully satisfied with this my solution, feel free to study them.

Best of luck!

Add all files to a commit except a single file?

We can add all the files and exclude the file which has to be removed by git reset.

git add .
git reset -- <file_name_to_exclude>

Facebook login "given URL not allowed by application configuration"

I was getting this problem while using a tunnel because I:

  1. had the tunnel url:port set in the FB app settings
  2. but was accessing the local server by pointing my browser to "http://localhost:3000"

once i started punching the tunnel url:port into the browser, i was good to go.

i'm using Rails and Facebooker, but might help others just the same.

Difference between 'struct' and 'typedef struct' in C++?

Struct is to create a data type. The typedef is to set a nickname for a data type.

How to sum up an array of integers in C#

An improvement on Theodor Zoulias's nice multi-core Parallel.ForEach implementation:

    public static ulong SumToUlongPar(this uint[] arrayToSum, int startIndex, int length, int degreeOfParallelism = 0)
    {
        var concurrentSums = new ConcurrentBag<ulong>();

        int maxDegreeOfPar = degreeOfParallelism <= 0 ? Environment.ProcessorCount : degreeOfParallelism;
        var options = new ParallelOptions() { MaxDegreeOfParallelism = maxDegreeOfPar };

        Parallel.ForEach(Partitioner.Create(startIndex, startIndex + length), options, range =>
        {
            ulong localSum = 0;
            for (int i = range.Item1; i < range.Item2; i++)
                localSum += arrayToSum[i];
            concurrentSums.Add(localSum);
        });

        ulong sum = 0;
        var sumsArray = concurrentSums.ToArray();
        for (int i = 0; i < sumsArray.Length; i++)
            sum += sumsArray[i];

        return sum;
    }

which works for unsigned integer data types, since C# only support Interlocked.Add() for int and long. The above implementation can also be easily modified to support other integer and floating-point data types to do summation in parallel using multiple cores of the CPU. It is used in the HPCsharp nuget package.

PHP foreach with Nested Array?

foreach ($tmpArray as $innerArray) {
    //  Check type
    if (is_array($innerArray)){
        //  Scan through inner loop
        foreach ($innerArray as $value) {
            echo $value;
        }
    }else{
        // one, two, three
        echo $innerArray;
    }
}

Spring RestTemplate - how to enable full debugging/logging of requests/responses?

in Spring Boot you can get the full request/response by setting this in properties (or other 12 factor method)

logging.level.org.apache.http=DEBUG

this outputs

-DEBUG .i.c.DefaultHttpClientConnectionOperator : Connecting to localhost/127.0.0.1:41827
-DEBUG .i.c.DefaultHttpClientConnectionOperator : Connection established 127.0.0.1:39546<->127.0.0.1:41827
-DEBUG o.a.http.impl.execchain.MainClientExec   : Executing request POST /v0/users HTTP/1.1
-DEBUG o.a.http.impl.execchain.MainClientExec   : Target auth state: UNCHALLENGED
-DEBUG o.a.http.impl.execchain.MainClientExec   : Proxy auth state: UNCHALLENGED
-DEBUG org.apache.http.headers                  : http-outgoing-0 >> POST /v0/users HTTP/1.1
-DEBUG org.apache.http.headers                  : http-outgoing-0 >> Content-Type: application/json;charset=UTF-8
-DEBUG org.apache.http.headers                  : http-outgoing-0 >> Content-Length: 56
-DEBUG org.apache.http.headers                  : http-outgoing-0 >> Host: localhost:41827
-DEBUG org.apache.http.headers                  : http-outgoing-0 >> Connection: Keep-Alive
-DEBUG org.apache.http.headers                  : http-outgoing-0 >> User-Agent: Apache-HttpClient/4.5.2 (Java/1.8.0_102)
-DEBUG org.apache.http.headers                  : http-outgoing-0 >> Accept-Encoding: gzip,deflate
-DEBUG org.apache.http.wire                     : http-outgoing-0 >> "POST /v0/users HTTP/1.1[\r][\n]"
-DEBUG org.apache.http.wire                     : http-outgoing-0 >> "Content-Type: application/json;charset=UTF-8[\r][\n]"
-DEBUG org.apache.http.wire                     : http-outgoing-0 >> "Content-Length: 56[\r][\n]"
-DEBUG org.apache.http.wire                     : http-outgoing-0 >> "Host: localhost:41827[\r][\n]"
-DEBUG org.apache.http.wire                     : http-outgoing-0 >> "Connection: Keep-Alive[\r][\n]"
-DEBUG org.apache.http.wire                     : http-outgoing-0 >> "User-Agent: Apache-HttpClient/4.5.2 (Java/1.8.0_102)[\r][\n]"
-DEBUG org.apache.http.wire                     : http-outgoing-0 >> "Accept-Encoding: gzip,deflate[\r][\n]"
-DEBUG org.apache.http.wire                     : http-outgoing-0 >> "[\r][\n]"
-DEBUG org.apache.http.wire                     : http-outgoing-0 >> "{"id":null,"email":"[email protected]","new":true}"

and response

-DEBUG .i.c.DefaultHttpClientConnectionOperator : Connecting to localhost/127.0.0.1:41827
-DEBUG .i.c.DefaultHttpClientConnectionOperator : Connection established 127.0.0.1:39546<->127.0.0.1:41827
-DEBUG o.a.http.impl.execchain.MainClientExec   : Executing request POST /v0/users HTTP/1.1
-DEBUG o.a.http.impl.execchain.MainClientExec   : Target auth state: UNCHALLENGED
-DEBUG o.a.http.impl.execchain.MainClientExec   : Proxy auth state: UNCHALLENGED
-DEBUG org.apache.http.headers                  : http-outgoing-0 >> POST /v0/users HTTP/1.1
-DEBUG org.apache.http.headers                  : http-outgoing-0 >> Content-Type: application/json;charset=UTF-8
-DEBUG org.apache.http.headers                  : http-outgoing-0 >> Content-Length: 56
-DEBUG org.apache.http.headers                  : http-outgoing-0 >> Host: localhost:41827
-DEBUG org.apache.http.headers                  : http-outgoing-0 >> Connection: Keep-Alive
-DEBUG org.apache.http.headers                  : http-outgoing-0 >> User-Agent: Apache-HttpClient/4.5.2 (Java/1.8.0_102)
-DEBUG org.apache.http.headers                  : http-outgoing-0 >> Accept-Encoding: gzip,deflate
-DEBUG org.apache.http.wire                     : http-outgoing-0 >> "POST /v0/users HTTP/1.1[\r][\n]"
-DEBUG org.apache.http.wire                     : http-outgoing-0 >> "Content-Type: application/json;charset=UTF-8[\r][\n]"
-DEBUG org.apache.http.wire                     : http-outgoing-0 >> "Content-Length: 56[\r][\n]"
-DEBUG org.apache.http.wire                     : http-outgoing-0 >> "Host: localhost:41827[\r][\n]"
-DEBUG org.apache.http.wire                     : http-outgoing-0 >> "Connection: Keep-Alive[\r][\n]"
-DEBUG org.apache.http.wire                     : http-outgoing-0 >> "User-Agent: Apache-HttpClient/4.5.2 (Java/1.8.0_102)[\r][\n]"
-DEBUG org.apache.http.wire                     : http-outgoing-0 >> "Accept-Encoding: gzip,deflate[\r][\n]"
-DEBUG org.apache.http.wire                     : http-outgoing-0 >> "[\r][\n]"
-DEBUG org.apache.http.wire                     : http-outgoing-0 >> "{"id":null,"email":"[email protected]","new":true}"

or just logging.level.org.apache.http.wire=DEBUG which seems to contain all of the relevant information

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

If the content is a variable, it will be necessary to concatenate it with quotation marks. It worked for me. Like this:

itemSelected(id: number){
    console.log('label contains', document.querySelector("label[for='" + id + "']"));
}

How do I control how Emacs makes backup files?

If you've ever been saved by an Emacs backup file, you probably want more of them, not less of them. It is annoying that they go in the same directory as the file you're editing, but that is easy to change. You can make all backup files go into a directory by putting something like the following in your .emacs.

(setq backup-directory-alist `(("." . "~/.saves")))

There are a number of arcane details associated with how Emacs might create your backup files. Should it rename the original and write out the edited buffer? What if the original is linked? In general, the safest but slowest bet is to always make backups by copying.

(setq backup-by-copying t)

If that's too slow for some reason you might also have a look at backup-by-copying-when-linked.

Since your backups are all in their own place now, you might want more of them, rather than less of them. Have a look at the Emacs documentation for these variables (with C-h v).

(setq delete-old-versions t
  kept-new-versions 6
  kept-old-versions 2
  version-control t)

Finally, if you absolutely must have no backup files:

(setq make-backup-files nil)

It makes me sick to think of it though.

How to Set OnClick attribute with value containing function in ie8?

You don't need to use setAttribute for that - This code works (IE8 also)

<div id="something" >Hello</div>
<script type="text/javascript" >
    (function() {
        document.getElementById("something").onclick = function() { 
            alert('hello'); 
        };
    })();
</script>

Check cell for a specific letter or set of letters

You can use RegExMatch:

=IF(RegExMatch(A1;"Bla");"YES";"NO")

MySQL/Writing file error (Errcode 28)

Run the following code:

du -sh /var/log/mysql

Perhaps mysql binary logs filled the memory, If so, follow the removal of old logs and restart the server. Also add in my.cnf:

expire_logs_days = 3

Twitter Bootstrap modal on mobile devices

Gil's answer holds promise (the library he linked to) --- but for the time being, it still doesn't work when scrolled down on the mobile device.

I solved the issue for myself using just a snippet of CSS at the end of my CSS files:

@media (max-width: 767px) {
  #content .modal.fade.in {
    top: 5%;
  }
}

The #content selector is simply an id that wraps my html so I can override Bootstrap's specificity (set to your own id wrapping your modal html).

The downside: It's not centered vertically on the mobile devices.

The upside: It's visible, and on smaller devices, a reasonably sized modal will take up much of the screen, so the "non-centering" won't be as apparent.

Why it works:

When you're at low screen sizes with Bootstrap's responsive CSS, for devices with smaller screens, it sets .modal.fade.in's 'top' to 'auto'. For some reason the mobile webkit browsers seem to have a hard time with figuring out the vertical placement with the "auto" assignment. So just switch it back to a fixed value and it works great.

Since the modal is already set to postition: absolute, the value is relative to the viewport's height, not the document height, so it works no matter how long the page is or where you're scrolled to.

Can I connect to SQL Server using Windows Authentication from Java EE webapp?

look at

http://jtds.sourceforge.net/faq.html#driverImplementation

What is the URL format used by jTDS?

The URL format for jTDS is:

jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]]

... domain Specifies the Windows domain to authenticate in. If present and the user name and password are provided, jTDS uses Windows (NTLM) authentication instead of the usual SQL Server authentication (i.e. the user and password provided are the domain user and password). This allows non-Windows clients to log in to servers which are only configured to accept Windows authentication.

If the domain parameter is present but no user name and password are provided, jTDS uses its native Single-Sign-On library and logs in with the logged Windows user's credentials (for this to work one would obviously need to be on Windows, logged into a domain, and also have the SSO library installed -- consult README.SSO in the distribution on how to do this).

How to find which version of TensorFlow is installed in my system?

Another variation, i guess :P

python3 -c 'print(__import__("tensorflow").__version__)'

Access Denied for User 'root'@'localhost' (using password: YES) - No Privileges?

Use the instructions for resetting the root password - but instead of resetting the root password, we'll going to forcefully INSERT a record into the mysql.user table

In the init file, use this instead

INSERT INTO mysql.user (Host, User, Password) VALUES ('%', 'root', password('YOURPASSWORD'));
GRANT ALL ON *.* TO 'root'@'%' WITH GRANT OPTION;

Why do some functions have underscores "__" before and after the function name?

Added an example to understand the use of __ in python. Here is the list of All __

https://docs.python.org/3/genindex-all.html#_

Certain classes of identifiers (besides keywords) have special meanings. Any use of * names, in any other context, that does not follow explicitly documented use, is subject to breakage without warning

Access restriction using __

"""
Identifiers:
-  Contain only (A-z, 0-9, and _ )
-  Start with a lowercase letter or _.
-  Single leading _ :  private
-  Double leading __ :  strong private
-  Start & End  __ : Language defined Special Name of Object/ Method
-  Class names start with an uppercase letter.
-

"""


class BankAccount(object):
    def __init__(self, name, money, password):
        self.name = name            # Public
        self._money = money         # Private : Package Level
        self.__password = password  # Super Private

    def earn_money(self, amount):
        self._money += amount
        print("Salary Received: ", amount, " Updated Balance is: ", self._money)

    def withdraw_money(self, amount):
        self._money -= amount
        print("Money Withdraw: ", amount, " Updated Balance is: ", self._money)

    def show_balance(self):
        print(" Current Balance is: ", self._money)


account = BankAccount("Hitesh", 1000, "PWD")  # Object Initalization

# Method Call
account.earn_money(100)

# Show Balance
print(account.show_balance())

print("PUBLIC ACCESS:", account.name)  # Public Access

# account._money is accessible because it is only hidden by convention
print("PROTECTED ACCESS:", account._money)  # Protected Access

# account.__password will throw error but account._BankAccount__password will not
# because __password is super private
print("PRIVATE ACCESS:", account._BankAccount__password)

# Method Call
account.withdraw_money(200)

# Show Balance
print(account.show_balance())

# account._money is accessible because it is only hidden by convention
print(account._money)  # Protected Access

Lodash .clone and .cloneDeep behaviors

Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.

As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:

var clone = _.clone(data, true);

data[1].values.d = 'x';

I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.

Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).

Find duplicate lines in a file and count how many time each line was duplicated?

In windows using "Windows PowerShell" I used the command mentioned below to achieve this

Get-Content .\file.txt | Group-Object | Select Name, Count

Also we can use the where-object Cmdlet to filter the result

Get-Content .\file.txt | Group-Object | Where-Object { $_.Count -gt 1 } | Select Name, Count

Best timestamp format for CSV/Excel?

Try MM/dd/yyyy hh:mm:ss a format.

Java code to create XML file.

xmlResponse.append("mydate>").append(this.formatDate(resultSet.getTimestamp("date"), "MM/dd/yyyy hh:mm:ss a")).append("");

public String formatDate(Date date, String format)
{
    String dateString = "";
    if(null != date)
    {
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        dateString = dateFormat.format(date);
    }
    return dateString;
}

Difference between static STATIC_URL and STATIC_ROOT on Django

All the answers above are helpful but none solved my issue. In my production file, my STATIC_URL was https://<URL>/static and I used the same STATIC_URL in my dev settings.py file.

This causes a silent failure in django/conf/urls/static.py.

The test elif not settings.DEBUG or '://' in prefix: picks up the '//' in the URL and does not add the static URL pattern, causing no static files to be found.

It would be thoughtful if Django spit out an error message stating you can't use a http(s):// with DEBUG = True

I had to change STATIC_URL to be '/static/'

How to initialize an array of custom objects

The simplest way to initialize an array

Create array

$array = @()

Create your header

$line = "" | select name,age,phone

Fill the line

$line.name = "Leandro"
$line.age = "39"
$line.phone = "555-555555"

Add line to $array

$array += $line

Result

$array

name                                                     age                                                      phone
----                                                     ---                                                      -----
Leandro                                                  39                                                       555-555555

Why and how to fix? IIS Express "The specified port is in use"

I had the same problem, but no proccess appeared neither in netstat nor in resmon.

What solved the problem for me was closing all the open browser windows.

NoClassDefFoundError - Eclipse and Android

I got the exact same problem ... To fix it, I just removed my Android Private Libs in "build path" and clicked ok ... and when i opened op the "build path" again eclipse had added them by itself again, and then it worked for me ;)...

Selector on background color of TextView

Even this works.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@color/dim_orange_btn_pressed" />
    <item android:state_focused="true" android:drawable="@color/dim_orange_btn_pressed" />
    <item android:drawable="@android:color/white" />
</selector>

I added the android:drawable attribute to each item, and their values are colors.

By the way, why do they say that color is one of the attributes of selector? They don't write that android:drawable is required.

Color State List Resource

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:color="hex_color"
        android:state_pressed=["true" | "false"]
        android:state_focused=["true" | "false"]
        android:state_selected=["true" | "false"]
        android:state_checkable=["true" | "false"]
        android:state_checked=["true" | "false"]
        android:state_enabled=["true" | "false"]
        android:state_window_focused=["true" | "false"] />
</selector>

Simple way to change the position of UIView?

aView.frame = CGRectMake(100, 200, aView.frame.size.width, aView.frame.size.height);

Excel 2010 VBA Referencing Specific Cells in other worksheets

I am going to give you a simplistic answer that hopefully will help you with VBA in general. The easiest way to learn how VBA works and how to reference and access elements is to record your macro then edit it in the VBA editor. This is how I learned VBA. It is based on visual basic so all the programming conventions of VB apply. Recording the macro lets you see how to access and do things.

you could use something like this:

var result = 0
Sheets("Sheet1").Select
result = Range("A1").Value * Range("B1").Value
Sheets("Sheet2").Select
Range("D1").Value = result

Alternatively you can also reference a cell using Cells(1,1).Value This way you can set variables and increment them as you wish. I think I am just not clear on exactly what you are trying to do but i hope this helps.

Remove title in Toolbar in appcompat-v7

Try this...

 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_landing_page); 

    .....

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_landing_page);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowTitleEnabled(false);

    .....

 }

How to insert selected columns from a CSV file to a MySQL database using LOAD DATA INFILE

if you have number of columns in your database table more than number of columns in your csv you can proceed like this:

LOAD DATA LOCAL INFILE 'pathOfFile.csv'
INTO TABLE youTable 
CHARACTER SET latin1 FIELDS TERMINATED BY ';' #you can use ',' if you have comma separated
OPTIONALLY ENCLOSED BY '"' 
ESCAPED BY '\\' 
LINES TERMINATED BY '\r\n'
(yourcolumn,yourcolumn2,yourcolumn3,yourcolumn4,...);

How to change context root of a dynamic web project in Eclipse?

In the java project, open .settings folder. there locate the file named "org.eclipse.wst.common.component" . Change tag <wb-module deploy-name="NEW_NAME"> .

Also you may want to change context root in project properties

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256

You should set signatureVersion: 'v4' in config to use new sign version:

AWS.config.update({
    signatureVersion: 'v4'
});

Works for JS sdk.

How to stop a setTimeout loop?

SIMPLIEST WAY TO HANDLE TIMEOUT LOOP

function myFunc (terminator = false) {
    if(terminator) {
        clearTimeout(timeOutVar);
    } else {
        // do something
        timeOutVar = setTimeout(function(){myFunc();}, 1000);
    }
}   
myFunc(true); //  -> start loop
myFunc(false); //  -> end loop

bootstrap 4 responsive utilities visible / hidden xs sm lg not working

Some version working

<div class="hidden-xs">Only Mobile hidden</div>
<div class="visible-xs">Only Mobile visible</div>

how to find my angular version in my project?

  1. Browser > Inspect > Element >

    <.app-root _nghost-hey-c0="" ng-version="8.2.11">

  2. In terminal

    :> ng version
    :> ng --version
    :> ng -v

Programmatically get the version number of a DLL

To get it for the assembly that was started (winform, console app, etc...)

using System.Reflection;
...
Assembly.GetEntryAssembly().GetName().Version

Find child element in AngularJS directive

jQlite (angular's "jQuery" port) doesn't support lookup by classes.

One solution would be to include jQuery in your app.

Another is using QuerySelector or QuerySelectorAll:

link: function(scope, element, attrs) {
   console.log(element[0].querySelector('.list-scrollable'))
}

We use the first item in the element array, which is the HTML element. element.eq(0) would yield the same.

FIDDLE

Getting Exception(org.apache.poi.openxml4j.exception - no content type [M1.13]) when reading xlsx file using Apache POI?

You might also see this error if you attempt to parse the same file twice from the same source.

I was parsing the file once to validate and again (from the same InputStream) to process - this produced the above error.

To get round this I parsed the source file into 2 different InputStreams, one to validate and one to process.

Best way to select random rows PostgreSQL

Starting with PostgreSQL 9.5, there's a new syntax dedicated to getting random elements from a table :

SELECT * FROM mytable TABLESAMPLE SYSTEM (5);

This example will give you 5% of elements from mytable.

See more explanation on the documentation: http://www.postgresql.org/docs/current/static/sql-select.html

Remove Top Line of Text File with PowerShell

For smaller files you could use this:

& C:\windows\system32\more +1 oldfile.csv > newfile.csv | out-null

... but it's not very effective at processing my example file of 16MB. It doesn't seem to terminate and release the lock on newfile.csv.

Setting selected values for ng-options bound select elements

Using ng-selected for selected value. I Have successfully implemented code in AngularJS v1.3.2

_x000D_
_x000D_
<select ng-model="objBillingAddress.StateId"  >_x000D_
   <option data-ng-repeat="c in States" value="{{c.StateId}}" ng-selected="objBillingAddress.BillingStateId==c.StateId">{{c.StateName}}</option>_x000D_
                                                </select>
_x000D_
_x000D_
_x000D_

How do I check if a property exists on a dynamic anonymous type in c#?

  public static bool IsPropertyExist(dynamic settings, string name)
  {
    if (settings is ExpandoObject)
      return ((IDictionary<string, object>)settings).ContainsKey(name);

    return settings.GetType().GetProperty(name) != null;
  }

  var settings = new {Filename = @"c:\temp\q.txt"};
  Console.WriteLine(IsPropertyExist(settings, "Filename"));
  Console.WriteLine(IsPropertyExist(settings, "Size"));

Output:

 True
 False

How do I display a wordpress page content?

You can achieve this by adding this simple php code block

<?php if ( have_posts() ) : while ( have_posts() ) : the_post();
      the_content();
      endwhile; else: ?>
      <p>!Sorry no posts here</p>
<?php endif; ?>

Exact difference between CharSequence and String in java

I know it a kind of obvious, but CharSequence is an interface whereas String is a concrete class :)

java.lang.String is an implementation of this interface...

Resolving a Git conflict with binary files

This procedure is to resolve binary file conflicts after you have submitted a pull request to Github:

  1. So on Github, you found your pull request has a conflict on a binary file.
  2. Now go back to the same git branch on your local computer.
  3. You (a) re-make / re-build this binary file again, and (b) commit the resulted binary file to this same git branch.
  4. Then you push this same git branch again to Github.

On Github, on your pull request, the conflict should disappear.

How to enable CORS in AngularJs

we can enable CORS in the frontend by using the ngResourse module. But most importantly, we should have this piece of code while making the ajax request in the controller,

$scope.weatherAPI = $resource(YOUR API,
     {callback: "JSON_CALLBACK"}, {get: {method: 'JSONP'}});
 $scope.weatherResult = $scope.weatherAPI.get(YOUR REQUEST DATA, if any);

Also, you must add ngResourse CDN in the script part and add as a dependency in the app module.

<script src="https://code.angularjs.org/1.2.16/angular-resource.js"></script>

Then use "ngResourse" in the app module dependency section

var routerApp = angular.module("routerApp", ["ui.router", 'ngResource']);

Javascript - Append HTML to container element without innerHTML

I am surprised that none of the answers mentioned the insertAdjacentHTML() method. Check it out here. The first parameter is where you want the string appended and takes ("beforebegin", "afterbegin", "beforeend", "afterend"). In the OP's situation you would use "beforeend". The second parameter is just the html string.

Basic usage:

var d1 = document.getElementById('one');
d1.insertAdjacentHTML('beforeend', '<div id="two">two</div>');

Show/Hide Table Rows using Javascript classes

event.preventDefault()

Doesn't work in all browsers. Instead you could return false in OnClick event.

onClick="toggle_it('tr1');toggle_it('tr2'); return false;">

Not sure if this is the best way, but I tested in IE, FF and Chrome and its working fine.

How do you refresh the MySQL configuration file without restarting?

Specific actions you can do from SQL client and you don't need to restart anything:

SET GLOBAL log = 'ON';
FLUSH LOGS;

How to run a single RSpec test?

Given you're on a rails 3 project with rspec 2, From the rails root directory:

  bundle exec rspec spec/controllers/groups_controller_spec.rb 

should definitely work. i got tired of typing that so i created an alias to shorten 'bundle exec rspec' to 'bersp'

'bundle exec' is so that it loads the exact gem environment specified in your gem file: http://gembundler.com/

Rspec2 switched from the 'spec' command to the 'rspec' command.

How to remove a column from an existing table?

The question is, can you only delete a column from an unexisting table ;-)

BEGIN TRANSACTION

IF exists (SELECT * FROM  sys.columns c 
INNER JOIN  sys.objects t ON (c.[object_id] = t.[object_id])
WHERE t.[object_id] = OBJECT_ID(N'[dbo].[MyTable]')
AND c.[name] = 'ColumnName')
    BEGIN TRY
        ALTER TABLE [dbo].[MyTable] DROP COLUMN ColumnName
    END TRY
    BEGIN CATCH
        print 'FAILED!'
    END CATCH
ELSE
    BEGIN 
        SELECT ERROR_NUMBER() AS ErrorNumber;
        print 'NO TABLE OR COLUMN FOUND !'
    END 

COMMIT  

Is there a kind of Firebug or JavaScript console debug for Android?

We are following the below steps in our project for debugging a website on mobile.

  1. Install mobogenie software on mobile and desktop (both have the same version).
  2. Open your site in mobile Google Chrome browser.
  3. Open Google Chrome on desktop. Go to Option --> More Options --> Inspect Device.
  4. Here you find a list of sites which are open on mobile and click on inspect and you get the JavaScript console which you want.

filter: progid:DXImageTransform.Microsoft.gradient is not working in ie7

Having seen your fiddle in the comments the issue is quite easy to fix. You just need to add overflow:auto or set a specific height to your div. Live example: http://jsfiddle.net/tw16/xRcXL/3/

.Tab{
    overflow:auto; /* add this */
    border:solid 1px #faa62a;
    border-bottom:none;
    padding:7px 10px;
    background:-moz-linear-gradient(center top , #FAD59F, #FA9907) repeat scroll 0 0 transparent;
    background:-webkit-gradient(linear, left top, left bottom, from(#fad59f), to(#fa9907));
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#fad59f, endColorstr=#fa9907);    
    -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#fad59f, endColorstr=#fa9907)";
}

How to mkdir only if a directory does not already exist?

Defining complex directory trees with one command

mkdir -p project/{lib/ext,bin,src,doc/{html,info,pdf},demo/stat/a}

Change Oracle port from port 8080

Just open Run SQL Command Line and login as sysadmin and then enter below command

Exec DBMS_XDB.SETHTTPPORT(8181);

That's it. You are done.....

Java - ignore exception and continue

You are already doing it in your code. Run this example below. The catch will "handle" the exception, and you can move forward, assuming whatever you caught and handled did not break code down the road which you did not anticipate.

 try{
      throw new Exception();
 }catch (Exception ex){
   ex.printStackTrace();
 }
 System.out.println("Made it!");

However, you should always handle an exception properly. You can get yourself into some pretty messy situations and write difficult to maintain code by "ignoring" exceptions. You should only do this if you are actually handling whatever went wrong with the exception to the point that it really does not affect the rest of the program.

Capturing mobile phone traffic on Wireshark

Preconditions: adb and wireshark is installed on your computer and you have a rooted android device.

  1. Download tcpdump to ~/Downloads
  2. adb push ~/Downloads/tcpdump /sdcard/
  3. adb shell
  4. su root
  5. mv /sdcard/tcpdump /data/local/
  6. cd /data/local/
  7. chmod +x tcpdump
  8. ./tcpdump -vv -i any -s 0 -w /sdcard/dump.pcap
  9. CTRL+C after you've captured enough packets.
  10. exit
  11. exit
  12. adb pull /sdcard/dump.pcap ~/Downloads/

Now you can open the pcap file using Wireshark.

git push rejected: error: failed to push some refs

git push -f if you have permission, but that will screw up anyone else who pulls from that repo, so be careful.

If that is denied, and you have access to the server, as canzar says below, you can allow this on the server with

git config receive.denyNonFastForwards false

How to run a specific Android app using Terminal?

I used all the above answers and it was giving me errors so I tried

adb shell monkey -p com.yourpackage.name -c android.intent.category.LAUNCHER 1

and it worked. One advantage is you dont have to specify your launcher activity if you use this command.

Declare an empty two-dimensional array in Javascript?

You can try something like this:-

var arr = new Array([]);

Push data:

arr[0][0] = 'abc xyz';

How to perform a LEFT JOIN in SQL Server between two SELECT statements?

SELECT * FROM 
(SELECT [UserID] FROM [User]) a
LEFT JOIN (SELECT [TailUser], [Weight] FROM [Edge] WHERE [HeadUser] = 5043) b
ON a.UserId = b.TailUser

React.js: onChange event for contentEditable

This is the is simplest solution that worked for me.

<div
  contentEditable='true'
  onInput={e => console.log('Text inside div', e.currentTarget.textContent)}
>
Text inside div
</div>

Save file Javascript with file name

function saveAs(uri, filename) {
    var link = document.createElement('a');
    if (typeof link.download === 'string') {
        document.body.appendChild(link); // Firefox requires the link to be in the body
        link.download = filename;
        link.href = uri;
        link.click();
        document.body.removeChild(link); // remove the link when done
    } else {
        location.replace(uri);
    }
}

Save internal file in my own internal folder in Android

Save:

public boolean saveFile(Context context, String mytext){
    Log.i("TESTE", "SAVE");
    try {
        FileOutputStream fos = context.openFileOutput("file_name"+".txt",Context.MODE_PRIVATE);
        Writer out = new OutputStreamWriter(fos);
        out.write(mytext);
        out.close();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

Load:

public String load(Context context){
    Log.i("TESTE", "FILE");
    try {
        FileInputStream fis = context.openFileInput("file_name"+".txt");
        BufferedReader r = new BufferedReader(new InputStreamReader(fis));
        String line= r.readLine();
        r.close();
        return line;
    } catch (IOException e) {
        e.printStackTrace();
        Log.i("TESTE", "FILE - false");
        return null;
    }
}

How can I create an array with key value pairs?

No need array_push function.if you want to add multiple item it works fine. simply try this and it worked for me

class line_details {
   var $commission_one=array();
   foreach($_SESSION['commission'] as $key=>$data){
          $row=  explode('-', $key);
          $this->commission_one[$row['0']]= $row['1'];            
   }

}

How do I display images from Google Drive on a website?

I have the same problem right now but this article helps me. Updates for the year 2020!

I got the solution from this article:
https://dev.to/imamcu07/embed-or-display-image-to-html-page-from-google-drive-3ign

These are the steps from the article:

  1. Upload your image to google drive.
  2. Share your image from the sharing option.
  3. Copy your sharing link (Sample: https://drive.google.com/file/d/14hz3ySPn-zBd4Tu3NtY1F05LSGdFfWvp/view?usp=sharing)
  4. Copy the id from your link, in the above link, the id is: 14hz3ySPn-zBd4Tu3NtY1F05LSGdFfWvp
  5. Have a look at the below link and replace the ID. https://drive.google.com/thumbnail?id=1jNWSPr_BOSbm7iIJQTTbl7lXX06NH9_r

After Replace ID: https://drive.google.com/thumbnail?id=14hz3ySPn-zBd4Tu3NtY1F05LSGdFfWvp

  1. Now insert the link to your <img> tag.

And now it should work.

Cannot open local file - Chrome: Not allowed to load local resource

Chrome specifically blocks local file access this way for security reasons.

Here's a workaround to enable the flag in Chrome (and open your system up to vulnerabilities):

c:\Program Files (x86)\google\chrome\Application\chrome.exe --allow-file-access-from-files

Simple file write function in C++

The function declaration int writeFile () ; seems to be missing in the code. Add int writeFile () ; before the function main()

How to close Browser Tab After Submitting a Form?

try onsubmit="submit(); window.close()"

Node Express sending image files as API response

a proper solution with streams and error handling is below:

const fs = require('fs')
const stream = require('stream')

app.get('/report/:chart_id/:user_id',(req, res) => {
  const r = fs.createReadStream('path to file') // or any other way to get a readable stream
  const ps = new stream.PassThrough() // <---- this makes a trick with stream error handling
  stream.pipeline(
   r,
   ps, // <---- this makes a trick with stream error handling
   (err) => {
    if (err) {
      console.log(err) // No such file or any other kind of error
      return res.sendStatus(400); 
    }
  })
  ps.pipe(res) // <---- this makes a trick with stream error handling
})

with Node older then 10 you will need to use pump instead of pipeline.

How do I disable form resizing for users?

Change the FormBorderStyle to one of the fixed values: FixedSingle, Fixed3D, FixedDialog or FixedToolWindow.

The FormBorderStyle property is under the Appearance category.

Or check this:

// Define the border style of the form to a dialog box.
form1.FormBorderStyle = FormBorderStyle.FixedDialog;

// Set the MaximizeBox to false to remove the maximize box.
form1.MaximizeBox = false;

// Set the MinimizeBox to false to remove the minimize box.
form1.MinimizeBox = false;

// Set the start position of the form to the center of the screen.
form1.StartPosition = FormStartPosition.CenterScreen;

// Display the form as a modal dialog box.
form1.ShowDialog();

Using Java to find substring of a bigger string using Regular Expression

If you simply need to get whatever is between [], the you can use \[([^\]]*)\] like this:

Pattern regex = Pattern.compile("\\[([^\\]]*)\\]");
Matcher m = regex.matcher(str);
if (m.find()) {
    result = m.group();
}

If you need it to be of the form identifier + [ + content + ] then you can limit extracting the content only when the identifier is a alphanumerical:

[a-zA-Z][a-z-A-Z0-9_]*\s*\[([^\]]*)\]

This will validate things like Foo [Bar], or myDevice_123["input"] for instance.

Main issue

The main problem is when you want to extract the content of something like this:

FOO[BAR[CAT[123]]+DOG[FOO]]

The Regex won't work and will return BAR[CAT[123 and FOO.
If we change the Regex to \[(.*)\] then we're OK but then, if you're trying to extract the content from more complex things like:

FOO[BAR[CAT[123]]+DOG[FOO]] = myOtherFoo[BAR[5]]

None of the Regexes will work.

The most accurate Regex to extract the proper content in all cases would be a lot more complex as it would need to balance [] pairs and give you they content.

A simpler solution

If your problems is getting complex and the content of the [] arbitrary, you could instead balance the pairs of [] and extract the string using plain old code rathe than a Regex:

int i;
int brackets = 0;
string c;
result = "";
for (i = input.indexOf("["); i < str.length; i++) {
    c = str.substring(i, i + 1);
    if (c == '[') {
        brackets++;
    } else if (c == ']') {
        brackets--;
        if (brackets <= 0) 
            break;
    }
    result = result + c;
}   

This is more pseudo-code than real code, I'm not a Java coder so I don't know if the syntax is correct, but it should be easy enough to improve upon.
What count is that this code should work and allow you to extract the content of the [], however complex it is.

Remove duplicates from an array of objects in JavaScript

Here is another technique to find number of duplicate and and remove it easily from you data object. "dupsCount" is number of duplicate files count. sort your data first then remove. it will gives you fastest duplication remove.

  dataArray.sort(function (a, b) {
            var textA = a.name.toUpperCase();
            var textB = b.name.toUpperCase();
            return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
        });
        for (var i = 0; i < dataArray.length - 1; ) {
            if (dataArray[i].name == dataArray[i + 1].name) {
                dupsCount++;
                dataArray.splice(i, 1);
            } else {
                i++;
            }
        }

How do you do a limit query in JPQL or HQL?

String hql = "select userName from AccountInfo order by points desc 5";

This worked for me without using setmaxResults();

Just provide the max value in the last (in this case 5) without using the keyword limit. :P

MySQL said: Documentation #1045 - Access denied for user 'root'@'localhost' (using password: NO)

My.ini from the file #password and #bind-address="127.0.0.1" are commented change the password to root and uncomment bind-address="127.0.0.1" and from the file cds.php change the

mysql_connect("localhost", "root", ""); to
mysql_connect("localhost", "root", "root");

Stop the Mysql services and try login again it got logged in.

Font.createFont(..) set color and size (java.awt.Font)

To set the color of a font, you must first initialize the color by doing this:

Color maroon = new Color (128, 0, 0);

Once you've done that, you then put:

Font font = new Font ("Courier New", 1, 25); //Initializes the font
c.setColor (maroon); //Sets the color of the font
c.setFont (font); //Sets the font
c.drawString ("Your text here", locationX, locationY); //Outputs the string

Note: The 1 represents the type of font and this can be used to replace Font.PLAIN and the 25 represents the size of your font.

Postgres integer arrays as parameters?

See: http://www.postgresql.org/docs/9.1/static/arrays.html

If your non-native driver still does not allow you to pass arrays, then you can:

  • pass a string representation of an array (which your stored procedure can then parse into an array -- see string_to_array)

    CREATE FUNCTION my_method(TEXT) RETURNS VOID AS $$ 
    DECLARE
           ids INT[];
    BEGIN
           ids = string_to_array($1,',');
           ...
    END $$ LANGUAGE plpgsql;
    

    then

    SELECT my_method(:1)
    

    with :1 = '1,2,3,4'

  • rely on Postgres itself to cast from a string to an array

    CREATE FUNCTION my_method(INT[]) RETURNS VOID AS $$ 
           ...
    END $$ LANGUAGE plpgsql;
    

    then

    SELECT my_method('{1,2,3,4}')
    
  • choose not to use bind variables and issue an explicit command string with all parameters spelled out instead (make sure to validate or escape all parameters coming from outside to avoid SQL injection attacks.)

    CREATE FUNCTION my_method(INT[]) RETURNS VOID AS $$ 
           ...
    END $$ LANGUAGE plpgsql;
    

    then

    SELECT my_method(ARRAY [1,2,3,4])
    

Virtualbox shared folder permissions

In my personal experience, it's difficult to enable shared folders in VirtualBox but it Is posible. I have a debian Buster guest virtual machine installed in my Windows 10 host.

I don't recognize exactly what did it, but I remember I went to Windows defender, my antivirus to see if they recognize VirtualBox as a program and not as a virus. After that, I press right click on the document file and allowed to share the folder and I gave click to some buttons there and accepted to share with groups and with muy user in Windows 10.

Also, I found a webpage of Windows about something like virtual machines that I don't remember well, but it took me to a panel and I had to change three things double clicking so when I update Windows, it recognizes my virtual machine. Also, in muy debian, in the terminal, using some command lines, muy VirtualBox recognized my user giving permissions, I based on some info in the Ubuntu forums. I put all what I remember.

Locate the nginx.conf file my nginx is actually using

In addition to @Daniel Li's answer, the nginx installation with Valet would use the Velet configuration as well, this is found in "/usr/local/etc/nginx/valet/valet.conf". The nginx.conf file would have imported this Valet conf file. The settings you need may be in the Valet file.

Xcode 'CodeSign error: code signing is required'

Summarised form an answer to Xcode fails with "Code Signing" Error

project.pbxproj files can be merged in such a way that two CODE_SIGN_IDENTITY lines can be inserted. Deleting one of these normally fixes the issue.

I have created simple script to help diagnose this issue it can be found here: https://gist.github.com/4339226

A full answer can be found here.

mean() warning: argument is not numeric or logical: returning NA

The same error appears if you do not use the correct (numeric) format of your data in your data.frame column using mean() function. Therefore, check your data using str(data.frame&column) function to see what data type you have, and convert it to numeric format if necessary. For example, if your data is Character convert it with as.numeric(data.frame$column), or as a factor with as.numeric(as.character(data.frame$column)). The mean function does not work with types other than numeric.

How to get all key in JSON object (javascript)

var input = {"document":
  {"people":[
    {"name":["Harry Potter"],"age":["18"],"gender":["Male"]},
    {"name":["hermione granger"],"age":["18"],"gender":["Female"]},
  ]}
}

var keys = [];
for(var i = 0;i<input.document.people.length;i++)
{
    Object.keys(input.document.people[i]).forEach(function(key){
        if(keys.indexOf(key) == -1)
        {
            keys.push(key);
        }
    });
}
console.log(keys);

regular expression for Indian mobile numbers

Here's a regex designed to match typical phone numbers:

^(((\+?\(91\))|0|((00|\+)?91))-?)?[7-9]\d{9}$

How do I implement charts in Bootstrap?

Github did this using the HTML canvas element.

This specification defines the 2D Context for the HTML canvas element. The 2D Context provides objects, methods, and properties to draw and manipulate graphics on a canvas drawing surface.

If you use a browser inspector, you see inside every list element a div with a canvas element.

<div class="participation-graph">
   <canvas class="bars" data-color-all="#F5F5F5" data-color-owner="#F5F5F5" data-source="/mxcl/homebrew/graphs/owner_participation" height="80" width="640"></canvas>
</div>

With CSS (z-index, position...) you can put that canvas in the background of a li element or table, in your case.

Do a search about jquery pluggins that fit your requirement.

Hope this pointers help you to achieve that.

GitLab git user password

To add yet another reason to the list ... in my case I found this problem was being caused by an SELinux permissions problem on the server. This is worth checking if your server is running Fedora / CentOS / Red Hat. To test this scenario you can run:

Client: ssh -vT git@<gitlab-server> -- asks for password
Server: sudo setenforce 0
Client: ssh -vT git@<gitlab-server> -- succeeds
Server: sudo setenforce 1

In my case the gitlab/git user's authorized_keys file had the wrong SELinux file context, and the ssh service was being denied permission to read it. I fixed this on the server side as follows:

sudo semanage fcontext -a -t ssh_home_t /gitlab/.ssh/
sudo semanage fcontext -a -t ssh_home_t /gitlab/.ssh/authorized_keys
sudo restorecon -F -Rv /gitlab/.ssh/

And I was then able to git clone on the client side as expected.

How to create correct JSONArray in Java using JSONObject

Small reusable method can be written for creating person json object to avoid duplicate code

JSONObject  getPerson(String firstName, String lastName){
   JSONObject person = new JSONObject();
   person .put("firstName", firstName);
   person .put("lastName", lastName);
   return person ;
} 

public JSONObject getJsonResponse(){

    JSONArray employees = new JSONArray();
    employees.put(getPerson("John","Doe"));
    employees.put(getPerson("Anna","Smith"));
    employees.put(getPerson("Peter","Jones"));

    JSONArray managers = new JSONArray();
    managers.put(getPerson("John","Doe"));
    managers.put(getPerson("Anna","Smith"));
    managers.put(getPerson("Peter","Jones"));

    JSONObject response= new JSONObject();
    response.put("employees", employees );
    response.put("manager", managers );
    return response;
  }

How do I set <table> border width with CSS?

Doing borders on tables with css is a bit more complicated (but not as much, see this jsfiddle as example):

_x000D_
_x000D_
table {_x000D_
  border-collapse: collapse;_x000D_
  border: 1px solid black;_x000D_
}_x000D_
_x000D_
table td {_x000D_
  border: 1px solid black;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>test</td>_x000D_
    <td>test</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How can I compare two ordered lists in python?

The expression a == b should do the job.

do { ... } while (0) — what is it good for?

It's the only construct in C that you can use to #define a multistatement operation, put a semicolon after, and still use within an if statement. An example might help:

#define FOO(x) foo(x); bar(x)

if (condition)
    FOO(x);
else // syntax error here
    ...;

Even using braces doesn't help:

#define FOO(x) { foo(x); bar(x); }

Using this in an if statement would require that you omit the semicolon, which is counterintuitive:

if (condition)
    FOO(x)
else
    ...

If you define FOO like this:

#define FOO(x) do { foo(x); bar(x); } while (0)

then the following is syntactically correct:

if (condition)
    FOO(x);
else
    ....

Producer/Consumer threads using a Queue

You are reinventing the wheel.

If you need persistence and other enterprise features use JMS (I'd suggest ActiveMq).

If you need fast in-memory queues use one of the impementations of java's Queue.

If you need to support java 1.4 or earlier, use Doug Lea's excellent concurrent package.