Programs & Examples On #Image transcoding

Anything related to image transcoding, i.e. the process of converting a digital image from a storage format to another (e.g. from PNG to JPG).

How to check string length and then select substring in Sql Server

To conditionally check the length of the string, use CASE.

SELECT  CASE WHEN LEN(comments) <= 60 
             THEN comments
             ELSE LEFT(comments, 60) + '...'
        END  As Comments
FROM    myView

What is the difference between Scala's case class and class?

No one mentioned that case classes are also instances of Product and thus inherit these methods:

def productElement(n: Int): Any
def productArity: Int
def productIterator: Iterator[Any]

where the productArity returns the number of class parameters, productElement(i) returns the ith parameter, and productIterator allows iterating through them.

How can I change the font size of ticks of axes object in matplotlib

fig = plt.figure()
ax = fig.add_subplot(111)
plt.xticks([0.4,0.14,0.2,0.2], fontsize = 50) # work on current fig
plt.show()

the x/yticks has the same properties as matplotlib.text

How to make a whole 'div' clickable in html and css without JavaScript?

Without JS, I am doing it like this:

My HTML:

<div class="container">
  <div class="sometext">Some text here</div>
  <div class="someothertext">Some other text here</div>
  <a href="#" class="mylink">text of my link</a>
</div>

My CSS:

.container{
  position: relative;
}

.container.a{
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  text-indent: -9999px; //these two lines are to hide my actual link text.
  overflow: hidden; //these two lines are to hide my actual link text.
}

How to extract extension from filename string in Javascript?

I would recommend using lastIndexOf() as opposed to indexOf()

var myString = "this.is.my.file.txt"
alert(myString.substring(myString.lastIndexOf(".")+1))

import dat file into R

The dat file has some lines of extra information before the actual data. Skip them with the skip argument:

read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat", 
           header=TRUE, skip=3)

An easy way to check this if you are unfamiliar with the dataset is to first use readLines to check a few lines, as below:

readLines("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat", 
          n=10)
# [1] "Ozone data from CZ03 2009"   "Local time: GMT + 0"        
# [3] ""                            "Date        Hour      Value"
# [5] "01.01.2009 00:00       34.3" "01.01.2009 01:00       31.9"
# [7] "01.01.2009 02:00       29.9" "01.01.2009 03:00       28.5"
# [9] "01.01.2009 04:00       32.9" "01.01.2009 05:00       20.5"

Here, we can see that the actual data starts at [4], so we know to skip the first three lines.

Update

If you really only wanted the Value column, you could do that by:

as.vector(
    read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
               header=TRUE, skip=3)$Value)

Again, readLines is useful for helping us figure out the actual name of the columns we will be importing.

But I don't see much advantage to doing that over reading the whole dataset in and extracting later.

Escape double quotes in parameter

I'm calling powershell from cmd, and passing quotes and neither escapes here worked. The grave accent worked to escape double quotes on this Win 10 surface pro.

>powershell.exe "echo la`"" >> test
>type test
la"

Below are outputs I got for other characters to escape a double quote:

la\
la^
la
la~

Using another quote to escape a quote resulted in no quotes. As you can see, the characters themselves got typed, but didn't escape the double quotes.

How to decrypt the password generated by wordpress

This is one of the proposed solutions found in the article Jacob mentioned, and it worked great as a manual way to change the password without having to use the email reset.

  1. In the DB table wp_users, add a key, like abc123 to the user_activation column.
  2. Visit yoursite.com/wp-login.php?action=rp&key=abc123&login=yourusername
  3. You will be prompted to enter a new password.

Ubuntu, how do you remove all Python 3 but not 2

First of all, don't try the following command as suggested by Germain above.

   `sudo apt-get remove 'python3.*'`

In Ubuntu, many software depends upon Python3 so if you will execute this command it will remove all of them as it happened with me. I found following answer useful to recover it.

https://askubuntu.com/questions/810854/i-deleted-package-python3-on-ubuntu-and-i-have-lost-dashboard-terminal-and-un

If you want to use different python versions for different projects then create virtual environments it will be very useful. refer to the following link to create virtual environments.

Creating Virtual Environment also helps in using Tensorflow and Keras in Jupyter Notebook.

https://linoxide.com/linux-how-to/setup-python-virtual-environment-ubuntu/

Filtering a pyspark dataframe using isin by exclusion

It looks like the ~ gives the functionality that I need, but I am yet to find any appropriate documentation on it.

df.filter(~col('bar').isin(['a','b'])).show()



+---+---+
| id|bar|
+---+---+
|  4|  c|
|  5|  d|
+---+---+

How do you clear your Visual Studio cache on Windows Vista?

I had the same issue but when i deleted the cached items from Temp folder the build failed.

In order to make the build work again I had to close the project and reopen it.

Plotting a python dict in order of key values

Simply pass the sorted items from the dictionary to the plot() function. concentration.items() returns a list of tuples where each tuple contains a key from the dictionary and its corresponding value.

You can take advantage of list unpacking (with *) to pass the sorted data directly to zip, and then again to pass it into plot():

import matplotlib.pyplot as plt

concentration = {
    0: 0.19849878712984576,
    5000: 0.093917341754771386,
    10000: 0.075060643507712022,
    20000: 0.06673074282575861,
    30000: 0.057119318961966224,
    50000: 0.046134834546203485,
    100000: 0.032495766396631424,
    200000: 0.018536317451599615,
    500000: 0.0059499290585381479}

plt.plot(*zip(*sorted(concentration.items())))
plt.show()

sorted() sorts tuples in the order of the tuple's items so you don't need to specify a key function because the tuples returned by dict.item() already begin with the key value.

How to enable Auto Logon User Authentication for Google Chrome

Chrome did change their menus since this question was asked. This solution was tested with Chrome 47.0.2526.73 to 72.0.3626.109.

If you are using Chrome right now, you can check your version with : chrome://version

  1. Goto: chrome://settings

  1. Scroll down to the bottom of the page and click on "Advanced" to show more settings.

OLDER VERSIONS:

Scroll down to the bottom of the page and click on "Show advanced settings..." to show more settings.

  1. In the "System" section, click on "Open proxy settings".

OLDER VERSIONS:

In the "Network" section, click on "Change proxy settings...".

  1. Click on the "Security" tab, then select "Local intranet" icon and click on "Sites" button.

  1. Click on "Advanced" button.

  1. Insert your intranet local address and click on the "Add" button.

  1. Close all windows.

That's it.

C# Get a control's position on a form

In my testing, both Hans Kesting's and Fredrik Mörk's solutions gave the same answer. But:

I found an interesting discrepancy in the answer using the methods of Raj More and Hans Kesting, and thought I'd share. Thanks to both though for their help; I can't believe such a method is not built into the framework.

Please note that Raj didn't write code and therefore my implementation could be different than he meant.

The difference I found was that the method from Raj More would often be two pixels greater (in both X and Y) than the method from Hans Kesting. I have not yet determined why this occurs. I'm pretty sure it has something to do with the fact that there seems to be a two-pixel border around the contents of a Windows form (as in, inside the form's outermost borders). In my testing, which was certainly not exhaustive to any extent, I've only come across it on controls that were nested. However, not all nested controls exhibit it. For example, I have a TextBox inside a GroupBox which exhibits the discrepancy, but a Button inside the same GroupBox does not. I cannot explain why.

Note that when the answers are equivalent, they consider the point (0, 0) to be inside the content border I mentioned above. Therefore I believe I'll consider the solutions from Hans Kesting and Fredrik Mörk to be correct but don't think I'll trust the solution I've implemented of Raj More's.

I also wondered exactly what code Raj More would have written, since he gave an idea but didn't provide code. I didn't fully understand the PointToScreen() method until I read this post: http://social.msdn.microsoft.com/Forums/en-US/netfxcompact/thread/aa91d4d8-e106-48d1-8e8a-59579e14f495

Here's my method for testing. Note that 'Method 1' mentioned in the comments is slightly different than Hans Kesting's.

private Point GetLocationRelativeToForm(Control c)
{
  // Method 1: walk up the control tree
  Point controlLocationRelativeToForm1 = new Point();
  Control currentControl = c;
  while (currentControl.Parent != null)
  {
    controlLocationRelativeToForm1.Offset(currentControl.Left, currentControl.Top);
    currentControl = currentControl.Parent;
  }

  // Method 2: determine absolute position on screen of control and form, and calculate difference
  Point controlScreenPoint = c.PointToScreen(Point.Empty);
  Point formScreenPoint = PointToScreen(Point.Empty);
  Point controlLocationRelativeToForm2 = controlScreenPoint - new Size(formScreenPoint);

  // Method 3: combine PointToScreen() and PointToClient()
  Point locationOnForm = c.FindForm().PointToClient(c.Parent.PointToScreen(c.Location));

  // Theoretically they should be the same
  Debug.Assert(controlLocationRelativeToForm1 == controlLocationRelativeToForm2);
  Debug.Assert(locationOnForm == controlLocationRelativeToForm1);
  Debug.Assert(locationOnForm == controlLocationRelativeToForm2);

  return controlLocationRelativeToForm1;
}

why is plotting with Matplotlib so slow?

To start, Joe Kington's answer provides very good advice using a gui-neutral approach, and you should definitely take his advice (especially about Blitting) and put it into practice. More info on this approach, read the Matplotlib Cookbook

However, the non-GUI-neutral (GUI-biased?) approach is key to speeding up the plotting. In other words, the backend is extremely important to plot speed.

Put these two lines before you import anything else from matplotlib:

import matplotlib
matplotlib.use('GTKAgg') 

Of course, there are various options to use instead of GTKAgg, but according to the cookbook mentioned before, this was the fastest. See the link about backends for more options.

What are the differences between C, C# and C++ in terms of real-world applications?

For raw speed, use C. For power, use C++. For .NET compatibility, use C#.

They're all pretty complex as languages go; C through decades of gradual accretion, C++ through years of more rapid enhancement, and C# through the power of Microsoft.

How to install Android Studio on Ubuntu?

To install android studio on ubuntu here is the simplest way possible:

First of all, you have to install Ubuntu Make before installing Android Studio. Type following commands in the same order one by one on terminal:

1) sudo add-apt-repository ppa:ubuntu-desktop/ubuntu-make

2) sudo apt-get update

3) sudo apt-get install ubuntu-make

Now since you are done with Ubuntu make, use below command to install Android Studio:

4) umake android

While installation it will give you a couple of option which you can handle. So, Installation is done. You can open it and run an App of your choice. Isn’t it very easy? Let me know if you go through any problem, I can help.

Source Install Android Studio

PHP max_input_vars

Have just attempted this fix with 5.3.3 and there's no change. Googling around I found this web page http://anothersysadmin.wordpress.com/2012/02/16/php-5-3-max_input_vars-and-big-forms/ detailing other settings which need changing if your server uses the Suhosin patch which Apache under Debian does.

The site explains:

So, if you want to increase this number to, say, 3000 from the default number which is 1000, you have to put in your php.ini these lines:

max_input_vars = 3000 suhosin.post.max_vars = 3000 suhosin.request.max_vars = 3000

I tested it (added settings to php.ini both in /etc/php5/apache2 and /etc/php5/cli, and restarted Apache successfully) but still no max_input_vars variable in phpinfo.

A few sites point to PHP 5.3.9 as the first PHP version in which this change will take, so my fault for not RTM properly in the first place, although I'm interested to see people reporting it working in version above 5.3.3 but below 5.3.9.

Unable to load AWS credentials from the /AwsCredentials.properties file on the classpath

Example java code:

        //DATA//
        //get from: https://console.aws.amazon.com/iam/home?#/security_credentials -> Access keys (access key ID and secret access key) -> Generate key if not exists
        String accessKey;
        String secretKey;
        Regions region = Regions.AP_SOUTH_1; //get from "https://ap-south-1.console.aws.amazon.com/lambda/" > your function > ARN at top right
        
        //CODE//
        AWSLambda awsLambda = AWSLambdaClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey)))
                .withRegion(region)
                .build();

        List<FunctionConfiguration> functionList= awsLambda.listFunctions().getFunctions();
        for (FunctionConfiguration functConfig : functionList) {
           System.out.println("FunctionName="+functConfig.getFunctionName());
        }

pandas DataFrame: replace nan values with average of columns

# To read data from csv file
Dataset = pd.read_csv('Data.csv')

X = Dataset.iloc[:, :-1].values

# To calculate mean use imputer class
from sklearn.impute import SimpleImputer
imputer = SimpleImputer(missing_values=np.nan, strategy='mean')
imputer = imputer.fit(X[:, 1:3])
X[:, 1:3] = imputer.transform(X[:, 1:3])

Quickly create a large file on a Linux system

One approach: if you can guarantee unrelated applications won't use the files in a conflicting manner, just create a pool of files of varying sizes in a specific directory, then create links to them when needed.

For example, have a pool of files called:

  • /home/bigfiles/512M-A
  • /home/bigfiles/512M-B
  • /home/bigfiles/1024M-A
  • /home/bigfiles/1024M-B

Then, if you have an application that needs a 1G file called /home/oracle/logfile, execute a "ln /home/bigfiles/1024M-A /home/oracle/logfile".

If it's on a separate filesystem, you will have to use a symbolic link.

The A/B/etc files can be used to ensure there's no conflicting use between unrelated applications.

The link operation is about as fast as you can get.

Using G++ to compile multiple .cpp and .h files

If you want to use #include <myheader.hpp> inside your cpp files you can use:

g++ *.cpp -I. -o out

What’s the best RESTful method to return total number of items in an object?

I would recommend adding headers for the same, like:

HTTP/1.1 200

Pagination-Count: 100
Pagination-Page: 5
Pagination-Limit: 20
Content-Type: application/json

[
  {
    "id": 10,
    "name": "shirt",
    "color": "red",
    "price": "$23"
  },
  {
    "id": 11,
    "name": "shirt",
    "color": "blue",
    "price": "$25"
  }
]

For details refer to:

https://github.com/adnan-kamili/rest-api-response-format

For swagger file:

https://github.com/adnan-kamili/swagger-response-template

How to append elements at the end of ArrayList in Java?

I ran into a similar problem and just passed the end of the array to the ArrayList.add() index param like so:

public class Stack {

    private ArrayList<String> stringList = new ArrayList<String>();

    RandomStringGenerator rsg = new RandomStringGenerator();

    private void push(){
        String random = rsg.randomStringGenerator();
        stringList.add(stringList.size(), random);
    }

}

How to solve : SQL Error: ORA-00604: error occurred at recursive SQL level 1

I noticed following line from error.

exact fetch returns more than requested number of rows

That means Oracle was expecting one row but It was getting multiple rows. And, only dual table has that characteristic, which returns only one row.

Later I recall, I have done few changes in dual table and when I executed dual table. Then found multiple rows.

So, I truncated dual table and inserted only row which X value. And, everything working fine.

TypeError: Cannot read property 'then' of undefined

TypeError: Cannot read property 'then' of undefined when calling a Django service using AngularJS.

If you are calling a Python service, the code will look like below:

this.updateTalentSupplier=function(supplierObj){
  var promise = $http({
    method: 'POST',
      url: bbConfig.BWS+'updateTalentSupplier/',
      data:supplierObj,
      withCredentials: false,
      contentType:'application/json',
      dataType:'json'
    });
    return promise; //Promise is returned 
}

We are using MongoDB as the database(I know it doesn't matter. But if someone is searching with MongoDB + Python (Django) + AngularJS the result should come.

Recyclerview inside ScrollView not scrolling smoothly

Kotlin

Set isNestedScrollingEnabled to false for every RecyclerView that is under the scrolling view

val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
recyclerView.isNestedScrollingEnabled = false

Using XML Layout

<android.support.v7.widget.RecyclerView
    android:layout_marginTop="10dp"
    android:layout_marginBottom="10dp"
    android:id="@+id/friendsList"
    android:layout_width="match_parent"
    android:nestedScrollingEnabled="false"
    android:layout_height="wrap_content" />

How to execute raw queries with Laravel 5.1?

you can run raw query like this way too.

DB::table('setting_colleges')->first();

Visual Studio: How to break on handled exceptions?

A technique I use is something like the following. Define a global variable that you can use for one or multiple try catch blocks depending on what you're trying to debug and use the following structure:

if(!GlobalTestingBool)
{
   try
   {
      SomeErrorProneMethod();
   }
   catch (...)
   {
      // ... Error handling ...
   }
}
else
{
   SomeErrorProneMethod();
}

I find this gives me a bit more flexibility in terms of testing because there are still some exceptions I don't want the IDE to break on.

jQuery get specific option tag text

It's looking for an element with id list which has a property value equal to 2.
What you want is the option child of the list:

$("#list option[value='2']").text()

What does the variable $this mean in PHP?

This is long detailed explanation. I hope this will help the beginners. I will make it very simple.

First, let's create a class

<?php 

class Class1
{
    
}

You can omit the php closing tag ?> if you are using php code only.

Now let's add properties and a method inside Class1.

<?php 

class Class1
{
    public $property1 = "I am property 1";
    public $property2 = "I am property 2";

    public function Method1()
    {
        return "I am Method 1";
    }
}

The property is just a simple variable , but we give it the name property cuz its inside a class.

The method is just a simple function , but we say method cuz its also inside a class.

The public keyword mean that the method or a property can be accessed anywhere in the script.

Now, how we can use the properties and the method inside Class1 ?

The answer is creating an instance or an object, think of an object as a copy of the class.

<?php 

class Class1
{
    public $property1 = "I am property 1";
    public $property2 = "I am property 2";

    public function Method1()
    {
        return "I am Method 1";
    }
}

$object1 = new Class1;
var_dump($object1);

We created an object, which is $object1 , which is a copy of Class1 with all its contents. And we dumped all the contents of $object1 using var_dump() .

This will give you

object(Class1)#1 (2) { ["property1"]=> string(15) "I am property 1" ["property2"]=> string(15) "I am property 2" }

So all the contents of Class1 are in $object1 , except Method1 , i don't know why methods doesn't show while dumping objects.

Now what if we want to access $property1 only. Its simple , we do var_dump($object1->property1); , we just added ->property1 , we pointed to it.

we can also access Method1() , we do var_dump($object1->Method1());.

Now suppose i want to access $property1 from inside Method1() , i will do this

<?php 

class Class1
{
    public $property1 = "I am property 1";
    public $property2 = "I am property 2";

    public function Method1()
    {   
        $object2 = new Class1;
        return $object2->property1;
    }
}

$object1 = new Class1;
var_dump($object1->Method1()); 

we created $object2 = new Class1; which is a new copy of Class1 or we can say an instance. Then we pointed to property1 from $object2

return $object2->property1;

This will print string(15) "I am property 1" in the browser.

Now instead of doing this inside Method1()

$object2 = new Class1;
return $object2->property1;

We do this

return $this->property1;

The $this object is used inside the class to refer to the class itself.

It is an alternative for creating new object and then returning it like this

$object2 = new Class1;
return $object2->property1;

Another example

<?php 

class Class1
{
    public $property1 = 119;
    public $property2 = 666;
    public $result;

    public function Method1()
    {   
        $this->result = $this->property1 + $this->property2;
        return $this->result;
    }
}

$object1 = new Class1;
var_dump($object1->Method1());

We created 2 properties containing integers and then we added them and put the result in $this->result.

Do not forget that

$this->property1 = $property1 = 119

they have that same value .. etc

I hope that explains the idea.

This series of videos will help you a lot in OOP

https://www.youtube.com/playlist?list=PLe30vg_FG4OSEHH6bRF8FrA7wmoAMUZLv

C# Convert string from UTF-8 to ISO-8859-1 (Latin1) H

Try this:

Encoding iso = Encoding.GetEncoding("ISO-8859-1");
Encoding utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(Message);
byte[] isoBytes = Encoding.Convert(utf8,iso,utfBytes);
string msg = iso.GetString(isoBytes);

Generating all permutations of a given string

Well here is an elegant, non-recursive, O(n!) solution:

public static StringBuilder[] permutations(String s) {
        if (s.length() == 0)
            return null;
        int length = fact(s.length());
        StringBuilder[] sb = new StringBuilder[length];
        for (int i = 0; i < length; i++) {
            sb[i] = new StringBuilder();
        }
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            int times = length / (i + 1);
            for (int j = 0; j < times; j++) {
                for (int k = 0; k < length / times; k++) {
                    sb[j * length / times + k].insert(k, ch);
                }
            }
        }
        return sb;
    }

Link entire table row?

Also it depends if you need to use a table element or not. You can imitate a table using CSS and make an A element the row

<div class="table" style="width:100%;">
  <a href="#" class="tr">
    <span class="td">
      cell 1
    </span>
    <span class="td">
      cell 2
    </span>
  </a>
</div>

css:

.table{display:table;}
.tr{display:table-row;}
.td{display:table-cell;}
.tr:hover{background-color:#ccc;}

How to sort by column in descending order in Spark SQL?

You can also sort the column by importing the spark sql functions

import org.apache.spark.sql.functions._
df.orderBy(asc("col1"))

Or

import org.apache.spark.sql.functions._
df.sort(desc("col1"))

importing sqlContext.implicits._

import sqlContext.implicits._
df.orderBy($"col1".desc)

Or

import sqlContext.implicits._
df.sort($"col1".desc)

PHP session lost after redirect

Now that GDPR is a thing, people visiting this question probably use a cookie script. Well, that script caused the problem for me. Apparently, PHP uses a cookie called PHPSESSID to track the session. If that script deletes it, you lose your data.

I used this cookie script. It has an option to enable "essential" cookies. I added PHPSESSID to the list, the script stopped deleting the cookie, and everything started to work again.

You could probably enable some PHP setting to avoid using PHPSESSID, but if your cookie script is the cause of the problem, why not fix that.

how to set width for PdfPCell in ItextSharp

aca definis los anchos

 float[] anchoDeColumnas= new float[] {10f, 20f, 30f, 10f};

aca se los insertas a la tabla que tiene las columnas

table.setWidths(anchoDeColumnas);

Disable all Database related auto configuration in Spring Boot

Also if you use Spring Actuator org.springframework.boot.actuate.autoconfigure.jdbc.DataSourceHealthContributorAutoConfiguration might be initializing DataSource as well.

How can I refresh or reload the JFrame?

just use frame.setVisible(false); frame.setVisible(true); I've had this problem with JLabels with images, and this solved it

Java JDBC - How to connect to Oracle using Service Name instead of SID

http://download.oracle.com/docs/cd/B28359_01/java.111/b31224/urls.htm#BEIDHCBA

Thin-style Service Name Syntax

Thin-style service names are supported only by the JDBC Thin driver. The syntax is:

@//host_name:port_number/service_name

For example:

jdbc:oracle:thin:scott/tiger@//myhost:1521/myservicename

So I would try:

jdbc:oracle:thin:@//oracle.hostserver2.mydomain.ca:1522/ABCD

Also, per Robert Greathouse's answer, you can also specify the TNS name in the JDBC URL as below:

jdbc:oracle:thin:@(DESCRIPTION =(ADDRESS_LIST =(ADDRESS =(PROTOCOL=TCP)(HOST=blah.example.com)(PORT=1521)))(CONNECT_DATA=(SID=BLAHSID)(GLOBAL_NAME=BLAHSID.WORLD)(SERVER=DEDICATED)))

Python Pandas replicate rows in dataframe

This is an old question, but since it still comes up at the top of my results in Google, here's another way.

import pandas as pd
import numpy as np

df = pd.DataFrame({'col1':list("abc"),'col2':range(3)},index = range(3))

Say you want to replicate the rows where col1="b".

reps = [3 if val=="b" else 1 for val in df.col1]
df.loc[np.repeat(df.index.values, reps)]

You could replace the 3 if val=="b" else 1 in the list interpretation with another function that could return 3 if val=="b" or 4 if val=="c" and so on, so it's pretty flexible.

A server is already running. Check …/tmp/pids/server.pid. Exiting - rails

Simple:

go in the root folder of the project when this happens and run:

gem install shutup
shutup

This will find the process currently running, kill it and clean up the pid file

NOTE: if you are using rvm install the gem globally

rvm @global do gem install shutup

How to skip to next iteration in jQuery.each() util?

Javascript sort of has the idea of 'truthiness' and 'falsiness'. If a variable has a value then, generally 9as you will see) it has 'truthiness' - null, or no value tends to 'falsiness'. The snippets below might help:

var temp1; 
if ( temp1 )...  // false

var temp2 = true;
if ( temp2 )...  // true

var temp3 = "";
if ( temp3 ).... // false

var temp4 = "hello world";
if ( temp4 )...  // true

Hopefully that helps?

Also, its worth checking out these videos from Douglas Crockford

update: thanks @cphpython for spotting the broken links - I've updated to point at working versions now

The Javascript language

Javascript - The Good Parts

How are iloc and loc different?

iloc works based on integer positioning. So no matter what your row labels are, you can always, e.g., get the first row by doing

df.iloc[0]

or the last five rows by doing

df.iloc[-5:]

You can also use it on the columns. This retrieves the 3rd column:

df.iloc[:, 2]    # the : in the first position indicates all rows

You can combine them to get intersections of rows and columns:

df.iloc[:3, :3] # The upper-left 3 X 3 entries (assuming df has 3+ rows and columns)

On the other hand, .loc use named indices. Let's set up a data frame with strings as row and column labels:

df = pd.DataFrame(index=['a', 'b', 'c'], columns=['time', 'date', 'name'])

Then we can get the first row by

df.loc['a']     # equivalent to df.iloc[0]

and the second two rows of the 'date' column by

df.loc['b':, 'date']   # equivalent to df.iloc[1:, 1]

and so on. Now, it's probably worth pointing out that the default row and column indices for a DataFrame are integers from 0 and in this case iloc and loc would work in the same way. This is why your three examples are equivalent. If you had a non-numeric index such as strings or datetimes, df.loc[:5] would raise an error.

Also, you can do column retrieval just by using the data frame's __getitem__:

df['time']    # equivalent to df.loc[:, 'time']

Now suppose you want to mix position and named indexing, that is, indexing using names on rows and positions on columns (to clarify, I mean select from our data frame, rather than creating a data frame with strings in the row index and integers in the column index). This is where .ix comes in:

df.ix[:2, 'time']    # the first two rows of the 'time' column

I think it's also worth mentioning that you can pass boolean vectors to the loc method as well. For example:

 b = [True, False, True]
 df.loc[b] 

Will return the 1st and 3rd rows of df. This is equivalent to df[b] for selection, but it can also be used for assigning via boolean vectors:

df.loc[b, 'name'] = 'Mary', 'John'

Best practice to validate null and empty collection in Java

If you need to check for null, that is the way. However, if you have control on this, just return empty collection, whenever you can, and check only for empty later on.

This thread is about the same thing with C#, but the principles applies equally well to java. Like mentioned there, null should be returned only if

  • null might mean something more specific;
  • your API (contract) might force you to return null.

PermGen elimination in JDK 8

Because the PermGen space was removed. Memory management has changed a bit.

java-8-permgen-metaspace

How to remove trailing whitespaces with sed?

Thanks to codaddict for suggesting the -i option.

The following command solves the problem on Snow Leopard

sed -i '' -e's/[ \t]*$//' "$1"

How does numpy.histogram() work?

A bin is range that represents the width of a single bar of the histogram along the X-axis. You could also call this the interval. (Wikipedia defines them more formally as "disjoint categories".)

The Numpy histogram function doesn't draw the histogram, but it computes the occurrences of input data that fall within each bin, which in turns determines the area (not necessarily the height if the bins aren't of equal width) of each bar.

In this example:

 np.histogram([1, 2, 1], bins=[0, 1, 2, 3])

There are 3 bins, for values ranging from 0 to 1 (excl 1.), 1 to 2 (excl. 2) and 2 to 3 (incl. 3), respectively. The way Numpy defines these bins if by giving a list of delimiters ([0, 1, 2, 3]) in this example, although it also returns the bins in the results, since it can choose them automatically from the input, if none are specified. If bins=5, for example, it will use 5 bins of equal width spread between the minimum input value and the maximum input value.

The input values are 1, 2 and 1. Therefore, bin "1 to 2" contains two occurrences (the two 1 values), and bin "2 to 3" contains one occurrence (the 2). These results are in the first item in the returned tuple: array([0, 2, 1]).

Since the bins here are of equal width, you can use the number of occurrences for the height of each bar. When drawn, you would have:

  • a bar of height 0 for range/bin [0,1] on the X-axis,
  • a bar of height 2 for range/bin [1,2],
  • a bar of height 1 for range/bin [2,3].

You can plot this directly with Matplotlib (its hist function also returns the bins and the values):

>>> import matplotlib.pyplot as plt
>>> plt.hist([1, 2, 1], bins=[0, 1, 2, 3])
(array([0, 2, 1]), array([0, 1, 2, 3]), <a list of 3 Patch objects>)
>>> plt.show()

enter image description here

Reload the page after ajax success

use this Reload page

success: function(data){
   if(data.success == true){ // if true (1)
      setTimeout(function(){// wait for 5 secs(2)
           location.reload(); // then reload the page.(3)
      }, 5000); 
   }
}

Android: Align button to bottom-right of screen using FrameLayout?

There are many methods to do this using constraint widget of the activity.xml page of android studio.

Two most common methods are:

  1. Select your button view and adjust it's margins.
  2. Go to "All attributes",then to "layout_constraints",then select
    • layout_constraintBottom_toBottomOf_parent
    • layout_constraintRight_toRightOf_parent

How to inspect Javascript Objects

Use console.dir(object) and the Firebug plugin

Pretty git branch graphs

git-forest is an excellent perl script I've been using for more than a year and I hardly use the git log command directly any more.

These are some of the things I love about this script:

  • It uses unicode characters to draw the lines in the graph giving a more continuous look to the graph lines.
  • You can combine --reverse with the graph output, which is not possible with the regular git log command.
  • It uses git log internally to grab the list of commits, so all options that you pass to git log can also be passed to this script as well.

I have an alias using git-forest as follows:

[alias]
tree = "forest --pretty=format:\"%C(red)%h %C(magenta)(%ar) %C(blue)%an %C(reset)%s\" --style=15 --reverse"

This is how the output looks like on a terminal:

enter image description here

What's the CMake syntax to set and use variables?

$ENV{FOO} for usage, where FOO is being picked up from the environment variable. otherwise use as ${FOO}, where FOO is some other variable. For setting, SET(FOO "foo") would be used in CMake.

Convert object of any type to JObject with Json.NET

JObject implements IDictionary, so you can use it that way. For ex,

var cycleJson  = JObject.Parse(@"{""name"":""john""}");

//add surname
cycleJson["surname"] = "doe";

//add a complex object
cycleJson["complexObj"] = JObject.FromObject(new { id = 1, name = "test" });

So the final json will be

{
  "name": "john",
  "surname": "doe",
  "complexObj": {
    "id": 1,
    "name": "test"
  }
}

You can also use dynamic keyword

dynamic cycleJson  = JObject.Parse(@"{""name"":""john""}");
cycleJson.surname = "doe";
cycleJson.complexObj = JObject.FromObject(new { id = 1, name = "test" });

How to search JSON data in MySQL?

If you have MySQL version >= 5.7, then you can try this:

SELECT JSON_EXTRACT(name, "$.id") AS name
FROM table
WHERE JSON_EXTRACT(name, "$.id") > 3

Output:

+-------------------------------+
| name                          | 
+-------------------------------+
| {"id": "4", "name": "Betty"}  | 
+-------------------------------+


Please check MySQL reference manual for more details:
https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html

phpmailer error "Could not instantiate mail function"

Your code looks good, did you forget to install PostFix on your server?

sudo apt-get install postfix

It worked for me ;)

Cheers

How to make Sonar ignore some classes for codeCoverage metric?

Accordingly to this document for SonarQube 7.1

sonar.exclusions - Comma-delimited list of file path patterns to be excluded from analysis sonar.coverage.exclusions - Comma-delimited list of file path patterns to be excluded from coverage calculations

This document gives some examples on how to create path patterns

# Exclude all classes ending by "Bean"
# Matches org/sonar.api/MyBean.java, org/sonar/util/MyOtherBean.java, org/sonar/util/MyDTO.java, etc.
sonar.exclusions=**/*Bean.java,**/*DTO.java

# Exclude all classes in the "src/main/java/org/sonar" directory
# Matches src/main/java/org/sonar/MyClass.java, src/main/java/org/sonar/MyOtherClass.java
# But does not match src/main/java/org/sonar/util/MyClassUtil.java
sonar.exclusions=src/main/java/org/sonar/*

# Exclude all COBOL programs in the "bank" directory and its sub-directories
# Matches bank/ZTR00021.cbl, bank/data/CBR00354.cbl, bank/data/REM012345.cob
sonar.exclusions=bank/**/*

# Exclude all COBOL programs in the "bank" directory and its sub-directories whose extension is .cbl
# Matches bank/ZTR00021.cbl, bank/data/CBR00354.cbl
sonar.exclusions=bank/**/*.cbl

If you are using Maven for your project, Maven command line parameters can be passed like this for example -Dsonar.coverage.exclusions=**/config/*,**/model/*

I was having problem with excluding single class explicitly. Below my observations:

**/*GlobalExceptionhandler.java - not working for some reason, I was expecting such syntax should work
com/some/package/name/GlobalExceptionhandler.java - not working
src/main/java/com/some/package/name/GlobalExceptionhandler.java - good, class excluded explicitly without using wildcards

Disable XML validation in Eclipse

Ensure your encoding is correct for all of your files, this can sometimes happen if you have the encoding wrong for your file or the wrong encoding in your XML header.

So, if I have the following NewFile.xml:

<?xml version="1.0" encoding="UTF-16"?>
<bar foo="foiré" />

And the eclipse encoding is UTF-8:

Eclipse Encoding Resource

The encoding of your file, the defined encoding in Eclipse (through Properties->Resource) and the declared encoding in the XML document all need to agree.

The validator is attempting to read the file, expecting <?xml ... but because the encoding is different from that expected, it's not finding it. Hence the error: Content is not allowed in prolog. The prolog is the bit before the <?xml declaration.

EDIT: Sorry, didn't realise that the .xml files were generated and actually contain javascript.

When you suspend the validators, the error messages that you've generated don't go away. To get them to go away, you have to manually delete them.

  1. Suspend the validators
  2. Click on the 'Content is not allowed in prolog' message, right click and delete. You can select multiple ones, or all of them.
  3. Do a Project->Clean. The messages should not come back.

I think that because you've suspended the validators, Eclipse doesn't realise it has to delete the old error messages which came from the validators.

Use .corr to get the correlation between two columns

changing 'Citable docs per Capita' to numeric before correlation will solve the problem.

    Top15['Citable docs per Capita'] = pd.to_numeric(Top15['Citable docs per Capita'])
    data = Top15[['Citable docs per Capita','Energy Supply per Capita']]
    correlation = data.corr(method='pearson')

What is trunk, branch and tag in Subversion?

A trunk is considered your main code base, a branch offshoot of the trunk. Like, you create a branch if you want to implement a new feature, but don't want to affect the main trunk.

TortoiseSVN has good documentation, and a great diff tool.

I use Visual studio, and I use VisualSVN and TortoiseSVN.

Insert a background image in CSS (Twitter Bootstrap)

If you add the following you can set the background colour or image (your css)

 html { 
     background-image: url('http://yoursite/i/tile.jpg');
     background-repeat: repeat; 
 }

 .body {
     background-color: transparent; 
 }

This is because BS applies a css rule for background colour and also for the .container class.

Questions every good PHP Developer should be able to answer

Terry Chay has a blog post basically summarizing what every PHP developer should know and/or be expected to answer to some degree in a job interview.

http://terrychay.com/article/php-coders.shtml

I think its a great summary.

How do I correct the character encoding of a file?

I found this question when searching for a solution to a code page issue i had with Chinese characters, but in the end my problem was just an issue with Windows not displaying them correctly in the UI.

In case anyone else has that same issue, you can fix it simply by changing the local in windows to China and then back again.

I found the solution here:

http://answers.microsoft.com/en-us/windows/forum/windows_7-desktop/how-can-i-get-chinesejapanese-characters-to/fdb1f1da-b868-40d1-a4a4-7acadff4aafa?page=2&auth=1

Also upvoted Gabriel's answer as looking at the data in notepad++ was what tipped me off about windows.

How to display PDF file in HTML?

I understand you want to display using HTMl but you can also open the PDF file using php by pointing out the path and the browser will render it in a few simple steps

<?php
$your_file_name = "url_here";

//Content type and this case its a PDF
header("Content-type: application/pdf");

header("Content-Length: " . filesize($your_file_name )); 

//Display the file
readfile($your_file_name );
?>

How to install PyQt4 in anaconda?

FYI

PyQt is now available on all platforms via conda!
Use conda install pyqt to get these #Python bindings for the Qt framework. @ 1:02 PM - 1 May 2014

https://twitter.com/ContinuumIO/status/461958764451880960

How to export and import environment variables in windows?

I would use the SET command from the command prompt to export all the variables, rather than just PATH as recommended above.

C:\> SET >> allvariables.txt

To import the variablies, one can use a simple loop:

C:\> for /F %A in (allvariables.txt) do SET %A

org.springframework.beans.factory.BeanCreationException: Error creating bean with name

you need to add jar file in your build path..

commons-dbcp-1.1-RC2.jar

or any version of that..!!!!

ADDED : also make sure you have commons-pool-1.1.jar too in your build path.

ADDED: sorry saw complete list of jar late... may be version clashes might be there.. better check out..!!! just an assumption.

RegEx for matching UK Postcodes

I recently posted an answer to this question on UK postcodes for the R language. I discovered that the UK Government's regex pattern is incorrect and fails to properly validate some postcodes. Unfortunately, many of the answers here are based on this incorrect pattern.

I'll outline some of these issues below and provide a revised regular expression that actually works.


Note

My answer (and regular expressions in general):

  • Only validates postcode formats.
  • Does not ensure that a postcode legitimately exists.
    • For this, use an appropriate API! See Ben's answer for more info.

If you don't care about the bad regex and just want to skip to the answer, scroll down to the Answer section.

The Bad Regex

The regular expressions in this section should not be used.

This is the failing regex that the UK government has provided developers (not sure how long this link will be up, but you can see it in their Bulk Data Transfer documentation):

^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))[0-9][A-Za-z]{2})$

Problems

Problem 1 - Copy/Paste

See regex in use here.

As many developers likely do, they copy/paste code (especially regular expressions) and paste them expecting them to work. While this is great in theory, it fails in this particular case because copy/pasting from this document actually changes one of the characters (a space) into a newline character as shown below:

^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))
[0-9][A-Za-z]{2})$

The first thing most developers will do is just erase the newline without thinking twice. Now the regex won't match postcodes with spaces in them (other than the GIR 0AA postcode).

To fix this issue, the newline character should be replaced with the space character:

^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$
                                                                                                                                                     ^

Problem 2 - Boundaries

See regex in use here.

^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$
^^                     ^ ^                                                                                                                                            ^^

The postcode regex improperly anchors the regex. Anyone using this regex to validate postcodes might be surprised if a value like fooA11 1AA gets through. That's because they've anchored the start of the first option and the end of the second option (independently of one another), as pointed out in the regex above.

What this means is that ^ (asserts position at start of the line) only works on the first option ([Gg][Ii][Rr] 0[Aa]{2}), so the second option will validate any strings that end in a postcode (regardless of what comes before).

Similarly, the first option isn't anchored to the end of the line $, so GIR 0AAfoo is also accepted.

^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))[0-9][A-Za-z]{2})$

To fix this issue, both options should be wrapped in another group (or non-capturing group) and the anchors placed around that:

^(([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2}))$
^^                                                                                                                                                                      ^^

Problem 3 - Improper Character Set

See regex in use here.

^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$
                                                                                       ^^

The regex is missing a - here to indicate a range of characters. As it stands, if a postcode is in the format ANA NAA (where A represents a letter and N represents a number), and it begins with anything other than A or Z, it will fail.

That means it will match A1A 1AA and Z1A 1AA, but not B1A 1AA.

To fix this issue, the character - should be placed between the A and Z in the respective character set:

^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$
                                                                                        ^

Problem 4 - Wrong Optional Character Set

See regex in use here.

^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$
                                                                                                                                        ^

I swear they didn't even test this thing before publicizing it on the web. They made the wrong character set optional. They made [0-9] option in the fourth sub-option of option 2 (group 9). This allows the regex to match incorrectly formatted postcodes like AAA 1AA.

To fix this issue, make the next character class optional instead (and subsequently make the set [0-9] match exactly once):

^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?)))) [0-9][A-Za-z]{2})$
                                                                                                                                                ^

Problem 5 - Performance

Performance on this regex is extremely poor. First off, they placed the least likely pattern option to match GIR 0AA at the beginning. How many users will likely have this postcode versus any other postcode; probably never? This means every time the regex is used, it must exhaust this option first before proceeding to the next option. To see how performance is impacted check the number of steps the original regex took (35) against the same regex after having flipped the options (22).

The second issue with performance is due to the way the entire regex is structured. There's no point backtracking over each option if one fails. The way the current regex is structured can greatly be simplified. I provide a fix for this in the Answer section.

Problem 6 - Spaces

See regex in use here

This may not be considered a problem, per se, but it does raise concern for most developers. The spaces in the regex are not optional, which means the users inputting their postcodes must place a space in the postcode. This is an easy fix by simply adding ? after the spaces to render them optional. See the Answer section for a fix.


Answer

1. Fixing the UK Government's Regex

Fixing all the issues outlined in the Problems section and simplifying the pattern yields the following, shorter, more concise pattern. We can also remove most of the groups since we're validating the postcode as a whole (not individual parts):

See regex in use here

^([A-Za-z][A-Ha-hJ-Yj-y]?[0-9][A-Za-z0-9]? ?[0-9][A-Za-z]{2}|[Gg][Ii][Rr] ?0[Aa]{2})$

This can further be shortened by removing all of the ranges from one of the cases (upper or lower case) and using a case-insensitive flag. Note: Some languages don't have one, so use the longer one above. Each language implements the case-insensitivity flag differently.

See regex in use here.

^([A-Z][A-HJ-Y]?[0-9][A-Z0-9]? ?[0-9][A-Z]{2}|GIR ?0A{2})$

Shorter again replacing [0-9] with \d (if your regex engine supports it):

See regex in use here.

^([A-Z][A-HJ-Y]?\d[A-Z\d]? ?\d[A-Z]{2}|GIR ?0A{2})$

2. Simplified Patterns

Without ensuring specific alphabetic characters, the following can be used (keep in mind the simplifications from 1. Fixing the UK Government's Regex have also been applied here):

See regex in use here.

^([A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}|GIR ?0A{2})$

And even further if you don't care about the special case GIR 0AA:

^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$

3. Complicated Patterns

I would not suggest over-verification of a postcode as new Areas, Districts and Sub-districts may appear at any point in time. What I will suggest potentially doing, is added support for edge-cases. Some special cases exist and are outlined in this Wikipedia article.

Here are complex regexes that include the subsections of 3. (3.1, 3.2, 3.3).

In relation to the patterns in 1. Fixing the UK Government's Regex:

See regex in use here

^(([A-Z][A-HJ-Y]?\d[A-Z\d]?|ASCN|STHL|TDCU|BBND|[BFS]IQQ|PCRN|TKCA) ?\d[A-Z]{2}|BFPO ?\d{1,4}|(KY\d|MSR|VG|AI)[ -]?\d{4}|[A-Z]{2} ?\d{2}|GE ?CX|GIR ?0A{2}|SAN ?TA1)$

And in relation to 2. Simplified Patterns:

See regex in use here

^(([A-Z]{1,2}\d[A-Z\d]?|ASCN|STHL|TDCU|BBND|[BFS]IQQ|PCRN|TKCA) ?\d[A-Z]{2}|BFPO ?\d{1,4}|(KY\d|MSR|VG|AI)[ -]?\d{4}|[A-Z]{2} ?\d{2}|GE ?CX|GIR ?0A{2}|SAN ?TA1)$

3.1 British Overseas Territories

The Wikipedia article currently states (some formats slightly simplified):

  • AI-1111: Anguila
  • ASCN 1ZZ: Ascension Island
  • STHL 1ZZ: Saint Helena
  • TDCU 1ZZ: Tristan da Cunha
  • BBND 1ZZ: British Indian Ocean Territory
  • BIQQ 1ZZ: British Antarctic Territory
  • FIQQ 1ZZ: Falkland Islands
  • GX11 1ZZ: Gibraltar
  • PCRN 1ZZ: Pitcairn Islands
  • SIQQ 1ZZ: South Georgia and the South Sandwich Islands
  • TKCA 1ZZ: Turks and Caicos Islands
  • BFPO 11: Akrotiri and Dhekelia
  • ZZ 11 & GE CX: Bermuda (according to this document)
  • KY1-1111: Cayman Islands (according to this document)
  • VG1111: British Virgin Islands (according to this document)
  • MSR 1111: Montserrat (according to this document)

An all-encompassing regex to match only the British Overseas Territories might look like this:

See regex in use here.

^((ASCN|STHL|TDCU|BBND|[BFS]IQQ|GX\d{2}|PCRN|TKCA) ?\d[A-Z]{2}|(KY\d|MSR|VG|AI)[ -]?\d{4}|(BFPO|[A-Z]{2}) ?\d{2}|GE ?CX)$

3.2 British Forces Post Office

Although they've been recently changed it to better align with the British postcode system to BF# (where # represents a number), they're considered optional alternative postcodes. These postcodes follow(ed) the format of BFPO, followed by 1-4 digits:

See regex in use here

^BFPO ?\d{1,4}$

3.3 Santa?

There's another special case with Santa (as mentioned in other answers): SAN TA1 is a valid postcode. A regex for this is very simply:

^SAN ?TA1$

Android Crop Center of Bitmap

Here a more complete snippet that crops out the center of an [bitmap] of arbitrary dimensions and scales the result to your desired [IMAGE_SIZE]. So you will always get a [croppedBitmap] scaled square of the image center with a fixed size. ideal for thumbnailing and such.

Its a more complete combination of the other solutions.

final int IMAGE_SIZE = 255;
boolean landscape = bitmap.getWidth() > bitmap.getHeight();

float scale_factor;
if (landscape) scale_factor = (float)IMAGE_SIZE / bitmap.getHeight();
else scale_factor = (float)IMAGE_SIZE / bitmap.getWidth();
Matrix matrix = new Matrix();
matrix.postScale(scale_factor, scale_factor);

Bitmap croppedBitmap;
if (landscape){
    int start = (tempBitmap.getWidth() - tempBitmap.getHeight()) / 2;
    croppedBitmap = Bitmap.createBitmap(tempBitmap, start, 0, tempBitmap.getHeight(), tempBitmap.getHeight(), matrix, true);
} else {
    int start = (tempBitmap.getHeight() - tempBitmap.getWidth()) / 2;
    croppedBitmap = Bitmap.createBitmap(tempBitmap, 0, start, tempBitmap.getWidth(), tempBitmap.getWidth(), matrix, true);
}

Disabling of EditText in Android

There are multiple was how to achieve multiple levels of disabled.

  • editText.setShowSoftInputOnFocus(false); and editText.setFocusable

prevents the EditText from showing keyboard - writing in some text. But cursor is still visible and user can paste in some text.

  • editText.setCursorVisible(false)

hides the cursor. Not sure why would you want to do that tho. User can input text & paste.

  • editText.setKeyListener(null)

I find this way most convenient. There is no way how user can input text, but widget still works with OnClickListener if you want to trigger action when user touches it

  • editText.setEnabled(false);

completely disables EditText. It is literally 'read-only', user cannot input any text in it and (for example) OnClickListener doesn't work with it.

TextEdit documentation

How can I force division to be floating point? Division keeps rounding down to 0?

You can cast to float by doing c = a / float(b). If the numerator or denominator is a float, then the result will be also.


A caveat: as commenters have pointed out, this won't work if b might be something other than an integer or floating-point number (or a string representing one). If you might be dealing with other types (such as complex numbers) you'll need to either check for those or use a different method.

Boolean checking in the 'if' condition

Former, of course. Latter is redundant, and only goes to show that you haven't understood the concept of booleans very well.

One more suggestion: Choose a different name for your boolean variable. As per this Java style guide:

is prefix should be used for boolean variables and methods.

isSet, isVisible, isFinished, isFound, isOpen

This is the naming convention for boolean methods and variables used by Sun for the Java core packages.

Using the is prefix solves a common problem of choosing bad boolean names like status or flag. isStatus or isFlag simply doesn't fit, and the programmer is forced to chose more meaningful names.

Setter methods for boolean variables must have set prefix as in:

void setFound(boolean isFound);

There are a few alternatives to the is prefix that fits better in some situations. These are has, can and should prefixes:

boolean hasLicense();
boolean canEvaluate();
boolean shouldAbort = false;

Concatenating elements in an array to a string

take a look at generic method to print all elements in an array

but in short, the Arrays.toString(arr) is just a easy way of printing the content of a primative array.

Are multiple `.gitignore`s frowned on?

You can have multiple .gitignore, each one of course in its own directory.
To check which gitignore rule is responsible for ignoring a file, use git check-ignore: git check-ignore -v -- afile.

And you can have different version of a .gitignore file per branch: I have already seen that kind of configuration for ensuring one branch ignores a file while the other branch does not: see this question for instance.

If your repo includes several independent projects, it would be best to reference them as submodules though.
That would be the actual best practices, allowing each of those projects to be cloned independently (with their respective .gitignore files), while being referenced by a specific revision in a global parent project.
See true nature of submodules for more.


Note that, since git 1.8.2 (March 2013) you can do a git check-ignore -v -- yourfile in order to see which gitignore run (from which .gitignore file) is applied to 'yourfile', and better understand why said file is ignored.
See "which gitignore rule is ignoring my file?"

Calculating frames per second in a game

There are at least two ways to do it:


The first is the one others have mentioned here before me. I think it's the simplest and preferred way. You just to keep track of

  • cn: counter of how many frames you've rendered
  • time_start: the time since you've started counting
  • time_now: the current time

Calculating the fps in this case is as simple as evaluating this formula:

  • FPS = cn / (time_now - time_start).

Then there is the uber cool way you might like to use some day:

Let's say you have 'i' frames to consider. I'll use this notation: f[0], f[1],..., f[i-1] to describe how long it took to render frame 0, frame 1, ..., frame (i-1) respectively.

Example where i = 3

|f[0]      |f[1]         |f[2]   |
+----------+-------------+-------+------> time

Then, mathematical definition of fps after i frames would be

(1) fps[i]   = i     / (f[0] + ... + f[i-1])

And the same formula but only considering i-1 frames.

(2) fps[i-1] = (i-1) / (f[0] + ... + f[i-2]) 

Now the trick here is to modify the right side of formula (1) in such a way that it will contain the right side of formula (2) and substitute it for it's left side.

Like so (you should see it more clearly if you write it on a paper):

fps[i] = i / (f[0] + ... + f[i-1])
       = i / ((f[0] + ... + f[i-2]) + f[i-1])
       = (i/(i-1)) / ((f[0] + ... + f[i-2])/(i-1) + f[i-1]/(i-1))
       = (i/(i-1)) / (1/fps[i-1] + f[i-1]/(i-1))
       = ...
       = (i*fps[i-1]) / (f[i-1] * fps[i-1] + i - 1)

So according to this formula (my math deriving skill are a bit rusty though), to calculate the new fps you need to know the fps from the previous frame, the duration it took to render the last frame and the number of frames you've rendered.

How to filter an array of objects based on values in an inner array with jq?

Here is another solution which uses any/2

map(select(any(.Names[]; contains("data"))|not)|.Id)[]

with the sample data and the -r option it produces

cb94e7a42732b598ad18a8f27454a886c1aa8bbba6167646d8f064cd86191e2b
a4b7e6f5752d8dcb906a5901f7ab82e403b9dff4eaaeebea767a04bac4aada19

generate random string for div id

2018 edit: I think this answer has some interesting info, but for any practical applications you should use Joe's answer instead.

A simple way to create a unique ID in JavaScript is to use the Date object:

var uniqid = Date.now();

That gives you the total milliseconds elapsed since January 1st 1970, which is a unique value every time you call that.

The problem with that value now is that you cannot use it as an element's ID, since in HTML, IDs need to start with an alphabetical character. There is also the problem that two users doing an action at the exact same time might result in the same ID. We could lessen the probability of that, and fix our alphabetical character problem, by appending a random letter before the numerical part of the ID.

var randLetter = String.fromCharCode(65 + Math.floor(Math.random() * 26));
var uniqid = randLetter + Date.now();

This still has a chance, however slim, of colliding though. Your best bet for a unique id is to keep a running count, increment it every time, and do all that in a single place, ie, on the server.

Run Executable from Powershell script with parameters

Try quoting the argument list:

Start-Process -FilePath "C:\Program Files\MSBuild\test.exe" -ArgumentList "/genmsi/f $MySourceDirectory\src\Deployment\Installations.xml"

You can also provide the argument list as an array (comma separated args) but using a string is usually easier.

Implement division with bit-wise operator

For integers:

public class Division {

    public static void main(String[] args) {
        System.out.println("Division: " + divide(100, 9));
    }

    public static int divide(int num, int divisor) {
        int sign = 1;
        if((num > 0 && divisor < 0) || (num < 0 && divisor > 0))
            sign = -1;

        return divide(Math.abs(num), Math.abs(divisor), Math.abs(divisor)) * sign;
    }

    public static int divide(int num, int divisor, int sum) {
        if (sum > num) {
            return 0;
        }

        return 1 + divide(num, divisor, sum + divisor);
    }
}

MySQL direct INSERT INTO with WHERE clause

The INSERT INTO Statement
The INSERT INTO statement is used to insert a new row in a table.
SQL INSERT INTO Syntax

It is possible to write the INSERT INTO statement in two forms.

The first form doesn't specify the column names where the data will be inserted, only their values:

INSERT INTO table_name
VALUES (value1, value2, value3,...)

The second form specifies both the column names and the values to be inserted:

INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

WooCommerce - get category for product page

<?php
   $terms = get_the_terms($product->ID, 'product_cat');
      foreach ($terms as $term) {

        $product_cat = $term->name;
           echo $product_cat;
             break;
  }
 ?>

Opacity of div's background without affecting contained element in IE 8?

opacity on parent element sets it for the whole sub DOM tree

You can't really set opacity for certain element that wouldn't cascade to descendants as well. That's not how CSS opacity works I'm afraid.

What you can do is to have two sibling elements in one container and set transparent one's positioning:

<div id="container">
    <div id="transparent"></div>
    <div id="content"></div>
</div>

then you have to set transparent position: absolute/relative so its content sibling will be rendered over it.

rgba can do background transparency of coloured backgrounds

rgba colour setting on element's background-color will of course work, but it will limit you to only use colour as background. No images I'm afraid. You can of course use CSS3 gradients though if you provide gradient stop colours in rgba. That works as well.

But be advised that rgba may not be supported by your required browsers.

Alert-free modal dialog functionality

But if you're after some kind of masking the whole page, this is usually done by adding a separate div with this set of styles:

position: fixed;
width: 100%;
height: 100%;
z-index: 1000; /* some high enough value so it will render on top */
opacity: .5;
filter: alpha(opacity=50);

Then when you display the content it should have a higher z-index. But these two elements are not related in terms of siblings or anything. They're just displayed as they should be. One over the other.

node.js - request - How to "emitter.setMaxListeners()"?

Try to use:

require('events').EventEmitter.defaultMaxListeners = Infinity; 

For loop for HTMLCollection elements

Alternative to Array.from is to use Array.prototype.forEach.call

forEach: Array.prototype.forEach.call(htmlCollection, i => { console.log(i) });

map: Array.prototype.map.call(htmlCollection, i => { console.log(i) });

ect...

jquery $(window).width() and $(window).height() return different values when viewport has not been resized

Note that if the problem is being caused by appearing scrollbars, putting

body {
  overflow: hidden;
}

in your CSS might be an easy fix (if you don't need the page to scroll).

Combine multiple results in a subquery into a single comma-separated value

Even this will serve the purpose

Sample data

declare @t table(id int, name varchar(20),somecolumn varchar(MAX))
insert into @t
    select 1,'ABC','X' union all
    select 1,'ABC','Y' union all
    select 1,'ABC','Z' union all
    select 2,'MNO','R' union all
    select 2,'MNO','S'

Query:

SELECT ID,Name,
    STUFF((SELECT ',' + CAST(T2.SomeColumn AS VARCHAR(MAX))
     FROM @T T2 WHERE T1.id = T2.id AND T1.name = T2.name
     FOR XML PATH('')),1,1,'') SOMECOLUMN
FROM @T T1
GROUP BY id,Name

Output:

ID  Name    SomeColumn
1   ABC     X,Y,Z
2   MNO     R,S

Get Date Object In UTC format in Java

final Date currentTime = new Date();
final SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy hh:mm:ss a z");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("UTC time: " + sdf.format(currentTime));

c++ Read from .csv file

You can follow this answer to see many different ways to process CSV in C++.

In your case, the last call to getline is actually putting the last field of the first line and then all of the remaining lines into the variable genero. This is because there is no space delimiter found up until the end of file. Try changing the space character into a newline instead:

    getline(file, genero, file.widen('\n'));

or more succinctly:

    getline(file, genero);

In addition, your check for file.good() is premature. The last newline in the file is still in the input stream until it gets discarded by the next getline() call for ID. It is at this point that the end of file is detected, so the check should be based on that. You can fix this by changing your while test to be based on the getline() call for ID itself (assuming each line is well formed).

while (getline(file, ID, ',')) {
    cout << "ID: " << ID << " " ; 

    getline(file, nome, ',') ;
    cout << "User: " << nome << " " ;

    getline(file, idade, ',') ;
    cout << "Idade: " << idade << " "  ; 

    getline(file, genero);
    cout << "Sexo: " <<  genero<< " "  ;
}

For better error checking, you should check the result of each call to getline().

SQL Server command line backup statement

Combine Remove Old Backup files with above script then this can perform backup by a scheduler, keep last 10 backup files

echo off
:: set folder to save backup files ex. BACKUPPATH=c:\backup
set BACKUPPATH=<<back up folder here>>

:: set Sql Server location ex. set SERVERNAME=localhost\SQLEXPRESS
set SERVERNAME=<<sql host here>>

:: set Database name to backup
set DATABASENAME=<<db name here>>

:: filename format Name-Date (eg MyDatabase-2009-5-19_1700.bak)
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)

set DATESTAMP=%mydate%_%mytime%
set BACKUPFILENAME=%BACKUPPATH%\%DATABASENAME%-%DATESTAMP%.bak
echo.

sqlcmd -E -S %SERVERNAME% -d master -Q "BACKUP DATABASE [%DATABASENAME%] TO DISK = N'%BACKUPFILENAME%' WITH INIT , NOUNLOAD , NAME = N'%DATABASENAME% backup', NOSKIP , STATS = 10, NOFORMAT"
echo.

:: In this case, we are choosing to keep the most recent 10 files
:: Also, the files we are looking for have a 'bak' extension
for /f "skip=10 delims=" %%F in ('dir %BACKUPPATH%\*.bak /s/b/o-d/a-d') do del "%%F"

Regex to match a 2-digit number (to validate Credit/Debit Card Issue number)

You can use the start (^) and end ($) of line indicators:

^[0-9]{2}$

Some language also have functions that allows you to match against an entire string, where-as you were using a find function. Matching against the entire string will make your regex work as an alternative to the above. The above regex will also work, but the ^ and $ will be redundant.

Send JSON data with jQuery

I wrote a short convenience function for posting JSON.

$.postJSON = function(url, data, success, args) {
  args = $.extend({
    url: url,
    type: 'POST',
    data: JSON.stringify(data),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    async: true,
    success: success
  }, args);
  return $.ajax(args);
};

$.postJSON('test/url', data, function(result) {
  console.log('result', result);
});

App can't be opened because it is from an unidentified developer

It's because of the Security options.

Go to System Preferences... > Security & Privacy and there should be a button saying Open Anyway, under the General tab.

You can avoid doing this by changing the options under Allow apps downloaded from:, however I would recommend keeping it at the default Mac App Store and identified developers.

Returning JSON response from Servlet to Javascript/JSP page

I think that what you want to do is turn the JSON string back into an object when it arrives back in your XMLHttpRequest - correct?

If so, you need to eval the string to turn it into a JavaScript object - note that this can be unsafe as you're trusting that the JSON string isn't malicious and therefore executing it. Preferably you could use jQuery's parseJSON

Oracle TNS names not showing when adding new connection to SQL Developer

Open SQL Developer. Go to Tools -> Preferences -> Databases -> Advanced Then explicitly set the Tnsnames Directory

My TNSNAMES was set up correctly and I could connect to Toad, SQL*Plus etc. but I needed to do this to get SQL Developer to work. Perhaps it was a Win 7 issue as it was a pain to install too.

Error: Java: invalid target release: 11 - IntelliJ IDEA

I added these two lines to build.gradle file

compileJava.options.fork = true
                                              
compileJava.options.forkOptions.executable = 'C:\\Program Files\\Java\\jdk-11.0.8'

and it works

I am using windows and my project based on gradle

my jdk path -> 'C:\Program Files\Java\jdk-11.0.8'

please provide your jdk path

Update an outdated branch against master in a Git repo

Update the master branch, which you need to do regardless.

Then, one of:

  1. Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.

  2. Merge your branch into master, and resolve the merge conflicts.

  3. Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.

None of these is better than the other, they just have different trade-off patterns.

I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.

To rebase and keep the branch you would:

git checkout <branch> && git rebase <target>

In your case, check out the old branch, then

git rebase master 

to get it rebuilt against master.

Python Dictionary contains List as Value - How to update?

>>> dictionary = {'C1' : [10,20,30],'C2' : [20,30,40]}
>>> dictionary['C1'] = [x+1 for x in dictionary['C1']]
>>> dictionary
{'C2': [20, 30, 40], 'C1': [11, 21, 31]}

Function to close the window in Tkinter

def exit(self):
    self.frame.destroy()
exit_btn=Button(self.frame,text='Exit',command=self.exit,activebackground='grey',activeforeground='#AB78F1',bg='#58F0AB',highlightcolor='red',padx='10px',pady='3px')
exit_btn.place(relx=0.45,rely=0.35)

This worked for me to destroy my Tkinter frame on clicking the exit button.

await is only valid in async function

If you are writing a Chrome Extension and you get this error for your code at root, you can fix it using the following "workaround":

async function run() {
    // Your async code here
    const beers = await fetch("https://api.punkapi.com/v2/beers");
}

run();

Basically you have to wrap your async code in an async function and then call the function without awaiting it.

Get index of clicked element in collection with jQuery

This will alert the index of the clicked selector (starting with 0 for the first):

$('selector').click(function(){
    alert( $('selector').index(this) );
});

Oracle PL/SQL string compare issue

Only change the line str1:=''; to str1:=' ';

Using multiple delimiters in awk

Perl one-liner:

perl -F'/[\/=]/' -lane 'print "$F[2]\t$F[4]\t$F[7]"' file

These command-line options are used:

  • -n loop around every line of the input file, put the line in the $_ variable, do not automatically print every line

  • -l removes newlines before processing, and adds them back in afterwards

  • -a autosplit mode – perl will automatically split input lines into the @F array. Defaults to splitting on whitespace

  • -F autosplit modifier, in this example splits on either / or =

  • -e execute the perl code

Perl is closely related to awk, however, the @F autosplit array starts at index $F[0] while awk fields start with $1.

Where is Python language used?

Python started as a scripting language for Linux like Perl but less cryptic. Now it is used for both web and desktop applications and is available on Windows too. Desktop GUI APIs like GTK have their Python implementations and Python based web frameworks like Django are preferred by many over PHP et al. for web applications.

And by the way,

  • What can you do with PHP that you can't do with ASP or JSP?
  • What can you do with Java that you can't do with C++?

How to get file URL using Storage facade in laravel 5?

Another solution I found is this:

Storage::disk('documents')->getDriver()->getConfig()->get('url')

Will return the url with the base path of the documents Storage

XSL substring and indexOf

I want to select the text of a string that is located after the occurrence of substring

You could use:

substring-after($string,$match)

If you want a subtring of the above with some length then use:

substring(substring-after($string,$match),1,$length)

But problems begin if there is no ocurrence of the matching substring... So, if you want a substring with specific length located after the occurrence of a substring, or from the whole string if there is no match, you could use:

substring(substring-after($string,substring-before($string,$match)),
          string-length($match) * contains($string,$match) + 1,
          $length) 

BigDecimal equals() versus compareTo()

I see that BigDecimal has an inflate() method on equals() method. What does inflate() do actually?

Basically, inflate() calls BigInteger.valueOf(intCompact) if necessary, i.e. it creates the unscaled value that is stored as a BigInteger from long intCompact. If you don't need that BigInteger and the unscaled value fits into a long BigDecimal seems to try to save space as long as possible.

Private Variables and Methods in Python

The double underscore. It mangles the name in such a way that it can't be accessed simply through __fieldName from outside the class, which is what you want to begin with if they're to be private. (Though it's still not very hard to access the field.)

class Foo:
    def __init__(self):
        self.__privateField = 4;
        print self.__privateField # yields 4 no problem

foo = Foo()
foo.__privateField
# AttributeError: Foo instance has no attribute '__privateField'

It will be accessible through _Foo__privateField instead. But it screams "I'M PRIVATE DON'T TOUCH ME", which is better than nothing.

Placing border inside of div and not on its edge

Although this question has already been adequately answered with solutions using the box-shadow and outline properties, I would like to slightly expand on this for all those who have landed here (like myself) searching for a solution for an inner border with an offset

So let's say you have a black 100px x 100px div and you need to inset it with a white border - which has an inner offset of 5px (say) - this can still be done with the above properties.

box-shadow

The trick here is to know that multiple box-shadows are allowed, where the first shadow is on top and subsequent shadows have lower z-ordering.

With that knowledge, the box-shadow declaration will be:

box-shadow: inset 0 0 0 5px black, inset 0 0 0 10px white;

_x000D_
_x000D_
div {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: black;_x000D_
  box-shadow: inset 0 0 0 5px black, inset 0 0 0 10px white; _x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

Basically, what that declaration is saying is: render the last (10px white) shadow first, then render the previous 5px black shadow above it.

outline with outline-offset

For the same effect as above the outline declarations would be:

outline: 5px solid white;
outline-offset: -10px;

_x000D_
_x000D_
div {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: black;_x000D_
  outline: 5px solid white;_x000D_
  outline-offset: -10px;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

NB: outline-offset isn't supported by IE if that's important to you.


Codepen demo

How can I print out all possible letter combinations a given phone number can represent?

Scala solution:

def mnemonics(phoneNum: String, dict: IndexedSeq[String]): Iterable[String] = {
  def mnemonics(d: Int, prefix: String): Seq[String] = {
    if (d >= phoneNum.length) {
      Seq(prefix)
    } else {
      for {
        ch <- dict(phoneNum.charAt(d).asDigit)
        num <- mnemonics(d + 1, s"$prefix$ch")
      } yield num
    }
  }

  mnemonics(0, "")
}

Assuming each digit maps to at most 4 characters, the number of recursive calls T satisfy the inequality T(n) <= 4T(n-1), which is of the order 4^n.

combining two string variables

IMO, froadie's simple concatenation is fine for a simple case like you presented. If you want to put together several strings, the string join method seems to be preferred:

the_text = ''.join(['the ', 'quick ', 'brown ', 'fox ', 'jumped ', 'over ', 'the ', 'lazy ', 'dog.'])

Edit: Note that join wants an iterable (e.g. a list) as its single argument.

How to print colored text to the terminal?

# Pure Python 3.x demo, 256 colors
# Works with bash under Linux and MacOS

fg = lambda text, color: "\33[38;5;" + str(color) + "m" + text + "\33[0m"
bg = lambda text, color: "\33[48;5;" + str(color) + "m" + text + "\33[0m"

def print_six(row, format, end="\n"):
    for col in range(6):
        color = row*6 + col - 2
        if color>=0:
            text = "{:3d}".format(color)
            print (format(text,color), end=" ")
        else:
            print(end="    ")   # four spaces
    print(end=end)

for row in range(0, 43):
    print_six(row, fg, " ")
    print_six(row, bg)

# Simple usage: print(fg("text", 160))

Text with altering foreground and background, colors 0..141 Text with altering foreground and background, colors 142..255

Try it online

How to insert values into the database table using VBA in MS access

  1. Remove this line of code: For i = 1 To DatDiff. A For loop must have the word NEXT
  2. Also, remove this line of code: StrSQL = StrSQL & "SELECT 'Test'" because its making Access look at your final SQL statement like this; INSERT INTO Test (Start_Date) VALUES ('" & InDate & "' );SELECT 'Test' Notice the semicolon in the middle of the SQL statement (should always be at the end. its by the way not required. you can also omit it). also, there is no space between the semicolon and the key word SELECT

in summary: remove those two lines of code above and your insert statement will work fine. You can the modify the code it later to suit your specific needs. And by the way, some times, you have to enclose dates in pounds signs like #

Find intersection of two nested lists?

You don't need to define intersection. It's already a first-class part of set.

>>> b1 = [1,2,3,4,5,9,11,15]
>>> b2 = [4,5,6,7,8]
>>> set(b1).intersection(b2)
set([4, 5])

How to set UTF-8 encoding for a PHP file

Also note that setting a header to "text/plain" will result in all html and php (in part) printing the characters on the screen as TEXT, not as HTML. So be aware of possible HTML not parsing when using text type plain.

Using:

header('Content-type: text/html; charset=utf-8');

Can return HTML and PHP as well. Not just text.

Generating random numbers with Swift

===== Swift 4.2 / Xcode 10 =====

let randomIntFrom0To10 = Int.random(in: 1..<10)
let randomFloat = Float.random(in: 0..<1)

// if you want to get a random element in an array
let greetings = ["hey", "hi", "hello", "hola"]
greetings.randomElement()

Under the hood Swift uses arc4random_buf to get job done.

===== Swift 4.1 / Xcode 9 =====

arc4random() returns a random number in the range of 0 to 4 294 967 295

drand48() returns a random number in the range of 0.0 to 1.0

arc4random_uniform(N) returns a random number in the range of 0 to N - 1

Examples:

arc4random() // => UInt32 = 2739058784
arc4random() // => UInt32 = 2672503239
arc4random() // => UInt32 = 3990537167
arc4random() // => UInt32 = 2516511476
arc4random() // => UInt32 = 3959558840

drand48() // => Double = 0.88642843322303122
drand48() // => Double = 0.015582849408328769
drand48() // => Double = 0.58409022031727176
drand48() // => Double = 0.15936862653180484
drand48() // => Double = 0.38371587480719427

arc4random_uniform(3) // => UInt32 = 0
arc4random_uniform(3) // => UInt32 = 1
arc4random_uniform(3) // => UInt32 = 0
arc4random_uniform(3) // => UInt32 = 1
arc4random_uniform(3) // => UInt32 = 2

arc4random_uniform() is recommended over constructions like arc4random() % upper_bound as it avoids "modulo bias" when the upper bound is not a power of two.

How do I get the difference between two Dates in JavaScript?

this code fills the duration of study years when you input the start date and end date(qualify accured date) of study and check if the duration less than a year if yes the alert a message take in mind there are three input elements the first txtFromQualifDate and second txtQualifDate and third txtStudyYears

it will show result of number of years with fraction

function getStudyYears()
    {
        if(document.getElementById('txtFromQualifDate').value != '' && document.getElementById('txtQualifDate').value != '')
        {
            var d1 = document.getElementById('txtFromQualifDate').value;

            var d2 = document.getElementById('txtQualifDate').value;

            var one_day=1000*60*60*24;

            var x = d1.split("/");
            var y = d2.split("/");

            var date1=new Date(x[2],(x[1]-1),x[0]);

            var date2=new Date(y[2],(y[1]-1),y[0])

            var dDays = (date2.getTime()-date1.getTime())/one_day;

            if(dDays < 365)
            {
                alert("the date between start study and graduate must not be less than a year !");

                document.getElementById('txtQualifDate').value = "";
                document.getElementById('txtStudyYears').value = "";

                return ;
            }

            var dMonths = Math.ceil(dDays / 30);

            var dYears = Math.floor(dMonths /12) + "." + dMonths % 12;

            document.getElementById('txtStudyYears').value = dYears;
        }
    }

How to normalize a signal to zero mean and unit variance?

It seems like you are essentially looking into computing the z-score or standard score of your data, which is calculated through the formula: z = (x-mean(x))/std(x)

This should work:

%% Original data (Normal with mean 1 and standard deviation 2)
x = 1 + 2*randn(100,1);
mean(x)
var(x)
std(x)

%% Normalized data with mean 0 and variance 1
z = (x-mean(x))/std(x);
mean(z)
var(z)
std(z)

Django templates: If false?

Just ran into this again (certain I had before and came up with a less-than-satisfying solution).

For a tri-state boolean semantic (for example, using models.NullBooleanField), this works well:

{% if test.passed|lower == 'false' %} ... {% endif %}

Or if you prefer getting excited over the whole thing...

{% if test.passed|upper == 'FALSE' %} ... {% endif %}

Either way, this handles the special condition where you don't care about the None (evaluating to False in the if block) or True case.

React : difference between <Route exact path="/" /> and <Route path="/" />

Please try this.

       <Router>
          <div>
            <Route exact path="/" component={Home} />
            <Route path="/news" component={NewsFeed} />
          </div>
        </Router> 

            

How to lowercase a pandas dataframe string column if it has missing values?

you can try this one also,

df= df.applymap(lambda s:s.lower() if type(s) == str else s)

Unable to load DLL 'SQLite.Interop.dll'

So, after adding the NuGet the deployment doesn't copy down the Interops. You can add this to your csproj file and it should fix that behavior:

 <PropertyGroup> 
    <ContentSQLiteInteropFiles>true</ContentSQLiteInteropFiles>
    <CopySQLiteInteropFiles>false</CopySQLiteInteropFiles>
    <CleanSQLiteInteropFiles>false</CleanSQLiteInteropFiles>
    <CollectSQLiteInteropFiles>false</CollectSQLiteInteropFiles>
 </PropertyGroup>

If you look in the source for NuGet for SQLite you can see what these are doing specifically. This allowed me to get a deploy working with ASP.Net Core.

Automatic HTTPS connection/redirect with node.js/express

I use the solution proposed by Basarat but I also need to overwrite the port because I used to have 2 different ports for HTTP and HTTPS protocols.

res.writeHead(301, { "Location": "https://" + req.headers['host'].replace(http_port,https_port) + req.url });

I prefer also to use not standard port so to start nodejs without root privileges. I like 8080 and 8443 because I came from lots of years of programming on tomcat.

My complete file become

var fs = require('fs');
var http = require('http');
var http_port    =   process.env.PORT || 8080; 
var app = require('express')();

// HTTPS definitions
var https = require('https');
var https_port    =   process.env.PORT_HTTPS || 8443; 
var options = {
   key  : fs.readFileSync('server.key'),
   cert : fs.readFileSync('server.crt')
};

app.get('/', function (req, res) {
   res.send('Hello World!');
});

https.createServer(options, app).listen(https_port, function () {
   console.log('Magic happens on port ' + https_port); 
});

// Redirect from http port to https
http.createServer(function (req, res) {
    res.writeHead(301, { "Location": "https://" + req.headers['host'].replace(http_port,https_port) + req.url });
    console.log("http request, will go to >> ");
    console.log("https://" + req.headers['host'].replace(http_port,https_port) + req.url );
    res.end();
}).listen(http_port);

Then I use iptable for forwording 80 and 443 traffic on my HTTP and HTTPS ports.

sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080
sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 443 -j REDIRECT --to-port 8443

CSS: Fix row height

I haven't tried it but if you put a div in your table cell set so that it will have scrollbars if needed, then you could insert in there, with a fixed height on the div and it should keep your table row to a fixed height.

How do I filter an array with AngularJS and use a property of the filtered object as the ng-model attribute?

please note, if you use $filter like this:

$scope.failedSubjects = $filter('filter')($scope.results.subjects, {'grade':'C'});

and you happened to have another grade for, Oh I don't know, CC or AC or C+ or CCC it pulls them in to. you need to append a requirement for an exact match:

$scope.failedSubjects = $filter('filter')($scope.results.subjects, {'grade':'C'}, true);

This really killed me when I was pulling in some commission details like this:

var obj = this.$filter('filter')(this.CommissionTypes, { commission_type_id: 6}))[0];

only get called in for a bug because it was pulling in the commission ID 56 rather than 6.

Adding the true forces an exact match.

var obj = this.$filter('filter')(this.CommissionTypes, { commission_type_id: 6}, true))[0];

Yet still, I prefer this (I use typescript, hence the "Let" and =>):

let obj = this.$filter('filter')(this.CommissionTypes, (item) =>{ 
             return item.commission_type_id === 6;
           })[0];

I do that because, at some point down the road, I might want to get some more info from that filtered data, etc... having the function right in there kind of leaves the hood open.

Why doesn't Java allow overriding of static methods?

In Java (and many OOP languages, but I cannot speak for all; and some do not have static at all) all methods have a fixed signature - the parameters and types. In a virtual method, the first parameter is implied: a reference to the object itself and when called from within the object, the compiler automatically adds this.

There is no difference for static methods - they still have a fixed signature. However, by declaring the method static you have explicitly stated that the compiler must not include the implied object parameter at the beginning of that signature. Therefore, any other code that calls this must must not attempt to put a reference to an object on the stack. If it did do that, then the method execution would not work since the parameters would be in the wrong place - shifted by one - on the stack.

Because of this difference between the two; virtual methods always have a reference to the context object (i.e. this) so then it is possible to reference anything within the heap that belong to that instance of the object. But with static methods, since there is no reference passed, that method cannot access any object variables and methods since the context is not known.

If you wish that Java would change the definition so that a object context is passed in for every method, static or virtual, then you would in essence have only virtual methods.

As someone asked in a comment to the op - what is your reason and purpose for wanting this feature?

I do not know Ruby much, as this was mentioned by the OP, I did some research. I see that in Ruby classes are really a special kind of object and one can create (even dynamically) new methods. Classes are full class objects in Ruby, they are not in Java. This is just something you will have to accept when working with Java (or C#). These are not dynamic languages, though C# is adding some forms of dynamic. In reality, Ruby does not have "static" methods as far as I could find - in that case these are methods on the singleton class object. You can then override this singleton with a new class and the methods in the previous class object will call those defined in the new class (correct?). So if you called a method in the context of the original class it still would only execute the original statics, but calling a method in the derived class, would call methods either from the parent or sub-class. Interesting and I can see some value in that. It takes a different thought pattern.

Since you are working in Java, you will need to adjust to that way of doing things. Why they did this? Well, probably to improve performance at the time based on the technology and understanding that was available. Computer languages are constantly evolving. Go back far enough and there is no such thing as OOP. In the future, there will be other new ideas.

EDIT: One other comment. Now that I see the differences and as I Java/C# developer myself, I can understand why the answers you get from Java developers may be confusing if you are coming from a language like Ruby. Java static methods are not the same as Ruby class methods. Java developers will have a hard time understanding this, as will conversely those who work mostly with a language like Ruby/Smalltalk. I can see how this would also be greatly confusing by the fact that Java also uses "class method" as another way to talk about static methods but this same term is used differently by Ruby. Java does not have Ruby style class methods (sorry); Ruby does not have Java style static methods which are really just old procedural style functions, as found in C.

By the way - thanks for the question! I learned something new for me today about class methods (Ruby style).

How to go to each directory and execute a command?

I don't get the point with the formating of the file, since you only want to iterate through folders... Are you looking for something like this?

cd parent
find . -type d | while read d; do
   ls $d/
done

Does Visual Studio have code coverage for unit tests?

As already mentioned you can use Fine Code Coverage that visualize coverlet output. If you create a xunit test project (dotnet new xunit) you'll find coverlet reference already present in csproj file because Coverlet is the default coverage tool for every .NET Core and >= .NET 5 applications.

Microsoft has an example using ReportGenerator that converts coverage reports generated by coverlet, OpenCover, dotCover, Visual Studio, NCover, Cobertura, JaCoCo, Clover, gcov or lcov into human readable reports in various formats.

Example report:

enter image description here

While the article focuses on C# and xUnit as the test framework, both MSTest and NUnit would also work.

Guide:

https://docs.microsoft.com/en-us/dotnet/core/testing/unit-testing-code-coverage?tabs=windows#generate-reports

If you want code coverage in .xml files you can run any of these commands:

dotnet test --collect:"XPlat Code Coverage"

dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura

Generate sql insert script from excel worksheet

Depending on the database, you can export to CSV and then use an import method.

MySQL - http://dev.mysql.com/doc/refman/5.1/en/load-data.html

PostgreSQL - http://www.postgresql.org/docs/8.2/static/sql-copy.html

On Duplicate Key Update same as insert

you can use insert ignore for such case, it will ignore if it gets duplicate records INSERT IGNORE ... ; -- without ON DUPLICATE KEY

Value of type 'T' cannot be converted to

Both lines have the same problem

T newT1 = "some text";
T newT2 = (string)t;

The compiler doesn't know that T is a string and so has no way of knowing how to assign that. But since you checked you can just force it with

T newT1 = "some text" as T;
T newT2 = t; 

you don't need to cast the t since it's already a string, also need to add the constraint

where T : class

Why is this printing 'None' in the output?

Because of double print function. I suggest you to use return instead of print inside the function definition.

def lyrics():
    return "The very first line"
print(lyrics())

OR

def lyrics():
    print("The very first line")
lyrics()

What does 'git blame' do?

The command explains itself quite well. It's to figure out which co-worker wrote the specific line or ruined the project, so you can blame them :)

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use

This solution is for windows:

  1. Open command prompt in Administrator Mode.
  2. Goto path: C:\Program Files\MySQL\MySQL Server 5.6\bin
  3. Run below command: mysqldump -h 127.0.01 -u root -proot db table1 table2 > result.sql

What's the difference between "super()" and "super(props)" in React when using es6 classes?

Here is the fiddle I've made:jsfiddle.net. It shows that props are assigned not in the constructor by default. As I understand they are assinged in the method React.createElement. Hence super(props) should be called only when the superclass's constructor manually assings props to this.props. If you just extend the React.Component calling super(props) will do nothing with props. Maybe It will be changed in the next versions of React.

Html5 Full screen video

Here is a very simple way (3 lines of code) using the Fullscreen API and RequestFullscreen method that I used, which is compatible across all popular browsers:

_x000D_
_x000D_
var elem = document.getElementsByTagName('video')[0];_x000D_
var fullscreen = elem.webkitRequestFullscreen || elem.mozRequestFullScreen || elem.msRequestFullscreen;_x000D_
fullscreen.call(elem); // bind the 'this' from the video object and instantiate the correct fullscreen method.
_x000D_
_x000D_
_x000D_

For browser compatibility: MDN & Can I use

CSS: How to change colour of active navigation page menu

Add ID current for active/current page:

<div class="menuBar">
  <ul>
  <li id="current"><a href="index.php">HOME</a></li>
  <li><a href="two.php">PORTFOLIO</a></li>
  <li><a href="three.php">ABOUT</a></li>
  <li><a href="four.php">CONTACT</a></li>
  <li><a href="five.php">SHOP</a></li>
 </ul>

#current a { color: #ff0000; }

How to count the number of columns in a table using SQL?

Old question - but I recently needed this along with the row count... here is a query for both - sorted by row count desc:

SELECT t.owner, 
       t.table_name, 
       t.num_rows, 
       Count(*) 
FROM   all_tables t 
       LEFT JOIN all_tab_columns c 
              ON t.table_name = c.table_name 
WHERE  num_rows IS NOT NULL 
GROUP  BY t.owner, 
          t.table_name, 
          t.num_rows 
ORDER  BY t.num_rows DESC; 

Which is the default location for keystore/truststore of Java applications?

Like bruno said, you're better configuring it yourself. Here's how I do it. Start by creating a properties file (/etc/myapp/config.properties).

javax.net.ssl.keyStore = /etc/myapp/keyStore
javax.net.ssl.keyStorePassword = 123456

Then load the properties to your environment from your code. This makes your application configurable.

FileInputStream propFile = new FileInputStream("/etc/myapp/config.properties");
Properties p = new Properties(System.getProperties());
p.load(propFile);
System.setProperties(p);

Reset select value to default

A simple way that runs is

 var myselect = $("select.SimpleAddAClass");
 myselect[0].selectedIndex = 0;
 myselect.selectmenu("refresh");

How to switch between python 2.7 to python 3 from command line?

There is an easier way than all of the above; You can use the PY_PYTHON environment variable. From inside the cmd.exe shell;

For the latest version of Python 2

set PY_PYTHON=2

For the latest version of Python 3

set PY_PYTHON=3

If you want it to be permanent, set it in the control panel. Or use setx instead of set in the cmd.exe shell.

HTML input file selection event not firing upon selecting the same file

<form enctype='multipart/form-data'>
    <input onchange="alert(this.value); this.value=null; return false;" type='file'>
    <br>
    <input type='submit' value='Upload'>
</form>

this.value=null; is only necessary for Chrome, Firefox will work fine just with return false;

Here is a FIDDLE

Which browsers support <script async="async" />?

A comprehensive list of browser versions supporting the async parameter is available here

Firebase TIMESTAMP to date and Time

It is simple. Use that function to get server timestamp as milliseconds one time only:

var getServerTime = function( cb ) {
    this.db.ref( '.info/serverTimeOffset' ).once( 'value', function( snap ) {
      var offset = snap.val();

      // Get server time by milliseconds
      cb( new Date().getTime() + offset );
    });
};

Now you can use it anywhere like that:

getServerTime( function( now ) {
    console.log( now );
});

Why use this way?

According to latest Firebase documentation, you should convert your Firebase timestamp into milliseconds. So you can use estimatedServerTimeMs variable below:

var offsetRef = firebase.database().ref(".info/serverTimeOffset");
offsetRef.on("value", function(snap) {
  var offset = snap.val();
  var estimatedServerTimeMs = new Date().getTime() + offset;
});

While firebase.database.ServerValue.TIMESTAMP is much more accurate, and preferable for most read/write operations, it can occasionally be useful to estimate the client's clock skew with respect to the Firebase Realtime Database's servers. You can attach a callback to the location /.info/serverTimeOffset to obtain the value, in milliseconds, that Firebase Realtime Database clients add to the local reported time (epoch time in milliseconds) to estimate the server time. Note that this offset's accuracy can be affected by networking latency, and so is useful primarily for discovering large (> 1 second) discrepancies in clock time.

https://firebase.google.com/docs/database/web/offline-capabilities

What are callee and caller saved registers?

Callee vs caller saved is a convention for who is responsible for saving and restoring the value in a register across a call. ALL registers are "global" in that any code anywhere can see (or modify) a register and those modifications will be seen by any later code anywhere. The point of register saving conventions is that code is not supposed to modify certain registers, as other code assumes that the value is not modified.

In your example code, NONE of the registers are callee save, as it makes no attempt to save or restore the register values. However, it would seem to not be an entire procedure, as it contains a branch to an undefined label (l$loop). So it might be a fragment of code from the middle of a procedure that treats some registers as callee save; you're just missing the save/restore instructions.

Is there an exponent operator in C#?

The lack of an exponential operator for C# was a big annoyance for us when looking for a new language to convert our calculation software to from the good ol' vb6.

I'm glad we went with C# but it still annoys me whenever I'm writing a complex equation including exponents. The Math.Pow() method makes equations quite hard to read IMO.

Our solution was to create a special DoubleX class where we override the ^-operator (see below)

This works fairly well as long as you declare at least one of the variables as DoubleX:

DoubleX a = 2;
DoubleX b = 3;

Console.WriteLine($"a = {a}, b = {b}, a^b = {a ^ b}");

or use an explicit converter on standard doubles:

double c = 2;
double d = 3;

Console.WriteLine($"c = {c}, d = {d}, c^d = {c ^ (DoubleX)d}");     // Need explicit converter

One problem with this method though is that the exponent is calculated in the wrong order compared to other operators. This can be avoided by always putting an extra ( ) around the operation which again makes it a bit harder to read the equations:

DoubleX a = 2;
DoubleX b = 3;

Console.WriteLine($"a = {a}, b = {b}, 3+a^b = {3 + a ^ b}");        // Wrong result
Console.WriteLine($"a = {a}, b = {b}, 3+a^b = {3 + (a ^ b)}");      // Correct result

I hope this can be of help to others who uses a lot of complex equations in their code, and maybe someone even has an idea of how to improve this method?!

DoubleX class:

using System;

namespace ExponentialOperator
{
    /// <summary>
    /// Double class that uses ^ as exponential operator
    /// </summary>
    public class DoubleX
    {
        #region ---------------- Fields ----------------

        private readonly double _value;

        #endregion ------------- Fields ----------------

        #region -------------- Properties --------------

        public double Value
        {
            get { return _value; }
        }

        #endregion ----------- Properties --------------

        #region ------------- Constructors -------------

        public DoubleX(double value)
        {
            _value = value;
        }

        public DoubleX(int value)
        {
            _value = Convert.ToDouble(value);
        }

        #endregion ---------- Constructors -------------

        #region --------------- Methods ----------------

        public override string ToString()
        {
            return _value.ToString();
        }

        #endregion ------------ Methods ----------------

        #region -------------- Operators ---------------

        // Change the ^ operator to be used for exponents.

        public static DoubleX operator ^(DoubleX value, DoubleX exponent)
        {
            return Math.Pow(value, exponent);
        }

        public static DoubleX operator ^(DoubleX value, double exponent)
        {
            return Math.Pow(value, exponent);
        }

        public static DoubleX operator ^(double value, DoubleX exponent)
        {
            return Math.Pow(value, exponent);
        }

        public static DoubleX operator ^(DoubleX value, int exponent)
        {
            return Math.Pow(value, exponent);
        }

        #endregion ----------- Operators ---------------

        #region -------------- Converters --------------

        // Allow implicit convertion

        public static implicit operator DoubleX(double value)
        {
            return new DoubleX(value);
        }

        public static implicit operator DoubleX(int value)
        {
            return new DoubleX(value);
        }

        public static implicit operator Double(DoubleX value)
        {
            return value._value;
        }

        #endregion ----------- Converters --------------
    }
}

symbol(s) not found for architecture i386

In my case none of the posted solutions worked. I had to delete the project and make a fresh checkout from the SVN server. Lucky me the project was hosted in a version control system. Don't know what I'd do otherwise.

Android emulator not able to access the internet

I am on android studio 3.1 and it happened. Solved it by restarting the adb server

$ adb kill-server
$ adb start-server

Hope it helps. Thank you

SQL count rows in a table

Why don't you just right click on the table and then properties -> Storage and it would tell you the row count. You can use the below for row count in a view

SELECT SUM (row_count) 
FROM sys.dm_db_partition_stats 
WHERE object_id=OBJECT_ID('Transactions')    
AND (index_id=0 or index_id=1)`

.gitignore is ignored by Git

I had this problem, with a .gitignore file containing this line:

lib/ext/

I just realized that in fact, this directory is a symbolic link to a folder somewhere else:

ls -la lib/ext/
lrwxr-xr-x 1 roipoussiere users 47 Feb  6 14:16 lib/ext -> /home/roipoussiere/real/path/to/the/lib

On the line lib/ext/, Git actually looks for a folder, but a symbolic link is a file, so my lib folder is not ignored.

I fixed this by replacing lib/ext/ by lib/ext in my .gitignore file.

Android list view inside a scroll view

This code will solve your problem if you have implemented just a ListView in a code.

If you are using RelativeLayout as ListView child than this code return a NullPointerException here listItem.measure(0, 0);, because of RelativeLayout.And the solution is put your Relativelayout inside a LinearLayout and it will work fine.

public static void setListViewHeightBasedOnChildren(ListView listView) {
    ListAdapter listAdapter = listView.getAdapter(); 
    if (listAdapter == null) {
        // pre-condition
        return;
    }

    int totalHeight = 0;
    for (int i = 0; i < listAdapter.getCount(); i++) {
        View listItem = listAdapter.getView(i, null, listView);
        listItem.measure(0, 0);
        totalHeight += listItem.getMeasuredHeight();
    }

    ViewGroup.LayoutParams params = listView.getLayoutParams();
    params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
    listView.setLayoutParams(params);
    listView.requestLayout();
}

LINQ to Entities does not recognize the method

If anyone is looking for a VB.Net answer (as I was initially), here it is:

Public Function IsSatisfied() As Expression(Of Func(Of Charity, String, String, Boolean))

Return Function(charity, name, referenceNumber) (String.IsNullOrWhiteSpace(name) Or
                                                         charity.registeredName.ToLower().Contains(name.ToLower()) Or
                                                         charity.alias.ToLower().Contains(name.ToLower()) Or
                                                         charity.charityId.ToLower().Contains(name.ToLower())) And
                                                    (String.IsNullOrEmpty(referenceNumber) Or
                                                     charity.charityReference.ToLower().Contains(referenceNumber.ToLower()))
End Function

How to delete a workspace in Perforce (using p4v)?

It could also be done without a visual client with the following small script.

$ cat ~/bin/pdel

#!/bin/sh

#Todo: add error handling

( p4 -c $1 client -o | perl -pne 's/\blocked\s//' | p4 -c $1  client -i ) && p4 client -d $1

How to pass a value from one Activity to another in Android?

Standard way of passing data from one activity to another:

If you want to send large number of data from one activity to another activity then you can put data in a bundle and then pass it using putExtra() method.

//Create the `intent`
 Intent i = new Intent(this, ActivityTwo.class);
String one="xxxxxxxxxxxxxxx";
String two="xxxxxxxxxxxxxxxxxxxxx";
//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString(“ONE”, one);
bundle.putString(“TWO”, two);  
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
startActivity(i);

otherwise you can use putExtra() directly with intent to send data and getExtra() to get data.

Intent i=new Intent(this, ActivityTwo.class);
i.putExtra("One",one);
i.putExtra("Two",two);
startActivity(i);

java.util.Date to XMLGregorianCalendar

Assuming you are decoding or encoding xml and using JAXB, then it's possible to replace the dateTime binding entirely and use something else than `XMLGregorianCalendar' for every date in the schema.

In that way you can have JAXB do the repetitive stuff while you can spend the time on writing awesome code that delivers value.

Example for a jodatime DateTime: (Doing this with java.util.Date would also work - but with certain limitations. I prefer jodatime and it's copied from my code so I know it works...)

<jxb:globalBindings>
    <jxb:javaType name="org.joda.time.LocalDateTime" xmlType="xs:dateTime"
        parseMethod="test.util.JaxbConverter.parseDateTime"
        printMethod="se.seb.bis.test.util.JaxbConverter.printDateTime" />
    <jxb:javaType name="org.joda.time.LocalDate" xmlType="xs:date"
        parseMethod="test.util.JaxbConverter.parseDate"
        printMethod="test.util.JaxbConverter.printDate" />
    <jxb:javaType name="org.joda.time.LocalTime" xmlType="xs:time"
        parseMethod="test.util.JaxbConverter.parseTime"
        printMethod="test.util.JaxbConverter.printTime" />
    <jxb:serializable uid="2" />
</jxb:globalBindings>

And the converter:

public class JaxbConverter {
static final DateTimeFormatter dtf = ISODateTimeFormat.dateTimeNoMillis();
static final DateTimeFormatter df = ISODateTimeFormat.date();
static final DateTimeFormatter tf = ISODateTimeFormat.time();

public static LocalDateTime parseDateTime(String s) {
    try {
        if (StringUtils.trimToEmpty(s).isEmpty())
            return null;
        LocalDateTime r = dtf.parseLocalDateTime(s);
        return r;
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}

public static String printDateTime(LocalDateTime d) {
    try {
        if (d == null)
            return null;
        return dtf.print(d);
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}

public static LocalDate parseDate(String s) {
    try {
        if (StringUtils.trimToEmpty(s).isEmpty())
            return null;
        return df.parseLocalDate(s);
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}

public static String printDate(LocalDate d) {
    try {
        if (d == null)
            return null;
        return df.print(d);
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}

public static String printTime(LocalTime d) {
    try {
        if (d == null)
            return null;
        return tf.print(d);
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}

public static LocalTime parseTime(String s) {
    try {
        if (StringUtils.trimToEmpty(s).isEmpty())
            return null;
        return df.parseLocalTime(s);
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}

See here: how replace XmlGregorianCalendar by Date?

If you are happy to just map to an instant based on the timezone+timestamp, and the original timezone is not really relevant, then java.util.Date is probably fine too.

How to check whether a pandas DataFrame is empty?

I prefer going the long route. These are the checks I follow to avoid using a try-except clause -

  1. check if variable is not None
  2. then check if its a dataframe and
  3. make sure its not empty

Here, DATA is the suspect variable -

DATA is not None and isinstance(DATA, pd.DataFrame) and not DATA.empty

Xcode doesn't see my iOS device but iTunes does

Have you tried to delete and re install the device in your Apple Developer portal? If yes, try to upgrade your xcode to 4.3.2, I remember that I needed to update to xCode 4.3.2 after updating my iPhone to iOS 5.1

What does servletcontext.getRealPath("/") mean and when should I use it

My Method:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        String path = request.getRealPath("/WEB-INF/conf.properties");
        Properties p = new Properties();
        p.load(new FileInputStream(path));

        String StringConexion=p.getProperty("StringConexion");
        String User=p.getProperty("User");
        String Password=p.getProperty("Password");
    }
    catch(Exception e){
        String msg = "Excepcion " + e;
    }
}

Redirecting from HTTP to HTTPS with PHP

On my AWS beanstalk server, I don't see $_SERVER['HTTPS'] variable. I do see $_SERVER['HTTP_X_FORWARDED_PROTO'] which can be either 'http' or 'https' so if you're hosting on AWS, use this:

if ($_SERVER['HTTP_HOST'] != 'localhost' and $_SERVER['HTTP_X_FORWARDED_PROTO'] != "https") {
    $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: ' . $location);
    exit;
}

Creating a List of Lists in C#

A quick example:

List<List<string>> myList = new List<List<string>>();
myList.Add(new List<string> { "a", "b" });
myList.Add(new List<string> { "c", "d", "e" });
myList.Add(new List<string> { "qwerty", "asdf", "zxcv" });
myList.Add(new List<string> { "a", "b" });

// To iterate over it.
foreach (List<string> subList in myList)
{
    foreach (string item in subList)
    {
        Console.WriteLine(item);
    }
}

Is that what you were looking for? Or are you trying to create a new class that extends List<T> that has a member that is a `List'?

Why is there no xrange function in Python3?

comp:~$ python Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2

>>> import timeit
>>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=100)

5.656799077987671

>>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=100)

5.579368829727173

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)

21.54827117919922

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)

22.014557123184204

With timeit number=1 param:

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=1)

0.2245171070098877

>>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=1)

0.10750913619995117

comp:~$ python3 Python 3.4.3 (default, Oct 14 2015, 20:28:29) [GCC 4.8.4] on linux

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)

9.113872020003328

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)

9.07014398300089

With timeit number=1,2,3,4 param works quick and in linear way:

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=1)

0.09329321900440846

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=2)

0.18501482300052885

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=3)

0.2703447980020428

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=4)

0.36209142999723554

So it seems if we measure 1 running loop cycle like timeit.timeit("[x for x in range(1000000) if x%4]",number=1) (as we actually use in real code) python3 works quick enough, but in repeated loops python 2 xrange() wins in speed against range() from python 3.

OpenCV resize fails on large image with "error: (-215) ssize.area() > 0 in function cv::resize"

I had the same error. Resizing the images resolved the issue. However, I used online tools to resize the images because using pillow to resize them did not solve my problem.

How to use conditional statement within child attribute of a Flutter Widget (Center Widget)

****You can also use conditions by using this method** **

 int _moneyCounter = 0;
  void _rainMoney(){
    setState(() {
      _moneyCounter +=  100;
    });
  }

new Expanded(
          child: new Center(
            child: new Text('\$$_moneyCounter', 

            style:new TextStyle(
              color: _moneyCounter > 1000 ? Colors.blue : Colors.amberAccent,
              fontSize: 47,
              fontWeight: FontWeight.w800
            )

            ),
          ) 
        ),

Unstaged changes left after git reset --hard

I believe that there is an issue with git for Windows where git randomly writes the wrong line endings on checkout and the only workaround is to checkout some other branch and force git to ignore changes. Then checkout the branch you actually want to work on.

git checkout master -f
git checkout <your branch>

Be aware that this will discard any changes you might have intentionally made, so only do this if you have this problem immediately after checkout.

Edit: I might have actually got lucky the first time. It turns out that I got bit again after switching branches. It turned out that the files git was reporting as modified after changing branches was changing. (Apparently because git was not consistently applying the CRLF line ending to files properly.)

I updated to the latest git for Windows and hope the problem is gone.

Dividing two integers to produce a float result

Cast the operands to floats:

float ans = (float)a / (float)b;

Making LaTeX tables smaller?

http://en.wikibooks.org/wiki/LaTeX/Tables#Resize_tables talks about two ways to do this.

I used:

\scalebox{0.7}{
  \begin{tabular}
    ...
  \end{tabular}
}

How to remove an element slowly with jQuery?

I've modified Greg's answer to suit my case, and it works. Here it is:

$("#note-items").children('.active').hide('slow', function(){ $("#note-items").children('.active').remove(); });

How to get the absolute coordinates of a view

My utils function for get view location, it will return a Point object with x value and y value

public static Point getLocationOnScreen(View view){
    int[] location = new int[2];
    view.getLocationOnScreen(location);
    return new Point(location[0], location[1]);
}

Using

Point viewALocation = getLocationOnScreen(viewA);

Priority queue in .Net

I had the same issue recently and ended up creating a NuGet package for this.

This implements a standard heap-based priority queue. It also has all the usual niceties of the BCL collections: ICollection<T> and IReadOnlyCollection<T> implementation, custom IComparer<T> support, ability to specify an initial capacity, and a DebuggerTypeProxy to make the collection easier to work with in the debugger.

There is also an Inline version of the package which just installs a single .cs file into your project (useful if you want to avoid taking externally-visible dependencies).

More information is available on the github page.

Case Function Equivalent in Excel

Even if old, this seems to be a popular questions, so I'll post another solution, which I think is very elegant:

http://fiveminutelessons.com/learn-microsoft-excel/using-multiple-if-statements-excel

It's elegant because it uses just the IF function. Basically, it boils down to this:

if(condition, choose/use a value from the table, if(condition, choose/use another value from the table...

And so on

Works beautifully, even better than HLOOKUP or VLOOOKUP

but... Be warned - there is a limit to the number of nested if statements excel can handle.

Display rows with one or more NaN values in pandas dataframe

Suppose gamma1 and gamma2 are two such columns for which df.isnull().any() gives True value , the following code can be used to print the rows.

bool1 = pd.isnull(df['gamma1'])
bool2 = pd.isnull(df['gamma2'])
df[bool1]
df[bool2]

IOCTL Linux device driver

The ioctl function is useful for implementing a device driver to set the configuration on the device. e.g. a printer that has configuration options to check and set the font family, font size etc. ioctl could be used to get the current font as well as set the font to a new one. A user application uses ioctl to send a code to a printer telling it to return the current font or to set the font to a new one.

int ioctl(int fd, int request, ...)
  1. fd is file descriptor, the one returned by open;
  2. request is request code. e.g GETFONT will get the current font from the printer, SETFONT will set the font on the printer;
  3. the third argument is void *. Depending on the second argument, the third may or may not be present, e.g. if the second argument is SETFONT, the third argument can be the font name such as "Arial";

int request is not just a macro. A user application is required to generate a request code and the device driver module to determine which configuration on device must be played with. The application sends the request code using ioctl and then uses the request code in the device driver module to determine which action to perform.

A request code has 4 main parts

    1. A Magic number - 8 bits
    2. A sequence number - 8 bits
    3. Argument type (typically 14 bits), if any.
    4. Direction of data transfer (2 bits).  

If the request code is SETFONT to set font on a printer, the direction for data transfer will be from user application to device driver module (The user application sends the font name "Arial" to the printer). If the request code is GETFONT, direction is from printer to the user application.

In order to generate a request code, Linux provides some predefined function-like macros.

1._IO(MAGIC, SEQ_NO) both are 8 bits, 0 to 255, e.g. let us say we want to pause printer. This does not require a data transfer. So we would generate the request code as below

#define PRIN_MAGIC 'P'
#define NUM 0
#define PAUSE_PRIN __IO(PRIN_MAGIC, NUM) 

and now use ioctl as

ret_val = ioctl(fd, PAUSE_PRIN);

The corresponding system call in the driver module will receive the code and pause the printer.

  1. __IOW(MAGIC, SEQ_NO, TYPE) MAGIC and SEQ_NO are the same as above, and TYPE gives the type of the next argument, recall the third argument of ioctl is void *. W in __IOW indicates that the data flow is from user application to driver module. As an example, suppose we want to set the printer font to "Arial".
#define PRIN_MAGIC 'S'
#define SEQ_NO 1
#define SETFONT __IOW(PRIN_MAGIC, SEQ_NO, unsigned long)

further,

char *font = "Arial";
ret_val = ioctl(fd, SETFONT, font); 

Now font is a pointer, which means it is an address best represented as unsigned long, hence the third part of _IOW mentions type as such. Also, this address of font is passed to corresponding system call implemented in device driver module as unsigned long and we need to cast it to proper type before using it. Kernel space can access user space and hence this works. other two function-like macros are __IOR(MAGIC, SEQ_NO, TYPE) and __IORW(MAGIC, SEQ_NO, TYPE) where the data flow will be from kernel space to user space and both ways respectively.

Please let me know if this helps!

How to apply a CSS class on hover to dynamically generated submit buttons?

You have two options:

  1. Extend your .paging class definition:

    .paging:hover {
        border:1px solid #999;
        color:#000;
    }
    
  2. Use the DOM hierarchy to apply the CSS style:

    div.paginate input:hover {
        border:1px solid #999;
        color:#000;
    }
    

Resize external website content to fit iFrame width

Tip for 1 website resizing the height. But you can change to 2 websites.

Here is my code to resize an iframe with an external website. You need insert a code into the parent (with iframe code) page and in the external website as well, so, this won't work with you don't have access to edit the external website.

  • local (iframe) page: just insert a code snippet
  • remote (external) page: you need a "body onload" and a "div" that holds all contents. And body needs to be styled to "margin:0"

Local:

<IFRAME STYLE="width:100%;height:1px" SRC="http://www.remote-site.com/" FRAMEBORDER="no" BORDER="0" SCROLLING="no" ID="estframe"></IFRAME>

<SCRIPT>
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
  if (e.data.substring(0,3)=='frm') document.getElementById('estframe').style.height = e.data.substring(3) + 'px';
},false);
</SCRIPT>

You need this "frm" prefix to avoid problems with other embeded codes like Twitter or Facebook plugins. If you have a plain page, you can remove the "if" and the "frm" prefix on both pages (script and onload).

Remote:

You need jQuery to accomplish about "real" page height. I cannot realize how to do with pure JavaScript since you'll have problem when resize the height down (higher to lower height) using body.scrollHeight or related. For some reason, it will return always the biggest height (pre-redimensioned).

<BODY onload="parent.postMessage('frm'+$('#master').height(),'*')" STYLE="margin:0">
<SCRIPT SRC="path-to-jquery/jquery.min.js"></SCRIPT>
<DIV ID="master">
your content
</DIV>

So, parent page (iframe) has a 1px default height. The script inserts a "wait for message/event" from the iframe. When a message (post message) is received and the first 3 chars are "frm" (to avoid the mentioned problem), will get the number from 4th position and set the iframe height (style), including 'px' unit.

The external site (loaded in the iframe) will "send a message" to the parent (opener) with the "frm" and the height of the main div (in this case id "master"). The "*" in postmessage means "any source".

Hope this helps. Sorry for my english.

correct quoting for cmd.exe for multiple arguments

Spaces are horrible in filenames or directory names.

The correct syntax for this is to include every directory name that includes spaces, in double quotes

cmd /c C:\"Program Files"\"Microsoft Visual Studio 9.0"\Common7\IDE\devenv.com mysolution.sln /build "release|win32"

How to Convert the value in DataTable into a string array in c#

If that's all what you want to do, you don't need to convert it into an array. You can just access it as:

string myData=yourDataTable.Rows[0][1].ToString();//Gives you USA

How to get the current directory in a C program?

Note that getcwd(3) is also available in Microsoft's libc: getcwd(3), and works the same way you'd expect.

Must link with -loldnames (oldnames.lib, which is done automatically in most cases), or use _getcwd(). The unprefixed version is unavailable under Windows RT.

What is the difference between require() and library()?

In addition to the good advice already given, I would add this:

It is probably best to avoid using require() unless you actually will be using the value it returns e.g in some error checking loop such as given by thierry.

In most other cases it is better to use library(), because this will give an error message at package loading time if the package is not available. require() will just fail without an error if the package is not there. This is the best time to find out if the package needs to be installed (or perhaps doesn't even exist because it it spelled wrong). Getting error feedback early and at the relevant time will avoid possible headaches with tracking down why later code fails when it attempts to use library routines

PKIX path building failed in Java application

If you are using Eclipse just cross check in Eclipse Windows--> preferences---->java---> installed JREs is pointing the current JRE and the JRE where you have configured your certificate. If not remove the JRE and add the jre where your certificate is installed

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

Colin is correct that a profile should be used. However, his answer hard-codes the target directory in the profile. An alternate solution would be to add a profile like this:

    <profile>
        <id>alternateBuildDir</id>
        <activation>
            <property>
                <name>alt.build.dir</name>
            </property>
        </activation>
        <build>
            <directory>${alt.build.dir}</directory>
        </build>
    </profile>

Doing so would have the effect of changing the build directory to whatever is given by the alt.build.dir property, which can be given in a POM, in the user's settings, or on the command line. If the property is not present, the compilation will happen in the normal target directory.

Android EditText delete(backspace) key event

NOTE: onKeyListener doesn't work for soft keyboards.

You can set OnKeyListener for you editText so you can detect any key press
EDIT: A common mistake we are checking KeyEvent.KEYCODE_BACK for backspace, but really it is KeyEvent.KEYCODE_DEL (Really that name is very confusing! )

editText.setOnKeyListener(new OnKeyListener() {                 
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        //You can identify which key pressed buy checking keyCode value with KeyEvent.KEYCODE_
        if(keyCode == KeyEvent.KEYCODE_DEL) {  
            //this is for backspace
        }
        return false;       
    }
});

Best font for coding

I like Consolas a lot. This top-10 list is a good resource for others. It includes examples and descriptions.

Correct MySQL configuration for Ruby on Rails Database.yml file

If you can have an empty config/database.yml file then define ENV['DATABASE_URL'] variable, then It will work

$ cat config/database.yml
 
$ echo $DATABASE_URL
mysql://root:[email protected]:3306/my_db_name

for Heroku: heroku config:set DATABASE_URL='mysql://root:[email protected]/my_db_name'

How to convert DOS/Windows newline (CRLF) to Unix newline (LF) in a Bash script?

Had just to ponder that same question (on Windows-side, but equally applicable to linux.) Suprisingly nobody mentioned a very much automated way of doing CRLF<->LF conversion for text-files using good old zip -ll option (Info-ZIP):

zip -ll textfiles-lf.zip files-with-crlf-eol.*
unzip textfiles-lf.zip 

NOTE: this would create a zip file preserving the original file names but converting the line endings to LF. Then unzip would extract the files as zip'ed, that is with their original names (but with LF-endings), thus prompting to overwrite the local original files if any.

Relevant excerpt from the zip --help:

zip --help
...
-l   convert LF to CR LF (-ll CR LF to LF)

How to know user has clicked "X" or the "Close" button?

I also had to register the closing function inside the form's "InitializeComponent()" method:

private void InitializeComponent() {
// ...
this.FormClosing += FrmMain_FormClosing;
// ...
}

My "FormClosing" function looks similar to the given answer (https://stackoverflow.com/a/2683846/3323790):

private void FrmMain_FormClosing(object sender, FormClosingEventArgs e) {
    if (e.CloseReason == CloseReason.UserClosing){
        MessageBox.Show("Closed by User", "UserClosing");
    }

    if (e.CloseReason == CloseReason.WindowsShutDown){
        MessageBox.Show("Closed by Windows shutdown", "WindowsShutDown");
    }
}

One more thing to mention: There is also a "FormClosed" function which occurs after "FormClosing". To use this function, register it as shown below:

this.FormClosed += MainPage_FormClosed;

private void MainPage_FormClosing(object sender, FormClosingEventArgs e)
{
// your code after the form is closed
}

Is there a naming convention for MySQL?

I would say that first and foremost: be consistent.

I reckon you are almost there with the conventions that you have outlined in your question. A couple of comments though:

Points 1 and 2 are good I reckon.

Point 3 - sadly this is not always possible. Think about how you would cope with a single table foo_bar that has columns foo_id and another_foo_id both of which reference the foo table foo_id column. You might want to consider how to deal with this. This is a bit of a corner case though!

Point 4 - Similar to Point 3. You may want to introduce a number at the end of the foreign key name to cater for having more than one referencing column.

Point 5 - I would avoid this. It provides you with little and will become a headache when you want to add or remove columns from a table at a later date.

Some other points are:

Index Naming Conventions

You may wish to introduce a naming convention for indexes - this will be a great help for any database metadata work that you might want to carry out. For example you might just want to call an index foo_bar_idx1 or foo_idx1 - totally up to you but worth considering.

Singular vs Plural Column Names

It might be a good idea to address the thorny issue of plural vs single in your column names as well as your table name(s). This subject often causes big debates in the DB community. I would stick with singular forms for both table names and columns. There. I've said it.

The main thing here is of course consistency!

jQuery - find child with a specific class

Based on your comment, moddify this:

$( '.bgHeaderH2' ).html (); // will return whatever is inside the DIV

to:

$( '.bgHeaderH2', $( this ) ).html (); // will return whatever is inside the DIV

More about selectors: https://api.jquery.com/category/selectors/

What's the difference between console.dir and console.log?

None of the 7 prior answers mentioned that console.dir supports extra arguments: depth, showHidden, and whether to use colors.

Of particular interest is depth, which (in theory) allows travering objects into more than the default 2 levels that console.log supports.

I wrote "in theory" because in practice when I had a Mongoose object and ran console.log(mongoose) and console.dir(mongoose, { depth: null }), the output was the same. What actually recursed deeply into the mongoose object was using util.inspect:

import * as util from 'util';
console.log(util.inspect(myObject, {showHidden: false, depth: null}));

Is there any ASCII character for <br>?

The answer is amp#13; — change "amp" to the ampersand sign and go.

Example of Named Pipes

For someone who is new to IPC and Named Pipes, I found the following NuGet package to be a great help.

GitHub: Named Pipe Wrapper for .NET 4.0

To use first install the package:

PS> Install-Package NamedPipeWrapper

Then an example server (copied from the link):

var server = new NamedPipeServer<SomeClass>("MyServerPipe");
server.ClientConnected += delegate(NamedPipeConnection<SomeClass> conn)
    {
        Console.WriteLine("Client {0} is now connected!", conn.Id);
        conn.PushMessage(new SomeClass { Text: "Welcome!" });
    };

server.ClientMessage += delegate(NamedPipeConnection<SomeClass> conn, SomeClass message)
    {
        Console.WriteLine("Client {0} says: {1}", conn.Id, message.Text);
    };

server.Start();

Example client:

var client = new NamedPipeClient<SomeClass>("MyServerPipe");
client.ServerMessage += delegate(NamedPipeConnection<SomeClass> conn, SomeClass message)
    {
        Console.WriteLine("Server says: {0}", message.Text);
    };

client.Start();

Best thing about it for me is that unlike the accepted answer here it supports multiple clients talking to a single server.

How to add style from code behind?

try this

 lblMsg.Text = @"Your search result for <b style=""color:green;"">" + txtCode.Text.Trim() + "</b> ";

How to change Status Bar text color in iOS

You can use this for iOS 6 and 7:

#ifdef __IPHONE_7_0
# define STATUS_STYLE UIStatusBarStyleLightContent
#else
# define STATUS_STYLE UIStatusBarStyleBlackTranslucent
#endif

[[UIApplication sharedApplication] setStatusBarStyle:STATUS_STYLE animated:YES];

Row numbers in query result using Microsoft Access

Since I am sorting alphabetically on a string field and NOT by ID, the Count(*) and DCOUNT() approaches didn't work for me. My solution was to write a function that returns the Row Number:

Option Compare Database
Option Explicit
Private Rst As Recordset

Public Function GetRowNum(ID As Long) As Long
  If Rst Is Nothing Then
    Set Rst = CurrentDb.OpenRecordset("SELECT ID FROM FileList ORDER BY RealName")
  End If
  Rst.FindFirst "ID=" & ID
  GetRowNum = Rst.AbsolutePosition + 1
' Release the Rst 1 sec after it's last use
'------------------------------------------
  SetTimer Application.hWndAccessApp, 1, 1000, AddressOf ReleaseRst  
End Function


Private Sub ReleaseRst(ByVal hWnd As LongPtr, ByVal uMsg As Long, ByVal nIDEEvent As Long, ByVal dwTime As Long)
  KillTimer Application.hWndAccessApp, 1 
  Set Rst = Nothing
End Sub

No connection could be made because the target machine actively refused it 127.0.0.1:3446

Check if any other program is using that port.

If an instance of the same program is still active, kill that process.

Setting background colour of Android layout element

If you want to change a color quickly (and you don't have Hex numbers memorized) android has a few preset colors you can access like this:

android:background="@android:color/black"

There are 15 colors you can choose from which is nice for testing things out quickly, and you don't need to set up additional files.

Setting up a values/colors.xml file and using straight Hex like explained above will still work.

how to move elasticsearch data from one server to another

If you don't want to use the elasticdump like a console tool. You can use next node.js script

Adding a UISegmentedControl to UITableView

   self.tableView.tableHeaderView = segmentedControl; 

If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.

enter image description here enter image description here

Need to ZIP an entire directory using Node.js

Since archiver is not compatible with the new version of webpack for a long time, I recommend using zip-lib.

var zl = require("zip-lib");

zl.archiveFolder("path/to/folder", "path/to/target.zip").then(function () {
    console.log("done");
}, function (err) {
    console.log(err);
});