Programs & Examples On #Autosize

A user interface implementation to automatically resize a control or element to accommodate its contents.

Wpf control size to content?

I had a user control which sat on page in a free form way, not constrained by another container, and the contents within the user control would not auto size but expand to the full size of what the user control was handed.

To get the user control to simply size to its content, for height only, I placed it into a grid with on row set to auto size such as this:

<Grid Margin="0,60,10,200">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <controls1:HelpPanel x:Name="HelpInfoPanel"
                         Visibility="Visible"
                         Width="570"
                         HorizontalAlignment="Right"
                         ItemsSource="{Binding HelpItems}"
                         Background="#FF313131" />
</Grid>

How to set width to 100% in WPF

It is the container of the Grid that is imposing on its width. In this case, that's a ListBoxItem, which is left-aligned by default. You can set it to stretch as follows:

<ListBox>
    <!-- other XAML omitted, you just need to add the following bit -->
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="HorizontalAlignment" Value="Stretch"/>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

How to auto-size an iFrame?

My solution, (using jquery):

<iframe id="Iframe1" class="tabFrame" width="100%" height="100%" scrolling="no" src="http://samedomain" frameborder="0" >
</iframe>  
<script type="text/javascript">
    $(function () {

        $('.tabFrame').load(function () {
            var iframeContentWindow = this.contentWindow;
            var height = iframeContentWindow.$(document).height();
            this.style.height = height + 'px';
        });
    });
</script>

react native get TextInput value

This work for me

    <Form>

    <TextInput
    style={{height: 40}}
    placeholder="userName"
    onChangeText={(text) => this.userName = text}
    />

    <TextInput
    style={{height: 40}}
    placeholder="Password"
    onChangeText={(text) => this.Password = text}
    />


    <Button 
    title="Sign in!" 
    onPress={this._signInAsync} 
    />

    </Form>

and

  _signInAsync = async () => {
        console.log(this.userName)
        console.log(this.Password) 
  };

What is jQuery Unobtrusive Validation?

jQuery Validation Unobtrusive Native is a collection of ASP.Net MVC HTML helper extensions. These make use of jQuery Validation's native support for validation driven by HTML 5 data attributes. Microsoft shipped jquery.validate.unobtrusive.js back with MVC 3. It provided a way to apply data model validations to the client side using a combination of jQuery Validation and HTML 5 data attributes (that's the "unobtrusive" part).

When should we use Observer and Observable?

If the interviewer asks to implement Observer design pattern without using Observer classes and interfaces, you can use the following simple example!

MyObserver as observer interface

interface MyObserver {

    void update(MyObservable o, Object arg);
}

MyObservable as Observable class

class MyObservable
{
    ArrayList<MyObserver> myObserverList = new ArrayList<MyObserver>();

    boolean changeFlag = false;

    public void notifyObservers(Object o)
    {
        if (hasChanged())
        {
            for(MyObserver mo : myObserverList) {
                mo.update(this, o);
            }
            clearChanged();
        }
    }


    public void addObserver(MyObserver o) {
        myObserverList.add(o);        
    }

    public void setChanged() {
        changeFlag = true;
    }

    public boolean hasChanged() {
        return changeFlag;
    }

    protected void clearChanged() {
        changeFlag = false;
    }

    // ...
}

Your example with MyObserver and MyObservable!

class MessageBoard extends MyObservable {
  private String message;

  public String getMessage() {
    return message;
  }

  public void changeMessage(String message) {
    this.message = message;
    setChanged();
    notifyObservers(message);
  }

  public static void main(String[] args) {
    MessageBoard board = new MessageBoard();
    Student bob = new Student();
    Student joe = new Student();
    board.addObserver(bob);
    board.addObserver(joe);
    board.changeMessage("More Homework!");
  }
}

class Student implements MyObserver {

  @Override
  public void update(MyObservable o, Object arg) {
    System.out.println("Message board changed: " + arg);
  }

}

int to string in MySQL

select t2.* 
from t1 join t2 on t2.url='site.com/path/%' + cast(t1.id as varchar)  + '%/more' 
where t1.id > 9000

Using concat like suggested is even better though

Cosine Similarity between 2 Number Lists

You can use this simple function to calculate the cosine similarity:

def cosine_similarity(a, b):
return sum([i*j for i,j in zip(a, b)])/(math.sqrt(sum([i*i for i in a]))* math.sqrt(sum([i*i for i in b])))

Shared-memory objects in multiprocessing

If you use an operating system that uses copy-on-write fork() semantics (like any common unix), then as long as you never alter your data structure it will be available to all child processes without taking up additional memory. You will not have to do anything special (except make absolutely sure you don't alter the object).

The most efficient thing you can do for your problem would be to pack your array into an efficient array structure (using numpy or array), place that in shared memory, wrap it with multiprocessing.Array, and pass that to your functions. This answer shows how to do that.

If you want a writeable shared object, then you will need to wrap it with some kind of synchronization or locking. multiprocessing provides two methods of doing this: one using shared memory (suitable for simple values, arrays, or ctypes) or a Manager proxy, where one process holds the memory and a manager arbitrates access to it from other processes (even over a network).

The Manager approach can be used with arbitrary Python objects, but will be slower than the equivalent using shared memory because the objects need to be serialized/deserialized and sent between processes.

There are a wealth of parallel processing libraries and approaches available in Python. multiprocessing is an excellent and well rounded library, but if you have special needs perhaps one of the other approaches may be better.

How to write a link like <a href="#id"> which link to the same page in PHP?

try this

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
    <body>
        <a href="#name">click me</a>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
        <div name="name" id="name">here</div>
    </body>
    </html>

How to determine if object is in array

You can just use the equality operator: ==. Objects are checked by reference by default, so you don't even need to use the === operator.

try this, just make sure you're using the correct variable reference in the place of car1:

var i, car, l = cars.length;

for (i = 0; i < l; i++)
{
  if ((car = cars[i]) == car1)
  {
    break;
  }
  else car = null;
}

Edit to add:

An array extension was mentioned, so here's the code for it:

Array.prototype.contains = Array.prototype.contains || function(obj)
{
  var i, l = this.length;
  for (i = 0; i < l; i++)
  {
    if (this[i] == obj) return true;
  }
  return false;
};

Note that I'm caching the length value, as the Array's length property is actually an accessor, which is marginally slower than an internal variable.

Download and install an ipa from self hosted url on iOS

Create a Virtual Machine with Windows running on it and download the file to a shared folder. :-D

XAMPP permissions on Mac OS X?

Best solution for MAC OS Catalina Xampp

  1. Open Finder
  2. Press Cmd + shift + C
  3. Macintosh HD => Users => copy {username}

  4. Open /Applications/XAMPP/xamppfiles/etc/httpd.conf

    Find User daemon edit daemon => {username}

  5. Xampp Manage Server => Restart all

If you encounter problems in phpMyAdmin:

1. Browser (Chrome) restart

Goodluck

Opacity CSS not working in IE8

CSS

I used to use the following from CSS-Tricks:

.transparent_class {
  /* IE 8 */
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";

  /* IE 5-7 */
  filter: alpha(opacity=50);

  /* Netscape */
  -moz-opacity: 0.5;

  /* Safari 1.x */
  -khtml-opacity: 0.5;

  /* Good browsers */
  opacity: 0.5;
}

Compass

However, a better solution is to use the Opacity Compass mixin, all you need to do is to @include opacity(0.1); and it will take care of any cross-browser issues for you. You can find an example here.

Simple logical operators in Bash

A very portable version (even to legacy bourne shell):

if [ "$varA" = 1 -a \( "$varB" = "t1" -o "$varB" = "t2" \) ]
then    do-something
fi

This has the additional quality of running only one subprocess at most (which is the process [), whatever the shell flavor.

Replace = with -eq if variables contain numeric values, e.g.

  • 3 -eq 03 is true, but
  • 3 = 03 is false. (string comparison)

Generate an integer sequence in MySQL

There is no sequence number generator (CREATE SEQUENCE) in MySQL. Closest thing is AUTO_INCREMENT, which can help you construct the table.

PHP Deprecated: Methods with the same name

As mentioned in the error, the official manual and the comments:

Replace

public function TSStatus($host, $queryPort)

with

public function __construct($host, $queryPort)

How to format Joda-Time DateTime to only mm/dd/yyyy?

UPDATED:

You can: create a constant:

private static final DateTimeFormatter DATE_FORMATTER_YYYY_MM_DD =
          DateTimeFormat.forPattern("yyyy-MM-dd"); // or whatever pattern that you need.

This DateTimeFormat is importing from: (be careful with that)

import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter;

Parse the Date with:

DateTime.parse(dateTimeScheduled.toString(), DATE_FORMATTER_YYYY_MM_DD);

Before:
DateTime.parse("201711201515",DateTimeFormat.forPattern("yyyyMMddHHmm")).toString("yyyyMMdd");

if want datetime:

DateTime.parse("201711201515", DateTimeFormat.forPattern("yyyyMMddHHmm")).withTimeAtStartOfDay();

Bootstrap dropdown not working

Working demo: http://codebins.com/bin/4ldqp73

try this

<ul class='nav'>
  <li class='active'>Home</li>
  <li>
    <div class="dropdown">
      <a class="dropdown-toggle" data-toggle="dropdown" href="#">Personal asset loans</a>
      <ul class="dropdown-menu" role="menu" aria-labelledby="dLabel">            
        <li><a href="#">asds</a></li>
        <li class="divider"></li>
      </ul>
    </div>   
    </li>
    <li>Payday loans</li>
  <li>About</li>
  <li>Contact</li>
</ul>

Xcode 'CodeSign error: code signing is required'

  1. Populate "Code Signing" in both "Project" and "Targets" section
  2. Select valid entries in "Code Signing Identity" in both "Debug" and "Release"
  3. Under "Debug" select you Developer certificate
  4. Under "Release" select your Distributor certificate

Following these 4 steps always solves my issues.

Converting Chart.js canvas chart to image using .toDataUrl() results in blank image

The chart seem to be async so you will probably need to provide a callback when the animation has finished or else the canvas will be empty.

var options = {
    bezierCurve : false,
    onAnimationComplete: done  /// calls function done() {} at end
};

Javascript : get <img> src and set as variable?

var youtubeimgsrc = document.getElementById('youtubeimg').src;
document.write(youtubeimgsrc);

Here's a fiddle for you http://jsfiddle.net/cruxst/dvrEN/

Java: int[] array vs int array[]

Both are the same. I usually use int[] array = new int[10];, because of better (contiguous) readability of the type int[].

Java Embedded Databases Comparison

I use Apache Derby for pretty much all of my embedded database needs. You can also use Sun's Java DB that is based on Derby but the latest version of Derby is much newer. It supports a lot of options that commercial, native databases support but is much smaller and easier to embed. I've had some database tables with more than a million records with no issues.

I used to use HSQLDB and Hypersonic about 3 years ago. It has some major performance issues at the time and I switch to Derby from it because of those issues. Derby has been solid even when it was in incubator at Apache.

MySql: Tinyint (2) vs tinyint(1) - what is the difference?

It means display width

Whether you use tinyint(1) or tinyint(2), it does not make any difference.

I always use tinyint(1) and int(11), I used several mysql clients (navicat, sequel pro).

It does not mean anything AT ALL! I ran a test, all above clients or even the command-line client seems to ignore this.

But, display width is most important if you are using ZEROFILL option, for example your table has following 2 columns:

A tinyint(2) zerofill

B tinyint(4) zerofill

both columns has the value of 1, output for column A would be 01 and 0001 for B, as seen in screenshot below :)

zerofill with displaywidth

When do I use super()?

The first line of your subclass' constructor must be a call to super() to ensure that the constructor of the superclass is called.

How can I open a website in my web browser using Python?

import webbrowser

webbrowser.open("http://www.google.com")

The link will be opened in default web browser unless specified

Toggle display:none style with JavaScript

You can do this through straight javascript and DOM, but I really recommend learning JQuery. Here is a function you can use to actually toggle that object.

http://api.jquery.com/toggle/

EDIT: Adding the actual code:

Solution:

HTML snippet:

<a href="#" id="showAll" title="Show Tags">Show All Tags</a>
<ul id="tags" class="subforums" style="display:none;overflow-x: visible; overflow-y: visible; ">
    <li>Tag 1</li>
    <li>Tag 2</li>
    <li>Tag 3</li>
    <li>Tag 4</li>
    <li>Tag 5</li>
</ul>

Javascript code using JQuery from Google's Content Distribution Network: https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js

$(function() {
    $('#showAll').click(function(){  //Adds click event listener  
        $('#tags').toggle('slow'); // Toggles visibility.  Use the 'slow' parameter to add a nice effect.
    });
});

You can test directly from this link: http://jsfiddle.net/vssJr/5/

Additional Comments on JQuery:

Someone has suggested that using JQuery for something like this is wrong because it is a 50k Library. I have a strong opinion against that.

JQuery is widely used because of the huge advantages it offers (like many other javascript frameworks). Additionally, JQuery is hosted by Content Distribution Networks (CDNs) like Google's CDN that will guarantee that the library is cached in the client's browser. It will have minimal impact on the client.

Additionally, with JQuery you can use powerful selectors, adding event listener, and use functions that are for the most part guaranteed to be cross-browser.

If you are a beginner and want to learn Javascript, please don't discount frameworks like JQuery. It will make your life so much easier.

Occurrences of substring in a string

I'm very surprised no one has mentioned this one liner. It's simple, concise and performs slightly better than str.split(target, -1).length-1

public static int count(String str, String target) {
    return (str.length() - str.replace(target, "").length()) / target.length();
}

Adding a Time to a DateTime in C#

Using https://github.com/FluentDateTime/FluentDateTime

DateTime dateTime = DateTime.Now;
DateTime combined = dateTime + 36.Hours();
Console.WriteLine(combined);

Parse rfc3339 date strings in Python?

This has already been answered here: How do I translate a ISO 8601 datetime string into a Python datetime object?

d = datetime.datetime.strptime( "2012-10-09T19:00:55Z", "%Y-%m-%dT%H:%M:%SZ" )
d.weekday()

How to check if directory exist using C++ and winAPI

Here is a simple function which does exactly this :

#include <windows.h>
#include <string>

bool dirExists(const std::string& dirName_in)
{
  DWORD ftyp = GetFileAttributesA(dirName_in.c_str());
  if (ftyp == INVALID_FILE_ATTRIBUTES)
    return false;  //something is wrong with your path!

  if (ftyp & FILE_ATTRIBUTE_DIRECTORY)
    return true;   // this is a directory!

  return false;    // this is not a directory!
}

Table is marked as crashed and should be repaired

Connect to your server via SSH

then connect to your mysql console

and

USE user_base
REPAIR TABLE TABLE;

-OR-

If there are a lot of broken tables in current database:

mysqlcheck -uUSER -pPASSWORD  --repair --extended user_base

If there are a lot of broken tables in a lot of databases:

mysqlcheck -uUSER -pPASSWORD  --repair --extended -A

Formatting a float to 2 decimal places

string outString= number.ToString("####0.00");

Error:java: invalid source release: 8 in Intellij. What does it mean?

I add one more path unmentioned in this answer https://stackoverflow.com/a/26009627/4609353

but very important is Edit Configurations

one more path

Comparing two arrays of objects, and exclude the elements who match values into new array in JS

Here is another solution using Lodash:

var _ = require('lodash');

var result1 = [
    {id:1, name:'Sandra', type:'user', username:'sandra'},
    {id:2, name:'John', type:'admin', username:'johnny2'},
    {id:3, name:'Peter', type:'user', username:'pete'},
    {id:4, name:'Bobby', type:'user', username:'be_bob'}
];

var result2 = [
    {id:2, name:'John', email:'[email protected]'},
    {id:4, name:'Bobby', email:'[email protected]'}
];

// filter all those that do not match
var result = types1.filter(function(o1){
    // if match found return false
    return _.findIndex(types2, {'id': o1.id, 'name': o1.name}) !== -1 ? false : true;
});

console.log(result);

How to truncate string using SQL server

You could also use the below, the iif avoids the case statement and only adds ellipses when required (only good in SQL Server 2012 and later) and the case statement is more ANSI compliant (but more verbose)

SELECT 
  col, LEN(col), 
  col2, LEN(col2), 
  col3, LEN(col3) FROM (
  SELECT 
    col, 
    LEFT(x.col, 15) + (IIF(len(x.col) > 15, '...', '')) AS col2, 
    LEFT(x.col, 15) + (CASE WHEN len(x.col) > 15 THEN '...' ELSE '' END) AS col3 
  from (
      select 'this is a long string. One that is longer than 15 characters' as col
      UNION 
      SELECT 'short string' AS col
      UNION 
      SELECT 'string==15 char' AS col
      UNION 
      SELECT NULL AS col
      UNION 
      SELECT '' AS col
) x
) y

How to get thread id of a pthread in linux c program?

As noted in other answers, pthreads does not define a platform-independent way to retrieve an integral thread ID.

On Linux systems, you can get thread ID thus:

#include <sys/types.h>
pid_t tid = gettid();

On many BSD-based platforms, this answer https://stackoverflow.com/a/21206357/316487 gives a non-portable way.

However, if the reason you think you need a thread ID is to know whether you're running on the same or different thread to another thread you control, you might find some utility in this approach

static pthread_t threadA;

// On thread A...
threadA = pthread_self();

// On thread B...
pthread_t threadB = pthread_self();
if (pthread_equal(threadA, threadB)) printf("Thread B is same as thread A.\n");
else printf("Thread B is NOT same as thread A.\n");

If you just need to know if you're on the main thread, there are additional ways, documented in answers to this question how can I tell if pthread_self is the main (first) thread in the process?.

What is the proper way to re-throw an exception in C#?

The first preserves the original stack trace of the exception, the second one replaces it with the current location.

Therefore the first is BY FAR the better.

PDO get the last ID inserted

That's because that's an SQL function, not PHP. You can use PDO::lastInsertId().

Like:

$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();

If you want to do it with SQL instead of the PDO API, you would do it like a normal select query:

$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();

Comparing two byte arrays in .NET

If you are looking for a very fast byte array equality comparer, I suggest you take a look at this STSdb Labs article: Byte array equality comparer. It features some of the fastest implementations for byte[] array equality comparing, which are presented, performance tested and summarized.

You can also focus on these implementations:

BigEndianByteArrayComparer - fast byte[] array comparer from left to right (BigEndian) BigEndianByteArrayEqualityComparer - - fast byte[] equality comparer from left to right (BigEndian) LittleEndianByteArrayComparer - fast byte[] array comparer from right to left (LittleEndian) LittleEndianByteArrayEqualityComparer - fast byte[] equality comparer from right to left (LittleEndian)

Install psycopg2 on Ubuntu

Using Ubuntu 12.04 it appears to work fine for me:

jon@minerva:~$ sudo apt-get install python-psycopg2
[sudo] password for jon: 
Reading package lists... Done
Building dependency tree       
Reading state information... Done
Suggested packages:
  python-psycopg2-doc
The following NEW packages will be installed
  python-psycopg2
0 upgraded, 1 newly installed, 0 to remove and 334 not upgraded.
Need to get 153 kB of archives.

What error are you getting exactly? - double check you've spelt psycopg right - that's quite often a gotcha... and it never hurts to run an apt-get update to make sure your repo. is up to date.

Jenkins not executing jobs (pending - waiting for next executor)

In my case it was caused by number of executors (I had 1) and running Jenkins Job (Project) from Pipeline (my pipeline script started other Job in Jenkins). It caused deadlock - my pipeline held executor and was waiting for its job, but the job was waiting for free executor.

The solution may be increasing of # of executors in Jenkins -> Manage Jenkins -> Manage Nodes -> Configure (icon on required node).

class << self idiom in Ruby

What class << thing does:

class Hi
  self #=> Hi
  class << self #same as 'class << Hi'
    self #=> #<Class:Hi>
    self == Hi.singleton_class #=> true
  end
end

[it makes self == thing.singleton_class in the context of its block].


What is thing.singleton_class?

hi = String.new
def hi.a
end

hi.class.instance_methods.include? :a #=> false
hi.singleton_class.instance_methods.include? :a #=> true

hi object inherits its #methods from its #singleton_class.instance_methods and then from its #class.instance_methods.
Here we gave hi's singleton class instance method :a. It could have been done with class << hi instead.
hi's #singleton_class has all instance methods hi's #class has, and possibly some more (:a here).

[instance methods of thing's #class and #singleton_class can be applied directly to thing. when ruby sees thing.a, it first looks for :a method definition in thing.singleton_class.instance_methods and then in thing.class.instance_methods]


By the way - they call object's singleton class == metaclass == eigenclass.

The point of test %eax %eax

Some x86 instructions are designed to leave the content of the operands (registers) as they are and just set/unset specific internal CPU flags like the zero-flag (ZF). You can think at the ZF as a true/false boolean flag that resides inside the CPU.

in this particular case, TEST instruction performs a bitwise logical AND, discards the actual result and sets/unsets the ZF according to the result of the logical and: if the result is zero it sets ZF = 1, otherwise it sets ZF = 0.

Conditional jump instructions like JE are designed to look at the ZF for jumping/notjumping so using TEST and JE together is equivalent to perform a conditional jump based on the value of a specific register:

example:

TEST EAX,EAX
JE some_address



the CPU will jump to "some_address" if and only if ZF = 1, in other words if and only if AND(EAX,EAX) = 0 which in turn it can occur if and only if EAX == 0

the equivalent C code is:

if(eax == 0)
{
    goto some_address
}

Laravel 5.2 not reading env file

I ran into this same problem on my local, and I have tried all the answers here but to no avail. Only this worked for me, php artisan config:clear and restart server. Works like a charm!

Using IF ELSE in Oracle

IF is a PL/SQL construct. If you are executing a query, you are using SQL not PL/SQL.

In SQL, you can use a CASE statement in the query itself

SELECT DISTINCT a.item, 
                (CASE WHEN b.salesman = 'VIKKIE'
                      THEN 'ICKY'
                      ELSE b.salesman
                  END), 
                NVL(a.manufacturer,'Not Set') Manufacturer
  FROM inv_items a, 
       arv_sales b
 WHERE  a.co = '100'
   AND a.co = b.co
   AND A.ITEM_KEY = b.item_key   
   AND a.item LIKE 'BX%'
   AND b.salesman in ('01','15')
   AND trans_date BETWEEN to_date('010113','mmddrr')
                      and to_date('011713','mmddrr')
ORDER BY a.item

Since you aren't doing any aggregation, you don't want a GROUP BY in your query. Are you really sure that you need the DISTINCT? People often throw that in haphazardly or add it when they are missing a join condition rather than considering whether it is really necessary to do the extra work to identify and remove duplicates.

Explanation of BASE terminology

ACID and BASE are consistency models for RDBMS and NoSQL respectively. ACID transactions are far more pessimistic i.e. they are more worried about data safety. In the NoSQL database world, ACID transactions are less fashionable as some databases have loosened the requirements for immediate consistency, data freshness and accuracy in order to gain other benefits, like scalability and resiliency.

BASE stands for -

  • Basic Availability - The database appears to work most of the time.
  • Soft-state - Stores don't have to be write-consistent, nor do different replicas have to be mutually consistent all the time.
  • Eventual consistency - Stores exhibit consistency at some later point (e.g., lazily at read time).

Therefore BASE relaxes consistency to allow the system to process request even in an inconsistent state.

Example: No one would mind if their tweet were inconsistent within their social network for a short period of time. It is more important to get an immediate response than to have a consistent state of users' information.

How can I use break or continue within for loop in Twig template?

This can be nearly done by setting a new variable as a flag to break iterating:

{% set break = false %}
{% for post in posts if not break %}
    <h2>{{ post.heading }}</h2>
    {% if post.id == 10 %}
        {% set break = true %}
    {% endif %}
{% endfor %}

An uglier, but working example for continue:

{% set continue = false %}
{% for post in posts %}
    {% if post.id == 10 %}
        {% set continue = true %}
    {% endif %}
    {% if not continue %}
        <h2>{{ post.heading }}</h2>
    {% endif %}
    {% if continue %}
        {% set continue = false %}
    {% endif %}
{% endfor %}

But there is no performance profit, only similar behaviour to the built-in break and continue statements like in flat PHP.

What does __FILE__ mean in Ruby?

In Ruby, the Windows version anyways, I just checked and __FILE__ does not contain the full path to the file. Instead it contains the path to the file relative to where it's being executed from.

In PHP __FILE__ is the full path (which in my opinion is preferable). This is why, in order to make your paths portable in Ruby, you really need to use this:

File.expand_path(File.dirname(__FILE__) + "relative/path/to/file")

I should note that in Ruby 1.9.1 __FILE__ contains the full path to the file, the above description was for when I used Ruby 1.8.7.

In order to be compatible with both Ruby 1.8.7 and 1.9.1 (not sure about 1.9) you should require files by using the construct I showed above.

Subtracting Dates in Oracle - Number or Interval Datatype?

Ok, I don't normally answer my own questions but after a bit of tinkering, I have figured out definitively how Oracle stores the result of a DATE subtraction.

When you subtract 2 dates, the value is not a NUMBER datatype (as the Oracle 11.2 SQL Reference manual would have you believe). The internal datatype number of a DATE subtraction is 14, which is a non-documented internal datatype (NUMBER is internal datatype number 2). However, it is actually stored as 2 separate two's complement signed numbers, with the first 4 bytes used to represent the number of days and the last 4 bytes used to represent the number of seconds.

An example of a DATE subtraction resulting in a positive integer difference:

select date '2009-08-07' - date '2008-08-08' from dual;

Results in:

DATE'2009-08-07'-DATE'2008-08-08'
---------------------------------
                              364

select dump(date '2009-08-07' - date '2008-08-08') from dual;

DUMP(DATE'2009-08-07'-DATE'2008
-------------------------------
Typ=14 Len=8: 108,1,0,0,0,0,0,0

Recall that the result is represented as a 2 seperate two's complement signed 4 byte numbers. Since there are no decimals in this case (364 days and 0 hours exactly), the last 4 bytes are all 0s and can be ignored. For the first 4 bytes, because my CPU has a little-endian architecture, the bytes are reversed and should be read as 1,108 or 0x16c, which is decimal 364.

An example of a DATE subtraction resulting in a negative integer difference:

select date '1000-08-07' - date '2008-08-08' from dual;

Results in:

DATE'1000-08-07'-DATE'2008-08-08'
---------------------------------
                          -368160

select dump(date '1000-08-07' - date '2008-08-08') from dual;

DUMP(DATE'1000-08-07'-DATE'2008-08-0
------------------------------------
Typ=14 Len=8: 224,97,250,255,0,0,0,0

Again, since I am using a little-endian machine, the bytes are reversed and should be read as 255,250,97,224 which corresponds to 11111111 11111010 01100001 11011111. Now since this is in two's complement signed binary numeral encoding, we know that the number is negative because the leftmost binary digit is a 1. To convert this into a decimal number we would have to reverse the 2's complement (subtract 1 then do the one's complement) resulting in: 00000000 00000101 10011110 00100000 which equals -368160 as suspected.

An example of a DATE subtraction resulting in a decimal difference:

select to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS'
 - to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS') from dual;

TO_DATE('08/AUG/200414:00:00','DD/MON/YYYYHH24:MI:SS')-TO_DATE('08/AUG/20048:00:
--------------------------------------------------------------------------------
                                                                             .25

The difference between those 2 dates is 0.25 days or 6 hours.

select dump(to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS')
 - to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS')) from dual;

DUMP(TO_DATE('08/AUG/200414:00:
-------------------------------
Typ=14 Len=8: 0,0,0,0,96,84,0,0

Now this time, since the difference is 0 days and 6 hours, it is expected that the first 4 bytes are 0. For the last 4 bytes, we can reverse them (because CPU is little-endian) and get 84,96 = 01010100 01100000 base 2 = 21600 in decimal. Converting 21600 seconds to hours gives you 6 hours which is the difference which we expected.

Hope this helps anyone who was wondering how a DATE subtraction is actually stored.


You get the syntax error because the date math does not return a NUMBER, but it returns an INTERVAL:

SQL> SELECT DUMP(SYSDATE - start_date) from test;

DUMP(SYSDATE-START_DATE)
-------------------------------------- 
Typ=14 Len=8: 188,10,0,0,223,65,1,0

You need to convert the number in your example into an INTERVAL first using the NUMTODSINTERVAL Function

For example:

SQL> SELECT (SYSDATE - start_date) DAY(5) TO SECOND from test;

(SYSDATE-START_DATE)DAY(5)TOSECOND
----------------------------------
+02748 22:50:04.000000

SQL> SELECT (SYSDATE - start_date) from test;

(SYSDATE-START_DATE)
--------------------
           2748.9515

SQL> select NUMTODSINTERVAL(2748.9515, 'day') from dual;

NUMTODSINTERVAL(2748.9515,'DAY')
--------------------------------
+000002748 22:50:09.600000000

SQL>

Based on the reverse cast with the NUMTODSINTERVAL() function, it appears some rounding is lost in translation.

How to pass credentials to the Send-MailMessage command for sending emails

So..it was SSL problem. Whatever I was doing was absolutely correct. Only that I was not using the ssl option. So I added "-Usessl true" to my original command and it worked.

Codesign error: Provisioning profile cannot be found after deleting expired profile

Just spent a hour or so doing this and with the help of Brad's advice and a few additional changes it all worked.

I've done this using the following: 10.7.3, Xcode 4.3.2, iOS 5.1 btw.

1) Right click on your myapp.xcodeproj and select package contents

2) open project.pbxproj with a text editor (don't recommend textedit as it may screw up the formatting)

3) Scroll all the way down until you find /* Begin XCBuildConfiguration section */

4) Notice that you have a debug and release sections

5) In the release section take a look at CODE_SIGN_IDENTITY & "CODE_SIGN_IDENTITY[sdk=iphoneos*]" it should look something like this:

CODE_SIGN_IDENTITY = "iPhone Distribution: MyCompany LLC";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution: MyCompany LLC";

6) Take a look at PROVISIONING_PROFILE and "PROVISIONING_PROFILE[sdk=iphoneos*]" they should look like this:

PROVISIONING_PROFILE = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX";
"PROVISIONING_PROFILE[sdk=iphoneos*]" = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX";

This should match your provisioning profile in Xcode. To see if they match open Xcode > Window > Organizer > Devices > Provisioning Profiles > Right click on the profile > Reveal in Finder > The filename of the .mobileprovision is your profile id.

7) Scroll down in the project.pbxproj and find a second instance of the release section. The second instance of the release section should end with a comment saying /* End XCBuildConfiguration section */

8) make sure that the second section matches the first section so that CODE_SIGN_IDENTITY, "CODE_SIGN_IDENTITY[sdk=iphoneos*], and PROVISIONING_PROFILE are all filled in.

How can I pretty-print JSON using Go?

i am sort of new to go, but this is what i gathered up so far:

package srf

import (
    "bytes"
    "encoding/json"
    "os"
)

func WriteDataToFileAsJSON(data interface{}, filedir string) (int, error) {
    //write data as buffer to json encoder
    buffer := new(bytes.Buffer)
    encoder := json.NewEncoder(buffer)
    encoder.SetIndent("", "\t")

    err := encoder.Encode(data)
    if err != nil {
        return 0, err
    }
    file, err := os.OpenFile(filedir, os.O_RDWR|os.O_CREATE, 0755)
    if err != nil {
        return 0, err
    }
    n, err := file.Write(buffer.Bytes())
    if err != nil {
        return 0, err
    }
    return n, nil
}

This is the execution of the function, and just standard

b, _ := json.MarshalIndent(SomeType, "", "\t")

Code:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"

    minerals "./minerals"
    srf "./srf"
)

func main() {

    //array of Test struct
    var SomeType [10]minerals.Test

    //Create 10 units of some random data to write
    for a := 0; a < 10; a++ {
        SomeType[a] = minerals.Test{
            Name:   "Rand",
            Id:     123,
            A:      "desc",
            Num:    999,
            Link:   "somelink",
            People: []string{"John Doe", "Aby Daby"},
        }
    }

    //writes aditional data to existing file, or creates a new file
    n, err := srf.WriteDataToFileAsJSON(SomeType, "test2.json")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("srf printed ", n, " bytes to ", "test2.json")

    //overrides previous file
    b, _ := json.MarshalIndent(SomeType, "", "\t")
    ioutil.WriteFile("test.json", b, 0644)

}

Reverse each individual word of "Hello World" string with Java

    String input = "Hello World!";

    String temp = "";
    String result = "";

    for (int i = 0; i <= input.length(); i++) {
        if (i != input.length() && input.charAt(i) != ' ') {
            temp = input.charAt(i) + temp;
        } else {
            result = temp + " " + result;
            temp = "";
        }
    }

    System.out.println("the result is: " + result);

Min and max value of input in angular4 application

Most simple approach in Template driven forms for min/max validation with out using reactive forms and building any directive, would be to use pattern attribute of html. This has already been explained and answered here please look https://stackoverflow.com/a/63312336/14069524

How many concurrent requests does a single Flask process receive?

Flask will process one request per thread at the same time. If you have 2 processes with 4 threads each, that's 8 concurrent requests.

Flask doesn't spawn or manage threads or processes. That's the responsability of the WSGI gateway (eg. gunicorn).

Finding an elements XPath using IE Developer tool

This post suggests that you should be able to get the IE Developer Toolbar to show you the XPath for an element you click on if you turn on the "select element by click" option. http://blog.balfes.net/?p=62

Alternatively this post suggests either bookmarklets, or IE debugbar: Equivalent of Firebug's "Copy XPath" in Internet Explorer?

nodejs vs node on ubuntu 12.04

Best way to install nodejs is through NVM (Node Version Manager)

Delete previous versions :

$ sudo apt-get purge node
$ sudo apt autoremove

Also delete all node_modules by $ sudo rm -rf node_modules in the directory containing this folder.

Node & Nodejs are technically the same thing. Just the naming changed.

First Install or update nvm

to run as root

$ sudo su 

Then

$ curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.31.7/install.sh | bash

OR

$ wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.31.7/install.sh | bash

Check nvm to path

$ source ~/.profile
$ nvm ls-remote

if you get error regarding the listing then install git.

$ sudo apt-get install git

Re-run :

$ nvm ls-remote
OR
$ sudo nvm ls-remote

$ nvm install version-you-require 

Checking Version

# node --version
nvm use version-you-require

INFORMATION COURTESY :

https://www.digitalocean.com/community/tutorials/how-to-install-node-js-with-nvm-node-version-manager-on-a-vps

jQuery: how to trigger anchor link's click event

You cannot open in a new tab programmatically, it's a browser functionality. You can open a link in an external window . Have a look here

Delete files in subfolder using batch script

You can use the /s switch for del to delete in subfolders as well.

Example

del D:\test\*.* /s

Would delete all files under test including all files in all subfolders.

To remove folders use rd, same switch applies.

rd D:\test\folder /s /q

rd doesn't support wildcards * though so if you want to recursively delete all subfolders under the test directory you can use a for loop.

for /r /d D:\test %a in (*) do rd %a /s /q

If you are using the for option in a batch file remember to use 2 %'s instead of 1.

svn over HTTP proxy

If you're using the standard SVN installation the svn:// connection will work on tcpip port 3690 and so it's basically impossible to connect unless you change your network configuration (you said only Http traffic is allowed) or you install the http module and Apache on the server hosting your SVN server.

Recursive Fibonacci

int fib(int x) 
{
    if (x == 0)
      return 0;
    else if (x == 1 || x == 2) 
      return 1;
    else 
      return (fib(x - 1) + fib(x - 2));
}

Select first 4 rows of a data.frame in R

Use head:

dnow <- data.frame(x=rnorm(100), y=runif(100))
head(dnow,4) ## default is 6

Encrypting & Decrypting a String in C#

The easiest way that I've seen to do encryption is through RSA

Check out the MSDN on it: http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsacryptoserviceprovider.aspx

It does involve using bytes, but when it comes down to it you kind of do want encryption and decryption to be tough to figure out otherwise it will be easy to hack.

Best way to load module/class from lib folder in Rails 3?

As of Rails 2.3.9, there is a setting in config/application.rb in which you can specify directories that contain files you want autoloaded.

From application.rb:

# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)

How to find which columns contain any NaN value in Pandas dataframe

i use these three lines of code to print out the column names which contain at least one null value:

for column in dataframe:
    if dataframe[column].isnull().any():
       print('{0} has {1} null values'.format(column, dataframe[column].isnull().sum()))

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

Try ISDATE() function in SQL Server. If 1, select valid date. If 0 selects invalid dates.

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail 
WHERE ISDATE(LoginTime) = 1

EDIT :

As per your update i need to extract the date only and remove the time, then you could simply use the inner CONVERT

SELECT CONVERT(VARCHAR, LoginTime, 101) FROM AuditTrail 

or

SELECT LEFT(LoginTime,10) FROM AuditTrail

EDIT 2 :

The major reason for the error will be in your date in WHERE clause.ie,

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <= 
CAST('06/18/2012' AS DATE)

will be different from

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <= 
CAST('18/06/2012' AS DATE)

CONCLUSION

In EDIT 2 the first query tries to filter in mm/dd/yyyy format, while the second query tries to filter in dd/mm/yyyy format. Either of them will fail and throws error

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

So please make sure to filter date either with mm/dd/yyyy or with dd/mm/yyyy format, whichever works in your db.

Why use pip over easy_install?

REQUIREMENTS files.

Seriously, I use this in conjunction with virtualenv every day.


QUICK DEPENDENCY MANAGEMENT TUTORIAL, FOLKS

Requirements files allow you to create a snapshot of all packages that have been installed through pip. By encapsulating those packages in a virtualenvironment, you can have your codebase work off a very specific set of packages and share that codebase with others.

From Heroku's documentation https://devcenter.heroku.com/articles/python

You create a virtual environment, and set your shell to use it. (bash/*nix instructions)

virtualenv env
source env/bin/activate

Now all python scripts run with this shell will use this environment's packages and configuration. Now you can install a package locally to this environment without needing to install it globally on your machine.

pip install flask

Now you can dump the info about which packages are installed with

pip freeze > requirements.txt

If you checked that file into version control, when someone else gets your code, they can setup their own virtual environment and install all the dependencies with:

pip install -r requirements.txt

Any time you can automate tedium like this is awesome.

Adjusting the Xcode iPhone simulator scale and size

With Xcode 9 - Simulator, you can pick & drag any corner of simulator to resize it and set according to your requirement.

Look at this snapshot.

enter image description here


Note: With Xcode 9.1+, Simulator scale options are changed.


Keyboard short-keys:
According to Xcode 9.1+

Physical Size       ? 1      command + 1
Pixel Accurate      ? 2      command + 2


According to Xcode 9

50% Scale           ? 1      command + 1
100% Scale          ? 2      command + 2
200% Scale          ? 3      command + 3

Simulator scale options from Xcode Menu:

Xcode 9.1+:
Menubar ? Window ? "Here, options available change simulator scale" (Physical Size & Pixel Accurate)

Pixel Accurate: Resizes your simulator to actual (Physical) device's pixels, if your mac system display screen size (pixel) supports that much high resolution, else this option will remain disabled.

Tip: rotate simulator ( ? + ? or ? + ? ), if Pixel Accurate is disabled. It may be enabled (if it fits to screen) in landscape.

enter image description here


Xcode 9.0
Menubar ? Window ? Scale ? "Here, options available change simulator scale"

enter image description here


Tip: How do you get screen shot with 100% (a scale with actual device size) that can be uploaded on AppStore?

Disable 'Optimize Rendering for Window scale' from Debug menu, before you take a screen shot (See here: How to take screenshots in the iOS simulator)

There is an option

Menubar ? Debug ? Disable "Optimize Rendering for Window scale"

enter image description here


Here is Apple's document: Resize a simulator window

Writing String to Stream and reading it back does not work

You need to reset the stream to the beginning:

stringAsStream.Seek(0, SeekOrigin.Begin);
Console.WriteLine("Differs from:\t" + (char)stringAsStream.ReadByte());

This can also be done by setting the Position property to 0:

stringAsStream.Position = 0

Convert Existing Eclipse Project to Maven Project

There is a command line program to convert any Java project into a SBT/Maven project.

It resolves all jars and tries to figure out the correct version based on SHA checksum, classpath or filename. Then it tries to compile the sources until it finds a working configuration. Custom tasks to execute per dependency configuration can be given too.

UniversalResolver 1.0
Usage: UniversalResolver [options]

  -s <srcpath1>,<srcpath2>... | --srcPaths <srcpath1>,<srcpath2>...
        required src paths to include
  -j <jar1>,<jar2>... | --jars <jar1>,<jar2>...
        required jars/jar paths to include
  -t /path/To/Dir | --testDirectory /path/To/Dir
        required directory where test configurations will be stored
  -a <task1>,<task2>... | --sbt-tasks <task1>,<task2>...
        SBT Tasks to be executed. i.e. compile
  -d /path/To/dependencyFile.json | --dependencyFile /path/To/dependencyFile.json
        optional file where the dependency buffer will be stored
  -l | --search
        load and search dependencies from remote repositories
  -g | --generateConfigurations
        generate dependency configurations
  -c <value> | --findByNameCount <value>
        number of dependencies to resolve by class name per jar

https://bitbucket.org/mnyx/universalresolver

cpp / c++ get pointer value or depointerize pointer

To get the value of a pointer, just de-reference the pointer.

int *ptr;
int value;
*ptr = 9;

value = *ptr;

value is now 9.

I suggest you read more about pointers, this is their base functionality.

JavaScript Nested function

Functions are another type of variable in JavaScript (with some nuances of course). Creating a function within another function changes the scope of the function in the same way it would change the scope of a variable. This is especially important for use with closures to reduce total global namespace pollution.

The functions defined within another function won't be accessible outside the function unless they have been attached to an object that is accessible outside the function:

function foo(doBar)
{
  function bar()
  {
    console.log( 'bar' );
  }

  function baz()
  {
    console.log( 'baz' );
  }

  window.baz = baz;
  if ( doBar ) bar();
}

In this example, the baz function will be available for use after the foo function has been run, as it's overridden window.baz. The bar function will not be available to any context other than scopes contained within the foo function.

as a different example:

function Fizz(qux)
{
  this.buzz = function(){
    console.log( qux );
  };
}

The Fizz function is designed as a constructor so that, when run, it assigns a buzz function to the newly created object.

Fastest way to tell if two files have the same contents in Unix/Linux?

Try also to use the cksum command:

chk1=`cksum <file1> | awk -F" " '{print $1}'`
chk2=`cksum <file2> | awk -F" " '{print $1}'`

if [ $chk1 -eq $chk2 ]
then
  echo "File is identical"
else
  echo "File is not identical"
fi

The cksum command will output the byte count of a file. See 'man cksum'.

addClass and removeClass in jQuery - not removing class

Whenever I see addClass and removeClass I think why not just use toggleClass. In this case we can remove the .clickable class to avoid event bubbling, and to avoid the event from being fired on everything we click inside of the .clickable div.

$(document).on("click", ".close_button", function () { 
    $(this).closest(".grown").toggleClass("spot grown clickable");
});  

$(document).on("click", ".clickable", function () {
    $(this).toggleClass("spot grown clickable");
}); 

I also recommend a parent wrapper for your .clickable divs instead of using the document. I am not sure how you are adding them dynamically so didn't want to assume your layout for you.

http://jsfiddle.net/bplumb/ECQg5/2/

Happy Coding :)

UIButton: how to center an image and a text using imageEdgeInsets and titleEdgeInsets?

With this chunk of code, you will get something like this title and image alignment

extension UIButton {
    func alignTextUnderImage() {
        guard let imageView = imageView else {
                return
        }
        self.contentVerticalAlignment = .Top
        self.contentHorizontalAlignment = .Center
        let imageLeftOffset = (CGRectGetWidth(self.bounds) - CGRectGetWidth(imageView.bounds)) / 2//put image in center
        let titleTopOffset = CGRectGetHeight(imageView.bounds) + 5
        self.imageEdgeInsets = UIEdgeInsetsMake(0, imageLeftOffset, 0, 0)
        self.titleEdgeInsets = UIEdgeInsetsMake(titleTopOffset, -CGRectGetWidth(imageView.bounds), 0, 0)
    }
}

How to use boost bind with a member function

Use the following instead:

boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );

This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.

Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.

How to drop columns using Rails migration

Through
remove_column :table_name, :column_name
in a migration file

You can remove a column directly in a rails console by typing:
ActiveRecord::Base.remove_column :table_name, :column_name

'Framework not found' in Xcode

None of the above worked for me until I found that I had a blank "Any Architecture | Any SDK" line underneath Framework Search Paths / Debug under Build Settings.

Deleted the line and it works!

how to set JAVA_OPTS for Tomcat in Windows?

Apparently the correct form is without the ""

As in

set JAVA_OPTS=-Xms512M -Xmx1024M

How can I enable MySQL's slow query log without restarting MySQL?

Try SET GLOBAL slow_query_log = 'ON'; and perhaps FLUSH LOGS;

This assumes you are using MySQL 5.1 or later. If you are using an earlier version, you'll need to restart the server. This is documented in the MySQL Manual. You can configure the log either in the config file or on the command line.

Spring JPA @Query with LIKE

Using Query creation from method names, check table 4 where they explain some keywords.

  1. Using Like: select ... like :username

     List<User> findByUsernameLike(String username);
    
  2. StartingWith: select ... like :username%

     List<User> findByUsernameStartingWith(String username);
    
  3. EndingWith: select ... like %:username

     List<User> findByUsernameEndingWith(String username);
    
  4. Containing: select ... like %:username%

     List<User> findByUsernameContaining(String username);
    

Notice that the answer that you are looking for is number 4. You don't have to use @Query

Node Express sending image files as API response

There is an api in Express.

res.sendFile

app.get('/report/:chart_id/:user_id', function (req, res) {
    // res.sendFile(filepath);
});

http://expressjs.com/en/api.html#res.sendFile

What is the reason for java.lang.IllegalArgumentException: No enum const class even though iterating through values() works just fine?

I had parsing enum problem when i was trying to pass Nullable Enum that we get from Backend. Of course it was working when we get value, but it was problem when the null comes up.

java.lang.IllegalArgumentException: No enum constant

Also the problem was when we at Parcelize read moment write some short if.

My solution for this was

1.Create companion object with parsing method.

enum class CarsType {
    @Json(name = "SMALL")
    SMALL,
    @Json(name = "BIG")
    BIG;

    companion object {
        fun nullableValueOf(name: String?) = when (name) {
            null -> null
            else -> valueOf(name)
        }
    }
}

2. In Parcerable read place use it like this

data class CarData(
    val carId: String? = null,
    val carType: CarsType?,
    val data: String?
) : Parcelable {
    constructor(parcel: Parcel) : this(
        parcel.readString(),
        CarsType.nullableValueOf(parcel.readString()),
        parcel.readString())

How to capitalize first letter of each word, like a 2-word city?

The JavaScript function:

String.prototype.capitalize = function(){
       return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
      };

To use this function:

capitalizedString = someString.toLowerCase().capitalize();

Also, this would work on multiple words string.

To make sure the converted City name is injected into the database, lowercased and first letter capitalized, then you would need to use JavaScript before you send it over to server side. CSS simply styles, but the actual data would remain pre-styled. Take a look at this jsfiddle example and compare the alert message vs the styled output.

Pointer to incomplete class type is not allowed

Check out if you are missing some import.

Column order manipulation using col-lg-push and col-lg-pull in Twitter Bootstrap 3

This answer is in three parts, see below for the official release (v3 and v4)

I couldn't even find the col-lg-push-x or pull classes in the original files for RC1 i downloaded, so check your bootstrap.css file. hopefully this is something they will sort out in RC2.

anyways, the col-push-* and pull classes did exist and this will suit your needs. Here is a demo

<div class="row">
    <div class="col-sm-5 col-push-5">
        Content B
    </div>
    <div class="col-sm-5 col-pull-5">
        Content A
    </div>
    <div class="col-sm-2">
        Content C
    </div>
</div>

EDIT: BELOW IS THE ANSWER FOR THE OFFICIAL RELEASE v3.0

Also see This blog post on the subject

  • col-vp-push-x = push the column to the right by x number of columns, starting from where the column would normally render -> position: relative, on a vp or larger view-port.

  • col-vp-pull-x = pull the column to the left by x number of columns, starting from where the column would normally render -> position: relative, on a vp or larger view-port.

    vp = xs, sm, md, or lg

    x = 1 thru 12

I think what messes most people up, is that you need to change the order of the columns in your HTML markup (in the example below, B comes before A), and that it only does the pushing or pulling on view-ports that are greater than or equal to what was specified. i.e. col-sm-push-5 will only push 5 columns on sm view-ports or greater. This is because Bootstrap is a "mobile first" framework, so your HTML should reflect the mobile version of your site. The Pushing and Pulling are then done on the larger screens.

  • (Desktop) Larger view-ports get pushed and pulled.
  • (Mobile) Smaller view-ports render in normal order.

DEMO

<div class="row">
    <div class="col-sm-5 col-sm-push-5">
        Content B
    </div>
    <div class="col-sm-5 col-sm-pull-5">
        Content A
    </div>
    <div class="col-sm-2">
        Content C
    </div>
</div>

View-port >= sm

|A|B|C|

View-port < sm

|B|
|A|
|C|

EDIT: BELOW IS THE ANSWER FOR v4.0

With v4 comes flexbox and other changes to the grid system and the push\pull classes have been removed in favor of using flexbox ordering.

  • Use .order-* classes to control visual order (where * = 1 thru 12)
  • This can also be grid tier specific .order-md-*
  • Also .order-first (-1) and .order-last (13) avalable

_x000D_
_x000D_
<div class="row">_x000D_
  <div class="col order-2">1st yet 2nd</div>_x000D_
  <div class="col order-1">2nd yet 1st</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

CSS how to make an element fade in and then fade out?

A way to do this would be to set the color of the element to black, and then fade to the color of the background like this:

<style> 
p {
animation-name: example;
animation-duration: 2s;
}

@keyframes example {
from {color:black;}
to {color:white;}
}
</style>
<p>I am FADING!</p>

I hope this is what you needed!

Iterating through directories with Python

Another way of returning all files in subdirectories is to use the pathlib module, introduced in Python 3.4, which provides an object oriented approach to handling filesystem paths (Pathlib is also available on Python 2.7 via the pathlib2 module on PyPi):

from pathlib import Path

rootdir = Path('C:/Users/sid/Desktop/test')
# Return a list of regular files only, not directories
file_list = [f for f in rootdir.glob('**/*') if f.is_file()]

# For absolute paths instead of relative the current dir
file_list = [f for f in rootdir.resolve().glob('**/*') if f.is_file()]

Since Python 3.5, the glob module also supports recursive file finding:

import os
from glob import iglob

rootdir_glob = 'C:/Users/sid/Desktop/test/**/*' # Note the added asterisks
# This will return absolute paths
file_list = [f for f in iglob(rootdir_glob, recursive=True) if os.path.isfile(f)]

The file_list from either of the above approaches can be iterated over without the need for a nested loop:

for f in file_list:
    print(f) # Replace with desired operations

How do I programmatically click on an element in JavaScript?

Using jQuery you can do exactly the same thing, for example:

$("a").click();

Which will "click" all anchors on the page.

What is the "-->" operator in C/C++?

-- is the decrement operator and > is the greater-than operator.

The two operators are applied as a single one like -->.

SQLException: No suitable Driver Found for jdbc:oracle:thin:@//localhost:1521/orcl

i have changed my old path: jdbc:odbc:thin:@localhost:1521:orcl

to new : jdbc:oracle:thin:@//localhost:1521/orcl

and it worked for me.....hurrah!! image

PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?

I am not sure and not really trust $_SERVER['HTTP_HOST'] because it depend on header from client. In another way, if a domain requested by client is not mine one, they will not getting into my site because DNS and TCP/IP protocol point it to the correct destination. However I don't know if possible to hijack the DNS, network or even Apache server. To be safe, I define host name in environment and compare it with $_SERVER['HTTP_HOST'].

Add SetEnv MyHost domain.com in .htaccess file on root and add ths code in Common.php

if (getenv('MyHost')!=$_SERVER['HTTP_HOST']) {
  header($_SERVER['SERVER_PROTOCOL'].' 400 Bad Request');
  exit();
}

I include this Common.php file in every php page. This page doing anything required for each request like session_start(), modify session cookie and reject if post method come from different domain.

Remove characters before character "."

Extension methods I commonly use to solve this problem:

public static string RemoveAfter(this string value, string character)
    {
        int index = value.IndexOf(character);
        if (index > 0)
        {
            value = value.Substring(0, index);
        }
        return value;
    }

    public static string RemoveBefore(this string value, string character)
    {
        int index = value.IndexOf(character);
        if (index > 0)
        {
            value = value.Substring(index + 1);
        }
        return value;
    }

String formatting in Python 3

Python 3.6 now supports shorthand literal string interpolation with PEP 498. For your use case, the new syntax is simply:

f"({self.goals} goals, ${self.penalties})"

This is similar to the previous .format standard, but lets one easily do things like:

>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal('12.34567')
>>> f'result: {value:{width}.{precision}}'
'result:      12.35'

Converting integer to string in Python

>>> i = 5
>>> print "Hello, world the number is " + i
TypeError: must be str, not int
>>> s = str(i)
>>> print "Hello, world the number is " + s
Hello, world the number is 5

Compress files while reading data from STDIN

Yes, use gzip for this. The best way is to read data as input and redirect the compressed to output file i.e.

cat test.csv | gzip > test.csv.gz

cat test.csv will send the data as stdout and using pipe-sign gzip will read that data as stdin. Make sure to redirect the gzip output to some file as compressed data will not be written to the terminal.

Is it possible to register a http+domain-based URL Scheme for iPhone apps, like YouTube and Maps?

If you add an iframe on your web page with the src set to custom scheme for your App, iOS will automatically redirect to that location in the App. If the app is not installed, nothing will happen. This allows you to deep link into the App if it is installed, or redirect to the App Store if it is not installed.

For example, if you have the twitter app installed, and navigate to a webpage containing the following markup, you would be immediately directed to the app.

<!DOCTYPE html>
<html>
    <head>
    <title>iOS Automatic Deep Linking</title>
    </head>
    <body>
        <iframe src="twitter://" width="0" height="0"></iframe>
        <p>Website content.</p>
    </body>
</html>

Here is a more thorough example that redirects to the App store if the App is not installed:

<!DOCTYPE html>
<html>
    <head>
    <title>iOS Automatic Deep Linking</title>
    <script src='//code.jquery.com/jquery-1.11.2.min.js'></script>
    <script src='//mobileesp.googlecode.com/svn/JavaScript/mdetect.js'></script>
    <script>
      (function ($, MobileEsp) {
        // On document ready, redirect to the App on the App store.
        $(function () {
          if (typeof MobileEsp.DetectIos !== 'undefined' && MobileEsp.DetectIos()) {
            // Add an iframe to twitter://, and then an iframe for the app store
            // link. If the first fails to redirect to the Twitter app, the
            // second will redirect to the app on the App Store. We use jQuery
            // to add this after the document is fully loaded, so if the user
            // comes back to the browser, they see the content they expect.
            $('body').append('<iframe class="twitter-detect" src="twitter://" />')
              .append('<iframe class="twitter-detect" src="itms-apps://itunes.com/apps/twitter" />');
          }
        });
      })(jQuery, MobileEsp);
    </script>
    <style type="text/css">
      .twitter-detect {
        display: none;
      }
    </style>
    </head>
    <body>
    <p>Website content.</p>
    </body>
</html>

Simple jQuery, PHP and JSONP example?

To make the server respond with a valid JSONP array, wrap the JSON in brackets () and preprend the callback:

echo $_GET['callback']."([{'fullname' : 'Jeff Hansen'}])";

Using json_encode() will convert a native PHP array into JSON:

$array = array(
    'fullname' => 'Jeff Hansen',
    'address' => 'somewhere no.3'
);
echo $_GET['callback']."(".json_encode($array).")";

Declare a variable as Decimal

To declare a variable as a Decimal, first declare it as a Variant and then convert to Decimal with CDec. The type would be Variant/Decimal in the watch window:

enter image description here

Considering that programming floating point arithmetic is not what one has studied during Maths classes at school, one should always try to avoid common pitfalls by converting to decimal whenever possible.

In the example below, we see that the expression:

0.1 + 0.11 = 0.21

is either True or False, depending on whether the collectibles (0.1,0.11) are declared as Double or as Decimal:

Public Sub TestMe()

    Dim preciseA As Variant: preciseA = CDec(0.1)
    Dim preciseB As Variant: preciseB = CDec(0.11)

    Dim notPreciseA As Double: notPreciseA = 0.1
    Dim notPreciseB As Double: notPreciseB = 0.11

    Debug.Print preciseA + preciseB
    Debug.Print preciseA + preciseB = 0.21 'True

    Debug.Print notPreciseA + notPreciseB
    Debug.Print notPreciseA + notPreciseB = 0.21 'False

End Sub

enter image description here

How can I query for null values in entity framework?

Since Entity Framework 5.0 you can use following code in order to solve your issue:

public abstract class YourContext : DbContext
{
  public YourContext()
  {
    (this as IObjectContextAdapter).ObjectContext.ContextOptions.UseCSharpNullComparisonBehavior = true;
  }
}

This should solve your problems as Entity Framerwork will use 'C# like' null comparison.

Multiple modals overlay

Everytime you run sys.showModal function increment z-index and set it to your new modal.

function system() {

    this.modalIndex = 2000;

    this.showModal = function (selector) {
        this.modalIndex++;

        $(selector).modal({
            backdrop: 'static',
            keyboard: true
        });
        $(selector).modal('show');
        $(selector).css('z-index', this.modalIndex );       
    }

}

var sys = new system();

sys.showModal('#myModal1');
sys.showModal('#myModal2');

Random color generator

Use this:

// RGBA()
function getRandomRGBA() {
    function numbers() {
        var x = Math.floor(Math.random() * 256);
        return x;
    }

    alpha = 1.0;
    return (
        "rgba(" +
        numbers() +
        ", " +
        numbers() +
        ", " +
        numbers() +
        ", " +
        alpha.toFixed(1) +
        ")"
    );
}

Set form backcolor to custom color

With Winforms you can use Form.BackColor to do this.
From within the Form's code:

BackColor = Color.LightPink;

If you mean a WPF Window you can use the Background property.
From within the Window's code:

Background = Brushes.LightPink;

CSS /JS to prevent dragging of ghost image?

You can set the image that is shown when an item is dragged. Tested with Chrome.

setDragImage

use

onclick = myFunction();
myFunction(e) {
    e.dataTransfer.setDragImage(someImage, xOffset, yOffset);
}

Alternatively, as already mentioned in the answers, you can set draggable="false" on the HTML element, if not being able to drag the element at all is no issue.

How to force view controller orientation in iOS 8?

For iOS 7 - 10:

Objective-C:

[[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeLeft) forKey:@"orientation"];
[UINavigationController attemptRotationToDeviceOrientation];

Swift 3:

let value = UIInterfaceOrientation.landscapeLeft.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
UINavigationController.attemptRotationToDeviceOrientation()

Just call it in - viewDidAppear: of the presented view controller.

"Could not find a version that satisfies the requirement opencv-python"

I faced the same issue but the mistake which I was making was pip install python-opencv where I should have used pip install opencv-python. Hope this helps to anyone. It took me few hours to find.

How can I update window.location.hash without jumping the document?

There is a workaround by using the history API on modern browsers with fallback on old ones:

if(history.pushState) {
    history.pushState(null, null, '#myhash');
}
else {
    location.hash = '#myhash';
}

Credit goes to Lea Verou

What's the difference between xsd:include and xsd:import?

Direct quote from MSDN: <xsd:import> Element, Remarks section

The difference between the include element and the import element is that import element allows references to schema components from schema documents with different target namespaces and the include element adds the schema components from other schema documents that have the same target namespace (or no specified target namespace) to the containing schema. In short, the import element allows you to use schema components from any schema; the include element allows you to add all the components of an included schema to the containing schema.

How to log as much information as possible for a Java Exception?

It should be quite simple if you are using LogBack or SLF4J. I do it as below

//imports
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//Initialize logger
Logger logger = LoggerFactory.getLogger(<classname>.class);
try {
   //try something
} catch(Exception e){
   //Actual logging of error
   logger.error("some message", e);
}

How to generate a random string in Ruby

I don't know ruby, so I can't give you the exact syntax, but I would set a constant string with the list of acceptable characters, then use the substring operator to pick a random character out of it.

The advantage here is that if the string is supposed to be user-enterable, then you can exclude easily confused characters like l and 1 and i, 0 and O, 5 and S, etc.

Best way to clear a PHP array's values

Maybe simple, economic way (less signs to use)...

$array = [];

We can read in php manual :

As of PHP 5.4 you can also use the short array syntax, which replaces array() with [].

Bash if statement with multiple conditions throws an error

You can use either [[ or (( keyword. When you use [[ keyword, you have to use string operators such as -eq, -lt. I think, (( is most preferred for arithmetic, because you can directly use operators such as ==, < and >.

Using [[ operator

a=$1
b=$2
if [[ a -eq 1 || b -eq 2 ]] || [[ a -eq 3 && b -eq 4 ]]
then
     echo "Error"
else
     echo "No Error"
fi

Using (( operator

a=$1
b=$2
if (( a == 1 || b == 2 )) || (( a == 3 && b == 4 ))
then
     echo "Error"
else
     echo "No Error"
fi

Do not use -a or -o operators Since it is not Portable.

Android check permission for LocationManager

If you simply want to check for permissions (rather than request for permissions), I wrote a simple extension like so:

fun BaseActivity.checkPermission(permissionName: String): Boolean {
        return if (Build.VERSION.SDK_INT >= 23) {
            val granted =
                ContextCompat.checkSelfPermission(this, permissionName)
            granted == PackageManager.PERMISSION_GRANTED
        } else {
            val granted =
                PermissionChecker.checkSelfPermission(this, permissionName)
            granted == PermissionChecker.PERMISSION_GRANTED
        }
    }

Now, if I want to check for a permission I can simply pass in a permission like so:

checkPermission(Manifest.permission.READ_CONTACTS)

IIS Express gives Access Denied error when debugging ASP.NET MVC

In my case I had to open the file:

C:\...\Documents\IISExpress\config\applicationhost.config

I had this inside the file:

  <authentication>
  <anonymousAuthentication enabled="true" User="" />

I just removed the User="" part. I really don't know how this thing got there... :)

Note: Make sure you have something like this in the end of applicationhost.config:

   .
   .
   .
   <location path="MyCompany.MyProjectName.Web">
        <system.webServer>
            <security>
                <authentication>
                    <anonymousAuthentication enabled="true" />
                    <windowsAuthentication enabled="false" />
                </authentication>
            </security>
        </system.webServer>
    </location>
</configuration>

You may also want to take a look here: https://stackoverflow.com/a/10041779/114029

Now I can access the login page as expected.

What does it mean when a PostgreSQL process is "idle in transaction"?

The PostgreSQL manual indicates that this means the transaction is open (inside BEGIN) and idle. It's most likely a user connected using the monitor who is thinking or typing. I have plenty of those on my system, too.

If you're using Slony for replication, however, the Slony-I FAQ suggests idle in transaction may mean that the network connection was terminated abruptly. Check out the discussion in that FAQ for more details.

jQuery hyperlinks - href value?

I almost had this problem and it was very deceiving. I am providing an answer in case someone winds up in my same position.

  1. I thought I had this problem
  2. But, I was using return false and javascript:void(0);
  3. Then a distinct difference in problem kept surfacing:
  4. I realized it's not going ALL the way to the top - and my problem zone was near the bottom of the page so this jump was strange and annoying.
  5. I realized I was using fadeIn() [jQuery library], which for a short time my content was display:none
  6. And then my content extended the reach of the page! Causing what looks like a jump!
  7. Using visibility hidden toggles now..

Hope this helps the person stuck with jumps!!

Difference between break and continue statement

The break statement exists the current looping control structure and jumps behind it while the continue exits too but jumping back to the looping condition.

How to remove all files from directory without removing directory in Node.js

graph-fs


Install

npm i graph-fs

Use

const {Node} = require("graph-fs");
const directory = new Node("/path/to/directory");

directory.clear(); // <--

Amazon S3 upload file and get URL

You can work it out for yourself given the bucket and the file name you specify in the upload request.

e.g. if your bucket is mybucket and your file is named myfilename:

https://mybucket.s3.amazonaws.com/myfilename

The s3 bit will be different depending on which region your bucket is in. For example, I use the south-east asia region so my urls are like:

https://mybucket.s3-ap-southeast-1.amazonaws.com/myfilename

Iterate through <select> options

And the requisite, non-jquery way, for followers, since google seems to send everyone here:

  var select = document.getElementById("select_id");
  for (var i = 0; i < select.length; i++){
    var option = select.options[i];
    // now have option.text, option.value
  }

C++ where to initialize static const

In a translation unit within the same namespace, usually at the top:

// foo.h
struct foo
{
    static const std::string s;
};

// foo.cpp
const std::string foo::s = "thingadongdong"; // this is where it lives

// bar.h
namespace baz
{
    struct bar
    {
        static const float f;
    };
}

// bar.cpp
namespace baz
{
    const float bar::f = 3.1415926535;
}

How to "Open" and "Save" using java

You may also want to consider the possibility of using SWT (another Java GUI library). Pros and cons of each are listed at:

Java Desktop application: SWT vs. Swing

How do I use SELECT GROUP BY in DataTable.Select(Expression)?

dt = dt.AsEnumerable().GroupBy(r => r.Field<int>("ID")).Select(g => g.First()).CopyToDataTable();

How to split a string to 2 strings in C

#include <string.h>

char *token;
char line[] = "SEVERAL WORDS";
char *search = " ";


// Token will point to "SEVERAL".
token = strtok(line, search);


// Token will point to "WORDS".
token = strtok(NULL, search);

Update

Note that on some operating systems, strtok man page mentions:

This interface is obsoleted by strsep(3).

An example with strsep is shown below:

char* token;
char* string;
char* tofree;

string = strdup("abc,def,ghi");

if (string != NULL) {

  tofree = string;

  while ((token = strsep(&string, ",")) != NULL)
  {
    printf("%s\n", token);
  }

  free(tofree);
}

How to layout multiple panels on a jFrame? (java)

The JPanel is actually only a container where you can put different elements in it (even other JPanels). So in your case I would suggest one big JPanel as some sort of main container for your window. That main panel you assign a Layout that suits your needs ( here is an introduction to the layouts).

After you set the layout to your main panel you can add the paint panel and the other JPanels you want (like those with the text in it..).

  JPanel mainPanel = new JPanel();
  mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

  JPanel paintPanel = new JPanel();
  JPanel textPanel = new JPanel();

  mainPanel.add(paintPanel);
  mainPanel.add(textPanel);

This is just an example that sorts all sub panels vertically (Y-Axis). So if you want some other stuff at the bottom of your mainPanel (maybe some icons or buttons) that should be organized with another layout (like a horizontal layout), just create again a new JPanel as a container for all the other stuff and set setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS).

As you will find out, the layouts are quite rigid and it may be difficult to find the best layout for your panels. So don't give up, read the introduction (the link above) and look at the pictures – this is how I do it :)

Or you can just use NetBeans to write your program. There you have a pretty easy visual editor (drag and drop) to create all sorts of Windows and Frames. (only understanding the code afterwards is ... tricky sometimes.)

EDIT

Since there are some many people interested in this question, I wanted to provide a complete example of how to layout a JFrame to make it look like OP wants it to.

The class is called MyFrame and extends swings JFrame

public class MyFrame extends javax.swing.JFrame{

    // these are the components we need.
    private final JSplitPane splitPane;  // split the window in top and bottom
    private final JPanel topPanel;       // container panel for the top
    private final JPanel bottomPanel;    // container panel for the bottom
    private final JScrollPane scrollPane; // makes the text scrollable
    private final JTextArea textArea;     // the text
    private final JPanel inputPanel;      // under the text a container for all the input elements
    private final JTextField textField;   // a textField for the text the user inputs
    private final JButton button;         // and a "send" button

    public MyFrame(){

        // first, lets create the containers:
        // the splitPane devides the window in two components (here: top and bottom)
        // users can then move the devider and decide how much of the top component
        // and how much of the bottom component they want to see.
        splitPane = new JSplitPane();

        topPanel = new JPanel();         // our top component
        bottomPanel = new JPanel();      // our bottom component

        // in our bottom panel we want the text area and the input components
        scrollPane = new JScrollPane();  // this scrollPane is used to make the text area scrollable
        textArea = new JTextArea();      // this text area will be put inside the scrollPane

        // the input components will be put in a separate panel
        inputPanel = new JPanel();
        textField = new JTextField();    // first the input field where the user can type his text
        button = new JButton("send");    // and a button at the right, to send the text

        // now lets define the default size of our window and its layout:
        setPreferredSize(new Dimension(400, 400));     // let's open the window with a default size of 400x400 pixels
        // the contentPane is the container that holds all our components
        getContentPane().setLayout(new GridLayout());  // the default GridLayout is like a grid with 1 column and 1 row,
        // we only add one element to the window itself
        getContentPane().add(splitPane);               // due to the GridLayout, our splitPane will now fill the whole window

        // let's configure our splitPane:
        splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);  // we want it to split the window verticaly
        splitPane.setDividerLocation(200);                    // the initial position of the divider is 200 (our window is 400 pixels high)
        splitPane.setTopComponent(topPanel);                  // at the top we want our "topPanel"
        splitPane.setBottomComponent(bottomPanel);            // and at the bottom we want our "bottomPanel"

        // our topPanel doesn't need anymore for this example. Whatever you want it to contain, you can add it here
        bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.Y_AXIS)); // BoxLayout.Y_AXIS will arrange the content vertically

        bottomPanel.add(scrollPane);                // first we add the scrollPane to the bottomPanel, so it is at the top
        scrollPane.setViewportView(textArea);       // the scrollPane should make the textArea scrollable, so we define the viewport
        bottomPanel.add(inputPanel);                // then we add the inputPanel to the bottomPanel, so it under the scrollPane / textArea

        // let's set the maximum size of the inputPanel, so it doesn't get too big when the user resizes the window
        inputPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, 75));     // we set the max height to 75 and the max width to (almost) unlimited
        inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.X_AXIS));   // X_Axis will arrange the content horizontally

        inputPanel.add(textField);        // left will be the textField
        inputPanel.add(button);           // and right the "send" button

        pack();   // calling pack() at the end, will ensure that every layout and size we just defined gets applied before the stuff becomes visible
    }

    public static void main(String args[]){
        EventQueue.invokeLater(new Runnable(){
            @Override
            public void run(){
                new MyFrame().setVisible(true);
            }
        });
    }
}

Please be aware that this is only an example and there are multiple approaches to layout a window. It all depends on your needs and if you want the content to be resizable / responsive. Another really good approach would be the GridBagLayout which can handle quite complex layouting, but which is also quite complex to learn.

Tool to Unminify / Decompress JavaScript

Despite its miles-away-from-being-pretty interface, JSPretty is a good, free and online tool for making javascript source codes human-readable. You can enforce your preferred type of indentation and it can also detect obfuscation.

Free c# QR-Code generator

ZXing is an open source project that can detect and parse a number of different barcodes. It can also generate QR-codes. (Only QR-codes, though).

There are a number of variants for different languages: ActionScript, Android (java), C++, C#, IPhone (Obj C), Java ME, Java SE, JRuby, JSP. Support for generating QR-codes comes with some of those: ActionScript, Android, C# and the Java variants.

Mapping list in Yaml to list of objects in Spring Boot

I had referenced this article and many others and did not find a clear cut concise response to help. I am offering my discovery, arrived at with some references from this thread, in the following:

Spring-Boot version: 1.3.5.RELEASE

Spring-Core version: 4.2.6.RELEASE

Dependency Management: Brixton.SR1

The following is the pertinent yaml excerpt:

tools:
  toolList:
    - 
      name: jira
      matchUrl: http://someJiraUrl
    - 
      name: bamboo
      matchUrl: http://someBambooUrl

I created a Tools.class:

@Component
@ConfigurationProperties(prefix = "tools")
public class Tools{
    private List<Tool> toolList = new ArrayList<>();
    public Tools(){
      //empty ctor
    }

    public List<Tool> getToolList(){
        return toolList;
    }

    public void setToolList(List<Tool> tools){
       this.toolList = tools;
    }
}

I created a Tool.class:

@Component
public class Tool{
    private String name;
    private String matchUrl;

    public Tool(){
      //empty ctor
    }

    public String getName(){
        return name;
    }

    public void setName(String name){
       this.name= name;
    }
    public String getMatchUrl(){
        return matchUrl;
    }

    public void setMatchUrl(String matchUrl){
       this.matchUrl= matchUrl;
    }

    @Override
    public String toString(){
        StringBuffer sb = new StringBuffer();
        String ls = System.lineSeparator();
        sb.append(ls);
        sb.append("name:  " + name);
        sb.append(ls);
        sb.append("matchUrl:  " + matchUrl);
        sb.append(ls);
    }
}

I used this combination in another class through @Autowired

@Component
public class SomeOtherClass{

   private Logger logger = LoggerFactory.getLogger(SomeOtherClass.class);

   @Autowired
   private Tools tools;

   /* excluded non-related code */

   @PostConstruct
   private void init(){
       List<Tool>  toolList = tools.getToolList();
       if(toolList.size() > 0){
           for(Tool t: toolList){
               logger.info(t.toString());
           }
       }else{
           logger.info("*****-----     tool size is zero     -----*****");
       }  
   }

   /* excluded non-related code */

}

And in my logs the name and matching url's were logged. This was developed on another machine and thus I had to retype all of the above so please forgive me in advance if I inadvertently mistyped.

I hope this consolidation comment is helpful to many and I thank the previous contributors to this thread!

Java time-based map/cache with expiring keys

Yes. Google Collections, or Guava as it is named now has something called MapMaker which can do exactly that.

ConcurrentMap<Key, Graph> graphs = new MapMaker()
   .concurrencyLevel(4)
   .softKeys()
   .weakValues()
   .maximumSize(10000)
   .expiration(10, TimeUnit.MINUTES)
   .makeComputingMap(
       new Function<Key, Graph>() {
         public Graph apply(Key key) {
           return createExpensiveGraph(key);
         }
       });

Update:

As of guava 10.0 (released September 28, 2011) many of these MapMaker methods have been deprecated in favour of the new CacheBuilder:

LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
    .maximumSize(10000)
    .expireAfterWrite(10, TimeUnit.MINUTES)
    .build(
        new CacheLoader<Key, Graph>() {
          public Graph load(Key key) throws AnyException {
            return createExpensiveGraph(key);
          }
        });

Making a Sass mixin with optional arguments

A so much better DRY way

is to pass $args... to the @mixin. That way, no matter how many $args you will pass. In the @input call, you can pass all args needed. Like so:

@mixin box-shadow($args...) {
  -webkit-box-shadow: $args;
  -moz-box-shadow: $args;
  box-shadow: $args;
}

And now you can reuse your box-shadow in every class you want by passing all needed args:

.my-box-shadow {
  @include box-shadow(2px 2px 5px #555, inset 0 0 0);
}

sublime text2 python error message /usr/bin/python: can't find '__main__' module in ''

I got the same error as I didn't save the script before executing it. Check to see if you have saved it!

Best design for a changelog / auditing database table?

There are a lot of interesting answers here and in similar questions. The only things that I can add from personal experience are:

  1. Put your audit table in another database. Ideally, you want separation from the original data. If you need to restore your database, you don't really want to restore the audit trail.

  2. Denormalize as much as reasonably possible. You want the table to have as few dependencies as possible to the original data. The audit table should be simple and lightning fast to retrieve data from. No fancy joins or lookups across other tables to get to the data.

Delete all the queues from RabbitMQ?

If you don't have rabbitmqadmin installed, try to purge queues with rabbitmqctl:

rabbitmqctl list_queues | awk '{ print $1 }' | xargs -L1 rabbitmqctl purge_queue

Maven Run Project

1. Edit POM.xml

Add the following property in pom.xml. Make sure you use the fully qualified class name (i.e. with package name) which contains the main method:

<properties>
        <exec.mainClass>fully-qualified-class-name</exec.mainClass>
</properties>

2. Run Command

Now from the terminal, trigger the following command:

mvn clean compile exec:java

NOTE You can pass further arguments via -Dexec.args="xxx" flag.

"Parser Error Message: Could not load type" in Global.asax

For my case, the web assembly was part of GAC... so after build, it need to installed in GAC and it worked.

Javascript to open popup window and disable parent window

var popupWindow=null;

function popup()
{
    popupWindow = window.open('child_page.html','name','width=200,height=200');
}

function parent_disable() {
if(popupWindow && !popupWindow.closed)
popupWindow.focus();
}

and then declare these functions in the body tag of parent window

<body onFocus="parent_disable();" onclick="parent_disable();">

As you requested here is the complete html code of the parent window

<html>
<head>
<script type="text/javascript">

var popupWindow=null;

function child_open()
{ 

popupWindow =window.open('new.jsp',"_blank","directories=no, status=no, menubar=no, scrollbars=yes, resizable=no,width=600, height=280,top=200,left=200");

}
function parent_disable() {
if(popupWindow && !popupWindow.closed)
popupWindow.focus();
}
</script>
</head>
<body onFocus="parent_disable();" onclick="parent_disable();">
    <a href="javascript:child_open()">Click me</a>
</body>    
</html>

Content of new.jsp below

<html>
<body>
I am child
</body>
</html>

Setting HTTP headers

I create wrapper for this case:

func addDefaultHeaders(fn http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Access-Control-Allow-Origin", "*")
        fn(w, r)
    }
}

How to change font size in html?

If you want to do this without adding classes...

p:first-child {
    font-size: 16px;
}

p:last-child {
    font-size: 12px;
}

or

p:nth-child(1) {
    font-size: 16px;
}

p:nth-child(2) {
    font-size: 12px;
}

java.lang.NoClassDefFoundError in junit

The org/hamcrest/SelfDescribing class is not on the run-time classpath.

Java ArrayList Index

In order to store Strings in an dynamic array (add-method) you can't define it as an array of integers ( int[3] ). You should declare it like this:

ArrayList<String> alist = new ArrayList<String>();
alist.add("apple"); 
alist.add("banana"); 
alist.add("orange"); 

System.out.println( alist.get(1) );

Java Constructor Inheritance

You essentially do inherit the constuctors in the sense that you can simply call super if and when appropriate, it's just that it would be error prone for reasons others have mentioned if it happened by default. The compiler can't presume when it is appropriate and when it isn't.

The job of the compiler is to provide as much flexibility as possible while reducing complexity and risk of unintended side-effects.

how to get the first and last days of a given month

$month = 10; // october

$firstday = date('01-' . $month . '-Y');
$lastday = date(date('t', strtotime($firstday)) .'-' . $month . '-Y');

Combining CSS Pseudo-elements, ":after" the ":last-child"

Adding another answer to this question because I needed precisely what @derek was asking for and I'd already gotten a bit further before seeing the answers here. Specifically, I needed CSS that could also account for the case with exactly two list items, where the comma is NOT desired. As an example, some authorship bylines I wanted to produce would look like the following:

One author: By Adam Smith.

Two authors: By Adam Smith and Jane Doe.

Three authors: By Adam Smith, Jane Doe, and Frank Underwood.

The solutions already given here work for one author and for 3 or more authors, but neglect to account for the two author case—where the "Oxford Comma" style (also known as "Harvard Comma" style in some parts) doesn't apply - ie, there should be no comma before the conjunction.

After an afternoon of tinkering, I had come up with the following:

<html>
 <head>
  <style type="text/css">
    .byline-list {
      list-style: none;
      padding: 0;
      margin: 0;
    }
    .byline-list > li {
      display: inline;
      padding: 0;
      margin: 0;
    }
    .byline-list > li::before {
      content: ", ";
    }
    .byline-list > li:last-child::before {
      content: ", and ";
    }
    .byline-list > li:first-child + li:last-child::before {
      content: " and ";
    }
    .byline-list > li:first-child::before {
      content: "By ";
    }
    .byline-list > li:last-child::after {
      content: ".";
    }
  </style>
 </head>
 <body>
  <ul class="byline-list">
   <li>Adam Smith</li>
  </ul>
  <ul class="byline-list">
   <li>Adam Smith</li><li>Jane Doe</li>
  </ul>
  <ul class="byline-list">
   <li>Adam Smith</li><li>Jane Doe</li><li>Frank Underwood</li>
  </ul>
 </body>
</html>

It displays the bylines as I've got them above.

In the end, I also had to get rid of any whitespace between li elements, in order to get around an annoyance: the inline-block property would otherwise leave a space before each comma. There's probably an alternative decent hack for it but that isn't the subject of this question so I'll leave that for someone else to answer.

Fiddle here: http://jsfiddle.net/5REP2/

Xcode "Device Locked" When iPhone is unlocked

sometimes your device stops trusting your PC for no reseaon. go to your settings then general > reset > reset location and privacy. and replug your device to your PC again and press "trust this device" prompt that shows up in your phone.

Fatal error: iostream: No such file or directory in compiling C program using GCC

Neither <iostream> nor <iostream.h> are standard C header files. Your code is meant to be C++, where <iostream> is a valid header. Use g++ (and a .cpp file extension) for C++ code.

Alternatively, this program uses mostly constructs that are available in C anyway. It's easy enough to convert the entire program to compile using a C compiler. Simply remove #include <iostream> and using namespace std;, and replace cout << endl; with putchar('\n');... I advise compiling using C99 (eg. gcc -std=c99)

Pandas: Setting no. of max rows

Set display.max_rows:

pd.set_option('display.max_rows', 500)

For older versions of pandas (<=0.11.0) you need to change both display.height and display.max_rows.

pd.set_option('display.height', 500)
pd.set_option('display.max_rows', 500)

See also pd.describe_option('display').

You can set an option only temporarily for this one time like this:

from IPython.display import display
with pd.option_context('display.max_rows', 100, 'display.max_columns', 10):
    display(df) #need display to show the dataframe when using with in jupyter
    #some pandas stuff

You can also reset an option back to its default value like this:

pd.reset_option('display.max_rows')

And reset all of them back:

pd.reset_option('all')

How to set editor theme in IntelliJ Idea

OK I found the problem, I was checking in the wrong place which is for the whole IDE's look and feel at File->Settings->Appearance

The correct place to change the editor appearance is through File->Settings->Editor->Colors &Fonts and then choose the scheme there. The imported settings appear there :)

Note: The theme site seems to have moved.

How to get hex color value rather than RGB value?

Since the question was using JQuery, here’s a JQuery plugin based on Daniel Elliott’s code:

$.fn.cssAsHex = function(colorProp) {

    var hexDigits = '0123456789abcdef';

    function hex(x) {
        return isNaN(x) ? '00' : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
    };

    // Convert RGB color to Hex format
    function rgb2hex(rgb) {
        var rgbRegex = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
        return '#' + hex(rgbRegex[1]) + hex(rgbRegex[2]) + hex(rgbRegex[3]);
    };

    return rgb2hex(this.css(colorProp));
};

Use it like:

var hexBackgroundColor = $('#myElement').cssAsHex('background-color');

How to calculate probability in a normal distribution given mean & standard deviation?

In case you would like to find the area between 2 values of x mean = 1; standard deviation = 2; the probability of x between [0.5,2]

import scipy.stats
scipy.stats.norm(1, 2).cdf(2) - scipy.stats.norm(1,2).cdf(0.5)

OpenCV - Saving images to a particular folder of choice

FOR MAC USERS if you are working with open cv

import cv2

cv2.imwrite('path_to_folder/image.jpg',image)

How to deploy a war file in Tomcat 7

This has been working for me:

  1. Create your war file (mysite.war) locally.
  2. Rename it locally to something besides .war, like mysite.www
  3. With tomcat still running, upload mysite.www to webapps directory.
  4. After it finishes uploading, delete the previous version mysite.war
  5. List the directory, watching for the directory /mysite to disappear.
  6. Rename mysite.www to be mysite.war
  7. List the directory, watching for the new /mysite to be created.

If you try uploading the new file as a war file, with tomcat still running, it will attempt to expand it before it is all there. It will fail. Having failed, it will not try again. Thus, uploading a www file, then renaming it, allows the whole war file to be present before tomcat notices it.

Hint, don't forget to check that the war file's owner is tomcat (Use chown)

REST API - Use the "Accept: application/json" HTTP Header

You guessed right, HTTP Headers are not part of the URL.

And when you type a URL in the browser the request will be issued with standard headers. Anyway REST Apis are not meant to be consumed by typing the endpoint in the address bar of a browser.

The most common scenario is that your server consumes a third party REST Api.

To do so your server-side code forges a proper GET (/PUT/POST/DELETE) request pointing to a given endpoint (URL) setting (when needed, like your case) some headers and finally (maybe) sending some data (as typically occurrs in a POST request for example).

The code to forge the request, send it and finally get the response back depends on your server side language.

If you want to test a REST Api you may use curl tool from the command line.

curl makes a request and outputs the response to stdout (unless otherwise instructed).

In your case the test request would be issued like this:

$curl -H "Accept: application/json" 'http://localhost:8080/otp/routers/default/plan?fromPlace=52.5895,13.2836&toPlace=52.5461,13.3588&date=2017/04/04&time=12:00:00'

The H or --header directive sets a header and its value.

Regex for allowing alphanumeric,-,_ and space

var string = 'test- _ 0Test';
string.match(/^[-_ a-zA-Z0-9]+$/)

Get the closest number out of an array

Working code as below:

_x000D_
_x000D_
var array = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362];_x000D_
_x000D_
function closest(array, num) {_x000D_
  var i = 0;_x000D_
  var minDiff = 1000;_x000D_
  var ans;_x000D_
  for (i in array) {_x000D_
    var m = Math.abs(num - array[i]);_x000D_
    if (m < minDiff) {_x000D_
      minDiff = m;_x000D_
      ans = array[i];_x000D_
    }_x000D_
  }_x000D_
  return ans;_x000D_
}_x000D_
console.log(closest(array, 88));
_x000D_
_x000D_
_x000D_

React img tag issue with url and class

var Hello = React.createClass({
    render: function() {
      return (
        <div className="divClass">
           <img src={this.props.url} alt={`${this.props.title}'s picture`}  className="img-responsive" />
           <span>Hello {this.props.name}</span>
        </div>
      );
    }
});

batch to copy files with xcopy

Based on xcopy help, I tried and found that following works perfectly for me (tried on Win 7)

xcopy C:\folder1 C:\folder2\folder1 /E /C /I /Q /G /H /R /K /Y /Z /J

Set a persistent environment variable from cmd.exe

An example with VBScript (.vbs)

Sub sety(wsh, action, typey, vary, value)
  Dim wu
  Set wu = wsh.Environment(typey)
  wui = wu.Item(vary)
  Select Case action
    Case "ls"
      WScript.Echo wui
    Case "del"
      On Error Resume Next
      wu.remove(vary)
      On Error Goto 0
    Case "set"
      wu.Item(vary) = value
    Case "add"
      If wui = "" Then
        wu.Item(vary) = value
      ElseIf InStr(UCase(";" & wui & ";"), UCase(";" & value & ";")) = 0 Then
        wu.Item(vary) = value & ";" & wui
      End If
    Case Else
      WScript.Echo "Bad action"
  End Select
End Sub

Dim wsh, args
Set wsh = WScript.CreateObject("WScript.Shell")
Set args = WScript.Arguments
Select Case WScript.Arguments.Length
  Case 3
    value = ""
  Case 4
    value = args(3)
  Case Else
    WScript.Echo "Arguments - 0: ls,del,set,add; 1: user,system, 2: variable; 3: value"
    value = "```"
End Select
If Not value = "```" Then
  ' 0: ls,del,set,add; 1: user,system, 2: variable; 3: value
  sety wsh, args(0), args(1), UCase(args(2)), value
End If

How do I prevent the error "Index signature of object type implicitly has an 'any' type" when compiling typescript with noImplicitAny flag enabled?

At today better solution is to declare types. Like

enum SomeObjectKeys {
    firstKey = 'firstKey',
    secondKey = 'secondKey',
    thirdKey = 'thirdKey',
}

let someObject: Record<SomeObjectKeys, string> = {
    firstKey:   'firstValue',
    secondKey:  'secondValue',
    thirdKey:   'thirdValue',
};

let key: SomeObjectKeys = 'secondKey';

let secondValue: string = someObject[key];

What are MVP and MVC and what is the difference?

I blogged about this a while back, quoting on Todd Snyder's excellent post on the difference between the two:

Here are the key differences between the patterns:

MVP Pattern

  • View is more loosely coupled to the model. The presenter is responsible for binding the model to the view.
  • Easier to unit test because interaction with the view is through an interface
  • Usually view to presenter map one to one. Complex views may have multi presenters.

MVC Pattern

  • Controller are based on behaviors and can be shared across views
  • Can be responsible for determining which view to display

It is the best explanation on the web I could find.

iOS - Calling App Delegate method from ViewController

If someone need the same in Xamarin (Xamarin.ios / Monotouch), this worked for me:

var myDelegate = UIApplication.SharedApplication.Delegate as AppDelegate;

(Require using UIKit;)

Get Path from another app (WhatsApp)

You can try this it will help for you.You can't get path from WhatsApp directly.If you need an file path first copy file and send new file path. Using the code below

 public static String getFilePathFromURI(Context context, Uri contentUri) {
    String fileName = getFileName(contentUri);
    if (!TextUtils.isEmpty(fileName)) {
        File copyFile = new File(TEMP_DIR_PATH  + fileName+".jpg");
        copy(context, contentUri, copyFile);
        return copyFile.getAbsolutePath();
    }
    return null;
}

public static String getFileName(Uri uri) {
    if (uri == null) return null;
    String fileName = null;
    String path = uri.getPath();
    int cut = path.lastIndexOf('/');
    if (cut != -1) {
        fileName = path.substring(cut + 1);
    }
    return fileName;
}

public static void copy(Context context, Uri srcUri, File dstFile) {
    try {
        InputStream inputStream = context.getContentResolver().openInputStream(srcUri);
        if (inputStream == null) return;
        OutputStream outputStream = new FileOutputStream(dstFile);
        IOUtils.copy(inputStream, outputStream);
        inputStream.close();
        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Then IOUtils class is like below

public class IOUtils {



private static final int BUFFER_SIZE = 1024 * 2;

private IOUtils() {
    // Utility class.
}

public static int copy(InputStream input, OutputStream output) throws Exception, IOException {
    byte[] buffer = new byte[BUFFER_SIZE];

    BufferedInputStream in = new BufferedInputStream(input, BUFFER_SIZE);
    BufferedOutputStream out = new BufferedOutputStream(output, BUFFER_SIZE);
    int count = 0, n = 0;
    try {
        while ((n = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
            out.write(buffer, 0, n);
            count += n;
        }
        out.flush();
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            Log.e(e.getMessage(), e.toString());
        }
        try {
            in.close();
        } catch (IOException e) {
            Log.e(e.getMessage(), e.toString());
        }
    }
    return count;
}


}

how do I make a single legend for many subplots with matplotlib?

While rather late to the game, I'll give another solution here as this is still one of the first links to show up on google. Using matplotlib 2.2.2, this can be achieved using the gridspec feature. In the example below the aim is to have four subplots arranged in a 2x2 fashion with the legend shown at the bottom. A 'faux' axis is created at the bottom to place the legend in a fixed spot. The 'faux' axis is then turned off so only the legend shows. Result: https://i.stack.imgur.com/5LUWM.png.

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

#Gridspec demo
fig = plt.figure()
fig.set_size_inches(8,9)
fig.set_dpi(100)

rows   = 17 #the larger the number here, the smaller the spacing around the legend
start1 = 0
end1   = int((rows-1)/2)
start2 = end1
end2   = int(rows-1)

gspec = gridspec.GridSpec(ncols=4, nrows=rows)

axes = []
axes.append(fig.add_subplot(gspec[start1:end1,0:2]))
axes.append(fig.add_subplot(gspec[start2:end2,0:2]))
axes.append(fig.add_subplot(gspec[start1:end1,2:4]))
axes.append(fig.add_subplot(gspec[start2:end2,2:4]))
axes.append(fig.add_subplot(gspec[end2,0:4]))

line, = axes[0].plot([0,1],[0,1],'b')           #add some data
axes[-1].legend((line,),('Test',),loc='center') #create legend on bottommost axis
axes[-1].set_axis_off()                         #don't show bottommost axis

fig.tight_layout()
plt.show()

Open and write data to text file using Bash?

You can redirect the output of a command to a file:

$ cat file > copy_file

or append to it

$ cat file >> copy_file

If you want to write directly the command is echo 'text'

$ echo 'Hello World' > file

Gradle - Move a folder from ABC to XYZ

Your task declaration is incorrectly combining the Copy task type and project.copy method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File API) will do. Assuming Project1 is the project directory:

task renABCToXYZ {     doLast {         file("ABC").renameTo(file("XYZ"))     } } 

Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast task action) to the task that produces ABC.

Why calling react setState method doesn't mutate the state immediately?

As mentioned in the React documentation, there is no guarantee of setState being fired synchronously, so your console.log may return the state prior to it updating.

Michael Parker mentions passing a callback within the setState. Another way to handle the logic after state change is via the componentDidUpdate lifecycle method, which is the method recommended in React docs.

Generally we recommend using componentDidUpdate() for such logic instead.

This is particularly useful when there may be successive setStates fired, and you would like to fire the same function after every state change. Rather than adding a callback to each setState, you could place the function inside of the componentDidUpdate, with specific logic inside if necessary.

// example
componentDidUpdate(prevProps, prevState) {
  if (this.state.value > prevState.value) {
    this.foo();  
  }
}

Using cURL with a username and password?

To securely pass the password in a script (i.e. prevent it from showing up with ps auxf or logs) you can do it with the -K- flag (read config from stdin) and a heredoc:

curl --url url -K- <<< "--user user:password"

How to implement static class member functions in *.cpp file?

Yes you can define static member functions in *.cpp file. If you define it in the header, compiler will by default treat it as inline. However, it does not mean separate copies of the static member function will exist in the executable. Please follow this post to learn more about this: Are static member functions in c++ copied in multiple translation units?

Swift: Determine iOS Screen size

In Swift 3.0

let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height

In older swift: Do something like this:

let screenSize: CGRect = UIScreen.mainScreen().bounds

then you can access the width and height like this:

let screenWidth = screenSize.width
let screenHeight = screenSize.height

if you want 75% of your screen's width you can go:

let screenWidth = screenSize.width * 0.75

Swift 4.0

// Screen width.
public var screenWidth: CGFloat {
    return UIScreen.main.bounds.width
}

// Screen height.
public var screenHeight: CGFloat {
    return UIScreen.main.bounds.height
}

In Swift 5.0

let screenSize: CGRect = UIScreen.main.bounds

How to debug on a real device (using Eclipse/ADT)

With an Android-powered device, you can develop and debug your Android applications just as you would on the emulator.

1. Declare your application as "debuggable" in AndroidManifest.xml.

<application
    android:debuggable="true"
    ... >
    ...
</application>

2. On your handset, navigate to Settings > Security and check Unknown sources

enter image description here

3. Go to Settings > Developer Options and check USB debugging
Note that if Developer Options is invisible you will need to navigate to Settings > About Phone and tap on Build number several times until you are notified that it has been unlocked.

enter image description here

4. Set up your system to detect your device.
Follow the instructions below for your OS:


Windows Users

Install the Google USB Driver from the ADT SDK Manager
(Support for: ADP1, ADP2, Verizon Droid, Nexus One, Nexus S).

enter image description here

For devices not listed above, install an OEM driver for your device


Mac OS X

Your device should automatically work; Go to the next step


Ubuntu Linux

Add a udev rules file that contains a USB configuration for each type of device you want to use for development. In the rules file, each device manufacturer is identified by a unique vendor ID, as specified by the ATTR{idVendor} property. For a list of vendor IDs, click here. To set up device detection on Ubuntu Linux:

  1. Log in as root and create this file: /etc/udev/rules.d/51-android.rules.
  2. Use this format to add each vendor to the file:
    SUBSYSTEM=="usb", ATTR{idVendor}=="0bb4", MODE="0666", GROUP="plugdev"
    In this example, the vendor ID is for HTC. The MODE assignment specifies read/write permissions, and GROUP defines which Unix group owns the device node.
  3. Now execute: chmod a+r /etc/udev/rules.d/51-android.rules

Note: The rule syntax may vary slightly depending on your environment. Consult the udev documentation for your system as needed. For an overview of rule syntax, see this guide to writing udev rules.


5. Run the project with your connected device.

With Eclipse/ADT: run or debug your application as usual. You will be presented with a Device Chooser dialog that lists the available emulator(s) and connected device(s).

With ADB: issue commands with the -d flag to target your connected device.

Still need help? Click here for the full guide.

How to get exception message in Python properly

To improve on the answer provided by @artofwarfare, here is what I consider a neater way to check for the message attribute and print it or print the Exception object as a fallback.

try:
    pass 
except Exception as e:
    print getattr(e, 'message', repr(e))

The call to repr is optional, but I find it necessary in some use cases.


Update #1:

Following the comment by @MadPhysicist, here's a proof of why the call to repr might be necessary. Try running the following code in your interpreter:

try:
    raise Exception 
except Exception as e:
    print(getattr(e, 'message', repr(e)))
    print(getattr(e, 'message', str(e)))

Update #2:

Here is a demo with specifics for Python 2.7 and 3.5: https://gist.github.com/takwas/3b7a6edddef783f2abddffda1439f533

Socket.io + Node.js Cross-Origin Request Blocked

I am facing problem while making an chat app using socket.io and node.js & React. Also this issue is not spacefic to Firefox browser, i face same issue in Edge & Chrome also.

"Cross-Origin request is blocked and it is used by some other resources..."

Then i download cors in project directory and put it in the server file index.js as below: To download simply type command using node.js :

npm install cors

const cors = require('cors');
app.use(cors());

This will allow CORS to used by different resources in the files and allow cross origin request in the browser.

Decreasing height of bootstrap 3.0 navbar

if you are using the less source, there should be a variable for the navbar height in the variables.less file. If you are not using the source, then you can customize it using the customize utilty that bootstrap's site provides. And then you can downloaded it and include it in your project. The variable you are looking for is: @navbar-height

Select and display only duplicate records in MySQL

The IN was too slow in my situation (180 secs)

So I used a JOIN instead (0.3 secs)

SELECT i.id, i.payer_email
FROM paypal_ipn_orders i
INNER JOIN (
 SELECT payer_email
    FROM paypal_ipn_orders 
    GROUP BY payer_email
    HAVING COUNT( id ) > 1
) j ON i.payer_email=j.payer_email

How do I use brew installed Python as the default Python?

I did brew install python, my $PATH was good, but still, which python gave me the system installed one. Restarting the terminal fixed it.

Cell Style Alignment on a range

Modifying styles directly in range or cells did not work for me. But the idea to:

  1. create a separate style
  2. apply all the necessary style property values
  3. set the style's name to the Style property of the range

, given in MSDN How to: Programmatically Apply Styles to Ranges in Workbooks did the job.

For example:

var range = worksheet.Range[string.Format("A{0}:C{0}", rowIndex++)];
range.Merge();
range.Value = "some value";

var style = workbook.AddStyle();
style.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;

range.Style = style.Name;

How to delete a whole folder and content?

This is what I do... (terse and tested)

    ...
    deleteDir(new File(dir_to_be_deleted));
    ...

    // delete directory and contents
    void deleteDir(File file) { 
        if (file.isDirectory())
            for (String child : file.list())
                deleteDir(new File(file, child));
        file.delete();  // delete child file or empty directory
    }

What's the purpose of SQL keyword "AS"?

Everyone who answered before me is correct. You use it kind of as an alias shortcut name for a table when you have long queries or queries that have joins. Here's a couple examples.

Example 1

SELECT P.ProductName,
       P.ProductGroup,
       P.ProductRetailPrice
FROM   Products AS P

Example 2

SELECT P.ProductName,
       P.ProductRetailPrice,
       O.Quantity
FROM   Products AS P
LEFT OUTER JOIN Orders AS O ON O.ProductID = P.ProductID
WHERE  O.OrderID = 123456

Example 3 It's a good practice to use the AS keyword, and very recommended, but it is possible to perform the same query without one (and I do often).

SELECT P.ProductName,
       P.ProductRetailPrice,
       O.Quantity
FROM   Products P
LEFT OUTER JOIN Orders O ON O.ProductID = P.ProductID
WHERE  O.OrderID = 123456

As you can tell, I left out the AS keyword in the last example. And it can be used as an alias.

Example 4

SELECT P.ProductName AS "Product",
       P.ProductRetailPrice AS "Retail Price",
       O.Quantity AS "Quantity Ordered"
FROM   Products P
LEFT OUTER JOIN Orders O ON O.ProductID = P.ProductID
WHERE  O.OrderID = 123456

Output of Example 4

Product             Retail Price     Quantity Ordered
Blue Raspberry Gum  $10 pk/$50 Case  2 Cases
Twizzler            $5 pk/$25 Case   10 Cases

How to call a stored procedure from Java and JPA

You can use @Query(value = "{call PROC_TEST()}", nativeQuery = true) in your repository. This worked for me.

Attention: use '{' and '}' or else it will not work.

Join/Where with LINQ and Lambda

I find that if you're familiar with SQL syntax, using the LINQ query syntax is much clearer, more natural, and makes it easier to spot errors:

var id = 1;
var query =
   from post in database.Posts
   join meta in database.Post_Metas on post.ID equals meta.Post_ID
   where post.ID == id
   select new { Post = post, Meta = meta };

If you're really stuck on using lambdas though, your syntax is quite a bit off. Here's the same query, using the LINQ extension methods:

var id = 1;
var query = database.Posts    // your starting point - table in the "from" statement
   .Join(database.Post_Metas, // the source table of the inner join
      post => post.ID,        // Select the primary key (the first part of the "on" clause in an sql "join" statement)
      meta => meta.Post_ID,   // Select the foreign key (the second part of the "on" clause)
      (post, meta) => new { Post = post, Meta = meta }) // selection
   .Where(postAndMeta => postAndMeta.Post.ID == id);    // where statement

How to run function of parent window when child window closes?

Along with jerjer answer(top), sometimes in your parent window and child window are not both external or both internal you will see a problem of opener undefined, and you cannot access parent page properties, see window.opener is undefined on Internet Explorer

Collision resolution in Java HashMap

There is no collision in your example. You use the same key, so the old value gets replaced with the new one. Now, if you used two keys that map to the same hash code, then you'd have a collision. But even in that case, HashMap would replace your value! If you want the values to be chained in case of a collision, you have to do it yourself, e.g. by using a list as a value.

How to convert an object to a byte array in C#

Take a look at Serialization, a technique to "convert" an entire object to a byte stream. You may send it to the network or write it into a file and then restore it back to an object later.

When do Java generics require <? extends T> instead of <T> and is there any downside of switching?

what if you use

Map<String, ? extends Class<? extends Serializable>> expected = null;

Importing csv file into R - numeric values read as characters

Whatever algebra you are doing in Excel to create the new column could probably be done more effectively in R.

Please try the following: Read the raw file (before any excel manipulation) into R using read.csv(... stringsAsFactors=FALSE). [If that does not work, please take a look at ?read.table (which read.csv wraps), however there may be some other underlying issue].

For example:

   delim = ","  # or is it "\t" ?
   dec = "."    # or is it "," ?
   myDataFrame <- read.csv("path/to/file.csv", header=TRUE, sep=delim, dec=dec, stringsAsFactors=FALSE)

Then, let's say your numeric columns is column 4

   myDataFrame[, 4]  <- as.numeric(myDataFrame[, 4])  # you can also refer to the column by "itsName"


Lastly, if you need any help with accomplishing in R the same tasks that you've done in Excel, there are plenty of folks here who would be happy to help you out

pointer to array c++

The parenthesis are superfluous in your example. The pointer doesn't care whether there's an array involved - it only knows that its pointing to an int

  int g[] = {9,8};
  int (*j) = g;

could also be rewritten as

  int g[] = {9,8};
  int *j = g;

which could also be rewritten as

  int g[] = {9,8};
  int *j = &g[0];

a pointer-to-an-array would look like

  int g[] = {9,8};
  int (*j)[2] = &g;

  //Dereference 'j' and access array element zero
  int n = (*j)[0];

There's a good read on pointer declarations (and how to grok them) at this link here: http://www.codeproject.com/Articles/7042/How-to-interpret-complex-C-C-declarations

Git update submodules recursively

As it may happens that the default branch of your submodules are not master (which happens a lot in my case), this is how I automate the full Git submodules upgrades:

git submodule init
git submodule update
git submodule foreach 'git fetch origin; git checkout $(git rev-parse --abbrev-ref HEAD); git reset --hard origin/$(git rev-parse --abbrev-ref HEAD); git submodule update --recursive; git clean -dfx'

Simple C example of doing an HTTP POST and consuming the response

A message has a header part and a message body separated by a blank line. The blank line is ALWAYS needed even if there is no message body. The header starts with a command and has additional lines of key value pairs separated by a colon and a space. If there is a message body, it can be anything you want it to be.

Lines in the header and the blank line at the end of the header must end with a carraige return and linefeed pair (see HTTP header line break style) so that's why those lines have \r\n at the end.

A URL has the form of http://host:port/path?query_string

There are two main ways of submitting a request to a website:

  • GET: The query string is optional but, if specified, must be reasonably short. Because of this the header could just be the GET command and nothing else. A sample message could be:

    GET /path?query_string HTTP/1.0\r\n
    \r\n
    
  • POST: What would normally be in the query string is in the body of the message instead. Because of this the header needs to include the Content-Type: and Content-Length: attributes as well as the POST command. A sample message could be:

    POST /path HTTP/1.0\r\n
    Content-Type: text/plain\r\n
    Content-Length: 12\r\n
    \r\n
    query_string
    

So, to answer your question: if the URL you are interested in POSTing to is http://api.somesite.com/apikey=ARG1&command=ARG2 then there is no body or query string and, consequently, no reason to POST because there is nothing to put in the body of the message and so nothing to put in the Content-Type: and Content-Length:

I guess you could POST if you really wanted to. In that case your message would look like:

POST /apikey=ARG1&command=ARG2 HTTP/1.0\r\n
\r\n

So to send the message the C program needs to:

  • create a socket
  • lookup the IP address
  • open the socket
  • send the request
  • wait for the response
  • close the socket

The send and receive calls won't necessarily send/receive ALL the data you give them - they will return the number of bytes actually sent/received. It is up to you to call them in a loop and send/receive the remainder of the message.

What I did not do in this sample is any sort of real error checking - when something fails I just exit the program. Let me know if it works for you:

#include <stdio.h> /* printf, sprintf */
#include <stdlib.h> /* exit */
#include <unistd.h> /* read, write, close */
#include <string.h> /* memcpy, memset */
#include <sys/socket.h> /* socket, connect */
#include <netinet/in.h> /* struct sockaddr_in, struct sockaddr */
#include <netdb.h> /* struct hostent, gethostbyname */

void error(const char *msg) { perror(msg); exit(0); }

int main(int argc,char *argv[])
{
    /* first what are we going to send and where are we going to send it? */
    int portno =        80;
    char *host =        "api.somesite.com";
    char *message_fmt = "POST /apikey=%s&command=%s HTTP/1.0\r\n\r\n";

    struct hostent *server;
    struct sockaddr_in serv_addr;
    int sockfd, bytes, sent, received, total;
    char message[1024],response[4096];

    if (argc < 3) { puts("Parameters: <apikey> <command>"); exit(0); }

    /* fill in the parameters */
    sprintf(message,message_fmt,argv[1],argv[2]);
    printf("Request:\n%s\n",message);

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

    /* lookup the ip address */
    server = gethostbyname(host);
    if (server == NULL) error("ERROR, no such host");

    /* fill in the structure */
    memset(&serv_addr,0,sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(portno);
    memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);

    /* connect the socket */
    if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
        error("ERROR connecting");

    /* send the request */
    total = strlen(message);
    sent = 0;
    do {
        bytes = write(sockfd,message+sent,total-sent);
        if (bytes < 0)
            error("ERROR writing message to socket");
        if (bytes == 0)
            break;
        sent+=bytes;
    } while (sent < total);

    /* receive the response */
    memset(response,0,sizeof(response));
    total = sizeof(response)-1;
    received = 0;
    do {
        bytes = read(sockfd,response+received,total-received);
        if (bytes < 0)
            error("ERROR reading response from socket");
        if (bytes == 0)
            break;
        received+=bytes;
    } while (received < total);

    if (received == total)
        error("ERROR storing complete response from socket");

    /* close the socket */
    close(sockfd);

    /* process response */
    printf("Response:\n%s\n",response);

    return 0;
}

Like the other answer pointed out, 4096 bytes is not a very big response. I picked that number at random assuming that the response to your request would be short. If it can be big you have two choices:

  • read the Content-Length: header from the response and then dynamically allocate enough memory to hold the whole response.
  • write the response to a file as the pieces arrive

Additional information to answer the question asked in the comments:

What if you want to POST data in the body of the message? Then you do need to include the Content-Type: and Content-Length: headers. The Content-Length: is the actual length of everything after the blank line that separates the header from the body.

Here is a sample that takes the following command line arguments:

  • host
  • port
  • command (GET or POST)
  • path (not including the query data)
  • query data (put into the query string for GET and into the body for POST)
  • list of headers (Content-Length: is automatic if using POST)

So, for the original question you would run:

a.out api.somesite.com 80 GET "/apikey=ARG1&command=ARG2"

And for the question asked in the comments you would run:

a.out api.somesite.com 80 POST / "name=ARG1&value=ARG2" "Content-Type: application/x-www-form-urlencoded"

Here is the code:

#include <stdio.h> /* printf, sprintf */
#include <stdlib.h> /* exit, atoi, malloc, free */
#include <unistd.h> /* read, write, close */
#include <string.h> /* memcpy, memset */
#include <sys/socket.h> /* socket, connect */
#include <netinet/in.h> /* struct sockaddr_in, struct sockaddr */
#include <netdb.h> /* struct hostent, gethostbyname */

void error(const char *msg) { perror(msg); exit(0); }

int main(int argc,char *argv[])
{
    int i;

    /* first where are we going to send it? */
    int portno = atoi(argv[2])>0?atoi(argv[2]):80;
    char *host = strlen(argv[1])>0?argv[1]:"localhost";

    struct hostent *server;
    struct sockaddr_in serv_addr;
    int sockfd, bytes, sent, received, total, message_size;
    char *message, response[4096];

    if (argc < 5) { puts("Parameters: <host> <port> <method> <path> [<data> [<headers>]]"); exit(0); }

    /* How big is the message? */
    message_size=0;
    if(!strcmp(argv[3],"GET"))
    {
        message_size+=strlen("%s %s%s%s HTTP/1.0\r\n");        /* method         */
        message_size+=strlen(argv[3]);                         /* path           */
        message_size+=strlen(argv[4]);                         /* headers        */
        if(argc>5)
            message_size+=strlen(argv[5]);                     /* query string   */
        for(i=6;i<argc;i++)                                    /* headers        */
            message_size+=strlen(argv[i])+strlen("\r\n");
        message_size+=strlen("\r\n");                          /* blank line     */
    }
    else
    {
        message_size+=strlen("%s %s HTTP/1.0\r\n");
        message_size+=strlen(argv[3]);                         /* method         */
        message_size+=strlen(argv[4]);                         /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            message_size+=strlen(argv[i])+strlen("\r\n");
        if(argc>5)
            message_size+=strlen("Content-Length: %d\r\n")+10; /* content length */
        message_size+=strlen("\r\n");                          /* blank line     */
        if(argc>5)
            message_size+=strlen(argv[5]);                     /* body           */
    }

    /* allocate space for the message */
    message=malloc(message_size);

    /* fill in the parameters */
    if(!strcmp(argv[3],"GET"))
    {
        if(argc>5)
            sprintf(message,"%s %s%s%s HTTP/1.0\r\n",
                strlen(argv[3])>0?argv[3]:"GET",               /* method         */
                strlen(argv[4])>0?argv[4]:"/",                 /* path           */
                strlen(argv[5])>0?"?":"",                      /* ?              */
                strlen(argv[5])>0?argv[5]:"");                 /* query string   */
        else
            sprintf(message,"%s %s HTTP/1.0\r\n",
                strlen(argv[3])>0?argv[3]:"GET",               /* method         */
                strlen(argv[4])>0?argv[4]:"/");                /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            {strcat(message,argv[i]);strcat(message,"\r\n");}
        strcat(message,"\r\n");                                /* blank line     */
    }
    else
    {
        sprintf(message,"%s %s HTTP/1.0\r\n",
            strlen(argv[3])>0?argv[3]:"POST",                  /* method         */
            strlen(argv[4])>0?argv[4]:"/");                    /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            {strcat(message,argv[i]);strcat(message,"\r\n");}
        if(argc>5)
            sprintf(message+strlen(message),"Content-Length: %d\r\n",strlen(argv[5]));
        strcat(message,"\r\n");                                /* blank line     */
        if(argc>5)
            strcat(message,argv[5]);                           /* body           */
    }

    /* What are we going to send? */
    printf("Request:\n%s\n",message);

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

    /* lookup the ip address */
    server = gethostbyname(host);
    if (server == NULL) error("ERROR, no such host");

    /* fill in the structure */
    memset(&serv_addr,0,sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(portno);
    memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);

    /* connect the socket */
    if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
        error("ERROR connecting");

    /* send the request */
    total = strlen(message);
    sent = 0;
    do {
        bytes = write(sockfd,message+sent,total-sent);
        if (bytes < 0)
            error("ERROR writing message to socket");
        if (bytes == 0)
            break;
        sent+=bytes;
    } while (sent < total);

    /* receive the response */
    memset(response,0,sizeof(response));
    total = sizeof(response)-1;
    received = 0;
    do {
        bytes = read(sockfd,response+received,total-received);
        if (bytes < 0)
            error("ERROR reading response from socket");
        if (bytes == 0)
            break;
        received+=bytes;
    } while (received < total);

    if (received == total)
        error("ERROR storing complete response from socket");

    /* close the socket */
    close(sockfd);

    /* process response */
    printf("Response:\n%s\n",response);

    free(message);
    return 0;
}

What is the best way to programmatically detect porn images?

There is software that detects the probability for porn, but this is not an exact science, as computers can't recognize what is actually on pictures (pictures are only a big set of values on a grid with no meaning). You can just teach the computer what is porn and what not by giving examples. This has the disadvantage that it will only recognize these or similar images.

Given the repetitive nature of porn you have a good chance if you train the system with few false positives. For example if you train the system with nude people it may flag pictures of a beach with "almost" naked people as porn too.

A similar software is the facebook software that recently came out. It's just specialized on faces. The main principle is the same.

Technically you would implement some kind of feature detector that utilizes a bayes filtering. The feature detector may look for features like percentage of flesh colored pixels if it's a simple detector or just computes the similarity of the current image with a set of saved porn images.

This is of course not limited to porn, it's actually more a corner case. I think more common are systems that try to find other things in images ;-)

Is there an equivalent of lsusb for OS X

system_profiler SPUSBDataType

it your need command on macos

Vertically align text to top within a UILabel

enter image description here

In Interface Builder

  • Set UILabel to size of biggest possible Text
  • Set Lines to '0' in Attributes Inspector

In your code

  • Set the text of the label
  • Call sizeToFit on your label

Code Snippet:

self.myLabel.text = @"Short Title";
[self.myLabel sizeToFit];

WARNING: Can't verify CSRF token authenticity rails

I struggled with this issue for days. Any GET call was working correctly, but all PUTs would generate a "Can't verify CSRF token authenticity" error. My website was working fine until I had added a SSL cert to nginx.

I finally stumbled on this missing line in my nginx settings:

location @puma { 
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
    proxy_set_header Host $http_host; 
    proxy_redirect off;
    proxy_set_header X-Forwarded-Proto https;   # Needed to avoid 'WARNING: Can't verify CSRF token authenticity'
    proxy_pass http://puma; 
}

After adding the missing line "proxy_set_header X-Forwarded-Proto https;", all my CSRF token errors quit.

Hopefully this helps someone else who also is beating their head against a wall. haha

How do I select text nodes with jQuery?

if you want to strip all tags, then try this

function:

String.prototype.stripTags=function(){
var rtag=/<.*?[^>]>/g;
return this.replace(rtag,'');
}

usage:

var newText=$('selector').html().stripTags();

Proper use of 'yield return'

As a conceptual example for understanding when you ought to use yield, let's say the method ConsumeLoop() processes the items returned/yielded by ProduceList():

void ConsumeLoop() {
    foreach (Consumable item in ProduceList())        // might have to wait here
        item.Consume();
}

IEnumerable<Consumable> ProduceList() {
    while (KeepProducing())
        yield return ProduceExpensiveConsumable();    // expensive
}

Without yield, the call to ProduceList() might take a long time because you have to complete the list before returning:

//pseudo-assembly
Produce consumable[0]                   // expensive operation, e.g. disk I/O
Produce consumable[1]                   // waiting...
Produce consumable[2]                   // waiting...
Produce consumable[3]                   // completed the consumable list
Consume consumable[0]                   // start consuming
Consume consumable[1]
Consume consumable[2]
Consume consumable[3]

Using yield, it becomes rearranged, sort of interleaved:

//pseudo-assembly
Produce consumable[0]
Consume consumable[0]                   // immediately yield & Consume
Produce consumable[1]                   // ConsumeLoop iterates, requesting next item
Consume consumable[1]                   // consume next
Produce consumable[2]
Consume consumable[2]                   // consume next
Produce consumable[3]
Consume consumable[3]                   // consume next

And lastly, as many before have already suggested, you should use Version 2 because you already have the completed list anyway.

Directory.GetFiles: how to get only filename, not full path?

Use this to obtain only the filename.

Path.GetFileName(files[0]);

Install python 2.6 in CentOS

Late to the party, but the OP should have gone with Buildout or Virtualenv, and sidestepped the problem completely.

I am currently working on a Centos server, well, toiling away would be the proper term and I can assure everyone that the only way I am able to blink back the tears whilst using the software equivalents of fire hardened spears, is buildout.

Get Country of IP Address with PHP

There are free, easy APIs you can use, like those:

Which one looks the most trustworthy is up to you :)

Otherwise, there are scripts which are based on local databases on your server. The database data needs to be updated regularly, though. Check out this one:

HTH!

Edit: And of course, depending on your project you might want to look at HTML5 Location features. You can't use them yet on the Internet Explorer (IE9 will support it, long way to go yet), but in case your audience is mainly on mobile devices or using Safari/Firefox it's definitely worth to look at it!

Once you have the coordinates, you can reverse geocode them to a country code. Again there are APIs like this one:

Update, April 2013
Today I would recommend using Geocoder, a PHP library which makes it very easy to geocode ip addresses as well as postal address data.

***Update, September 2016
Since Google's privacy politics has changed, you can't use HTML5 Geolocation API if your server doesn't have HTPPS certificate or user doesn't allow you check his location. So now you can use user's IP and check in in PHP or get HTTPS certificate.

IIS7 Cache-Control

The F5 Refresh has the semantic of "please reload the current HTML AND its direct dependancies". Hence you should expect to see any imgs, css and js resource directly referenced by the HTML also being refetched. Of course a 304 is an acceptable response to this but F5 refresh implies that the browser will make the request rather than rely on fresh cache content.

Instead try simply navigating somewhere else and then navigating back.

You can force the refresh, past a 304, by holding ctrl while pressing f5 in most browsers.