Programs & Examples On #Wxperl

wxperl is the module/library used to access the WxWidgets portable GUI classes.

How to implement a confirmation (yes/no) DialogPreference?

Use Intent Preference if you are using preference xml screen or you if you are using you custom screen then the code would be like below

intentClearCookies = getPreferenceManager().createPreferenceScreen(this);
    Intent clearcookies = new Intent(PopupPostPref.this, ClearCookies.class);

    intentClearCookies.setIntent(clearcookies);
    intentClearCookies.setTitle(R.string.ClearCookies);
    intentClearCookies.setEnabled(true);
    launchPrefCat.addPreference(intentClearCookies);

And then Create Activity Class somewhat like below, As different people as different approach you can use any approach you like this is just an example.

public class ClearCookies extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    showDialog();
}

/**
 * @throws NotFoundException
 */
private void showDialog() throws NotFoundException {
    new AlertDialog.Builder(this)
            .setTitle(getResources().getString(R.string.ClearCookies))
            .setMessage(
                    getResources().getString(R.string.ClearCookieQuestion))
            .setIcon(
                    getResources().getDrawable(
                            android.R.drawable.ic_dialog_alert))
            .setPositiveButton(
                    getResources().getString(R.string.PostiveYesButton),
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog,
                                int which) {
                            //Do Something Here

                        }
                    })
            .setNegativeButton(
                    getResources().getString(R.string.NegativeNoButton),
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog,
                                int which) {
                            //Do Something Here
                        }
                    }).show();
}}

As told before there are number of ways doing this. this is one of the way you can do your task, please accept the answer if you feel that you have got it what you wanted.

Find a string by searching all tables in SQL Server Management Studio 2008

The answer that was mentioned in this post already several times I have adopted a little bit because I needed to search in only one table too:

(and also made input for the table name a bit more simpler)

ALTER PROC dbo.db_compare_SearchAllTables_sp
(
    @SearchStr nvarchar(100),
    @TableName nvarchar(256) = ''
)
AS
BEGIN
        if PARSENAME(@TableName, 2) is null
            set @TableName = 'dbo.' + QUOTENAME(@TableName, '"')

    declare @results TABLE(ColumnName nvarchar(370), ColumnValue nvarchar(3630))

    SET NOCOUNT ON

    DECLARE @ColumnName nvarchar(128) = '', @SearchStr2 nvarchar(110)
    SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
        IF @TableName <> ''
        WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
        BEGIN
            SET @ColumnName =
            (
                SELECT MIN(QUOTENAME(COLUMN_NAME))
                FROM     INFORMATION_SCHEMA.COLUMNS
                WHERE         TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                    AND    TABLE_NAME    = PARSENAME(@TableName, 1)
                    AND    DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
                    AND    QUOTENAME(COLUMN_NAME) > @ColumnName
            )

            IF @ColumnName IS NOT NULL
            BEGIN
                INSERT INTO @results
                EXEC
                (
                    'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) 
                    FROM ' + @TableName + ' WITH (NOLOCK) ' +
                    ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
                )
            END
        END    
        ELSE
    WHILE @TableName IS NOT NULL
    BEGIN
        SET @ColumnName = ''
        SET @TableName = 
        (
            SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
            FROM     INFORMATION_SCHEMA.TABLES
            WHERE         TABLE_TYPE = 'BASE TABLE'
                AND    QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
                AND    OBJECTPROPERTY(
                        OBJECT_ID(
                            QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                             ), 'IsMSShipped'
                               ) = 0
        )

        WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
        BEGIN
            SET @ColumnName =
            (
                SELECT MIN(QUOTENAME(COLUMN_NAME))
                FROM     INFORMATION_SCHEMA.COLUMNS
                WHERE         TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                    AND    TABLE_NAME    = PARSENAME(@TableName, 1)
                    AND    DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
                    AND    QUOTENAME(COLUMN_NAME) > @ColumnName
            )

            IF @ColumnName IS NOT NULL
            BEGIN
                INSERT INTO @results
                EXEC
                (
                    'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) 
                    FROM ' + @TableName + ' WITH (NOLOCK) ' +
                    ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
                )
            END
        END    
    END

    SELECT ColumnName, ColumnValue FROM @results
END

Test class with a new() call in it with Mockito

    public class TestedClass {
    public LoginContext login(String user, String password) {
        LoginContext lc = new LoginContext("login", callbackHandler);
        lc.doThis();
        lc.doThat();
    }
  }

-- Test Class:

    @RunWith(PowerMockRunner.class)
    @PrepareForTest(TestedClass.class)
    public class TestedClassTest {

        @Test
        public void testLogin() {
            LoginContext lcMock = mock(LoginContext.class);
            whenNew(LoginContext.class).withArguments(anyString(), anyString()).thenReturn(lcMock);
//comment: this is giving mock object ( lcMock )
            TestedClass tc = new TestedClass();
            tc.login ("something", "something else"); ///  testing this method.
            // test the login's logic
        }
    }

When calling the actual method tc.login ("something", "something else"); from the testLogin() { - This LoginContext lc is set to null and throwing NPE while calling lc.doThis();

How exactly does __attribute__((constructor)) work?

.init/.fini isn't deprecated. It's still part of the the ELF standard and I'd dare say it will be forever. Code in .init/.fini is run by the loader/runtime-linker when code is loaded/unloaded. I.e. on each ELF load (for example a shared library) code in .init will be run. It's still possible to use that mechanism to achieve about the same thing as with __attribute__((constructor))/((destructor)). It's old-school but it has some benefits.

.ctors/.dtors mechanism for example require support by system-rtl/loader/linker-script. This is far from certain to be available on all systems, for example deeply embedded systems where code executes on bare metal. I.e. even if __attribute__((constructor))/((destructor)) is supported by GCC, it's not certain it will run as it's up to the linker to organize it and to the loader (or in some cases, boot-code) to run it. To use .init/.fini instead, the easiest way is to use linker flags: -init & -fini (i.e. from GCC command line, syntax would be -Wl -init my_init -fini my_fini).

On system supporting both methods, one possible benefit is that code in .init is run before .ctors and code in .fini after .dtors. If order is relevant that's at least one crude but easy way to distinguish between init/exit functions.

A major drawback is that you can't easily have more than one _init and one _fini function per each loadable module and would probably have to fragment code in more .so than motivated. Another is that when using the linker method described above, one replaces the original _init and _fini default functions (provided by crti.o). This is where all sorts of initialization usually occur (on Linux this is where global variable assignment is initialized). A way around that is described here

Notice in the link above that a cascading to the original _init() is not needed as it's still in place. The call in the inline assembly however is x86-mnemonic and calling a function from assembly would look completely different for many other architectures (like ARM for example). I.e. code is not transparent.

.init/.fini and .ctors/.detors mechanisms are similar, but not quite. Code in .init/.fini runs "as is". I.e. you can have several functions in .init/.fini, but it is AFAIK syntactically difficult to put them there fully transparently in pure C without breaking up code in many small .so files.

.ctors/.dtors are differently organized than .init/.fini. .ctors/.dtors sections are both just tables with pointers to functions, and the "caller" is a system-provided loop that calls each function indirectly. I.e. the loop-caller can be architecture specific, but as it's part of the system (if it exists at all i.e.) it doesn't matter.

The following snippet adds new function pointers to the .ctors function array, principally the same way as __attribute__((constructor)) does (method can coexist with __attribute__((constructor))).

#define SECTION( S ) __attribute__ ((section ( S )))
void test(void) {
   printf("Hello\n");
}
void (*funcptr)(void) SECTION(".ctors") =test;
void (*funcptr2)(void) SECTION(".ctors") =test;
void (*funcptr3)(void) SECTION(".dtors") =test;

One can also add the function pointers to a completely different self-invented section. A modified linker script and an additional function mimicking the loader .ctors/.dtors loop is needed in such case. But with it one can achieve better control over execution order, add in-argument and return code handling e.t.a. (In a C++ project for example, it would be useful if in need of something running before or after global constructors).

I'd prefer __attribute__((constructor))/((destructor)) where possible, it's a simple and elegant solution even it feels like cheating. For bare-metal coders like myself, this is just not always an option.

Some good reference in the book Linkers & loaders.

Iterating through directories with Python

From python >= 3.5 onward, you can use **, glob.iglob(path/**, recursive=True) and it seems the most pythonic solution, i.e.:

import glob, os

for filename in glob.iglob('/pardadox-music/**', recursive=True):
    if os.path.isfile(filename): # filter dirs
        print(filename)

Output:

/pardadox-music/modules/her1.mod
/pardadox-music/modules/her2.mod
...

Notes:
1 - glob.iglob

glob.iglob(pathname, recursive=False)

Return an iterator which yields the same values as glob() without actually storing them all simultaneously.

2 - If recursive is True, the pattern '**' will match any files and zero or more directories and subdirectories.

3 - If the directory contains files starting with . they won’t be matched by default. For example, consider a directory containing card.gif and .card.gif:

>>> import glob
>>> glob.glob('*.gif') ['card.gif'] 
>>> glob.glob('.c*')['.card.gif']

4 - You can also use rglob(pattern), which is the same as calling glob() with **/ added in front of the given relative pattern.

How do you use NSAttributedString?

To solve such kind of problems I created library in swift which is called Atributika.

let str = "<r>first</r><g>second</g><b>third</b>".style(tags:
        Style("r").foregroundColor(.red),
        Style("g").foregroundColor(.green),
        Style("b").foregroundColor(.blue)).attributedString

label.attributedText = str

You can find it here https://github.com/psharanda/Atributika

View RDD contents in Python Spark?

In Spark 2.0 (I didn't tested with earlier versions). Simply:

print myRDD.take(n)

Where n is the number of lines and myRDD is wc in your case.

How can I move all the files from one folder to another using the command line?

OMG I Got A Quick File Move Command form CMD

1)Command will move All Files and Sub Folders into another location in 1 second .

check command

C:\user>move "your source path " "your destination path" 

Hint : For move all Files and Sub folders

C:\user>move "f:\wamp\www" "f:\wapm_3.2\www\old Projects"

check image enter image description here

you can see that it's before i try some other code that was not working due to more than 1 files and folder was there. when i try to execute code that is under line by red color then all folder move in 1 second.

now check this image. here Total 6.7GB data moved in 1 second... you can check date of post and move as well as Folder name. enter image description here

i will soon make a windows app that will do same..

How do I install a color theme for IntelliJ IDEA 7.0.x

If you just have the xml file of the color scheme you can:

Go to Preferences -> Editor -> Color and Fonts and use the Import button.

enter image description here

Bootstrap modal appearing under background

The solution is to put the modal directly under the body tag. If that is not possible for some reason then just add a overflow: visible property to the tag enclosing the modal, or use the following code:

<script>
    $(document).on('show.bs.modal', '.modal', function () {
        $('.div-wrapper-for-modal').css('overflow', 'visible');
    });

    $(document).on('hide.bs.modal', '.modal', function () {
        $('.div-wrapper-for-modal').css('overflow', 'auto');
    });
</script>
<div class="div-wrapper-for-modal">
    <div class="modal hide fade">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            <h3>Modal header</h3>
        </div>
        <div class="modal-body">
            <p>One fine body…</p>
        </div>
        <div class="modal-footer">
            <a href="#" class="btn">Close</a>
            <a href="#" class="btn btn-primary">Save changes</a>
        </div>
    </div>
</div>

How to check version of python modules?

I suggest opening a python shell in terminal (in the python version you are interested), importing the library, and getting its __version__ attribute.

>>> import statlib
>>> statlib.__version__

>>> import construct
>>> contruct.__version__

Note 1: We must regard the python version. If we have installed different versions of python, we have to open the terminal in the python version we are interested in. For example, opening the terminal with python3.8 can (surely will) give a different version of a library than opening with python3.5 or python2.7.

Note 2: We avoid using the print function, because its behavior depends on python2 or python3. We do not need it, the terminal will show the value of the expression.

CSS transition effect makes image blurry / moves image 1px, in Chrome?

I recommended an experimental new attribute CSS I tested on latest browser and it's good:

image-rendering: optimizeSpeed;             /*                     */
image-rendering: -moz-crisp-edges;          /* Firefox             */
image-rendering: -o-crisp-edges;            /* Opera               */
image-rendering: -webkit-optimize-contrast; /* Chrome (and Safari) */
image-rendering: optimize-contrast;         /* CSS3 Proposed       */
-ms-interpolation-mode: nearest-neighbor;   /* IE8+                */

With this the browser will know the algorithm for rendering

Android: adb pull file on desktop

do adb pull \sdcard\log.txt C:Users\admin\Desktop

Start script missing error when running npm start

Take a look at your client/package.json. You have to have these scripts

"scripts": {
  "start": "react-scripts start",
  "build": "react-scripts build",
  "test": "react-scripts test --env=jsdom",
  "eject": "react-scripts eject"
}

Reorder HTML table rows using drag-and-drop

thanks to Jim Petkus that did gave me a wonderful answer . but i was trying to solve my own script not to changing it to another plugin . My main focus was not using an independent plugin and do what i wanted just by using the jquery core !

and guess what i did find the problem .

var title = $("em").attr("title");
$("div").text(title);

this is what i add to my script and the blew codes to my html part :

<td> <em title=\"$weight\">$weight</em></td>

and found each row $weight value

thanks again to Jim Petkus

How to choose the id generation strategy when using JPA and Hibernate

I find this lecture very valuable https://vimeo.com/190275665, in point 3 it summarizes these generators and also gives some performance analysis and guideline one when you use each one.

How in node to split string by newline ('\n')?

The first one should work:

> "a\nb".split("\n");
[ 'a', 'b' ]
> var a = "test.js\nagain.js"
undefined
> a.split("\n");
[ 'test.js', 'again.js' ]

How to create dispatch queue in Swift 3

Compiles under >=Swift 3. This example contains most of the syntax that we need.

QoS - new quality of service syntax

weak self - to disrupt retain cycles

if self is not available, do nothing

async global utility queue - for network query, does not wait for the result, it is a concurrent queue, the block (usually) does not wait when started. Exception for a concurrent queue could be, when its task limit has been previously reached, then the queue temporarily turns into a serial queue and waits until some previous task in that queue completes.

async main queue - for touching the UI, the block does not wait for the result, but waits for its slot at the start. The main queue is a serial queue.

Of course, you need to add some error checking to this...

DispatchQueue.global(qos: .utility).async { [weak self] () -> Void in

    guard let strongSelf = self else { return }

    strongSelf.flickrPhoto.loadLargeImage { loadedFlickrPhoto, error in

        if error != nil {
            print("error:\(error)")
        } else {
            DispatchQueue.main.async { () -> Void in
                activityIndicator.removeFromSuperview()
                strongSelf.imageView.image = strongSelf.flickrPhoto.largeImage
            }
        }
    }
}

Swift do-try-catch syntax

enum NumberError: Error {
  case NegativeNumber(number: Int)
  case ZeroNumber
  case OddNumber(number: Int)
}

extension NumberError: CustomStringConvertible {
         var description: String {
         switch self {
             case .NegativeNumber(let number):
                 return "Negative number \(number) is Passed."
             case .OddNumber(let number):
                return "Odd number \(number) is Passed."
             case .ZeroNumber:
                return "Zero is Passed."
      }
   }
}

 func validateEvenNumber(_ number: Int) throws ->Int {
     if number == 0 {
        throw NumberError.ZeroNumber
     } else if number < 0 {
        throw NumberError.NegativeNumber(number: number)
     } else if number % 2 == 1 {
         throw NumberError.OddNumber(number: number)
     }
    return number
}

Now Validate Number :

 do {
     let number = try validateEvenNumber(0)
     print("Valid Even Number: \(number)")
  } catch let error as NumberError {
     print(error.description)
  }

How to print register values in GDB?

Gdb commands:

  • i r <register_name>: print a single register, e.g i r rax, i r eax
  • i r <register_name_1> <register_name_2> ...: print multiple registers, e.g i r rdi rsi,
  • i r: print all register except floating point & vector register (xmm, ymm, zmm).
  • i r a: print all register, include floating point & vector register (xmm, ymm, zmm).
  • i r f: print all FPU floating registers (st0-7 and a few other f*)

Other register groups besides a (all) and f (float) can be found with:

maint print reggroups

as documented at: https://sourceware.org/gdb/current/onlinedocs/gdb/Registers.html#Registers

Tips:

  • xmm0 ~ xmm15, are 128 bits, almost every modern machine has it, they are released in 1999.
  • ymm0 ~ ymm15, are 256 bits, new machine usually have it, they are released in 2011.
  • zmm0 ~ zmm31, are 512 bits, normal pc probably don't have it (as the year 2016), they are released in 2013, and mainly used in servers so far.
  • Only one serial of xmm / ymm / zmm will be shown, because they are the same registers in different mode. On my machine ymm is shown.

Get multiple elements by Id

You can get the multiple element by id by identifying what element it is. For example

<div id='id'></div>
<div id='id'></div>
<div id='id'></div>

I assume if you are using jQuery you can select all them all by

$("div#id")

. This will get you array of elements you loop them based on your logic.

Remove object from a list of objects in python

If you want to remove multiple object from a list. There are various ways to delete an object from a list

Try this code. a is list with all object, b is list object you want to remove.

example :

a = [1,2,3,4,5,6]
b = [2,3]

for i in b:
   if i in a:
      a.remove(i)

print(a)

the output is [1,4,5,6] I hope, it will work for you

How to document Python code using Doxygen

The doxypy input filter allows you to use pretty much all of Doxygen's formatting tags in a standard Python docstring format. I use it to document a large mixed C++ and Python game application framework, and it's working well.

Javascript: How to pass a function with string parameters as a parameter to another function

One way would be to just escape the quotes properly:

<input type="button" value="click" id="mybtn"
       onclick="myfunction('/myController/myAction', 
               'myfuncionOnOK(\'/myController2/myAction2\', 
                   \'myParameter2\');',
               'myfuncionOnCancel(\'/myController3/myAction3\', 
                   \'myParameter3\');');">

In this case, though, I think a better way to handle this would be to wrap the two handlers in anonymous functions:

<input type="button" value="click" id="mybtn"
       onclick="myfunction('/myController/myAction', 
                function() { myfuncionOnOK('/myController2/myAction2', 
                             'myParameter2'); },
                function() { myfuncionOnCancel('/myController3/myAction3', 
                             'myParameter3'); });">

And then, you could call them from within myfunction like this:

function myfunction(url, onOK, onCancel)
{
    // Do whatever myfunction would normally do...

    if (okClicked)
    {
        onOK();
    }

    if (cancelClicked)
    {
        onCancel();
    }
}

That's probably not what myfunction would actually look like, but you get the general idea. The point is, if you use anonymous functions, you have a lot more flexibility, and you keep your code a lot cleaner as well.

Cannot Resolve Collation Conflict

The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.

When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.

Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:

http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database

Update Collation of all fields in database on the fly

http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx

If you need to have different collation on two objects or can't change collations - you can still JOIN between them using COLLATE command, and choosing the collation you want for join.

SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS 

or using default database collation:

SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT

How to check whether an object has certain method/property?

You could write something like that :

public static bool HasMethod(this object objectToCheck, string methodName)
{
    var type = objectToCheck.GetType();
    return type.GetMethod(methodName) != null;
} 

Edit : you can even do an extension method and use it like this

myObject.HasMethod("SomeMethod");

regex for zip-code

I know this may be obvious for most people who use RegEx frequently, but in case any readers are new to RegEx, I thought I should point out an observation I made that was helpful for one of my projects.

In a previous answer from @kennytm:

^\d{5}(?:[-\s]\d{4})?$

…? = The pattern before it is optional (for condition 1)

If you want to allow both standard 5 digit and +4 zip codes, this is a great example.

To match only zip codes in the US 'Zip + 4' format as I needed to do (conditions 2 and 3 only), simply remove the last ? so it will always match the last 5 character group.

A useful tool I recommend for tinkering with RegEx is linked below:

https://regexr.com/

I use this tool frequently when I find RegEx that does something similar to what I need, but could be tailored a bit better. It also has a nifty RegEx reference menu and informative interface that keeps you aware of how your changes impact the matches for the sample text you entered.

If I got anything wrong or missed an important piece of information, please correct me.

Match two strings in one line with grep

You can use

grep 'string1' filename | grep 'string2'

Or

grep 'string1.*string2\|string2.*string1' filename

How to hide columns in an ASP.NET GridView with auto-generated columns?

Try putting the e.Row.Cells[0].Visible = false; inside the RowCreated event of your grid.

protected void bla_RowCreated(object sender, GridViewRowEventArgs e)
{
    e.Row.Cells[0].Visible = false; // hides the first column
}

This way it auto-hides the whole column.

You don't have access to the generated columns through grid.Columns[i] in your gridview's DataBound event.

round up to 2 decimal places in java?

I just modified your code. It works fine in my system. See if this helps

class round{
    public static void main(String args[]){

    double a = 123.13698;
    double roundOff = Math.round(a*100)/100.00;

    System.out.println(roundOff);
}
}

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

Create an interface to define the 'indexer' interface

Then create your object with that index.

Note: this will still have same issues other answers have described with respect to enforcing the type of each item - but that's often exactly what you want.

You can make the generic type parameter whatever you need : ObjectIndexer< Dog | Cat>

// this should be global somewhere, or you may already be 
// using a library that provides such a type
export interface ObjectIndexer<T> {
  [id: string]: T;
}

interface ISomeObject extends ObjectIndexer<string>
{
    firstKey:   string;
    secondKey:  string;
    thirdKey:   string;
}

let someObject: ISomeObject = {
    firstKey:   'firstValue',
    secondKey:  'secondValue',
    thirdKey:   'thirdValue'
};

let key: string = 'secondKey';

let secondValue: string = someObject[key];

Typescript Playground


You can even use this in a generic constraint when defining a generic type:

export class SmartFormGroup<T extends IndexableObject<any>> extends FormGroup

Then T inside the class can be indexed :-)

phpMyAdmin - Error > Incorrect format parameter?

Without any problems, I imported directly from the command line.

mysql -uroot -hURLServer -p DBName< filename.sql

Where does the iPhone Simulator store its data?

Looks like Xcode 6.0 has moved this location once again, at least for iOS 8 simulators.

~/Library/Developer/CoreSimulator/Devices/[DeviceID]/data/Containers/Data/Application/[AppID]

support FragmentPagerAdapter holds reference to old fragments

Global working tested solution.

getSupportFragmentManager() keeps the null reference some times and View pager does not create new since it find reference to same fragment. So to over come this use getChildFragmentManager() solves problem in simple way.

Don't do this:

new PagerAdapter(getSupportFragmentManager(), fragments);

Do this:

new PagerAdapter(getChildFragmentManager() , fragments);

How does Python's super() work with multiple inheritance?

This is detailed with a reasonable amount of detail by Guido himself in his blog post Method Resolution Order (including two earlier attempts).

In your example, Third() will call First.__init__. Python looks for each attribute in the class's parents as they are listed left to right. In this case, we are looking for __init__. So, if you define

class Third(First, Second):
    ...

Python will start by looking at First, and, if First doesn't have the attribute, then it will look at Second.

This situation becomes more complex when inheritance starts crossing paths (for example if First inherited from Second). Read the link above for more details, but, in a nutshell, Python will try to maintain the order in which each class appears on the inheritance list, starting with the child class itself.

So, for instance, if you had:

class First(object):
    def __init__(self):
        print "first"

class Second(First):
    def __init__(self):
        print "second"

class Third(First):
    def __init__(self):
        print "third"

class Fourth(Second, Third):
    def __init__(self):
        super(Fourth, self).__init__()
        print "that's it"

the MRO would be [Fourth, Second, Third, First].

By the way: if Python cannot find a coherent method resolution order, it'll raise an exception, instead of falling back to behavior which might surprise the user.

Edited to add an example of an ambiguous MRO:

class First(object):
    def __init__(self):
        print "first"

class Second(First):
    def __init__(self):
        print "second"

class Third(First, Second):
    def __init__(self):
        print "third"

Should Third's MRO be [First, Second] or [Second, First]? There's no obvious expectation, and Python will raise an error:

TypeError: Error when calling the metaclass bases
    Cannot create a consistent method resolution order (MRO) for bases Second, First

Edit: I see several people arguing that the examples above lack super() calls, so let me explain: The point of the examples is to show how the MRO is constructed. They are not intended to print "first\nsecond\third" or whatever. You can – and should, of course, play around with the example, add super() calls, see what happens, and gain a deeper understanding of Python's inheritance model. But my goal here is to keep it simple and show how the MRO is built. And it is built as I explained:

>>> Fourth.__mro__
(<class '__main__.Fourth'>,
 <class '__main__.Second'>, <class '__main__.Third'>,
 <class '__main__.First'>,
 <type 'object'>)

How to count lines in a document?

To count all lines use:

$ wc -l file

To filter and count only lines with pattern use:

$ grep -w "pattern" -c file  

Or use -v to invert match:

$ grep -w "pattern" -c -v file 

See the grep man page to take a look at the -e,-i and -x args...

How do I navigate to another page when PHP script is done?

if ($done)
{
    header("Location: /url/to/the/other/page");
    exit;
}

Changing case in Vim

See the following methods:

 ~    : Changes the case of current character

 guu  : Change current line from upper to lower.

 gUU  : Change current LINE from lower to upper.

 guw  : Change to end of current WORD from upper to lower.

 guaw : Change all of current WORD to lower.

 gUw  : Change to end of current WORD from lower to upper.

 gUaw : Change all of current WORD to upper.

 g~~  : Invert case to entire line

 g~w  : Invert case to current WORD

 guG : Change to lowercase until the end of document.

Override browser form-filling and input highlighting with HTML/CSS

This fixes the problem on both Safari and Chrome

if(navigator.userAgent.toLowerCase().indexOf("chrome") >= 0 || navigator.userAgent.toLowerCase().indexOf("safari") >= 0){
window.setInterval(function(){
    $('input:-webkit-autofill').each(function(){
        var clone = $(this).clone(true, true);
        $(this).after(clone).remove();
    });
}, 20);
}

Replacing blank values (white space) with NaN in pandas

These are all close to the right answer, but I wouldn't say any solve the problem while remaining most readable to others reading your code. I'd say that answer is a combination of BrenBarn's Answer and tuomasttik's comment below that answer. BrenBarn's answer utilizes isspace builtin, but does not support removing empty strings, as OP requested, and I would tend to attribute that as the standard use case of replacing strings with null.

I rewrote it with .apply, so you can call it on a pd.Series or pd.DataFrame.


Python 3:

To replace empty strings or strings of entirely spaces:

df = df.apply(lambda x: np.nan if isinstance(x, str) and (x.isspace() or not x) else x)

To replace strings of entirely spaces:

df = df.apply(lambda x: np.nan if isinstance(x, str) and x.isspace() else x)

To use this in Python 2, you'll need to replace str with basestring.

Python 2:

To replace empty strings or strings of entirely spaces:

df = df.apply(lambda x: np.nan if isinstance(x, basestring) and (x.isspace() or not x) else x)

To replace strings of entirely spaces:

df = df.apply(lambda x: np.nan if isinstance(x, basestring) and x.isspace() else x)

Encoding as Base64 in Java

You need to change the import of your class:

import org.apache.commons.codec.binary.Base64;

And then change your class to use the Base64 class.

Here's some example code:

byte[] encodedBytes = Base64.encodeBase64("Test".getBytes());
System.out.println("encodedBytes " + new String(encodedBytes));
byte[] decodedBytes = Base64.decodeBase64(encodedBytes);
System.out.println("decodedBytes " + new String(decodedBytes));

Then read why you shouldn't use sun.* packages.


Update (2016-12-16)

You can now use java.util.Base64 with Java 8. First, import it as you normally do:

import java.util.Base64;

Then use the Base64 static methods as follows:

byte[] encodedBytes = Base64.getEncoder().encode("Test".getBytes());
System.out.println("encodedBytes " + new String(encodedBytes));
byte[] decodedBytes = Base64.getDecoder().decode(encodedBytes);
System.out.println("decodedBytes " + new String(decodedBytes));

If you directly want to encode string and get the result as encoded string, you can use this:

String encodeBytes = Base64.getEncoder().encodeToString((userName + ":" + password).getBytes());

See Java documentation for Base64 for more.

JQuery $.ajax() post - data in a java servlet

You don't want a string, you really want a JS map of key value pairs. E.g., change:

 data: myDataVar.toString(),

with:

var myKeyVals = { A1984 : 1, A9873 : 5, A1674 : 2, A8724 : 1, A3574 : 3, A1165 : 5 }



var saveData = $.ajax({
      type: 'POST',
      url: "someaction.do?action=saveData",
      data: myKeyVals,
      dataType: "text",
      success: function(resultData) { alert("Save Complete") }
});
saveData.error(function() { alert("Something went wrong"); });

jQuery understands key value pairs like that, it does NOT understand a big string. It passes it simply as a string.

UPDATE: Code fixed.

Python vs Bash - In which kind of tasks each one outruns the other performance-wise?

There are 2 scenario's where Bash performance is at least equal I believe:

  • Scripting of command line utilities
  • Scripts which take only a short time to execute; where starting the Python interpreter takes more time than the operation itself

That said, I usually don't really concern myself with performance of the scripting language itself. If performance is a real issue you don't script but program (possibly in Python).

How to amend older Git commit?

You can use git rebase --interactive, using the edit command on the commit you want to amend.

How to subtract X day from a Date object in Java?

@JigarJoshi it's the good answer, and of course also @Tim recommendation to use .joda-time.

I only want to add more possibilities to subtract days from a java.util.Date.

Apache-commons

One possibility is to use apache-commons-lang. You can do it using DateUtils as follows:

Date dateBefore30Days = DateUtils.addDays(new Date(),-30);

Of course add the commons-lang dependency to do only date subtract it's probably not a good options, however if you're already using commons-lang it's a good choice. There is also convenient methods to addYears,addMonths,addWeeks and so on, take a look at the api here.

Java 8

Another possibility is to take advantage of new LocalDate from Java 8 using minusDays(long days) method:

LocalDate dateBefore30Days = LocalDate.now(ZoneId.of("Europe/Paris")).minusDays(30);

How can I get the session object if I have the entity-manager?

To be totally exhaustive, things are different if you're using a JPA 1.0 or a JPA 2.0 implementation.

JPA 1.0

With JPA 1.0, you'd have to use EntityManager#getDelegate(). But keep in mind that the result of this method is implementation specific i.e. non portable from application server using Hibernate to the other. For example with JBoss you would do:

org.hibernate.Session session = (Session) manager.getDelegate();

But with GlassFish, you'd have to do:

org.hibernate.Session session = ((org.hibernate.ejb.EntityManagerImpl) em.getDelegate()).getSession(); 

I agree, that's horrible, and the spec is to blame here (not clear enough).

JPA 2.0

With JPA 2.0, there is a new (and much better) EntityManager#unwrap(Class<T>) method that is to be preferred over EntityManager#getDelegate() for new applications.

So with Hibernate as JPA 2.0 implementation (see 3.15. Native Hibernate API), you would do:

Session session = entityManager.unwrap(Session.class);

How can I simulate mobile devices and debug in Firefox Browser?

You can use tools own browser (Firefox, IE, Chrome...) to debug your JavaScript.

As for resizing, Firefox/Chrome has own resources accessible via Ctrl + Shift + I OR F12. Going tab "style editor" and clicking "adaptive/responsive design" icon.

Old Firefox versions

Old Firefox

New Firefox/Firebug

Firefox

Chrome

Chrome

*Another way is to install an addon like "Web Developer"

Check whether a string contains a substring

Case Insensitive Substring Example

This is an extension of Eugene's answer, which converts the strings to lower case before checking for the substring:

if (index(lc($str), lc($substr)) != -1) {
    print "$str contains $substr\n";
} 

New line in JavaScript alert box

In C# I did:

alert('Text\\n\\nSome more text');

It display as:

Text

Some more text

Wpf control size to content?

I had a problem like this whereby I had specified the width of my Window, but had the height set to Auto. The child DockPanel had it's VerticalAlignment set to Top and the Window had it's VerticalContentAlignment set to Top, yet the Window would still be much taller than the contents.

Using Snoop, I discovered that the ContentPresenter within the Window (part of the Window, not something I had put there) has it's VerticalAlignment set to Stretch and can't be changed without retemplating the entire Window!

After a lot of frustration, I discovered the SizeToContent property - you can use this to specify whether you want the Window to size vertically, horizontally or both, according to the size of the contents - everything is sizing nicely now, I just can't believe it took me so long to find that property!

How to enable cURL in PHP / XAMPP

In SUSE Linux:

zypper in php5-curl
rcapache2 restart

SQL Last 6 Months

Try this one

where datediff(month, datetime_column, getdate()) <= 6

To exclude or filter out future dates

where datediff(month, datetime_column, getdate()) between 0 and 6


This part datediff(month, datetime_column, getdate()) will get the month difference in number of current date and Datetime_Column and will return Rows like:

Result
1
2
3
4
5
6
7
8
9
10

This is Our final condition to get last 6 months data

where result <= 6

Where to find htdocs in XAMPP Mac

Make sure no other apache servers are running as it generates an error when you try to access it on the browser even with a different port. Go to Finder and below Device you will usually see the lampp icon. You can also open the htdocs from any of the ide or code editor by opening files or project once you locate the lampp icon. Make sure you mount the stack.

How do I get specific properties with Get-AdUser

This worked for me as well:

Get-ADUser -Filter * -SearchBase "ou=OU,dc=Domain,dc=com" -Properties Enabled, CanonicalName, Displayname, Givenname, Surname, EmployeeNumber, EmailAddress, Department, StreetAddress, Title | select Enabled, CanonicalName, Displayname, GivenName, Surname, EmployeeNumber, EmailAddress, Department, Title | Export-CSV "C:\output.csv"

Warning: A non-numeric value encountered

It seems that in PHP 7.1, a Warning will be emitted if a non-numeric value is encountered. See this link.

Here is the relevant portion that pertains to the Warning notice you are getting:

New E_WARNING and E_NOTICE errors have been introduced when invalid strings are coerced using operators expecting numbers or their assignment equivalents. An E_NOTICE is emitted when the string begins with a numeric value but contains trailing non-numeric characters, and an E_WARNING is emitted when the string does not contain a numeric value.

I'm guessing either $item['quantity'] or $product['price'] does not contain a numeric value, so make sure that they do before trying to multiply them. Maybe use some sort of conditional before calculating the $sub_total, like so:

<?php

if (is_numeric($item['quantity']) && is_numeric($product['price'])) {
  $sub_total += ($item['quantity'] * $product['price']);
} else {
  // do some error handling...
}

Can't start hostednetwork

First off, when I went into cmd and typed "netsh wlan show drivers", I had a NO for hosted network support too. Doesn't matter, you can still do it. Just not in cmd.

I think this problem happens because they changed the way hosted networks work in windows 10. Don't use command line.

Just go on your pc to settings>Network>Mobile Hotspot and you should see all the necessary settings there. Turn it on, set up your network.

If it's still not working, go to Control panel>Network and Internet>Network and Sharing Center>Change Adapter Options> and then click on the properties of the network adapter that you want to share. Go to the sharing tab, and share that internet connection, selecting the name of the adapter you want to use to share it with.

How to overcome "'aclocal-1.15' is missing on your system" warning?

I think the touch command is the right answer e.g. do something like

touch --date="`date`" aclocal.m4 Makefile.am configure Makefile.in

before [./configure && make].

Sidebar I: Otherwise, I agree with @kaz: adding dependencies for aclocal.m4 and/or configure and/or Makefile.am and/or Makefile.in makes assumptions about the target system that may be invalid. Specifically, those assumptions are

1) that all target systems have autotools,

2) that all target systems have the same version of autotools (e.g. automake.1.15 in this case).

3) that if either (1) or (2) are not true for any user, that the user is extracting the package from a maintainer-produced TAR or ZIP format that maintains timestamps of the relevant files, in which case all autotool/configure/Makefile.am/Makefile.in dependencies in the configure-generated Makefile will be satisfied before the make command is issued.

The second assumption fails on many Mac systems because automake.1.14 is the "latest" for OSX (at least that is what I see in MacPorts, and apparently the same is true for brew).

The third assumption fails spectacularly in a world with Github. This failure is an example of an "everyone thinks they are normative" mindset; specifically, the maintainers, who are the only class of users that should need to edit Makefile.am, have now put everyone into that class.

Perhaps there is an option in autowhatever that keeps these dependencies from being added to Makefile.in and/or Makefile.

Sidebar II [Why @kaz is right]: of course it is obvious, to me and other cognoscenti, to simply try a sequence of [touch] commands to fool the configure-created Makefile from re-running configure and the autotools. But that is not the point of configure; the point of configure is to ensure as many users on as many different systems as as possible can simply do [./configure && make] and move on; most users are not interested in "shaving the yak" e.g. debugging faulty assumptions of the autotools developers.

Sidebar III: it could be argued that ./configure, now that autotools adds these dependencies, is the wrong build tool to use with Github-distributed packages.

Sidebar IV: perhaps configure-based Github repos should put the necessary touch command into their readme, e.g. https://github.com/drbitboy/Tycho2_SQLite_RTree.

How do I apply a perspective transform to a UIView?

You can only use Core Graphics (Quartz, 2D only) transforms directly applied to a UIView's transform property. To get the effects in coverflow, you'll have to use CATransform3D, which are applied in 3-D space, and so can give you the perspective view you want. You can only apply CATransform3Ds to layers, not views, so you're going to have to switch to layers for this.

Check out the "CovertFlow" sample that comes with Xcode. It's mac-only (ie not for iPhone), but a lot of the concepts transfer well.

Run a mySQL query as a cron job?

This was a very handy page as I have a requirement to DELETE records from a mySQL table where the expiry date is < Today.

I am on a shared host and CRON did not like the suggestion AndrewKDay. it also said (and I agree) that exposing the password in this way could be insecure.

I then tried turning Events ON in phpMyAdmin but again being on a shared host this was a no no. Sorry fancyPants.

So I turned to embedding the SQL script in a PHP file. I used the example [here][1]

[1]: https://www.w3schools.com/php/php_mysql_create_table.asp stored it in a sub folder somewhere safe and added an empty index.php for good measure. I was then able to test that this PHP file (and my SQL script) was working from the browser URL line.

All good so far. On to CRON. Following the above example almost worked. I ended up calling PHP before the path for my *.php file. Otherwise CRON didn't know what to do with the file.

my cron is set to run once per day and looks like this, modified for security.

00 * * * * php mywebsiteurl.com/wp-content/themes/ForteChildTheme/php/DeleteExpiredAssessment.php

For the final testing with CRON I initially set it to run each minute and had email alerts turned on. This quickly confirmed that it was running as planned and I changed it back to once per day.

Hope this helps.

How to secure an ASP.NET Web API

in continuation to @ Cuong Le's answer , my approach to prevent replay attack would be

// Encrypt the Unix Time at Client side using the shared private key(or user's password)

// Send it as part of request header to server(WEB API)

// Decrypt the Unix Time at Server(WEB API) using the shared private key(or user's password)

// Check the time difference between the Client's Unix Time and Server's Unix Time, should not be greater than x sec

// if User ID/Hash Password are correct and the decrypted UnixTime is within x sec of server time then it is a valid request

how to load url into div tag

You need to use an iframe.

<html>
<head>
<script type="text/javascript">
    $(document).ready(function(){
    $("#content").attr("src","http://vnexpress.net");
})
</script>
</head>
<body>
<iframe id="content" src="about:blank"></iframe>
</body>
</html

Javascript/DOM: How to remove all events of a DOM object?

You can add a hook function to intercept all calls to addEventHandler. The hook will push the handler to a list that can be used for cleanup. For example,

if (EventTarget.prototype.original_addEventListener == null) {
    EventTarget.prototype.original_addEventListener = EventTarget.prototype.addEventListener;

    function addEventListener_hook(typ, fn, opt) {
        console.log('--- add event listener',this.nodeName,typ);
        this.all_handlers = this.all_handlers || [];
        this.all_handlers.push({typ,fn,opt});
        this.original_addEventListener(typ, fn, opt);  
    }

    EventTarget.prototype.addEventListener = addEventListener_hook;
}

You should insert this code near the top of your main web page (e.g. index.html). During cleanup, you can loop thru all_handlers, and call removeEventHandler for each. Don't worry about calling removeEventHandler multiple times with the same function. It is harmless.

For example,

function cleanup(elem) {
    for (let t in elem) if (t.startsWith('on') && elem[t] != null) {
        elem[t] = null;
        console.log('cleanup removed listener from '+elem.nodeName,t);
    } 
    for (let t of elem.all_handlers || []) {
        elem.removeEventListener(t.typ, t.fn, t.opt);
        console.log('cleanup removed listener from '+elem.nodeName,t.typ);
    } 
}

Note: for IE use Element instead of EventTarget, and change => to function, and various other things.

"unable to locate adb" using Android Studio

if using avast go for virus chest,will find adb,restore it by clicking right button..thats all,perfectly works

How do I make a redirect in PHP?

Using header function for routing

<?php
     header('Location: B.php');
     exit();
?>

Suppose we want to route from A.php file to B.php than we have to take help of <button> or <a>. Lets see an example

<?php
if(isset($_GET['go_to_page_b'])) {
    header('Location: B.php');
    exit();

}
?>

<p>I am page A</p>
<button name='go_to_page_b'>Page B</button>

B.php

<p> I am Page B</p>

Div with horizontal scrolling only

overflow-x: scroll;
overflow-y: hidden;

EDIT:

It works for me:

<div style='overflow-x:scroll;overflow-y:hidden;width:250px;height:200px'>
    <div style='width:400px;height:250px'></div>
</div>

How to check if a .txt file is in ASCII or UTF-8 format in Windows environment?

Open it in a hex editor and make sure that the first three bytes are a UTF8 BOM (EF BB BF)

How to auto-reload files in Node.js?

node-supervisor is awesome

usage to restart on save:

npm install supervisor -g
supervisor app.js

by isaacs - http://github.com/isaacs/node-supervisor

Phone Number Validation MVC

[DataType(DataType.PhoneNumber)] does not come with any validation logic out of the box.

According to the docs:

When you apply the DataTypeAttribute attribute to a data field you must do the following:

  • Issue validation errors as appropriate.

The [Phone] Attribute inherits from [DataType] and was introduced in .NET Framework 4.5+ and is in .NET Core which does provide it's own flavor of validation logic. So you can use like this:

[Phone()]
public string PhoneNumber { get; set; }

However, the out-of-the-box validation for Phone numbers is pretty permissive, so you might find yourself wanting to inherit from DataType and implement your own IsValid method or, as others have suggested here, use a regular expression & RegexValidator to constrain input.

Note: Use caution with Regex against unconstrained input per the best practices as .NET has made the pivot away from regular expressions in their own internal validation logic for phone numbers

Reading content from URL with Node.js

HTTP and HTTPS:

const getScript = (url) => {
    return new Promise((resolve, reject) => {
        const http      = require('http'),
              https     = require('https');

        let client = http;

        if (url.toString().indexOf("https") === 0) {
            client = https;
        }

        client.get(url, (resp) => {
            let data = '';

            // A chunk of data has been recieved.
            resp.on('data', (chunk) => {
                data += chunk;
            });

            // The whole response has been received. Print out the result.
            resp.on('end', () => {
                resolve(data);
            });

        }).on("error", (err) => {
            reject(err);
        });
    });
};

(async (url) => {
    console.log(await getScript(url));
})('https://sidanmor.com/');

Determine the size of an InputStream

You can't determine the amount of data in a stream without reading it; you can, however, ask for the size of a file:

http://java.sun.com/javase/6/docs/api/java/io/File.html#length()

If that isn't possible, you can write the bytes you read from the input stream to a ByteArrayOutputStream which will grow as required.

DOS: find a string, if found then run another script

@echo off
cls
MD %homedrive%\TEMPBBDVD\
CLS
TIMEOUT /T 1 >NUL
CLS
systeminfo >%homedrive%\TEMPBBDVD\info.txt
cls
timeout /t 3 >nul
cls
find "x64-based PC" %homedrive%\TEMPBBDVD\info.txt >nul
if %errorlevel% equ 1 goto 32bitsok
goto 64bitsok
cls

:commandlineerror
cls
echo error, command failed or you not are using windows OS.
pause >nul
cls
exit

:64bitsok
cls
echo done, system of 64 bits
pause >nul
cls
del /q /f %homedrive%\TEMPBBDVD\info.txt >nul
cls
timeout /t 1 >nul
cls
RD %homedrive%\TEMPBBDVD\ >nul
cls
exit

:32bitsok
cls
echo done, system of 32 bits
pause >nul
cls
del /q /f %homedrive%\TEMPBBDVD\info.txt >nul
cls
timeout /t 1 >nul
cls
RD %homedrive%\TEMPBBDVD\ >nul
cls
exit

Get the length of a String

Swift 4 update comparing with swift 3

Swift 4 removes the need for a characters array on String. This means that you can directly call count on a string without getting characters array first.

"hello".count                  // 5

Whereas in swift 3, you will have to get characters array and then count element in that array. Note that this following method is still available in swift 4.0 as you can still call characters to access characters array of the given string

"hello".characters.count       // 5

Swift 4.0 also adopts Unicode 9 and it can now interprets grapheme clusters. For example, counting on an emoji will give you 1 while in swift 3.0, you may get counts greater than 1.

"".count // Swift 4.0 prints 1, Swift 3.0 prints 2
"?????".count // Swift 4.0 prints 1, Swift 3.0 prints 4

How to check if a string starts with a specified string?

You can check if your string starts with http or https using the small function below.

function has_prefix($string, $prefix) {
   return substr($string, 0, strlen($prefix)) == $prefix;
}

$url   = 'http://www.google.com';
echo 'the url ' . (has_prefix($url, 'http://')  ? 'does' : 'does not') . ' start with http://';
echo 'the url ' . (has_prefix($url, 'https://') ? 'does' : 'does not') . ' start with https://';

How do you run a command for each line of a file?

I see that you tagged bash, but Perl would also be a good way to do this:

perl -p -e '`chmod 755 $_`' file.txt

You could also apply a regex to make sure you're getting the right files, e.g. to only process .txt files:

perl -p -e 'if(/\.txt$/) `chmod 755 $_`' file.txt

To "preview" what's happening, just replace the backticks with double quotes and prepend print:

perl -p -e 'if(/\.txt$/) print "chmod 755 $_"' file.txt

Building and running app via Gradle and Android Studio is slower than via Eclipse

You could make the process faster, if you use gradle from command line. There is a lot of optimization to do for the IDE developers. But it is just an early version.

For more information read this discussion on g+ with some of the devs.

In Bootstrap open Enlarge image in modal

css:

img.modal-img {
  cursor: pointer;
  transition: 0.3s;
}
img.modal-img:hover {
  opacity: 0.7;
}
.img-modal {
  display: none;
  position: fixed;
  z-index: 99999;
  padding-top: 100px;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0,0,0,0.9);
}
.img-modal img {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700%;
}
.img-modal div {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
  text-align: center;
  color: #ccc;
  padding: 10px 0;
  height: 150px;
}
.img-modal img, .img-modal div {
  animation: zoom 0.6s;
}
.img-modal span {
  position: absolute;
  top: 15px;
  right: 35px;
  color: #f1f1f1;
  font-size: 40px;
  font-weight: bold;
  transition: 0.3s;
  cursor: pointer;
}
@media only screen and (max-width: 700px) {
  .img-modal img {
    width: 100%;
  }
}
@keyframes zoom {
  0% {
    transform: scale(0);
  }
  100% {
    transform: scale(1);
  }
}

Javascript:

_x000D_
_x000D_
$('img.modal-img').each(function() {_x000D_
    var modal = $('<div class="img-modal"><span>&times;</span><img /><div></div></div>');_x000D_
    modal.find('img').attr('src', $(this).attr('src'));_x000D_
    if($(this).attr('alt'))_x000D_
      modal.find('div').text($(this).attr('alt'));_x000D_
    $(this).after(modal);_x000D_
    modal = $(this).next();_x000D_
    $(this).click(function(event) {_x000D_
      modal.show(300);_x000D_
      modal.find('span').show(0.3);_x000D_
    });_x000D_
    modal.find('span').click(function(event) {_x000D_
      modal.hide(300);_x000D_
    });_x000D_
  });_x000D_
  $(document).keyup(function(event) {_x000D_
    if(event.which==27)_x000D_
      $('.img-modal>span').click();_x000D_
  });
_x000D_
img.modal-img {_x000D_
  cursor: pointer;_x000D_
  transition: 0.3s;_x000D_
}_x000D_
img.modal-img:hover {_x000D_
  opacity: 0.7;_x000D_
}_x000D_
.img-modal {_x000D_
  display: none;_x000D_
  position: fixed;_x000D_
  z-index: 99999;_x000D_
  padding-top: 100px;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  overflow: auto;_x000D_
  background-color: rgba(0,0,0,0.9);_x000D_
}_x000D_
.img-modal img {_x000D_
  margin: auto;_x000D_
  display: block;_x000D_
  width: 80%;_x000D_
  max-width: 700%;_x000D_
}_x000D_
.img-modal div {_x000D_
  margin: auto;_x000D_
  display: block;_x000D_
  width: 80%;_x000D_
  max-width: 700px;_x000D_
  text-align: center;_x000D_
  color: #ccc;_x000D_
  padding: 10px 0;_x000D_
  height: 150px;_x000D_
}_x000D_
.img-modal img, .img-modal div {_x000D_
  animation: zoom 0.6s;_x000D_
}_x000D_
.img-modal span {_x000D_
  position: absolute;_x000D_
  top: 15px;_x000D_
  right: 35px;_x000D_
  color: #f1f1f1;_x000D_
  font-size: 40px;_x000D_
  font-weight: bold;_x000D_
  transition: 0.3s;_x000D_
  cursor: pointer;_x000D_
}_x000D_
@media only screen and (max-width: 700px) {_x000D_
  .img-modal img {_x000D_
    width: 100%;_x000D_
  }_x000D_
}_x000D_
@keyframes zoom {_x000D_
  0% {_x000D_
    transform: scale(0);_x000D_
  }_x000D_
  100% {_x000D_
    transform: scale(1);_x000D_
  }_x000D_
}_x000D_
Javascript:_x000D_
_x000D_
$('img.modal-img').each(function() {_x000D_
    var modal = $('<div class="img-modal"><span>&times;</span><img /><div></div></div>');_x000D_
    modal.find('img').attr('src', $(this).attr('src'));_x000D_
    if($(this).attr('alt'))_x000D_
      modal.find('div').text($(this).attr('alt'));_x000D_
    $(this).after(modal);_x000D_
    modal = $(this).next();_x000D_
    $(this).click(function(event) {_x000D_
      modal.show(300);_x000D_
      modal.find('span').show(0.3);_x000D_
    });_x000D_
    modal.find('span').click(function(event) {_x000D_
      modal.hide(300);_x000D_
    });_x000D_
  });_x000D_
  $(document).keyup(function(event) {_x000D_
    if(event.which==27)_x000D_
      $('.img-modal>span').click();_x000D_
  });_x000D_
_x000D_
HTML:
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<img src="http://www.google.com/favicon.ico" class="modal-img">
_x000D_
_x000D_
_x000D_

How to create a 100% screen width div inside a container in bootstrap?

2019's answer as this is still actively seen today

You should likely change the .container to .container-fluid, which will cause your container to stretch the entire screen. This will allow any div's inside of it to naturally stretch as wide as they need.

original hack from 2015 that still works in some situations

You should pull that div outside of the container. You're asking a div to stretch wider than its parent, which is generally not recommended practice.

If you cannot pull it out of the div for some reason, you should change the position style with this css:

.full-width-div {
    position: absolute;
    width: 100%;
    left: 0;
}

Instead of absolute, you could also use fixed, but then it will not move as you scroll.

Draw text in OpenGL ES

For static text:

  • Generate an image with all words used on your PC (For example with GIMP).
  • Load this as a texture and use it as material for a plane.

For long text that needs to be updated once in a while:

  • Let android draw on a bitmap canvas (JVitela's solution).
  • Load this as material for a plane.
  • Use different texture coordinates for each word.

For a number (formatted 00.0):

  • Generate an image with all numbers and a dot.
  • Load this as material for a plane.
  • Use below shader.
  • In your onDraw event only update the value variable sent to the shader.

    precision highp float;
    precision highp sampler2D;
    
    uniform float uTime;
    uniform float uValue;
    uniform vec3 iResolution;
    
    varying vec4 v_Color;
    varying vec2 vTextureCoord;
    uniform sampler2D s_texture;
    
    void main() {
    
    vec4 fragColor = vec4(1.0, 0.5, 0.2, 0.5);
    vec2 uv = vTextureCoord;
    
    float devisor = 10.75;
    float digit;
    float i;
    float uCol;
    float uRow;
    
    if (uv.y < 0.45) {
        if (uv.x > 0.75) {
            digit = floor(uValue*10.0);
            digit = digit - floor(digit/10.0)*10.0;
            i = 48.0 - 32.0 + digit;
            uRow = floor(i / 10.0);
            uCol = i - 10.0 * uRow;
            fragColor = texture2D( s_texture, uv / devisor * 2.0 + vec2((uCol-1.5) / devisor, uRow / devisor) );
        } else if (uv.x > 0.5) {
            uCol = 4.0;
            uRow = 1.0;
            fragColor = texture2D( s_texture, uv / devisor * 2.0 + vec2((uCol-1.0) / devisor, uRow / devisor) );
        } else if (uv.x > 0.25) {
            digit = floor(uValue);
            digit = digit - floor(digit/10.0)*10.0;
            i = 48.0 - 32.0 + digit;
            uRow = floor(i / 10.0);
            uCol = i - 10.0 * uRow;
            fragColor = texture2D( s_texture, uv / devisor * 2.0 + vec2((uCol-0.5) / devisor, uRow / devisor) );
        } else if (uValue >= 10.0) {
            digit = floor(uValue/10.0);
            digit = digit - floor(digit/10.0)*10.0;
            i = 48.0 - 32.0 + digit;
            uRow = floor(i / 10.0);
            uCol = i - 10.0 * uRow;
            fragColor = texture2D( s_texture, uv / devisor * 2.0 + vec2((uCol-0.0) / devisor, uRow / devisor) );
        } else {
            fragColor = vec4(0.0, 0.0, 0.0, 0.0);
        }
    } else {
        fragColor = vec4(0.0, 0.0, 0.0, 0.0);
    }
    gl_FragColor = fragColor;
    
    }
    

Above code works for a texture atlas where numbers start from 0 at the 7th column of the 2nd row of the font atlas (texture).

Refer to https://www.shadertoy.com/view/Xl23Dw for demonstration (with wrong texture though)

Google Maps: Auto close open InfoWindows?

//assuming you have a map called 'map'
var infowindow = new google.maps.InfoWindow();

var latlng1 = new google.maps.LatLng(0,0);
var marker1 = new google.maps.Marker({position:latlng1, map:map});
google.maps.event.addListener(marker1, 'click',
    function(){
        infowindow.close();//hide the infowindow
        infowindow.setContent('Marker #1');//update the content for this marker
        infowindow.open(map, marker1);//"move" the info window to the clicked marker and open it
    }
);
var latlng2 = new google.maps.LatLng(10,10);
var marker2 = new google.maps.Marker({position:latlng2, map:map});
google.maps.event.addListener(marker2, 'click',
    function(){
        infowindow.close();//hide the infowindow
        infowindow.setContent('Marker #2');//update the content for this marker
        infowindow.open(map, marker2);//"move" the info window to the clicked marker and open it
    }
);

This will "move" the info window around to each clicked marker, in effect closing itself, then reopening (and panning to fit the viewport) in its new location. It changes its contents before opening to give the desired effect. Works for n markers.

How do I lock the orientation to portrait mode in a iPhone Web Application?

In coffee if anyone needs it.

    $(window).bind 'orientationchange', ->
        if window.orientation % 180 == 0
            $(document.body).css
                "-webkit-transform-origin" : ''
                "-webkit-transform" : ''
        else
            if window.orientation > 0
                $(document.body).css
                    "-webkit-transform-origin" : "200px 190px"
                    "-webkit-transform" : "rotate(-90deg)"
            else
                $(document.body).css
                    "-webkit-transform-origin" : "280px 190px"
                    "-webkit-transform" : "rotate(90deg)"

How do you make div elements display inline?

As mentioned, display:inline is probably what you want. Some browsers also support inline-blocks.

http://www.quirksmode.org/css/display.html#inlineblock

PostgreSQL return result set as JSON array?

Also if you want selected field from table and aggregated then as array .

SELECT json_agg(json_build_object('data_a',a,
                                  'data_b',b,
))  from t;

The result will come .

 [{'data_a':1,'data_b':'value1'}
  {'data_a':2,'data_b':'value2'}]

What is the best way to get all the divisors of a number?

Given your factorGenerator function, here is a divisorGen that should work:

def divisorGen(n):
    factors = list(factorGenerator(n))
    nfactors = len(factors)
    f = [0] * nfactors
    while True:
        yield reduce(lambda x, y: x*y, [factors[x][0]**f[x] for x in range(nfactors)], 1)
        i = 0
        while True:
            f[i] += 1
            if f[i] <= factors[i][1]:
                break
            f[i] = 0
            i += 1
            if i >= nfactors:
                return

The overall efficiency of this algorithm will depend entirely on the efficiency of the factorGenerator.

Response Buffer Limit Exceeded

If you are not allowed to change the buffer limit at the server level, you will need to use the <%Response.Buffer = False%> method.

HOWEVER, if you are still getting this error and have a large table on the page, the culprit may be table itself. By design, some versions of Internet Explorer will buffer the entire content between before it is rendered to the page. So even if you are telling the page to not buffer the content, the table element may be buffered and causing this error.

Some alternate solutions may be to paginate the table results, but if you must display the entire table and it has thousands of rows, throw this line of code in the middle of the table generation loop: <% Response.Flush %>. For speed considerations, you may also want to consider adding a basic counter so that the flush only happens every 25 or 100 lines or so.

Drawbacks of not buffering the output:

  1. slowdown of overall page load
  2. tables and columns will adjust their widths as content is populated (table appears to wiggle)
  3. Users will be able to click on links and interact with the page before it is fully loaded. So if you have some javascript at the bottom of the page, you may want to move it to the top to ensure it is loaded before some of your faster moving users click on things.

See this KB article for more information http://support.microsoft.com/kb/925764

Hope that helps.

How to calculate growth with a positive and negative number?

You could try shifting the number space upward so they both become positive.

To calculate a gain between any two positive or negative numbers, you're going to have to keep one foot in the magnitude-growth world and the other foot in the volume-growth world. You can lean to one side or the other depending on how you want the result gains to appear, and there are consequences to each choice.

Strategy

  1. Create a shift equation that generates a positive number relative to the old and new numbers.

  2. Add the custom shift to the old and new numbers to get new_shifted and old_shifted.

  3. Take the (new_shifted - old_shifted) / old_shifted) calculation to get the gain.

For example:

old -> new
-50 -> 30               //Calculate a shift like (2*(50 + 30)) = 160

shifted_old -> shifted_new
110         ->  190

= (new-old)/old
= (190-110)/110 = 72.73%

How to choose a shift function

If your shift function shifts the numbers too far upward, like for example adding 10000 to each number, you always get a tiny growth/decline. But if the shift is just big enough to get both numbers into positive territory, you'll get wild swings in the growth/decline on edge cases. You'll need to dial in the shift function so it makes sense for your particular application. There is no totally correct solution to this problem, you must take the bitter with the sweet.

Add this to your excel to see how the numbers and gains move about:

                           shift function
old new  abs_old  abs_new  2*abs(old)+abs(new)   shiftedold  shiftednew    gain
-50  30  50          30          160                110         190        72.73%
-50  40  50          40          180                130         220        69.23%
10   20  10          20          60                 70          80         14.29%
10   30  10          30          80                 90          110        22.22%
1    10  1           10          22                 23          32         39.13%
1    20  1           20          42                 43          62         44.19%
-10  10  10          10          40                 30          50         66.67%
-10  20  10          20          60                 50          80         60.00%
1    100  1          100         202                203         302        48.77%
1    1000 1          1000        2002               2003        3002       49.88%

The gain percentage is affected by the magnitude of the numbers. The numbers above are a bad example and result from a primitive shift function.

You have to ask yourself which critter has the most productive gain:

Evaluate the growth of critters A, B, C, and D:
A used to consume 0.01 units of energy and now consumes 10 units.
B used to consume 500 units and now consumes 700 units.
C used to consume -50 units (Producing units!) and now consumes 30 units.
D used to consume -0.01 units (Producing) and now consumes -30 units (producing).

In some ways arguments can be made that each critter is the biggest grower in their own way. Some people say B is best grower, others will say D is a bigger gain. You have to decide for yourself which is better.

The question becomes, can we map this intuitive feel of what we label as growth into a continuous function that tells us what humans tend to regard as "awesome growth" vs "mediocre growth".

Growth a mysterious thing

You then have to take into account that Critter B may have had a far more difficult time than critter D. Critter D may have far more prospects for it in the future than the others. It had an advantage! How do you measure the opportunity, difficulty, velocity and acceleration of growth? To be able to predict the future, you need to have an intuitive feel for what constitutes a "major home run" and a "lame advance in productivity".

The first and second derivatives of a function will give you the "velocity of growth" and "acceleration of growth". Learn about those in calculus, they are super important.

Which is growing more? A critter that is accelerating its growth minute by minute, or a critter that is decelerating its growth? What about high and low velocity and high/low rate of change? What about the notion of exhausting opportunities for growth. Cost benefit analysis and ability/inability to capitalize on opportunity. What about adversarial systems (where your success comes from another person's failure) and zero sum games?

There is exponential growth, liner growth. And unsustainable growth. Cost benefit analysis and fitting a curve to the data. The world is far queerer than we can suppose. Plotting a perfect line to the data does not tell you which data point comes next because of the black swan effect. I suggest all humans listen to this lecture on growth, the University of Colorado At Boulder gave a fantastic talk on growth, what it is, what it isn't, and how humans completely misunderstand it. http://www.youtube.com/watch?v=u5iFESMAU58

Fit a line to the temperature of heated water, once you think you've fit a curve, a black swan happens, and the water boils. This effect happens all throughout our universe, and your primitive function (new-old)/old is not going to help you.

Here is Java code that accomplishes most of the above notions in a neat package that suits my needs:

Critter growth - (a critter can be "radio waves", "beetles", "oil temprature", "stock options", anything).

public double evaluate_critter_growth_return_a_gain_percentage(
        double old_value, double new_value) throws Exception{

    double abs_old = Math.abs(old_value);
    double abs_new = Math.abs(new_value);

    //This is your shift function, fool around with it and see how
    //It changes.  Have a full battery of unit tests though before you fiddle.
    double biggest_absolute_value = (Math.max(abs_old, abs_new)+1)*2;

    if (new_value <= 0 || old_value <= 0){
        new_value = new_value + (biggest_absolute_value+1);
        old_value = old_value + (biggest_absolute_value+1);
    }

    if (old_value == 0 || new_value == 0){
        old_value+=1;
        new_value+=1;
    }

    if (old_value <= 0)
        throw new Exception("This should never happen.");

    if (new_value <= 0)
        throw new Exception("This should never happen.");


    return (new_value - old_value) / old_value;


}

Result

It behaves kind-of sort-of like humans have an instinctual feel for critter growth. When our bank account goes from -9000 to -3000, we say that is better growth than when the account goes from 1000 to 2000.

1->2     (1.0)  should be bigger than   1->1 (0.0)
1->2     (1.0)  should be smaller than  1->4 (3.0)
0->1     (0.2)  should be smaller than  1->3 (2.0)
-5-> -3  (0.25) should be smaller than -5->-1 (0.5)
-5->1    (0.75) should be smaller than -5->5 (1.25)
100->200 (1.0)  should be the same as  10->20 (1.0)
-10->1   (0.84) should be smaller than -20->1 (0.91)
-10->10  (1.53) should be smaller than -20->20 (1.73)
-200->200 should not be in outer space (say more than 500%):(1.97)
handle edge case 1-> -4: (-0.41)
1-> -4:  (-0.42) should be bigger than 1-> -9:(-0.45)

If my shift function makes sense for your needs, use it. Be sure to battle test this, if you crash the space shuttle its totally NOT my fault. This method is a heuristic.

Is it better to use path() or url() in urls.py for django 2.0?

path is simply new in Django 2.0, which was only released a couple of weeks ago. Most tutorials won't have been updated for the new syntax.

It was certainly supposed to be a simpler way of doing things; I wouldn't say that URL is more powerful though, you should be able to express patterns in either format.

How to vertically align text inside a flexbox?

It's depend on your li height just call one more thing line height

_x000D_
_x000D_
* {
  padding: 0;
  margin: 0;
}

html,
body {
  height: 100%;
}

ul {
  height: 100%;
}

li {
  display: flex;
  justify-content: center;
  align-self: center;
  background: silver;
  width: 100%;
  height:50px;line-height:50px;
}
_x000D_
<ul>
  <li>This is the text</li>
</ul>
_x000D_
_x000D_
_x000D_

MATLAB, Filling in the area between two sets of data, lines in one figure

You can accomplish this using the function FILL to create filled polygons under the sections of your plots. You will want to plot the lines and polygons in the order you want them to be stacked on the screen, starting with the bottom-most one. Here's an example with some sample data:

x = 1:100;             %# X range
y1 = rand(1,100)+1.5;  %# One set of data ranging from 1.5 to 2.5
y2 = rand(1,100)+0.5;  %# Another set of data ranging from 0.5 to 1.5
baseLine = 0.2;        %# Baseline value for filling under the curves
index = 30:70;         %# Indices of points to fill under

plot(x,y1,'b');                              %# Plot the first line
hold on;                                     %# Add to the plot
h1 = fill(x(index([1 1:end end])),...        %# Plot the first filled polygon
          [baseLine y1(index) baseLine],...
          'b','EdgeColor','none');
plot(x,y2,'g');                              %# Plot the second line
h2 = fill(x(index([1 1:end end])),...        %# Plot the second filled polygon
          [baseLine y2(index) baseLine],...
          'g','EdgeColor','none');
plot(x(index),baseLine.*ones(size(index)),'r');  %# Plot the red line

And here's the resulting figure:

enter image description here

You can also change the stacking order of the objects in the figure after you've plotted them by modifying the order of handles in the 'Children' property of the axes object. For example, this code reverses the stacking order, hiding the green polygon behind the blue polygon:

kids = get(gca,'Children');        %# Get the child object handles
set(gca,'Children',flipud(kids));  %# Set them to the reverse order

Finally, if you don't know exactly what order you want to stack your polygons ahead of time (i.e. either one could be the smaller polygon, which you probably want on top), then you could adjust the 'FaceAlpha' property so that one or both polygons will appear partially transparent and show the other beneath it. For example, the following will make the green polygon partially transparent:

set(h2,'FaceAlpha',0.5);

Creating a Plot Window of a Particular Size

Use dev.new(). (See this related question.)

plot(1:10)
dev.new(width=5, height=4)
plot(1:20)

To be more specific which units are used:

dev.new(width=5, height=4, unit="in")
plot(1:20)
dev.new(width = 550, height = 330, unit = "px")
plot(1:15)

edit additional argument for Rstudio (May 2020), (thanks user Soren Havelund Welling)

For Rstudio, add dev.new(width=5,height=4,noRStudioGD = TRUE)

Windows could not start the Apache2 on Local Computer - problem

Run the httpd.exe from the command line, as Tim mentioned. The path to PostgreSQL changed, nothing else was running on Port 80 and I didn't see anything in the error.log file.

I clone my boot drive/partition once the base is setup so I don't have to spend three days installing and retweaking everything. Turns I had reinstalled my WAPP stack and used very specific names/versions for PostgreSQL. Windows will not return a specific error message unless you run the command from the command line.

IsNumeric function in c#

Is numeric can be achieved via many ways, but i use my way

public bool IsNumeric(string value)
{
    bool isNumeric = true;
    char[] digits = "0123456789".ToCharArray();
    char[] letters = value.ToCharArray();
    for (int k = 0; k < letters.Length; k++)
    {
        for (int i = 0; i < digits.Length; i++)
        {
            if (letters[k] != digits[i])
            {
                isNumeric = false;
                break;
            }
        }
    }
    return isNumeric;
}

Python how to write to a binary file?

As of Python 3.2+, you can also accomplish this using the to_bytes native int method:

newFileBytes = [123, 3, 255, 0, 100]
# make file
newFile = open("filename.txt", "wb")
# write to file
for byte in newFileBytes:
    newFile.write(byte.to_bytes(1, byteorder='big'))

I.e., each single call to to_bytes in this case creates a string of length 1, with its characters arranged in big-endian order (which is trivial for length-1 strings), which represents the integer value byte. You can also shorten the last two lines into a single one:

newFile.write(''.join([byte.to_bytes(1, byteorder='big') for byte in newFileBytes]))

Android Studio : How to uninstall APK (or execute adb command) automatically before Run or Debug?

I use an Android Studio plug-in called "adb idea" -- has a drop down menu for various functions (Uninstall, Kill, Start, etc) that you can target at any connected or simulated device. One could argue it takes me a step away from having a deeper understanding of the power of adb commands and I'd probably agree....though I'm really operating at a lower level of understanding anyway so for me it helps to have a helper. ADB Idea enter image description here

Highlight Bash/shell code in Markdown files

Per the documentation from GitHub regarding GFM syntax highlighted code blocks

We use Linguist to perform language detection and syntax highlighting. You can find out which keywords are valid in the languages YAML file.

Rendered on GitHub, console makes the lines after the console blue. bash, sh, or shell don't seem to "highlight" much ...and you can use posh for PowerShell or CMD.

Python 101: Can't open file: No such file or directory

Try uninstalling Python and then install it again, but this time make sure that the option Add Python to Path is marked as checked during the installation process.

DirectX SDK (June 2010) Installation Problems: Error Code S1023

I had the same problem and for me it was because the vc2010 redist x86 was too recent.

Check your temp folder (C:\Users\\AppData\Local\Temp) for the most recent file named

Microsoft Visual C++ 2010 x64 Redistributable Setup_20110608_xxx.html ##

and check if you have the following error

Installation Blockers:

A newer version of Microsoft Visual C++ 2010 Redistributable has been detected on the machine.

Final Result: Installation failed with error code: (0x000013EC), "A StopBlock was hit or a System >Requirement was not met." (Elapsed time: 0 00:00:00).

then go to Control Panel>Program & Features and uninstall all the

Microsoft Visual C++ 2010 x86/x64 redistributable - 10.0.(number over 30319)

After successful installation of DXSDK, simply run Windows Update and it will update the redistributables back to the latest version.

Angular and Typescript: Can't find names - Error: cannot find name

I was able to fix this by installing the typings module.

npm install -g typings
typings install

(Using ng 2.0.0-rc.1)

Permanently add a directory to PYTHONPATH?

On linux you can create a symbolic link from your package to a directory of the PYTHONPATH without having to deal with the environment variables. Something like:

ln -s /your/path /usr/lib/pymodules/python2.7/

Converting list to *args when calling function

*args just means that the function takes a number of arguments, generally of the same type.

Check out this section in the Python tutorial for more info.

Regex to match any character including new lines

Yeap, you just need to make . match newline :

$string =~ /(START)(.+?)(END)/s;

How to set password for Redis?

For those who use docker-compose, it’s really easy to set a password without any config file like redis.conf. Here’s how you would normally use the official Redis image:

redis:
    image: 'redis:4-alpine'
    ports:
      - '6379:6379'

And here’s all you need to change to set a custom password:

  redis:
    image: 'redis:4-alpine'
    command: redis-server --requirepass yourpassword
    ports:
      - '6379:6379'

Everything will start up as normal and your Redis server will be protected by a password.

For details, this blog post seems to support the idea.

How to remove the querystring and get only the url?

Most Easiest Way

$url = 'https://www.youtube.com/embed/ROipDjNYK4k?rel=0&autoplay=1';
$url_arr = parse_url($url);
$query = $url_arr['query'];
print $url = str_replace(array($query,'?'), '', $url);

//output
https://www.youtube.com/embed/ROipDjNYK4k

Get content of a DIV using JavaScript

You need to set Div2 to Div1's innerHTML. Also, JavaScript is case sensitive - in your HTML, the id Div2 is DIV2. Also, you should use document, not Document:

var MyDiv1 = document.getElementById('DIV1');
var MyDiv2 = document.getElementById('DIV2');
MyDiv2.innerHTML = MyDiv1.innerHTML; 

Here is a JSFiddle: http://jsfiddle.net/gFN6r/.

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

This is code in xml of how to center an ImageView, I used "layout_centerHorizontal".

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_centerHorizontal="true"
    >
    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:src="@drawable/img2"
    />
    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:src="@drawable/img1"
        />
</LinearLayout>

or this other example...

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:gravity="center_horizontal"
    >
    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:src="@drawable/img2"
    />
    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:src="@drawable/img1"
        />
</LinearLayout>

how to find all indexes and their columns for tables, views and synonyms in oracle

Your query should work for synonyms as well as the tables. However, you seem to expect indexes on views where there are not. Maybe is it materialized views ?

detect back button click in browser

best way I know

         window.onbeforeunload = function (e) {
            var e = e || window.event;
            var msg = "Do you really want to leave this page?"

            // For IE and Firefox
            if (e) {
                e.returnValue = msg;
            }

            // For Safari / chrome
            return msg;
         };

how to sort pandas dataframe from one column

This worked for me

df.sort_values(by='Column_name', inplace=True, ascending=False)

Append to the end of a file in C

Following the documentation of fopen:

``a'' Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then cur- rent end of file, irrespective of any intervening fseek(3) or similar.

So if you pFile2=fopen("myfile2.txt", "a"); the stream is positioned at the end to append automatically. just do:

FILE *pFile;
FILE *pFile2;
char buffer[256];

pFile=fopen("myfile.txt", "r");
pFile2=fopen("myfile2.txt", "a");
if(pFile==NULL) {
    perror("Error opening file.");
}
else {
    while(fgets(buffer, sizeof(buffer), pFile)) {
        fprintf(pFile2, "%s", buffer);
    }
}
fclose(pFile);
fclose(pFile2);

Get the current URL with JavaScript?

To get the path, you can use:

_x000D_
_x000D_
console.log('document.location', document.location.href);_x000D_
console.log('location.pathname',  window.location.pathname); // Returns path only_x000D_
console.log('location.href', window.location.href); // Returns full URL
_x000D_
_x000D_
_x000D_

How to check if a process is running via a batch script

You should check the parent process name, see The Code Project article about a .NET based solution**.

A non-programmatic way to check:

  1. Launch Cmd.exe
  2. Launch an application (for instance, c:\windows\notepad.exe)
  3. Check properties of the Notepad.exe process in Process Explorer
  4. Check for parent process (This shows cmd.exe)

The same can be checked by getting the parent process name.

Checking if a worksheet-based checkbox is checked

Sub Button167_Click()
 If ThisWorkbook.Worksheets(1).Shapes("Check Box 1").OLEFormat.Object.Value = 1 Then
 Range("Y12").Value = 1
 Else
 Range("Y12").Value = 0
 End If
End Sub

1 is checked, -4146 is unchecked, 2 is mixed (grey box)

Smooth scroll without the use of jQuery

You can use a for loop with window.scrollTo and setTimeout to scroll smoothly with plain Javascript. To scroll to an element with my scrollToSmoothly function: scrollToSmoothly(elem.offsetTop) (assuming elem is a DOM element). You can use this to scroll smoothly to any y-position in the document.

function scrollToSmoothly(pos, time){
/*Time is only applicable for scrolling upwards*/
/*Code written by hev1*/
/*pos is the y-position to scroll to (in pixels)*/
     if(isNaN(pos)){
      throw "Position must be a number";
     }
     if(pos<0){
     throw "Position can not be negative";
     }
    var currentPos = window.scrollY||window.screenTop;
    if(currentPos<pos){
    var t = 10;
       for(let i = currentPos; i <= pos; i+=10){
       t+=10;
        setTimeout(function(){
        window.scrollTo(0, i);
        }, t/2);
      }
    } else {
    time = time || 2;
       var i = currentPos;
       var x;
      x = setInterval(function(){
         window.scrollTo(0, i);
         i -= 10;
         if(i<=pos){
          clearInterval(x);
         }
     }, time);
      }
}

Demo:

_x000D_
_x000D_
<button onClick="scrollToDiv()">Scroll To Element</button>_x000D_
<div style="margin: 1000px 0px; text-align: center;">Div element<p/>_x000D_
<button onClick="scrollToSmoothly(Number(0))">Scroll back to top</button>_x000D_
</div>_x000D_
<script>_x000D_
function scrollToSmoothly(pos, time){_x000D_
/*Time is only applicable for scrolling upwards*/_x000D_
/*Code written by hev1*/_x000D_
/*pos is the y-position to scroll to (in pixels)*/_x000D_
     if(isNaN(pos)){_x000D_
      throw "Position must be a number";_x000D_
     }_x000D_
     if(pos<0){_x000D_
     throw "Position can not be negative";_x000D_
     }_x000D_
    var currentPos = window.scrollY||window.screenTop;_x000D_
    if(currentPos<pos){_x000D_
    var t = 10;_x000D_
       for(let i = currentPos; i <= pos; i+=10){_x000D_
       t+=10;_x000D_
        setTimeout(function(){_x000D_
       window.scrollTo(0, i);_x000D_
        }, t/2);_x000D_
      }_x000D_
    } else {_x000D_
    time = time || 2;_x000D_
       var i = currentPos;_x000D_
       var x;_x000D_
      x = setInterval(function(){_x000D_
         window.scrollTo(0, i);_x000D_
         i -= 10;_x000D_
         if(i<=pos){_x000D_
          clearInterval(x);_x000D_
         }_x000D_
     }, time);_x000D_
      }_x000D_
}_x000D_
function scrollToDiv(){_x000D_
  var elem = document.querySelector("div");_x000D_
  scrollToSmoothly(elem.offsetTop);_x000D_
}_x000D_
</script>
_x000D_
_x000D_
_x000D_

How do I shut down a python simpleHTTPserver?

It seems like overkill but you can use supervisor to start and stop your simpleHttpserver, and completely manage it as a service.

Or just run it in the foreground as suggested and kill it with control c

How do you convert a byte array to a hexadecimal string in C?

If you want to store the hex values in a char * string, you can use snprintf. You need to allocate space for all the printed characters, including the leading zeros and colon.

Expanding on Mark's answer:

char str_buf* = malloc(3*X + 1);   // X is the number of bytes to be converted

int i;
for (i = 0; i < x; i++)
{
    if (i > 0) snprintf(str_buf, 1, ":");
    snprintf(str_buf, 2, "%02X", num_buf[i]);  // need 2 characters for a single hex value
}
snprintf(str_buf, 2, "\n\0"); // dont forget the NULL byte

So now str_buf will contain the hex string.

How to use a calculated column to calculate another column in the same view

In SQL Server

You can do this using With CTE

WITH common_table_expression (Transact-SQL)

CREATE TABLE tab(ColumnA DECIMAL(10,2), ColumnB DECIMAL(10,2), ColumnC DECIMAL(10,2))

INSERT INTO tab(ColumnA, ColumnB, ColumnC) VALUES (2, 10, 2),(3, 15, 6),(7, 14, 3)

WITH tab_CTE (ColumnA, ColumnB, ColumnC,calccolumn1)  
AS  
(  
Select
    ColumnA,
    ColumnB,
    ColumnC,
    ColumnA + ColumnB As calccolumn1
  from tab
)  

SELECT
  ColumnA,
  ColumnB,
  calccolumn1,
  calccolumn1 / ColumnC AS calccolumn2
FROM  tab_CTE

DBFiddle Demo

W3WP.EXE using 100% CPU - where to start?

If you identify a page that takes time to load, use SharePoint's Developer Dashboard to see which component takes time.

git: can't push (unpacker error) related to permission issues

I had this error for two weeks, and the majority of the solutions stated 'chmod -R' as the the answer, unfortunately for me my git repos (local / remote / shared - with team) were all on Windows OS, and even though chmod -Rv showed all the files changed to 'rwxrwxrwx', a subsequent 'ls -l' still showed all files as 'rwxr-xr-x' and the error repeated itself. I eventually saw this solution by Ariejan de Vroom. It worked and we were all able to pull and push again.

On both local (the local that is having trouble pushing) and remote repos, run the following commands:

$ git fsck
$ git prune
$ git repack
$ git fsck

On a side note, I tried using Windows' native file permissions / ACL and even resorted to elevating the problem user to Administrator, but none of that seemed to help. Not sure if the environment is important, but it may help someone with a similar setup - problem team member and remote (Windows Server 2008 R2 Standard), my local (Windows 7 VM).

How to find out the MySQL root password

This worked for me:

On terminal type the following

$ sudo mysql -u root -p

Enter password://just press enter

mysql>

Combining paste() and expression() functions in plot labels

Very nice example using paste and substitute to typeset both symbols (mathplot) and variables at http://vis.supstat.com/2013/04/mathematical-annotation-in-r/

Here is a ggplot adaptation

library(ggplot2)
x_mean <- 1.5
x_sd <- 1.2
N <- 500

n <- ggplot(data.frame(x <- rnorm(N, x_mean, x_sd)),aes(x=x)) +
    geom_bar() + stat_bin() +
    labs(title=substitute(paste(
             "Histogram of random data with ",
             mu,"=",m,", ",
             sigma^2,"=",s2,", ",
             "draws = ", numdraws,", ",
             bar(x),"=",xbar,", ",
             s^2,"=",sde),
             list(m=x_mean,xbar=mean(x),s2=x_sd^2,sde=var(x),numdraws=N)))

print(n)

How to make a 3-level collapsing menu in Bootstrap?

Bootstrap 2.3.x and later supports the dropdown-submenu..

<ul class="dropdown-menu">
            <li><a href="#">Login</a></li>
            <li class="dropdown-submenu">
                <a tabindex="-1" href="#">More options</a>
                <ul class="dropdown-menu">
                    <li><a tabindex="-1" href="#">Second level</a></li>
                    <li><a href="#">Second level</a></li>
                    <li><a href="#">Second level</a></li>
                </ul>
            </li>
            <li><a href="#">Logout</a></li>
</ul>

Working demo on Bootply.com

Check orientation on Android phone

Another way of solving this problem is by not relying on the correct return value from the display but relying on the Android resources resolving.

Create the file layouts.xml in the folders res/values-land and res/values-port with the following content:

res/values-land/layouts.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <bool name="is_landscape">true</bool>
</resources>

res/values-port/layouts.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <bool name="is_landscape">false</bool>
</resources>

In your source code you can now access the current orientation as follows:

context.getResources().getBoolean(R.bool.is_landscape)

Adding items in a Listbox with multiple columns

By using the List property.

ListBox1.AddItem "foo"
ListBox1.List(ListBox1.ListCount - 1, 1) = "bar"

Python 2.7 getting user input and manipulating as string without quotations

This is my work around to fail safe in case if i will need to move to python 3 in future.

def _input(msg):
  return raw_input(msg)

Can I hide the HTML5 number input’s spin box?

I've encountered this problem with a input[type="datetime-local"], which is similar to this problem.

And I've found a way to overcome this kind of problems.

First, you must turn on chrome's shadow-root feature by "DevTools -> Settings -> General -> Elements -> Show user agent shadow DOM"

Then you can see all shadowed DOM elements, for example, for <input type="number">, the full element with shadowed DOM is:

_x000D_
_x000D_
<input type="number">_x000D_
  <div id="text-field-container" pseudo="-webkit-textfield-decoration-container">_x000D_
    <div id="editing-view-port">_x000D_
      <div id="inner-editor"></div>_x000D_
    </div>_x000D_
    <div pseudo="-webkit-inner-spin-button" id="spin"></div>_x000D_
  </div>_x000D_
</input>
_x000D_
_x000D_
_x000D_

shadow DOM of input[type="number"

And according to these info, you can draft some CSS to hide unwanted elements, just as @Josh said.

How do I print a datetime in the local timezone?

I use this function datetime_to_local_timezone(), which seems overly convoluted but I found no simpler version of a function that converts a datetime instance to the local time zone, as configured in the operating system, with the UTC offset that was in effect at that time:

import time, datetime

def datetime_to_local_timezone(dt):
    epoch = dt.timestamp() # Get POSIX timestamp of the specified datetime.
    st_time = time.localtime(epoch) #  Get struct_time for the timestamp. This will be created using the system's locale and it's time zone information.
    tz = datetime.timezone(datetime.timedelta(seconds = st_time.tm_gmtoff)) # Create a timezone object with the computed offset in the struct_time.

    return dt.astimezone(tz) # Move the datetime instance to the new time zone.

utc = datetime.timezone(datetime.timedelta())
dt1 = datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, utc) # DST was in effect
dt2 = datetime.datetime(2009, 1, 10, 18, 44, 59, 193982, utc) # DST was not in effect

print(dt1)
print(datetime_to_local_timezone(dt1))

print(dt2)
print(datetime_to_local_timezone(dt2))

This example prints four dates. For two moments in time, one in January and one in July 2009, each, it prints the timestamp once in UTC and once in the local time zone. Here, where CET (UTC+01:00) is used in the winter and CEST (UTC+02:00) is used in the summer, it prints the following:

2009-07-10 18:44:59.193982+00:00
2009-07-10 20:44:59.193982+02:00

2009-01-10 18:44:59.193982+00:00
2009-01-10 19:44:59.193982+01:00

Java: get greatest common divisor

For int and long, as primitives, not really. For Integer, it is possible someone wrote one.

Given that BigInteger is a (mathematical/functional) superset of int, Integer, long, and Long, if you need to use these types, convert them to a BigInteger, do the GCD, and convert the result back.

private static int gcdThing(int a, int b) {
    BigInteger b1 = BigInteger.valueOf(a);
    BigInteger b2 = BigInteger.valueOf(b);
    BigInteger gcd = b1.gcd(b2);
    return gcd.intValue();
}

How to dynamically change the color of the selected menu item of a web page?

It would probably be easiest to implement this using JavaScript ... Here's a JQuery script to demo ... As the others mentioned ... we have a class named 'active' to indicate the active tab - NOT the pseudo-class ':active.' We could have just as easily named it anything though ... selected, current, etc., etc.

/* CSS */

#nav { width:480px;margin:1em auto;}

#nav ul {margin:1em auto; padding:0; font:1em "Arial Black",sans-serif; }

#nav ul li{display:inline;} 

#nav ul li a{text-decoration:none; margin:0; padding:.25em 25px; background:#666; color:#ffffff;} 

#nav ul li a:hover{background:#ff9900; color:#ffffff;} 

#nav ul li a.active {background:#ff9900; color:#ffffff;} 

/* JQuery Example */

<script type="text/javascript">
$(function (){

    $('#nav ul li a').each(function(){
        var path = window.location.href;
        var current = path.substring(path.lastIndexOf('/')+1);
        var url = $(this).attr('href');

        if(url == current){
            $(this).addClass('active');
        };
    });         
});

</script>

 /* HTML */

<div id="nav" >
    <ul>
        <li><a href='index.php?1'>One</a></li>
        <li><a href='index.php?2'>Two</a></li>
        <li><a href='index.php?3'>Three</a></li>
        <li><a href='index.php?4'>Four</a></li>
    </ul>
</div>

Can I create view with parameter in MySQL?

I previously came up with a different workaround that doesn't use stored procedures, but instead uses a parameter table and some connection_id() magic.

EDIT (Copied up from comments)

create a table that contains a column called connection_id (make it a bigint). Place columns in that table for parameters for the view. Put a primary key on the connection_id. replace into the parameter table and use CONNECTION_ID() to populate the connection_id value. In the view use a cross join to the parameter table and put WHERE param_table.connection_id = CONNECTION_ID(). This will cross join with only one row from the parameter table which is what you want. You can then use the other columns in the where clause for example where orders.order_id = param_table.order_id.

Java: How to convert List to Map

Many solutions come to mind, depending on what you want to achive:

Every List item is key and value

for( Object o : list ) {
    map.put(o,o);
}

List elements have something to look them up, maybe a name:

for( MyObject o : list ) {
    map.put(o.name,o);
}

List elements have something to look them up, and there is no guarantee that they are unique: Use Googles MultiMaps

for( MyObject o : list ) {
    multimap.put(o.name,o);
}

Giving all the elements the position as a key:

for( int i=0; i<list.size; i++ ) {
    map.put(i,list.get(i));
}

...

It really depends on what you want to achive.

As you can see from the examples, a Map is a mapping from a key to a value, while a list is just a series of elements having a position each. So they are simply not automatically convertible.

Comparing two strings in C?

if(strcmp(sr1,str2)) // this returns 0 if strings r equal 
    flag=0;
else flag=1; // then last check the variable flag value and print the message 

                         OR

char str1[20],str2[20];
printf("enter first str > ");
gets(str1);
printf("enter second str > ");
gets(str2);

for(int i=0;str1[i]!='\0';i++)
{
    if(str[i]==str2[i])
         flag=0;
    else {flag=1; break;}
}

 //check the value of flag if it is 0 then strings r equal simple :)

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in

use global scope on your $con and put it inside your getPosts() function like so.

function getPosts() {
global $con;
$query = mysqli_query($con,"SELECT * FROM Blog");
while($row = mysqli_fetch_array($query))
    {
        echo "<div class=\"blogsnippet\">";
        echo "<h4>" . $row['Title'] . "</h4>" . $row['SubHeading'];
        echo "</div>";
    }
}

How do I change JPanel inside a JFrame on the fly?

On the user action:

// you have to do something along the lines of

myJFrame.getContentPane().removeAll()
myJFrame.getContentPane().invalidate()

myJFrame.getContentPane().add(newContentPanel)
myJFrame.getContentPane().revalidate()

Then you can resize your wndow as needed.

Two column div layout with fluid left and fixed right column

CSS Solutuion

#left{
    float:right;
    width:200px;
    height:500px;
    background:red;   
}

#right{
    margin-right: 200px;
    height:500px;
    background:blue;
}

Check working example at http://jsfiddle.net/NP4vb/3/

jQuery Solution

var parentw = $('#parent').width();
var rightw = $('#right').width();
$('#left').width(parentw - rightw);

Check working example http://jsfiddle.net/NP4vb/

How can I determine if an image has loaded, using Javascript/jQuery?

May I suggest a pure CSS solution altogether?

Just have a Div that you want to show the image in. Set the image as background. Then have the property background-size: cover or background-size: contain depending on how you want it.

cover will crop the image until smaller sides cover the box. contain will keep the entire image inside the div, leaving you with spaces on sides.

Check the snippet below.

_x000D_
_x000D_
div {_x000D_
  height: 300px;_x000D_
  width: 300px;_x000D_
  border: 3px dashed grey;_x000D_
  background-position: center;_x000D_
  background-repeat: no-repeat;_x000D_
}_x000D_
_x000D_
.cover-image {_x000D_
  background-size: cover;_x000D_
}_x000D_
_x000D_
.contain-image {_x000D_
  background-size: contain;_x000D_
}
_x000D_
<div class="cover-image" style="background-image:url(https://assets1.ignimgs.com/2019/04/25/avengers-endgame-1280y-1556226255823_1280w.jpg)">_x000D_
</div>_x000D_
<br/>_x000D_
<div class="contain-image" style="background-image:url(https://assets1.ignimgs.com/2019/04/25/avengers-endgame-1280y-1556226255823_1280w.jpg)">_x000D_
</div>
_x000D_
_x000D_
_x000D_

nil detection in Go

In Go 1.13 and later, you can use Value.IsZero method offered in reflect package.

if reflect.ValueOf(v).IsZero() {
    // v is zero, do something
}

Apart from basic types, it also works for Array, Chan, Func, Interface, Map, Ptr, Slice, UnsafePointer, and Struct. See this for reference.

How do I install a NuGet package .nupkg file locally?

For .nupkg files I like to use:

Install-Package C:\Path\To\Some\File.nupkg

Allow only pdf, doc, docx format for file upload?

var file = form.getForm().findField("file").getValue();
var fileLen = file.length;
var lastValue = file.substring(fileLen - 3, fileLen);
if (lastValue == 'doc') {//check same for other file format}

writing to existing workbook using xlwt

You need xlutils.copy. Try something like this:

from xlutils.copy import copy
w = copy('book1.xls')
w.get_sheet(0).write(0,0,"foo")
w.save('book2.xls')

Keep in mind you can't overwrite cells by default as noted in this question.

Spring Boot application in eclipse, the Tomcat connector configured to listen on port XXXX failed to start

this issue can be resolved using 2 ways:

  1. Kill application running on 8080
netstat -ao | find "8080"

Taskkill /PID 1342 /F
  1. change spring server port in application.properties file

server.port=8081

How to uninstall Apache with command line

I've had this sort of problem.....

The solve: cmd / powershell run as ADMINISTRATOR! I always forget.

Notice: In powershell, you need to put .\ for example:

.\httpd -k shutdown .\httpd -k stop .\httpd -k uninstall

Result: Removing the apache2.4 service The Apache2.4 service has been removed successfully.

AssertNull should be used or AssertNotNull

assertNotNull asserts that the object is not null. If it is null the test fails, so you want that.

Why is Ant giving me a Unsupported major.minor version error

You would need to say which version of Ant and which JVM version.

You can run ant -v to see which settings Ant is using as per the doc

Ant 1.8* requires JDK 1.4 or higher.

The 'Unsupported major.minor version 51.0' means somewhere code was compiled for a version of the JDK, and that you are trying to run those classes under an older version of the JDK. (see here)

Can I install the "app store" in an IOS simulator?

No, according to Apple here:

Note: You cannot install apps from the App Store in simulation environments.

How do I obtain crash-data from my Android application?

I made my own version here : http://androidblogger.blogspot.com/2009/12/how-to-improve-your-application-crash.html

It's basically the same thing, but I'm using a mail rather than a http connexion to send the report, and, more important, I added some informations like application version, OS version, Phone model, or avalaible memory to my report...

How to convert XML to java.util.Map and vice versa

I have tried different kinds of maps and the Conversion Box worked. I have used your map and have pasted an example below with some inner maps. Hope it is helpful to you ....

import java.util.HashMap;
import java.util.Map;

import cjm.component.cb.map.ToMap;
import cjm.component.cb.xml.ToXML;

public class Testing
{
public static void main(String[] args)
{
    try
    {
        Map<String, Object> map = new HashMap<String, Object>(); // ORIGINAL MAP

        map.put("name", "chris");
        map.put("island", "faranga");

        Map<String, String> mapInner = new HashMap<String, String>(); // SAMPLE INNER MAP

        mapInner.put("a", "A");
        mapInner.put("b", "B");
        mapInner.put("c", "C");

        map.put("innerMap", mapInner);

        Map<String, Object> mapRoot = new HashMap<String, Object>(); // ROOT MAP

        mapRoot.put("ROOT", map);

        System.out.println("Map: " + mapRoot);

        System.out.println();

        ToXML toXML = new ToXML();

        String convertedXML = String.valueOf(toXML.convertToXML(mapRoot, true)); // CONVERTING ROOT MAP TO XML

        System.out.println("Converted XML: " + convertedXML);

        System.out.println();

        ToMap toMap = new ToMap();

        Map<String, Object> convertedMap = toMap.convertToMap(convertedXML); // CONVERTING CONVERTED XML BACK TO MAP

        System.out.println("Converted Map: " + convertedMap);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}
}

Output:

Map: {ROOT={name=chris, innerMap={b=B, c=C, a=A}, island=faranga}}

 -------- Map Detected -------- 
 -------- XML created Successfully -------- 
Converted XML: <ROOT><name>chris</name><innerMap><b>B</b><c>C</c><a>A</a></innerMap><island>faranga</island></ROOT>

 -------- XML Detected -------- 
 -------- Map created Successfully -------- 
Converted Map: {ROOT={name=chris, innerMap={b=B, c=C, a=A}, island=faranga}}

Inserting a text where cursor is using Javascript/jquery

using @quick_sliv answer:

function insertAtCaret(el, text) {
    var caretPos = el.selectionStart;
    var textAreaTxt = el.value;
    el.value = textAreaTxt.substring(0, caretPos) + text + textAreaTxt.substring(caretPos);
};

Try reinstalling `node-sass` on node 0.12?

My issue was that I was on a machine with node version 0.12.2, but that had an old 1.x.x version of npm. Be sure to update your version of npm: sudo npm install -g npm Once that is done, remove any existing node-sass and reinstall it via npm.

Mysql - How to quit/exit from stored procedure

This works for me :

 CREATE DEFINER=`root`@`%` PROCEDURE `save_package_as_template`( IN package_id int , 
IN bus_fun_temp_id int  , OUT o_message VARCHAR (50) ,
            OUT o_number INT )
 BEGIN

DECLARE  v_pkg_name  varchar(50) ;

DECLARE  v_pkg_temp_id  int(10)  ; 

DECLARE  v_workflow_count INT(10);

-- checking if workflow created for package
select count(*)  INTO v_workflow_count from workflow w where w.package_id = 
package_id ;

this_proc:BEGIN   -- this_proc block start here 

 IF  v_workflow_count = 0 THEN
   select 'no work flow ' as 'workflow_status' ;
    SET o_message ='Work flow is not created for this package.';
    SET  o_number = -2 ;
      LEAVE this_proc;
 END IF;

select 'work flow  created ' as 'workflow_status' ;
-- To  send some message
SET o_message ='SUCCESSFUL';
SET  o_number = 1 ;

  END ;-- this_proc block end here 

END

Making sure at least one checkbox is checked

Prevent user from deselecting last checked checkbox.
jQuery (original answer).

$('input[type="checkbox"][name="chkBx"]').on('change',function(){
    var getArrVal = $('input[type="checkbox"][name="chkBx"]:checked').map(function(){
        return this.value;
    }).toArray();

    if(getArrVal.length){
        //execute the code
        $('#msg').html(getArrVal.toString());

    } else {
        $(this).prop("checked",true);
        $('#msg').html("At least one value must be checked!");
        return false;

    }
});

UPDATED ANSWER 2019-05-31
Plain JS

_x000D_
_x000D_
let i,_x000D_
    el = document.querySelectorAll('input[type="checkbox"][name="chkBx"]'),_x000D_
    msg = document.getElementById('msg'),_x000D_
    onChange = function(ev){_x000D_
        ev.preventDefault();_x000D_
        let _this = this,_x000D_
            arrVal = Array.prototype.slice.call(_x000D_
                document.querySelectorAll('input[type="checkbox"][name="chkBx"]:checked'))_x000D_
                    .map(function(cur){return cur.value});_x000D_
_x000D_
        if(arrVal.length){_x000D_
            msg.innerHTML = JSON.stringify(arrVal);_x000D_
        } else {_x000D_
            _this.checked=true;_x000D_
            msg.innerHTML = "At least one value must be checked!";_x000D_
        }_x000D_
    };_x000D_
_x000D_
for(i=el.length;i--;){el[i].addEventListener('change',onChange,false);}
_x000D_
<label><input type="checkbox" name="chkBx" value="value1" checked> Value1</label>_x000D_
<label><input type="checkbox" name="chkBx" value="value2"> Value2</label>_x000D_
<label><input type="checkbox" name="chkBx" value="value3"> Value3</label>_x000D_
<div id="msg"></div>
_x000D_
_x000D_
_x000D_

Why am I getting error CS0246: The type or namespace name could not be found?

most of the problems cause by .NET Framework. So just go to project properties and change .Net version same as your reference dll.

Done!!!

Hope it's help :)

Status bar and navigation bar appear over my view's bounds in iOS 7

I have a scenario where I use the BannerViewController written by Apple to display my ads and a ScrollViewController embedded in the BannerViewController.

To prevent the navigation bar from hiding my content, I had to make two changes.

1) Modify BannerViewController.m

- (void)viewDidLoad
{
   [super viewDidLoad];
   float systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
   if (systemVersion >= 7.0) {
      self.edgesForExtendedLayout = UIRectEdgeNone;
   }
}

2) Modify my ScrollViewContoller

- (void)viewDidLoad
{
    [super viewDidLoad];
    float systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (systemVersion >= 7.0) {
        self.edgesForExtendedLayout = UIRectEdgeBottom;
    }
}

Now the ads show up correctly at the bottom of the view instead of being covered by the Navigation bar and the content on the top is not cut off.

jquery, selector for class within id

Also $( "#container" ).find( "div.robotarm" );
is equal to: $( "div.robotarm", "#container" )

Changing upload_max_filesize on PHP

If you are running in a local server, such as wamp or xampp, make sure it's using the php.ini you think it is. These servers usually default to a php.ini that's not in your html docs folder.

How to use Git Revert

Use git revert like so:

git revert <insert bad commit hash here>

git revert creates a new commit with the changes that are rolled back. git reset erases your git history instead of making a new commit.

The steps after are the same as any other commit.

Selenium Finding elements by class name in python

As per the HTML:

<html>
    <body>
    <p class="content">Link1.</p>
    </body>
<html>
<html>
    <body>
    <p class="content">Link2.</p>
    </body>
<html>

Two(2) <p> elements are having the same class content.

So to filter the elements having the same class i.e. content and create a list you can use either of the following Locator Strategies:

  • Using class_name:

    elements = driver.find_elements_by_class_name("content")
    
  • Using css_selector:

     elements = driver.find_elements_by_css_selector(".content")
    
  • Using xpath:

    elements = driver.find_elements_by_xpath("//*[@class='content']")
    

Ideally, to click on the element you need to induce WebDriverWait for the visibility_of_all_elements_located() and you can use either of the following Locator Strategies:

  • Using CLASS_NAME:

    elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CLASS_NAME, "content")))
    
  • Using CSS_SELECTOR:

    elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, ".content")))
    
  • Using XPATH:

    elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//*[@class='content']")))
    
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

References

You can find a couple of relevant discussions in:

MySQL - How to select data by string length

select * from *tablename* where 1 having length(*fieldname*)=*fieldlength*

Example if you want to select from customer the entry's with a name shorter then 2 chars.

select * from customer where 1 **having length(name)<2**

How do I save JSON to local text file

It's my solution to save local data to txt file.

_x000D_
_x000D_
function export2txt() {_x000D_
  const originalData = {_x000D_
    members: [{_x000D_
        name: "cliff",_x000D_
        age: "34"_x000D_
      },_x000D_
      {_x000D_
        name: "ted",_x000D_
        age: "42"_x000D_
      },_x000D_
      {_x000D_
        name: "bob",_x000D_
        age: "12"_x000D_
      }_x000D_
    ]_x000D_
  };_x000D_
_x000D_
  const a = document.createElement("a");_x000D_
  a.href = URL.createObjectURL(new Blob([JSON.stringify(originalData, null, 2)], {_x000D_
    type: "text/plain"_x000D_
  }));_x000D_
  a.setAttribute("download", "data.txt");_x000D_
  document.body.appendChild(a);_x000D_
  a.click();_x000D_
  document.body.removeChild(a);_x000D_
}
_x000D_
<button onclick="export2txt()">Export data to local txt file</button>
_x000D_
_x000D_
_x000D_

How to obtain the absolute path of a file via Shell (BASH/ZSH/SH)?

#! /bin/bash

file="$@"
realpath "$file" 2>/dev/null || eval realpath $(echo $file | sed 's/ /\\ /g')

This makes up for the shortcomings of realpath, store it in a shell script fullpath. You can now call:

$ cd && touch a\ a && rm A 2>/dev/null 
$ fullpath "a a"
/home/user/a a
$ fullpath ~/a\ a
/home/user/a a
$ fullpath A
A: No such file or directory.

EF Code First "Invalid column name 'Discriminator'" but no inheritance

I get the error in another situation, and here are the problem and the solution:

I have 2 classes derived from a same base class named LevledItem:

public partial class Team : LeveledItem
{
   //Everything is ok here!
}
public partial class Story : LeveledItem
{
   //Everything is ok here!
}

But in their DbContext, I copied some code but forget to change one of the class name:

public class MFCTeamDbContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //Other codes here
        modelBuilder.Entity<LeveledItem>()
            .Map<Team>(m => m.Requires("Type").HasValue(ItemType.Team));
    }

public class ProductBacklogDbContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //Other codes here
        modelBuilder.Entity<LeveledItem>()
            .Map<Team>(m => m.Requires("Type").HasValue(ItemType.Story));
    }

Yes, the second Map< Team> should be Map< Story>. And it cost me half a day to figure it out!

Font Awesome not working, icons showing as squares

If you are using the version 5.* or greater, then you have to use the

all.css or all.min.css

Including the fontawesome.css does not work as it has no reference to the webfonts folder and there is no reference to the @font-face or font-family

You can inspect this by searching the code for the font-family property in fontawesome.css or fontawesome.min.css

Why is Thread.Sleep so harmful

I agree with many here, but I also think it depends.

Recently I did this code:

private void animate(FlowLayoutPanel element, int start, int end)
{
    bool asc = end > start;
    element.Show();
    while (start != end) {
        start += asc ? 1 : -1;
        element.Height = start;
        Thread.Sleep(1);
    }
    if (!asc)
    {
        element.Hide();
    }
    element.Focus();
}

It was a simple animate-function, and I used Thread.Sleep on it.

My conclusion, if it does the job, use it.

Spring MVC - Why not able to use @RequestBody and @RequestParam together

It happens because of not very straight forward Servlet specification. If you are working with a native HttpServletRequest implementation you cannot get both the URL encode body and the parameters. Spring does some workarounds, which make it even more strange and nontransparent.

In such cases Spring (version 3.2.4) re-renders a body for you using data from the getParameterMap() method. It mixes GET and POST parameters and breaks the parameter order. The class, which is responsible for the chaos is ServletServerHttpRequest. Unfortunately it cannot be replaced, but the class StringHttpMessageConverter can be.

The clean solution is unfortunately not simple:

  1. Replacing StringHttpMessageConverter. Copy/Overwrite the original class adjusting method readInternal().
  2. Wrapping HttpServletRequest overwriting getInputStream(), getReader() and getParameter*() methods.

In the method StringHttpMessageConverter#readInternal following code must be used:

    if (inputMessage instanceof ServletServerHttpRequest) {
        ServletServerHttpRequest oo = (ServletServerHttpRequest)inputMessage;
        input = oo.getServletRequest().getInputStream();
    } else {
        input = inputMessage.getBody();
    }

Then the converter must be registered in the context.

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="true/false">
        <bean class="my-new-converter-class"/>
   </mvc:message-converters>
</mvc:annotation-driven>

The step two is described here: Http Servlet request lose params from POST body after read it once

Best way to retrieve variable values from a text file?

A simple way of reading variables from a text file using the standard library:

# Get vars from conf file
var = {}
with open("myvars.conf") as conf:
        for line in conf:
                if ":" in line:
                        name, value = line.split(":")
                        var[name] = str(value).rstrip()
globals().update(var)

What's the difference between Instant and LocalDateTime?

Instant corresponds to time on the prime meridian (Greenwich).

Whereas LocalDateTime relative to OS time zone settings, and

cannot represent an instant without additional information such as an offset or time-zone.

Storing files in SQL Server

There's still no simple answer. It depends on your scenario. MSDN has documentation to help you decide.

There are other options covered here. Instead of storing in the file system directly or in a BLOB, you can use the FileStream or File Table in SQL Server 2012. The advantages to File Table seem like a no-brainier (but admittedly I have no personal first-hand experience with them.)

The article is definitely worth a read.

can't multiply sequence by non-int of type 'float'

for i in growthRates:  
    fund = fund * (1 + 0.01 * growthRates) + depositPerYear

should be:

for i in growthRates:  
    fund = fund * (1 + 0.01 * i) + depositPerYear

You are multiplying 0.01 with the growthRates list object. Multiplying a list by an integer is valid (it's overloaded syntactic sugar that allows you to create an extended a list with copies of its element references).

Example:

>>> 2 * [1,2]
[1, 2, 1, 2]

SQL to search objects, including stored procedures, in Oracle

I would use DBA_SOURCE (if you have access to it) because if the object you require is not owned by the schema under which you are logged in you will not see it.

If you need to know the functions and Procs inside the packages try something like this:

select * from all_source
 where type = 'PACKAGE'
   and (upper(text) like '%FUNCTION%' or upper(text) like '%PROCEDURE%')
   and owner != 'SYS';

The last line prevents all the sys stuff (DBMS_ et al) from being returned. This will work in user_source if you just want your own schema stuff.

How do I perform an IF...THEN in an SQL SELECT?

SELECT  
(CASE 
     WHEN (Obsolete = 'N' OR InStock = 'Y') THEN 'YES'
                                            ELSE 'NO' 
 END) as Salable
, * 
FROM Product

How to add a response header on nginx when using proxy_pass?

Hide response header and then add a new custom header value

Adding a header with add_header works fine with proxy pass, but if there is an existing header value in the response it will stack the values.

If you want to set or replace a header value (for example replace the Access-Control-Allow-Origin header to match your client for allowing cross origin resource sharing) then you can do as follows:

# 1. hide the Access-Control-Allow-Origin from the server response
proxy_hide_header Access-Control-Allow-Origin;
# 2. add a new custom header that allows all * origins instead
add_header Access-Control-Allow-Origin *;

So proxy_hide_header combined with add_header gives you the power to set/replace response header values.

Similar answer can be found here on ServerFault

UPDATE:

Note: proxy_set_header is for setting request headers before the request is sent further, not for setting response headers (these configuration attributes for headers can be a bit confusing).

How can I use a custom font in Java?

From the Java tutorial, you need to create a new font and register it in the graphics environment:

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf")));

After this step is done, the font is available in calls to getAvailableFontFamilyNames() and can be used in font constructors.

Python script to do something at the same time every day

I needed something similar for a task. This is the code I wrote: It calculates the next day and changes the time to whatever is required and finds seconds between currentTime and next scheduled time.

import datetime as dt

def my_job():
    print "hello world"
nextDay = dt.datetime.now() + dt.timedelta(days=1)
dateString = nextDay.strftime('%d-%m-%Y') + " 01-00-00"
newDate = nextDay.strptime(dateString,'%d-%m-%Y %H-%M-%S')
delay = (newDate - dt.datetime.now()).total_seconds()
Timer(delay,my_job,()).start()

How to do if-else in Thymeleaf?

Thymeleaf has an equivalent to <c:choose> and <c:when>: the th:switch and th:case attributes introduced in Thymeleaf 2.0.

They work as you'd expect, using * for the default case:

<div th:switch="${user.role}"> 
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="#{roles.manager}">User is a manager</p>
  <p th:case="*">User is some other thing</p> 
</div>

See this for a quick explanation of syntax (or the Thymeleaf tutorials).

Disclaimer: As required by StackOverflow rules, I'm the author of Thymeleaf.

How to add a string to a string[] array? There's no .Add function

This is how I add to a string when needed:

string[] myList;
myList = new string[100];
for (int i = 0; i < 100; i++)
{
    myList[i] = string.Format("List string : {0}", i);
}

Passing Variable through JavaScript from one html page to another page

Without reading your code but just your scenario, I would solve by using localStorage. Here's an example, I'll use prompt() for short.

On page1:

window.onload = function() {
   var getInput = prompt("Hey type something here: ");
   localStorage.setItem("storageName",getInput);
}

On page2:

window.onload = alert(localStorage.getItem("storageName"));

You can also use cookies but localStorage allows much more spaces, and they aren't sent back to servers when you request pages.

jQuery: how to find first visible input/select/textarea excluding buttons?

The JQuery code is fine. You must execute in the ready handler not in the window load event.

<script type="text/javascript">
$(function(){
  var aspForm  = $("form#aspnetForm");
  var firstInput = $(":input:not(input[type=button],input[type=submit],button):visible:first", aspForm);
  firstInput.focus();
});
</script>

Update

I tried with the example of Karim79(thanks for the example) and it works fine: http://jsfiddle.net/2sMfU/

Pandas convert dataframe to array of tuples

Changing the data frames list into a list of tuples.

df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]})
print(df)
OUTPUT
   col1  col2
0     1     4
1     2     5
2     3     6

records = df.to_records(index=False)
result = list(records)
print(result)
OUTPUT
[(1, 4), (2, 5), (3, 6)]

FirstOrDefault returns NullReferenceException if no match is found

i assume you are working with nullable datatypes, you can do something like this:

var t = things.Where(x => x!=null && x.Value.ID == long.Parse(options.ID)).FirstOrDefault();
var res = t == null ? "" : t.Value;

Dynamically set value of a file input

It is not possible to dynamically change the value of a file field, otherwise you could set it to "c:\yourfile" and steal files very easily.

However there are many solutions to a multi-upload system. I'm guessing that you're wanting to have a multi-select open dialog.

Perhaps have a look at http://www.plupload.com/ - it's a very flexible solution to multiple file uploads, and supports drop zones e.t.c.

CSS strikethrough different color from text?

Blazemonger's reply (above or below) needs voting up - but I don't have enough points.

I wanted to add a grey bar across some 20px wide CSS round buttons to indicate "not available" and tweaked Blazemonger's css:

.round_btn:after {
    content:"";    /* required property */
    position: absolute;
    top: 6px;
    left: -1px;
    border-top: 6px solid rgba(170,170,170,0.65);
    height: 6px;
    width: 19px;
}

How do I concatenate two strings in C?

#include <string.h>
#include <stdio.h>
int main()
{
   int a,l;
   char str[50],str1[50],str3[100];
   printf("\nEnter a string: ");
   scanf("%s",str);
   str3[0]='\0';
   printf("\nEnter the string which you want to concat with string one: ");
   scanf("%s",str1);
   strcat(str3,str);
   strcat(str3,str1);
   printf("\nThe string is %s\n",str3);
}

Android selector & text color

Have you tried setOnFocusChangeListener? Within the handler, you could change the text appearance.

For instance:

TextView text = (TextView)findViewById(R.id.text);
text.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            ((TextView)v).setXXXX();
        } else {
            ((TextView)v).setXXXX();
        }
    }
});

You can then apply whatever changes you want when it's focused or not. You can also use the ViewTreeObserver to listen for Global focus changes.

For instance:

View all = findViewById(R.id.id_of_top_level_view_on_layout);
ViewTreeObserver vto = all.getViewTreeObserver();
vto.addOnGlobalFocusChangeListener(new ViewTreeObserver.OnGlobalFocusChangeListener() {
    public void onGlobalFocusChanged(
        View oldFocus, View newFocus) {
        // xxxx
    }
});

I hope this helps or gives you ideas.

Python spacing and aligning strings

You can use expandtabs to specify the tabstop, like this:

>>> print ('Location:'+'10-10-10-10'+'\t'+ 'Revision: 1'.expandtabs(30))
>>> print ('District: Tower'+'\t'+ 'Date: May 16, 2012'.expandtabs(30))
#Output:
Location:10-10-10-10          Revision: 1
District: Tower               Date: May 16, 2012

What's the best UML diagramming tool?

For me it's Enterprise Architect from Sparx Systems. A very rounded UML tool for a very reasonable price.

Very strong feature list including: integrated project management, baselining, export/import (including export to html), documentation generation from the model, various templates (Zachman, TOGAF, etc.), IDE plugins, code generation (with IDE plugins available for Visual Studio, Eclipse & others), automation API - the list goes on.

Oh yeah, don't forget support for source control directly from inside the tool (SVN, CVS, TFS & SCC).

I would also stay away from Visio - you only get diagrams, not a model. Rename a class in one place in a UML modelling tool and you rename in all places. This is not the case in Visio!

Changing background color of selected cell?

var last_selected:IndexPath!

define last_selected:IndexPath inside the class

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath) as! Cell
    cell.contentView.backgroundColor = UIColor.lightGray
    cell.txt.textColor = UIColor.red

    if(last_selected != nil){
        //deselect
        let deselect_cell = tableView.cellForRow(at: last_selected) as! Cell
        deselect_cell.contentView.backgroundColor = UIColor.white
        deselect_cell.txt.textColor = UIColor.black
    }

    last_selected = indexPath
}

Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

I would simply delete from schema_version the migration/s that deviates from migrations to be applied. This way you don't throw away any test data that you might have.

For example:

SELECT * from schema_version order by installed_on desc

V_005_five.sql
V_004_four.sql
V_003_three.sql
V_002_two.sql
V_001_one.sql

Migrations to be applied

V_005_five.sql
* V_004_addUserTable.sql *
V_003_three.sql
V_002_two.sql
V_001_one.sql

Solution here is to delete from schema_version

V_005_five.sql
V_004_four.sql

AND revert any database changes caused. for example if schema created new table then you must drop that table before you run you migrations.

when you run flyway it will only re apply

V_005_five.sql
* V_004_addUserTable.sql *

new schema_version will be

V_005_five.sql
* V_004_addUserTable.sql *
V_003_three.sql
V_002_two.sql
V_001_one.sql

Hope it helps

Why can't I call a public method in another class?

For example 1 and 2 you need to create static methods:

public static string InstanceMethod() {return "Hello World";}

Then for example 3 you need an instance of your object to invoke the method:

object o = new object();
string s = o.InstanceMethod();

brew install mysql on macOS

If mysql is already installed

Stop mysql completely.

  1. mysql.server stop <-- may need editing based on your version
  2. ps -ef | grep mysql <-- lists processes with mysql in their name
  3. kill [PID] <-- kill the processes by PID

Remove files. Instructions above are good. I'll add:

  1. sudo find /. -name "*mysql*"
  2. Using your judgement, rm -rf these files. Note that many programs have drivers for mysql which you do not want to remove. For example, don't delete stuff in a PHP install's directory. Do remove stuff in its own mysql directory.

Install

Hopefully you have homebrew. If not, download it.

I like to run brew as root, but I don't think you have to. Edit 2018: you can't run brew as root anymore

  1. sudo brew update
  2. sudo brew install cmake <-- dependency for mysql, useful
  3. sudo brew install openssl <-- dependency for mysql, useful
  4. sudo brew info mysql <-- skim through this... it gives you some idea of what's coming next
  5. sudo brew install mysql --with-embedded; say done <-- Installs mysql with the embedded server. Tells you when it finishes (my install took 10 minutes)

Afterwards

  1. sudo chown -R mysql /usr/local/var/mysql/ <-- mysql wouldn't work for me until I ran this command
  2. sudo mysql.server start <-- once again, the exact syntax may vary
  3. Create users in mysql (http://dev.mysql.com/doc/refman/5.7/en/create-user.html). Remember to add a password for the root user.

Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);

It's just common stuff for making cin input work faster.

For a quick explanation: the first line turns off buffer synchronization between the cin stream and C-style stdio tools (like scanf or gets) — so cin works faster, but you can't use it simultaneously with stdio tools.

The second line unties cin from cout — by default the cout buffer flushes each time when you read something from cin. And that may be slow when you repeatedly read something small then write something small many times. So the line turns off this synchronization (by literally tying cin to null instead of cout).

How to convert a std::string to const char* or char*?

C++17

C++17 (upcoming standard) changes the synopsis of the template basic_string adding a non const overload of data():

charT* data() noexcept;

Returns: A pointer p such that p + i == &operator for each i in [0,size()].


CharT const * from std::basic_string<CharT>

std::string const cstr = { "..." };
char const * p = cstr.data(); // or .c_str()

CharT * from std::basic_string<CharT>

std::string str = { "..." };
char * p = str.data();

C++11

CharT const * from std::basic_string<CharT>

std::string str = { "..." };
str.c_str();

CharT * from std::basic_string<CharT>

From C++11 onwards, the standard says:

  1. The char-like objects in a basic_string object shall be stored contiguously. That is, for any basic_string object s, the identity &*(s.begin() + n) == &*s.begin() + n shall hold for all values of n such that 0 <= n < s.size().

  1. const_reference operator[](size_type pos) const;
    reference operator[](size_type pos);

    Returns: *(begin() + pos) if pos < size(), otherwise a reference to an object of type CharT with value CharT(); the referenced value shall not be modified.


  1. const charT* c_str() const noexcept;
    const charT* data() const noexcept;

    Returns: A pointer p such that p + i == &operator[](i) for each i in [0,size()].

There are severable possible ways to get a non const character pointer.

1. Use the contiguous storage of C++11

std::string foo{"text"};
auto p = &*foo.begin();

Pro

  • Simple and short
  • Fast (only method with no copy involved)

Cons

  • Final '\0' is not to be altered / not necessarily part of the non-const memory.

2. Use std::vector<CharT>

std::string foo{"text"};
std::vector<char> fcv(foo.data(), foo.data()+foo.size()+1u);
auto p = fcv.data();

Pro

  • Simple
  • Automatic memory handling
  • Dynamic

Cons

  • Requires string copy

3. Use std::array<CharT, N> if N is compile time constant (and small enough)

std::string foo{"text"};
std::array<char, 5u> fca;
std::copy(foo.data(), foo.data()+foo.size()+1u, fca.begin());

Pro

  • Simple
  • Stack memory handling

Cons

  • Static
  • Requires string copy

4. Raw memory allocation with automatic storage deletion

std::string foo{ "text" };
auto p = std::make_unique<char[]>(foo.size()+1u);
std::copy(foo.data(), foo.data() + foo.size() + 1u, &p[0]);

Pro

  • Small memory footprint
  • Automatic deletion
  • Simple

Cons

  • Requires string copy
  • Static (dynamic usage requires lots more code)
  • Less features than vector or array

5. Raw memory allocation with manual handling

std::string foo{ "text" };
char * p = nullptr;
try
{
  p = new char[foo.size() + 1u];
  std::copy(foo.data(), foo.data() + foo.size() + 1u, p);
  // handle stuff with p
  delete[] p;
}
catch (...)
{
  if (p) { delete[] p; }
  throw;
}

Pro

  • Maximum 'control'

Con

  • Requires string copy
  • Maximum liability / susceptibility for errors
  • Complex

How can I save a screenshot directly to a file in Windows?

Of course you could write a program that monitors the clipboard and displays an annoying SaveAs-dialog for every image in the clipboard ;-). I guess you can even find out if the last key pressed was PrintScreen to limit the number of false positives.

While I'm thinking about it.. you could also google for someone who already did exactly that.


EDIT: .. or just wait for someone to post the source here - as just happend :-)

COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'

The same error is produced in MariaDB (10.1.36-MariaDB) by using the combination of parenthesis and the COLLATE statement. My SQL was different, the error was the same, I had:

SELECT *
FROM table1
WHERE (field = 'STRING') COLLATE utf8_bin;

Omitting the parenthesis was solving it for me.

SELECT *
FROM table1
WHERE field = 'STRING' COLLATE utf8_bin;

JSON.Parse,'Uncaught SyntaxError: Unexpected token o

Without single quotes around it, you are creating an array with two objects inside of it. This is JavaScript's own syntax. When you add the quotes, that object (array+2 objects) is now a string. You can use JSON.parse to convert a string into a JavaScript object. You cannot use JSON.parse to convert a JavaScript object into a JavaScript object.

//String - you can use JSON.parse on it
var jsonStringNoQuotes = '[{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}]';

//Already a javascript object - you cannot use JSON.parse on it
var jsonStringNoQuotes = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];

Furthermore, your last example fails because you are adding literal single quote characters to the JSON string. This is illegal. JSON specification states that only double quotes are allowed. If you were to console.log the following...

console.log("'"+[{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}]+"'");
//Logs:
'[object Object],[object Object]'

You would see that it returns the string representation of the array, which gets converted to a comma separated list, and each list item would be the string representation of an object, which is [object Object]. Remember, associative arrays in javascript are simply objects with each key/value pair being a property/value.

Why does this happen? Because you are starting with a string "'", then you are trying to append the array to it, which requests the string representation of it, then you are appending another string "'".

Please do not confuse JSON with Javascript, as they are entirely different things. JSON is a data format that is humanly readable, and was intended to match the syntax used when creating javascript objects. JSON is a string. Javascript objects are not, and therefor when declared in code are not surrounded in quotes.

See this fiddle: http://jsfiddle.net/NrnK5/

Why doesn't java.io.File have a close method?

Essentially random access file wraps input and output streams in order to manage the random access. You don't open and close a file, you open and close streams to a file.

Get div tag scroll position using JavaScript

you use the scrollTop attribute

var position = document.getElementById('id').scrollTop;

How can I return the current action in an ASP.NET MVC view?

In the RC you can also extract route data like the action method name like this

ViewContext.Controller.ValueProvider["action"].RawValue
ViewContext.Controller.ValueProvider["controller"].RawValue
ViewContext.Controller.ValueProvider["id"].RawValue

Update for MVC 3

ViewContext.Controller.ValueProvider.GetValue("action").RawValue
ViewContext.Controller.ValueProvider.GetValue("controller").RawValue
ViewContext.Controller.ValueProvider.GetValue("id").RawValue

Update for MVC 4

ViewContext.Controller.RouteData.Values["action"]
ViewContext.Controller.RouteData.Values["controller"]
ViewContext.Controller.RouteData.Values["id"]

Update for MVC 4.5

ViewContext.RouteData.Values["action"]
ViewContext.RouteData.Values["controller"]
ViewContext.RouteData.Values["id"]

Alternate table row color using CSS?

You have the :nth-child() pseudo-class:

table tr:nth-child(odd) td{
    ...
}
table tr:nth-child(even) td{
    ...
}

In the early days of :nth-child() its browser support was kind of poor. That's why setting class="odd" became such a common technique. In late 2013 I'm glad to say that IE6 and IE7 are finally dead (or sick enough to stop caring) but IE8 is still around — thankfully, it's the only exception.