Programs & Examples On #Publishing site

How to display the first few characters of a string in Python?

If you want first 2 letters and last 2 letters of a string then you can use the following code: name = "India" name[0:2]="In" names[-2:]="ia"

Setting device orientation in Swift iOS

For Swift 3, iOS 10

override open var shouldAutorotate: Bool {
    return false
}

override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return .portrait
}

override open var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
    return .portrait
}

However, there is a bug with the setting shouldAutorotate doesn't work on iOS 9 currently.

Is there a function to split a string in PL/SQL?

Please find next an example you may find useful

--1st substring

select substr('alfa#bravo#charlie#delta', 1,  
  instr('alfa#bravo#charlie#delta', '#', 1, 1)-1) from dual;

--2nd substring

select substr('alfa#bravo#charlie#delta', instr('alfa#bravo#charlie#delta', '#', 1, 1)+1,  
  instr('alfa#bravo#charlie#delta', '#', 1, 2) - instr('alfa#bravo#charlie#delta', '#', 1, 1) -1) from dual;

--3rd substring

select substr('alfa#bravo#charlie#delta', instr('alfa#bravo#charlie#delta', '#', 1, 2)+1,  
  instr('alfa#bravo#charlie#delta', '#', 1, 3) - instr('alfa#bravo#charlie#delta', '#', 1, 2) -1) from dual;

--4th substring

select substr('alfa#bravo#charlie#delta', instr('alfa#bravo#charlie#delta', '#', 1, 3)+1) from dual;

Best regards

Emanuele

Why is document.write considered a "bad practice"?

There's actually nothing wrong with document.write, per se. The problem is that it's really easy to misuse it. Grossly, even.

In terms of vendors supplying analytics code (like Google Analytics) it's actually the easiest way for them to distribute such snippets

  1. It keeps the scripts small
  2. They don't have to worry about overriding already established onload events or including the necessary abstraction to add onload events safely
  3. It's extremely compatible

As long as you don't try to use it after the document has loaded, document.write is not inherently evil, in my humble opinion.

Return value of x = os.system(..)

os.system() returns the (encoded) process exit value. 0 means success:

On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.

The output you see is written to stdout, so your console or terminal, and not returned to the Python caller.

If you wanted to capture stdout, use subprocess.check_output() instead:

x = subprocess.check_output(['whoami'])

Static method in a generic class?

I ran into this same problem. I found my answer by downloading the source code for Collections.sort in the java framework. The answer I used was to put the <T> generic in the method, not in the class definition.

So this worked:

public class QuickSortArray  {
    public static <T extends Comparable> void quickSort(T[] array, int bottom, int top){
//do it
}

}

Of course, after reading the answers above I realized that this would be an acceptable alternative without using a generic class:

public static void quickSort(Comparable[] array, int bottom, int top){
//do it
}

How to launch PowerShell (not a script) from the command line

Set the default console colors and fonts:

http://poshcode.org/2220
From Windows PowerShell Cookbook (O'Reilly)
by Lee Holmes (http://www.leeholmes.com/guide)

Set-StrictMode -Version Latest

Push-Location
Set-Location HKCU:\Console
New-Item '.\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe'
Set-Location '.\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe'

New-ItemProperty . ColorTable00 -type DWORD -value 0x00562401
New-ItemProperty . ColorTable07 -type DWORD -value 0x00f0edee
New-ItemProperty . FaceName -type STRING -value "Lucida Console"
New-ItemProperty . FontFamily -type DWORD -value 0x00000036
New-ItemProperty . FontSize -type DWORD -value 0x000c0000
New-ItemProperty . FontWeight -type DWORD -value 0x00000190
New-ItemProperty . HistoryNoDup -type DWORD -value 0x00000000
New-ItemProperty . QuickEdit -type DWORD -value 0x00000001
New-ItemProperty . ScreenBufferSize -type DWORD -value 0x0bb80078
New-ItemProperty . WindowSize -type DWORD -value 0x00320078
Pop-Location

how to set radio option checked onload with jQuery

Say you had radio buttons like these, for example:

<input type='radio' name='gender' value='Male'>
<input type='radio' name='gender' value='Female'>

And you wanted to check the one with a value of "Male" onload if no radio is checked:

$(function() {
    var $radios = $('input:radio[name=gender]');
    if($radios.is(':checked') === false) {
        $radios.filter('[value=Male]').prop('checked', true);
    }
});

How to fix corrupted git repository?

In my case, I was creating the repository from source code already in my pc and that error appeared. I deleted the .git folder and did everything again and it worked :)

How to check if element has any children in Javascript?

As slashnick & bobince mention, hasChildNodes() will return true for whitespace (text nodes). However, I didn't want this behaviour, and this worked for me :)

element.getElementsByTagName('*').length > 0

Edit: for the same functionality, this is a better solution:

 element.children.length > 0

children[] is a subset of childNodes[], containing elements only.

Compatibility

Import/Index a JSON file into Elasticsearch

I wrote some code to expose the Elasticsearch API via a Filesystem API.

It is good idea for clear export/import of data for example.

I created prototype elasticdriver. It is based on FUSE

demo

Creating and Update Laravel Eloquent

If you need the same functionality using the DB, in Laravel >= 5.5 you can use:

DB::table('table_name')->updateOrInsert($attributes, $values);

or the shorthand version when $attributes and $values are the same:

DB::table('table_name')->updateOrInsert($values);

How to replace ${} placeholders in a text file?

Here is a way to get the shell to do the substitution for you, as if the contents of the file were instead typed between double quotes.

Using the example of template.txt with contents:

The number is ${i}
The word is ${word}

The following line will cause the shell to interpolate the contents of template.txt and write the result to standard out.

i='1' word='dog' sh -c 'echo "'"$(cat template.txt)"'"'

Explanation:

  • i and word are passed as environment variables scopped to the execution of sh.
  • sh executes the contents of the string it is passed.
  • Strings written next to one another become one string, that string is:
    • 'echo "' + "$(cat template.txt)" + '"'
  • Since the substitution is between ", "$(cat template.txt)" becomes the output of cat template.txt.
  • So the command executed by sh -c becomes:
    • echo "The number is ${i}\nThe word is ${word}",
    • where i and word are the specified environment variables.

Spring Data JPA Update @Query not updating?

I finally understood what was going on.

When creating an integration test on a statement saving an object, it is recommended to flush the entity manager so as to avoid any false negative, that is, to avoid a test running fine but whose operation would fail when run in production. Indeed, the test may run fine simply because the first level cache is not flushed and no writing hits the database. To avoid this false negative integration test use an explicit flush in the test body. Note that the production code should never need to use any explicit flush as it is the role of the ORM to decide when to flush.

When creating an integration test on an update statement, it may be necessary to clear the entity manager so as to reload the first level cache. Indeed, an update statement completely bypasses the first level cache and writes directly to the database. The first level cache is then out of sync and reflects the old value of the updated object. To avoid this stale state of the object, use an explicit clear in the test body. Note that the production code should never need to use any explicit clear as it is the role of the ORM to decide when to clear.

My test now works just fine.

Permissions for /var/www/html

You just need 775 for /var/www/html as long as you are logging in as myuser. The 7 octal in the middle (which is for "group" acl) ensures that the group has permission to read/write/execute. As long as you belong to the group that owns the files, "myuser" should be able to write to them. You may need to give group permissions to all the files in the docuemnt root, though:

chmod -R g+w /var/www/html

Generate random string/characters in JavaScript

I think this will work for you:

_x000D_
_x000D_
function makeid(length) {_x000D_
   var result           = '';_x000D_
   var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';_x000D_
   var charactersLength = characters.length;_x000D_
   for ( var i = 0; i < length; i++ ) {_x000D_
      result += characters.charAt(Math.floor(Math.random() * charactersLength));_x000D_
   }_x000D_
   return result;_x000D_
}_x000D_
_x000D_
console.log(makeid(5));
_x000D_
_x000D_
_x000D_

Javascript "Not a Constructor" Exception while creating objects

For me it was the differences between import and require on ES6.

E.g.

// processor.js
class Processor {

}

export default Processor

//index.js
const Processor = require('./processor');
const processor = new Processor() //fails with the error

import Processor from './processor'
const processor = new Processor() // succeeds

Emulate/Simulate iOS in Linux

  1. Run Ripple emulator(retired as of 2015-12-06) on Chrome
  2. Run iPadian on WineHQ
  3. Run QMole on Linux or Android
  4. Run XCode on PureDarwin

Tomcat view catalina.out log file

If you are in the home directory first move to apache tomcat use below command

cd apache-tomcat/

then move to logs

cd logs/

then open the catelina.out use the below command

tail -f catalina.out

localhost refused to connect Error in visual studio

My problem turned out to be a property which called itself:

enter image description here

Once I fixed this, the misleading connection error message disappeared.

Pass variable to function in jquery AJAX success callback

You can also use indexValue attribute for passing multiple parameters via object:

var someData = "hello";

jQuery.ajax({
    url: "http://maps.google.com/maps/api/js?v=3",
    indexValue: {param1:someData, param2:"Other data 2", param3: "Other data 3"},
    dataType: "script"
}).done(function() {
    console.log(this.indexValue.param1);
    console.log(this.indexValue.param2);
    console.log(this.indexValue.param3);
}); 

Javascript - check array for value

Try this:

// this will fix old browsers
if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(value) {
    for (var i = 0; i < this.length; i++) {
      if (this[i] === value) {
        return i;
      }
    }

    return -1;
  }
}

// example
if ([1, 2, 3].indexOf(2) != -1) {
  // yay!
}

Pointer-to-pointer dynamic two-dimensional array

this can be done this way

  1. I have used Operator Overloading
  2. Overloaded Assignment
  3. Overloaded Copy Constructor

    /*
     * Soumil Nitin SHah
     * Github: https://github.com/soumilshah1995
     */
    
    #include <iostream>
    using namespace std;
            class Matrix{
    
    public:
        /*
         * Declare the Row and Column
         *
         */
        int r_size;
        int c_size;
        int **arr;
    
    public:
        /*
         * Constructor and Destructor
         */
    
        Matrix(int r_size, int c_size):r_size{r_size},c_size{c_size}
        {
            arr = new int*[r_size];
            // This Creates a 2-D Pointers
            for (int i=0 ;i < r_size; i++)
            {
                arr[i] = new int[c_size];
            }
    
            // Initialize all the Vector to 0 initially
            for (int row=0; row<r_size; row ++)
            {
                for (int column=0; column < c_size; column ++)
                {
                    arr[row][column] = 0;
                }
            }
            std::cout << "Constructor -- creating Array Size ::" << r_size << " " << c_size << endl;
        }
    
        ~Matrix()
        {
            std::cout << "Destructpr  -- Deleting  Array Size ::" << r_size <<" " << c_size << endl;
    
        }
    
        Matrix(const Matrix &source):Matrix(source.r_size, source.c_size)
    
        {
            for (int row=0; row<source.r_size; row ++)
            {
                for (int column=0; column < source.c_size; column ++)
                {
                    arr[row][column] = source.arr[row][column];
                }
            }
    
            cout << "Copy Constructor " << endl;
        }
    
    
    public:
        /*
         * Operator Overloading
         */
    
        friend std::ostream &operator<<(std::ostream &os, Matrix & rhs)
        {
            int rowCounter = 0;
            int columnCOUNTER = 0;
            int globalCounter = 0;
    
            for (int row =0; row < rhs.r_size; row ++)
            {
                for (int column=0; column < rhs.c_size ; column++)
                {
                    globalCounter = globalCounter + 1;
                }
                rowCounter = rowCounter + 1;
            }
    
    
            os << "Total There are " << globalCounter << " Elements" << endl;
            os << "Array Elements are as follow -------" << endl;
            os << "\n";
    
            for (int row =0; row < rhs.r_size; row ++)
            {
                for (int column=0; column < rhs.c_size ; column++)
                {
                    os << rhs.arr[row][column] << " ";
                }
            os <<"\n";
            }
            return os;
        }
    
        void operator()(int row, int column , int Data)
        {
            arr[row][column] = Data;
        }
    
        int &operator()(int row, int column)
        {
            return arr[row][column];
        }
    
        Matrix &operator=(Matrix &rhs)
                {
                    cout << "Assingment Operator called " << endl;cout <<"\n";
                    if(this == &rhs)
                    {
                        return *this;
                    } else
                        {
                        delete [] arr;
    
                            arr = new int*[r_size];
                            // This Creates a 2-D Pointers
                            for (int i=0 ;i < r_size; i++)
                            {
                                arr[i] = new int[c_size];
                            }
    
                            // Initialize all the Vector to 0 initially
                            for (int row=0; row<r_size; row ++)
                            {
                                for (int column=0; column < c_size; column ++)
                                {
                                    arr[row][column] = rhs.arr[row][column];
                                }
                            }
    
                            return *this;
                        }
    
                }
    
    };
    
                int main()
    {
    
        Matrix m1(3,3);         // Initialize Matrix 3x3
    
        cout << m1;cout << "\n";
    
        m1(0,0,1);
        m1(0,1,2);
        m1(0,2,3);
    
        m1(1,0,4);
        m1(1,1,5);
        m1(1,2,6);
    
        m1(2,0,7);
        m1(2,1,8);
        m1(2,2,9);
    
        cout << m1;cout <<"\n";             // print Matrix
        cout << "Element at Position (1,2) : " << m1(1,2) << endl;
    
        Matrix m2(3,3);
        m2 = m1;
        cout << m2;cout <<"\n";
    
        print(m2);
    
        return 0;
    }
    

C - function inside struct

This will only work in C++. Functions in structs are not a feature of C.

Same goes for your client.AddClient(); call ... this is a call for a member function, which is object oriented programming, i.e. C++.

Convert your source to a .cpp file and make sure you are compiling accordingly.

If you need to stick to C, the code below is (sort of) the equivalent:

typedef struct client_t client_t, *pno;
struct client_t
{
        pid_t pid;
        char password[TAM_MAX]; // -> 50 chars
        pno next;

};


pno AddClient(pno *pclient) 
{
    /* code */
}


int main()
{

    client_t client;

    //code ..

    AddClient(client);

}

Removing the remembered login and password list in SQL Server Management Studio

As gluecks pointed out, no more SqlStudio.bin in Microsoft SQL Server Management Studio 18. I also found this UserSettings.xml in C:\Users\userName\AppData\Roaming\Microsoft\SQL Server Management Studio\18.0. But removing the <Element> containing the credential seems not working, it comes right back on the xml file, if I close and re-open it again.

Turns out, you need to close the SQL Server Management Studio first, then edit the UserSettings.xml file in your favorite editor, e.g. Visual Studio Code. I guess it's cached somewhere in SSMS besides this xml file?! And it's not on Control Panel\All Control Panel Items\Credential Manager\Windows Credentials.

Making view resize to its parent when added with addSubview

Just copy the parent view's frame to the child-view then add it. After that autoresizing will work. Actually you should only copy the size CGRectMake(0, 0, parentView.frame.size.width, parentView.frame.size.height)

childView.frame = CGRectMake(0, 0, parentView.frame.size.width, parentView.frame.size.height);
[parentView addSubview:childView];

The iOS Simulator deployment targets is set to 7.0, but the range of supported deployment target version for this platform is 8.0 to 12.1

If anyone came here from react native issue, just delete the /build folder and type react-native run ios

How to return a resolved promise from an AngularJS Service using $q?

To return a resolved promise, you can use:

return $q.defer().resolve();

If you need to resolve something or return data:

return $q.defer().resolve(function(){

    var data;
    return data;

});

How can I open a .tex file?

I don't know what the .tex extension on your file means. If we are saying that it is any file with any extension you have several methods of reading it.

I have to assume you are using windows because you have mentioned notepad++.

  1. Use notepad++. Right click on the file and choose "edit with notepad++"

  2. Use notepad Change the filename extension to .txt and double click the file.

  3. Use command prompt. Open the folder that your file is in. Hold down shift and right click. (not on the file, but in the folder that the file is in.) Choose "open command window here" from the command prompt type: "type filename.tex"

If these don't work, I would need more detail as to how they are not working. Errors that you may be getting or what you may expect to be in the file might help.

Maven build debug in Eclipse

probleme : unit test result are not the same runing with eclipse and maven due ti order of library used by eclipse and maven. In my case the test was success with maven but i want to debug my unit test using eclipse, so the most easy way to debug unit test class with eclipse and runing maven is :

1) mvn -Dtest=MySuperClassTest -Dmaven.surefire.debug test ==> it will listen to the 5005 port (default port)

2) Go to eclipse, open a debug configuration, add a new java remote application and change the port to 5005 and debug

3) of course you must add break point somewhere in the class that you want to debug

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test

I tried following instructions given in most of the comments on this thread, including the chosen answer but the error persisted. I did some research and found this page that gave a solution that helped me out (okay, with some guessing though of my part).

So what I did is that I replaced the version number in the maven surefire plugin as follows: <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.0.0-M1</version>

I hope this helps!

How to detect iPhone 5 (widescreen devices)?

Here is the correct test of the device, without depending on the orientation

- (BOOL)isIPhone5
{
    CGSize size = [[UIScreen mainScreen] bounds].size;
    if (MIN(size.width,size.height) == 320 && MAX(size.width,size.height == 568)) {
        return YES;
    }
    return NO;
}

How can I match multiple occurrences with a regex in JavaScript similar to PHP's preg_match_all()?

To capture several parameters using the same name, I modified the while loop in Tomalak's method like this:

  while (match = re.exec(url)) {
    var pName = decode(match[1]);
    var pValue = decode(match[2]);
    params[pName] ? params[pName].push(pValue) : params[pName] = [pValue];
  }

input: ?firstname=george&lastname=bush&firstname=bill&lastname=clinton

returns: {firstname : ["george", "bill"], lastname : ["bush", "clinton"]}

What is the best way to programmatically detect porn images?

A graduate student from National Cheng Kung University in Taiwan did a research on this subject in 2004. He was able to achieve success rate of 89.79% in detecting nude pictures downloaded from the Internet. Here is the link to his thesis: The Study on Naked People Image Detection Based on Skin Color
It's in Chinese therefore you may need a translator in case you can't read it.

How to embed images in html email

This is the code I'm using to embed images into HTML mail and PDF documents.

<?php
$logo_path = 'http://localhost/img/logo.jpg';
$type = pathinfo($logo_path, PATHINFO_EXTENSION);
$image_contents = file_get_contents($logo_path);
$image64 = 'data:image/' . $type . ';base64,' . base64_encode($image_contents);

echo '<img src="' . $image64 .'" />';
?>

Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8)

Expanding on retrography's answer..: I had this same problem even when using LocalDate and not LocalDateTime. The issue was that I had created my DateTimeFormatter using .withResolverStyle(ResolverStyle.STRICT);, so I had to use date pattern uuuuMMdd instead of yyyyMMdd (i.e. "year" instead of "year-of-era")!

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
  .parseStrict()
  .appendPattern("uuuuMMdd")
  .toFormatter()
  .withResolverStyle(ResolverStyle.STRICT);
LocalDate dt = LocalDate.parse("20140218", formatter);

(This solution was originally a comment to retrography's answer, but I was encouraged to post it as a stand-alone answer because it apparently works really well for many people.)

Get file content from URL?

Don't forget: to get HTTPS contents, your OPENSSL extension should be enabled in your php.ini. (how to get contents of site use HTTPS)

How do I get the YouTube video ID from a URL?

Here's a radically different solution.

You could request the JSON oEmbed document from 'https://www.youtube.com/oembed?format=json&url=' . rawurlencode($url) and then thumbnail_url has a fixed format, match it with a PCRE pattern like https://i.ytimg.com/vi/([^/]+), the first group is the YouTube ID.

Is it possible to hide the cursor in a webpage using CSS or Javascript?

If you want to do it in CSS:

#ID { cursor: none !important; }

Java Minimum and Maximum values in Array

Sum, Maximum and Minimum value of an Array in One Line

 public static void getMinMaxByArraysMethods(int[] givenArray){

       //Sum of Array in One Line 
       long sumofArray =  Arrays.stream(givenArray).sum();

       //get Minimum Value in an array in One Line
        int minimumValue = Arrays.stream(givenArray).min().getAsInt();

        //Get Maximum Value of an Array in One Line
        int MaxmumValue =  Arrays.stream(givenArray).max().getAsInt();

    }

Ruby capitalize every word first letter

try this:

puts 'one TWO three foUR'.split.map(&:capitalize).join(' ')

#=> One Two Three Four

or

puts 'one TWO three foUR'.split.map(&:capitalize)*' '

Importing Maven project into Eclipse

Since Eclipse Neon which contains Eclipse Maven Integration (m2e) 1.7, the preferred way is one of the following ways:

  • File > Projects from File System... - This works for Eclipse projects (containing the file .project) as well as for non-Eclipse projects that only contain the file pom.xml.
  • If importing from a Git repository, in the Git Repositories view right-click the repository node, one folder or multiple selected folders in the Working Tree and choose Import Projects.... This opens the same dialog, but you don't have to select the directory.

How do you add an action to a button programmatically in xcode

UIButton *btnNotification=[UIButton buttonWithType:UIButtonTypeCustom];
btnNotification.frame=CGRectMake(130,80,120,40);
btnNotification.backgroundColor=[UIColor greenColor];
[btnNotification setTitle:@"create Notification" forState:UIControlStateNormal];
[btnNotification addTarget:self action:@selector(btnClicked) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btnNotification];


}

-(void)btnClicked
{
    // Here You can write functionality 

}

ng-if, not equal to?

I don't like "hacks" but in a quick pinch for a deadline I have done this

<li ng-if="edit === false && filtered.length === 0">
    <p ng-if="group.title != 'Dispatcher News'" style="padding: 5px">No links in group.</p>
</li>

Yes, I have another inner nested ng-if, I just didn't like too many conditions on one line.

Calling class staticmethod within the class body?

This is due to staticmethod being a descriptor and requires a class-level attribute fetch to exercise the descriptor protocol and get the true callable.

From the source code:

It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()); the instance is ignored except for its class.

But not directly from inside the class while it is being defined.

But as one commenter mentioned, this is not really a "Pythonic" design at all. Just use a module level function instead.

What does a (+) sign mean in an Oracle SQL WHERE clause?

This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.

In standard SQL one would write:

SELECT t0.foo, t1.bar
  FROM FIRST_TABLE t0
 RIGHT OUTER JOIN SECOND_TABLE t1;

Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :

Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]

struct in class

I declared class B inside class A, how do I access it?

Just because you declare your struct B inside class A does not mean that an instance of class A automatically has the properties of struct B as members, nor does it mean that it automatically has an instance of struct B as a member.

There is no true relation between the two classes (A and B), besides scoping.


struct A { 
  struct B { 
    int v;
  };  

  B inner_object;
};

int
main (int argc, char *argv[]) {
  A object;
    object.inner_object.v = 123;
}

How do I convert a file path to a URL in ASP.NET

The problem with all these answers is that they do not take virtual directories into account.

Consider:

Site named "tempuri.com/" rooted at c:\domains\site
virtual directory "~/files" at c:\data\files
virtual directory "~/files/vip" at c:\data\VIPcust\files

So:

Server.MapPath("~/files/vip/readme.txt") 
  = "c:\data\VIPcust\files\readme.txt"

But there is no way to do this:

MagicResolve("c:\data\VIPcust\files\readme.txt") 
   = "http://tempuri.com/files/vip/readme.txt"

because there is no way to get a complete list of virtual directories.

How do you determine what SQL Tables have an identity column programmatically

Another potential way to do this for SQL Server, which has less reliance on the system tables (which are subject to change, version to version) is to use the INFORMATION_SCHEMA views:

select COLUMN_NAME, TABLE_NAME
from INFORMATION_SCHEMA.COLUMNS
where COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
order by TABLE_NAME 

ORA-01830: date format picture ends before converting entire input string / Select sum where date query

What you have written in your sql string is a Timestamp not Date. You must convert it to Date or change type of database field to Timestamp for it to be seen correctly.

How to add lines to end of file on Linux

The easiest way is to redirect the output of the echo by >>:

echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile

What is the use of <<<EOD in PHP?

That is not HTML, but PHP. It is called the HEREDOC string method, and is an alternative to using quotes for writing multiline strings.

The HTML in your example will be:

    <tr>
      <td>TEST</td>
    </tr>

Read the PHP documentation that explains it.

#1064 -You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version

Remove the comma

receipt int(10),

And also AUTO INCREMENT should be a KEY

double datatype also requires the precision of decimal places so right syntax is double(10,2)

Truncate Decimal number not Round Off

What format are you wanting the output?

If you're happy with a string then consider the following C# code:

double num = 3.12345;
num.ToString("G3");

The result will be "3.12".

This link might be of use if you're using .NET. http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

I hope that helps....but unless you identify than language you are using and the format in which you want the output it is difficult to suggest an appropriate solution.

Convert JsonNode into POJO

This should do the trick:

mapper.readValue(fileReader, MyClass.class);

I say should because I'm using that with a String, not a BufferedReader but it should still work.

Here's my code:

String inputString = // I grab my string here
MySessionClass sessionObject;
try {
    ObjectMapper objectMapper = new ObjectMapper();
    sessionObject = objectMapper.readValue(inputString, MySessionClass.class);

Here's the official documentation for that call: http://jackson.codehaus.org/1.7.9/javadoc/org/codehaus/jackson/map/ObjectMapper.html#readValue(java.lang.String, java.lang.Class)

You can also define a custom deserializer when you instantiate the ObjectMapper: http://wiki.fasterxml.com/JacksonHowToCustomDeserializers

Edit: I just remembered something else. If your object coming in has more properties than the POJO has and you just want to ignore the extras you'll want to set this:

    objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

Or you'll get an error that it can't find the property to set into.

Getting error "No such module" using Xcode, but the framework is there

In rare cases this error might be fixed by setting proper platform here [ProjectNavigator]->[Project]->[Target]-> (Architectures) BaseSDK

enter image description here

When creating a framework I've chosen accidentally wrong template (as I was creating macOS framework previously) because it was set to like my previous choice. When adding a target it is easy to miss out configuring platform so double check that.

enter image description here

Python: converting a list of dictionaries to json

import json

list = [{'id': 123, 'data': 'qwerty', 'indices': [1,10]}, {'id': 345, 'data': 'mnbvc', 'indices': [2,11]}]

Write to json File:

with open('/home/ubuntu/test.json', 'w') as fout:
    json.dump(list , fout)

Read Json file:

with open(r"/home/ubuntu/test.json", "r") as read_file:
    data = json.load(read_file)
print(data)
#list = [{'id': 123, 'data': 'qwerty', 'indices': [1,10]}, {'id': 345, 'data': 'mnbvc', 'indices': [2,11]}]

Reading a registry key in C#

You can use the following to get where the registry thinks it's installed:

(string)Registry.LocalMachine.GetValue(@"SOFTWARE\MyApplication\AppPath",
   "Installed", null);

Or you can use the following to find out where the application is actually being launched from:

System.Windows.Forms.Application.StartupPath

The latter is more reliable than the former if you're trying to use the .exe location as a relative path to find related files. The user could easily move things around after the install and still have the app work fine because .NET apps aren't so dependent upon the registry.

Using StartupPath, you could even do something clever like have your app update the registry entries at run time instead of crashing miserably due to missing/wrong/corrupted entries.

And be sure to look at the app settings functionality as storage for values rather than the registry (Properties.Settings.Default.mySettingEtc). You can read/write settings for the app and/or the user levels that get saved as simple MyApp.exe.config files in standard locations. A nice blast from the past (good old Win 3.1/DOS days) to have the application install/delete be a simple copy/delete of a folder structure or two rather than some convoluted, arcane install/uninstall routine that leaves all kinds of garbage in the registry and sprinkled all over the hard drive.

Run MySQLDump without Locking Tables

    mysqldump -uuid -ppwd --skip-opt --single-transaction --max_allowed_packet=1G -q db |   mysql -u root --password=xxx -h localhost db

What is the difference between display: inline and display: inline-block?

A visual answer

Imagine a <span> element inside a <div>. If you give the <span> element a height of 100px and a red border for example, it will look like this with

display: inline

display: inline

display: inline-block

display: inline-block

display: block

enter image description here

Code: http://jsfiddle.net/Mta2b/

Elements with display:inline-block are like display:inline elements, but they can have a width and a height. That means that you can use an inline-block element as a block while flowing it within text or other elements.

Difference of supported styles as summary:

  • inline: only margin-left, margin-right, padding-left, padding-right
  • inline-block: margin, padding, height, width

Querying Datatable with where condition

You can do it with Linq, as mamoo showed, but the oldies are good too:

var filteredDataTable = dt.Select(@"EmpId > 2
    AND (EmpName <> 'abc' OR EmpName <> 'xyz')
    AND EmpName like '%il%'" );

Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0

After much pain, googling and hair pulling, I ended up uninstalling MVC 4 using nuget, deleting all references to MVC, razor and infrastructure from the web config, deleting the dlls from the bin folder - then using nuget to reinstall everything. It took less time then trying to figure out why the dlls did not match.

How to activate an Anaconda environment

I've tried to activate env from Jenkins job (in bash) with conda activate base and it failed, so after many tries, this one worked for me (CentOS 7) :

source /opt/anaconda2/bin/activate base

Display filename before matching line

No trick necessary.

grep --with-filename 'pattern' file

With line numbers:

grep -n --with-filename 'pattern' file

post checkbox value

In your form tag, rather than

name="booking.php"

use

action="booking.php"

And then, in booking.php use

$checkValue = $_POST['booking-check'];

Also, you'll need a submit button in there

<input type='submit'>

Get length of array?

Length of an array:

UBound(columns)-LBound(columns)+1

UBound alone is not the best method for getting the length of every array as arrays in VBA can start at different indexes, e.g Dim arr(2 to 10)

UBound will return correct results only if the array is 1-based (starts indexing at 1 e.g. Dim arr(1 to 10). It will return wrong results in any other circumstance e.g. Dim arr(10)

More on the VBA Array in this VBA Array tutorial.

Android: Unable to add window. Permission denied for this window type

if you use apiLevel >= 19, don't use

WindowManager.LayoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT 

which gets the following error:

android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRootImpl$W@40ec8528 -- permission denied for this window type

Use this instead:

LayoutParams.TYPE_TOAST or TYPE_APPLICATION_PANEL

Redirect From Action Filter Attribute

Set filterContext.Result

With the route name:

filterContext.Result = new RedirectToRouteResult("SystemLogin", routeValues);

You can also do something like:

filterContext.Result = new ViewResult
{
    ViewName = SharedViews.SessionLost,
    ViewData = filterContext.Controller.ViewData
};

If you want to use RedirectToAction:

You could make a public RedirectToAction method on your controller (preferably on its base controller) that simply calls the protected RedirectToAction from System.Web.Mvc.Controller. Adding this method allows for a public call to your RedirectToAction from the filter.

public new RedirectToRouteResult RedirectToAction(string action, string controller)
{
    return base.RedirectToAction(action, controller);
}

Then your filter would look something like:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    var controller = (SomeControllerBase) filterContext.Controller;
    filterContext.Result = controller.RedirectToAction("index", "home");
}

Difference between HashMap and Map in Java..?

Map is an interface, i.e. an abstract "thing" that defines how something can be used. HashMap is an implementation of that interface.

Error: JavaFX runtime components are missing, and are required to run this application with JDK 11

This worked for me:

File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)

clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.

Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.

then in:

Run >> Edit Configurations

Add this line to VM Options:

--module-path /path/to/JavaFX/lib --add-modules=javafx.controls

(oh and don't forget to set the SDK)

Semi-transparent color layer over background-image?

I know this is a really old thread, but it shows up at the top in Google, so here's another option.

This one is pure CSS, and doesn't require any extra HTML.

box-shadow: inset 0 0 0 1000px rgba(0,0,0,.2);

There are a surprising number of uses for the box-shadow feature.

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

It also possible to check tab activity by document.hidden property

Possible solution

document.location = 'app://deep-link';

setInterval( function(){
  if (!document.hidden) {
    document.location = 'https://app.store.link';
  }
}, 1000);

But seems like this not works in Safari

How to check if a function exists on a SQL database

This is what SSMS uses when you script using the DROP and CREATE option

IF EXISTS (SELECT *
           FROM   sys.objects
           WHERE  object_id = OBJECT_ID(N'[dbo].[foo]')
                  AND type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' ))
  DROP FUNCTION [dbo].[foo]

GO 

This approach to deploying changes means that you need to recreate all permissions on the object so you might consider ALTER-ing if Exists instead.

How can I send large messages with Kafka (over 15MB)?

You need to adjust three (or four) properties:

  • Consumer side:fetch.message.max.bytes - this will determine the largest size of a message that can be fetched by the consumer.
  • Broker side: replica.fetch.max.bytes - this will allow for the replicas in the brokers to send messages within the cluster and make sure the messages are replicated correctly. If this is too small, then the message will never be replicated, and therefore, the consumer will never see the message because the message will never be committed (fully replicated).
  • Broker side: message.max.bytes - this is the largest size of the message that can be received by the broker from a producer.
  • Broker side (per topic): max.message.bytes - this is the largest size of the message the broker will allow to be appended to the topic. This size is validated pre-compression. (Defaults to broker's message.max.bytes.)

I found out the hard way about number 2 - you don't get ANY exceptions, messages, or warnings from Kafka, so be sure to consider this when you are sending large messages.

What is the most efficient way of finding all the factors of a number in Python?

I reckon this is the simplest way to do that:

    x = 23

    i = 1
    while i <= x:
      if x % i == 0:
        print("factor: %s"% i)
      i += 1

Get yesterday's date in bash on Linux, DST-safe

date -d "yesterday" '+%Y-%m-%d'

To use this later:

date=$(date -d "yesterday" '+%Y-%m-%d')

Angular 2 Date Input not binding to date value

use DatePipe

> // ts file

import { DatePipe } from '@angular/common';

@Component({
....
providers:[DatePipe]
})

export class FormComponent {

constructor(private datePipe : DatePipe){}

    demoUser = new User(0, '', '', '', '', this.datePipe.transform(new Date(), 'yyyy-MM-dd'), '', 0, [], []);  
}

How to filter an array/object by checking multiple values

You can use .filter() method of the Array object:

var filtered = workItems.filter(function(element) {
   // Create an array using `.split()` method
   var cats = element.category.split(' ');

   // Filter the returned array based on specified filters
   // If the length of the returned filtered array is equal to
   // length of the filters array the element should be returned  
   return cats.filter(function(cat) {
       return filtersArray.indexOf(cat) > -1;
   }).length === filtersArray.length;
});

http://jsfiddle.net/6RBnB/

Some old browsers like IE8 doesn't support .filter() method of the Array object, if you are using jQuery you can use .filter() method of jQuery object.

jQuery version:

var filtered = $(workItems).filter(function(i, element) {
   var cats = element.category.split(' ');

    return $(cats).filter(function(_, cat) {
       return $.inArray(cat, filtersArray) > -1;
    }).length === filtersArray.length;
});

Java: Reading a file into an array

Here is some example code to help you get started:

package com.acme;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileArrayProvider {

    public String[] readLines(String filename) throws IOException {
        FileReader fileReader = new FileReader(filename);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        List<String> lines = new ArrayList<String>();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            lines.add(line);
        }
        bufferedReader.close();
        return lines.toArray(new String[lines.size()]);
    }
}

And an example unit test:

package com.acme;

import java.io.IOException;

import org.junit.Test;

public class FileArrayProviderTest {

    @Test
    public void testFileArrayProvider() throws IOException {
        FileArrayProvider fap = new FileArrayProvider();
        String[] lines = fap
                .readLines("src/main/java/com/acme/FileArrayProvider.java");
        for (String line : lines) {
            System.out.println(line);
        }
    }
}

Hope this helps.

Accessing an array out of bounds gives no error, why?

libstdc++, which is part of gcc, has a special debug mode for error checking. It is enabled by compiler flag -D_GLIBCXX_DEBUG. Among other things it does bounds checking for std::vector at the cost of performance. Here is online demo with recent version of gcc.

So actually you can do bounds checking with libstdc++ debug mode but you should do it only when testing because it costs notable performance compared to normal libstdc++ mode.

Has Windows 7 Fixed the 255 Character File Path Limit?

@Cort3z: if the problem is still present, this hotfix: https://support.microsoft.com/en-us/kb/2891362 should solve it (from win7 sp1 to 8.1)

In MySQL, how to copy the content of one table to another table within the same database?

This worked for me. You can make the SELECT statement more complex, with WHERE and LIMIT clauses.

First duplicate your large table (without the data), run the following query, and then truncate the larger table.

INSERT INTO table_small (SELECT * FROM table_large WHERE column = 'value' LIMIT 100)

Super simple. :-)

PHP - warning - Undefined property: stdClass - fix?

Error control operator

In case the warning is expected you can use the error control operator @ to suppress thrown messages.

$role_arr = getRole(@$response->records);

While this reduces clutter in your code you should use it with caution as it may make debugging future errors harder. An example where using @ may be useful is when creating an object from user input and running it through a validation method before using it in further logic.


Null Coalesce Operator

Another alternative is using the isset_ternary operator ??. This allows you to avoid warnings and assign default value in a short one line fashion.

$role_arr = getRole($response->records ?? null);

How to align a div inside td element using CSS class

I cannot help you much without a small (possibly reduced) snippit of the problem. If the problem is what I think it is then it's because a div by default takes up 100% width, and as such cannot be aligned.

What you may be after is to align the inline elements inside the div (such as text) with text-align:center; otherwise you may consider setting the div to display:inline-block;

If you do go down the inline-block route then you may have to consider my favorite IE hack.

width:100px;
display:inline-block;
zoom:1; //IE only
*display:inline; //IE only

Happy Coding :)

How do you view ALL text from an ntext or nvarchar(max) in SSMS?

Alternative 1: Right Click to copy cell and Paste into Text Editor (hopefully with utf-8 support)

Alternative 2: Right click and export to CSV File

Alternative 3: Use SUBSTRING function to visualize parts of the column. Example:

SELECT SUBSTRING(fileXml,2200,200) FROM mytable WHERE id=123456

How to convert Java String to JSON Object

Your json -

{
    "title":"Free Music Archive - Genres",
    "message":"",
    "errors":[
    ],
    "total":"163",
    "total_pages":82,
    "page":1,
    "limit":"2",
    "dataset":[
    {
    "genre_id":"1",
    "genre_parent_id":"38",
    "genre_title":"Avant-Garde",
    "genre_handle":"Avant-Garde",
    "genre_color":"#006666"
    },
    {
    "genre_id":"2",
    "genre_parent_id":null,
    "genre_title":"International",
    "genre_handle":"International",
    "genre_color":"#CC3300"
    }
    ]
    }

Using the JSON library from json.org -

JSONObject o = new JSONObject(jsonString);

NOTE:

The following information will be helpful to you - json.org.

UPDATE:

import org.json.JSONObject;
 //Other lines of code
URL seatURL = new URL("http://freemusicarchive.org/
 api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=2");
 //Return the JSON Response from the API
 BufferedReader br = new BufferedReader(new         
 InputStreamReader(seatURL.openStream(),
 Charset.forName("UTF-8")));
 String readAPIResponse = " ";
 StringBuilder jsonString = new StringBuilder();
 while((readAPIResponse = br.readLine()) != null){
   jsonString.append(readAPIResponse);
 }
 JSONObject jsonObj = new JSONObject(jsonString.toString());
 System.out.println(jsonString);
 System.out.println("---------------------------");
 System.out.println(jsonObj);

How to get Domain name from URL using jquery..?

While pure JavaScript is sufficient here, I still prefer the jQuery approach. After all, the ask was to get the hostname using jQuery.

var hostName = $(location).attr('hostname');      // www.example.com

Round a divided number in Bash

To do rounding up in truncating arithmetic, simply add (denom-1) to the numerator.

Example, rounding down:

N/2
M/5
K/16

Example, rounding up:

(N+1)/2
(M+4)/5
(K+15)/16

To do round-to-nearest, add (denom/2) to the numerator (halves will round up):

(N+1)/2
(M+2)/5
(K+8)/16

anchor jumping by using javascript

You can get the coordinate of the target element and set the scroll position to it. But this is so complicated.

Here is a lazier way to do that:

function jump(h){
    var url = location.href;               //Save down the URL without hash.
    location.href = "#"+h;                 //Go to the target element.
    history.replaceState(null,null,url);   //Don't like hashes. Changing it back.
}

This uses replaceState to manipulate the url. If you also want support for IE, then you will have to do it the complicated way:

function jump(h){
    var top = document.getElementById(h).offsetTop; //Getting Y of target element
    window.scrollTo(0, top);                        //Go there directly or some transition
}?

Demo: http://jsfiddle.net/DerekL/rEpPA/
Another one w/ transition: http://jsfiddle.net/DerekL/x3edvp4t/

You can also use .scrollIntoView:

document.getElementById(h).scrollIntoView();   //Even IE6 supports this

(Well I lied. It's not complicated at all.)

Color picker utility (color pipette) in Ubuntu

I recommend GPick:

sudo apt-get install gpick

Applications -> Graphics -> GPick

It has many more features than gcolor2 but is still extremely simple to use: click on one of the hex swatches, move your mouse around the screen over the colours you want to pick, then press the Space bar to add to your swatch list.

If that doesn't work, another way is to click-and-drag from the centre of the hexagon and release your mouse over the pixel that you want to sample. Then immediately hit Space to copy that color into the next swatch in rotation.

It also has a traditional colour picker (like gcolor2) in the bottom right-hand corner of the window to allow you to pick individual colours with magnification.

Visual Studio 2010 - recommended extensions

RockScroll (free) - Double-click on a word/symbol highlights all occurrences of that word/symbol. Also replaces the scroll bar with a preview of your code, with edit spots and "all occurences" lines highlighted.

Example of use: want to see whether a variable is used anywhere else in current source file? Double-click variable, look at scroll bar for any red highlights.

Border length smaller than div width?

I have case to have some bottom border between pictures in div container and the best one line code was - border-bottom-style: inset;

How to search for file names in Visual Studio?

In Visual Studio 2008 (and probably later), the free DevExpress CodeRush Xpress add-in supplies Ctrl+Alt+F, Quick File Navigation, which searches on an exact substring in the file name or on capital letters.

(Unrelated to this answer, but note the rather more useful, Quick Navigation, Ctrl+Shift+Q, which I would have liked to have known about before now :-) )

Compiling php with curl, where is curl installed?

None of these will allow you to compile PHP with cURL enabled.

In order to compile with cURL, you need libcurl header files (.h files). They are usually found in /usr/include/curl. They generally are bundled in a separate development package.

Per example, to install libcurl in Ubuntu:

sudo apt-get install libcurl4-gnutls-dev

Or CentOS:

sudo yum install curl-devel

Then you can just do:

./configure --with-curl # other options...

If you compile cURL manually, you can specify the path to the files without the lib or include suffix. (e.g.: /usr/local if cURL headers are in /usr/local/include/curl).

String comparison technique used by Python

A pure Python equivalent for string comparisons would be:

def less(string1, string2):
    # Compare character by character
    for idx in range(min(len(string1), len(string2))):
        # Get the "value" of the character
        ordinal1, ordinal2 = ord(string1[idx]), ord(string2[idx])
        # If the "value" is identical check the next characters
        if ordinal1 == ordinal2:
            continue
        # It's not equal so we're finished at this index and can evaluate which is smaller.
        else:
            return ordinal1 < ordinal2
    # We're out of characters and all were equal, so the result depends on the length
    # of the strings.
    return len(string1) < len(string2)

This function does the equivalent of the real method (Python 3.6 and Python 2.7) just a lot slower. Also note that the implementation isn't exactly "pythonic" and only works for < comparisons. It's just to illustrate how it works. I haven't checked if it works like Pythons comparison for combined unicode characters.

A more general variant would be:

from operator import lt, gt

def compare(string1, string2, less=True):
    op = lt if less else gt
    for char1, char2 in zip(string1, string2):
        ordinal1, ordinal2 = ord(char1), ord(char1)
        if ordinal1 == ordinal2:
            continue
        else:
            return op(ordinal1, ordinal2)
    return op(len(string1), len(string2))

How to capture the "virtual keyboard show/hide" event in Android?

You can also check for first DecorView's child bottom padding. It will be set to non-zero value when keyboard is shown.

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    View view = getRootView();
    if (view != null && (view = ((ViewGroup) view).getChildAt(0)) != null) {
        setKeyboardVisible(view.getPaddingBottom() > 0);
    }
    super.onLayout(changed, left, top, right, bottom);
}

Bootstrap 3 - How to load content in modal body via AJAX?

Check this SO answer out.

It looks like the only way is to provide the whole modal structure with your ajax response.

As you can check from the bootstrap source code, the load function is binded to the root element.

In case you can't modify the ajax response, a simple workaround could be an explicit call of the $(..).modal(..) plugin on your body element, even though it will probably break the show/hide functions of the root element.

Visual Studio 2013 License Product Key

I solved this, without having to completely reinstall Visual Studio 2013.

For those who may come across this in the future, the following steps worked for me:

  1. Run the ISO (or vs_professional.exe).
  2. If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3 "The product version that you are trying to set up is earlier than the version already installed on this computer."

    • Click the link for 'examine the log file' and look near the bottom of the log, for this line: Detected related bundle ... operation: Downgrade

    • open regedit.exe and do an Edit > Find... for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}. This was found in:

      HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}

    • Edit the BundleVersion value and change it to a lower version. I changed mine from 12.0.21005.13 to 12.0.21000.13: BundleVersion for Visual Studio lower the version for BundleVersion

    • Exit the registry

  3. Run the ISO (or vs_professional.exe) again. If it has a repair button like the image below, you can skip to step 4.

    Visual Studio Repair button

    • Otherwise you have to let the installer fix the registry. I did this by "installing" at least one feature, even though I think I already had all features (they were not detected). This took about 20 minutes.
  4. Run the ISO (or vs_professional.exe) again. This time repair should be visible.

  5. Click Repair and let it update your installation and apply its embedded license key. This took about 20 minutes.


Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product:

License: Product key applied

Hope this helps somebody in the future!

Reference blog 'story'

How do I center list items inside a UL element?

write display:inline-block instead of float:left.

li {
        display:inline-block;
        *display:inline; /*IE7*/
        *zoom:1; /*IE7*/
        background:blue;
        color:white;
        margin-right:10px;
}

http://jsfiddle.net/3Ezx2/3/

How to sort an object array by date property?

With ES6 arrow functions, you can further write just one line of concise code (excluding variable declaration).

Eg.:

_x000D_
_x000D_
var isDescending = true; //set to false for ascending
console.log(["8/2/2020","8/1/2020","8/13/2020", "8/2/2020"].sort((a,b) => isDescending ? new Date(b).getTime() - new Date(a).getTime() : new Date(a).getTime() - new Date(b).getTime()));
_x000D_
_x000D_
_x000D_

Since time does not exists with the above dates, the Date object will consider following default time for sorting:

00:00:00

The code will work for both ascending and descending sort. Just change the value of isDescending variable as required.

Spring MVC: difference between <context:component-scan> and <annotation-driven /> tags?

<mvc:annotation-driven /> means that you can define spring beans dependencies without actually having to specify a bunch of elements in XML or implement an interface or extend a base class. For example @Repository to tell spring that a class is a Dao without having to extend JpaDaoSupport or some other subclass of DaoSupport. Similarly @Controller tells spring that the class specified contains methods that will handle Http requests without you having to implement the Controller interface or extend a subclass that implements the controller.

When spring starts up it reads its XML configuration file and looks for <bean elements within it if it sees something like <bean class="com.example.Foo" /> and Foo was marked up with @Controller it knows that the class is a controller and treats it as such. By default, Spring assumes that all the classes it should manage are explicitly defined in the beans.XML file.

Component scanning with <context:component-scan base-package="com.mycompany.maventestwebapp" /> is telling spring that it should search the classpath for all the classes under com.mycompany.maventestweapp and look at each class to see if it has a @Controller, or @Repository, or @Service, or @Component and if it does then Spring will register the class with the bean factory as if you had typed <bean class="..." /> in the XML configuration files.

In a typical spring MVC app you will find that there are two spring configuration files, a file that configures the application context usually started with the Spring context listener.

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

And a Spring MVC configuration file usually started with the Spring dispatcher servlet. For example.

<servlet>
        <servlet-name>main</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>main</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

Spring has support for hierarchical bean factories, so in the case of the Spring MVC, the dispatcher servlet context is a child of the main application context. If the servlet context was asked for a bean called "abc" it will look in the servlet context first, if it does not find it there it will look in the parent context, which is the application context.

Common beans such as data sources, JPA configuration, business services are defined in the application context while MVC specific configuration goes not the configuration file associated with the servlet.

Hope this helps.

How to get div height to auto-adjust to background size?

Had this issue with the Umbraco CMS and in this scenario you can add the image to the div using something like this for the 'style' attribute of the div:

style="background: url('@(image.mediaItem.Image.umbracoFile)') no-repeat scroll 0 0 transparent; height: @(image.mediaItem.Image.umbracoHeight)px"

Xcode stops working after set "xcode-select -switch"

You should be pointing it towards the Developer directory, not the Xcode application bundle. Run this:

sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer

With recent versions of Xcode, you can go to Xcode ? Preferences… ? Locations and pick one of the options for Command Line Tools to set the location.

What are the differences between Visual Studio Code and Visual Studio?

Visual Studio (full version) is a "full-featured" and "convenient" development environment.

Visual Studio (free "Express" versions - only until 2017) are feature-centered and simplified versions of the full version. Feature-centered meaning that there are different versions (Visual Studio Web Developer, Visual Studio C#, etc.) depending on your goal.

Visual Studio (free Community edition - since 2015) is a simplified version of the full version and replaces the separated express editions used before 2015.

Visual Studio Code (VSCode) is a cross-platform (Linux, Mac OS, Windows) editor that can be extended with plugins to your needs.

For example, if you want to create an ASP.NET application using Visual Studio Code you need to perform several steps on your own to setup the project. There is a separate tutorial for each OS.

MySQL Insert with While Loop

drop procedure if exists doWhile;
DELIMITER //  
CREATE PROCEDURE doWhile()   
BEGIN
DECLARE i INT DEFAULT 2376921001; 
WHILE (i <= 237692200) DO
    INSERT INTO `mytable` (code, active, total) values (i, 1, 1);
    SET i = i+1;
END WHILE;
END;
//  

CALL doWhile(); 

How to prevent form resubmission when page is refreshed (F5 / CTRL+R)

A refined version of Moob's post. Create a hash of the POST, save it as a session cookie, and compare hashes every session.

// Optionally Disable browser caching on "Back"
header( 'Cache-Control: no-store, no-cache, must-revalidate' );
header( 'Expires: Sun, 1 Jan 2000 12:00:00 GMT' );
header( 'Last-Modified: ' . gmdate('D, d M Y H:i:s') . 'GMT' );

$post_hash = md5( json_encode( $_POST ) );

if( session_start() )
{
    $post_resubmitted = isset( $_SESSION[ 'post_hash' ] ) && $_SESSION[ 'post_hash' ] == $post_hash;
    $_SESSION[ 'post_hash' ] = $post_hash;
    session_write_close();
}
else
{
    $post_resubmitted = false;
}

if ( $post_resubmitted ) {
  // POST was resubmitted
}
else
{
  // POST was submitted normally
}

Facebook share link without JavaScript

It is possible to include JavaScript in your code and still support non-JavaScript users.

If a user clicks any of the following links without JavaScript enabled, it will simply open a new tab:

<!-- Remember to change URL_HERE, TITLE_HERE and TWITTER_HANDLE_HERE -->
<a href="http://www.facebook.com/sharer/sharer.php?u=URL_HERE&t=TITLE_HERE" target="_blank" class="share-popup">Share on Facebook</a>
<a href="http://www.twitter.com/intent/tweet?url=URL_HERE&via=TWITTER_HANDLE_HERE&text=TITLE_HERE" target="_blank" class="share-popup">Share on Twitter</a>
<a href="http://plus.google.com/share?url=URL_HERE" target="_blank" class="share-popup">Share on Googleplus</a>

Because they contain the share-popup class, we can easily reference these in jQuery, and change the window size to suit the domain we are sharing from:

$(".share-popup").click(function(){
    var window_size = "width=585,height=511";
    var url = this.href;
    var domain = url.split("/")[2];
    switch(domain) {
        case "www.facebook.com":
            window_size = "width=585,height=368";
            break;
        case "www.twitter.com":
            window_size = "width=585,height=261";
            break;
        case "plus.google.com":
            window_size = "width=517,height=511";
            break;
    }
    window.open(url, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,' + window_size);
    return false;
});

No more ugly inline JavaScript, or countless window sizing alterations. And it still supports non-JavaScript users.

Create a button programmatically and set a background image

SWIFT 3 Version of Alex Reynolds' Answer

let image = UIImage(named: "name") as UIImage?
let button = UIButton(type: UIButtonType.custom) as UIButton
button.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
button.setImage(image, for: .normal)
button.addTarget(self, action: Selector("btnTouched:"), for:.touchUpInside)
        self.view.addSubview(button)

How to drop all tables from the database with manage.py CLI in Django?

Using Python to make a flushproject command, you use :

from django.db import connection
cursor = connection.cursor()
cursor.execute(“DROP DATABASE %s;”, [connection.settings_dict['NAME']])
cursor.execute(“CREATE DATABASE %s;”, [connection.settings_dict['NAME']])

How to create circular ProgressBar in android?

You can try this Circle Progress library

enter image description here

enter image description here

NB: please always use same width and height for progress views

DonutProgress:

 <com.github.lzyzsd.circleprogress.DonutProgress
        android:id="@+id/donut_progress"
        android:layout_marginLeft="50dp"
        android:layout_width="100dp"
        android:layout_height="100dp"
        custom:circle_progress="20"/>

CircleProgress:

  <com.github.lzyzsd.circleprogress.CircleProgress
        android:id="@+id/circle_progress"
        android:layout_marginLeft="50dp"
        android:layout_width="100dp"
        android:layout_height="100dp"
        custom:circle_progress="20"/>

ArcProgress:

<com.github.lzyzsd.circleprogress.ArcProgress
        android:id="@+id/arc_progress"
        android:background="#214193"
        android:layout_marginLeft="50dp"
        android:layout_width="100dp"
        android:layout_height="100dp"
        custom:arc_progress="55"
        custom:arc_bottom_text="MEMORY"/>

Javascript Uncaught TypeError: Cannot read property '0' of undefined

The error is here:

hasLetter("a",words[]);

You are passing the first item of words, instead of the array.

Instead, pass the array to the function:

hasLetter("a",words);

Problem solved!


Here's a breakdown of what the problem was:

I'm guessing in your browser (chrome throws a different error), words[] == words[0], so when you call hasLetter("a",words[]);, you are actually calling hasLetter("a",words[0]);. So, in essence, you are passing the first item of words to your function, not the array as a whole.

Of course, because words is just an empty array, words[0] is undefined. Therefore, your function call is actually:

hasLetter("a", undefined);

which means that, when you try to access d[ascii], you are actually trying to access undefined[0], hence the error.

Conda: Installing / upgrading directly from github

I found a reference to this in condas issues. The following should now work.

name: sample_env
channels:
dependencies:
   - requests
   - bokeh>=0.10.0
   - pip:
     - git+https://github.com/pythonforfacebook/facebook-sdk.git

Python - Passing a function into another function

Treat function as variable in your program so you can just pass them to other functions easily:

def test ():
   print "test was invoked"

def invoker(func):
   func()

invoker(test)  # prints test was invoked

Removing highcharts.com credits link

add

credits: {
    enabled: false
}

[NOTE] that it is in the same line with xAxis: {} and yAxis: {}

How can I detect if this dictionary key exists in C#?

You can use ContainsKey:

if (dict.ContainsKey(key)) { ... }

or TryGetValue:

dict.TryGetValue(key, out value);

Update: according to a comment the actual class here is not an IDictionary but a PhysicalAddressDictionary, so the methods are Contains and TryGetValue but they work in the same way.

Example usage:

PhysicalAddressEntry entry;
PhysicalAddressKey key = c.PhysicalAddresses[PhysicalAddressKey.Home].Street;
if (c.PhysicalAddresses.TryGetValue(key, out entry))
{
    row["HomeStreet"] = entry;
}

Update 2: here is the working code (compiled by question asker)

PhysicalAddressEntry entry;
PhysicalAddressKey key = PhysicalAddressKey.Home;
if (c.PhysicalAddresses.TryGetValue(key, out entry))
{
    if (entry.Street != null)
    {
        row["HomeStreet"] = entry.Street.ToString();
    }
}

...with the inner conditional repeated as necessary for each key required. The TryGetValue is only done once per PhysicalAddressKey (Home, Work, etc).

Git: See my last commit

You can run

 git show --source

it shows the author, Date, the commit's message and the diff --git for all changed files in latest commit.

Html.RenderPartial() syntax with Razor

Html.RenderPartial() is a void method - you can check whether a method is a void method by placing your mouse over the call to RenderPartial in your code and you will see the text (extension) void HtmlHelper.RenderPartial...

Void methods require a semicolon at the end of the calling code.

In the Webforms view engine you would have encased your Html.RenderPartial() call within the bee stings <% %>

like so

<% Html.RenderPartial("Path/to/my/partial/view"); %>

when you are using the Razor view engine the equivalent is

@{Html.RenderPartial("Path/to/my/partial/view");}

Passing argument to alias in bash

To simplify leed25d's answer, use a combination of an alias and a function. For example:

function __GetIt {
    cp ./path/to/stuff/$* .
}

alias GetIt='__GetIt'

optional parameters in SQL Server stored proc?

You can declare like this

CREATE PROCEDURE MyProcName
    @Parameter1 INT = 1,
    @Parameter2 VARCHAR (100) = 'StringValue',
    @Parameter3 VARCHAR (100) = NULL
AS

/* check for the NULL / default value (indicating nothing was passed */
if (@Parameter3 IS NULL)
BEGIN
    /* whatever code you desire for a missing parameter*/
    INSERT INTO ........
END

/* and use it in the query as so*/
SELECT *
FROM Table
WHERE Column = @Parameter

Bootstrap - 5 column layout

Copypastable version of wearesicc's 5 col solution with bootstrap variables:

.col-xs-15,
.col-sm-15,
.col-md-15,
.col-lg-15 {
    position: relative;
    min-height: 1px;
    padding-right: ($gutter / 2);
    padding-left: ($gutter / 2);
}

.col-xs-15 {
    width: 20%;
    float: left;
}
@media (min-width: $screen-sm) {
    .col-sm-15 {
        width: 20%;
        float: left;
    }
}
@media (min-width: $screen-md) {
    .col-md-15 {
        width: 20%;
        float: left;
    }
}
@media (min-width: $screen-lg) {
    .col-lg-15 {
        width: 20%;
        float: left;
    }
}

bootstrap responsive table content wrapping

The behaviour is on purpose:

Create responsive tables by wrapping any .table in .table-responsive to make them scroll horizontally on small devices (under 768px). When viewing on anything larger than 768px wide, you will not see any difference in these tables.

Which means tables are responsive by default (are adjusting their size). But only if you wish to not break your table's lines and add scrollbar when there is not enough room use .table-responsive class.

If you take a look at bootstrap's source you will notice there is media query that only activates on XS screen size and it sets text of table to white-space: nowrap which causes it to not breaking.

TL;DR; Solution

Simply remove .table-responsive element/class from your html code.

R solve:system is exactly singular

Using solve with a single parameter is a request to invert a matrix. The error message is telling you that your matrix is singular and cannot be inverted.

Python date string to date object

Directly related question:

What if you have

datetime.datetime.strptime("2015-02-24T13:00:00-08:00", "%Y-%B-%dT%H:%M:%S-%H:%M").date()

and you get:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/_strptime.py", line 308, in _strptime
    format_regex = _TimeRE_cache.compile(format)
  File "/usr/local/lib/python2.7/_strptime.py", line 265, in compile
    return re_compile(self.pattern(format), IGNORECASE)
  File "/usr/local/lib/python2.7/re.py", line 194, in compile
    return _compile(pattern, flags)
  File "/usr/local/lib/python2.7/re.py", line 251, in _compile
    raise error, v # invalid expression
sre_constants.error: redefinition of group name 'H' as group 7; was group 4

and you tried:

<-24T13:00:00-08:00", "%Y-%B-%dT%HH:%MM:%SS-%HH:%MM").date()

but you still get the traceback above.

Answer:

>>> from dateutil.parser import parse
>>> from datetime import datetime
>>> parse("2015-02-24T13:00:00-08:00")
datetime.datetime(2015, 2, 24, 13, 0, tzinfo=tzoffset(None, -28800))

Console.log not working at all

In my case, all console messages were not showing because I had left a string in the "filter" textbox.

Remove the filter it by clicking the X as shown:

enter image description here

Specified cast is not valid?

From your comment:

this line DateTime Date = reader.GetDateTime(0); was throwing the exception

The first column is not a valid DateTime. Most likely, you have multiple columns in your table, and you're retrieving them all by running this query:

SELECT * from INFO

Replace it with a query that retrieves only the two columns you're interested in:

SELECT YOUR_DATE_COLUMN, YOUR_TIME_COLUMN from INFO

Then try reading the values again:

var Date = reader.GetDateTime(0);
var Time = reader.GetTimeSpan(1);  // equivalent to time(7) from your database

Or:

var Date = Convert.ToDateTime(reader["YOUR_DATE_COLUMN"]);
var Time = (TimeSpan)reader["YOUR_TIME_COLUMN"];

Arrow operator (->) usage in C

The -> operator makes the code more readable than the * operator in some situations.

Such as: (quoted from the EDK II project)

typedef
EFI_STATUS
(EFIAPI *EFI_BLOCK_READ)(
  IN EFI_BLOCK_IO_PROTOCOL          *This,
  IN UINT32                         MediaId,
  IN EFI_LBA                        Lba,
  IN UINTN                          BufferSize,
  OUT VOID                          *Buffer
  );


struct _EFI_BLOCK_IO_PROTOCOL {
  ///
  /// The revision to which the block IO interface adheres. All future
  /// revisions must be backwards compatible. If a future version is not
  /// back wards compatible, it is not the same GUID.
  ///
  UINT64              Revision;
  ///
  /// Pointer to the EFI_BLOCK_IO_MEDIA data for this device.
  ///
  EFI_BLOCK_IO_MEDIA  *Media;

  EFI_BLOCK_RESET     Reset;
  EFI_BLOCK_READ      ReadBlocks;
  EFI_BLOCK_WRITE     WriteBlocks;
  EFI_BLOCK_FLUSH     FlushBlocks;

};

The _EFI_BLOCK_IO_PROTOCOL struct contains 4 function pointer members.

Suppose you have a variable struct _EFI_BLOCK_IO_PROTOCOL * pStruct, and you want to use the good old * operator to call it's member function pointer. You will end up with code like this:

(*pStruct).ReadBlocks(...arguments...)

But with the -> operator, you can write like this:

pStruct->ReadBlocks(...arguments...).

Which looks better?

Export to CSV using MVC, C# and jQuery

In addition to Biff MaGriff's answer. To export the file using JQuery, redirect the user to a new page.

$('#btn_export').click(function () {
    window.location.href = 'NewsLetter/Export';
});

How to call window.alert("message"); from C#?

if you are using ajax in your page that require script manager Page.ClientScript
will not work, Try this and it would do the work:

ScriptManager.RegisterClientScriptBlock(this, GetType(),
            "alertMessage", @"alert('your Message ')", true);

TypeError: 'float' object is not subscriptable

PriceList[0] is a float. PriceList[0][1] is trying to access the first element of a float. Instead, do

PriceList[0] = PriceList[1] = ...code omitted... = PriceList[6] = PizzaChange

or

PriceList[0:7] = [PizzaChange]*7

What is the ideal data type to use when storing latitude / longitude in a MySQL database?

The ideal datatype for storing Lat Long values is decimal(9,6)

This is at approximately 10cm precision, whilst only using 5 bytes of storage.

e.g. CAST(123.456789 as decimal(9,6))

Swift - how to make custom header for UITableView?

Did you set the section header height in the viewDidLoad?

self.tableView.sectionHeaderHeight = 70

Plus you should replace

self.view.addSubview(view)

by

view.addSubview(label)

Finally you have to check your frames

let view = UIView(frame: CGRect.zeroRect)

and eventually the desired text color as it seems to be currently white on white.

Starting with Zend Tutorial - Zend_DB_Adapter throws Exception: "SQLSTATE[HY000] [2002] No such file or directory"

Do not assume your unix_socket which would be different from one to another, try to find it.

First of all, get your unix_socket location.

$ mysql -u root -p

Enter your mysql password and login your mysql server from command line.

mysql> show variables like '%sock%';
+---------------+---------------------------------------+
| Variable_name | Value                                 |
+---------------+---------------------------------------+
| socket        | /opt/local/var/run/mysql5/mysqld.sock |
+---------------+---------------------------------------+

Your unix_soket could be diffrent.

Then change your php.ini, find your php.ini file from

<? phpinfo();

You maybe install many php with different version, so please don't assume your php.ini file location, get it from your 'phpinfo';

Change your php.ini:

mysql.default_socket = /opt/local/var/run/mysql5/mysqld.sock

mysqli.default_socket = /opt/local/var/run/mysql5/mysqld.sock

pdo_mysql.default_socket = /opt/local/var/run/mysql5/mysqld.sock

Then restart your apache or php-fpm.

How can I pad an integer with zeros on the left?

Use java.lang.String.format(String,Object...) like this:

String.format("%05d", yournumber);

for zero-padding with a length of 5. For hexadecimal output replace the d with an x as in "%05x".

The full formatting options are documented as part of java.util.Formatter.

Unique device identification

You can use this javascript plugin

https://github.com/biggora/device-uuid

It can get a large list of information for you about mobiles and desktop machines including the uuid for example

var uuid = new DeviceUUID().get();

e9dc90ac-d03d-4f01-a7bb-873e14556d8e

var dua = [
    du.language,
    du.platform,
    du.os,
    du.cpuCores,
    du.isAuthoritative,
    du.silkAccelerated,
    du.isKindleFire,
    du.isDesktop,
    du.isMobile,
    du.isTablet,
    du.isWindows,
    du.isLinux,
    du.isLinux64,
    du.isMac,
    du.isiPad,
    du.isiPhone,
    du.isiPod,
    du.isSmartTV,
    du.pixelDepth,
    du.isTouchScreen
];

Implementing Singleton with an Enum (in Java)

Like all enum instances, Java instantiates each object when the class is loaded, with some guarantee that it's instantiated exactly once per JVM. Think of the INSTANCE declaration as a public static final field: Java will instantiate the object the first time the class is referred to.

The instances are created during static initialization, which is defined in the Java Language Specification, section 12.4.

For what it's worth, Joshua Bloch describes this pattern in detail as item 3 of Effective Java Second Edition.

Fatal error: Call to undefined function imap_open() in PHP

On Mac OS X with Homebrew, as obviously, PHP is already installed due to provided error we cannot run:

Update: Tha latest version brew instal php --with-imap will not work any more!!!

$ brew install php72 --with-imap
Warning: homebrew/php/php72 7.2.xxx is already installed

Also, installing module only, here will not work:

$ brew install php72-imap
Error: No available formula with the name "php72-imap"

So, we must reinstall it:

$ brew reinstall php72 --with-imap

It will take a while :-) (built in 8 minutes 17 seconds)

Angular 2 filter/search list

Slight modification to @Mosche answer, for handling if there exist no filter element.

TS:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'filterFromList'
})
export class FilterPipe implements PipeTransform {
    public transform(value, keys: string, term: string) {

        if (!term) {
            return value
        }
        let res = (value || []).filter((item) => keys.split(',').some(key => item.hasOwnProperty(key) && new RegExp(term, 'gi').test(item[key])));
        return res.length ? res : [-1];

    }
}

Now, in your HTML you can check via '-1' value, for no results.

HTML:

<div *ngFor="let item of list | filterFromList: 'attribute': inputVariableModel">
            <mat-list-item *ngIf="item !== -1">
                <h4 mat-line class="inline-block">
                 {{item}}
                </h4>
            </mat-list-item>
            <mat-list-item *ngIf="item === -1">
                No Matches
            </mat-list-item>
        </div>

Laravel: Get Object From Collection By Attribute

You can use filter, like so:

$desired_object = $food->filter(function($item) {
    return $item->id == 24;
})->first();

filter will also return a Collection, but since you know there will be only one, you can call first on that Collection.

You don't need the filter anymore (or maybe ever, I don't know this is almost 4 years old). You can just use first:

$desired_object = $food->first(function($item) {
    return $item->id == 24;
});

Difference between filter and filter_by in SQLAlchemy

We actually had these merged together originally, i.e. there was a "filter"-like method that accepted *args and **kwargs, where you could pass a SQL expression or keyword arguments (or both). I actually find that a lot more convenient, but people were always confused by it, since they're usually still getting over the difference between column == expression and keyword = expression. So we split them up.

Save text file UTF-8 encoded with VBA

Here is another way to do this - using the API function WideCharToMultiByte:

Option Explicit

Private Declare Function WideCharToMultiByte Lib "kernel32.dll" ( _
  ByVal CodePage As Long, _
  ByVal dwFlags As Long, _
  ByVal lpWideCharStr As Long, _
  ByVal cchWideChar As Long, _
  ByVal lpMultiByteStr As Long, _
  ByVal cbMultiByte As Long, _
  ByVal lpDefaultChar As Long, _
  ByVal lpUsedDefaultChar As Long) As Long

Private Sub getUtf8(ByRef s As String, ByRef b() As Byte)
Const CP_UTF8 As Long = 65001
Dim len_s As Long
Dim ptr_s As Long
Dim size As Long
  Erase b
  len_s = Len(s)
  If len_s = 0 Then _
    Err.Raise 30030, , "Len(WideChars) = 0"
  ptr_s = StrPtr(s)
  size = WideCharToMultiByte(CP_UTF8, 0, ptr_s, len_s, 0, 0, 0, 0)
  If size = 0 Then _
    Err.Raise 30030, , "WideCharToMultiByte() = 0"
  ReDim b(0 To size - 1)
  If WideCharToMultiByte(CP_UTF8, 0, ptr_s, len_s, VarPtr(b(0)), size, 0, 0) = 0 Then _
    Err.Raise 30030, , "WideCharToMultiByte(" & Format$(size) & ") = 0"
End Sub

Public Sub writeUtf()
Dim file As Integer
Dim s As String
Dim b() As Byte
  s = "äöüßµ@€|~{}[]²³\ .." & _
    " OMEGA" & ChrW$(937) & ", SIGMA" & ChrW$(931) & _
    ", alpha" & ChrW$(945) & ", beta" & ChrW$(946) & ", pi" & ChrW$(960) & vbCrLf
  file = FreeFile
  Open "C:\Temp\TestUtf8.txt" For Binary Access Write Lock Read Write As #file
  getUtf8 s, b
  Put #file, , b
  Close #file
End Sub

Drop data frame columns by name

within(df, rm(x))

is probably easiest, or for multiple variables:

within(df, rm(x, y))

Or if you're dealing with data.tables (per How do you delete a column by name in data.table?):

dt[, x := NULL]   # Deletes column x by reference instantly.

dt[, !"x"]   # Selects all but x into a new data.table.

or for multiple variables

dt[, c("x","y") := NULL]

dt[, !c("x", "y")]

Using :: in C++

look at it is informative [Qualified identifiers

A qualified id-expression is an unqualified id-expression prepended by a scope resolution operator ::, and optionally, a sequence of enumeration, (since C++11)class or namespace names or decltype expressions (since C++11) separated by scope resolution operators. For example, the expression std::string::npos is an expression that names the static member npos in the class string in namespace std. The expression ::tolower names the function tolower in the global namespace. The expression ::std::cout names the global variable cout in namespace std, which is a top-level namespace. The expression boost::signals2::connection names the type connection declared in namespace signals2, which is declared in namespace boost.

The keyword template may appear in qualified identifiers as necessary to disambiguate dependent template names]1

How to update a menu item shown in the ActionBar?

I have used this code:

public boolean onPrepareOptionsMenu (Menu menu) {       
    MenuInflater inflater = getMenuInflater();
    TextView title  = (TextView) findViewById(R.id.title);
    menu.getItem(0).setTitle(
        getString(R.string.payFor) + " " + title.getText().toString());
    menu.getItem(1).setTitle(getString(R.string.payFor) + "...");
    return true;        
}

And worked like a charm to me you can find OnPrepareOptionsMenu here

Undoing a 'git push'

Undo multiple commits git reset --hard 0ad5a7a6 (Just provide commit SHA1 hash)

Undo last commit

git reset --hard HEAD~1 (changes to last commit will be removed ) git reset --soft HEAD~1 (changes to last commit will be available as uncommited local modifications)

How to set child process' environment variable in Makefile

I would re-write the original target test, taking care the needed variable is defined IN THE SAME SUB-PROCESS as the application to launch:

test:
    ( NODE_ENV=test mocha --harmony --reporter spec test )

Git - How to fix "corrupted" interactive rebase?

In my case eighter git rebase --abort and git rebase --continue was throwing:

error: could not read '.git/rebase-apply/head-name': No such file or directory

I managed to fix this issue by manually removing: .git\rebase-apply directory.

How can I String.Format a TimeSpan object with a custom format in .NET?

The Substring method works perfectly when you only want the Hours:Minutes:Seconds. It's simple, clean code and easy to understand.

    var yourTimeSpan = DateTime.Now - DateTime.Now.AddMinutes(-2);

    var formatted = yourTimeSpan.ToString().Substring(0,8);// 00:00:00 

    Console.WriteLine(formatted);

Val and Var in Kotlin

var is a variable like any other language. eg.

var price: Double

On the other side, val provides you feature of referencing. eg.

val CONTINENTS = 7
// You refer this to get constant value 7. In this case, val acts as access
// specifier final in Java

and,

val Int.absolute: Int
    get() {
        return Math.abs(this)
    }
// You refer to the newly create 'method' which provides absolute value 
// of your integer

println(-5.absolute) // O.P: 5

Unable to read data from the transport connection : An existing connection was forcibly closed by the remote host

The reason this was happening to me was I had a recursive dependency in my DI provider. In my case I had:

services.AddScoped(provider => new CfDbContext(builder.Options));
services.AddScoped(provider => provider.GetService<CfDbContext>());

Fix was to just remove the second scoped service registration

services.AddScoped(provider => new CfDbContext(builder.Options));

Warning: mysql_connect(): Access denied for user 'root'@'localhost' (using password: YES)

try $conn = mysql_connect("localhost", "root") or $conn = mysql_connect("localhost", "root", "")

Is it possible to get all arguments of a function as single object inside that function?

You can also convert it to an array if you prefer. If Array generics are available:

var args = Array.slice(arguments)

Otherwise:

var args = Array.prototype.slice.call(arguments);

from Mozilla MDN:

You should not slice on arguments because it prevents optimizations in JavaScript engines (V8 for example).

Find and replace in file and overwrite file doesn't work, it empties the file

When the shell sees > index.html in the command line it opens the file index.html for writing, wiping off all its previous contents.

To fix this you need to pass the -i option to sed to make the changes inline and create a backup of the original file before it does the changes in-place:

sed -i.bak s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g index.html

Without the .bak the command will fail on some platforms, such as Mac OSX.

PostgreSQL Crosstab Query

Solution with JSON aggregation:

CREATE TEMP TABLE t (
  section   text
, status    text
, ct        integer  -- don't use "count" as column name.
);

INSERT INTO t VALUES 
  ('A', 'Active', 1), ('A', 'Inactive', 2)
, ('B', 'Active', 4), ('B', 'Inactive', 5)
                   , ('C', 'Inactive', 7); 


SELECT section,
       (obj ->> 'Active')::int AS active,
       (obj ->> 'Inactive')::int AS inactive
FROM (SELECT section, json_object_agg(status,ct) AS obj
      FROM t
      GROUP BY section
     )X

How do I register a .NET DLL file in the GAC?

From the Publish tab go to application Files.

Then, click unnecessary files.

After that, do the exclude press ok.

Finally, build the project files and run the projects.

Creating a copy of an object in C#

There's already a question about this, you could perhaps read it

Deep cloning objects

There's no Clone() method as it exists in Java for example, but you could include a copy constructor in your clases, that's another good approach.

class A
{
  private int attr

  public int Attr
  {
     get { return attr; }
     set { attr = value }
  }

  public A()
  {
  }

  public A(A p)
  {
     this.attr = p.Attr;
  }  
}

This would be an example, copying the member 'Attr' when building the new object.

How to redirect single url in nginx?

Put this in your server directive:

location /issue {
   rewrite ^/issue(.*) http://$server_name/shop/issues/custom_issue_name$1 permanent;
 }

Or duplicate it:

location /issue1 {
   rewrite ^/.* http://$server_name/shop/issues/custom_issue_name1 permanent;
}
location /issue2 {
   rewrite ^.* http://$server_name/shop/issues/custom_issue_name2 permanent;
}
 ...

How to access PHP session variables from jQuery function in a .js file?

You can pass you session variables from your php script to JQUERY using JSON such as

JS:

jQuery("#rowed2").jqGrid({
    url:'yourphp.php?q=3', 
    datatype: "json", 
    colNames:['Actions'], 
    colModel:[{
                name:'Actions',
                index:'Actions', 
                width:155,
                sortable:false
              }], 
    rowNum:30, 
    rowList:[50,100,150,200,300,400,500,600], 
    pager: '#prowed2', 
    sortname: 'id',
    height: 660,        
    viewrecords: true, 
    sortorder: 'desc',
    gridview:true,
    editurl: 'yourphp.php', 
    caption: 'Caption', 
    gridComplete: function() { 
        var ids = jQuery("#rowed2").jqGrid('getDataIDs'); 
        for (var i = 0; i < ids.length; i++) { 
            var cl = ids[i]; 
            be = "<input style='height:22px;width:50px;' `enter code here` type='button' value='Edit' onclick=\"jQuery('#rowed2').editRow('"+cl+"');\" />"; 
            se = "<input style='height:22px;width:50px;' type='button' value='Save' onclick=\"jQuery('#rowed2').saveRow('"+cl+"');\" />"; 
            ce = "<input style='height:22px;width:50px;' type='button' value='Cancel' onclick=\"jQuery('#rowed2').restoreRow('"+cl+"');\" />"; 
            jQuery("#rowed2").jqGrid('setRowData', ids[i], {Actions:be+se+ce}); 
        } 
    }
}); 

PHP

// start your session
session_start();

// get session from database or create you own
$session_username = $_SESSION['John'];
$session_email = $_SESSION['[email protected]'];

$response = new stdClass();
$response->session_username = $session_username;
$response->session_email = $session_email;

$i = 0;
while ($row = mysqli_fetch_array($result)) { 
    $response->rows[$i]['id'] = $row['ID']; 
    $response->rows[$i]['cell'] = array("", $row['rowvariable1'], $row['rowvariable2']); 
    $i++; 
} 

echo json_encode($response);
// this response (which contains your Session variables) is sent back to your JQUERY 

mysql error 1364 Field doesn't have a default values

Its work and tested Copy to Config File: /etc/mysql/my.cnf OR /bin/mysql/my.ini

[mysqld]
port = 3306
sql-mode=""

then restart MySQL

Place a button right aligned

a modern approach in 2019 using flex-box

with div tag

_x000D_
_x000D_
<div style="display:flex; justify-content:flex-end; width:100%; padding:0;">_x000D_
    <input type="button" value="Click Me"/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

with span tag

_x000D_
_x000D_
<span style="display:flex; justify-content:flex-end; width:100%; padding:0;">_x000D_
    <input type="button" value="Click Me"/>_x000D_
</span>
_x000D_
_x000D_
_x000D_

How to modify a CSS display property from JavaScript?

I found the solution.

As said in the EDIT of my answer, a <div> is misfunctioning in a <table>. So I wrote this code instead :

<tr id="hidden" style="display:none;">
    <td class="depot_table_left">
        <label for="sexe">Sexe</label>
    </td>
    <td>
        <select type="text" name="sexe">
            <option value="1">Sexe</option>
            <option value="2">Joueur</option>
            <option value="3">Joueuse</option>
        </select>
    </td>
</tr>

And this is working fine.

Thanks everybody ;)

Purpose of __repr__ method?

This is explained quite well in the Python documentation:

repr(object): Return a string containing a printable representation of an object. This is the same value yielded by conversions (reverse quotes). It is sometimes useful to be able to access this operation as an ordinary function. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.

So what you're seeing here is the default implementation of __repr__, which is useful for serialization and debugging.

How to use a PHP class from another file?

In this case, it appears that you've already included the file somewhere. But for class files, you should really "include" them using require_once to avoid that sort of thing; it won't include the file if it already has been. (And you should usually use require[_once], not include[_once], the difference being that require will cause a fatal error if the file doesn't exist, instead of just issuing a warning.)

How do you calculate the variance, median, and standard deviation in C++ or Java?

public class Statistics {
    double[] data;
    int size;   

    public Statistics(double[] data) {
        this.data = data;
        size = data.length;
    }   

    double getMean() {
        double sum = 0.0;
        for(double a : data)
            sum += a;
        return sum/size;
    }

    double getVariance() {
        double mean = getMean();
        double temp = 0;
        for(double a :data)
            temp += (a-mean)*(a-mean);
        return temp/(size-1);
    }

    double getStdDev() {
        return Math.sqrt(getVariance());
    }

    public double median() {
       Arrays.sort(data);
       if (data.length % 2 == 0)
          return (data[(data.length / 2) - 1] + data[data.length / 2]) / 2.0;
       return data[data.length / 2];
    }
}

android: how to align image in the horizontal center of an imageview?

For me android:gravity="center" did the trick in the parent layout element.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/fullImageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:contentDescription="@string/fullImageView"
        android:layout_gravity="center" />

</LinearLayout>

How to printf long long

    // acos(0.0) will return value of pi/2, inverse of cos(0) is pi/2 
    double pi = 2 * acos(0.0);
    int n; // upto 6 digit
    scanf("%d",&n); //precision with which you want the value of pi
    printf("%.*lf\n",n,pi); // * will get replaced by n which is the required precision

batch file to list folders within a folder to one level

print all folders name where batch script file is kept

for /d %%d in (*.*) do (
    set test=%%d
    echo !test!
)
pause

global variable for all controller and views

View::share('site_settings', $site_settings);

Add to

app->Providers->AppServiceProvider file boot method

it's global variable.

How to set time zone of a java.util.Date?

Be aware that java.util.Date objects do not contain any timezone information by themselves - you cannot set the timezone on a Date object. The only thing that a Date object contains is a number of milliseconds since the "epoch" - 1 January 1970, 00:00:00 UTC.

As ZZ Coder shows, you set the timezone on the DateFormat object, to tell it in which timezone you want to display the date and time.

Get height and width of a layout programmatically

For frame:

height=fr.getHeight();
width=fr.getWidth();

For screen:

width = getWindowManager().getDefaultDisplay().getWidth();
height = getWindowManager().getDefaultDisplay().getHeight();

FtpWebRequest Download File

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverPath);

After this you may use the below line to avoid error..(access denied etc.)

request.Proxy = null;

How to create a multi line body in C# System.Net.Mail.MailMessage

Try using the verbatim operator "@" before your message:

message.Body = 
@"
FirstLine
SecondLine
"

Consider that also the distance of the text from the left margin affects on the real distance from the email body left margin..

How to write a Unit Test?

I provide this post for both IntelliJ and Eclipse.

Eclipse:

For making unit test for your project, please follow these steps (I am using Eclipse in order to write this test):

1- Click on New -> Java Project.

Create Project

2- Write down your project name and click on finish.

Create Project

3- Right click on your project. Then, click on New -> Class.

Create Class

4- Write down your class name and click on finish.

Create Class

Then, complete the class like this:

public class Math {
    int a, b;
    Math(int a, int b) {
        this.a = a;
        this.b = b;
    }
    public int add() {
        return a + b;
    }
}

5- Click on File -> New -> JUnit Test Case.

Create JUnite Test

6- Check setUp() and click on finish. SetUp() will be the place that you initialize your test.

Check SetUp()

7- Click on OK.

Add JUnit

8- Here, I simply add 7 and 10. So, I expect the answer to be 17. Complete your test class like this:

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class MathTest {
    Math math;
    @Before
    public void setUp() throws Exception {
        math = new Math(7, 10);
    }
    @Test
    public void testAdd() {
        Assert.assertEquals(17, math.add());
    }
}

9- Write click on your test class in package explorer and click on Run as -> JUnit Test.

Run JUnit Test

10- This is the result of the test.

Result of The Test

IntelliJ: Note that I used IntelliJ IDEA community 2020.1 for the screenshots. Also, you need to set up your jre before these steps. I am using JDK 11.0.4.

1- Right-click on the main folder of your project-> new -> directory. You should call this 'test'. enter image description here 2- Right-click on the test folder and create the proper package. I suggest creating the same packaging names as the original class. Then, you right-click on the test directory -> mark directory as -> test sources root. enter image description here 3- In the right package in the test directory, you need to create a Java class (I suggest to use Test.java). enter image description here 4- In the created class, type '@Test'. Then, among the options that IntelliJ gives you, select Add 'JUnitx' to classpath. enter image description here enter image description here 5- Write your test method in your test class. The method signature is like:

@Test
public void test<name of original method>(){
...
}

You can do your assertions like below:

Assertions.assertTrue(f.flipEquiv(node1_1, node2_1));

These are the imports that I added:

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

enter image description here

This is the test that I wrote: enter image description here

You can check your methods like below:

Assertions.assertEquals(<Expected>,<actual>);
Assertions.assertTrue(<actual>);
...

For running your unit tests, right-click on the test and click on Run . enter image description here

If your test passes, the result will be like below: enter image description here

I hope it helps. You can see the structure of the project in GitHub https://github.com/m-vahidalizadeh/problem_solving_project.

How to implement zoom effect for image view in android?

Below is the code for ImageFullViewActivity Class

 public class ImageFullViewActivity extends AppCompatActivity {

        private ScaleGestureDetector mScaleGestureDetector;
        private float mScaleFactor = 1.0f;
        private ImageView mImageView;

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

            mImageView = (ImageView) findViewById(R.id.imageView);
            mScaleGestureDetector = new ScaleGestureDetector(this, new ScaleListener());

        }

        @Override
        public boolean onTouchEvent(MotionEvent motionEvent) {
            mScaleGestureDetector.onTouchEvent(motionEvent);
            return true;
        }

        private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
            @Override
            public boolean onScale(ScaleGestureDetector scaleGestureDetector) {
                mScaleFactor *= scaleGestureDetector.getScaleFactor();
                mScaleFactor = Math.max(0.1f,
                        Math.min(mScaleFactor, 10.0f));
                mImageView.setScaleX(mScaleFactor);
                mImageView.setScaleY(mScaleFactor);
                return true;
            }
        }
    }

Excel 2010 VBA - Close file No Save without prompt

If you're not wanting to save changes set savechanges to false

    Sub CloseBook2()
        ActiveWorkbook.Close savechanges:=False
    End Sub

for more examples, http://support.microsoft.com/kb/213428 and i believe in the past I've just used

    ActiveWorkbook.Close False

Is there a Newline constant defined in Java like Environment.Newline in C#?

As of Java 7 (and Android API level 19):

System.lineSeparator()

Documentation: Java Platform SE 7


For older versions of Java, use:

System.getProperty("line.separator");

See https://java.sun.com/docs/books/tutorial/essential/environment/sysprop.html for other properties.

What does <> mean in excel?

It means "not equal to" (as in, the values in cells E37-N37 are not equal to "", or in other words, they are not empty.)

python object() takes no parameters error

You must press twice on tap and (_) key each time, it must look like:

__init__

Convert timestamp to string

new Date().toString();

http://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/

Dateformatter can make it to any string you want

How to change button background image on mouseOver?

You can create a class based on a Button with specific images for MouseHover and MouseDown like this:

public class AdvancedImageButton : Button {

public Image HoverImage { get; set; }
public Image PlainImage { get; set; }
public Image PressedImage { get; set; }

protected override void OnMouseEnter(System.EventArgs e)
{
  base.OnMouseEnter(e);
  if (HoverImage == null) return;
  if (PlainImage == null) PlainImage = base.Image;
  base.Image = HoverImage;
}

protected override void OnMouseLeave(System.EventArgs e)
{
  base.OnMouseLeave(e);
  if (HoverImage == null) return;
  base.Image = PlainImage;
}

protected override void OnMouseDown(MouseEventArgs e)
{
  base.OnMouseDown(e);
  if (PressedImage == null) return;
  if (PlainImage == null) PlainImage = base.Image;
  base.Image = PressedImage;
}

}

This solution has a small drawback that I am sure can be fixed: when you need for some reason change the Image property, you will also have to change the PlainImage property also.

Why use pointers?

One use of pointers (I won't mention things already covered in other people's posts) is to access memory that you haven't allocated. This isn't useful much for PC programming, but it's used in embedded programming to access memory mapped hardware devices.

Back in the old days of DOS, you used to be able to access the video card's video memory directly by declaring a pointer to:

unsigned char *pVideoMemory = (unsigned char *)0xA0000000;

Many embedded devices still use this technique.

SQL LIKE condition to check for integer?

If you want to search as string, you can cast to text like this:

SELECT * FROM books WHERE price::TEXT LIKE '123%'

Haskell: Converting Int to String

The opposite of read is show.

Prelude> show 3
"3"

Prelude> read $ show 3 :: Int
3

Overflow-x:hidden doesn't prevent content from overflowing in mobile browsers

body{
height: 100%;
overflow: hidden !important;
width: 100%;
position: fixed;

works on iOS9

Swift - iOS - Dates and times in different format

Here is a solution that works with Xcode 10.1 (FEB 23 2019) :

func getCurrentDateTime() {

    let now = Date()
    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "fr_FR")
    formatter.dateFormat = "EEEE dd MMMM YYYY"
    labelDate.text = formatter.string(from: now)
    labelDate.font = UIFont(name: "HelveticaNeue-Bold", size: 12)
    labelDate.textColor = UIColor.lightGray

    let text = formatter.string(from: now)
    labelDate.text = text.uppercased()
}

The "Accueil" Label is not connected to the code.

7-zip commandline

Since 7-zip version 9.25 alpha there is a new -spf switch that can be used to store the full file paths including drive letter to the archive.

7zG.exe a -spf c:\BAckup\backup.zip @c:\temp\tmpFileList.txt

should be working just fine now.

Moment get current date

Just call moment as a function without any arguments:

moment()

For timezone information with moment, look at the moment-timezone package: http://momentjs.com/timezone/

How do I vertically center text with CSS?

The solution accepted as the answer is perfect to use line-height the same as the height of div, but this solution does not work perfectly when text is wrapped OR is in two lines.

Try this one if text is wrapped or is on multiple lines inside a div.

#box
{
  display: table-cell;
  vertical-align: middle;
}

For more reference, see:

How do I unlock a SQLite database?

If you want to remove a "database is locked" error then follow these steps:

  1. Copy your database file to some other location.
  2. Replace the database with the copied database. This will dereference all processes which were accessing your database file.

PHP Warning: Invalid argument supplied for foreach()

You should check that what you are passing to foreach is an array by using the is_array function

If you are not sure it's going to be an array you can always check using the following PHP example code:

if (is_array($variable)) {

  foreach ($variable as $item) {
   //do something
  }
}

Which one is the best PDF-API for PHP?

Try TCPDF. I find it the best so far.

For detailed tutorial on using the two most popular pdf generation classes: TCPDF and FPDF.. please follow this link: PHP: Easily create PDF on the fly with TCPDF and FPDF

Hope it helps.

How do I rotate a picture in WinForms

Simple method:

public Image RotateImage(Image img)
{
    var bmp = new Bitmap(img);

    using (Graphics gfx = Graphics.FromImage(bmp))
    {
        gfx.Clear(Color.White);
        gfx.DrawImage(img, 0, 0, img.Width, img.Height);
    }

    bmp.RotateFlip(RotateFlipType.Rotate270FlipNone);
    return bmp;
}

How to add a boolean datatype column to an existing table in sql?

In SQL SERVER it is BIT, though it allows NULL to be stored

ALTER TABLE person add  [AdminApproved] BIT default 'FALSE';

Also there are other mistakes in your query

  1. When you alter a table to add column no need to mention column keyword in alter statement

  2. For adding default constraint no need to use SET keyword

  3. Default value for a BIT column can be ('TRUE' or '1') / ('FALSE' or 0). TRUE or FALSE needs to mentioned as string not as Identifier

How to get image width and height in OpenCV?

Also for openCV in python you can do:

img = cv2.imread('myImage.jpg')
height, width, channels = img.shape 

Check list of words in another string

Easiest and Simplest method of solving this problem is using re

import re

search_list = ['one', 'two', 'there']
long_string = 'some one long two phrase three'
if re.compile('|'.join(search_list),re.IGNORECASE).search(long_string): #re.IGNORECASE is used to ignore case
    # Do Something if word is present
else:
    # Do Something else if word is not present

How to update a pull request from forked repo?

You have done it correctly. The pull request will automatically update. The process is:

  1. Open pull request
  2. Commit changes based on feedback in your local repo
  3. Push to the relevant branch of your fork

The pull request will automatically add the new commits at the bottom of the pull request discussion (ie, it's already there, scroll down!)