Programs & Examples On #Cs4

cs4 Stands for Creative Suite 4 And is a collection of programs made and/or managed by Adobe Systems.

intellij idea - Error: java: invalid source release 1.9

For anyone struggling with this issue who tried DeanM's solution but to no avail, there's something else worth checking, which is the version of the JDK you have configured for your project. What I'm trying to say is that if you have configured JDK 8u191 (for example) for your project, but have the language level set to anything higher than 8, you're gonna get this error.

In this case, it's probably better to ask whoever's in charge of the project, which version of the JDK would be preferable to compile the sources.

java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference

Your app is crashing at:

welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");

because mPlayer=null.

You forgot to initialize Player mPlayer in your PlayGame Activity.

mPlayer = new Player(context,"");

MySQL CONCAT returns NULL if any field contain NULL

SELECT CONCAT(isnull(`affiliate_name`,''),'-',isnull(`model`,''),'-',isnull(`ip`,''),'-',isnull(`os_type`,''),'-',isnull(`os_version`,'')) AS device_name
FROM devices

Adding a 'share by email' link to website

<a target="_blank" title="Share this page" href="http://www.sharethis.com/share?url=[INSERT URL]&title=[INSERT TITLE]&summary=[INSERT SUMMARY]&img=[INSERT IMAGE URL]&pageInfo=%7B%22hostname%22%3A%22[INSERT DOMAIN NAME]%22%2C%22publisher%22%3A%22[INSERT PUBLISHERID]%22%7D"><img width="86" height="25" alt="Share this page" src="http://w.sharethis.com/images/share-classic.gif"></a>

Instructions

First, insert these lines wherever you want within your newsletter code. Then:

  1. Change "INSERT URL" to whatever website holds the shared content.
  2. Change "INSERT TITLE" to the title of the article.
  3. Change "INSERT SUMMARY" to a short summary of the article.
  4. Change "INSERT IMAGE URL" to an image that will be shared with the rest of the content.
  5. Change "INSERT DOMAIN NAME" to your domain name.
  6. Change "INSERT PUBLISHERID" to your publisher ID (if you have an account, if not, remove "[INSERT PUBLISHERID]" or sign up!)

If you are using this on an email newsletter, make sure you add our sharing buttons to the destination page. This will ensure that you get complete sharing analytics for your page. Make sure you replace "INSERT PUBLISHERID" with your own.

The type arguments for method cannot be inferred from the usage

Now my aim was to have one pair with an base type and a type definition (Requirement A). For the type definition I want to use inheritance (Requirement B). The use should be possible, without explicite knowledge over the base type (Requirement C).

After I know now that the gernic constraints are not used for solving the generic return type, I experimented a little bit:

Ok let's introducte Get2:

class ServiceGate
{
    public IAccess<C, T> Get1<C, T>(C control) where C : ISignatur<T>
    {
        throw new NotImplementedException();
    }

    public IAccess<ISignatur<T>, T> Get2<T>(ISignatur<T> control)
    {
        throw new NotImplementedException();
    }
}

class Test
{
    static void Main()
    {
        ServiceGate service = new ServiceGate();
        //var bla1 = service.Get1(new Signatur()); // CS0411
        var bla = service.Get2(new Signatur()); // Works
    }
}

Fine, but this solution reaches not requriement B.

Next try:

class ServiceGate
{
    public IAccess<C, T> Get3<C, T>(C control, ISignatur<T> iControl) where C : ISignatur<T>
    {
        throw new NotImplementedException();
    }

}

class Test
{
    static void Main()
    {
        ServiceGate service = new ServiceGate();
        //var bla1 = service.Get1(new Signatur()); // CS0411
        var bla = service.Get2(new Signatur()); // Works
        var c = new Signatur();
        var bla3 = service.Get3(c, c); // Works!! 
    }
}

Nice! Now the compiler can infer the generic return types. But i don't like it. Other try:

class IC<A, B>
{
    public IC(A a, B b)
    {
        Value1 = a;
        Value2 = b;
    }

    public A Value1 { get; set; }

    public B Value2 { get; set; }
}

class Signatur : ISignatur<bool>
{
    public string Test { get; set; }

    public IC<Signatur, ISignatur<bool>> Get()
    {
        return new IC<Signatur, ISignatur<bool>>(this, this);
    }
}

class ServiceGate
{
    public IAccess<C, T> Get4<C, T>(IC<C, ISignatur<T>> control) where C : ISignatur<T>
    {
        throw new NotImplementedException();
    }
}

class Test
{
    static void Main()
    {
        ServiceGate service = new ServiceGate();
        //var bla1 = service.Get1(new Signatur()); // CS0411
        var bla = service.Get2(new Signatur()); // Works
        var c = new Signatur();
        var bla3 = service.Get3(c, c); // Works!!
        var bla4 = service.Get4((new Signatur()).Get()); // Better...
    }
}

My final solution is to have something like ISignature<B, C>, where B ist the base type and C the definition...

Error: Generic Array Creation

You can't create arrays with a generic component type.

Create an array of an explicit type, like Object[], instead. You can then cast this to PCB[] if you want, but I don't recommend it in most cases.

PCB[] res = (PCB[]) new Object[list.size()]; /* Not type-safe. */

If you want type safety, use a collection like java.util.List<PCB> instead of an array.

By the way, if list is already a java.util.List, you should use one of its toArray() methods, instead of duplicating them in your code. This doesn't get your around the type-safety problem though.

Flash CS4 refuses to let go

Flash still has the ASO file, which is the compiled byte code for your classes. On Windows, you can see the ASO files here:

C:\Documents and Settings\username\Local Settings\Application Data\Adobe\Flash CS4\en\Configuration\Classes\aso

On a Mac, the directory structure is similar in /Users/username/Library/Application Support/


You can remove those files by hand, or in Flash you can select Control->Delete ASO files to remove them.

How to add link to flash banner

If you have a flash FLA file that shows the FLV movie you can add a button inside the FLA file. This button can be given an action to load the URL.

on (release) {
  getURL("http://someurl/");
}

To make the button transparent you can place a square inside it that is moved to the hit-area frame of the button.

I think it would go too far to explain into depth with pictures how to go about in stackoverflow.

Select value from list of tuples where condition

One solution to this would be a list comprehension, with pattern matching inside your tuple:

>>> mylist = [(25,7),(26,9),(55,10)]
>>> [age for (age,person_id) in mylist if person_id == 10]
[55]

Another way would be using map and filter:

>>> map( lambda (age,_): age, filter( lambda (_,person_id): person_id == 10, mylist) )
[55]

Android: Flush DNS

You have a few options:

  • Release an update for your app that uses a different hostname that isn't in anyone's cache.
  • Same thing, but using the IP address of your server
  • Have your users go into settings -> applications -> Network Location -> Clear data.

You may want to check that last step because i don't know for a fact that this is the appropriate service. I can't really test that right now. Good luck!

Regex how to match an optional character

You have to mark the single letter as optional too:

([A-Z]{1})? +.*? +

or make the whole part optional

(([A-Z]{1}) +.*? +)?

Google Maps Android API v2 Authorization failure

Steps:

  • to ensure that device has Google Play services APK
  • to install Google Play Service rev. more than 2

enter image description here

  • to create project at https://code.google.com/apis/console/
  • to enable "Google Maps Android API v2" enter image description here
  • to register of SHA1 in project (NOW, YOU NEED WRITE SHA1;your.app.package.name) at APIs console and get API KEY
  • to copy directory ANDROID_SDK_DIR/extras/google/google_play_services/libproject/google-play-services_lib to root of your project
  • to add next line to the YOUR_PROJECT/project.properties

android.library.reference.1=google-play-services_lib

  • to add next lines to the YOUR_PROJECT/proguard-project.txt

.

-keep class * extends java.util.ListResourceBundle {

   protected Object[][] getContents();

}

Now you are ready to create your own Google Map app with using Google Map APIs V2 for Android.

If you create application with min SDK = 8, please use android support library v4 + SupportMapFragment instead of MapFragment.

How do I disable and re-enable a button in with javascript?

you can try with

document.getElementById('btn').disabled = !this.checked"

_x000D_
_x000D_
<input type="submit" name="btn"  id="btn" value="submit" disabled/>_x000D_
_x000D_
<input type="checkbox"  onchange="document.getElementById('btn').disabled = !this.checked"/>
_x000D_
_x000D_
_x000D_

How do you create a yes/no boolean field in SQL server?

There are already answers saying use of Bit. I will add more to these answers.

You should use bit for representing Boolean values.

Remarks from MSDN article.

Bit can take a value of 1, 0, or NULL.

The SQL Server Database Engine optimizes storage of bit columns. If there are 8 or less bit columns in a table, the columns are stored as 1 byte. If there are from 9 up to 16 bit columns, the columns are stored as 2 bytes, and so on.

The string values TRUE and FALSE can be converted to bit values: TRUE is converted to 1 and FALSE is converted to 0.

Converting to bit promotes any nonzero value to 1.

Reference

Note: It is good practice to keep values as 1 and 0 only with data type NOT NULL

As Bit have values 1, 0 and NULL. See truth table for this. So plan values accordingly. It might add confusion by allowing NULL value for bit data type.

enter image description here

Reference

How to see the values of a table variable at debug time in T-SQL?

That's not yet implemented according this Microsoft Connect link: Microsoft Connect

Gnuplot line types

Until version 4.6

The dash type of a linestyle is given by the linetype, which does also select the line color unless you explicitely set an other one with linecolor.

However, the support for dashed lines depends on the selected terminal:

  1. Some terminals don't support dashed lines, like png (uses libgd)
  2. Other terminals, like pngcairo, support dashed lines, but it is disables by default. To enable it, use set termoption dashed, or set terminal pngcairo dashed ....
  3. The exact dash patterns differ between terminals. To see the defined linetype, use the test command:

Running

set terminal pngcairo dashed
set output 'test.png'
test
set output

gives:

enter image description here

whereas, the postscript terminal shows different dash patterns:

set terminal postscript eps color colortext
set output 'test.eps'
test
set output

enter image description here

Version 5.0

Starting with version 5.0 the following changes related to linetypes, dash patterns and line colors are introduced:

  • A new dashtype parameter was introduced:

    To get the predefined dash patterns, use e.g.

    plot x dashtype 2
    

    You can also specify custom dash patterns like

    plot x dashtype (3,5,10,5),\
         2*x dashtype '.-_'
    
  • The terminal options dashed and solid are ignored. By default all lines are solid. To change them to dashed, use e.g.

    set for [i=1:8] linetype i dashtype i
    
  • The default set of line colors was changed. You can select between three different color sets with set colorsequence default|podo|classic:

enter image description here

git-diff to ignore ^M

Why do you get these ^M in your git diff?

In my case I was working on a project which was developed in Windows and I used OS X. When I changed some code, I saw ^M at the end of the lines I added in git diff. I think the ^M were showing up because they were different line endings than the rest of the file. Because the rest of the file was developed in Windows it used CR line endings, and in OS X it uses LF line endings.

Apparently, the Windows developer didn't use the option "Checkout Windows-style, commit Unix-style line endings" during the installation of Git.

So what should we do about this?

You can have the Windows users reinstall git and use the "Checkout Windows-style, commit Unix-style line endings" option. This is what I would prefer, because I see Windows as an exception in its line ending characters and Windows fixes its own issue this way.

If you go for this option, you should however fix the current files (because they're still using the CR line endings). I did this by following these steps:

  1. Remove all files from the repository, but not from your filesystem.

    git rm --cached -r .
    
  2. Add a .gitattributes file that enforces certain files to use a LF as line endings. Put this in the file:

    *.ext text eol=crlf
    

    Replace .ext with the file extensions you want to match.

  3. Add all the files again.

    git add .
    

    This will show messages like this:

    warning: CRLF will be replaced by LF in <filename>.
    The file will have its original line endings in your working directory.
    
  4. You could remove the .gitattributes file unless you have stubborn Windows users that don't want to use the "Checkout Windows-style, commit Unix-style line endings" option.

  5. Commit and push it all.

  6. Remove and checkout the applicable files on all the systems where they're used. On the Windows systems, make sure they now use the "Checkout Windows-style, commit Unix-style line endings" option. You should also do this on the system where you executed these tasks because when you added the files git said:

    The file will have its original line endings in your working directory.
    

    You can do something like this to remove the files:

    git ls | grep ".ext$" | xargs rm -f
    

    And then this to get them back with the correct line endings:

    git ls | grep ".ext$" | xargs git checkout
    

    Of course replacing .ext with the extension you want.

Now your project only uses LF characters for the line endings, and the nasty CR characters won't ever come back :).

The other option is to enforce windows style line endings. You can also use the .gitattributes file for this.

More info: https://help.github.com/articles/dealing-with-line-endings/#platform-all

How to get a shell environment variable in a makefile?

for those who want some official document to confirm the behavior

Variables in make can come from the environment in which make is run. Every environment variable that make sees when it starts up is transformed into a make variable with the same name and value. However, an explicit assignment in the makefile, or with a command argument, overrides the environment. (If the ‘-e’ flag is specified, then values from the environment override assignments in the makefile.

https://www.gnu.org/software/make/manual/html_node/Environment.html

How to zoom in/out an UIImage object when user pinches screen?

Another easy way to do this is to place your UIImageView within a UIScrollView. As I describe here, you need to set the scroll view's contentSize to be the same as your UIImageView's size. Set your controller instance to be the delegate of the scroll view and implement the viewForZoomingInScrollView: and scrollViewDidEndZooming:withView:atScale: methods to allow for pinch-zooming and image panning. This is effectively what Ben's solution does, only in a slightly more lightweight manner, as you don't have the overhead of a full web view.

One issue you may run into is that the scaling within the scroll view comes in the form of transforms applied to the image. This may lead to blurriness at high zoom factors. For something that can be redrawn, you can follow my suggestions here to provide a crisper display after the pinch gesture is finished. hniels' solution could be used at that point to rescale your image.

How to copy folders to docker image from Dockerfile?

the simplest way:

sudo docker cp path/on/your/machine adam_ubuntu:/root/path_in_container

Note putting into the root path if you are copying something that needs to be picked up by the root using ~.

How do I make Git ignore file mode (chmod) changes?

Try:

git config core.fileMode false

From git-config(1):

core.fileMode
    Tells Git if the executable bit of files in the working tree
    is to be honored.

    Some filesystems lose the executable bit when a file that is
    marked as executable is checked out, or checks out a
    non-executable file with executable bit on. git-clone(1)
    or git-init(1) probe the filesystem to see if it handles the 
    executable bit correctly and this variable is automatically
    set as necessary.

    A repository, however, may be on a filesystem that handles
    the filemode correctly, and this variable is set to true when
    created, but later may be made accessible from another
    environment that loses the filemode (e.g. exporting ext4
    via CIFS mount, visiting a Cygwin created repository with Git
    for Windows or Eclipse). In such a case it may be necessary
    to set this variable to false. See git-update-index(1).

    The default is true (when core.filemode is not specified
    in the config file).

The -c flag can be used to set this option for one-off commands:

git -c core.fileMode=false diff

And the --global flag will make it be the default behavior for the logged in user.

git config --global core.fileMode false

Changes of the global setting won't be applied to existing repositories. Additionally, git clone and git init explicitly set core.fileMode to true in the repo config as discussed in Git global core.fileMode false overridden locally on clone

Warning

core.fileMode is not the best practice and should be used carefully. This setting only covers the executable bit of mode and never the read/write bits. In many cases you think you need this setting because you did something like chmod -R 777, making all your files executable. But in most projects most files don't need and should not be executable for security reasons.

The proper way to solve this kind of situation is to handle folder and file permission separately, with something like:

find . -type d -exec chmod a+rwx {} \; # Make folders traversable and read/write
find . -type f -exec chmod a+rw {} \;  # Make files read/write

If you do that, you'll never need to use core.fileMode, except in very rare environment.

JavaScript: Check if mouse button down?

        var mousedown = 0;
        $(function(){
            document.onmousedown = function(e){
                mousedown = mousedown | getWindowStyleButton(e);
                e = e || window.event;
                console.log("Button: " + e.button + " Which: " + e.which + " MouseDown: " + mousedown);
            }

            document.onmouseup = function(e){
                mousedown = mousedown ^ getWindowStyleButton(e);
                e = e || window.event;
                console.log("Button: " + e.button + " Which: " + e.which + " MouseDown: " + mousedown);
            }

            document.oncontextmenu = function(e){
                // to suppress oncontextmenu because it blocks
                // a mouseup when two buttons are pressed and 
                // the right-mouse button is released before
                // the other button.
                return false;
            }
        });

        function getWindowStyleButton(e){
            var button = 0;
                if (e) {
                    if (e.button === 0) button = 1;
                    else if (e.button === 1) button = 4;
                    else if (e.button === 2) button = 2;  
                }else if (window.event){
                    button = window.event.button;
                }
            return button;
        }

this cross-browser version works fine for me.

Creating an array of objects in Java

The genaral form to declare a new array in java is as follows:

type arrayName[] = new type[numberOfElements];

Where type is a primitive type or Object. numberOfElements is the number of elements you will store into the array and this value can’t change because Java does not support dynamic arrays (if you need a flexible and dynamic structure for holding objects you may want to use some of the Java collections).

Lets initialize an array to store the salaries of all employees in a small company of 5 people:

int salaries[] = new int[5];

The type of the array (in this case int) applies to all values in the array. You can not mix types in one array.

Now that we have our salaries array initialized we want to put some values into it. We can do this either during the initialization like this:

int salaries[] = {50000, 75340, 110500, 98270, 39400};

Or to do it at a later point like this:

salaries[0] = 50000;
salaries[1] = 75340;
salaries[2] = 110500;
salaries[3] = 98270;
salaries[4] = 39400;

More visual example of array creation: enter image description here

To learn more about Arrays, check out the guide.

Superscript in Python plots

Alternatively, in python 3.6+, you can generate Unicode superscript and copy paste that in your code:

ax1.set_ylabel('Rate (min?¹)')

Insert a background image in CSS (Twitter Bootstrap)

Is your image on the same folder/directory as your css file? If so, your image url is correct. Otherwise, it's not.

If by any chance your folder structure is like so...

webpage
-index.html
-css
- - style.css
- images
- - background.png

then to reference the image on your css file you should use the following path:

../images/background.png

So that would be background: url('../images/background.png');

The logic is simple: Go up one folder by typing "../" (as many times as you need). Go down one folder by specifying the folder you wish to go down to.

Adding data attribute to DOM

 $(document.createElement("img")).attr({
                src: 'https://graph.facebook.com/'+friend.id+'/picture',
                title: friend.name ,
                'data-friend-id':friend.id,
                'data-friend-name':friend.name
            }).appendTo(divContainer);

How do I read an attribute on a class at runtime?

Rather then write a lot of code, just do this:

{         
   dynamic tableNameAttribute = typeof(T).CustomAttributes.FirstOrDefault().ToString();
   dynamic tableName = tableNameAttribute.Substring(tableNameAttribute.LastIndexOf('.'), tableNameAttribute.LastIndexOf('\\'));    
}

How to declare a structure in a header that is to be used by multiple files in c?

For a structure definition that is to be used across more than one source file, you should definitely put it in a header file. Then include that header file in any source file that needs the structure.

The extern declaration is not used for structure definitions, but is instead used for variable declarations (that is, some data value with a structure type that you have defined). If you want to use the same variable across more than one source file, declare it as extern in a header file like:

extern struct a myAValue;

Then, in one source file, define the actual variable:

struct a myAValue;

If you forget to do this or accidentally define it in two source files, the linker will let you know about this.

Gradle - Move a folder from ABC to XYZ

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

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

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

How to get a List<string> collection of values from app.config in WPF?

I love Richard Nienaber's answer, but as Chuu pointed out, it really doesn't tell how to accomplish what Richard is refering to as a solution. Therefore I have chosen to provide you with the way I ended up doing this, ending with the result Richard is talking about.

The solution

In this case I'm creating a greeting widget that needs to know which options it has to greet in. This may be an over-engineered solution to OPs question as I am also creating an container for possible future widgets.

First I set up my collection to handle the different greetings

public class GreetingWidgetCollection : System.Configuration.ConfigurationElementCollection
{
    public List<IGreeting> All { get { return this.Cast<IGreeting>().ToList(); } }

    public GreetingElement this[int index]
    {
        get
        {
            return base.BaseGet(index) as GreetingElement;
        }
        set
        {
            if (base.BaseGet(index) != null)
            {
                base.BaseRemoveAt(index);
            }
            this.BaseAdd(index, value);
        }
    }

    protected override ConfigurationElement CreateNewElement()
    {
        return new GreetingElement();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((GreetingElement)element).Greeting;
    }
}

Then we create the acutal greeting element and it's interface

(You can omit the interface, that's just the way I'm always doing it.)

public interface IGreeting
{
    string Greeting { get; set; }
}

public class GreetingElement : System.Configuration.ConfigurationElement, IGreeting
{
    [ConfigurationProperty("greeting", IsRequired = true)]
    public string Greeting
    {
        get { return (string)this["greeting"]; }
        set { this["greeting"] = value; }
    }
}

The greetingWidget property so our config understands the collection

We define our collection GreetingWidgetCollection as the ConfigurationProperty greetingWidget so that we can use "greetingWidget" as our container in the resulting XML.

public class Widgets : System.Configuration.ConfigurationSection
{
    public static Widgets Widget => ConfigurationManager.GetSection("widgets") as Widgets;

    [ConfigurationProperty("greetingWidget", IsRequired = true)]
    public GreetingWidgetCollection GreetingWidget
    {
        get { return (GreetingWidgetCollection) this["greetingWidget"]; }
        set { this["greetingWidget"] = value; }
    }
}

The resulting XML

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <widgets>
       <greetingWidget>
           <add greeting="Hej" />
           <add greeting="Goddag" />
           <add greeting="Hello" />
           ...
           <add greeting="Konnichiwa" />
           <add greeting="Namaskaar" />
       </greetingWidget>
    </widgets>
</configuration>

And you would call it like this

List<GreetingElement> greetings = Widgets.GreetingWidget.All;

C compiler for Windows?

GCC is ubiquitous. It is trusted and well understood by thousands of folks across dozens of communities.

Visual Studio is perhaps the best IDE ever developed. It has a great compiler underneath it. But it is strictly Windows-only.

If you're just playing, get GCC --it's free. If you're concerned about multiple platfroms, it's GCC. If you're talking serious Windows development, get Visual Studio.

Sort matrix according to first column in R

Creating a data.table with key=V1 automatically does this for you. Using Stephan's data foo

> require(data.table)
> foo.dt <- data.table(foo, key="V1")
> foo.dt
   V1  V2
1:  1 349
2:  1 393
3:  1 392
4:  2  94
5:  3  49
6:  3  32
7:  4 459

How to sort an ArrayList in Java

Use a Comparator like this:

List<Fruit> fruits= new ArrayList<Fruit>();

Fruit fruit;
for(int i = 0; i < 100; i++)
{
  fruit = new Fruit();
  fruit.setname(...);
  fruits.add(fruit);
}

// Sorting
Collections.sort(fruits, new Comparator<Fruit>() {
        @Override
        public int compare(Fruit fruit2, Fruit fruit1)
        {

            return  fruit1.fruitName.compareTo(fruit2.fruitName);
        }
    });

Now your fruits list is sorted based on fruitName.

Creating an object: with or without `new`

The first allocates an object with automatic storage duration, which means it will be destructed automatically upon exit from the scope in which it is defined.

The second allocated an object with dynamic storage duration, which means it will not be destructed until you explicitly use delete to do so.

Postgresql Windows, is there a default password?

Try this:

Open PgAdmin -> Files -> Open pgpass.conf

You would get the path of pgpass.conf at the bottom of the window. Go to that location and open this file, you can find your password there.

Reference

If the above does not work, you may consider trying this:

 1. edit pg_hba.conf to allow trust authorization temporarily
 2. Reload the config file (pg_ctl reload)
 3. Connect and issue ALTER ROLE / PASSWORD to set the new password
 4. edit pg_hba.conf again and restore the previous settings
 5. Reload the config file again

Removing spaces from string

String  input = EditTextinput.getText().toString();
input = input.replace(" ", "");

Sometimes you would want to remove only the spaces at the beginning or end of the String (not the ones in the middle). If that's the case you can use trim:

input = input.trim();

Unable to compile class for JSP

It may be related to Java JRE version.

In my case I need Tomcat 6.0.26 which presented same error with JRE 1.8.0_91. A downgrade to JRE 1.7.49 solved it.

You might find more information in: http://www.howopensource.com/2015/07/unable-to-compile-class-for-jsp-the-type-java-util-mapentry-cannot-be-resolved/

How to disable scrolling the document body?

If you want to use the iframe's scrollbar and not the parent's use this:

document.body.style.overflow = 'hidden';

If you want to use the parent's scrollbar and not the iframe's then you need to use:

document.getElementById('your_iframes_id').scrolling = 'no';

or set the scrolling="no" attribute in your iframe's tag: <iframe src="some_url" scrolling="no">.

How to get browser width using JavaScript code?

It's a pain in the ass. I recommend skipping the nonsense and using jQuery, which lets you just do $(window).width().

Set transparent background using ImageMagick and commandline prompt

Yep. Had this same problem too. Here's the command I ran and it worked perfectly: convert transparent-img1.png transparent-img2.png transparent-img3.png -channel Alpha favicon.ico

phpmyadmin - count(): Parameter must be an array or an object that implements Countable

Try replace this function in file: /usr/share/phpmyadmin/libraries/sql.lib.php

function PMA_isRememberSortingOrder($analyzed_sql_results)
{
    return $GLOBALS['cfg']['RememberSorting']
        && ! ($analyzed_sql_results['is_count']
            || $analyzed_sql_results['is_export']
            || $analyzed_sql_results['is_func']
            || $analyzed_sql_results['is_analyse'])
        && $analyzed_sql_results['select_from']
        && ((empty($analyzed_sql_results['select_expr']))
            || (count($analyzed_sql_results['select_expr']) == 1)
                && ($analyzed_sql_results['select_expr'][0] == '*'))
        && count($analyzed_sql_results['select_tables']) == 1;
}

Jackson and generic type reference

I modified rushidesai1's answer to include a working example.

JsonMarshaller.java

import java.io.*;
import java.util.*;

public class JsonMarshaller<T> {
    private static ClassLoader loader = JsonMarshaller.class.getClassLoader();

    public static void main(String[] args) {
        try {
            JsonMarshallerUnmarshaller<Station> marshaller = new JsonMarshallerUnmarshaller<>(Station.class);
            String jsonString = read(loader.getResourceAsStream("data.json"));
            List<Station> stations = marshaller.unmarshal(jsonString);
            stations.forEach(System.out::println);
            System.out.println(marshaller.marshal(stations));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @SuppressWarnings("resource")
    public static String read(InputStream ios) {
        return new Scanner(ios).useDelimiter("\\A").next(); // Read the entire file
    }
}

Output

Station [id=123, title=my title, name=my name]
Station [id=456, title=my title 2, name=my name 2]
[{"id":123,"title":"my title","name":"my name"},{"id":456,"title":"my title 2","name":"my name 2"}]

JsonMarshallerUnmarshaller.java

import java.io.*;
import java.util.List;

import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;

public class JsonMarshallerUnmarshaller<T> {
    private ObjectMapper mapper;
    private Class<T> targetClass;

    public JsonMarshallerUnmarshaller(Class<T> targetClass) {
        AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();

        mapper = new ObjectMapper();
        mapper.getDeserializationConfig().with(introspector);
        mapper.getSerializationConfig().with(introspector);

        this.targetClass = targetClass;
    }

    public List<T> unmarshal(String jsonString) throws JsonParseException, JsonMappingException, IOException {
        return parseList(jsonString, mapper, targetClass);
    }

    public String marshal(List<T> list) throws JsonProcessingException {
        return mapper.writeValueAsString(list);
    }

    public static <E> List<E> parseList(String str, ObjectMapper mapper, Class<E> clazz)
            throws JsonParseException, JsonMappingException, IOException {
        return mapper.readValue(str, listType(mapper, clazz));
    }

    public static <E> List<E> parseList(InputStream is, ObjectMapper mapper, Class<E> clazz)
            throws JsonParseException, JsonMappingException, IOException {
        return mapper.readValue(is, listType(mapper, clazz));
    }

    public static <E> JavaType listType(ObjectMapper mapper, Class<E> clazz) {
        return mapper.getTypeFactory().constructCollectionType(List.class, clazz);
    }
}

Station.java

public class Station {
    private long id;
    private String title;
    private String name;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return String.format("Station [id=%s, title=%s, name=%s]", id, title, name);
    }
}

data.json

[{
  "id": 123,
  "title": "my title",
  "name": "my name"
}, {
  "id": 456,
  "title": "my title 2",
  "name": "my name 2"
}]

What is the height of Navigation Bar in iOS 7?

There is a difference between the navigation bar and the status bar. The confusing part is that it looks like one solid feature at the top of the screen, but the areas can actually be separated into two distinct views; a status bar and a navigation bar. The status bar spans from y=0 to y=20 points and the navigation bar spans from y=20 to y=64 points. So the navigation bar (which is where the page title and navigation buttons go) has a height of 44 points, but the status bar and navigation bar together have a total height of 64 points.

Here is a great resource that addresses this question along with a number of other sizing idiosyncrasies in iOS7: http://ivomynttinen.com/blog/the-ios-7-design-cheat-sheet/

OTP (token) should be automatically read from the message

Yes, this is possible now in browsers also. Chrome release this feature in version 84 and above. With the help of WEBOTP API, we can detect OTP on the web for mobile devices.

Here is a Web-OTP integrated code with Angular PWA Apps: https://github.com/Rohit3230/webOtpAutoReadByAngular

Go for live working URL for angular PWA app. https://rohit3230.github.io/webOtpAutoReadByAngular/

Finding partial text in range, return an index

I just found this when googling to solve the same problem, and had to make a minor change to the solution to make it work in my situation, as I had 2 similar substrings, "Sun" and "Sunstruck" to search for. The offered solution was locating the wrong entry when searching for "Sun". Data in column B

I added another column C, formulaes C1=" "&B1&" " and changed the search to =COUNTIF(B1:B10,"* "&A1&" *")>0, the extra column to allow finding the first of last entry in the concatenated string.

How should the ViewModel close the form?

I used attached behaviours to close the window. Bind a "signal" property on your ViewModel to the attached behaviour (I actually use a trigger) When it's set to true, the behaviour closes the window.

http://adammills.wordpress.com/2009/07/01/window-close-from-xaml/

C pointers and arrays: [Warning] assignment makes pointer from integer without a cast

What are you doing: (I am using bytes instead of in for better reading)

You start with int *ap and so on, so your (your computers) memory looks like this:

-------------- memory used by some one else --------
000: ?
001: ?
...
098: ?
099: ?
-------------- your memory  --------
100: something          <- here is *ap
101: 41                 <- here starts a[] 
102: 42
103: 43
104: 44
105: 45
106: something          <- here waits x

lets take a look waht happens when (print short cut for ...print("$d", ...)

print a[0]  -> 41   //no surprise
print a     -> 101  // because a points to the start of the array
print *a    -> 41   // again the first element of array
print a+1   -> guess? 102
print *(a+1)    -> whats behind 102? 42 (we all love this number)

and so on, so a[0] is the same as *a, a[1] = *(a+1), ....

a[n] just reads easier.

now, what happens at line 9?

ap=a[4] // we know a[4]=*(a+4) somehow *105 ==>  45 
// warning! converting int to pointer!
-------------- your memory  --------
100: 45         <- here is *ap now 45

x = *ap;   // wow ap is 45 -> where is 45 pointing to?
-------------- memory used by some one else --------
bang!      // dont touch neighbours garden

So the "warning" is not just a warning it's a severe error.

How can I check if a MySQL table exists with PHP?

SHOW TABLES LIKE 'TableName'

If you have ANY results, the table exists.

To use this approach in PDO:

$pdo         = new \PDO(/*...*/);
$result      = $pdo->query("SHOW TABLES LIKE 'tableName'");
$tableExists = $result !== false && $result->rowCount() > 0;

To use this approach with DEPRECATED mysql_query

$result      = mysql_query("SHOW TABLES LIKE 'tableName'");
$tableExists = mysql_num_rows($result) > 0;

How to create string with multiple spaces in JavaScript

Use &nbsp;

It is the entity used to represent a non-breaking space. It is essentially a standard space, the primary difference being that a browser should not break (or wrap) a line of text at the point that this   occupies.

var a = 'something' + '&nbsp &nbsp &nbsp &nbsp &nbsp' + 'something'

Non-breaking Space

A common character entity used in HTML is the non-breaking space (&nbsp;).

Remember that browsers will always truncate spaces in HTML pages. If you write 10 spaces in your text, the browser will remove 9 of them. To add real spaces to your text, you can use the &nbsp; character entity.

http://www.w3schools.com/html/html_entities.asp

Demo

_x000D_
_x000D_
var a = 'something' + '&nbsp &nbsp &nbsp &nbsp &nbsp' + 'something';_x000D_
_x000D_
document.body.innerHTML = a;
_x000D_
_x000D_
_x000D_

How do I do a Date comparison in Javascript?

    function validateform()
    {
     if (trimAll(document.getElementById("<%=txtFromDate.ClientID %>").value) != "") {
   if (!isDate(trimAll(document.getElementById("<%=txtFromDate.ClientID %>").value)))
         msg = msg + "<li>Please enter valid From Date in mm/dd/yyyy format\n";
   else {
       var toDate = new Date();
       var txtdate = document.getElementById("<%=txtFromDate.ClientID %>").value;
       var d1 = new Date(txtdate)
   if (Date.parse(txtdate) > Date.parse(toDate)) {                   
         msg = msg + "<li>From date must be less than or equal to today's date\n";
   }
  }
}

     if (trimAll(document.getElementById("<%=txtToDate.ClientID %>").value) != "") {
            if (!isDate(trimAll(document.getElementById("<%=txtToDate.ClientID %>").value)))
                msg = msg + "<li>Please enter valid To Date in mm/dd/yyyy format\n";
            else {
                var toDate = new Date();
                var txtdate = document.getElementById("<%=txtToDate.ClientID %>").value;
                var d1 = new Date(txtdate)

                if (Date.parse(txtdate) > Date.parse(toDate)) {
                    msg = msg + "<li>To date must be less than or equal to today's date\n"; 
                  }
                 }
                }

Use URI builder in Android or create URL with variables

Using appendEncodePath() could save you multiple lines than appendPath(), the following code snippet builds up this url: http://api.openweathermap.org/data/2.5/forecast/daily?zip=94043

Uri.Builder urlBuilder = new Uri.Builder();
urlBuilder.scheme("http");
urlBuilder.authority("api.openweathermap.org");
urlBuilder.appendEncodedPath("data/2.5/forecast/daily");
urlBuilder.appendQueryParameter("zip", "94043,us");
URL url = new URL(urlBuilder.build().toString());

What should every programmer know about security?

Rule #1 of security for programmers: Don't roll your own

Unless you are yourself a security expert and/or cryptographer, always use a well-designed, well-tested, and mature security platform, framework, or library to do the work for you. These things have spent years being thought out, patched, updated, and examined by experts and hackers alike. You want to gain those advantages, not dismiss them by trying to reinvent the wheel.

Now, that's not to say you don't need to learn anything about security. You certainly need to know enough to understand what you're doing and make sure you're using the tools correctly. However, if you ever find yourself about to start writing your own cryptography algorithm, authentication system, input sanitizer, etc, stop, take a step back, and remember rule #1.

How to escape a while loop in C#

If you need to continue with additional logic use...

break;

or if you have a value to return...

return my_value_to_be_returned;

However, looking at your code, I believe you will control the loop with the revised example below without using a break or return...

private void CheckLog()
        {
            bool continueLoop = true;
            while (continueLoop)
            {
                Thread.Sleep(5000);
                if (!System.IO.File.Exists("Command.bat")) continue;
                using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat"))
                {
                    string s = "";
                    while (continueLoop && (s = sr.ReadLine()) != null)
                    {
                        if (s.Contains("mp4:production/CATCHUP/"))
                        {
                            RemoveEXELog();

                            Process p = new Process();
                            p.StartInfo.WorkingDirectory = "dump";
                            p.StartInfo.FileName = "test.exe"; 
                            p.StartInfo.Arguments = s; 
                            p.Start();
                            continueLoop = false;
                        }
                    }
                }
            }
        }

msvcr110.dll is missing from computer error while installing PHP

Since link to this question shows up on very top of returned results when you search for "php MSVCR110.dll" (not to mention it got 100k+ views and growing), here're some additional notes that you may find handy in your quest to solve MSVCR110.dll mistery...

The approach described in the answer is valid not only for MSVCR110.dll case but also applies when you are looking for other versions, like newer MSVCR71.dll and I updated the answer to include VC15 even it's beyond scope of the original question.


On http://windows.php.net/ you can read:

VC9, VC11 and VC15

More recent versions of PHP are built with VC9, VC11 or VC15 (Visual Studio 2008, 2012 or 2015 compiler respectively) and include improvements in performance and stability.

The VC9 builds require you to have the Visual C++ Redistributable for Visual Studio 2008 SP1 x86 or x64 installed.

The VC11 builds require to have the Visual C++ Redistributable for Visual Studio 2012 x86 or x64 installed.

The VC15 builds require to have the Visual C++ Redistributable for Visual Studio 2015 x86 or x64 installed.

This is quite crucial as you not only need to get Visual C++ Redistributable installed but you also need the right version of it, and which one is right and correct, depends on what PHP build you are actually going to use. Pay attention to what version of PHP for Windows you are fetching, especially pay attention to this "VCxx" suffix, because if you install PHP that requires VC9 while having redistributables VC11 installed it is not going to work as run-time dependency is simply not fulfilled. Contrary to what some may think, you need exactly the version required, as newer (higher) releases does NOT cover older (lower) versions. so i.e. VC11 is not providing VC9 compatibility. Also VC15 is neither fulfilling VC11 nor VC9 dependency. It is just VC15 and NOTHING ELSE. Deal with it :)

For example, archive name php-5.6.4-nts-Win32-VC11-x86 tells us the following

enter image description here

  1. it provides PHP v5.6.4,
  2. PHP build is Non-Thread Safe (nts),
  3. it provides binaries for Windows (Win32),
  4. to run, Visual Studio 2012 redistributable (VC11) is required,
  5. binaries are 32-bit (x86),

Most searches I did lead to VC9 of redistributables, so in case of constant failures to make thing works, if possible, try installing different PHP build, to see if you by any chance do not face mismatching versions.


Download links

Note that you are using 32-bit version of PHP, so you need 32-bit redistributable (x86) even if your version of Windows is 64-bit!

  • VC9: Visual C++ Redistributable for Visual Studio 2008: x86 or x64
  • VC11: Visual C++ Redistributable for Visual Studio 2012: x86 or x64
  • VC15: Visual C++ Redistributable for Visual Studio 2015: x86 or x64
  • VC17: Visual C++ Redistributable for Visual Studio 2017: x86 or x64

DynamoDB vs MongoDB NoSQL

Short answer: Start with SQL and add NoSQL only when/if needed. (unless you don't need anything beyond very simple queries)

My personal experience: I haven't used MongoDB for queries but as of April 2015 DynamoDB is still very crippled when it comes to anything beyond the most basic key/value queries. I love it for the basic stuff but if you want query language then look to a real SQL database solution.

In DynamoDB you can query on a hash or on a hash and range key, and you can have multiple secondary global indexes. I'm doing queries on a single table with 4 possible filter parameters and sorting the results, this is supported (barely) through the use of the global secondary indexes with filter expressions. The problem comes in when you try to get the total results matching the filter, you can't just search for the first 10 items matching the filter, but rather it checks 10 items and you may get 0 valid results forcing you to keep re-scanning from the continue key - pain in the neck and consumes too much of your table read quota for a simple scenario.

To be specific about the limit problem with filters in the query, this is from the docs (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html#ScanQueryLimit):

In a response, DynamoDB returns all the matching results within
the scope of the Limit value. For example, if you issue a Query 
or a Scan request with a Limit value of 6 and without a filter
expression, the operation returns the first six items in the 
table that match the request parameters. If you also supply a
FilterExpression, the operation returns the items within the 
first six items in the table that match the filter requirements.

My conclusion is that queries involving FilterExpressions are only usable on very rare occasions and are not scalable because each query can easily read most or all of your of your table which consumes far too many DynamoDB read units. Once you use too many read units you'll get throttled and see poor performance.

Expert opinion: In the AWS summit on Apr 9, 2015 Brett Hollman, Manager, Solutions Architecture, AWS in his talk on scalling to your first 10 million users advocates starting with a SQL database and then using NoSQL only when and if it makes sense. Because sooner or later you'll probably need a SQL server somewhere in your stack. His slides are here: http://www.slideshare.net/AmazonWebServices/deep-dive-scaling-up-to-your-first-10-million-users See slide 28.

Detect when a window is resized using JavaScript ?

This can be achieved with the onresize property of the GlobalEventHandlers interface in JavaScript, by assigning a function to the onresize property, like so:

window.onresize = functionRef;

The following code snippet demonstrates this, by console logging the innerWidth and innerHeight of the window whenever it's resized. (The resize event fires after the window has been resized)

_x000D_
_x000D_
function resize() {_x000D_
  console.log("height: ", window.innerHeight, "px");_x000D_
  console.log("width: ", window.innerWidth, "px");_x000D_
}_x000D_
_x000D_
window.onresize = resize;
_x000D_
<p>In order for this code snippet to work as intended, you will need to either shrink your browser window down to the size of this code snippet, or fullscreen this code snippet and resize from there.</p>
_x000D_
_x000D_
_x000D_

How to check if a string contains an element from a list in Python

Use list comprehensions if you want a single line solution. The following code returns a list containing the url_string when it has the extensions .doc, .pdf and .xls or returns empty list when it doesn't contain the extension.

print [url_string for extension in extensionsToCheck if(extension in url_string)]

NOTE: This is only to check if it contains or not and is not useful when one wants to extract the exact word matching the extensions.

How to set dropdown arrow in spinner?

If you have a vector icon and not bitmap, you can set it this way.

<item>
    <layer-list>
        <item>
            <shape android:shape="rectangle">
                <gradient android:angle="270" android:centerColor="#65FFFFFF" android:centerY="0.2" android:endColor="#00FFFFFF" android:startColor="@color/light_gray" />
                <stroke android:width="1dp" android:color="@color/darkGray" />
                <corners android:radius="@dimen/edit_text_corner_radius" />
            </shape>
        </item>

        <item
            android:right="5dp"
            android:gravity="center|right"
            android:drawable="@drawable/gardify_spinner_dropdown_icon"/>

    </layer-list>
</item>

How can I store the result of a system command in a Perl variable?

The easiest way is to use the `` feature in Perl. This will execute what is inside and return what was printed to stdout:

 my $pid = 5892;
 my $var = `top -H -p $pid -n 1 | grep myprocess | wc -l`;
 print "not = $var\n";

This should do it.

ImageView in circular through xml

@Jyotman Singh, answer is very good (for solid backgrounds), so I would like to enhance it by sharing vector drawable that can be re-colored for your needs, also it is convenient since vector one-piece shape is well scalable.

This is the rectangle-circle shape (@drawable/shape_round_profile_pic):

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:viewportWidth="284"
    android:viewportHeight="284"
    android:width="284dp"
    android:height="284dp">
    <path
        android:pathData="M0 142L0 0l142 0 142 0 0 142 0 142 -142 0 -142 0zm165 137.34231c26.06742 -4.1212 52.67405 -17.543 72.66855 -36.65787 11.82805 -11.30768 20.55487 -22.85153 27.7633 -36.72531C290.23789 158.21592 285.62874 101.14121 253.48951 58.078079 217.58149 9.9651706 154.68849 -10.125717 98.348685 8.5190299 48.695824 24.95084 12.527764 67.047123 3.437787 118.98655 1.4806194 130.16966 1.511302 152.96723 3.4990422 164.5 12.168375 214.79902 47.646316 256.70775 96 273.76783c21.72002 7.66322 44.26673 9.48476 69 5.57448z"
        android:fillColor="#ffffff" /> // you can change frame color
</vector>

Usage is the same:

<FrameLayout
        android:layout_width="70dp"
        android:layout_height="70dp">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/YOUR_PICTURE" />

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/shape_round_profile_pic"/>

    </FrameLayout>

TypeError: Invalid dimensions for image data when plotting array with imshow()

There is a (somewhat) related question on StackOverflow:

Here the problem was that an array of shape (nx,ny,1) is still considered a 3D array, and must be squeezed or sliced into a 2D array.

More generally, the reason for the Exception

TypeError: Invalid dimensions for image data

is shown here: matplotlib.pyplot.imshow() needs a 2D array, or a 3D array with the third dimension being of shape 3 or 4!

You can easily check this with (these checks are done by imshow, this function is only meant to give a more specific message in case it's not a valid input):

from __future__ import print_function
import numpy as np

def valid_imshow_data(data):
    data = np.asarray(data)
    if data.ndim == 2:
        return True
    elif data.ndim == 3:
        if 3 <= data.shape[2] <= 4:
            return True
        else:
            print('The "data" has 3 dimensions but the last dimension '
                  'must have a length of 3 (RGB) or 4 (RGBA), not "{}".'
                  ''.format(data.shape[2]))
            return False
    else:
        print('To visualize an image the data must be 2 dimensional or '
              '3 dimensional, not "{}".'
              ''.format(data.ndim))
        return False

In your case:

>>> new_SN_map = np.array([1,2,3])
>>> valid_imshow_data(new_SN_map)
To visualize an image the data must be 2 dimensional or 3 dimensional, not "1".
False

The np.asarray is what is done internally by matplotlib.pyplot.imshow so it's generally best you do it too. If you have a numpy array it's obsolete but if not (for example a list) it's necessary.


In your specific case you got a 1D array, so you need to add a dimension with np.expand_dims()

import matplotlib.pyplot as plt
a = np.array([1,2,3,4,5])
a = np.expand_dims(a, axis=0)  # or axis=1
plt.imshow(a)
plt.show()

enter image description here

or just use something that accepts 1D arrays like plot:

a = np.array([1,2,3,4,5])
plt.plot(a)
plt.show()

enter image description here

Background color on input type=button :hover state sticks in IE

You need to make sure images come first and put in a comma after the background image call. then it actually does work:

    background:url(egg.png) no-repeat 70px 2px #82d4fe; /* Old browsers */
background:url(egg.png) no-repeat 70px 2px, -moz-linear-gradient(top, #82d4fe 0%, #1db2ff 78%) ; /* FF3.6+ */
background:url(egg.png) no-repeat 70px 2px, -webkit-gradient(linear, left top, left bottom, color-stop(0%,#82d4fe), color-stop(78%,#1db2ff)); /* Chrome,Safari4+ */
background:url(egg.png) no-repeat 70px 2px, -webkit-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* Chrome10+,Safari5.1+ */
background:url(egg.png) no-repeat 70px 2px, -o-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* Opera11.10+ */
background:url(egg.png) no-repeat 70px 2px, -ms-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#82d4fe', endColorstr='#1db2ff',GradientType=0 ); /* IE6-9 */
background:url(egg.png) no-repeat 70px 2px, linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* W3C */

Javascript add leading zeroes to date

Try this: http://jsfiddle.net/xA5B7/

var MyDate = new Date();
var MyDateString;

MyDate.setDate(MyDate.getDate() + 20);

MyDateString = ('0' + MyDate.getDate()).slice(-2) + '/'
             + ('0' + (MyDate.getMonth()+1)).slice(-2) + '/'
             + MyDate.getFullYear();

EDIT:

To explain, .slice(-2) gives us the last two characters of the string.

So no matter what, we can add "0" to the day or month, and just ask for the last two since those are always the two we want.

So if the MyDate.getMonth() returns 9, it will be:

("0" + "9") // Giving us "09"

so adding .slice(-2) on that gives us the last two characters which is:

("0" + "9").slice(-2)
"09"

But if MyDate.getMonth() returns 10, it will be:

("0" + "10") // Giving us "010"

so adding .slice(-2) gives us the last two characters, or:

("0" + "10").slice(-2)
"10"

How to change package name of Android Project in Eclipse?

This worked perfectly for me (simple text replace):

Go to search -> file

Containing text: old pakage name

File name pattern: *

Scope: workspace

Press Replace

Replace: new package name

Now your project is full of errors.

Click your package in project explorer and press F2 (rename).

Fill in the new package name and check all checkmarks.

Press Preview.

Click OK.

Wait for Eclipse to refresh. If there are still errors, clean all projects in the workspace:

Project -> Clean

How to open a web server port on EC2 instance

You need to open TCP port 8787 in the ec2 Security Group. Also need to open the same port on the EC2 instance's firewall.

Emulator in Android Studio doesn't start

just check out if you have this problem "vt-x is disabled in bios"

enter image description here

in this case you need to enable virtualization technology bios

How to export data from Spark SQL to CSV

enter code here IN DATAFRAME:

val p=spark.read.format("csv").options(Map("header"->"true","delimiter"->"^")).load("filename.csv")

Full width layout with twitter bootstrap

I think you could just use class "col-md-12" it has required left and right paddings and 100% width. Looks like this is a good replacement for container-fluid from 2nd bootstrap.

Regex date validation for yyyy-mm-dd

You can use this regex to get the yyyy-MM-dd format:

((?:19|20)\\d\\d)-(0?[1-9]|1[012])-([12][0-9]|3[01]|0?[1-9])

You can find example for date validation: How to validate date with regular expression.

How to get textLabel of selected row in swift?

If you're in a class inherited from UITableViewController, then this is the swift version:

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    let cell = self.tableView.cellForRowAtIndexPath(indexPath)
    NSLog("did select and the text is \(cell?.textLabel?.text)")
}

Note that cell is an optional, so it must be unwrapped - and the same for textLabel. If any of the 2 is nil (unlikely to happen, because the method is called with a valid index path), if you want to be sure that a valid value is printed, then you should check that both cell and textLabel are both not nil:

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    let cell = self.tableView.cellForRowAtIndexPath(indexPath)
    let text = cell?.textLabel?.text
    if let text = text {
        NSLog("did select and the text is \(text)")
    }
}

Android Respond To URL in Intent

You might need to allow different combinations of data in your intent filter to get it to work in different cases (http/ vs https/, www. vs no www., etc).

For example, I had to do the following for an app which would open when the user opened a link to Google Drive forms (www.docs.google.com/forms)

Note that path prefix is optional.

        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data android:scheme="http" />
            <data android:scheme="https" />

            <data android:host="www.docs.google.com" />
            <data android:host="docs.google.com" />

            <data android:pathPrefix="/forms" />
        </intent-filter>

Stopping an Android app from console

If you have access to the application package, then you can install with the -r option and it will kill the process if it is currently running as a side effect. Like this:

adb -d install -r MyApp.apk ; adb -d shell am start -a android.intent.action.MAIN -n com.MyCompany.MyApp/.MyActivity

The -r option preserves the data currently associated with the app. However, if you want a clean slate like you mention you might not want to use that option.

How can I change NULL to 0 when getting a single value from a SQL function?

You could use

SELECT ISNULL(SUM(ISNULL(Price, 0)), 0).

I'm 99% sure that will work.

Remove a specific string from an array of string

You can't remove anything from an array - they're always fixed length. Once you've created an array of length 3, that array will always have length 3.

You'd be better off with a List<String>, e.g. an ArrayList<String>:

List<String> list = new ArrayList<String>();
list.add("google");
list.add("microsoft");
list.add("apple");
System.out.println(list.size()); // 3

list.remove("apple");
System.out.println(list.size()); // 2

Collections like this are generally much more flexible than working with arrays directly.

EDIT: For removal:

void removeRandomElement(List<?> list, Random random)
{
    int index = random.nextInt(list.size());
    list.remove(index);
}

How to write :hover condition for a:before and a:after?

This depends on what you're actually trying to do.

If you simply wish to apply styles to a :before pseudo-element when the a element matches a pseudo-class, you need to write a:hover:before or a:visited:before instead. Notice the pseudo-element comes after the pseudo-class (and in fact, at the very end of the entire selector). Notice also that they are two different things; calling them both "pseudo-selectors" is going to confuse you once you run into syntax problems such as this one.

If you're writing CSS3, you can denote a pseudo-element with double colons to make this distinction clearer. Hence, a:hover::before and a:visited::before. But if you're developing for legacy browsers such as IE8 and older, then you can get away with using single colons just fine.

This specific order of pseudo-classes and pseudo-elements is stated in the spec:

One pseudo-element may be appended to the last sequence of simple selectors in a selector.

A sequence of simple selectors is a chain of simple selectors that are not separated by a combinator. It always begins with a type selector or a universal selector. No other type selector or universal selector is allowed in the sequence.

A simple selector is either a type selector, universal selector, attribute selector, class selector, ID selector, or pseudo-class.

A pseudo-class is a simple selector. A pseudo-element, however, is not, even though it resembles a simple selector.

However, for user-action pseudo-classes such as :hover1, if you need this effect to apply only when the user interacts with the pseudo-element itself but not the a element, then this is not possible other than through some obscure layout-dependent workaround. As implied by the text, standard CSS pseudo-elements cannot currently have pseudo-classes. In that case, you will need to apply :hover to an actual child element instead of a pseudo-element.


1 Of course, this does not apply to link pseudo-classes such as :visited as in the question, since pseudo-elements aren't links.

How do you access the matched groups in a JavaScript regular expression?

We can access the matched group in a regular expressions by using backslash followed by number of the matching group:

/([a-z])\1/

In the code \1 represented matched by first group ([a-z])

How to change the display name for LabelFor in razor in mvc3?

This was an old question, but existing answers ignore the serious issue of throwing away any custom attributes when you regenerate the model. I am adding a more detailed answer to cover the current options available.

You have 3 options:

  • Add a [DisplayName("Name goes here")] attribute to the data model class. The downside is that this is thrown away whenever you regenerate the data models.
  • Add a string parameter to your Html.LabelFor. e.g. @Html.LabelFor(model => model.SomekingStatus, "My New Label", new { @class = "control-label"}) Reference: https://msdn.microsoft.com/en-us/library/system.web.mvc.html.labelextensions.labelfor(v=vs.118).aspx The downside to this is that you must repeat the label in every view.
  • Third option. Use a meta-data class attached to the data class (details follow).

Option 3 - Add a Meta-Data Class:

Microsoft allows for decorating properties on an Entity Framework class, without modifying the existing class! This by having meta-data classes that attach to your database classes (effectively a sideways extension of your EF class). This allow attributes to be added to the associated class and not to the class itself so the changes are not lost when you regenerate the data models.

For example, if your data class is MyModel with a SomekingStatus property, you could do it like this:

First declare a partial class of the same name (and using the same namespace), which allows you to add a class attribute without being overridden:

[MetadataType(typeof(MyModelMetaData))]
public partial class MyModel
{
}

All generated data model classes are partial classes, which allow you to add extra properties and methods by simply creating more classes of the same name (this is very handy and I often use it e.g. to provide formatted string versions of other field types in the model).

Step 2: add a metatadata class referenced by your new partial class:

public class MyModelMetaData
{
    // Apply DisplayNameAttribute (or any other attributes)
    [DisplayName("My New Label")]
    public string SomekingStatus;
}

Reference: https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.metadatatypeattribute(v=vs.110).aspx

Notes:

  • From memory, if you start using a metadata class, it may ignore existing attributes on the actual class ([required] etc) so you may need to duplicate those in the Meta-data class.
  • This does not operate by magic and will not just work with any classes. The code that looks for UI decoration attributes is designed to look for a meta-data class first.

How to return data from PHP to a jQuery ajax call

Yes, the way you are doing it is perfectly legitimate. To access that data on the client side, edit your success function to accept a parameter: data.

$.ajax({
    type: "POST",
    url: "somescript.php",
    datatype: "html",
    data: dataString,
    success: function(data) {
        doSomething(data);
    }
});

How to display div after click the button in Javascript?

HTML

<div id="myDiv" style="display:none;" class="answer_list" >WELCOME</div>
<input type="button" name="answer" onclick="ShowDiv()" />

JavaScript

function ShowDiv() {
    document.getElementById("myDiv").style.display = "";
}

Or if you wanted to use jQuery with a nice little animation:

<input id="myButton" type="button" name="answer" />

$('#myButton').click(function() {
  $('#myDiv').toggle('slow', function() {
    // Animation complete.
  });
});

assign value using linq

Be aware that it only updates the first company it found with company id 1. For multiple

 (from c in listOfCompany where c.id == 1 select c).First().Name = "Whatever Name";

For Multiple updates

 from c in listOfCompany where c.id == 1 select c => {c.Name = "Whatever Name";  return c;}

How do I stop/start a scheduled task on a remote computer programmatically?

Try this:

schtasks /change /ENABLE /tn "Auto Restart" /s mycomutername /u mycomputername\username/p mypassowrd

Margin-Top not working for span element?

span is an inline element that doesn't support vertical margins. Put the margin on the outer div instead.

Get the Year/Month/Day from a datetime in php?

Try below code if you want to use php loop to display

<span>
  <select name="birth_month">
    <?php for( $m=1; $m<=12; ++$m ) { 
      $month_label = date('F', mktime(0, 0, 0, $m, 1));
    ?>
      <option value="<?php echo $month_label; ?>"><?php echo $month_label; ?></option>
    <?php } ?>
  </select> 
</span>
<span>
  <select name="birth_day">
    <?php 
      $start_date = 1;
      $end_date   = 31;
      for( $j=$start_date; $j<=$end_date; $j++ ) {
        echo '<option value='.$j.'>'.$j.'</option>';
      }
    ?>
  </select>
</span>
<span>
  <select name="birth_year">
    <?php 
      $year = date('Y');
      $min = $year - 60;
      $max = $year;
      for( $i=$max; $i>=$min; $i-- ) {
        echo '<option value='.$i.'>'.$i.'</option>';
      }
    ?>
  </select>
</span>

Using group by and having clause

Because we can not use Where clause with aggregate functions like count(),min(), sum() etc. so having clause came into existence to overcome this problem in sql. see example for having clause go through this link

http://www.sqlfundamental.com/having-clause.php

WebView and Cookies on Android

I figured out what's going on.

When I load a page through a server side action (a url visit), and view the html returned from that action inside a Webview, that first action/page runs inside that Webview. However, when you click on any link that are action commands in your web app, these actions start a new browser. That is why cookie info gets lost because the first cookie information you set for Webview is gone, we have a seperate program here.

You have to intercept clicks on Webview so that browsing never leaves the app, everything stays inside the same Webview.

  WebView webview = new WebView(this);      
  webview.setWebViewClient(new WebViewClient() {  
      @Override  
      public boolean shouldOverrideUrlLoading(WebView view, String url)  
      {  
        view.loadUrl(url); //this is controversial - see comments and other answers
        return true;  
      }  
    });                 
  setContentView(webview);      
  webview.loadUrl([MY URL]);

This fixes the problem.

Store an array in HashMap

If you want to store multiple values for a key (if I understand you correctly), you could try a MultiHashMap (available in various libraries, not only commons-collections).

How to install VS2015 Community Edition offline

You can download visual studio community edition with /layout switch.

But I prefer to use /layout with /NoRefresh for my low-speed internet connection that downloading long more than a day.

vs_community.exe /layout /NoRefresh

Every time that you run the installer it searches for new updates and if it finds updates, start downloading them and consume more time and more bandwidth!

android: changing option menu items programmatically

you can accomplish your task simply by implementing as below:

private Menu menu;

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.drive_menu, menu);
    return true;
}

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    this.menu = menu;
    return super.onPrepareOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.action_toggle_grid) {
        handleMenuOption(id);
        return true;

    } else if(id == R.id.action_toggle_list){
        handleMenuOption(id);
        return true;
    }

    return super.onOptionsItemSelected(item);
}

private void handleMenuOption(int id) {
    MenuItem item = menu.findItem(id);
    if (id == R.id.action_toggle_grid){
        item.setVisible(false);
        menu.findItem(R.id.action_toggle_list).setVisible(true);
    }else if (id == R.id.action_toggle_list){
        item.setVisible(false);
        menu.findItem(R.id.action_toggle_grid).setVisible(true);
    }
}

HTML table with fixed headers?

Here is an improved answer to the one posted by Maximilian Hils.

This one works in Internet Explorer 11 with no flickering whatsoever:

var headerCells = tableWrap.querySelectorAll("thead td");
for (var i = 0; i < headerCells.length; i++) {
    var headerCell = headerCells[i];
    headerCell.style.backgroundColor = "silver";
}
var lastSTop = tableWrap.scrollTop;
tableWrap.addEventListener("scroll", function () {
    var stop = this.scrollTop;
    if (stop < lastSTop) {
        // Resetting the transform for the scrolling up to hide the headers
        for (var i = 0; i < headerCells.length; i++) {
            headerCells[i].style.transitionDelay = "0s";
            headerCells[i].style.transform = "";
        }
    }
    lastSTop = stop;
    var translate = "translate(0," + stop + "px)";
    for (var i = 0; i < headerCells.length; i++) {
        headerCells[i].style.transitionDelay = "0.25s";
        headerCells[i].style.transform = translate;
    }
});

How to change visibility of layout programmatically

TextView view = (TextView) findViewById(R.id.textView);
view.setText("Add your text here");
view.setVisibility(View.VISIBLE);

Android Activity without ActionBar

If you want most of your activities to have an action bar you would probably inherit your base theme from the default one (this is automatically generated by Android Studio per default):

<!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

And then add a special theme for your bar-less activity:

<style name="AppTheme.NoTitle" parent="AppTheme">
        <item name="windowNoTitle">true</item>
        <item name="windowActionBar">false</item>
        <item name="actionBarTheme">@null</item>
    </style>

For me, setting actionBarTheme to @null was the solution.

Finally setup the activity in your manifest file:

<activity ... android:theme="@style/AppTheme.NoTitle" ... >

How do you replace double quotes with a blank space in Java?

Strings are immutable, so you need to say

sInputString = sInputString("\"","");

not just the right side of the =

When to encode space to plus (+) or %20?

http://www.example.com/some/path/to/resource?param1=value1

The part before the question mark must use % encoding (so %20 for space), after the question mark you can use either %20 or + for a space. If you need an actual + after the question mark use %2B.

How can I autoformat/indent C code in vim?

Try the following keystrokes:

gg=G

Explanation: gg goes to the top of the file, = is a command to fix the indentation and G tells it to perform the operation to the end of the file.

CSS Font Border?

Sorry I'm late, but speaking about text-shadow, I thought you would also like this example (I use it quite often when I need good shadows on text):

text-shadow:
    -2px   -2px lightblue,
    -2px -1.5px lightblue,
    -2px   -1px lightblue,
    -2px -0.5px lightblue,
    -2px    0px lightblue,
    -2px  0.5px lightblue,
    -2px    1px lightblue,
    -2px  1.5px lightblue,
    -2px    2px lightblue,
    -1.5px  2px lightblue,
    -1px    2px lightblue,
    -0.5px  2px lightblue,
    0px     2px lightblue,
    0.5px   2px lightblue,
    1px     2px lightblue,
    1.5px   2px lightblue,
    2px     2px lightblue,
    2px   1.5px lightblue,
    2px     1px lightblue,
    2px   0.5px lightblue,
    2px     0px lightblue,
    2px  -0.5px lightblue,
    2px    -1px lightblue,
    2px  -1.5px lightblue,
    2px    -2px lightblue,
    1.5px  -2px lightblue,
    1px    -2px lightblue,
    0.5px  -2px lightblue,
    0px    -2px lightblue,
    -0.5px -2px lightblue,
    -1px   -2px lightblue,
    -1.5px -2px lightblue;

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

In Apache Derby DB, refrain from using table names as "user" or so because they are reserved keywords on Apache Derby but will work fine on MySql.

In the Query, you must specify the name of the Entity class that you want to fetch the data from in the FROM clause of the Query.

List<User> users=session.createQuery("from User").list();

Here, User is the name of my Java Entity class(Consider the casing of the name as in Java it matters.)

Output Django queryset as JSON

It didn't work, because QuerySets are not JSON serializable.

1) In case of json.dumps you have to explicitely convert your QuerySet to JSON serializable objects:

class Model(model.Model):
    def as_dict(self):
        return {
            "id": self.id,
            # other stuff
        }

And the serialization:

dictionaries = [ obj.as_dict() for obj in self.get_queryset() ]
return HttpResponse(json.dumps({"data": dictionaries}), content_type='application/json')

2) In case of serializers. Serializers accept either JSON serializable object or QuerySet, but a dictionary containing a QuerySet is neither. Try this:

serializers.serialize("json", self.get_queryset())

Read more about it here:

https://docs.djangoproject.com/en/dev/topics/serialization/

Gradle store on local file system

Gradle caches artifacts in USER_HOME/.gradle folder. The compiled scripts are usually in the .gradle folder in your project folder.

If you can't find the cache, maybe it's because you have not cached any artifacts yet. You can always see where Gradle has cached artifacts with a simple script:

apply plugin: 'java'

repositories{
  mavenCentral()
}

dependencies{
  compile 'com.google.guava:guava:12.0'
}

task showMeCache << {
  configurations.compile.each { println it }
}

Now if you run gradle showMeCache it should download the deps into cache and print the full path.

Class has been compiled by a more recent version of the Java Environment

IDE: Eclipse Oxygen.3

To temporarily correct the problem do the following:

Project menu > Properties > Java Compiler > Compiler compliance level > 1.8

A permanent fix likely involves installing JDK 9.

FYI 1.8 is what Java 8 is called.

Side bar

I recently returned to Java after a foray into C# (a breath of fresh air) and installed Eclipse Oxygen onto a clean system that had never had Java installed on it before. This default everything with a brand new install of Eclipse Oxygen yet somehow or other Eclipse can't get its own parameters to match the jdk that's installed. This is the second project I created and the second time I ran into this headache. Time to go back to C#?

Related Question

has been compiled by a more recent version of the Java Runtime (class file version 53.0)

Unix epoch time to Java Date object

java.time

Using the java.time framework built into Java 8 and later.

import java.time.LocalDateTime;
import java.time.Instant;
import java.time.ZoneId;

long epoch = Long.parseLong("1081157732");
Instant instant = Instant.ofEpochSecond(epoch);
ZonedDateTime.ofInstant(instant, ZoneOffset.UTC); # ZonedDateTime = 2004-04-05T09:35:32Z[UTC]

In this case you should better use ZonedDateTime to mark it as date in UTC time zone because Epoch is defined in UTC in Unix time used by Java.

ZoneOffset contains a handy constant for the UTC time zone, as seen in last line above. Its superclass, ZoneId can be used to adjust into other time zones.

ZoneId zoneId = ZoneId.of( "America/Montreal" );

using favicon with css

If (1) you need a favicon that is different for some parts of the domain, or (2) you want this to work with IE 8 or older (haven't tested any newer version), then you have to edit the html to specify the favicon

Select single item from a list

There are two easy ways, depending on if you want to deal with exceptions or get a default value.

You can use the First<T>() or the FirstOrDefault<T>() extension method to get the first result or default(T).

var list = new List<int> { 1, 2, 4 };
var result = list.Where(i => i == 3).First(); // throws InvalidOperationException
var result = list.Where(i => i == 3).FirstOrDefault(); // = 0

How to get cookie expiration date / creation date from javascript?

It's impossible. document.cookie contains information in string like this:

key1=value1;key2=value2;...

So there isn't any information about dates.

You can store these dates in separate cookie variable:

auth_user=Riateche;auth_expire=01/01/2012

But user can change this variable.

run a python script in terminal without the python command

Add the following line to the beginning script1.py

#!/usr/bin/env python

and then make the script executable:

$ chmod +x script1.py

If the script resides in a directory that appears in your PATH variable, you can simply type

$ script1.py

Otherwise, you'll need to provide the full path (either absolute or relative). This includes the current working directory, which should not be in your PATH.

$ ./script1.py

Getting the parent div of element

This might help you.

ParentID = pDoc.offsetParent;
alert(ParentID.id); 

Failed to create provisioning profile

What saved me from this error was when I changed my Bundle Identifier.

Try and do that

How is CountDownLatch used in Java Multithreading?

Yes, you understood correctly. CountDownLatch works in latch principle, the main thread will wait until the gate is open. One thread waits for n threads, specified while creating the CountDownLatch.

Any thread, usually the main thread of the application, which calls CountDownLatch.await() will wait until count reaches zero or it's interrupted by another thread. All other threads are required to count down by calling CountDownLatch.countDown() once they are completed or ready.

As soon as count reaches zero, the waiting thread continues. One of the disadvantages/advantages of CountDownLatch is that it's not reusable: once count reaches zero you cannot use CountDownLatch any more.

Edit:

Use CountDownLatch when one thread (like the main thread) requires to wait for one or more threads to complete, before it can continue processing.

A classical example of using CountDownLatch in Java is a server side core Java application which uses services architecture, where multiple services are provided by multiple threads and the application cannot start processing until all services have started successfully.

P.S. OP's question has a pretty straightforward example so I didn't include one.

How to specify line breaks in a multi-line flexbox layout?

For future questions, It's also possible to do it by using float property and clearing it in each 3 elements.

Here's an example I've made.

_x000D_
_x000D_
.grid {_x000D_
  display: inline-block;_x000D_
}_x000D_
_x000D_
.cell {_x000D_
  display: inline-block;_x000D_
  position: relative;_x000D_
  float: left;_x000D_
  margin: 8px;_x000D_
  width: 48px;_x000D_
  height: 48px;_x000D_
  background-color: #bdbdbd;_x000D_
  font-family: 'Helvetica', 'Arial', sans-serif;_x000D_
  font-size: 14px;_x000D_
  font-weight: 400;_x000D_
  line-height: 20px;_x000D_
  text-indent: 4px;_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
.cell:nth-child(3n) + .cell {_x000D_
  clear: both;_x000D_
}
_x000D_
<div class="grid">_x000D_
  <div class="cell">1</div>_x000D_
  <div class="cell">2</div>_x000D_
  <div class="cell">3</div>_x000D_
  <div class="cell">4</div>_x000D_
  <div class="cell">5</div>_x000D_
  <div class="cell">6</div>_x000D_
  <div class="cell">7</div>_x000D_
  <div class="cell">8</div>_x000D_
  <div class="cell">9</div>_x000D_
  <div class="cell">10</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

ES6 Class Multiple inheritance

I spent half a week trying to figure this out myself, and wrote a whole article on it, https://github.com/latitov/OOP_MI_Ct_oPlus_in_JS, and hope it helps some of you.

In short, here's how MI can be implemented in JavaScript:

    class Car {
        constructor(brand) {
            this.carname = brand;
        }
        show() {
            return 'I have a ' + this.carname;
        }
    }

    class Asset {
        constructor(price) {
            this.price = price;
        }
        show() {
            return 'its estimated price is ' + this.price;
        }
    }

    class Model_i1 {        // extends Car and Asset (just a comment for ourselves)
        //
        constructor(brand, price, usefulness) {
            specialize_with(this, new Car(brand));
            specialize_with(this, new Asset(price));
            this.usefulness = usefulness;
        }
        show() {
            return Car.prototype.show.call(this) + ", " + Asset.prototype.show.call(this) + ", Model_i1";
        }
    }

    mycar = new Model_i1("Ford Mustang", "$100K", 16);
    document.getElementById("demo").innerHTML = mycar.show();

And here's specialize_with() one-liner:

function specialize_with(o, S) { for (var prop in S) { o[prop] = S[prop]; } }

Again, please look at https://github.com/latitov/OOP_MI_Ct_oPlus_in_JS.

SQL to find the number of distinct values in a column

Count(distinct({fieldname})) is redundant

Simply Count({fieldname}) gives you all the distinct values in that table. It will not (as many presume) just give you the Count of the table [i.e. NOT the same as Count(*) from table]

What is the maximum number of edges in a directed graph with n nodes?

The correct answer is n*(n-1)/2. Each edge has been counted twice, hence the division by 2. A complete graph has the maximum number of edges, which is given by n choose 2 = n*(n-1)/2.

"Correct" way to specifiy optional arguments in R functions

You could also use missing() to test whether or not the argument y was supplied:

fooBar <- function(x,y){
    if(missing(y)) {
        x
    } else {
        x + y
    }
}

fooBar(3,1.5)
# [1] 4.5
fooBar(3)
# [1] 3

Virtual/pure virtual explained

"Virtual" means that the method may be overridden in subclasses, but has an directly-callable implementation in the base class. "Pure virtual" means it is a virtual method with no directly-callable implementation. Such a method must be overridden at least once in the inheritance hierarchy -- if a class has any unimplemented virtual methods, objects of that class cannot be constructed and compilation will fail.

@quark points out that pure-virtual methods can have an implementation, but as pure-virtual methods must be overridden, the default implementation can't be directly called. Here is an example of a pure-virtual method with a default:

#include <cstdio>

class A {
public:
    virtual void Hello() = 0;
};

void A::Hello() {
    printf("A::Hello\n");
}

class B : public A {
public:
    void Hello() {
        printf("B::Hello\n");
        A::Hello();
    }
};

int main() {
    /* Prints:
           B::Hello
           A::Hello
    */
    B b;
    b.Hello();
    return 0;
}

According to comments, whether or not compilation will fail is compiler-specific. In GCC 4.3.3 at least, it won't compile:

class A {
public:
    virtual void Hello() = 0;
};

int main()
{
    A a;
    return 0;
}

Output:

$ g++ -c virt.cpp 
virt.cpp: In function ‘int main()’:
virt.cpp:8: error: cannot declare variable ‘a’ to be of abstract type ‘A’
virt.cpp:1: note:   because the following virtual functions are pure within ‘A’:
virt.cpp:3: note:   virtual void A::Hello()

What is the better API to Reading Excel sheets in java - JXL or Apache POI

I have used both JXL (now "JExcel") and Apache POI. At first I used JXL, but now I use Apache POI.

First, here are the things where both APIs have the same end functionality:

  • Both are free
  • Cell styling: alignment, backgrounds (colors and patterns), borders (types and colors), font support (font names, colors, size, bold, italic, strikeout, underline)
  • Formulas
  • Hyperlinks
  • Merged cell regions
  • Size of rows and columns
  • Data formatting: Numbers and Dates
  • Text wrapping within cells
  • Freeze Panes
  • Header/Footer support
  • Read/Write existing and new spreadsheets
  • Both attempt to keep existing objects in spreadsheets they read in intact as far as possible.

However, there are many differences:

  • Perhaps the most significant difference is that Java JXL does not support the Excel 2007+ ".xlsx" format; it only supports the old BIFF (binary) ".xls" format. Apache POI supports both with a common design.
  • Additionally, the Java portion of the JXL API was last updated in 2009 (3 years, 4 months ago as I write this), although it looks like there is a C# API. Apache POI is actively maintained.
  • JXL doesn't support Conditional Formatting, Apache POI does, although this is not that significant, because you can conditionally format cells with your own code.
  • JXL doesn't support rich text formatting, i.e. different formatting within a text string; Apache POI does support it.
  • JXL only supports certain text rotations: horizontal/vertical, +/- 45 degrees, and stacked; Apache POI supports any integer number of degrees plus stacked.
  • JXL doesn't support drawing shapes; Apache POI does.
  • JXL supports most Page Setup settings such as Landscape/Portrait, Margins, Paper size, and Zoom. Apache POI supports all of that plus Repeating Rows and Columns.
  • JXL doesn't support Split Panes; Apache POI does.
  • JXL doesn't support Chart creation or manipulation; that support isn't there yet in Apache POI, but an API is slowly starting to form.
  • Apache POI has a more extensive set of documentation and examples available than JXL.

Additionally, POI contains not just the main "usermodel" API, but also an event-based API if all you want to do is read the spreadsheet content.

In conclusion, because of the better documentation, more features, active development, and Excel 2007+ format support, I use Apache POI.

Table header to stay fixed at the top when user scrolls it out of view with jQuery

I was able to fix the problem with changing column widths. I started with Andrew's solution above (thanks so much!) and then added one little loop to set the widths of the cloned td's:

$("#header-fixed td").each(function(index){
    var index2 = index;
    $(this).width(function(index2){
        return $("#table-1 td").eq(index).width();
    });
});

This solves the problem without having to clone the entire table and hide the body. I'm brand new to JavaScript and jQuery (and to stack overflow), so any comments are appreciated.

AngularJS POST Fails: Response for preflight has invalid HTTP status code 404

Ok so here's how I figured this out. It all has to do with CORS policy. Before the POST request, Chrome was doing a preflight OPTIONS request, which should be handled and acknowledged by the server prior to the actual request. Now this is really not what I wanted for such a simple server. Hence, resetting the headers client side prevents the preflight:

app.config(function ($httpProvider) {
  $httpProvider.defaults.headers.common = {};
  $httpProvider.defaults.headers.post = {};
  $httpProvider.defaults.headers.put = {};
  $httpProvider.defaults.headers.patch = {};
});

The browser will now send a POST directly. Hope this helps a lot of folks out there... My real problem was not understanding CORS enough.

Link to a great explanation: http://www.html5rocks.com/en/tutorials/cors/

Kudos to this answer for showing me the way.

How do I convert an Array to a List<object> in C#?

List<object>.AddRange(object[]) should do the trick. It will avoid all sorts of useless memory allocation. You could also use Linq, somewhat like this: object[].Cast<object>().ToList()

How to Query Database Name in Oracle SQL Developer?

To see database name, startup;

then type show parameter db_name;

How to convert an enum type variable to a string?

This is the pre processor block

#ifndef GENERATE_ENUM_STRINGS
    #define DECL_ENUM_ELEMENT( element ) element
    #define BEGIN_ENUM( ENUM_NAME ) typedef enum tag##ENUM_NAME
    #define END_ENUM( ENUM_NAME ) ENUM_NAME; \
            char* GetString##ENUM_NAME(enum tag##ENUM_NAME index);
#else
    #define DECL_ENUM_ELEMENT( element ) #element
    #define BEGIN_ENUM( ENUM_NAME ) char* gs_##ENUM_NAME [] =
    #define END_ENUM( ENUM_NAME ) ; char* GetString##ENUM_NAME(enum \
            tag##ENUM_NAME index){ return gs_##ENUM_NAME [index]; }
#endif

Enum definition

BEGIN_ENUM(Os_type)
{
    DECL_ENUM_ELEMENT(winblows),
    DECL_ENUM_ELEMENT(hackintosh),
} END_ENUM(Os_type)

Call using

GetStringOs_type(winblows);

Taken from here. How cool is that ? :)

Why do we use __init__ in Python classes?

Classes are objects with attributes (state, characteristic) and methods (functions, capacities) that are specific for that object (like the white color and fly powers, respectively, for a duck).

When you create an instance of a class, you can give it some initial personality (state or character like the name and the color of her dress for a newborn). You do this with __init__.

Basically __init__ sets the instance characteristics automatically when you call instance = MyClass(some_individual_traits).

PHP Echo a large block of text

One option is to get out of the php block and just write HTML.

With your code, after the opening curly brace of your if statement, end the PHP:

if (is_single()) { ?>

Then remove the echo ' and the ';

After all your html and css, before the closing }, write:

<? } else {

If the text you want to write to the page is dynamic, it gets a little trickier, but for now this should work fine.

fast way to copy formatting in excel

Just use the NumberFormat property after the Value property: In this example the Ranges are defined using variables called ColLetter and SheetRow and this comes from a for-next loop using the integer i, but they might be ordinary defined ranges of course.

TransferSheet.Range(ColLetter & SheetRow).Value = Range(ColLetter & i).Value TransferSheet.Range(ColLetter & SheetRow).NumberFormat = Range(ColLetter & i).NumberFormat

Download File Using Javascript/jQuery

Excelent solution from Corbacho, I just adapted to get rid o the var

function downloadURL(url) {
    if( $('#idown').length ){
        $('#idown').attr('src',url);
    }else{
        $('<iframe>', { id:'idown', src:url }).hide().appendTo('body');
    }
}

How does one generate a random number in Apple's Swift language?

Use arc4random_uniform(n) for a random integer between 0 and n-1.

let diceRoll = Int(arc4random_uniform(6) + 1)

Cast the result to Int so you don't have to explicitly type your vars as UInt32 (which seems un-Swifty).

C++ undefined reference to defined function

Though previous posters covered your particular error, you can get 'Undefined reference' linker errors when attempting to compile C code with g++, if you don't tell the compiler to use C linkage.

For example you should do this in your C header files:

extern "C" {

...

void myfunc(int param);

...

}

To make 'myfunc' available in C++ programs.

If you still also want to use this from C, wrap the extern "C" { and } in #ifdef __cplusplus preprocessor conditionals, like

#ifdef __cplusplus
extern "C" {
#endif

This way, the extern block will just be “skipped” when using a C compiler.

How can I make an entire HTML form "readonly"?

You can use this function to disable the form:

function disableForm(formID){
  $('#' + formID).children(':input').attr('disabled', 'disabled');
}

See the working demo here

Note that it uses jQuery.

Lightbox to show videos from Youtube and Vimeo?

Check out this list of lightbox plugins, depending on your exact requirements you can find the plugin of your choice from there easier than asking here. If you need a specific lightbox which can do just about anything and everything, try NyroModal.

Where are static variables stored in C and C++?

It depends on the platform and compiler that you're using. Some compilers store directly in the code segment. Static variables are always only accessible to the current translation unit and the names are not exported thus the reason name collisions never occur.

Reading in from System.in - Java

Well, you may read System.in itself as it is a valid InputStream. Or also you can wrap it in a BufferedReader:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

Returning an empty array

I'm pretty sure you should go with bar(); because with foo(); it creates a List (for nothing) since you create a new File[0] in the end anyway, so why not go with directly returning it!

JavaScript is in array

if(array.indexOf("67") != -1) // is in array

Joining two lists together

I just wanted to test how Union works with the default comparer on overlapping collections of reference type objects.

My object is:

class MyInt
{
    public int val;

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

My test code is:

MyInt[] myInts1 = new MyInt[10];
MyInt[] myInts2 = new MyInt[10];
int overlapFrom = 4;
Console.WriteLine("overlapFrom: {0}", overlapFrom);

Action<IEnumerable<MyInt>, string> printMyInts = (myInts, myIntsName) => Console.WriteLine("{2} ({0}): {1}", myInts.Count(), string.Join(" ", myInts), myIntsName);

for (int i = 0; i < myInts1.Length; i++)
    myInts1[i] = new MyInt { val = i };
printMyInts(myInts1, nameof(myInts1));

int j = 0;
for (; j + overlapFrom < myInts1.Length; j++)
    myInts2[j] = myInts1[j + overlapFrom];
for (; j < myInts2.Length; j++)
    myInts2[j] = new MyInt { val = j + overlapFrom };
printMyInts(myInts2, nameof(myInts2));

IEnumerable<MyInt> myUnion = myInts1.Union(myInts2);
printMyInts(myUnion, nameof(myUnion));

for (int i = 0; i < myInts2.Length; i++)
    myInts2[i].val += 10;
printMyInts(myInts2, nameof(myInts2));
printMyInts(myUnion, nameof(myUnion));

for (int i = 0; i < myInts1.Length; i++)
    myInts1[i].val = i;
printMyInts(myInts1, nameof(myInts1));
printMyInts(myUnion, nameof(myUnion));

The output is:

overlapFrom: 4
myInts1 (10): 0 1 2 3 4 5 6 7 8 9
myInts2 (10): 4 5 6 7 8 9 10 11 12 13
myUnion (14): 0 1 2 3 4 5 6 7 8 9 10 11 12 13
myInts2 (10): 14 15 16 17 18 19 20 21 22 23
myUnion (14): 0 1 2 3 14 15 16 17 18 19 20 21 22 23
myInts1 (10): 0 1 2 3 4 5 6 7 8 9
myUnion (14): 0 1 2 3 4 5 6 7 8 9 20 21 22 23

So, everything works fine.

Numpy - Replace a number with NaN

A[A==NDV]=numpy.nan

A==NDV will produce a boolean array that can be used as an index for A

How do you make a LinearLayout scrollable?

Here is how I did it by trial and error.

ScrollView - (the outer wrapper).

    LinearLayout (child-1).

        LinearLayout (child-1a).

        LinearLayout (child-1b).

Since ScrollView can have only one child, that child is a linear layout. Then all the other layout types occur in the first linear layout. I haven't tried to include a relative layout yet, but they drive me nuts so I will wait until my sanity returns.

How to fix the session_register() deprecated issue?

before PHP 5.3

session_register("name");

since PHP 5.3

$_SESSION['name'] = $name;

'cout' was not declared in this scope

Put the following code before int main():

using namespace std;

And you will be able to use cout.

For example:

#include<iostream>
using namespace std;
int main(){
    char t = 'f';
    char *t1;
    char **t2;
    cout<<t;        
    return 0;
}

Now take a moment and read up on what cout is and what is going on here: http://www.cplusplus.com/reference/iostream/cout/


Further, while its quick to do and it works, this is not exactly a good advice to simply add using namespace std; at the top of your code. For detailed correct approach, please read the answers to this related SO question.

Convert to absolute value in Objective-C

Depending on the type of your variable, one of abs(int), labs(long), llabs(long long), imaxabs(intmax_t), fabsf(float), fabs(double), or fabsl(long double).

Those functions are all part of the C standard library, and so are present both in Objective-C and plain C (and are generally available in C++ programs too.)

(Alas, there is no habs(short) function. Or scabs(signed char) for that matter...)


Apple's and GNU's Objective-C headers also include an ABS() macro which is type-agnostic. I don't recommend using ABS() however as it is not guaranteed to be side-effect-safe. For instance, ABS(a++) will have an undefined result.


If you're using C++ or Objective-C++, you can bring in the <cmath> header and use std::abs(), which is templated for all the standard integer and floating-point types.

Initialize class fields in constructor or at declaration?

I think there is one caveat. I once committed such an error: Inside of a derived class, I tried to "initialize at declaration" the fields inherited from an abstract base class. The result was that there existed two sets of fields, one is "base" and another is the newly declared ones, and it cost me quite some time to debug.

The lesson: to initialize inherited fields, you'd do it inside of the constructor.

You are trying to add a non-nullable field 'new_field' to userprofile without a default

If "website" can be empty than new_field should also be set to be empty.

Now if you want to add logic on save where if new_field is empty to grab the value from "website" all you need to do is override the save function for your Model like this:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    website = models.URLField(blank=True, default='DEFAULT VALUE')
    new_field = models.CharField(max_length=140, blank=True, default='DEFAULT VALUE')

    def save(self, *args, **kwargs):
        if not self.new_field:
            # Setting the value of new_field with website's value
            self.new_field = self.website

        # Saving the object with the default save() function
        super(UserProfile, self).save(*args, **kwargs)

Android - java.lang.SecurityException: Permission Denial: starting Intent

if we make the particular activity as

android:exported="true"

it will be the launching activity. Click on the module name just to the left of the run button and click on "Edit configurations..." Now make sure "Launch default Activity" is selected.

How to delete/remove nodes on Firebase

As others have noted the call to .remove() is asynchronous. We should all be aware nothing happens 'instantly', even if it is at the speed of light.

What you mean by 'instantly' is that the next line of code should be able to execute after the call to .remove(). With asynchronous operations the next line may be when the data has been removed, it may not - it is totally down to chance and the amount of time that has elapsed.

.remove() takes one parameter a callback function to help deal with this situation to perform operations after we know that the operation has been completed (with or without an error). .push() takes two params, a value and a callback just like .remove().

Here is your example code with modifications:

ref = new Firebase("myfirebase.com")

ref.push({key:val}, function(error){
  //do stuff after push completed
});

// deletes all data pushed so far
ref.remove(function(error){
  //do stuff after removal
});

How to find char in string and get all the indexes?

All the other answers have two main flaws:

  1. They do a Python loop through the string, which is horrifically slow, or
  2. They use numpy which is a pretty big additional dependency.
def findall(haystack, needle):
    idx = -1
    while True:
        idx = haystack.find(needle, idx+1)
        if idx == -1:
            break
        yield idx

This iterates through haystack looking for needle, always starting at where the previous iteration ended. It uses the builtin str.find which is much faster than iterating through haystack character-by-character. It doesn't require any new imports.

How do I expire a PHP session after 30 minutes?

Store a timestamp in the session


<?php    
$user = $_POST['user_name'];
$pass = $_POST['user_pass'];

require ('db_connection.php');

// Hey, always escape input if necessary!
$result = mysql_query(sprintf("SELECT * FROM accounts WHERE user_Name='%s' AND user_Pass='%s'", mysql_real_escape_string($user), mysql_real_escape_string($pass));

if( mysql_num_rows( $result ) > 0)
{
    $array = mysql_fetch_assoc($result);    

    session_start();
    $_SESSION['user_id'] = $user;
    $_SESSION['login_time'] = time();
    header("Location:loggedin.php");            
}
else
{
    header("Location:login.php");
}
?>

Now, Check if the timestamp is within the allowed time window (1800 seconds is 30 minutes)

<?php
session_start();
if( !isset( $_SESSION['user_id'] ) || time() - $_SESSION['login_time'] > 1800)
{
    header("Location:login.php");
}
else
{
    // uncomment the next line to refresh the session, so it will expire after thirteen minutes of inactivity, and not thirteen minutes after login
    //$_SESSION['login_time'] = time();
    echo ( "this session is ". $_SESSION['user_id'] );
    //show rest of the page and all other content
}
?>

How to get EditText value and display it on screen through TextView?

yesButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View arg0) {
        eiteText=(EditText)findViewById(R.id.nameET);
        String result=eiteText.getText().toString();
        Log.d("TAG",result);
    }
});

How to pass a textbox value from view to a controller in MVC 4?

You can use simple form:

@using(Html.BeginForm("Update", "Shopping"))
{
    <input type="text" id="ss" name="qty" value="@item.Quantity"/>
    ...
    <input type="submit" value="Update" />
}

And add here attribute:

[HttpPost]
public ActionResult Update(string id, string productid, int qty, decimal unitrate)

How to use '-prune' option of 'find' in sh?

Normally the native way we do things in linux and the way we think is from left to right.
So you would go and write what you are looking for first:

find / -name "*.php"

Then you probably hit enter and realize you are getting too many files from directories you wish not to. Let's exclude /media to avoid searching your mounted drives.
You should now just APPEND the following to the previous command:

-print -o -path '/media' -prune

so the final command is:

find / -name "*.php" -print -o -path '/media' -prune

...............|<--- Include --->|....................|<---------- Exclude --------->|

I think this structure is much easier and correlates to the right approach

Switch: Multiple values in one case?

There's no way to evaluate multiple values in one 'case'. You could either use an if statement (as others have suggested) or call a method which evaluates the range that the integer belongs to and returns a value which represents that range (such as "minor", "adult", etc.), then evaluate this returned value in the switch statement. Of course, you'd probably still be using an if statement in the custom method.

Provide password to ssh command inside bash script, Without the usage of public keys and Expect

AFAIK there is no possibility beside from using keys or expect if you are using the command line version ssh. But there are library bindings for the most programming languages like C, python, php, ... . You could write a program in such a language. This way it would be possible to pass the password automatically. But note this is of course a security problem as the password will be stored in plain text in that program

Responsive Bootstrap Jumbotron Background Image

The simplest way is to set the background-size CSS property to cover:

.jumbotron {
  background-image: url("../img/jumbotron_bg.jpg");
  background-size: cover;
}

Hive cast string to date dd-MM-yyyy

This will convert the whole column:

select from_unixtime(unix_timestamp(transaction_date,'yyyyMMdd')) from table1

Gerrit error when Change-Id in commit messages are missing

It is because Gerrit is configured to require Change-Id in the commit messages.

http://gerrit.googlecode.com/svn-history/r6114/documentation/2.1.7/error-missing-changeid.html

You have to change the messages of every commit that you are pushing to include the change id ( using git filter-branch ) and only then push.

Request UAC elevation from within a Python script?

The following example builds on MARTIN DE LA FUENTE SAAVEDRA's excellent work and accepted answer. In particular, two enumerations are introduced. The first allows for easy specification of how an elevated program is to be opened, and the second helps when errors need to be easily identified. Please note that if you want all command line arguments passed to the new process, sys.argv[0] should probably be replaced with a function call: subprocess.list2cmdline(sys.argv).

#! /usr/bin/env python3
import ctypes
import enum
import subprocess
import sys

# Reference:
# msdn.microsoft.com/en-us/library/windows/desktop/bb762153(v=vs.85).aspx


# noinspection SpellCheckingInspection
class SW(enum.IntEnum):
    HIDE = 0
    MAXIMIZE = 3
    MINIMIZE = 6
    RESTORE = 9
    SHOW = 5
    SHOWDEFAULT = 10
    SHOWMAXIMIZED = 3
    SHOWMINIMIZED = 2
    SHOWMINNOACTIVE = 7
    SHOWNA = 8
    SHOWNOACTIVATE = 4
    SHOWNORMAL = 1


class ERROR(enum.IntEnum):
    ZERO = 0
    FILE_NOT_FOUND = 2
    PATH_NOT_FOUND = 3
    BAD_FORMAT = 11
    ACCESS_DENIED = 5
    ASSOC_INCOMPLETE = 27
    DDE_BUSY = 30
    DDE_FAIL = 29
    DDE_TIMEOUT = 28
    DLL_NOT_FOUND = 32
    NO_ASSOC = 31
    OOM = 8
    SHARE = 26


def bootstrap():
    if ctypes.windll.shell32.IsUserAnAdmin():
        main()
    else:
       # noinspection SpellCheckingInspection
        hinstance = ctypes.windll.shell32.ShellExecuteW(
            None,
            'runas',
            sys.executable,
            subprocess.list2cmdline(sys.argv),
            None,
            SW.SHOWNORMAL
        )
        if hinstance <= 32:
            raise RuntimeError(ERROR(hinstance))


def main():
    # Your Code Here
    print(input('Echo: '))


if __name__ == '__main__':
    bootstrap()

Setting cursor at the end of any text of a textbox

You can set the caret position using TextBox.CaretIndex. If the only thing you need is to set the cursor at the end, you can simply pass the string's length, eg:

txtBox.CaretIndex=txtBox.Text.Length;

You need to set the caret index at the length, not length-1, because this would put the caret before the last character.

fastest way to export blobs from table into individual files

For me what worked by combining all the posts I have read is:

1.Enable OLE automation - if not enabled

sp_configure 'show advanced options', 1;  
GO  
RECONFIGURE;  
GO  
sp_configure 'Ole Automation Procedures', 1;  
GO  
RECONFIGURE;  
GO

2.Create a folder where the generated files will be stored:

C:\GREGTESTING

3.Create DocTable that will be used for file generation and store there the blobs in Doc_Content
enter image description here

CREATE TABLE [dbo].[Document](
    [Doc_Num] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
    [Extension] [varchar](50) NULL,
    [FileName] [varchar](200) NULL,
    [Doc_Content] [varbinary](max) NULL   
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] 

INSERT [dbo].[Document] ([Extension] ,[FileName] , [Doc_Content] )
    SELECT 'pdf', 'SHTP Notional hire - January 2019.pdf', 0x....(varbinary blob)

Important note!

Don't forget to add in Doc_Content column the varbinary of file you want to generate!

4.Run the below script

DECLARE @outPutPath varchar(50) = 'C:\GREGTESTING'
, @i bigint
, @init int
, @data varbinary(max) 
, @fPath varchar(max)  
, @folderPath  varchar(max)

--Get Data into temp Table variable so that we can iterate over it 
DECLARE @Doctable TABLE (id int identity(1,1), [Doc_Num]  varchar(100) , [FileName]  varchar(100), [Doc_Content] varBinary(max) )



INSERT INTO @Doctable([Doc_Num] , [FileName],[Doc_Content])
Select [Doc_Num] , [FileName],[Doc_Content] FROM  [dbo].[Document]



SELECT @i = COUNT(1) FROM @Doctable   

WHILE @i >= 1   

BEGIN    

SELECT 
    @data = [Doc_Content],
    @fPath = @outPutPath + '\' + [Doc_Num] +'_' +[FileName],
    @folderPath = @outPutPath + '\'+ [Doc_Num]
FROM @Doctable WHERE id = @i

EXEC sp_OACreate 'ADODB.Stream', @init OUTPUT; -- An instace created
EXEC sp_OASetProperty @init, 'Type', 1;  
EXEC sp_OAMethod @init, 'Open'; -- Calling a method
EXEC sp_OAMethod @init, 'Write', NULL, @data; -- Calling a method
EXEC sp_OAMethod @init, 'SaveToFile', NULL, @fPath, 2; -- Calling a method
EXEC sp_OAMethod @init, 'Close'; -- Calling a method
EXEC sp_OADestroy @init; -- Closed the resources
print 'Document Generated at - '+  @fPath   

--Reset the variables for next use
SELECT @data = NULL  
, @init = NULL
, @fPath = NULL  
, @folderPath = NULL
SET @i -= 1
END   

5.The results is shown below: enter image description here

Is there a Google Voice API?

No, there is no API for Google Voice announced as of 2021.

"pygooglevoice" can perform most of the voice functions from Python. It can send SMS. I've developed code to receive SMS messages, but the overhead is excessive given the current Google Voice interface. Each poll returns over 100K of content, so you'd use a quarter-gigabyte a day just polling every 30 seconds. There's a discussion on Google Code about this.

awk without printing newline

awk '{sum+=$3}; END {printf "%f",sum/NR}' ${file}_${f}_v1.xls >> to-plot-p.xls

print will insert a newline by default. You dont want that to happen, hence use printf instead.

Does the Java &= operator apply & or &&?

It's the last one:

a = a & b;

How do I insert non breaking space character &nbsp; in a JSF page?

Putting the HTML number directly did the trick for me:

&#160;

typescript - cloning object

Here is my mash-up! And here is a StackBlitz link to it. Its currently limited to only copying simple types and object types but could be modified easily I would think.

   let deepClone = <T>(source: T): { [k: string]: any } => {
      let results: { [k: string]: any } = {};
      for (let P in source) {
        if (typeof source[P] === 'object') {
          results[P] = deepClone(source[P]);
        } else {
          results[P] = source[P];
        }
      }
      return results;
    };

Ruby send JSON request

A simple json POST request example for those that need it even simpler than what Tom is linking to:

require 'net/http'

uri = URI.parse("http://www.example.com/search.json")
response = Net::HTTP.post_form(uri, {"search" => "Berlin"})

How to fix: "You need to use a Theme.AppCompat theme (or descendant) with this activity"

u should add a theme to ur all activities (u should add theme for all application in ur <application> in ur manifest) but if u have set different theme to ur activity u can use :

 android:theme="@style/Theme.AppCompat"

or each kind of AppCompat theme!

phpMyAdmin - Error > Incorrect format parameter?

I was able to resolve this by following the steps posted here: xampp phpmyadmin, Incorrect format parameter

Because I'm not using XAMPP, I also needed to update my php.ini.default to php.ini which finally did the trick.

What is a Subclass

It is a class that extends another class.

example taken from https://www.java-tips.org/java-se-tips-100019/24-java-lang/784-what-is-a-java-subclass.html, Cat is a sub class of Animal :-)

public class Animal {

    public static void hide() {
        System.out.println("The hide method in Animal.");
    }

    public void override() {
        System.out.println("The override method in Animal.");
    }
}

public class Cat extends Animal {

    public static void hide() {
        System.out.println("The hide method in Cat.");
    }

    public void override() {
        System.out.println("The override method in Cat.");
    }

    public static void main(String[] args) {
        Cat myCat = new Cat();
        Animal myAnimal = (Animal)myCat;
        myAnimal.hide();
        myAnimal.override();
    }
}

Python-Requests close http connection

As discussed here, there really isn't such a thing as an HTTP connection and what httplib refers to as the HTTPConnection is really the underlying TCP connection which doesn't really know much about your requests at all. Requests abstracts that away and you won't ever see it.

The newest version of Requests does in fact keep the TCP connection alive after your request.. If you do want your TCP connections to close, you can just configure the requests to not use keep-alive.

s = requests.session()
s.config['keep_alive'] = False

Update date + one year in mysql

This post helped me today, but I had to experiment to do what I needed. Here is what I found.

Should you want to add more complex time periods, for example 1 year and 15 days, you can use

UPDATE tablename SET datefieldname = curdate() + INTERVAL 15 DAY + INTERVAL 1 YEAR;

I found that using DATE_ADD doesn't allow for adding more than one interval. And there is no YEAR_DAYS interval keyword, though there are others that combine time periods. If you are adding times, use now() rather than curdate().

Failed to resolve: com.android.support:appcompat-v7:27.+ (Dependency Error)

Find root build.gradle file and add google maven repo inside allprojects tag

repositories {
        mavenLocal()
        mavenCentral()
        maven {                                  // <-- Add this
            url 'https://maven.google.com/' 
            name 'Google'
        }
    } 

It's better to use specific version instead of variable version

compile 'com.android.support:appcompat-v7:27.0.0'

If you're using Android Plugin for Gradle 3.0.0 or latter version

repositories {
      mavenLocal()
      mavenCentral()
      google()        //---> Add this
} 

and inject dependency in this way :

implementation 'com.android.support:appcompat-v7:27.0.0'

How to check if a variable is not null?

Have a read at this post: http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-2/

It has some nice tips for JavaScript in general but one thing it does mention is that you should check for null like:

if(myvar) { }

It also mentions what's considered 'falsey' that you might not realise.

How can I create a blank/hardcoded column in a sql query?

SELECT
    hat,
    shoe,
    boat,
    0 as placeholder -- for column having 0 value    
FROM
    objects


--OR '' as Placeholder -- for blank column    
--OR NULL as Placeholder -- for column having null value

Beginner question: returning a boolean value from a function in Python

Ignoring the refactoring issues, you need to understand functions and return values. You don't need a global at all. Ever. You can do this:

def rps():
    # Code to determine if player wins
    if player_wins:
        return True

    return False

Then, just assign a value to the variable outside this function like so:

player_wins = rps()

It will be assigned the return value (either True or False) of the function you just called.


After the comments, I decided to add that idiomatically, this would be better expressed thus:

 def rps(): 
     # Code to determine if player wins, assigning a boolean value (True or False)
     # to the variable player_wins.

     return player_wins

 pw = rps()

This assigns the boolean value of player_wins (inside the function) to the pw variable outside the function.

How to read GET data from a URL using JavaScript?

try this way

var url_string = window.location;
var url = new URL(url_string);
var name = url.searchParams.get("name");
var tvid = url.searchParams.get("id");

How to save MySQL query output to excel or .txt file?

You can write following codes to achieve this task:

SELECT ... FROM ... WHERE ... 
INTO OUTFILE 'textfile.csv'
FIELDS TERMINATED BY '|'

It export the result to CSV and then export it to excel sheet.

scp (secure copy) to ec2 instance without password

My hadoopec2cluster.pem file was the only one in the directory on my local mac, couldn't scp it to aws using scp -i hadoopec2cluster.pem hadoopec2cluster.pem ubuntu@serverip:~.

Copied hadoopec2cluster.pem to hadoopec2cluster_2.pem and then scp -i hadoopec2cluster.pem hadoopec2cluster_2.pem ubuntu@serverip:~. Voila!

error running apache after xampp install

I got the same error when xampp was installed on windows 10.

www.example.com:443:0 server certificate does NOT include an ID which matches the server name

So I opened httpd-ssl.conf file in xampp folder and changed the following line

ServerName www.example.com:443

To

ServerName localhost

And the problem was fixed.

Run PHP function on html button click

<?php
if (isset($_POST['str'])){
function printme($str){
echo $str;
}

printme("{$_POST['str']}");
}
?>
<form action="<?php $_PHP_SELF ?>" method="POST">
<input type="text" name="str" /> <input type="submit" value="Submit"/>
</form>

Show/hide forms using buttons and JavaScript

Would you want the same form with different parts, showing each part accordingly with a button?

Here an example with three steps, that is, three form parts, but it is expandable to any number of form parts. The HTML characters &laquo; and &raquo; just print respectively « and » which might be interesting for the previous and next button characters.

_x000D_
_x000D_
shows_form_part(1)_x000D_
_x000D_
/* this function shows form part [n] and hides the remaining form parts */_x000D_
function shows_form_part(n){_x000D_
  var i = 1, p = document.getElementById("form_part"+1);_x000D_
  while (p !== null){_x000D_
    if (i === n){_x000D_
      p.style.display = "";_x000D_
    }_x000D_
    else{_x000D_
      p.style.display = "none";_x000D_
    }_x000D_
    i++;_x000D_
    p = document.getElementById("form_part"+i);_x000D_
  }_x000D_
}_x000D_
_x000D_
/* this is called at the last step using info filled during the previous steps*/_x000D_
function calc_sum() {_x000D_
  var sum =_x000D_
    parseInt(document.getElementById("num1").value) +_x000D_
    parseInt(document.getElementById("num2").value) +_x000D_
    parseInt(document.getElementById("num3").value);_x000D_
_x000D_
  alert("The sum is: " + sum);_x000D_
}
_x000D_
<div id="form_part1">_x000D_
  Part 1<br>_x000D_
  <input type="number" value="1" id="num1"><br>_x000D_
  <button type="button" onclick="shows_form_part(2)">&raquo;</button>_x000D_
</div>_x000D_
_x000D_
<div id="form_part2">_x000D_
  Part 2<br>_x000D_
  <input type="number" value="2" id="num2"><br>_x000D_
  <button type="button" onclick="shows_form_part(1)">&laquo;</button>_x000D_
  <button type="button" onclick="shows_form_part(3)">&raquo;</button>_x000D_
</div>_x000D_
_x000D_
<div id="form_part3">_x000D_
  Part 3<br>_x000D_
  <input type="number" value="3" id="num3"><br>_x000D_
  <button type="button" onclick="shows_form_part(2)">&laquo;</button>_x000D_
  <button type="button" onclick="calc_sum()">Sum</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Android ADB devices unauthorized

  1. First Remove the adbkey and adbkey.pub from the .android directory in your Home directory.
  2. Make .android directory in your home with 710 permissions: $ chmod 710 .android/ and ownership as: chown -R <user>:<user> .android/. Ex:

    $ chmod 710 .android/
    $ chown -R ashan:ashan .android/
    
  3. Go to developer options in your mobile and tap option Revoke USB debugging authorizations

  4. Turn off all USB Debugging and Developer Options in the device and disconnect the device from your machine.

  5. Connect the device again and at first turn on the Developer Options. Then Turn on the USB debugging.

  6. At this point in your mobile, you will get a prompt for asking permission from you. Note: you must check the checkbox always accept from this …. option and click ok.

  7. Now in you machine, start the adb server: adb start-server.

  8. Hopefully when you issue the command: adb devices now, you will see your device ready authorized.

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

_x000D_
_x000D_
$('#surat_lampiran').bind('change', function() {_x000D_
  alerr = "";_x000D_
  sts = false;_x000D_
  alert(this.files[0].type);_x000D_
  if(this.files[0].type != "application/pdf" && this.files[0].type != "application/msword" && this.files[0].type != "application/vnd.openxmlformats-officedocument.wordprocessingml.document"){_x000D_
  sts = true;_x000D_
  alerr += "Jenis file bukan .pdf/.doc/.docx ";_x000D_
}_x000D_
});
_x000D_
_x000D_
_x000D_

Displaying a vector of strings in C++

You ask two questions; your title says "Displaying a vector of strings", but you're not actually doing that, you actually build a single string composed of all the strings and output that.

Your question body asks "Why doesn't this work".

It doesn't work because your for loop is constrained by "userString.size()" which is 0, and you test your loop variable for being "userString.size() - 1". The condition of a for() loop is tested before permitting execution of the first iteration.

int n = 1;
for (int i = 1; i < n; ++i) {
    std::cout << i << endl;
}

will print exactly nothing.

So your loop executes exactly no iterations, leaving userString and sentence empty.

Lastly, your code has absolutely zero reason to use a vector. The fact that you used "decltype(userString.size())" instead of "size_t" or "auto", while claiming to be a rookie, suggests you're either reading a book from back to front or you are setting yourself up to fail a class.

So to answer your question at the end of your post: It doesn't work because you didn't step through it with a debugger and inspect the values as it went. While I say it tongue-in-cheek, I'm going to leave it out there.

location.host vs location.hostname and cross-browser compatibility?

MDN: https://developer.mozilla.org/en/DOM/window.location

It seems that you will get the same result for both, but hostname contains clear host name without brackets or port number.

Python - Dimension of Data Frame

Summary of all ways to get info on dimensions of DataFrame or Series

There are a number of ways to get information on the attributes of your DataFrame or Series.

Create Sample DataFrame and Series

df = pd.DataFrame({'a':[5, 2, np.nan], 'b':[ 9, 2, 4]})
df

     a  b
0  5.0  9
1  2.0  2
2  NaN  4

s = df['a']
s

0    5.0
1    2.0
2    NaN
Name: a, dtype: float64

shape Attribute

The shape attribute returns a two-item tuple of the number of rows and the number of columns in the DataFrame. For a Series, it returns a one-item tuple.

df.shape
(3, 2)

s.shape
(3,)

len function

To get the number of rows of a DataFrame or get the length of a Series, use the len function. An integer will be returned.

len(df)
3

len(s)
3

size attribute

To get the total number of elements in the DataFrame or Series, use the size attribute. For DataFrames, this is the product of the number of rows and the number of columns. For a Series, this will be equivalent to the len function:

df.size
6

s.size
3

ndim attribute

The ndim attribute returns the number of dimensions of your DataFrame or Series. It will always be 2 for DataFrames and 1 for Series:

df.ndim
2

s.ndim
1

The tricky count method

The count method can be used to return the number of non-missing values for each column/row of the DataFrame. This can be very confusing, because most people normally think of count as just the length of each row, which it is not. When called on a DataFrame, a Series is returned with the column names in the index and the number of non-missing values as the values.

df.count() # by default, get the count of each column

a    2
b    3
dtype: int64


df.count(axis='columns') # change direction to get count of each row

0    2
1    2
2    1
dtype: int64

For a Series, there is only one axis for computation and so it just returns a scalar:

s.count()
2

Use the info method for retrieving metadata

The info method returns the number of non-missing values and data types of each column

df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
a    2 non-null float64
b    3 non-null int64
dtypes: float64(1), int64(1)
memory usage: 128.0 bytes

How to create an infinite loop in Windows batch file?

read help GOTO

and try

:again
do it
goto again

WooCommerce return product object by id

global $woocommerce;
var_dump($woocommerce->customer->get_country());
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
    $product = new WC_product($cart_item['product_id']);
    var_dump($product);
}

What is the volatile keyword useful for?

There are two different uses of volatile keyword.

  1. Prevents JVM from reading values from register (assume as cache), and forces its value to be read from memory.
  2. Reduces the risk of memory in-consistency errors.

Prevents JVM from reading values in register, and forces its value to be read from memory.

A busy flag is used to prevent a thread from continuing while the device is busy and the flag is not protected by a lock:

while (busy) {
    /* do something else */
}

The testing thread will continue when another thread turns off the busy flag:

busy = 0;

However, since busy is accessed frequently in the testing thread, the JVM may optimize the test by placing the value of busy in a register, then test the contents of the register without reading the value of busy in memory before every test. The testing thread would never see busy change and the other thread would only change the value of busy in memory, resulting in deadlock. Declaring the busy flag as volatile forces its value to be read before each test.

Reduces the risk of memory consistency errors.

Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a "happens-before" relationship with subsequent reads of that same variable. This means that changes to a volatile variable are always visible to other threads.

The technique of reading, writing without memory consistency errors is called atomic action.

An atomic action is one that effectively happens all at once. An atomic action cannot stop in the middle: it either happens completely, or it doesn't happen at all. No side effects of an atomic action are visible until the action is complete.

Below are actions you can specify that are atomic:

  • Reads and writes are atomic for reference variables and for most primitive variables (all types except long and double).
  • Reads and writes are atomic for all variables declared volatile (including long and double variables).

Cheers!

CSV in Python adding an extra carriage return, on Windows

You can introduce the lineterminator='\n' parameter in the csv writer command.

import csv
delimiter='\t'
with open('tmp.csv', '+w', encoding='utf-8') as stream:
    writer = csv.writer(stream, delimiter=delimiter, quoting=csv.QUOTE_NONE, quotechar='',  lineterminator='\n')
    writer.writerow(['A1' , 'B1', 'C1'])
    writer.writerow(['A2' , 'B2', 'C2'])
    writer.writerow(['A3' , 'B3', 'C3'])

Firestore Getting documents id from collection

For angular 8 and Firebase 6 you can use the option id field

      getAllDocs() {
           const ref = this.db.collection('items');
           return ref.valueChanges({idField: 'customIdName'});
      }

this adds the Id of the document on the object with a specified key (customIdName)

Capturing console output from a .NET application (C#)

ConsoleAppLauncher is an open source library made specifically to answer that question. It captures all the output generated in the console and provides simple interface to start and close console application.

The ConsoleOutput event is fired every time when a new line is written by the console to standard/error output. The lines are queued and guaranteed to follow the output order.

Also available as NuGet package.

Sample call to get full console output:

// Run simplest shell command and return its output.
public static string GetWindowsVersion()
{
    return ConsoleApp.Run("cmd", "/c ver").Output.Trim();
}

Sample with live feedback:

// Run ping.exe asynchronously and return roundtrip times back to the caller in a callback
public static void PingUrl(string url, Action<string> replyHandler)
{
    var regex = new Regex("(time=|Average = )(?<time>.*?ms)", RegexOptions.Compiled);
    var app = new ConsoleApp("ping", url);
    app.ConsoleOutput += (o, args) =>
    {
        var match = regex.Match(args.Line);
        if (match.Success)
        {
            var roundtripTime = match.Groups["time"].Value;
            replyHandler(roundtripTime);
        }
    };
    app.Run();
}

new DateTime() vs default(DateTime)

The answer is no. Keep in mind that in both cases, mdDate.Kind = DateTimeKind.Unspecified.

Therefore it may be better to do the following:

DateTime myDate = new DateTime(1, 1, 1, 0, 0, 0, DateTimeKind.Utc);

The myDate.Kind property is readonly, so it cannot be changed after the constructor is called.

How to pass password automatically for rsync SSH command?

Use a ssh key.

Look at ssh-keygen and ssh-copy-id.

After that you can use an rsync this way :

rsync -a --stats --progress --delete /home/path server:path

JQuery Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

I stumbled over the same and wanted to share my solution:

<script type="text/javascript">
    $( "#dialog-confirm" ).dialog("option","buttons",
                {
                    "delete": function() {
                        $.ajax({
                            url: "delete.php"
                        }).done(function(msg) {
                         //here "this" is the ajax object                                       
                            $(this).dialog( "close" );
                        });

                    },
                    "cancel": function() {
                        //here, "this" is correctly the dialog object
                        $(this).dialog( "close" );
                    }
                });
</script>

because "this" is referencing to an non-dialog object, I got the error mentioned.

Solution:

<script type="text/javascript">
    var theDialog = $( "#dialog-confirm" ).dialog("option","buttons",
                {
                    "delete": function() {
                        $.ajax({
                            url: "delete.php"
                        }).done(function(msg) {
                            $(theDialog).dialog( "close" );
                        });

                    },
                    "cancel": function() {
                        $(this).dialog( "close" );
                    }
                });
</script>

How do I remove all HTML tags from a string without knowing which tags are in it?

You can use the below code on your string and you will get the complete string without html part.

string title = "<b> Hulk Hogan's Celebrity Championship Wrestling &nbsp;&nbsp;&nbsp;<font color=\"#228b22\">[Proj # 206010]</font></b>&nbsp;&nbsp;&nbsp; (Reality Series, &nbsp;)".Replace("&nbsp;",string.Empty);            
        string s = Regex.Replace(title, "<.*?>", String.Empty);

Sort Pandas Dataframe by Date

The data containing the date column can be read by using the below code:

data = pd.csv(file_path,parse_dates=[date_column])

Once the data is read by using the above line of code, the column containing the information about the date can be accessed using pd.date_time() like:

pd.date_time(data[date_column], format = '%d/%m/%y')

to change the format of date as per the requirement.

Removing App ID from Developer Connection

  • As of Apr 2013, it is possible to delete App IDs.
  • As of Sep 2013, it is impossible to delete App IDs again after the big outage. I hope Apple will put it back.
  • As of mid 2014, it is possible to delete App IDs again. However, you can't delete id of apps existing in the App Store.

PHP Fatal error: Uncaught exception 'Exception'

This is expected behavior for an uncaught exception with display_errors off.

Your options here are to turn on display_errors via php or in the ini file or catch and output the exception.

 ini_set("display_errors", 1);

or

 try{
     // code that may throw an exception
 } catch(Exception $e){
     echo $e->getMessage();
 }

If you are throwing exceptions, the intention is that somewhere further down the line something will catch and deal with it. If not it is a server error (500).

Another option for you would be to use set_exception_handler to set a default error handler for your script.

 function default_exception_handler(Exception $e){
          // show something to the user letting them know we fell down
          echo "<h2>Something Bad Happened</h2>";
          echo "<p>We fill find the person responsible and have them shot</p>";
          // do some logging for the exception and call the kill_programmer function.
 }
 set_exception_handler("default_exception_handler");

How to get value by class name in JavaScript or jquery?

Try this:

$(document).ready(function(){
    var yourArray = [];
    $("span.HOEnZb").find("div").each(function(){
        if(($.trim($(this).text()).length>0)){
         yourArray.push($(this).text());
        }
    });
});

DEMO

Should MySQL have its timezone set to UTC?

This is a working example:

jdbc:mysql://localhost:3306/database?useUnicode=yes&characterEncoding=UTF-8&serverTimezone=Europe/Moscow

How to disable "prevent this page from creating additional dialogs"?

I know everybody is ethically against this, but I understand there are reasons of practical joking where this is desired. I think Chrome took a solid stance on this by enforcing a mandatory one second separation time between alert messages. This gives the visitor just enough time to close the page or refresh if they're stuck on an annoying prank site.

So to answer your question, it's all a matter of timing. If you alert more than once per second, Chrome will create that checkbox. Here's a simple example of a workaround:

var countdown = 99;
function annoy(){
    if(countdown>0){
        alert(countdown+" bottles of beer on the wall, "+countdown+" bottles of beer! Take one down, pass it around, "+(countdown-1)+" bottles of beer on the wall!");
        countdown--;

        // Time must always be 1000 milliseconds, 999 or less causes the checkbox to appear
        setTimeout(function(){
            annoy();
        }, 1000);
    }
}

// Don't alert right away or Chrome will catch you
setTimeout(function(){
    annoy();
}, 1000);

Disable Transaction Log

What's your problem with Tx logs? They grow? Then just set truncate on checkpoint option.

From Microsoft documentation:

In SQL Server 2000 or in SQL Server 2005, the "Simple" recovery model is equivalent to "truncate log on checkpoint" in earlier versions of SQL Server. If the transaction log is truncated every time a checkpoint is performed on the server, this prevents you from using the log for database recovery. You can only use full database backups to restore your data. Backups of the transaction log are disabled when the "Simple" recovery model is used.

The difference in months between dates in MySQL

This depends on how you want the # of months to be defined. Answer this questions: 'What is difference in months: Feb 15, 2008 - Mar 12, 2009'. Is it defined by clear cut # of days which depends on leap years- what month it is, or same day of previous month = 1 month.

A calculation for Days:

Feb 15 -> 29 (leap year) = 14 Mar 1, 2008 + 365 = Mar 1, 2009. Mar 1 -> Mar 12 = 12 days. 14 + 365 + 12 = 391 days. Total = 391 days / (avg days in month = 30) = 13.03333

A calculation of months:

Feb 15 2008 - Feb 15 2009 = 12 Feb 15 -> Mar 12 = less than 1 month Total = 12 months, or 13 if feb 15 - mar 12 is considered 'the past month'

Android: set view style programmatically

For a new Button/TextView:

Button mMyButton = new Button(new ContextThemeWrapper(this, R.style.button_disabled), null, 0);

For an existing instance:

mMyButton.setTextAppearance(this, R.style.button_enabled);

For Image or layouts:

Image mMyImage = new ImageView(new ContextThemeWrapper(context, R.style.article_image), null, 0);

How to add 20 minutes to a current date?

you have a lot of answers in the post

var d1 = new Date (),
d2 = new Date ( d1 );
d2.setMinutes ( d1.getMinutes() + 20 );
alert ( d2 );

Taking the record with the max date

The analytic function approach would look something like

SELECT a, some_date_column
  FROM (SELECT a,
               some_date_column,
               rank() over (partition by a order by some_date_column desc) rnk
          FROM tablename)
 WHERE rnk = 1

Note that depending on how you want to handle ties (or whether ties are possible in your data model), you may want to use either the ROW_NUMBER or the DENSE_RANK analytic function rather than RANK.

History or log of commands executed in Git

If you use Windows PowerShell, you could type "git" and the press F8. Continue to press F8 to cycle through all your git commands.

Or, if you use cygwin, you could do the same thing with ^R.

Markdown and image alignment

I have an alternative to the methods above that used the ALT tag and a CSS selector on the alt tag... Instead, add a URL hash like this:

First your Markdown image code:

![my image](/img/myImage.jpg#left)
![my image](/img/myImage.jpg#right)
![my image](/img/myImage.jpg#center)

Note the added URL hash #center.

Now add this rule in CSS using CSS 3 attribute selectors to select images with a certain path.

img[src*='#left'] {
    float: left;
}
img[src*='#right'] {
    float: right;
}
img[src*='#center'] {
    display: block;
    margin: auto;
}

You should be able to use a URL hash like this almost like defining a class name and it isn't a misuse of the ALT tag like some people had commented about for that solution. It also won't require any additional extensions. Do one for float right and left as well or any other styles you might want.

python global name 'self' is not defined

self is the self-reference in a Class. Your code is not in a class, you only have functions defined. You have to wrap your methods in a class, like below. To use the method main(), you first have to instantiate an object of your class and call the function on the object.

Further, your function setavalue should be in __init___, the method called when instantiating an object. The next step you probably should look at is supplying the name as an argument to init, so you can create arbitrarily named objects of the Name class ;)

class Name:
    def __init__(self):
        self.myname = "harry"

    def printaname(self):
        print "Name", self.myname     

    def main(self):
        self.printaname()

if __name__ == "__main__":
    objName = Name()
    objName.main() 

Have a look at the Classes chapter of the Python tutorial an at Dive into Python for further references.