Programs & Examples On #Abstract class

Abstract classes are classes which cannot be instantiated. They exist to provide common functionality and interface specifications to several concrete classes.

Can an abstract class have a constructor?

You would define a constructor in an abstract class if you are in one of these situations:

  • you want to perform some initialization (to fields of the abstract class) before the instantiation of a subclass actually takes place
  • you have defined final fields in the abstract class but you did not initialize them in the declaration itself; in this case, you MUST have a constructor to initialize these fields

Note that:

  • you may define more than one constructor (with different arguments)
  • you can (should?) define all your constructors protected (making them public is pointless anyway)
  • your subclass constructor(s) can call one constructor of the abstract class; it may even have to call it (if there is no no-arg constructor in the abstract class)

In any case, don't forget that if you don't define a constructor, then the compiler will automatically generate one for you (this one is public, has no argument, and does nothing).

Spring can you autowire inside an abstract class?

I have that kind of spring setup working

an abstract class with an autowired field

public abstract class AbstractJobRoute extends RouteBuilder {

    @Autowired
    private GlobalSettingsService settingsService;

and several children defined with @Component annotation.

Using Mockito to test abstract classes

Try using a custom answer.

For example:

import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

public class CustomAnswer implements Answer<Object> {

    public Object answer(InvocationOnMock invocation) throws Throwable {

        Answer<Object> answer = null;

        if (isAbstract(invocation.getMethod().getModifiers())) {

            answer = Mockito.RETURNS_DEFAULTS;

        } else {

            answer = Mockito.CALLS_REAL_METHODS;
        }

        return answer.answer(invocation);
    }
}

It will return the mock for abstract methods and will call the real method for concrete methods.

How do you handle a "cannot instantiate abstract class" error in C++?

If anyone is getting this error from a function, try using a reference to the abstract class in the parameters instead.

void something(Abstract bruh){
}

to

void something(Abstract& bruh){
}

Is it possible to make abstract classes in Python?

As explained in the other answers, yes you can use abstract classes in Python using the abc module. Below I give an actual example using abstract @classmethod, @property and @abstractmethod (using Python 3.6+). For me it is usually easier to start off with examples I can easily copy&paste; I hope this answer is also useful for others.

Let's first create a base class called Base:

from abc import ABC, abstractmethod

class Base(ABC):

    @classmethod
    @abstractmethod
    def from_dict(cls, d):
        pass
    
    @property
    @abstractmethod
    def prop1(self):
        pass

    @property
    @abstractmethod
    def prop2(self):
        pass

    @prop2.setter
    @abstractmethod
    def prop2(self, val):
        pass

    @abstractmethod
    def do_stuff(self):
        pass

Our Base class will always have a from_dict classmethod, a property prop1 (which is read-only) and a property prop2 (which can also be set) as well as a function called do_stuff. Whatever class is now built based on Base will have to implement all of these four methods/properties. Please note that for a method to be abstract, two decorators are required - classmethod and abstract property.

Now we could create a class A like this:

class A(Base):
    def __init__(self, name, val1, val2):
        self.name = name
        self.__val1 = val1
        self._val2 = val2

    @classmethod
    def from_dict(cls, d):
        name = d['name']
        val1 = d['val1']
        val2 = d['val2']

        return cls(name, val1, val2)

    @property
    def prop1(self):
        return self.__val1

    @property
    def prop2(self):
        return self._val2

    @prop2.setter
    def prop2(self, value):
        self._val2 = value

    def do_stuff(self):
        print('juhu!')

    def i_am_not_abstract(self):
        print('I can be customized')

All required methods/properties are implemented and we can - of course - also add additional functions that are not part of Base (here: i_am_not_abstract).

Now we can do:

a1 = A('dummy', 10, 'stuff')
a2 = A.from_dict({'name': 'from_d', 'val1': 20, 'val2': 'stuff'})

a1.prop1
# prints 10

a1.prop2
# prints 'stuff'

As desired, we cannot set prop1:

a.prop1 = 100

will return

AttributeError: can't set attribute

Also our from_dict method works fine:

a2.prop1
# prints 20

If we now defined a second class B like this:

class B(Base):
    def __init__(self, name):
        self.name = name

    @property
    def prop1(self):
        return self.name

and tried to instantiate an object like this:

b = B('iwillfail')

we will get an error

TypeError: Can't instantiate abstract class B with abstract methods do_stuff, from_dict, prop2

listing all the things defined in Base which we did not implement in B.

When do I have to use interfaces instead of abstract classes?

Interface and Abstract Class are the two different ways to achieve Abstraction in OOP Languages.

Interface provides 100% abstraction, i.e all methods are abstract.

Abstract class provides 0 to 100% abstraction, i.e it may have or may not have abstract methods.

We can use Interface when we want all the functionality of a type to be implemented by the client.

We can use Abstract Class when some common functionality can be provided by Abstract Class implementer and client will be given chance to implement what he needs actually.

When to use an interface instead of an abstract class and vice versa?

Personally, I almost never have the need to write abstract classes.

Most times I see abstract classes being (mis)used, it's because the author of the abstract class is using the "Template method" pattern.

The problem with "Template method" is that it's nearly always somewhat re-entrant - the "derived" class knows about not just the "abstract" method of its base class that it is implementing, but also about the public methods of the base class, even though most times it does not need to call them.

(Overly simplified) example:

abstract class QuickSorter
{
    public void Sort(object[] items)
    {
        // implementation code that somewhere along the way calls:
        bool less = compare(x,y);
        // ... more implementation code
    }
    abstract bool compare(object lhs, object rhs);
}

So here, the author of this class has written a generic algorithm and intends for people to use it by "specializing" it by providing their own "hooks" - in this case, a "compare" method.

So the intended usage is something like this:

class NameSorter : QuickSorter
{
    public bool compare(object lhs, object rhs)
    {
        // etc.
    }
}

The problem with this is that you've unduly coupled together two concepts:

  1. A way of comparing two items (what item should go first)
  2. A method of sorting items (i.e. quicksort vs merge sort etc.)

In the above code, theoretically, the author of the "compare" method can re-entrantly call back into the superclass "Sort" method... even though in practise they will never want or need to do this.

The price you pay for this unneeded coupling is that it's hard to change the superclass, and in most OO languages, impossible to change it at runtime.

The alternative method is to use the "Strategy" design pattern instead:

interface IComparator
{
    bool compare(object lhs, object rhs);
}

class QuickSorter
{
    private readonly IComparator comparator;
    public QuickSorter(IComparator comparator)
    {
        this.comparator = comparator;
    }

    public void Sort(object[] items)
    {
        // usual code but call comparator.Compare();
    }
}

class NameComparator : IComparator
{
    bool compare(object lhs, object rhs)
    {
        // same code as before;
    }
}

So notice now: All we have are interfaces, and concrete implementations of those interfaces. In practise, you don't really need anything else to do a high level OO design.

To "hide" the fact that we've implemented "sorting of names" by using a "QuickSort" class and a "NameComparator", we might still write a factory method somewhere:

ISorter CreateNameSorter()
{
    return new QuickSorter(new NameComparator());
}

Any time you have an abstract class you can do this... even when there is a natural re-entrant relationship between the base and derived class, it usually pays to make them explicit.

One final thought: All we've done above is "compose" a "NameSorting" function by using a "QuickSort" function and a "NameComparison" function... in a functional programming language, this style of programming becomes even more natural, with less code.

Interface or an Abstract Class: which one to use?

Why to use abstract classes? The following is a simple example. Lets say we have the following code:

<?php 

class Fruit {
    private $color;

    public function eat() {
        // chew
    }

    public function setColor($c) {
        $this->color = $c;
    }
}

class Apple extends Fruit {
    public function eat() {
        // chew until core
    }
}

class Orange extends Fruit {
    public function eat() {
        // peeling
        // chew
    }
}

Now I give you an apple and you eat it. What does it taste like? It tastes like an apple.

<?php 
$apple = new Apple();
$apple->eat();

// Now I give you a fruit.
$fruit = new Fruit();
$fruit->eat();

What does that taste like? Well, it doesn't make much sense, so you shouldn't be able to do that. This is accomplished by making the Fruit class abstract as well as the eat method inside of it.

<?php 
abstract class Fruit {
    private $color;

    abstract public function eat(){}

    public function setColor($c) {
        $this->color = $c;
    }
}
?>

An abstract class is just like an interface, but you can define methods in an abstract class whereas in an interface they are all abstract. Abstract classes can have both empty and working/concrete methods. In interfaces, functions defined there cannot have a body. In abstract classes, they can.

A real world example:

<?php 
abstract class person {

    public $LastName;
    public $FirstName;
    public $BirthDate;

    abstract protected function write_info();
}

final class employee extends person{

    public $EmployeeNumber;
    public $DateHired;

    public function write_info(){
        //sql codes here
        echo "Writing ". $this->LastName . "'s info to emloyee dbase table <br>";   
    }
}

final class student extends person{

    public $StudentNumber;
    public $CourseName;

    public function write_info(){
        //sql codes here
        echo "Writing ". $this->LastName . "'s info to student dbase table <br>";
    }
}

///----------
$personA = new employee;
$personB = new student;

$personA->FirstName="Joe";
$personA->LastName="Sbody";

$personB->FirstName="Ben";
$personB->LastName="Dover";

$personA->write_info();
// Writing Sbody's info to emloyee dbase table
$personB->write_info();
// Writing Dover's info to student dbase table 

How do you declare an interface in C++?

To expand on the answer by bradtgmurray, you may want to make one exception to the pure virtual method list of your interface by adding a virtual destructor. This allows you to pass pointer ownership to another party without exposing the concrete derived class. The destructor doesn't have to do anything, because the interface doesn't have any concrete members. It might seem contradictory to define a function as both virtual and inline, but trust me - it isn't.

class IDemo
{
    public:
        virtual ~IDemo() {}
        virtual void OverrideMe() = 0;
};

class Parent
{
    public:
        virtual ~Parent();
};

class Child : public Parent, public IDemo
{
    public:
        virtual void OverrideMe()
        {
            //do stuff
        }
};

You don't have to include a body for the virtual destructor - it turns out some compilers have trouble optimizing an empty destructor and you're better off using the default.

Interfaces vs. abstract classes

Abstract classes and interfaces are semantically different, although their usage can overlap.

An abstract class is generally used as a building basis for similar classes. Implementation that is common for the classes can be in the abstract class.

An interface is generally used to specify an ability for classes, where the classes doesn't have to be very similar.

Creating an abstract class in Objective-C

Cocoa doesn’t provide anything called abstract. We can create a class abstract which gets checked only at runtime, and at compile time this is not checked.

How to test abstract class in Java with JUnit?

Create a concrete class that inherits the abstract class and then test the functions the concrete class inherits from the abstract class.

Difference between abstract class and interface in Python

Python doesn't really have either concept.

It uses duck typing, which removed the need for interfaces (at least for the computer :-))

Python <= 2.5: Base classes obviously exist, but there is no explicit way to mark a method as 'pure virtual', so the class isn't really abstract.

Python >= 2.6: Abstract base classes do exist (http://docs.python.org/library/abc.html). And allow you to specify methods that must be implemented in subclasses. I don't much like the syntax, but the feature is there. Most of the time it's probably better to use duck typing from the 'using' client side.

When and Why to use abstract classes/methods?

read the following article http://mycodelines.wordpress.com/2009/09/01/in-which-scenario-we-use-abstract-classes-and-interfaces/

Abstract Classes

–> When you have a requirement where your base class should provide default implementation of certain methods whereas other methods should be open to being overridden by child classes use abstract classes.

For e.g. again take the example of the Vehicle class above. If we want all classes deriving from Vehicle to implement the Drive() method in a fixed way whereas the other methods can be overridden by child classes. In such a scenario we implement the Vehicle class as an abstract class with an implementation of Drive while leave the other methods / properties as abstract so they could be overridden by child classes.

–> The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.

For example a class library may define an abstract class that is used as a parameter to many of its functions and require programmers using that library to provide their own implementation of the class by creating a derived class.

Use an abstract class

When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning. This is the practice used by the Microsoft team which developed the Base Class Library. ( COM was designed around interfaces.) Use an abstract class to define a common base class for a family of types. Use an abstract class to provide default behavior. Subclass only a base class in a hierarchy to which the class logically belongs.

Interface vs Abstract Class (general OO)

While your question indicates it's for "general OO", it really seems to be focusing on .NET use of these terms.

In .NET (similar for Java):

  • interfaces can have no state or implementation
  • a class that implements an interface must provide an implementation of all the methods of that interface
  • abstract classes may contain state (data members) and/or implementation (methods)
  • abstract classes can be inherited without implementing the abstract methods (though such a derived class is abstract itself)
  • interfaces may be multiple-inherited, abstract classes may not (this is probably the key concrete reason for interfaces to exist separately from abtract classes - they permit an implementation of multiple inheritance that removes many of the problems of general MI).

As general OO terms, the differences are not necessarily well-defined. For example, there are C++ programmers who may hold similar rigid definitions (interfaces are a strict subset of abstract classes that cannot contain implementation), while some may say that an abstract class with some default implementations is still an interface or that a non-abstract class can still define an interface.

Indeed, there is a C++ idiom called the Non-Virtual Interface (NVI) where the public methods are non-virtual methods that 'thunk' to private virtual methods:

Why can't static methods be abstract in Java?

The abstract annotation to a method indicates that the method MUST be overriden in a subclass.

In Java, a static member (method or field) cannot be overridden by subclasses (this is not necessarily true in other object oriented languages, see SmallTalk.) A static member may be hidden, but that is fundamentally different than overridden.

Since static members cannot be overriden in a subclass, the abstract annotation cannot be applied to them.

As an aside - other languages do support static inheritance, just like instance inheritance. From a syntax perspective, those languages usually require the class name to be included in the statement. For example, in Java, assuming you are writing code in ClassA, these are equivalent statements (if methodA() is a static method, and there is no instance method with the same signature):

ClassA.methodA();

and

methodA();

In SmallTalk, the class name is not optional, so the syntax is (note that SmallTalk does not use the . to separate the "subject" and the "verb", but instead uses it as the statemend terminator):

ClassA methodA.

Because the class name is always required, the correct "version" of the method can always be determined by traversing the class hierarchy. For what it's worth, I do occasionally miss static inheritance, and was bitten by the lack of static inheritance in Java when I first started with it. Additionally, SmallTalk is duck-typed (and thus doesn't support program-by-contract.) Thus, it has no abstract modifier for class members.

Constructor of an abstract class in C#

Far as I know we can't instantiate an abstract class

There's your error right there. Of course you can instantiate an abstract class.

abstract class Animal {}
class Giraffe : Animal {}
...
Animal animal = new Giraffe();

There's an instance of Animal right there. You instantiate an abstract class by making a concrete class derived from it, and instantiating that. Remember, an instance of a derived concrete class is also an instance of its abstract base class. An instance of Giraffe is also an instance of Animal even if Animal is abstract.

Given that you can instantiate an abstract class, it needs to have a constructor like any other class, to ensure that its invariants are met.

Now, a static class is a class you actually cannot instantiate, and you'll notice that it is not legal to make an instance constructor in a static class.

Why do abstract classes in Java have constructors?

A constructor in Java doesn't actually "build" the object, it is used to initialize fields.

Imagine that your abstract class has fields x and y, and that you always want them to be initialized in a certain way, no matter what actual concrete subclass is eventually created. So you create a constructor and initialize these fields.

Now, if you have two different subclasses of your abstract class, when you instantiate them their constructors will be called, and then the parent constructor will be called and the fields will be initialized.

If you don't do anything, the default constructor of the parent will be called. However, you can use the super keyword to invoke specific constructor on the parent class.

invalid new-expression of abstract class type

invalid new-expression of abstract class type 'box'

There is nothing unclear about the error message. Your class box has at least one member that is not implemented, which means it is abstract. You cannot instantiate an abstract class.

If this is a bug, fix your box class by implementing the missing member(s).

If it's by design, derive from box, implement the missing member(s) and use the derived class.

How to unit test abstract classes: extend with stubs?

If the concrete methods invoke any of the abstract methods that strategy won't work, and you'd want to test each child class behavior separately. Otherwise, extending it and stubbing the abstract methods as you've described should be fine, again provided the abstract class concrete methods are decoupled from child classes.

What is the difference between an interface and abstract class?

The comparison of interface vs. abstract class is wrong. There should be two other comparisons instead: 1) interface vs. class and 2) abstract vs. final class.

Interface vs Class

Interface is a contract between two objects. E.g., I'm a Postman and you're a Package to deliver. I expect you to know your delivery address. When someone gives me a Package, it has to know its delivery address:

interface Package {
  String address();
}

Class is a group of objects that obey the contract. E.g., I'm a box from "Box" group and I obey the contract required by the Postman. At the same time I obey other contracts:

class Box implements Package, Property {
  @Override
  String address() {
    return "5th Street, New York, NY";
  }
  @Override
  Human owner() {
    // this method is part of another contract
  }
}

Abstract vs Final

Abstract class is a group of incomplete objects. They can't be used, because they miss some parts. E.g., I'm an abstract GPS-aware box - I know how to check my position on the map:

abstract class GpsBox implements Package {
  @Override
  public abstract String address();
  protected Coordinates whereAmI() {
    // connect to GPS and return my current position
  }
}

This class, if inherited/extended by another class, can be very useful. But by itself - it is useless, since it can't have objects. Abstract classes can be building elements of final classes.

Final class is a group of complete objects, which can be used, but can't be modified. They know exactly how to work and what to do. E.g., I'm a Box that always goes to the address specified during its construction:

final class DirectBox implements Package {
  private final String to;
  public DirectBox(String addr) {
    this.to = addr;
  }
  @Override
  public String address() {
    return this.to;
  }
}

In most languages, like Java or C++, it is possible to have just a class, neither abstract nor final. Such a class can be inherited and can be instantiated. I don't think this is strictly in line with object-oriented paradigm, though.

Again, comparing interfaces with abstract classes is not correct.

Abstract Class vs Interface in C++

Pure Virtual Functions are mostly used to define:

a) abstract classes

These are base classes where you have to derive from them and then implement the pure virtual functions.

b) interfaces

These are 'empty' classes where all functions are pure virtual and hence you have to derive and then implement all of the functions.

Pure virtual functions are actually functions which have no implementation in base class and have to be implemented in derived class.

When to use: Java 8+ interface default method, vs. abstract method

There are a few technical differences. Abstract classes can still do more in comparison to Java 8 interfaces:

  1. Abstract class can have a constructor.
  2. Abstract classes are more structured and can hold a state.

Conceptually, main purpose of defender methods is a backward compatibility after introduction of new features (as lambda-functions) in Java 8.

Class is not abstract and does not override abstract method

Both classes Rectangle and Ellipse need to override both of the abstract methods.

To work around this, you have 3 options:

  • Add the two methods
  • Make each class that extends Shape abstract
  • Have a single method that does the function of the classes that will extend Shape, and override that method in Rectangle and Ellipse, for example:

    abstract class Shape {
        // ...
        void draw(Graphics g);
    }
    

And

    class Rectangle extends Shape {
        void draw(Graphics g) {
            // ...
        }
    }

Finally

    class Ellipse extends Shape {
        void draw(Graphics g) {
            // ...
        }
    }

And you can switch in between them, like so:

    Shape shape = new Ellipse();
    shape.draw(/* ... */);

    shape = new Rectangle();
    shape.draw(/* ... */);

Again, just an example.

Why an abstract class implementing an interface can miss the declaration/implementation of one of the interface's methods?

Perfectly fine.
You can't instantiate abstract classes.. but abstract classes can be used to house common implementations for m1() and m3().
So if m2() implementation is different for each implementation but m1 and m3 are not. You could create different concrete IAnything implementations with just the different m2 implementation and derive from AbstractThing -- honoring the DRY principle. Validating if the interface is completely implemented for an abstract class is futile..

Update: Interestingly, I find that C# enforces this as a compile error. You are forced to copy the method signatures and prefix them with 'abstract public' in the abstract base class in this scenario.. (something new everyday:)

How should I have explained the difference between an Interface and an Abstract class?

In a few words, I would answer this way:

  • inheritance via class hierarchy implies a state inheritance;
  • whereas inheritance via interfaces stands for behavior inheritance;

Abstract classes can be treated as something between these two cases (it introduces some state but also obliges you to define a behavior), a fully-abstract class is an interface (this is a further development of classes consist from virtual methods only in C++ as far as I'm aware of its syntax).

Of course, starting from Java 8 things got slightly changed, but the idea is still the same.

I guess this is pretty enough for a typical Java interview, if you are not being interviewed to a compiler team.

What is an abstract class in PHP?

Abstract Class
1. Contains an abstract method
2. Cannot be directly initialized
3. Cannot create an object of abstract class
4. Only used for inheritance purposes

Abstract Method
1. Cannot contain a body
2. Cannot be defined as private
3. Child classes must define the methods declared in abstract class

Example Code:

abstract class A {
    public function test1() {
        echo 'Hello World';
    }
    abstract protected function f1();
    abstract public function f2();
    protected function test2(){
        echo 'Hello World test';
    }
}

class B extends A {
    public $a = 'India';
    public function f1() {
        echo "F1 Method Call";
    }
    public function f2() {
        echo "F2 Method Call";
    }
}

$b = new B();
echo $b->test1() . "<br/>";
echo $b->a . "<br/>";
echo $b->test2() . "<br/>";
echo $b->f1() . "<br/>";
echo $b->f2() . "<br/>";

Output:

Hello World
India
Hello World test
F1 Method Call
F2 Method Call

Abstract Class:-Real Time Example

You should be able to cite at least one from the JDK itself. Look in the java.util.collections package. There are several abstract classes. You should fully understand interface, abstract, and concrete for Map and why Joshua Bloch wrote it that way.

Abstract class in Java

Little addition to all these posts.

Sometimes you may want to declare a class and yet not know how to define all of the methods that belong to that class. For example, you may want to declare a class called Writer and include in it a member method called write(). However, you don't know how to code write() because it is different for each type of Writer devices. Of course, you plan to handle this by deriving subclass of Writer, such as Printer, Disk, Network and Console.

How to add two edit text fields in an alert dialog

Check the following code. It shows 2 edit text fields programmatically without any layout xml. Change 'this' to 'getActivity()' if you use it in a fragment.

The tricky thing is we have to set the second text field's input type after creating alert dialog, otherwise, the second text field shows texts instead of dots.

    public void showInput() {
        OnFocusChangeListener onFocusChangeListener = new OnFocusChangeListener() {
            @Override
            public void onFocusChange(final View v, boolean hasFocus) {
                if (hasFocus) {
                    // Must use message queue to show keyboard
                    v.post(new Runnable() {
                        @Override
                        public void run() {
                            InputMethodManager inputMethodManager= (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                            inputMethodManager.showSoftInput(v, 0);
                        }
                    });
                }
            }
        };

        final EditText editTextName = new EditText(this);
        editTextName.setHint("Name");
        editTextName.setFocusable(true);
        editTextName.setClickable(true);
        editTextName.setFocusableInTouchMode(true);
        editTextName.setSelectAllOnFocus(true);
        editTextName.setSingleLine(true);
        editTextName.setImeOptions(EditorInfo.IME_ACTION_NEXT);
        editTextName.setOnFocusChangeListener(onFocusChangeListener);

        final EditText editTextPassword = new EditText(this);
        editTextPassword.setHint("Password");
        editTextPassword.setFocusable(true);
        editTextPassword.setClickable(true);
        editTextPassword.setFocusableInTouchMode(true);
        editTextPassword.setSelectAllOnFocus(true);
        editTextPassword.setSingleLine(true);
        editTextPassword.setImeOptions(EditorInfo.IME_ACTION_DONE);
        editTextPassword.setOnFocusChangeListener(onFocusChangeListener);

        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout.addView(editTextName);
        linearLayout.addView(editTextPassword);

        DialogInterface.OnClickListener alertDialogClickListener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which){
                case DialogInterface.BUTTON_POSITIVE:
                    // Done button clicked
                    break;
                case DialogInterface.BUTTON_NEGATIVE:
                    // Cancel button clicked
                    break;
                }
            }
        };
        final AlertDialog alertDialog = (new AlertDialog.Builder(this)).setMessage("Please enter name and password")
                .setView(linearLayout)
                .setPositiveButton("Done", alertDialogClickListener)
                .setNegativeButton("Cancel", alertDialogClickListener)
                .create();

        editTextName.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                editTextPassword.requestFocus(); // Press Return to focus next one
                return false;
            }
        });
        editTextPassword.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                // Press Return to invoke positive button on alertDialog.
                alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).performClick();
                return false;
            }
        });

        // Must set password mode after creating alert dialog.
        editTextPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
        editTextPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
        alertDialog.show();
    }

Regex how to match an optional character

You also could use simpler regex designed for your case like (.*)\/(([^\?\n\r])*) where $2 match what you want.

Can I scale a div's height proportionally to its width using CSS?

If you want vertical sizing proportional to a width set in pixels on an enclosing div, I believe you need an extra element, like so:

#html

<div class="ptest">
    <div class="ptest-wrap">
        <div class="ptest-inner">
            Put content here
        </div>
    </div>
</div>

#css
.ptest {
  width: 200px;
  position: relative;
}

.ptest-wrap {
    padding-top: 60%;
}
.ptest-inner {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: #333;
}

Here's the 2 div solution that doesn't work. Note the 60% vertical padding is proportional to the window width, not the div.ptest width:

http://jsfiddle.net/d85FM/

Here's the example with the code above, which does work:

http://jsfiddle.net/mmq29/

Best way to determine user's locale within browser

This article suggests the following properties of the browser's navigator object:

  • navigator.language (Netscape - Browser Localization)
  • navigator.browserLanguage (IE-Specific - Browser Localized Language)
  • navigator.systemLanguage (IE-Specific - Windows OS - Localized Language)
  • navigator.userLanguage

Roll these into a javascript function and you should be able to guess the right language, in most circumstances. Be sure to degrade gracefully, so have a div containing your language choice links, so that if there is no javascript or the method doesn't work, the user can still decide. If it does work, just hide the div.

The only problem with doing this on the client side is that either you serve up all the languages to the client, or you have to wait until the script has run and detected the language before requesting the right version. Perhaps serving up the most popular language version as a default would irritate the fewest people.

Edit: I'd second Ivan's cookie suggestion, but make sure the user can always change the language later; not everyone prefers the language their browser defaults to.

Iterate all files in a directory using a 'for' loop

I use the xcopy command with the /L option to get the file names. So if you want to get either a directory or all the files in the subdirectory you could do something like this:

for /f "delims=" %%a IN ('xcopy "D:\*.pdf" c:\ /l') do echo %%a

I just use the c:\ as the destination because it always exists on windows systems and it is not copying so it does not matter. if you want the subdirectories too just use /s option on the end. You can also use the other switches of xcopy if you need them for other reasons.

if (boolean condition) in Java

boolean turnedOn;
    if(turnedOn)
    {
    //do stuff when the condition is true - i.e, turnedOn is true
    }
    else
    {
    //do stuff when the condition is false - i.e, turnedOn is false
    }

How to show only next line after the matched one?

I don't know of any way to do this with grep, but it is possible to use awk to achieve the same result:

awk '/blah/ {getline;print}' < logfile

Position of a string within a string using Linux shell script?

With bash

a="The cat sat on the mat"
b=cat
strindex() { 
  x="${1%%$2*}"
  [[ "$x" = "$1" ]] && echo -1 || echo "${#x}"
}
strindex "$a" "$b"   # prints 4
strindex "$a" foo    # prints -1

400 vs 422 response to POST of data

400 Bad Request is proper HTTP status code for your use case. The code is defined by HTTP/0.9-1.1 RFC.

The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

http://tools.ietf.org/html/rfc2616#section-10.4.1

422 Unprocessable Entity is defined by RFC 4918 - WebDav. Note that there is slight difference in comparison to 400, see quoted text below.

This error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

To keep uniform interface you should use 422 only in a case of XML responses and you should also support all status codes defined by Webdav extension, not just 422.

http://tools.ietf.org/html/rfc4918#page-78

See also Mark Nottingham's post on status codes:

it’s a mistake to try to map each part of your application “deeply” into HTTP status codes; in most cases the level of granularity you want to be aiming for is much coarser. When in doubt, it’s OK to use the generic status codes 200 OK, 400 Bad Request and 500 Internal Service Error when there isn’t a better fit.

How to Think About HTTP Status Codes

Heap space out of memory

Try adding -Xmx for more memory ( java -Xmx1024M YourClass ), and don't forget to stop referencing variables you don't need any more (memory leaks).

How to use sbt from behind proxy?

I used (this is a unix environment) :

export SBT_OPTS="$SBT_OPTS -Dhttp.proxyHost=myproxy-Dhttp.proxyPort=myport"

This did not work for my setup :

export JAVA_OPTS="$JAVA_OPTS -Dhttp.proxyHost=myproxy-Dhttp.proxyPort=myport"

In sbt.sh file :

JAVA_OPTS          environment variable, if unset uses "$java_opts"
SBT_OPTS           environment variable, if unset uses "$default_sbt_opts"

But apparently SBT_OPTS is used instead of JAVA_OPTS

tell pip to install the dependencies of packages listed in a requirement file

As @Ming mentioned:

pip install -r file.txt

Here's a simple line to force update all dependencies:

while read -r package; do pip install --upgrade --force-reinstall $package;done < pipfreeze.txt

How do you list volumes in docker containers?

Use docker ps to get the container id.

Then docker inspect -f '{{ .Mounts }}' containerid

Example:

terminal 1

$ docker run -it -v /tmp:/tmp ubuntu:14.04 /bin/bash

terminal 2

$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED              STATUS              PORTS               NAMES
ddb7b55902cc        ubuntu:14.04        "/bin/bash"         About a minute ago   Up About a minute                       distracted_banach   

$ docker inspect -f "{{ .Mounts }}" ddb7
map[/tmp:/tmp]

The output

map[/tmp:/tmp] 

is, apparently, due to the use of the Go language to implement the docker command tools.

The docker inspect command without the -f format is quite verbose. Since it is JSON you could pipe it to python or nodejs and extract whatever you needed.

paul@home:~$ docker inspect ddb7
[{
    "AppArmorProfile": "",
    "Args": [],
    "Config": {
        "AttachStderr": true,
        "AttachStdin": true,
        "AttachStdout": true,
        "Cmd": [
            "/bin/bash"
        ],
        "CpuShares": 0,
        "Cpuset": "",
        "Domainname": "",
        "Entrypoint": null,
        "Env": [
            "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
        ],
        "ExposedPorts": null,
        "Hostname": "ddb7b55902cc",
        "Image": "ubuntu:14.04",
        "MacAddress": "",
        "Memory": 0,
        "MemorySwap": 0,
        "NetworkDisabled": false,
        "OnBuild": null,
        "OpenStdin": true,
        "PortSpecs": null,
        "StdinOnce": true,
        "Tty": true,
        "User": "",
        "Volumes": null,
        "WorkingDir": ""
    },
    "Created": "2015-05-08T22:41:44.74862921Z",
    "Driver": "devicemapper",
    "ExecDriver": "native-0.2",
    "ExecIDs": null,
    "HostConfig": {
        "Binds": [
            "/tmp:/tmp"
        ],
        "CapAdd": null,
        "CapDrop": null,
        "ContainerIDFile": "",
        "Devices": [],
        "Dns": null,
        "DnsSearch": null,
        "ExtraHosts": null,
        "IpcMode": "",
        "Links": null,
        "LxcConf": [],
        "NetworkMode": "bridge",
        "PidMode": "",
        "PortBindings": {},
        "Privileged": false,
        "PublishAllPorts": false,
        "ReadonlyRootfs": false,
        "RestartPolicy": {
            "MaximumRetryCount": 0,
            "Name": ""
        },
        "SecurityOpt": null,
        "VolumesFrom": null
    },
    "HostnamePath": "/var/lib/docker/containers/ddb7b55902cc328612d794570fe9a936d96a9644411e89c4ea116a5fef4c311a/hostname",
    "HostsPath": "/var/lib/docker/containers/ddb7b55902cc328612d794570fe9a936d96a9644411e89c4ea116a5fef4c311a/hosts",
    "Id": "ddb7b55902cc328612d794570fe9a936d96a9644411e89c4ea116a5fef4c311a",
    "Image": "ed5a78b7b42bde1e3e4c2996e02da778882dca78f8919cbd0deb6694803edec3",
    "MountLabel": "",
    "Name": "/distracted_banach",
    "NetworkSettings": {
        "Bridge": "docker0",
        "Gateway": "172.17.42.1",
        "GlobalIPv6Address": "",
        "GlobalIPv6PrefixLen": 0,
        "IPAddress": "172.17.0.4",
        "IPPrefixLen": 16,
        "IPv6Gateway": "",
        "LinkLocalIPv6Address": "fe80::42:acff:fe11:4",
        "LinkLocalIPv6PrefixLen": 64,
        "MacAddress": "02:42:ac:11:00:04",
        "PortMapping": null,
        "Ports": {}
    },
    "Path": "/bin/bash",
    "ProcessLabel": "",
    "ResolvConfPath": "/var/lib/docker/containers/ddb7b55902cc328612d794570fe9a936d96a9644411e89c4ea116a5fef4c311a/resolv.conf",
    "RestartCount": 0,
    "State": {
        "Error": "",
        "ExitCode": 0,
        "FinishedAt": "0001-01-01T00:00:00Z",
        "OOMKilled": false,
        "Paused": false,
        "Pid": 6115,
        "Restarting": false,
        "Running": true,
        "StartedAt": "2015-05-08T22:41:45.367432585Z"
    },
    "Volumes": {
        "/tmp": "/tmp"
    },
    "VolumesRW": {
        "/tmp": true
    }
}
]

docker history <image name> will show the layers baked into an image. Unfortunately, docker history seems hobbled by its formatting and lack of options to choose what is displayed.

You can choose terse and verbose formats, via the --no-trunc flag.

$ docker history drpaulbrewer/spark-worker
IMAGE               CREATED             CREATED BY                                      SIZE
438ff4e1753a        2 weeks ago         /bin/sh -c #(nop) CMD [/bin/sh -c /spark/my-s   0 B
6b664e299724        2 weeks ago         /bin/sh -c #(nop) ADD file:09da603c5f0dca7cc6   296 B
f6ae126ae124        2 weeks ago         /bin/sh -c #(nop) MAINTAINER drpaulbrewer@eaf   0 B
70bcb3ffaec9        2 weeks ago         /bin/sh -c #(nop) EXPOSE 2222/tcp 4040/tcp 60   0 B
1332ac203849        2 weeks ago         /bin/sh -c apt-get update && apt-get --yes up   1.481 GB
8e6f1e0bb1b0        2 weeks ago         /bin/sh -c sed -e 's/archive.ubuntu.com/www.g   1.975 kB
b3d242776b1f        2 weeks ago         /bin/sh -c #(nop) WORKDIR /spark/spark-1.3.1    0 B
ac0d6cc5aa3f        2 weeks ago         /bin/sh -c #(nop) ADD file:b6549e3d28e2d149c0   25.89 MB
6ee404a44b3f        5 weeks ago         /bin/sh -c #(nop) WORKDIR /spark                0 B
c167faff18cf        5 weeks ago         /bin/sh -c adduser --disabled-password --home   335.1 kB
f55d468318a4        5 weeks ago         /bin/sh -c #(nop) MAINTAINER drpaulbrewer@eaf   0 B
19c8c047d0fe        8 weeks ago         /bin/sh -c #(nop) CMD [/bin/bash]               0 B
c44d976a473f        8 weeks ago         /bin/sh -c sed -i 's/^#\s*\(deb.*universe\)$/   1.879 kB
14dbf1d35e28        8 weeks ago         /bin/sh -c echo '#!/bin/sh' > /usr/sbin/polic   701 B
afa7a164a0d2        8 weeks ago         /bin/sh -c #(nop) ADD file:57f97478006b988c0c   131.5 MB
511136ea3c5a        23 months ago                                                       0 B

Here's a verbose example.

docker history --no-trunc=true drpaulbrewer/spark-worker
IMAGE                                                              CREATED             CREATED BY                                                                                                                                                                                                                                                                                                                                                                                                                        SIZE
438ff4e1753a60779f389a3de593d41f7d24a61da6e1df76dded74a688febd64   2 weeks ago         /bin/sh -c #(nop) CMD [/bin/sh -c /spark/my-spark-worker.sh]                                                                                                                                                                                                                                                                                                                                                                      0 B
6b664e29972481b8d6d47f98167f110609d9599f48001c3ca11c22364196c98a   2 weeks ago         /bin/sh -c #(nop) ADD file:09da603c5f0dca7cc60f1911caf30c3c70df5e4783f7eb10468e70df66e2109f in /spark/                                                                                                                                                                                                                                                                                                                            296 B
f6ae126ae124ca211c04a1257510930b37ea78425e31a273ea0b1495fa176c57   2 weeks ago         /bin/sh -c #(nop) MAINTAINER [email protected]                                                                                                                                                                                                                                                                                                                                                                               0 B
70bcb3ffaec97a0d14e93b170ed70cc7d68c3c9dfb0222c1d360a300d6e05255   2 weeks ago         /bin/sh -c #(nop) EXPOSE 2222/tcp 4040/tcp 6066/tcp 7077/tcp 7777/tcp 8080/tcp 8081/tcp                                                                                                                                                                                                                                                                                                                                           0 B
1332ac20384947fe1f15107213b675e5be36a68d72f0e81153d6d5a21acf35af   2 weeks ago         /bin/sh -c apt-get update && apt-get --yes upgrade     && apt-get --yes install sed nano curl wget openjdk-8-jdk scala     && echo "JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64" >>/etc/environment     && export MAVEN_OPTS="-Xmx2g -XX:MaxPermSize=512M -XX:ReservedCodeCacheSize=512m"     && ./build/mvn -Phive -Phive-thriftserver -DskipTests clean package     && chown -R spark:spark /spark     && mkdir /var/run/sshd   1.481 GB
8e6f1e0bb1b0b9286947d3a4b443cc8099b00f9670aab1d58654051e06f62e51   2 weeks ago         /bin/sh -c sed -e 's/archive.ubuntu.com/www.gtlib.gatech.edu\/pub/' /etc/apt/sources.list > /tmp/sources.list && mv /tmp/sources.list /etc/apt/sources.list                                                                                                                                                                                                                                                                       1.975 kB
b3d242776b1f1f1ae5685471d06a91a68f92845ef6fc6445d831835cd55e5d0b   2 weeks ago         /bin/sh -c #(nop) WORKDIR /spark/spark-1.3.1                                                                                                                                                                                                                                                                                                                                                                                      0 B
ac0d6cc5aa3fdc3b65fc0173f6775af283c3c395c8dae945cf23940435f2785d   2 weeks ago         /bin/sh -c #(nop) ADD file:b6549e3d28e2d149c0bc84f69eb0beab16f62780fc4889bcc64cfc9ce9f762d6 in /spark/                                                                                                                                                                                                                                                                                                                            25.89 MB
6ee404a44b3fdd3ef3318dc10f3d002f1995eea238c78f4eeb9733d00bb29404   5 weeks ago         /bin/sh -c #(nop) WORKDIR /spark                                                                                                                                                                                                                                                                                                                                                                                                  0 B
c167faff18cfecedef30343ef1cb54aca45f4ef0478a3f6296746683f69d601b   5 weeks ago         /bin/sh -c adduser --disabled-password --home /spark spark                                                                                                                                                                                                                                                                                                                                                                        335.1 kB
f55d468318a4778733160d377c5d350dc8f593683009699c2af85244471b15a3   5 weeks ago         /bin/sh -c #(nop) MAINTAINER [email protected]                                                                                                                                                                                                                                                                                                                                                                               0 B
19c8c047d0fe2de7239120f2b5c1a20bbbcb4d3eb9cbf0efa59ab27ab047377a   8 weeks ago         /bin/sh -c #(nop) CMD [/bin/bash]                                                                                                                                                                                                                                                                                                                                                                                                 0 B
c44d976a473f143937ef91449c73f2cabd109b540f6edf54facb9bc2b4fff136   8 weeks ago         /bin/sh -c sed -i 's/^#\s*\(deb.*universe\)$/\1/g' /etc/apt/sources.list                                                                                                                                                                                                                                                                                                                                                          1.879 kB
14dbf1d35e2849a00c6c2628055030fa84b4fb55eaadbe0ecad8b82df65cc0db   8 weeks ago         /bin/sh -c echo '#!/bin/sh' > /usr/sbin/policy-rc.d                                                                                                                                                                                                                                                                                                                                                                               && echo 'exit 101' >> /usr/sbin/policy-rc.d    && chmod +x /usr/sbin/policy-rc.d                        && dpkg-divert --local --rename --add /sbin/initctl    && cp -a /usr/sbin/policy-rc.d /sbin/initctl    && sed -i 's/^exit.*/exit 0/' /sbin/initctl                        && echo 'force-unsafe-io' > /etc/dpkg/dpkg.cfg.d/docker-apt-speedup                        && echo 'DPkg::Post-Invoke { "rm -f /var/cache/apt/archives/*.deb /var/cache/apt/archives/partial/*.deb /var/cache/apt/*.bin || true"; };' > /etc/apt/apt.conf.d/docker-clean    && echo 'APT::Update::Post-Invoke { "rm -f /var/cache/apt/archives/*.deb /var/cache/apt/archives/partial/*.deb /var/cache/apt/*.bin || true"; };' >> /etc/apt/apt.conf.d/docker-clean    && echo 'Dir::Cache::pkgcache ""; Dir::Cache::srcpkgcache "";' >> /etc/apt/apt.conf.d/docker-clean                        && echo 'Acquire::Languages "none";' > /etc/apt/apt.conf.d/docker-no-languages                        && echo 'Acquire::GzipIndexes "true"; Acquire::CompressionTypes::Order:: "gz";' > /etc/apt/apt.conf.d/docker-gzip-indexes   701 B
afa7a164a0d215dbf45cd1aadad2a4d12b8e33fc890064568cc2ea6d42ef9b3c   8 weeks ago         /bin/sh -c #(nop) ADD file:57f97478006b988c0c68e5bf82684372e427fd45f21cd7baf5d974d2cfb29e65 in /                                                                                                                                                                                                                                                                                                                                  131.5 MB
511136ea3c5a64f264b78b5433614aec563103b4d4702f3ba7d4d2698e22c158   23 months ago                                                                                                                                                                                                                                                                                                                                                                                                                                         0 B

Remove HTML Tags in Javascript with Regex

This is a solution for HTML tag and &nbsp etc and you can remove and add conditions to get the text without HTML and you can replace it by any.

convertHtmlToText(passHtmlBlock)
{
   str = str.toString();
  return str.replace(/<[^>]*(>|$)|&nbsp;|&zwnj;|&raquo;|&laquo;|&gt;/g, 'ReplaceIfYouWantOtherWiseKeepItEmpty');
}

Pass path with spaces as parameter to bat file

Interesting one. I love collecting quotes about quotes handling in cmd/command.

Your particular scripts gets fixed by using %1 instead of "%1" !!!

By adding an 'echo on' ( or getting rid of an echo off ), you could have easily found that out.

PKIX path building failed in Java application

Per your pastebin, you need to add the proxy.tkk.com certificate to the truststore.

use jQuery's find() on JSON object

This works for me on [{"id":"data"},{"id":"data"}]

function getObjects(obj, key, val) 
{
    var newObj = false; 
    $.each(obj, function()
    {
        var testObject = this; 
        $.each(testObject, function(k,v)
        {
            //alert(k);
            if(val == v && k == key)
            {
                newObj = testObject;
            }
        });
    });

    return newObj;
}

INSERT INTO...SELECT for all MySQL columns

More Examples & Detail

    INSERT INTO vendors (
     name, 
     phone, 
     addressLine1,
     addressLine2,
     city,
     state,
     postalCode,
     country,
     customer_id
 )
 SELECT 
     name,
     phone,
     addressLine1,
     addressLine2,
     city,
     state ,
     postalCode,
     country,
     customer_id
 FROM 
     customers;

How to get/generate the create statement for an existing hive table?

Describe Formatted/Extended will show the data definition of the table in hive

hive> describe Formatted dbname.tablename;

GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::ClassName()'

In my case the problem occured when i forgot to add the =0 on one function in my pure virtual class. It was fixed when the =0 was added. The same as for Frank above.

class ISettings
{
public: 
    virtual ~ISettings() {};
    virtual void OKFunction() =0;
    virtual void ProblemFunction(); // missing =0   
};

class Settings : ISettings
{
    virtual ~Settings() {};
    void OKFunction();
    void ProblemFunction(); 
};

void Settings::OKFunction()
{
    //stuff
}

void Settings::ProblemFunction()
{
    //stuff
}

Notepad++ - How can I replace blank lines

This will remove any number of blank lines

CTRL + H to replace

Select Extended search mode

replace all \r\n with (space)

then switch to regular expression and replace all \s+ with \n

What is the App_Data folder used for in Visual Studio?

in IIS, highlight the machine, double-click "Request Filtering", open the "Hidden Segments" tab. "App_Data" is listed there as a restricted folder. Yes i know this thread is really old, but this is still applicable.

How to make a phone call using intent in Android?

Request Permission in manifest

<uses-permission android:name="android.permission.CALL_PHONE" />

For calling use this code

Intent in = new Intent(Intent.ACTION_CALL, Uri.parse("tel:99xxxxxxxx"));
try {
    startActivity(in);
} catch (android.content.ActivityNotFoundException ex) {
    Toast.makeText(mcontext, "Could not find an activity to place the call.", Toast.LENGTH_SHORT).show();
}

ListView item background via custom selector

You can write a theme:

<pre>

    android:name=".List10" android:theme="@style/Theme"

theme.xml

<style name="Theme" parent="android:Theme">
        <item name="android:listViewStyle">@style/MyListView</item>
</style>

styles.xml

 <style name="MyListView" parent="@android:style/Widget.ListView">
<item name="android:listSelector">@drawable/my_selector</item>

my_selector is your want to custom selector I am sorry i donot know how to write my code

Using Address Instead Of Longitude And Latitude With Google Maps API

See this example, initializes the map to "San Diego, CA".

Uses the Google Maps Javascript API v3 Geocoder to translate the address into coordinates that can be displayed on the map.

<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Geocoding Simple</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
  var geocoder;
  var map;
  var address ="San Diego, CA";
  function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
      zoom: 8,
      center: latlng,
    mapTypeControl: true,
    mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
    navigationControl: true,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    if (geocoder) {
      geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
          map.setCenter(results[0].geometry.location);

            var infowindow = new google.maps.InfoWindow(
                { content: '<b>'+address+'</b>',
                  size: new google.maps.Size(150,50)
                });
    
            var marker = new google.maps.Marker({
                position: results[0].geometry.location,
                map: map, 
                title:address
            }); 
            google.maps.event.addListener(marker, 'click', function() {
                infowindow.open(map,marker);
            });

          } else {
            alert("No results found");
          }
        } else {
          alert("Geocode was not successful for the following reason: " + status);
        }
      });
    }
  }
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
 <div id="map_canvas" style="width:100%; height:100%">
</body>
</html>

working code snippet:

_x000D_
_x000D_
var geocoder;
var map;
var address = "San Diego, CA";

function initialize() {
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(-34.397, 150.644);
  var myOptions = {
    zoom: 8,
    center: latlng,
    mapTypeControl: true,
    mapTypeControlOptions: {
      style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
    },
    navigationControl: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  if (geocoder) {
    geocoder.geocode({
      'address': address
    }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
          map.setCenter(results[0].geometry.location);

          var infowindow = new google.maps.InfoWindow({
            content: '<b>' + address + '</b>',
            size: new google.maps.Size(150, 50)
          });

          var marker = new google.maps.Marker({
            position: results[0].geometry.location,
            map: map,
            title: address
          });
          google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map, marker);
          });

        } else {
          alert("No results found");
        }
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }
}
google.maps.event.addDomListener(window, 'load', initialize);
_x000D_
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
}
_x000D_
<script type="text/javascript" src="https://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas" ></div>
_x000D_
_x000D_
_x000D_

Can jQuery read/write cookies to a browser?

I have managed to write a script allowing the user to choose his/her language, using the cookie script from Klaus Hartl. It took me a few hours work, and I hope I can help others.

Close pre-existing figures in matplotlib when running from eclipse

See Bi Rico's answer for the general Eclipse case.

For anybody - like me - who lands here because you have lots of windows and you're struggling to close them all, just killing python can be effective, depending on your circumstances. It probably works under almost any circumstances - including with Eclipse.

I just spawned 60 plots from emacs (I prefer that to eclipse) and then I thought my script had exited. Running close('all') in my ipython window did not work for me because the plots did not come from ipython, so I resorted to looking for running python processes.

When I killed the interpreter running the script, then all 60 plots were closed - e.g.,

$ ps aux | grep python
rsage    11665  0.1  0.6 649904 109692 ?       SNl  10:54   0:03 /usr/bin/python3 /usr/bin/update-manager --no-update --no-focus-on-map
rsage    12111  0.9  0.5 390956 88212 pts/30   Sl+  11:08   0:17 /usr/bin/python /usr/bin/ipython -pylab
rsage    12410 31.8  2.4 576640 406304 pts/33  Sl+  11:38   0:06 python3 ../plot_motor_data.py
rsage    12431  0.0  0.0   8860   648 pts/32   S+   11:38   0:00 grep python

$ kill 12410

Note that I did not kill my ipython/pylab, nor did I kill the update manager (killing the update manager is probably a bad idea)...

What are these attributes: `aria-labelledby` and `aria-hidden`

Aria is used to improve the user experience of visually impaired users. Visually impaired users navigate though application using screen reader software like JAWS, NVDA,.. While navigating through the application, screen reader software announces content to users. Aria can be used to add content in the code which helps screen reader users understand role, state, label and purpose of the control

Aria does not change anything visually. (Aria is scared of designers too).

aria-hidden:

aria-hidden attribute is used to hide content for visually impaired users who navigate through application using screen readers (JAWS, NVDA,...).

aria-hidden attribute is used with values true, false.

How To Use:

<i class = "fa fa-books" aria-hidden = "true"></i>

using aria-hidden = "true" on the <i> hides content to screen reader users with no visual change in the application.

aria-label

aria-label attribute is used to communicate the label to screen reader users. Usually search input field does not have visual label (thanks to designers). aria-label can be used to communicate the label of control to screen reader users

How To Use:

<input type = "edit" aria-label = "search" placeholder = "search">

There is no visual change in application. But screen readers can understand the purpose of control

aria-labelledby

Both aria-label and aria-labelledby is used to communicate the label. But aria-labelledby can be used to reference any label already present in the page whereas aria-label is used to communicate the label which i not displayed visually

Approach 1:

<span id = "sd"> Search </span>

<input type = "text" aria-labelledby = "sd">

aria-labelledby can also be used to combine two labels for screen reader users

Approach 2:

<span id = "de"> Billing Address </span>

<span id = "sd"> First Name </span>

<input type = "text" aria-labelledby = "de sd">

Get the (last part of) current directory name in C#

Well, to exactly answer your question title :-)

var lastPartOfCurrentDirectoryName = 
   Path.GetFileName(Environment.CurrentDirectory);

Click a button with XPath containing partial id and title in Selenium IDE

Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.

You've got:

//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]

Which translates into:

Get me all the elements that have an ID that contains ctl00_btnAircraftMapCell. Out of these elements, get any child elements that have a title that contains Select Seat.

What you actually want is:

//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]

Which translates into:

Get me all the anchor elements that have both: an id that contains ctl00_btnAircraftMapCell and a title that contains Select Seat.

Effect of using sys.path.insert(0, path) and sys.path(append) when loading modules

Because python checks in the directories in sequential order starting at the first directory in sys.path list, till it find the .py file it was looking for.

Ideally, the current directory or the directory of the script is the first always the first element in the list, unless you modify it, like you did. From documentation -

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.

So, most probably, you had a .py file with the same name as the module you were trying to import from, in the current directory (where the script was being run from).

Also, a thing to note about ImportErrors , lets say the import error says - ImportError: No module named main - it doesn't mean the main.py is overwritten, no if that was overwritten we would not be having issues trying to read it. Its some module above this that got overwritten with a .py or some other file.

Example -

My directory structure looks like -

 - test
    - shared
         - __init__.py
         - phtest.py
  - testmain.py

Now From testmain.py , I call from shared import phtest , it works fine.

Now lets say I introduce a shared.py in test directory` , example -

 - test
    - shared
         - __init__.py
         - phtest.py
  - testmain.py 
  - shared.py

Now when I try to do from shared import phtest from testmain.py , I will get the error -

ImportError: cannot import name 'phtest'

As you can see above, the file that is causing the issue is shared.py , not phtest.py .

Linux: Which process is causing "device busy" when doing umount?

That's exactly why the "fuser -m /mount/point" exists.

BTW, I don't think "fuser" or "lsof" will indicate when a resource is held by kernel module, although I don't usually have that issue..

How to add bootstrap in angular 6 project?

For Angular Version 11+

Configuration

The styles and scripts options in your angular.json configuration now allow to reference a package directly:

before: "styles": ["../node_modules/bootstrap/dist/css/bootstrap.css"]
after: "styles": ["bootstrap/dist/css/bootstrap.css"]

          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/ng6",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css","bootstrap/dist/css/bootstrap.min.css"

            ],
            "scripts": [
                       "jquery/dist/jquery.min.js",
                       "bootstrap/dist/js/bootstrap.min.js"
                       ]
          },

Angular Version 10 and below

You are using Angular v6 not 2

Angular v6 Onwards

CLI projects in angular 6 onwards will be using angular.json instead of .angular-cli.json for build and project configuration.

Each CLI workspace has projects, each project has targets, and each target can have configurations.Docs

. {
  "projects": {
    "my-project-name": {
      "projectType": "application",
      "architect": {
        "build": {
          "configurations": {
            "production": {},
            "demo": {},
            "staging": {},
          }
        },
        "serve": {},
        "extract-i18n": {},
        "test": {},
      }
    },
    "my-project-name-e2e": {}
  },
}

OPTION-1
execute npm install bootstrap@4 jquery --save
The JavaScript parts of Bootstrap are dependent on jQuery. So you need the jQuery JavaScript library file too.

In your angular.json add the file paths to the styles and scripts array in under build target
NOTE: Before v6 the Angular CLI project configuration was stored in <PATH_TO_PROJECT>/.angular-cli.json. As of v6 the location of the file changed to angular.json. Since there is no longer a leading dot, the file is no longer hidden by default and is on the same level.
which also means that file paths in angular.json should not contain leading dots and slash

i.e you can provide an absolute path instead of a relative path

In .angular-cli.json file Path was "../node_modules/"
In angular.json it is "node_modules/"

 "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/ng6",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css","node_modules/bootstrap/dist/css/bootstrap.min.css"
               
            ],
            "scripts": ["node_modules/jquery/dist/jquery.min.js",
                       "node_modules/bootstrap/dist/js/bootstrap.min.js"]
          },

OPTION 2
Add files from CDN (Content Delivery Network) to your project CDN LINK

Open file src/index.html and insert

the <link> element at the end of the head section to include the Bootstrap CSS file
a <script> element to include jQuery at the bottom of the body section
a <script> element to include Popper.js at the bottom of the body section
a <script> element to include the Bootstrap JavaScript file at the bottom of the body section

  <!doctype html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>Angular</title>
      <base href="/">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="icon" type="image/x-icon" href="favicon.ico">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    </head>
    <body>
      <app-root>Loading...</app-root>
      <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
    </body>
    </html>

OPTION 3
Execute npm install bootstrap
In src/styles.css add the following line:

@import "~bootstrap/dist/css/bootstrap.css";

OPTION-4
ng-bootstrap It contains a set of native Angular directives based on Bootstrap’s markup and CSS. As a result, it's not dependent on jQuery or Bootstrap’s JavaScript

npm install --save @ng-bootstrap/ng-bootstrap

After Installation import it in your root module and register it in @NgModule imports` array

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
@NgModule({
  declarations: [AppComponent, ...],
  imports: [NgbModule.forRoot(), ...],
  bootstrap: [AppComponent]
})

NOTE
ng-bootstrap requires Bootstrap's 4 css to be added in your project. you need to Install it explicitly via:
npm install bootstrap@4 --save In your angular.json add the file paths to the styles array in under build target

   "styles": [
      "src/styles.css",
      "node_modules/bootstrap/dist/css/bootstrap.min.css"
   ],

P.S Do Restart Your server

`ng serve || npm start`

Video file formats supported in iPhone

Quoting the iPhone OS Technology Overview:

iPhone OS provides support for full-screen video playback through the Media Player framework (MediaPlayer.framework). This framework supports the playback of movie files with the .mov, .mp4, .m4v, and .3gp filename extensions and using the following compression standards:

  • H.264 video, up to 1.5 Mbps, 640 by 480 pixels, 30 frames per second, Low-Complexity version of the H.264 Baseline Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
  • H.264 video, up to 768 Kbps, 320 by 240 pixels, 30 frames per second, Baseline Profile up to Level 1.3 with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
  • MPEG-4 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second, Simple Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
  • Numerous audio formats, including the ones listed in “Audio Technologies”

For information about the classes of the Media Player framework, see Media Player Framework Reference.

How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium?

Try using ChromeDriverManager

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager 
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.set_headless()
browser =webdriver.Chrome(ChromeDriverManager().install(),chrome_options=chrome_options)
browser.get('https://google.com')
# capture the screen
browser.get_screenshot_as_file("capture.png")

How to 'restart' an android application programmatically

Checkout intent properties like no history , clear back stack etc ... Intent.setFlags

Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);

How to filter input type="file" dialog by specific file type?

Add a custom attribute to <input type="file" file-accept="jpg gif jpeg png bmp"> and read the filenames within javascript that matches the extension provided by the attribute file-accept. This will be kind of bogus, as a text file with any of the above extension will erroneously deteted as image.

What is lexical scope?

Lets try the shortest possible definition:

Lexical Scoping defines how variable names are resolved in nested functions: inner functions contain the scope of parent functions even if the parent function has returned.

That is all there is to it!

How to split a string literal across multiple lines in C / Objective-C?

GCC adds C++ multiline raw string literals as a C extension

C++11 has raw string literals as mentioned at: https://stackoverflow.com/a/44337236/895245

However, GCC also adds them as a C extension, you just have to use -std=gnu99 instead of -std=c99. E.g.:

main.c

#include <assert.h>
#include <string.h>

int main(void) {
    assert(strcmp(R"(
a
b
)", "\na\nb\n") == 0);
}

Compile and run:

gcc -o main -pedantic -std=gnu99 -Wall -Wextra main.c
./main

This can be used for example to insert multiline inline assembly into C code: How to write multiline inline assembly code in GCC C++?

Now you just have to lay back, and wait for it to be standardized on C20XY.

C++ was asked at: C++ multiline string literal

Tested on Ubuntu 16.04, GCC 6.4.0, binutils 2.26.1.

Load json from local file with http.get() in angular 2

If you are using Angular CLI: 7.3.3 What I did is, On my assets folder I put my fake json data then on my services I just did this.

const API_URL = './assets/data/db.json';

getAllPassengers(): Observable<PassengersInt[]> {
    return this.http.get<PassengersInt[]>(API_URL);
  }

enter image description here

How do I POST with multipart form data using fetch?

I was recently working with IPFS and worked this out. A curl example for IPFS to upload a file looks like this:

curl -i -H "Content-Type: multipart/form-data; boundary=CUSTOM" -d $'--CUSTOM\r\nContent-Type: multipart/octet-stream\r\nContent-Disposition: file; filename="test"\r\n\r\nHello World!\n--CUSTOM--' "http://localhost:5001/api/v0/add"

The basic idea is that each part (split by string in boundary with --) has it's own headers (Content-Type in the second part, for example.) The FormData object manages all this for you, so it's a better way to accomplish our goals.

This translates to fetch API like this:

const formData = new FormData()
formData.append('blob', new Blob(['Hello World!\n']), 'test')

fetch('http://localhost:5001/api/v0/add', {
  method: 'POST',
  body: formData
})
.then(r => r.json())
.then(data => {
  console.log(data)
})

Fatal error: Call to undefined function sqlsrv_connect()

If you are using Microsoft Drivers 3.1, 3.0, and 2.0. Please check your PHP version already install with IIS.

Use this script to check the php version:

<?php echo phpinfo(); ?>

OR

If you have installed PHP Manager in IIS using web platform Installer you can check the version from it.

Then:
If you are using new PHP version (5.6) please download Drivers from here

For PHP version Lower than 5.6 - please download Drivers from here

  • PHP Driver version 3.1 requires PHP 5.4.32, or PHP 5.5.16, or later.
  • PHP Driver version 3.0 requires PHP 5.3.0 or later. If possible, use PHP 5.3.6, or later.
  • PHP Driver version 2.0 driver works with PHP 5.2.4 or later, but not with PHP 5.4. If possible, use PHP 5.2.13, or later.

Then use the PHP Manager to add that downloaded drivers into php config file.You can do it as shown below (browse the files and press OK). Then Restart the IIS Server

enter image description here

If this method not work please change the php version and try to run your php script. enter image description here

Tip:Change the php version to lower and try to understand what happened.then you can download relevant drivers.

Running Facebook application on localhost

In my case the issue revealed to be chrome blocking the CORS request from localhost:4200 to facebook api website. Running Chrome with this setting: "YOUR_PATH_TO_CHROME\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="c:/chrome worked like a charm while developing. Even with no localhost added to facebook app's settings.

Remove '\' char from string c#

Trim only removes characters at the beginning and the end of the string, that's why your code doesn't quite work. You should use Replace instead:

line.Replace(@"\", string.Empty);

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

In a conda environment, this is what solved my problem (I was missing cudart64-100.dll:

  1. Downloaded it from dll-files.com/CUDART64_100.DLL

  2. Put it in my conda environment at C:\Users\<user>\Anaconda3\envs\<env name>\Library\bin

That's all it took! You can double check if it's working:

import tensorflow as tf
tf.config.experimental.list_physical_devices('GPU')

Is Fortran easier to optimize than C for heavy calculations?

I'm a hobbyist programmer and i'm "average" at both language. I find it easier to write fast Fortran code than C (or C++) code. Both Fortran and C are "historic" languages (by today standard), are heavily used, and have well supported free and commercial compiler.

I don't know if it's an historic fact but Fortran feel like it's built to be paralleled/distributed/vectorized/whatever-many-cores-ized. And today it's pretty much the "standard metric" when we're talking about speed : "does it scale ?"

For pure cpu crunching i love Fortran. For anything IO related i find it easier to work with C. (it's difficult in both case anyway).

Now of course, for parallel math intensive code you probably want to use your GPU. Both C and Fortran have a lot of more or less well integrated CUDA/OpenCL interface (and now OpenACC).

My moderately objective answer is : If you know both language equally well/poorly then i think Fortran is faster because i find it easier to write parallel/distributed code in Fortran than C. (once you understood that you can write "freeform" fortran and not just strict F77 code)

Here is a 2nd answer for those willing to downvote me because they don't like the 1st answer : Both language have the features required to write high-performance code. So it's dependent of the algorithm you're implementing (cpu intensive ? io intensive ? memory intensive?), the hardware (single cpu ? multi-core ? distribute supercomputer ? GPGPU ? FPGA ?), your skill and ultimately the compiler itself. Both C and Fortran have awesome compiler. (i'm seriously amazed by how advanced Fortran compilers are but so are C compilers).

PS : i'm glad you specifically excluded libs because i have a great deal of bad stuff to say about Fortran GUI libs. :)

node.js vs. meteor.js what's the difference?

A loose analogy is, "Meteor is to Node as Rails is to Ruby." It's a large, opinionated framework that uses Node on the server. Node itself is just a low-level framework providing functions for sending and receiving HTTP requests and performing other I/O.

Meteor is radically ambitious: By default, every page it serves is actually a Handlebars template that's kept in sync with the server. Try the Leaderboard example: You create a template that simply says "List the names and scores," and every time any client changes a name or score, the page updates with the new data—not just for that client, but for everyone viewing the page.

Another difference: While Node itself is stable and widely used in production, Meteor is in a "preview" state. There are serious bugs, and certain things that don't fit with Meteor's data-centric conceptual model (such as animations) are very hard to do.

If you love playing with new technologies, give Meteor a spin. If you want a more traditional, stable web framework built on Node, take a look at Express.

Customize list item bullets using CSS

I assume you mean the size of the bullet at the start of each list item. If that's the case, you can use an image instead of it:

list-style-image:url('bigger.gif');
list-style-type:none;

If you meant the actual size of the li element, then you can change that as normal with width and height.

How do I update pip itself from inside my virtual environment?

Upgrading pip using 'pip install --upgrade pip' does not always work because of the dreaded cert issue: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version

I like to use the one line command for virtual envs:

curl https://bootstrap.pypa.io/get-pip.py | python -

Or if you want to install it box wide you will need

curl https://bootstrap.pypa.io/get-pip.py | sudo python -

you can give curl a -s flag if you want to silence the output when running in an automation script.

How to check whether a given string is valid JSON in Java

Check whether a given string is valid JSON in Kotlin. I Converted answer of MByD Java to Kotlin

fun isJSONValid(test: String): Boolean {
    try {
        JSONObject(test);
    } catch (ex: JSONException) {
        try {
            JSONArray(test);
        } catch (ex1: JSONException) {
            return false;
        }
    }
    return true;
}

How to hide first section header in UITableView (grouped style)

This is how to hide the first section header in UITableView (grouped style).

Swift 3.0 & Xcode 8.0 Solution

  1. The TableView's delegate should implement the heightForHeaderInSection method

  2. Within the heightForHeaderInSection method, return the least positive number. (not zero!)

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    
        let headerHeight: CGFloat
    
        switch section {
        case 0:
            // hide the header
            headerHeight = CGFloat.leastNonzeroMagnitude
        default:
            headerHeight = 21
        }
    
        return headerHeight
    }
    

How to manually set an authenticated user in Spring Security / SpringMVC

Turn on debug logging to get a better picture of what is going on.

You can tell if the session cookies are being set by using a browser-side debugger to look at the headers returned in HTTP responses. (There are other ways too.)

One possibility is that SpringSecurity is setting secure session cookies, and your next page requested has an "http" URL instead of an "https" URL. (The browser won't send a secure cookie for an "http" URL.)

HTTP Basic: Access denied fatal: Authentication failed

When it asks for username and password. Just add gitlab user name and password for clonning. For the box to pop up asking credentials, do the following:

go to "control panel"-> user accounts-> manage credentials->windows credentials->git:https://[email protected]>click on down arrow-> then click remove.

Hope this helps!

could not extract ResultSet in hibernate

I had similar issue. Try use the HQL editor. It will display you the SQL (as you have a SQL grammar exception). Copy your SQL and execute it separately. In my case the problem was in schema definition. I defined the schema, but I should leave it empty. This raised the same exception as you got. And the error description reflected the actual state, as the schema name was included in SQL statement.

ORA-00060: deadlock detected while waiting for resource

You can get deadlocks on more than just row locks, e.g. see this. The scripts may be competing for other resources, such as index blocks.

I've gotten around this in the past by engineering the parallelism in such a way that different instances are working on portions of the workload that are less likely to affect blocks that are close to each other; for example, for an update of a large table, instead of setting up the parallel slaves using something like MOD(n,10), I'd use TRUNC(n/10) which mean that each slave worked on a contiguous set of data.

There are, of course, much better ways of splitting up a job for parallelism, e.g. DBMS_PARALLEL_EXECUTE.

Not sure why you're getting "PL/SQL successfully completed", perhaps your scripts are handling the exception?

Any good, visual HTML5 Editor or IDE?

Coffee Cup Just released one. July 6, 2010 http://www.coffeecup.com/html-editor/

They now also have an OS X version in beta — see also this stackoverflow post.

Return HTML content as a string, given URL. Javascript Function

you need to return when the readystate==4 e.g.

function httpGet(theUrl)
{
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            return xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET", theUrl, false );
    xmlhttp.send();    
}

What is the height of Navigation Bar in iOS 7?

I got this answer from the book Programming iOS 7, section Bar Position and Bar Metrics

If a navigation bar or toolbar — or a search bar (discussed earlier in this chapter) — is to occupy the top of the screen, the iOS 7 convention is that its height should be increased to underlap the transparent status bar. To make this possible, iOS 7 introduces the notion of a bar position.

UIBarPositionTopAttached

Specifies that the bar is at the top of the screen, as well as its containing view. Bars with this position draw their background extended upwards, allowing their background content to show through the status bar. Available in iOS 7.0 and later.

What's onCreate(Bundle savedInstanceState)

As Dhruv Gairola answered, you can save the state of the application by using Bundle savedInstanceState. I am trying to give a very simple example that new learners like me can understand easily.

Suppose, you have a simple fragment with a TextView and a Button. Each time you clicked the button the text changes. Now, change the orientation of you device/emulator and notice that you lost the data (means the changed data after clicking you got) and fragment starts as the first time again. By using Bundle savedInstanceState we can get rid of this. If you take a look into the life cyle of the fragment.Fragment Lifecylce you will get that a method "onSaveInstanceState" is called when the fragment is about to destroyed.

So, we can save the state means the changed text value into that bundle like this

 int counter  = 0;
 @Override
 public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("value",counter);
 }

After you make the orientation the "onCreate" method will be called right? so we can just do this

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if(savedInstanceState == null){
        //it is the first time the fragment is being called
        counter = 0;
    }else{
        //not the first time so we will check SavedInstanceState bundle
        counter = savedInstanceState.getInt("value",0); //here zero is the default value
    }
}

Now, you won't lose your value after the orientation. The modified value always will be displayed.

ReSharper "Cannot resolve symbol" even when project builds

As you see, the solution is what everyone has already mentioned - simply by Suspending ReSharper, then Clearing the Caches, and finally Resuming it. But, no one mentioned how to do it without closing/restarting Visual Studio.

Just follow these steps:

  1. Getting ReSharper Cache Location

    • Manually by going to ReSharper Options > Environment > General > Store Solution Caches in (Combo Box) (marked 2 in the image). Selecting Custom Folder, then Copying the location of the Caches Folder from the text box shown (marked 3 in the image). Reverting the settings back. The 1 marked shows the ClearCache Button. It's usually wouldn't work so leave it. Image showing the stuff
  2. Suspending ReSharper

    • You can do this by going to Tools > Options > ReSharper Or ReSharper Ultimate > Suspend Now (Button) ReSharper Suspend Option
  3. Clearing the Cache

    • Go to the location copied earlier in step 1 and delete everything in that folder. And yes, I do mean everything.
  4. Resuming ReSharper

    • You can do this by again going to Tools > Options > ReSharper Or ReSharper Ultimate > Resume (Button)

C++ Fatal Error LNK1120: 1 unresolved externals

I have faced this particular error when I didn't defined the main() function. Check if the main() function exists or check the name of the function letter by letter as Timothy described above or check if the file where the main function is located is included to your project.

How to run vi on docker container?

USE THIS:

apt-get update && apt-get install -y vim

Explanation of the above command

  1. apt-get update => Will update the current package
  2. apt-get install => Will install the package
  3. -y => Will by pass the permission, default permission will set to Yes.
  4. vim => Name of the package you want to install.

How can I join on a stored procedure?

Here's a terrible idea for you.

Use an alias, create a new linked server from your server to its own alias.

Now you can do:

select a.SomeColumns, b.OtherColumns
from LocalDb.dbo.LocalTable a
inner join (select * from openquery([AliasToThisServer],'
exec LocalDb.dbo.LocalStoredProcedure
') ) b
on a.Id = b.Id

M_PI works with math.h but not with cmath in Visual Studio

This works for me:

#define _USE_MATH_DEFINES
#include <cmath>
#include <iostream>

using namespace std;

int main()
{
    cout << M_PI << endl;

    return 0;
}

Compiles and prints pi like is should: cl /O2 main.cpp /link /out:test.exe.

There must be a mismatch in the code you have posted and the one you're trying to compile.

Be sure there are no precompiled headers being pulled in before your #define.

Python RuntimeWarning: overflow encountered in long scalars

An easy way to overcome this problem is to use 64 bit type

list = numpy.array(list, dtype=numpy.float64)

How to make layout with View fill the remaining space?

i found

 <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginEnd="10dp"
        android:fontFamily="casual"
        android:text="(By Zeus B0t)"
     ``   android:textSize="10sp"
        android:gravity="bottom"
        android:textStyle="italic" />

Laravel Soft Delete posts

In the Latest version of Laravel i.e above Laravel 5.0. It is quite simple to perform this task. In Model, inside the class just write 'use SoftDeletes'. Example

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model
{
    use SoftDeletes;
}

And In Controller, you can do deletion. Example

User::where('email', '[email protected]')->delete();

or

User::where('email', '[email protected]')->softDeletes();

Make sure that you must have 'deleted_at' column in the users Table.

How to assign name for a screen?

The easiest way use screen with name

screen -S 'name' 'application'
  • Ctrl+a, d = exit and leave application open

Return to screen:

screen -r 'name'

for example using lynx with screen

Create screen:

screen -S lynx lynx

Ctrl+a, d =exit

later you can return with:

screen -r lynx

How to get WooCommerce order details

Accessing direct properties and related are explained

// Get an instance of the WC_Order object
            $order = wc_get_order($order_id);
            $order_data = array(
                    'order_id' => $order->get_id(),
                    'order_number' => $order->get_order_number(),
                    'order_date' => date('Y-m-d H:i:s', strtotime(get_post($order->get_id())->post_date)),
                    'status' => $order->get_status(),
                    'shipping_total' => $order->get_total_shipping(),
                    'shipping_tax_total' => wc_format_decimal($order->get_shipping_tax(), 2),
                    'fee_total' => wc_format_decimal($fee_total, 2),
                    'fee_tax_total' => wc_format_decimal($fee_tax_total, 2),
                    'tax_total' => wc_format_decimal($order->get_total_tax(), 2),
                    'cart_discount' => (defined('WC_VERSION') && (WC_VERSION >= 2.3)) ? wc_format_decimal($order->get_total_discount(), 2) : wc_format_decimal($order->get_cart_discount(), 2),
                    'order_discount' => (defined('WC_VERSION') && (WC_VERSION >= 2.3)) ? wc_format_decimal($order->get_total_discount(), 2) : wc_format_decimal($order->get_order_discount(), 2),
                    'discount_total' => wc_format_decimal($order->get_total_discount(), 2),
                    'order_total' => wc_format_decimal($order->get_total(), 2),
                    'order_currency' => $order->get_currency(),
                    'payment_method' => $order->get_payment_method(),
                    'shipping_method' => $order->get_shipping_method(),
                    'customer_id' => $order->get_user_id(),
                    'customer_user' => $order->get_user_id(),
                    'customer_email' => ($a = get_userdata($order->get_user_id() )) ? $a->user_email : '',
                    'billing_first_name' => $order->get_billing_first_name(),
                    'billing_last_name' => $order->get_billing_last_name(),
                    'billing_company' => $order->get_billing_company(),
                    'billing_email' => $order->get_billing_email(),
                    'billing_phone' => $order->get_billing_phone(),
                    'billing_address_1' => $order->get_billing_address_1(),
                    'billing_address_2' => $order->get_billing_address_2(),
                    'billing_postcode' => $order->get_billing_postcode(),
                    'billing_city' => $order->get_billing_city(),
                    'billing_state' => $order->get_billing_state(),
                    'billing_country' => $order->get_billing_country(),
                    'shipping_first_name' => $order->get_shipping_first_name(),
                    'shipping_last_name' => $order->get_shipping_last_name(),
                    'shipping_company' => $order->get_shipping_company(),
                    'shipping_address_1' => $order->get_shipping_address_1(),
                    'shipping_address_2' => $order->get_shipping_address_2(),
                    'shipping_postcode' => $order->get_shipping_postcode(),
                    'shipping_city' => $order->get_shipping_city(),
                    'shipping_state' => $order->get_shipping_state(),
                    'shipping_country' => $order->get_shipping_country(),
                    'customer_note' => $order->get_customer_note(),
                    'download_permissions' => $order->is_download_permitted() ? $order->is_download_permitted() : 0,
            );

Additional details

  $line_items_shipping = $order->get_items('shipping');
            foreach ($line_items_shipping as $item_id => $item) {
                if (is_object($item)) {
                    if ($meta_data = $item->get_formatted_meta_data('')) :
                        foreach ($meta_data as $meta_id => $meta) :
                            if (in_array($meta->key, $line_items_shipping)) {
                                continue;
                            }
                            // html entity decode is not working preoperly
                            $shipping_items[] = implode('|', array('item:' . wp_kses_post($meta->display_key), 'value:' . str_replace('&times;', 'X', strip_tags($meta->display_value))));
                        endforeach;
                    endif;
                }
            }

            //get fee and total
            $fee_total = 0;
            $fee_tax_total = 0;

            foreach ($order->get_fees() as $fee_id => $fee) {

                $fee_items[] = implode('|', array(
                        'name:' .  html_entity_decode($fee['name'], ENT_NOQUOTES, 'UTF-8'),
                        'total:' . wc_format_decimal($fee['line_total'], 2),
                        'tax:' . wc_format_decimal($fee['line_tax'], 2),
                ));

                $fee_total += $fee['line_total'];
                $fee_tax_total += $fee['line_tax'];
            }

            // get tax items
            foreach ($order->get_tax_totals() as $tax_code => $tax) {            
                $tax_items[] = implode('|', array(
                    'rate_id:'.$tax->id,
                    'code:' . $tax_code,
                    'total:' . wc_format_decimal($tax->amount, 2),
                    'label:'.$tax->label,                
                    'tax_rate_compound:'.$tax->is_compound,
                ));
            }

            // add coupons
            foreach ($order->get_items('coupon') as $_ => $coupon_item) {

                $coupon = new WC_Coupon($coupon_item['name']);

                $coupon_post = get_post((WC()->version < '2.7.0') ? $coupon->id : $coupon->get_id());
                $discount_amount = !empty($coupon_item['discount_amount']) ? $coupon_item['discount_amount'] : 0;
                $coupon_items[] = implode('|', array(
                        'code:' . $coupon_item['name'],
                        'description:' . ( is_object($coupon_post) ? $coupon_post->post_excerpt : '' ),
                        'amount:' . wc_format_decimal($discount_amount, 2),
                ));
            }

            foreach ($order->get_refunds() as $refunded_items){
                $refund_items[] = implode('|', array(
                    'amount:' . $refunded_items->get_amount(),
            'reason:' . $refunded_items->get_reason(),
                    'date:'. date('Y-m-d H-i-s',strtotime((WC()->version < '2.7.0') ? $refunded_items->date_created : $refunded_items->get_date_created())),
                ));
            }

Equivalent of .bat in mac os

The common convention would be to put it in a .sh file that looks like this -

#!/bin/bash
java -cp  ".;./supportlibraries/Framework_Core.jar;... etc

Note that '\' become '/'.

You could execute as

sh myfile.sh

or set the x bit on the file

chmod +x myfile.sh

and then just call

myfile.sh

How to know if two arrays have the same values

A function to Compare two Arrays, to check if both has same elements. Even if they are out of order...

It's good for simple arrays. [String,Number,Boolean,null,NaN].

I don't use .sort(), it modifies the original array. Some say's its bad...

Caution. This function is limited it can't compare Objects"[],{}" or functions within these Arrays, arrays it's self are Objects.

   let arraysHasSameElements = (arr1, arr2) => {
        let count =
            // returns counting of occurrences.
            (arr, val) => arr.reduce((count, curr) => (curr === val ? 1 : 0) + count, 0);

        /* this will return true if lengths of the arrays is equal.
           then compare them.*/
        return arr1.length === arr2.length

            // compare arr1 against arr2.
            && arr1.reduce((checks, val) =>

                /*  creating array of checking if a value has equal amount of occurrences
                    in both arrays, then adds true 'check'. */
                checks.concat(count(arr1, val) === count(arr2, val)), [])

                // checking if each check is equal to true, then .every() returns true.
                .every(check => check);
    }

    let arr1 = ['',-99,true,NaN,21,null,false,'help',-99,'help',NaN], 
        arr2 = [null,-99,'',NaN,NaN,false,true,-99,'help',21,'help'];
    arraysHasSameElements(arr1, arr2); //true

    let arr3 = [false,false,false,false,false,false], 
        arr4 = [false,false,false,false,false,false]
    arraysHasSameElements(arr3, arr4); //true


    // here we have uncommented version.
    let arraysHasSameElements = (arr1, arr2) => {
        let count = (arr, val) => arr.reduce((count, curr) => (curr === val ? 1:0) + count, 0);
        return arr1.length === arr2.length && arr1.reduce((checks, val) =>
            checks.concat(count(arr1, val) === count(arr2, val)), []).every(check => check);
    }

Angular 2 - View not updating after model changes

Instead of dealing with zones and change detection — let AsyncPipe handle complexity. This will put observable subscription, unsubscription (to prevent memory leaks) and changes detection on Angular shoulders.

Change your class to make an observable, that will emit results of new requests:

export class RecentDetectionComponent implements OnInit {

    recentDetections$: Observable<Array<RecentDetection>>;

    constructor(private recentDetectionService: RecentDetectionService) {
    }

    ngOnInit() {
        this.recentDetections$ = Observable.interval(5000)
            .exhaustMap(() => this.recentDetectionService.getJsonFromApi())
            .do(recent => console.log(recent[0].macAddress));
    }
}

And update your view to use AsyncPipe:

<tr *ngFor="let detected of recentDetections$ | async">
    ...
</tr>

Want to add, that it's better to make a service with a method that will take interval argument, and:

  • create new requests (by using exhaustMap like in code above);
  • handle requests errors;
  • stop browser from making new requests while offline.

What's the meaning of System.out.println in Java?

System is a class of java.lang package, out is an object of PrintStream class and also static data member of System class, print() and println() is an instance method of PrintStream class. it is provide soft output on console.

Using awk to print all columns from the nth to the last

Because of a wrong most upvoted anwser with 340 votes, I just lost 5 minutes of my life! Did anybody try this answer out before upvoting this? Apparantly not. Completely useless.

I have a log where after $5 with an IP address can be more text or no text. I need everything from the IP address to the end of the line should there be anything after $5. In my case, this is actualy withn an awk program, not an awk oneliner so awk must solve the problem. When I try to remove the first 4 fields using the most upvoted but completely wrong answer:

echo "  7 27.10.16. Thu 11:57:18 37.244.182.218" | awk '{$1=$2=$3=$4=""; printf "[%s]\n", $0}'

it spits out wrong and useless response (I added [..] to demonstrate):

[    37.244.182.218 one two three]

There are even some sugestions to combine substr with this wrong answer. Like that complication is an improvement.

Instead, if columns are fixed width until the cut point and awk is needed, the correct answer is:

echo "  7 27.10.16. Thu 11:57:18 37.244.182.218" | awk '{printf "[%s]\n", substr($0,28)}'

which produces the desired output:

[37.244.182.218 one two three]

Are lists thread-safe?

Lists themselves are thread-safe. In CPython the GIL protects against concurrent accesses to them, and other implementations take care to use a fine-grained lock or a synchronized datatype for their list implementations. However, while lists themselves can't go corrupt by attempts to concurrently access, the lists's data is not protected. For example:

L[0] += 1

is not guaranteed to actually increase L[0] by one if another thread does the same thing, because += is not an atomic operation. (Very, very few operations in Python are actually atomic, because most of them can cause arbitrary Python code to be called.) You should use Queues because if you just use an unprotected list, you may get or delete the wrong item because of race conditions.

Convert alphabet letters to number in Python

Something like this

[str(ord(c)&31) for c in text]

What causes an HTTP 405 "invalid method (HTTP verb)" error when POSTing a form to PHP on IIS?

I am deploying VB6 IIS Applications to my remote dedicated server with 75 folders. The reason I was getting this error is the Default Document was not set on one of the folders, an oversight, so the URL hitting that folder did not know which page to server up, and thus threw the error mentioned in this thread.

Appending to an empty DataFrame in Pandas?

You can concat the data in this way:

InfoDF = pd.DataFrame()
tempDF = pd.DataFrame(rows,columns=['id','min_date'])

InfoDF = pd.concat([InfoDF,tempDF])

How to initialize const member variable in a class?

The const variable specifies whether a variable is modifiable or not. The constant value assigned will be used each time the variable is referenced. The value assigned cannot be modified during program execution.

Bjarne Stroustrup's explanation sums it up briefly:

A class is typically declared in a header file and a header file is typically included into many translation units. However, to avoid complicated linker rules, C++ requires that every object has a unique definition. That rule would be broken if C++ allowed in-class definition of entities that needed to be stored in memory as objects.

A const variable has to be declared within the class, but it cannot be defined in it. We need to define the const variable outside the class.

T1() : t( 100 ){}

Here the assignment t = 100 happens in initializer list, much before the class initilization occurs.

macro run-time error '9': subscript out of range

Why are you using a macro? Excel has Password Protection built-in. When you select File/Save As... there should be a Tools button by the Save button, click it then "General Options" where you can enter a "Password to Open" and a "Password to Modify".

What is a 'Closure'?

Variable scope

When you declare a local variable, that variable has a scope. Generally, local variables exist only within the block or function in which you declare them.

function() {
  var a = 1;
  console.log(a); // works
}    
console.log(a); // fails

If I try to access a local variable, most languages will look for it in the current scope, then up through the parent scopes until they reach the root scope.

var a = 1;
function() {
  console.log(a); // works
}    
console.log(a); // works

When a block or function is done with, its local variables are no longer needed and are usually blown out of memory.

This is how we normally expect things to work.

A closure is a persistent local variable scope

A closure is a persistent scope which holds on to local variables even after the code execution has moved out of that block. Languages which support closure (such as JavaScript, Swift, and Ruby) will allow you to keep a reference to a scope (including its parent scopes), even after the block in which those variables were declared has finished executing, provided you keep a reference to that block or function somewhere.

The scope object and all its local variables are tied to the function and will persist as long as that function persists.

This gives us function portability. We can expect any variables that were in scope when the function was first defined to still be in scope when we later call the function, even if we call the function in a completely different context.

For example

Here's a really simple example in JavaScript that illustrates the point:

outer = function() {
  var a = 1;
  var inner = function() {
    console.log(a);
  }
  return inner; // this returns a function
}

var fnc = outer(); // execute outer to get inner 
fnc();

Here I have defined a function within a function. The inner function gains access to all the outer function's local variables, including a. The variable a is in scope for the inner function.

Normally when a function exits, all its local variables are blown away. However, if we return the inner function and assign it to a variable fnc so that it persists after outer has exited, all of the variables that were in scope when inner was defined also persist. The variable a has been closed over -- it is within a closure.

Note that the variable a is totally private to fnc. This is a way of creating private variables in a functional programming language such as JavaScript.

As you might be able to guess, when I call fnc() it prints the value of a, which is "1".

In a language without closure, the variable a would have been garbage collected and thrown away when the function outer exited. Calling fnc would have thrown an error because a no longer exists.

In JavaScript, the variable a persists because the variable scope is created when the function is first declared and persists for as long as the function continues to exist.

a belongs to the scope of outer. The scope of inner has a parent pointer to the scope of outer. fnc is a variable which points to inner. a persists as long as fnc persists. a is within the closure.

How to avoid Python/Pandas creating an index in a saved csv?

If you want a good format the next statement is the best:

dataframe_prediction.to_csv('filename.csv', sep=',', encoding='utf-8', index=False)

In this case you have got a csv file with ',' as separate between columns and utf-8 format. In addition, numerical index won't appear.

Display tooltip on Label's hover?

Just set a title on the label:

<label for="male" title="Hello This Will Have Some Value">Hello...</label>

Using jQuery:

<label for="male" data-title="Language" />
<input type="hidden" name="Language" value="Hello This Will Have Some Value">

$("label").prop("title", function() {
    return $("input[name='" + $(this).data("title") + "']").text();
});

If you can use CSS3, you can use the text-overflow: ellipsis; to handle the ellipsis for you so all you need to do is copy the text from the label into the title attribute using jQuery:

HTML:

<label for="male">Hello This Will Have Some Value</label>

CSS:

label {
    display: inline-block;
    width: 50px;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
}

jQuery:

$("label").prop("title", function() {
   return $(this).text(); 
});

Example: http://jsfiddle.net/Xm8Xe/

Finally, if you need robust and cross-browser support, you could use the DotDotDot jQuery plugin.

How can I convert radians to degrees with Python?

I like this method,use sind(x) or cosd(x)

import math

def sind(x):
    return math.sin(math.radians(x))

def cosd(x):
    return math.cos(math.radians(x))

What is the "Temporary ASP.NET Files" folder for?

Thats where asp.net puts dynamically compiled assemblies.

Calculate business days

I had this same need i started with bobbin's first example and ended up with this

  function add_business_days($startdate,$buisnessdays,$holidays=array(),$dateformat){
    $enddate = strtotime($startdate);
    $day = date('N',$enddate);
    while($buisnessdays > 1){
        $enddate = strtotime(date('Y-m-d',$enddate).' +1 day');
        $day = date('N',$enddate);
        if($day < 6 && !in_array($enddate,$holidays))$buisnessdays--;
    }
    return date($dateformat,$enddate);
  }

hth someone

JavaScript, getting value of a td with id name

Have you tried: getElementbyId('ID_OF_ID').innerHTML?

Delete specified file from document directory

Swift 3.0:

func removeImage(itemName:String, fileExtension: String) {
  let fileManager = FileManager.default
  let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  guard let dirPath = paths.first else {
      return
  }  
  let filePath = "\(dirPath)/\(itemName).\(fileExtension)"
  do {
    try fileManager.removeItem(atPath: filePath)
  } catch let error as NSError {
    print(error.debugDescription)
  }}

Thanks to @Anil Varghese, I wrote very similiar code in swift 2.0:

static func removeImage(itemName:String, fileExtension: String) {
  let fileManager = NSFileManager.defaultManager()
  let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
  let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
  let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  guard let dirPath = paths.first else {
    return
  }
  let filePath = "\(dirPath)/\(itemName).\(fileExtension)"
  do {
    try fileManager.removeItemAtPath(filePath)
  } catch let error as NSError {
    print(error.debugDescription)
  }
}

Check if a path represents a file or a folder

To check if a string represents a path or a file programatically, you should use API methods such as isFile(), isDirectory().

How does system understand whether there's a file or a folder?

I guess, the file and folder entries are kept in a data structure and it's managed by the file system.

How to return value from function which has Observable subscription inside?

If you want to pre-subscribe to the same Observable which will be returned, just use

.do():

function getValueFromObservable() {
    return this.store.do(
        (data:any) => {
            console.log("Line 1: " +data);
        }
    );
}

getValueFromObservable().subscribe(
        (data:any) => {
            console.log("Line 2: " +data)
        }
    );

How to modify a CSS display property from JavaScript?

I found the solution.

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

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

And this is working fine.

Thanks everybody ;)

More elegant way of declaring multiple variables at the same time

Sounds like you're approaching your problem the wrong way to me.

Rewrite your code to use a tuple or write a class to store all of the data.

SQL Server reports 'Invalid column name', but the column is present and the query works through management studio

I eventually shut-down and restarted Microsoft SQL Server Management Studio; and that fixed it for me. But at other times, just starting a new query window was enough.

Failed to resolve: com.google.android.gms:play-services in IntelliJ Idea with gradle

I just replaced version 11.2.0 with 11.0.0 and then it seemed to work fine, so that had to mean that 11.2.0 wasn't included with the latest Android SDK.

So, after struggling with all the available scattered documentation, I reached this document by pure chance (I guess it is not indexed high enough by Google): https://developers.google.com/android/guides/releases

I quote from there:

Highlights from the Google Play services 11.2 release. Google Play services dependencies are now available via maven.google.com

Now, even when that shouldn't necessarily mean that they are not available with the downloaded SDK anymore, it seems that this is actually the case.

Anyway, adding google() to my build.gradle didn't work (not found, undefined, or whatever...), so I used a different approach that I found in this document referenced from the previous one:

https://developer.android.com/studio/build/dependencies.html#google-maven

I modified my build.gradle file adding that line to allprojects/repositories, as in:

allprojects {
...
    repositories {
...
        maven { url "https://maven.google.com/"}
    }
}

And then also in the android section in the same build.gradle file:

project(":android") {
...
    dependencies {
...
        compile 'com.google.android.gms:play-services-ads:11.2.0'
    }
}

Those two lines were enough to make Gradle sync without problems. I didn't need to add any plugins apart from the ones that are already added in my libGDX project by default.

After that, I got a few different errors, but none about Gradle or dependencies. In a brief, JFTR:

First, I had a minSdkVersion of 8. Solved by raising it to 14. I think I could live without supporting all those devices below 14.

Second, I had problems with the dex upper limit of references. I've never faced this problem before, but maybe you've already noticed the solution I used: instead of compiling the whole 'com.google.android.gms:play-services' I used only 'com.google.android.gms:play-services-ads' that's the API I'm actually interested right now. For those other particular cases where a solution like this may not be useful, this document could provide some better insight: https://developer.android.com/studio/build/multidex.html

Third, even after that I got this "jumbo" thing problem described and answered here: https://stackoverflow.com/a/26248495/1160360

And that's it. As of now, everything builds and my game does finally shows those Admob banners.

I've spent hours with this, thought, which makes me wonder if all these building automation systems we are using lately are worth the extra load they add.

I mean, the first time I had to add Admob to an app five years ago or so, I just had to download a .jar file and put it on a directory on my project. It was pretty obvious and the whole process, from googling "how to setup Admob in my android project" to have my app showing an Admob banner took me just a few minutes. I'm gonna leave it here, since this is not the place for such kind of debate.

Nonetheless, I hope my own experience is useful for someone else further.

How do I get extra data from intent on Android?

This is for adapter , for activity you just need to change mContext to your Activty name and for fragment you need to change mContext to getActivity()

 public static ArrayList<String> tags_array ;// static array list if you want to pass array data

      public void sendDataBundle(){
            tags_array = new ArrayList();
            tags_array.add("hashtag");//few array data
            tags_array.add("selling");
            tags_array.add("cityname");
            tags_array.add("more");
            tags_array.add("mobile");
            tags_array.add("android");
            tags_array.add("dress");
            Intent su = new Intent(mContext, ViewItemActivity.class);
            Bundle bun1 = new Bundle();
            bun1.putString("product_title","My Product Titile");
            bun1.putString("product_description", "My Product Discription");
            bun1.putString("category", "Product Category");
            bun1.putStringArrayList("hashtag", tags_array);//to pass array list 
            su.putExtras(bun1);
            mContext.startActivity(su);
        }

How can I change the width and height of slides on Slick Carousel?

I know there is already an answer to this but I just found a better solution using the variableWidth parameter, just set it to true in the settings of each breakpoint, like this:

$('#featured-articles').slick({
  arrows: true,
  autoplay: true,
  autoplaySpeed: 3000,
  dots: true,
  draggable: false,
  fade: true,
  infinite: false,
  responsive: [
  {
    breakpoint: 620,
    settings: {
        arrows: true,
        variableWidth: true
    }
  },
  {
    breakpoint: 345,
    settings: {
        arrows: true,
        variableWidth: true
    }
  }
  ]
});

How to print binary tree diagram?

See also these answers.

In particular it wasn't too difficult to use abego TreeLayout to produce results shown below with the default settings.

If you try that tool, note this caveat: It prints children in the order they were added. For a BST where left vs right matters I found this library to be inappropriate without modification.

Also, the method to add children simply takes a parent and child node as parameters. (So to process a bunch of nodes, you must take the first one separately to create a root.)

I ended up using this solution above, modifying it to take in the type <Node> so as to have access to Node's left and right (children).

tree created with abego TreeLayout

Color text in discord

Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.

Option #1 (Markdown code-blocks)

Discord supports Markdown and uses highlight.js to highlight code-blocks. Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.

To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).

```language
message
```

Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).

Option #2 (Embeds)

Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.

(Embed Cheat-sheet)
Embed Cheat-sheet

PHP Checking if the current date is before or after a set date

a MySQL-only solution would be something like this:

SELECT IF (UNIX_TIMESTAMP(`field`) > UNIX_TIMESTAMP(), `field`,'GO AHEAD') as `yourdate`
FROM `table`

Raise an event whenever a property's value changed?

The INotifyPropertyChanged interface is implemented with events. The interface has just one member, PropertyChanged, which is an event that consumers can subscribe to.

The version that Richard posted is not safe. Here is how to safely implement this interface:

public class MyClass : INotifyPropertyChanged
{
    private string imageFullPath;

    protected void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler(this, e);
    }

    protected void OnPropertyChanged(string propertyName)
    {
        OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
    }

    public string ImageFullPath
    {
        get { return imageFullPath; }
        set
        {
            if (value != imageFullPath)
            {
                imageFullPath = value;
                OnPropertyChanged("ImageFullPath");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

Note that this does the following things:

  • Abstracts the property-change notification methods so you can easily apply this to other properties;

  • Makes a copy of the PropertyChanged delegate before attempting to invoke it (failing to do this will create a race condition).

  • Correctly implements the INotifyPropertyChanged interface.

If you want to additionally create a notification for a specific property being changed, you can add the following code:

protected void OnImageFullPathChanged(EventArgs e)
{
    EventHandler handler = ImageFullPathChanged;
    if (handler != null)
        handler(this, e);
}

public event EventHandler ImageFullPathChanged;

Then add the line OnImageFullPathChanged(EventArgs.Empty) after the line OnPropertyChanged("ImageFullPath").

Since we have .Net 4.5 there exists the CallerMemberAttribute, which allows to get rid of the hard-coded string for the property name in the source code:

    protected void OnPropertyChanged(
        [System.Runtime.CompilerServices.CallerMemberName] string propertyName = "")
    {
        OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
    }

    public string ImageFullPath
    {
        get { return imageFullPath; }
        set
        {
            if (value != imageFullPath)
            {
                imageFullPath = value;
                OnPropertyChanged();
            }
        }
    }

Connection to SQL Server Works Sometimes

I fixed this error on Windows Server 2012 and SQL Server 2012 by enabling IPv6 and unblocking the inbound port 1433.

How to extract URL parameters from a URL with Ruby or Rails?

There more than one ways, to solve your problem. Others has shown you the some tricks. I know another trick. Here is my try :-

require 'uri'
url = "http://www.example.com/something?param1=value1&param2=value2&param3=value3"
uri = URI(url)
# => #<URI::HTTP:0x89e4898 URL:http://www.example.com/something?param1=value1&param2=value2&param3=value3>
URI::decode_www_form(uri.query).to_h # if you are in 2.1 or later version of Ruby
# => {"param1"=>"value1", "param2"=>"value2", "param3"=>"value3"}
Hash[URI::decode_www_form(uri.query)] # if you are below 2.1 version of Ruby
# => {"param1"=>"value1", "param2"=>"value2", "param3"=>"value3"}

Read the method docomentation of ::decode_www_form.

CSS :not(:last-child):after selector

Your sample does not work in IE for me, you have to specify Doctype header in your document to render your page in standard way in IE to use the content CSS property:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<head>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<html>

<ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
    <li>Five</li>
</ul>

</html>

Second way is to use CSS 3 selectors

li:not(:last-of-type):after
{
    content:           " |";
}

But you still need to specify Doctype

And third way is to use JQuery with some script like following:

<script type="text/javascript" src="jquery-1.4.1.js"></script>
<link href="style2.css" rel="stylesheet" type="text/css">
</head>
<html>

<ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
    <li>Five</li>
</ul>

<script type="text/javascript">
  $(document).ready(function () {
      $("li:not(:last)").append(" | ");
    });
</script>

Advantage of third way is that you dont have to specify doctype and jQuery will take care of compatibility.

Counting inversions in an array

I've found it in O(n * log n) time by the following method.

  1. Merge sort array A and create a copy (array B)
  2. Take A[1] and find its position in sorted array B via a binary search. The number of inversions for this element will be one less than the index number of its position in B since every lower number that appears after the first element of A will be an inversion.

    2a. accumulate the number of inversions to counter variable num_inversions.

    2b. remove A[1] from array A and also from its corresponding position in array B

  3. rerun from step 2 until there are no more elements in A.

Here’s an example run of this algorithm. Original array A = (6, 9, 1, 14, 8, 12, 3, 2)

1: Merge sort and copy to array B

B = (1, 2, 3, 6, 8, 9, 12, 14)

2: Take A[1] and binary search to find it in array B

A[1] = 6

B = (1, 2, 3, 6, 8, 9, 12, 14)

6 is in the 4th position of array B, thus there are 3 inversions. We know this because 6 was in the first position in array A, thus any lower value element that subsequently appears in array A would have an index of j > i (since i in this case is 1).

2.b: Remove A[1] from array A and also from its corresponding position in array B (bold elements are removed).

A = (6, 9, 1, 14, 8, 12, 3, 2) = (9, 1, 14, 8, 12, 3, 2)

B = (1, 2, 3, 6, 8, 9, 12, 14) = (1, 2, 3, 8, 9, 12, 14)

3: Rerun from step 2 on the new A and B arrays.

A[1] = 9

B = (1, 2, 3, 8, 9, 12, 14)

9 is now in the 5th position of array B, thus there are 4 inversions. We know this because 9 was in the first position in array A, thus any lower value element that subsequently appears would have an index of j > i (since i in this case is again 1). Remove A[1] from array A and also from its corresponding position in array B (bold elements are removed)

A = (9, 1, 14, 8, 12, 3, 2) = (1, 14, 8, 12, 3, 2)

B = (1, 2, 3, 8, 9, 12, 14) = (1, 2, 3, 8, 12, 14)

Continuing in this vein will give us the total number of inversions for array A once the loop is complete.

Step 1 (merge sort) would take O(n * log n) to execute. Step 2 would execute n times and at each execution would perform a binary search that takes O(log n) to run for a total of O(n * log n). Total running time would thus be O(n * log n) + O(n * log n) = O(n * log n).

Thanks for your help. Writing out the sample arrays on a piece of paper really helped to visualize the problem.

Get difference between 2 dates in JavaScript?

var date1 = new Date("7/11/2010");
var date2 = new Date("8/11/2010");
var diffDays = parseInt((date2 - date1) / (1000 * 60 * 60 * 24), 10); 

alert(diffDays )

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required?

enter image description here Make sure that Access less secure app is allowed.

        MailMessage mail = new MailMessage();
        mail.From = new MailAddress("[email protected]");
        mail.Sender = new MailAddress("[email protected]");
        mail.To.Add("external@emailaddress");
        mail.IsBodyHtml = true;
        mail.Subject = "Email Sent";
        mail.Body = "Body content from";

        SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
        smtp.UseDefaultCredentials = false;

        smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "xx");
        smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtp.EnableSsl = true;

        smtp.Timeout = 30000;
        try
        {

            smtp.Send(mail);
        }
        catch (SmtpException e)
        {
            textBox1.Text= e.Message;
        }

Using Rsync include and exclude options to include directory and file by pattern

rsync include exclude pattern examples:

"*"         means everything
"dir1"      transfers empty directory [dir1]
"dir*"      transfers empty directories like: "dir1", "dir2", "dir3", etc...
"file*"     transfers files whose names start with [file]
"dir**"     transfers every path that starts with [dir] like "dir1/file.txt", "dir2/bar/ffaa.html", etc...
"dir***"    same as above
"dir1/*"    does nothing
"dir1/**"   does nothing
"dir1/***"  transfers [dir1] directory and all its contents like "dir1/file.txt", "dir1/fooo.sh", "dir1/fold/baar.py", etc...

And final note is that simply dont rely on asterisks that are used in the beginning for evaluating paths; like "**dir" (its ok to use them for single folders or files but not paths) and note that more than two asterisks dont work for file names.

How to add style from code behind?

try this

 lblMsg.Text = @"Your search result for <b style=""color:green;"">" + txtCode.Text.Trim() + "</b> ";

SQL Server - boolean literal?

Most databases will accept this:

select * from SomeTable where true

However some databases (eg SQL Server, Oracle) do not have a boolean type. In these cases you may use:

select * from SomeTable where 1=1

BTW, if building up an sql where clause by hand, this is the basis for simplifying your code because you can avoid having to know if the condition you're about to add to a where clause is the first one (which should be preceded by "WHERE"), or a subsequent one (which should be preceded by "AND"). By always starting with "WHERE 1=1", all conditions (if any) added to the where clause are preceded by "AND".

Set output of a command as a variable (with pipes)

In a batch file I usually create a file in the temp directory and append output from a program, then I call it with a variable-name to set that variable. Like this:

:: Create a set_var.cmd file containing: set %1=
set /p="set %%1="<nul>"%temp%\set_var.cmd"

:: Append output from a command
ipconfig | find "IPv4" >> "%temp%\set_var.cmd"
call "%temp%\set_var.cmd" IPAddress
echo %IPAddress%

Send FormData and String Data Together Through JQuery AJAX?

For Multiple file input : Try this code :

 <form name="form" id="form" method="post" enctype="multipart/form-data">
    <input type="file" name="file[]">
    <input type="file" name="file[]" >
    <input type="text" name="name" id="name">
    <input type="text" name="name1" id="name1">
    <input type="button" name="submit" value="upload" id="upload">
 </form>


 $('#upload').on('click', function() {
  var fd = new FormData();
    var c=0;
    var file_data;
    $('input[type="file"]').each(function(){
        file_data = $('input[type="file"]')[c].files; // for multiple files

     for(var i = 0;i<file_data.length;i++){
         fd.append("file_"+c, file_data[i]);
     }
    c++;
 }); 
     var other_data = $('form').serializeArray();
     $.each(other_data,function(key,input){
         fd.append(input.name,input.value);
     });
     $.ajax({
         url: 'work.php',
         data: fd,
         contentType: false,
         processData: false,
         type: 'POST',
         success: function(data){
             console.log(data);
         }
     });
 });

What is the use of the JavaScript 'bind' method?

Consider the Simple Program listed below,

//we create object user
let User = { name: 'Justin' };

//a Hello Function is created to Alert the object User 
function Hello() {
  alert(this.name);
}

//since there the value of this is lost we need to bind user to use this keyword
let user = Hello.bind(User);
user();

//we create an instance to refer the this keyword (this.name);

Choose File Dialog

Thanx schwiz for idea! Here is modified solution:

public class FileDialog {
    private static final String PARENT_DIR = "..";
    private final String TAG = getClass().getName();
    private String[] fileList;
    private File currentPath;
    public interface FileSelectedListener {
        void fileSelected(File file);
    }
    public interface DirectorySelectedListener {
        void directorySelected(File directory);
    }
    private ListenerList<FileSelectedListener> fileListenerList = new ListenerList<FileDialog.FileSelectedListener>();
    private ListenerList<DirectorySelectedListener> dirListenerList = new ListenerList<FileDialog.DirectorySelectedListener>();
    private final Activity activity;
    private boolean selectDirectoryOption;
    private String fileEndsWith;    

    /**
    * @param activity 
    * @param initialPath
    */
    public FileDialog(Activity activity, File initialPath) {
        this(activity, initialPath, null);
    }

    public FileDialog(Activity activity, File initialPath, String fileEndsWith) {
        this.activity = activity;
        setFileEndsWith(fileEndsWith);
        if (!initialPath.exists()) initialPath = Environment.getExternalStorageDirectory();
            loadFileList(initialPath);
    }

    /**
    * @return file dialog
    */
    public Dialog createFileDialog() {
        Dialog dialog = null;
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);

        builder.setTitle(currentPath.getPath());
        if (selectDirectoryOption) {
            builder.setPositiveButton("Select directory", new OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Log.d(TAG, currentPath.getPath());
                    fireDirectorySelectedEvent(currentPath);
                }
            });
        }

        builder.setItems(fileList, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                String fileChosen = fileList[which];
                File chosenFile = getChosenFile(fileChosen);
                if (chosenFile.isDirectory()) {
                    loadFileList(chosenFile);
                    dialog.cancel();
                    dialog.dismiss();
                    showDialog();
                } else fireFileSelectedEvent(chosenFile);
            }
        });

        dialog = builder.show();
        return dialog;
    }


    public void addFileListener(FileSelectedListener listener) {
        fileListenerList.add(listener);
    }

    public void removeFileListener(FileSelectedListener listener) {
        fileListenerList.remove(listener);
    }

    public void setSelectDirectoryOption(boolean selectDirectoryOption) {
        this.selectDirectoryOption = selectDirectoryOption;
    }

    public void addDirectoryListener(DirectorySelectedListener listener) {
        dirListenerList.add(listener);
    }

    public void removeDirectoryListener(DirectorySelectedListener listener) {
        dirListenerList.remove(listener);
    }

    /**
    * Show file dialog
    */
    public void showDialog() {
        createFileDialog().show();
    }

    private void fireFileSelectedEvent(final File file) {
        fileListenerList.fireEvent(new FireHandler<FileDialog.FileSelectedListener>() {
            public void fireEvent(FileSelectedListener listener) {
                listener.fileSelected(file);
            }
        });
    }

    private void fireDirectorySelectedEvent(final File directory) {
        dirListenerList.fireEvent(new FireHandler<FileDialog.DirectorySelectedListener>() {
            public void fireEvent(DirectorySelectedListener listener) {
                listener.directorySelected(directory);
            }
        });
    }

    private void loadFileList(File path) {
        this.currentPath = path;
        List<String> r = new ArrayList<String>();
        if (path.exists()) {
            if (path.getParentFile() != null) r.add(PARENT_DIR);
            FilenameFilter filter = new FilenameFilter() {
                public boolean accept(File dir, String filename) {
                    File sel = new File(dir, filename);
                    if (!sel.canRead()) return false;
                    if (selectDirectoryOption) return sel.isDirectory();
                    else {
                        boolean endsWith = fileEndsWith != null ? filename.toLowerCase().endsWith(fileEndsWith) : true;
                        return endsWith || sel.isDirectory();
                    }
                }
            };
            String[] fileList1 = path.list(filter);
            for (String file : fileList1) {
                r.add(file);
            }
        }
        fileList = (String[]) r.toArray(new String[]{});
    }

    private File getChosenFile(String fileChosen) {
        if (fileChosen.equals(PARENT_DIR)) return currentPath.getParentFile();
        else return new File(currentPath, fileChosen);
    }

    private void setFileEndsWith(String fileEndsWith) {
        this.fileEndsWith = fileEndsWith != null ? fileEndsWith.toLowerCase() : fileEndsWith;
    }
}

class ListenerList<L> {
    private List<L> listenerList = new ArrayList<L>();

    public interface FireHandler<L> {
        void fireEvent(L listener);
    }

    public void add(L listener) {
        listenerList.add(listener);
    }

    public void fireEvent(FireHandler<L> fireHandler) {
        List<L> copy = new ArrayList<L>(listenerList);
        for (L l : copy) {
            fireHandler.fireEvent(l);
        }
    }

    public void remove(L listener) {
        listenerList.remove(listener);
    }

    public List<L> getListenerList() {
        return listenerList;
    }
}

Use it on activity onCreate (directory selection option is commented):

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    File mPath = new File(Environment.getExternalStorageDirectory() + "//DIR//");
    fileDialog = new FileDialog(this, mPath, ".txt");
    fileDialog.addFileListener(new FileDialog.FileSelectedListener() {
        public void fileSelected(File file) {
            Log.d(getClass().getName(), "selected file " + file.toString());
        }
    });
    //fileDialog.addDirectoryListener(new FileDialog.DirectorySelectedListener() {
    //  public void directorySelected(File directory) {
    //      Log.d(getClass().getName(), "selected dir " + directory.toString());
    //  }
    //});
    //fileDialog.setSelectDirectoryOption(false);
    fileDialog.showDialog();
}

How to bind an enum to a combobox control in WPF?

You'll need to create an array of the values in the enum, which can be created by calling System.Enum.GetValues(), passing it the Type of the enum that you want the items of.

If you specify this for the ItemsSource property, then it should be populated with all of the enum's values. You probably want to bind SelectedItem to EffectStyle (assuming it is a property of the same enum, and contains the current value).

How to delete multiple files at once in Bash on Linux?

I am not a linux guru, but I believe you want to pipe your list of output files to xargs rm -rf. I have used something like this in the past with good results. Test on a sample directory first!

EDIT - I might have misunderstood, based on the other answers that are appearing. If you can use wildcards, great. I assumed that your original list that you displayed was generated by a program to give you your "selection", so I thought piping to xargs would be the way to go.

Simulate a button click in Jest

You may use something like this to call the handler written on click:

import { shallow } from 'enzyme'; // Mount is not required

page = <MyCoolPage />;
pageMounted = shallow(page);

// The below line will execute your click function
pageMounted.instance().yourOnClickFunction();

DateTime to javascript date

JavaScript Date constructor accepts number of milliseconds since Unix epoch (1 January 1970 00:00:00 UTC). Here’s C# extension method that converts .Net DateTime object to JavaScript date:

public static class DateTimeJavaScript
{
   private static readonly long DatetimeMinTimeTicks =
      (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).Ticks;

   public static long ToJavaScriptMilliseconds(this DateTime dt)
   {
      return (long)((dt.ToUniversalTime().Ticks - DatetimeMinTimeTicks) / 10000);
   }
}

JavaScript Usage:

var dt = new Date(<%= DateTime.Today.ToJavaScriptMilliseconds() %>);
alert(dt);

Writing image to local server

Cleanest way of saving image locally using request:

const request = require('request');
request('http://link/to/your/image/file.png').pipe(fs.createWriteStream('fileName.png'))

If you need to add authentication token in headers do this:

const request = require('request');
request({
        url: 'http://link/to/your/image/file.png',
        headers: {
            "X-Token-Auth": TOKEN,
        }
    }).pipe(fs.createWriteStream('filename.png'))                    

Creating a singleton in Python

You probably never need a singleton in Python. Just define all your data and functions in a module and you have a de facto singleton:

import datetime
file_name=None

def set_file_name(new_file_name: str):
    global file_name
    file_name=new_file_name

def write(message: str):
    global file_name
    if file_name:
        with open(file_name, 'a+') as f:
            f.write("{} {}\n".format(datetime.datetime.now(), message))
    else:
        print("LOG: {}", message)

To use:

    import log
    log.set_file_name("debug.log")
    log.write("System starting")
    ...

If you really absolutely have to have a singleton class then I'd go with:

    class My_Singleton(object):
        def foo(self):
            pass

    my_singleton = My_Singleton()

To use:

    from mysingleton import my_singleton
    my_singleton.foo()

where mysingleton.py is your filename that My_Singleton is defined in. This works because after the first time a file is imported, Python doesn't re-execute the code.

How to remove the last character from a string?

How can a simple task be made complicated. My solution is:

public String removeLastChar(String s) {
    return s[0..-1]
}

or

public String removeLastChar(String s) {
    if (s.length() > 0) {
        return s[0..-1]
    }
    return s
}

How To Upload Files on GitHub

Here are the steps (in-short), since I don't know what exactly you have done:
1. Download and install Git on your system: http://git-scm.com/downloads
2. Using the Git Bash (a command prompt for Git) or your system's native command prompt, set up a local git repository.
3. Use the same console to checkout, commit, push, etc. the files on the Git.

Hope this helps to those who come searching here.

Add and remove a class on click using jQuery?

Why not try something like this?

$('#menu li a').on('click', function(){
    $('#menu li a.current').removeClass('current');
    $(this).addClass('current');
});

JSFiddle

What's the best way to set a single pixel in an HTML5 canvas?

It seems strange, but nonetheless HTML5 supports drawing lines, circles, rectangles and many other basic shapes, it does not have anything suitable for drawing the basic point. The only way to do so is to simulate point with whatever you have.

So basically there are 3 possible solutions:

  • draw point as a line
  • draw point as a polygon
  • draw point as a circle

Each of them has their drawbacks


Line

function point(x, y, canvas){
  canvas.beginPath();
  canvas.moveTo(x, y);
  canvas.lineTo(x+1, y+1);
  canvas.stroke();
}

Keep in mind that we are drawing to South-East direction, and if this is the edge, there can be a problem. But you can also draw in any other direction.


Rectangle

function point(x, y, canvas){
  canvas.strokeRect(x,y,1,1);
}

or in a faster way using fillRect because render engine will just fill one pixel.

function point(x, y, canvas){
  canvas.fillRect(x,y,1,1);
}

Circle


One of the problems with circles is that it is harder for an engine to render them

function point(x, y, canvas){
  canvas.beginPath();
  canvas.arc(x, y, 1, 0, 2 * Math.PI, true);
  canvas.stroke();
}

the same idea as with rectangle you can achieve with fill.

function point(x, y, canvas){
  canvas.beginPath();
  canvas.arc(x, y, 1, 0, 2 * Math.PI, true);
  canvas.fill();
}

Problems with all these solutions:

  • it is hard to keep track of all the points you are going to draw.
  • when you zoom in, it looks ugly.

If you are wondering, "What is the best way to draw a point?", I would go with filled rectangle. You can see my jsperf here with comparison tests.

Editor does not contain a main type in Eclipse

Right click on Sample.java file and delete it. Now go to File -> New -> Class , enter name of program (i.e. hello) , click on finish . It will create file hello.java. Enter source code of program and finallly press ctrl + F11

click here to see screenshot1

click here to see screenshot2

What are WSDL, SOAP and REST?

You're not going to "simply" understand something complex.

WSDL is an XML-based language for describing a web service. It describes the messages, operations, and network transport information used by the service. These web services usually use SOAP, but may use other protocols.

A WSDL is readable by a program, and so may be used to generate all, or part of the client code necessary to call the web service. This is what it means to call SOAP-based web services "self-describing".

REST is not related to WSDL at all.

Windows equivalent to UNIX pwd

It is cd for "current directory".

What data type to use for hashed password field and what length?

Always use a password hashing algorithm: Argon2, scrypt, bcrypt or PBKDF2.

Argon2 won the 2015 password hashing competition. Scrypt, bcrypt and PBKDF2 are older algorithms that are considered less preferred now, but still fundamentally sound, so if your platform doesn't support Argon2 yet, it's ok to use another algorithm for now.

Never store a password directly in a database. Don't encrypt it, either: otherwise, if your site gets breached, the attacker gets the decryption key and so can obtain all passwords. Passwords MUST be hashed.

A password hash has different properties from a hash table hash or a cryptographic hash. Never use an ordinary cryptographic hash such as MD5, SHA-256 or SHA-512 on a password. A password hashing algorithm uses a salt, which is unique (not used for any other user or in anybody else's database). The salt is necessary so that attackers can't just pre-calculate the hashes of common passwords: with a salt, they have to restart the calculation for every account. A password hashing algorithm is intrinsically slow — as slow as you can afford. Slowness hurts the attacker a lot more than you because the attacker has to try many different passwords. For more information, see How to securely hash passwords.

A password hash encodes four pieces of information:

  • An indicator of which algorithm is used. This is necessary for agility: cryptographic recommendations change over time. You need to be able to transition to a new algorithm.
  • A difficulty or hardness indicator. The higher this value, the more computation is needed to calculate the hash. This should be a constant or a global configuration value in the password change function, but it should increase over time as computers get faster, so you need to remember the value for each account. Some algorithms have a single numerical value, others have more parameters there (for example to tune CPU usage and RAM usage separately).
  • The salt. Since the salt must be globally unique, it has to be stored for each account. The salt should be generated randomly on each password change.
  • The hash proper, i.e. the output of the mathematical calculation in the hashing algorithm.

Many libraries include a pair functions that conveniently packages this information as a single string: one that takes the algorithm indicator, the hardness indicator and the password, generates a random salt and returns the full hash string; and one that takes a password and the full hash string as input and returns a boolean indicating whether the password was correct. There's no universal standard, but a common encoding is

$algorithm$parameters$salt$output

where algorithm is a number or a short alphanumeric string encoding the choice of algorithm, parameters is a printable string, and salt and output are encoded in Base64 without terminating =.

16 bytes are enough for the salt and the output. (See e.g. recommendations for Argon2.) Encoded in Base64, that's 21 characters each. The other two parts depend on the algorithm and parameters, but 20–40 characters are typical. That's a total of about 82 ASCII characters (CHAR(82), and no need for Unicode), to which you should add a safety margin if you think it's going to be difficult to enlarge the field later.

If you encode the hash in a binary format, you can get it down to 1 byte for the algorithm, 1–4 bytes for the hardness (if you hard-code some of the parameters), and 16 bytes each for the salt and output, for a total of 37 bytes. Say 40 bytes (BINARY(40)) to have at least a couple of spare bytes. Note that these are 8-bit bytes, not printable characters, in particular the field can include null bytes.

Note that the length of the hash is completely unrelated to the length of the password.

Java GUI frameworks. What to choose? Swing, SWT, AWT, SwingX, JGoodies, JavaFX, Apache Pivot?

Decision tree:

  1. Frameworks like Qt and SWT need native DLLs. So you have to ask yourself: Are all necessary platforms supported? Can you package the native DLLs with your app?

    See here, how to do this for SWT.

    If you have a choice here, you should prefer Qt over SWT. Qt has been developed by people who understand UI and the desktop while SWT has been developed out of necessity to make Eclipse faster. It's more a performance patch for Java 1.4 than a UI framework. Without JFace, you're missing many major UI components or very important features of UI components (like filtering on tables).

    If SWT is missing a feature that you need, the framework is somewhat hostile to extending it. For example, you can't extend any class in it (the classes aren't final, they just throw exceptions when the package of this.getClass() isn't org.eclipse.swt and you can't add new classes in that package because it's signed).

  2. If you need a native, pure Java solution, that leaves you with the rest. Let's start with AWT, Swing, SwingX - the Swing way.

    AWT is outdated. Swing is outdated (maybe less so but not much work has been done on Swing for the past 10 years). You could argue that Swing was good to begin with but we all know that code rots. And that's especially true for UIs today.

    That leaves you with SwingX. After a longer period of slow progress, development has picked up again. The major drawback with Swing is that it hangs on to some old ideas which very kind of bleeding edge 15 years ago but which feel "clumsy" today. For example, the table views do support filtering and sorting but you still have to configure this. You'll have to write a lot of boiler plate code just to get a decent UI that feels modern.

    Another weak area is theming. As of today, there are a lot of themes around. See here for a top 10. But some are slow, some are buggy, some are incomplete. I hate it when I write a UI and users complain that something doesn't work for them because they selected an odd theme.

  3. JGoodies is another layer on top of Swing, like SwingX. It tries to make Swing more pleasant to use. The web site looks great. Let's have a look at the tutorial ... hm ... still searching ... hang on. It seems that there is no documentation on the web site at all. Google to the rescue. Nope, no useful tutorials at all.

    I'm not feeling confident with a UI framework that tries so hard to hide the documentation from potential new fans. That doesn't mean JGoodies is bad; I just couldn't find anything good to say about it but that it looks nice.

  4. JavaFX. Great, stylish. Support is there but I feel it's more of a shiny toy than a serious UI framework. This feeling roots in the lack of complex UI components like tree tables. There is a webkit-based component to display HTML.

    When it was introduced, my first thought was "five years too late." If your aim is a nice app for phones or web sites, good. If your aim is professional desktop application, make sure it delivers what you need.

  5. Pivot. First time I heard about it. It's basically a new UI framework based on Java2D. So I gave it a try yesterday. No Swing, just tiny bit of AWT (new Font(...)).

    My first impression was a nice one. There is an extensive documentation that helps you getting started. Most of the examples come with live demos (Note: You must have Java enabled in your web browser; this is a security risk) in the web page, so you can see the code and the resulting application side by side.

    In my experience, more effort goes into code than into documentation. By looking at the Pivot docs, a lot of effort must have went into the code. Note that there is currently a bug which prevents some of the examples to work (PIVOT-858) in your browser.

    My second impression of Pivot is that it's easy to use. When I ran into a problem, I could usually solve it quickly by looking at an example. I'm missing a reference of all the styles which each component supports, though.

    As with JavaFX, it's missing some higher level components like a tree table component (PIVOT-306). I didn't try lazy loading with the table view. My impression is that if the underlying model uses lazy loading, then that's enough.

    Promising. If you can, give it a try.

Android: ProgressDialog.show() crashes with getApplicationContext

This is a common problem. Use this instead of getApplicationContext() That should solve your problem

Why do we need middleware for async flow in Redux?

OK, let's start to see how middleware working first, that quite answer the question, this is the source code applyMiddleWare function in Redux:

function applyMiddleware() {
  for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) {
    middlewares[_key] = arguments[_key];
  }

  return function (createStore) {
    return function (reducer, preloadedState, enhancer) {
      var store = createStore(reducer, preloadedState, enhancer);
      var _dispatch = store.dispatch;
      var chain = [];

      var middlewareAPI = {
        getState: store.getState,
        dispatch: function dispatch(action) {
          return _dispatch(action);
        }
      };
      chain = middlewares.map(function (middleware) {
        return middleware(middlewareAPI);
      });
      _dispatch = compose.apply(undefined, chain)(store.dispatch);

      return _extends({}, store, {
        dispatch: _dispatch
      });
    };
  };
}

Look at this part, see how our dispatch become a function.

  ...
  getState: store.getState,
  dispatch: function dispatch(action) {
  return _dispatch(action);
}
  • Note that each middleware will be given the dispatch and getState functions as named arguments.

OK, this is how Redux-thunk as one of the most used middlewares for Redux introduce itself:

Redux Thunk middleware allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met. The inner function receives the store methods dispatch and getState as parameters.

So as you see, it will return a function instead an action, means you can wait and call it anytime you want as it's a function...

So what the heck is thunk? That's how it's introduced in Wikipedia:

In computer programming, a thunk is a subroutine used to inject an additional calculation into another subroutine. Thunks are primarily used to delay a calculation until it is needed, or to insert operations at the beginning or end of the other subroutine. They have a variety of other applications to compiler code generation and in modular programming.

The term originated as a jocular derivative of "think".

A thunk is a function that wraps an expression to delay its evaluation.

//calculation of 1 + 2 is immediate 
//x === 3 
let x = 1 + 2;

//calculation of 1 + 2 is delayed 
//foo can be called later to perform the calculation 
//foo is a thunk! 
let foo = () => 1 + 2;

So see how easy the concept is and how it can help you manage your async actions...

That's something you can live without it, but remember in programming there are always better, neater and proper ways to do things...

Apply middleware Redux

How to highlight text using javascript

I have the same problem, a bunch of text comes in through a xmlhttp request. This text is html formatted. I need to highlight every occurrence.

str='<img src="brown fox.jpg" title="The brown fox" />'
    +'<p>some text containing fox.</p>'

The problem is that I don't need to highlight text in tags. For example I need to highlight fox:

Now I can replace it with:

var word="fox";
word="(\\b"+ 
    word.replace(/([{}()[\]\\.?*+^$|=!:~-])/g, "\\$1")
        + "\\b)";
var r = new RegExp(word,"igm");
str.replace(r,"<span class='hl'>$1</span>")

To answer your question: you can leave out the g in regexp options and only first occurrence will be replaced but this is still the one in the img src property and destroys the image tag:

<img src="brown <span class='hl'>fox</span>.jpg" title="The brown <span 
class='hl'>fox</span> />

This is the way I solved it but was wondering if there is a better way, something I've missed in regular expressions:

str='<img src="brown fox.jpg" title="The brown fox" />'
    +'<p>some text containing fox.</p>'
var word="fox";
word="(\\b"+ 
    word.replace(/([{}()[\]\\.?*+^$|=!:~-])/g, "\\$1")
    + "\\b)";
var r = new RegExp(word,"igm");
str.replace(/(>[^<]+<)/igm,function(a){
    return a.replace(r,"<span class='hl'>$1</span>");
});

Git status ignore line endings / identical files / windows & linux environment / dropbox / mled

Try setting core.autocrlf value like this :

git config --global core.autocrlf true

How to make Java Set?

Like this:

import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);

Or adding from an Array/ or multiple literals; wrap to a list, first.

Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b));         // from an array variable
b.addAll( Arrays.asList( 8, 9, 10));  // from literals

To get the intersection:

// copies all from A;  then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print;   r.toString() implied.
System.out.println("A intersect B="+r);

Hope this answer helps. Vote for it!

Resizing image in Java

Resize image with high quality:

private static InputStream resizeImage(InputStream uploadedInputStream, String fileName, int width, int height) {

        try {
            BufferedImage image = ImageIO.read(uploadedInputStream);
            Image originalImage= image.getScaledInstance(width, height, Image.SCALE_DEFAULT);

            int type = ((image.getType() == 0) ? BufferedImage.TYPE_INT_ARGB : image.getType());
            BufferedImage resizedImage = new BufferedImage(width, height, type);

            Graphics2D g2d = resizedImage.createGraphics();
            g2d.drawImage(originalImage, 0, 0, width, height, null);
            g2d.dispose();
            g2d.setComposite(AlphaComposite.Src);
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            ImageIO.write(resizedImage, fileName.split("\\.")[1], byteArrayOutputStream);
            return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        } catch (IOException e) {
            // Something is going wrong while resizing image
            return uploadedInputStream;
        }
    }

When should I use git pull --rebase?

I would like to provide a different perspective on what "git pull --rebase" actually means, because it seems to get lost sometimes.

If you've ever used Subversion (or CVS), you may be used to the behavior of "svn update". If you have changes to commit and the commit fails because changes have been made upstream, you "svn update". Subversion proceeds by merging upstream changes with yours, potentially resulting in conflicts.

What Subversion just did, was essentially "pull --rebase". The act of re-formulating your local changes to be relative to the newer version is the "rebasing" part of it. If you had done "svn diff" prior to the failed commit attempt, and compare the resulting diff with the output of "svn diff" afterwards, the difference between the two diffs is what the rebasing operation did.

The major difference between Git and Subversion in this case is that in Subversion, "your" changes only exist as non-committed changes in your working copy, while in Git you have actual commits locally. In other words, in Git you have forked the history; your history and the upstream history has diverged, but you have a common ancestor.

In my opinion, in the normal case of having your local branch simply reflecting the upstream branch and doing continuous development on it, the right thing to do is always "--rebase", because that is what you are semantically actually doing. You and others are hacking away at the intended linear history of a branch. The fact that someone else happened to push slightly prior to your attempted push is irrelevant, and it seems counter-productive for each such accident of timing to result in merges in the history.

If you actually feel the need for something to be a branch for whatever reason, that is a different concern in my opinion. But unless you have a specific and active desire to represent your changes in the form of a merge, the default behavior should, in my opinion, be "git pull --rebase".

Please consider other people that need to observe and understand the history of your project. Do you want the history littered with hundreds of merges all over the place, or do you want only the select few merges that represent real merges of intentional divergent development efforts?

LEFT JOIN in LINQ to entities?

Ah, got it myselfs.
The quirks and quarks of LINQ-2-entities.
This looks most understandable:

var query2 = (
    from users in Repo.T_Benutzer
    from mappings in Repo.T_Benutzer_Benutzergruppen
        .Where(mapping => mapping.BEBG_BE == users.BE_ID).DefaultIfEmpty()
    from groups in Repo.T_Benutzergruppen
        .Where(gruppe => gruppe.ID == mappings.BEBG_BG).DefaultIfEmpty()
    //where users.BE_Name.Contains(keyword)
    // //|| mappings.BEBG_BE.Equals(666)  
    //|| mappings.BEBG_BE == 666 
    //|| groups.Name.Contains(keyword)

    select new
    {
         UserId = users.BE_ID
        ,UserName = users.BE_User
        ,UserGroupId = mappings.BEBG_BG
        ,GroupName = groups.Name
    }

);


var xy = (query2).ToList();

Remove the .DefaultIfEmpty(), and you get an inner join.
That was what I was looking for.

How do I read / convert an InputStream into a String in Java?

This Code is for New Java Learners:

     private String textDataFromFile;

public String getFromFile(InputStream myInputStream) throws FileNotFoundException, IOException {

      BufferedReader bufferReader = new BufferedReader (new InputStreamReader(myInputStream));

       StringBuilder stringBuilder = new StringBuilder();

  String eachStringLine;

    while((eachStringLine=bufferReader.readLine()) != null){          
        stringBuilder.append(eachStringLine).append("\n");
    }

   textDataFromFile = stringBuilder.toString(); 



  return textDataFromFile;

}

Check if current directory is a Git repository

Or you could do this:

inside_git_repo="$(git rev-parse --is-inside-work-tree 2>/dev/null)"

if [ "$inside_git_repo" ]; then
  echo "inside git repo"
else
  echo "not in git repo"
fi

case statement in where clause - SQL Server

A CASE statement is an expression, just like a boolean comparison. That means the 'AND' needs to go before the 'CASE' statement, not within it.:

Select * From Times
WHERE (StartDate <= @Date) AND (EndDate >= @Date)

AND -- Added the "AND" here

CASE WHEN @day = 'Monday' THEN (Monday = 1)   -- Removed "AND" 
    WHEN @day = 'Tuesday' THEN (Tuesday = 1)  -- Removed "AND" 
    ELSE AND (Wednesday = 1) 
END

AngularJS - Trigger when radio button is selected

 <form name="myForm" ng-submit="submitForm()">
   <label data-ng-repeat="i in [1,2,3]"><input type="radio" name="test" ng-model="$parent.radioValue" value="{{i}}"/>{{i}}</label>
   <div>currently selected: {{radioValue}}</div>
   <button type="submit">Submit</button>
</form>

Maintaining the final state at end of a CSS3 animation

IF NOT USING THE SHORT HAND VERSION: Make sure the animation-fill-mode: forwards is AFTER the animation declaration or it will not work...

animation-fill-mode: forwards;
animation-name: appear;
animation-duration: 1s;
animation-delay: 1s;

vs

animation-name: appear;
animation-duration: 1s;
animation-fill-mode: forwards;
animation-delay: 1s;

How to define multiple CSS attributes in jQuery?

Pass it as an Object:

$(....).css({
    'property': 'value', 
    'property': 'value'
});

http://docs.jquery.com/CSS/css#properties

JSTL if tag for equal strings

I think the other answers miss one important detail regarding the property name to use in the EL expression. The rules for converting from the method names to property names are specified in 'Introspector.decpitalize` which is part of the java bean standard:

This normally means converting the first character from upper case to lower case, but in the (unusual) special case when there is more than one character and both the first and second characters are upper case, we leave it alone.

Thus "FooBah" becomes "fooBah" and "X" becomes "x", but "URL" stays as "URL".

So in your case the JSTL code should look like the following, note the capital 'P':

<c:if test = "${ansokanInfo.PSystem == 'NAT'}">

How do I activate C++ 11 in CMake?

The easiest way to set the Cxx standard is:

 set_property(TARGET tgt PROPERTY CXX_STANDARD 11)

See the CMake documentation for more details.

Replacing H1 text with a logo image: best method for SEO and accessibility?

I don't know but this is the format have used...

<h1>
    <span id="site-logo" title="xxx" href="#" target="_self">
        <img src="http://www.xxx.com/images/xxx.png" alt="xxx" width="xxx" height="xxx" />
        <a style="display:none">
            <strong>xxx</strong>
        </a>
    </span>
</h1>

Simple and it has not done my site any harm as far as I can see. You could css it but I don't see it loading any faster.

X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode

I also got the same issue of IE9 rendering in IE7 Document standards for local host. I tried many conditional comments tags but unsuccesful. In the end I just removed all conditional tags and just added meta tag immediatly after head like below and it worked like charm.

<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

Hope it helps

PHP Header redirect not working

COMMON PROBLEMS:

1) There should be NO output (i.e. echo... or HTML parts) before the header(...); command.

2) After header(...); you must use exit();

3) Remove any white-space(or newline) before <?php and after ?> tags.

4) Check that php file (and also other .php files, that are included) - they should have UTF8 without BOM encoding (and not just UTF-8). Because default UTF8 adds invisible character in the start of file (called "BOM"), so you should avoid that !!!!!!!!!!!

5) Use 301 or 302 reference:

header("location: http://example.com",  true,  301 );  exit;

6) Turn on error reporting. And tell the error.

7) If none of above helps, use JAVASCRIPT redirection (however, discouraged method), may be the last chance in custom cases...:

echo "<script type='text/javascript'>window.top.location='http://website.com/';</script>"; exit;

Git ignore file for Xcode projects

I've added:

xcuserstate
xcsettings

and placed my .gitignore file at the root of my project.

After committing and pushing. I then ran:

git rm --cached UserInterfaceState.xcuserstate WorkspaceSettings.xcsettings

buried with the folder below:

<my_project_name>/<my_project_name>.xcodeproj/project.xcworkspace/xcuserdata/<my_user_name>.xcuserdatad/

I then ran git commit and push again

What is an idiomatic way of representing enums in Go?

Here is an example that will prove useful when there are many enumerations. It uses structures in Golang, and draws upon Object Oriented Principles to tie them all together in a neat little bundle. None of the underlying code will change when a new enumeration is added or deleted. The process is:

  • Define an enumeration structure for enumeration items: EnumItem. It has an integer and string type.
  • Define the enumeration as a list of enumeration items: Enum
  • Build methods for the enumeration. A few have been included:
    • enum.Name(index int): returns the name for the given index.
    • enum.Index(name string): returns the name for the given index.
    • enum.Last(): returns the index and name of the last enumeration
  • Add your enumeration definitions.

Here is some code:

type EnumItem struct {
    index int
    name  string
}

type Enum struct {
    items []EnumItem
}

func (enum Enum) Name(findIndex int) string {
    for _, item := range enum.items {
        if item.index == findIndex {
            return item.name
        }
    }
    return "ID not found"
}

func (enum Enum) Index(findName string) int {
    for idx, item := range enum.items {
        if findName == item.name {
            return idx
        }
    }
    return -1
}

func (enum Enum) Last() (int, string) {
    n := len(enum.items)
    return n - 1, enum.items[n-1].name
}

var AgentTypes = Enum{[]EnumItem{{0, "StaffMember"}, {1, "Organization"}, {1, "Automated"}}}
var AccountTypes = Enum{[]EnumItem{{0, "Basic"}, {1, "Advanced"}}}
var FlagTypes = Enum{[]EnumItem{{0, "Custom"}, {1, "System"}}}

Get element from within an iFrame

Below code will help you to find out iframe data.

let iframe = document.getElementById('frameId');
let innerDoc = iframe.contentDocument || iframe.contentWindow.document;

How do I output the results of a HiveQL query to CSV?

This shell command prints the output format in csv to output.txt without the column headers.

$ hive --outputformat=csv2 -f 'hivedatascript.hql' --hiveconf hive.cli.print.header=false > output.txt

How to get the current plugin directory in WordPress?

To get the plugin directory you can use the Wordpress function plugin_basename($file). So you would use is as follows to extract the folder and filename of the plugin:

$plugin_directory = plugin_basename(__FILE__); 

You can combine this with the URL or the server path of the plugin directory. Therefor you can use the constants WP_PLUGIN_URL to get the plugin directory url or WP_PLUGIN_DIR to get the server path. But as Mark Jaquith mentioned in a comment below this only works if the plugins resides in the Wordpress plugin directory.

Read more about it in the Wordpress codex.

reStructuredText tool support

Salvaging (and extending) the list from an old version of the Wikipedia page:

Documentation

Implementations

Although the reference implementation of reStructuredText is written in Python, there are reStructuredText parsers in other languages too.

Python - Docutils

The main distribution of reStructuredText is the Python Docutils package. It contains several conversion tools:

  • rst2html - from reStructuredText to HTML
  • rst2xml - from reStructuredText to XML
  • rst2latex - from reStructuredText to LaTeX
  • rst2odt - from reStructuredText to ODF Text (word processor) document.
  • rst2s5 - from reStructuredText to S5, a Simple Standards-based Slide Show System
  • rst2man - from reStructuredText to Man page

Haskell - Pandoc

Pandoc is a Haskell library for converting from one markup format to another, and a command-line tool that uses this library. It can read Markdown and (subsets of) reStructuredText, HTML, and LaTeX, and it can write Markdown, reStructuredText, HTML, LaTeX, ConTeXt, PDF, RTF, DocBook XML, OpenDocument XML, ODT, GNU Texinfo, MediaWiki markup, groff man pages, and S5 HTML slide shows.

There is an Pandoc online tool (POT) to try this library. Unfortunately, compared to the reStructuredText online renderer (ROR),

  • POT truncates input rather more shortly. The POT user must render input in chunks that could be rendered whole by the ROR.
  • POT output lacks the helpful error messages displayed by the ROR (and generated by docutils)

Java - JRst

JRst is a Java reStructuredText parser. It can currently output HTML, XHTML, DocBook xdoc and PDF, BUT seems to have serious problems: neither PDF or (X)HTML generation works using the current full download, result pages in (X)HTML are empty and PDF generation fails on IO problems with XSL files (not bundled??). Note that the original JRst has been removed from the website; a fork is found on GitHub.

Scala - Laika

Laika is a new library for transforming markup languages to other output formats. Currently it supports input from Markdown and reStructuredText and produce HTML output. The library is written in Scala but should be also usable from Java.

Perl

PHP

C#/.NET

Nim/C

The Nim compiler features the commands rst2htmland rst2tex which transform reStructuredText files to HTML and TeX files. The standard library provides the following modules (used by the compiler) to handle reStructuredText files programmatically:

  • rst - implements a reStructuredText parser
  • rstast - implements an AST for the reStructuredText parser
  • rstgen - implements a generator of HTML/Latex from reStructuredText

Other 3rd party converters

Most (but not all) of these tools are based on Docutils (see above) and provide conversion to or from formats that might not be supported by the main distribution.

From reStructuredText

  • restview - This pip-installable python package requires docutils, which does the actual rendering. restview's major ease-of-use feature is that, when you save changes to your document(s), it automagically re-renders and re-displays them. restview
    1. starts a small web server
    2. calls docutils to render your document(s) to HTML
    3. calls your device's browser to display the output HTML.
  • rst2pdf - from reStructuredText to PDF
  • rst2odp - from reStructuredText to ODF Presentation
  • rst2beamer - from reStructuredText to LaTeX beamer Presentation class
  • Wikir - from reStructuredText to a Google (and possibly other) Wiki formats
  • rst2qhc - Convert a collection of reStructuredText files into a Qt (toolkit) Help file and (optional) a Qt Help Project file

To reStructuredText

  • xml2rst is an XSLT script to convert Docutils internal XML representation (back) to reStructuredText
  • Pandoc (see above) can also convert from Markdown, HTML and LaTeX to reStructuredText
  • db2rst is a simple and limited DocBook to reStructuredText translator
  • pod2rst - convert .pod files to reStructuredText files

Extensions

Some projects use reStructuredText as a baseline to build on, or provide extra functionality extending the utility of the reStructuredText tools.

Sphinx

The Sphinx documentation generator translates a set of reStructuredText source files into various output formats, automatically producing cross-references, indices etc.

rest2web

rest2web is a simple tool that lets you build your website from a single template (or as many as you want), and keep the contents in reStructuredText.

Pygments

Pygments is a generic syntax highlighter for general use in all kinds of software such as forum systems, Wikis or other applications that need to prettify source code. See Using Pygments in reStructuredText documents.

Free Editors

While any plain text editor is suitable to write reStructuredText documents, some editors have better support than others.

Emacs

The Emacs support via rst-mode comes as part of the Docutils package under /docutils/tools/editors/emacs/rst.el

Vim

The vim-common package for that comes with most GNU/Linux distributions has reStructuredText syntax highlight and indentation support of reStructuredText out of the box:

Jed

There is a rst mode for the Jed programmers editor.

gedit

gedit, the official text editor of the GNOME desktop environment. There is a gedit reStructuredText plugin.

Geany

Geany, a small and lightweight Integrated Development Environment include support for reStructuredText from version 0.12 (October 10, 2007).

Leo

Leo, an outlining editor for programmers, supports reStructuredText via rst-plugin or via "@auto-rst" nodes (it's not well-documented, but @auto-rst nodes allow editing rst files directly, parsing the structure into the Leo outline).

It also provides a way to preview the resulting HTML, in a "viewrendered" pane.

FTE

The FTE Folding Text Editor - a free (licensed under the GNU GPL) text editor for developers. FTE has a mode for reStructuredText support. It provides color highlighting of basic RSTX elements and special menu that provide easy way to insert most popular RSTX elements to a document.

PyK

PyK is a successor of PyEdit and reStInPeace, written in Python with the help of the Qt4 toolkit.

Eclipse

The Eclipse IDE with the ReST Editor plug-in provides support for editing reStructuredText files.

NoTex

NoTex is a browser based (general purpose) text editor, with integrated project management and syntax highlighting. Plus it enables to write books, reports, articles etc. using rST and convert them to LaTex, PDF or HTML. The PDF files are of high publication quality and are produced via Sphinx with the Texlive LaTex suite.

Notepad++

Notepad++ is a general purpose text editor for Windows. It has syntax highlighting for many languages built-in and support for reStructuredText via a user defined language for reStructuredText.

Visual Studio Code

Visual Studio Code is a general purpose text editor for Windows/macOS/Linux. It has syntax highlighting for many languages built-in and supports reStructuredText via an extension from LeXtudio.

Dedicated reStructuredText Editors

Proprietary editors

Sublime Text

Sublime Text is a completely customizable and extensible source code editor available for Windows, OS X, and Linux. Registration is required for long-term use, but all functions are available in the unregistered version, with occasional reminders to purchase a license. Versions 2 and 3 (currently in beta) support reStructuredText syntax highlighting by default, and several plugins are available through the package manager Package Control to provide snippets and code completion, additional syntax highlighting, conversion to/from RST and other formats, and HTML preview in the browser.

BBEdit / TextWrangler

BBEdit (and its free variant TextWrangler) for Mac can syntax-highlight reStructuredText using this codeless language module.

TextMate

TextMate, a proprietary general-purpose GUI text editor for Mac OS X, has a bundle for reStructuredText.

Intype

Intype is a proprietary text editor for Windows, that support reStructuredText out of the box.

E Text Editor

E is a proprietary Text Editor licensed under the "Open Company License". It supports TextMate's bundles, so it should support reStructuredText the same way TextMate does.

PyCharm

PyCharm (and other IntelliJ platform IDEs?) has ReST/Sphinx support (syntax highlighting, autocomplete and preview).instant preview)

Wiki

here are some Wiki programs that support the reStructuredText markup as the native markup syntax, or as an add-on:

MediaWiki

MediaWiki reStructuredText extension allows for reStructuredText markup in MediaWiki surrounded by <rst> and </rst>.

MoinMoin

MoinMoin is an advanced, easy to use and extensible WikiEngine with a large community of users. Said in a few words, it is about collaboration on easily editable web pages.

There is a reStructuredText Parser for MoinMoin.

Trac

Trac is an enhanced wiki and issue tracking system for software development projects. There is a reStructuredText Support in Trac.

This Wiki

This Wiki is a Webware for Python Wiki written by Ian Bicking. This wiki uses ReStructuredText for its markup.

rstiki

rstiki is a minimalist single-file personal wiki using reStructuredText syntax (via docutils) inspired by pwyky. It does not support authorship indication, versioning, hierarchy, chrome/framing/templating or styling. It leverages docutils/reStructuredText as the wiki syntax. As such, it's under 200 lines of code, and in a single file. You put it in a directory and it runs.

ikiwiki

Ikiwiki is a wiki compiler. It converts wiki pages into HTML pages suitable for publishing on a website. Ikiwiki stores pages and history in a revision control system such as Subversion or Git. There are many other features, including support for blogging, as well as a large array of plugins. It's reStructuredText plugin, however is somewhat limited and is not recommended as its' main markup language at this time.

Web Services

Sandbox

An Online reStructuredText editor can be used to play with the markup and see the results immediately.

Blogging frameworks

WordPress

WordPreSt reStructuredText plugin for WordPress. (PHP)

Zine

reStructuredText parser plugin for Zine (will become obsolete in version 0.2 when Zine is scheduled to get a native reStructuredText support). Zine is discontinued. (Python)

pelican

Pelican is a static blog generator that supports writing articles in ReST. (Python)

hyde

Hyde is a static website generator that supports ReST. (Python)

Acrylamid

Acrylamid is a static blog generator that supports writing articles in ReST. (Python)

Nikola

Nikola is a Static Site and Blog Generator that supports ReST. (Python)

ipsum genera

Ipsum genera is a static blog generator written in Nim.

Yozuch

Yozuch is a static blog generator written in Python.

More

How to get page content using cURL?

Get content with Curl php

request server support Curl function, enable in httpd.conf in folder Apache


function UrlOpener($url)
     global $output;
     $ch = curl_init(); 
     curl_setopt($ch, CURLOPT_URL, $url); 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
     $output = curl_exec($ch); 
     curl_close($ch);    
     echo $output;

If get content by google cache use Curl you can use this url: http://webcache.googleusercontent.com/search?q=cache:Put your url Sample: http://urlopener.mixaz.net/

Trying to SSH into an Amazon Ec2 instance - permission error

Take a look at this article. You do not use the public DNS but rather the form

ssh -i your.pem [email protected]

where the name is visible on your AMI panel

Is there a simple way to convert C++ enum to string?

I have an incredibly simple to use macro that does this in a completely DRY fashion. It involves variadic macros and some simple parsing magic. Here goes:

#define AWESOME_MAKE_ENUM(name, ...) enum class name { __VA_ARGS__, __COUNT}; \
inline std::ostream& operator<<(std::ostream& os, name value) { \
std::string enumName = #name; \
std::string str = #__VA_ARGS__; \
int len = str.length(); \
std::vector<std::string> strings; \
std::ostringstream temp; \
for(int i = 0; i < len; i ++) { \
if(isspace(str[i])) continue; \
        else if(str[i] == ',') { \
        strings.push_back(temp.str()); \
        temp.str(std::string());\
        } \
        else temp<< str[i]; \
} \
strings.push_back(temp.str()); \
os << enumName << "::" << strings[static_cast<int>(value)]; \
return os;} 

To use this in your code, simply do:

AWESOME_MAKE_ENUM(Animal,
    DOG,
    CAT,
    HORSE
);

Reorder bars in geom_bar ggplot2 by value

Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -sign before value:

ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) + 
  geom_bar(stat = "identity")

which gives:

enter image description here


Used data:

corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
                         variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
                         value = c(7L, 75L, 70L, 5L, 10L, 47L)),
                    class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))

Does Java support structs?

Java 14 has added support for Records, which are structured data types that are very easy to build.

You can declare a Java record like this:

public record AuditInfo(
    LocalDateTime createdOn,
    String createdBy,
    LocalDateTime updatedOn,
    String updatedBy
) {}
 
public record PostInfo(
    Long id,
    String title,
    AuditInfo auditInfo
) {}

And, the Java compiler will generate the following Java class associated to the AuditInfo Record:

public final class PostInfo
        extends java.lang.Record {
    private final java.lang.Long id;
    private final java.lang.String title;
    private final AuditInfo auditInfo;
 
    public PostInfo(
            java.lang.Long id,
            java.lang.String title,
            AuditInfo auditInfo) {
        /* compiled code */
    }
 
    public java.lang.String toString() { /* compiled code */ }
 
    public final int hashCode() { /* compiled code */ }
 
    public final boolean equals(java.lang.Object o) { /* compiled code */ }
 
    public java.lang.Long id() { /* compiled code */ }
 
    public java.lang.String title() { /* compiled code */ }
 
    public AuditInfo auditInfo() { /* compiled code */ }
}
 
public final class AuditInfo
        extends java.lang.Record {
    private final java.time.LocalDateTime createdOn;
    private final java.lang.String createdBy;
    private final java.time.LocalDateTime updatedOn;
    private final java.lang.String updatedBy;
 
    public AuditInfo(
            java.time.LocalDateTime createdOn,
            java.lang.String createdBy,
            java.time.LocalDateTime updatedOn,
            java.lang.String updatedBy) {
        /* compiled code */
    }
 
    public java.lang.String toString() { /* compiled code */ }
 
    public final int hashCode() { /* compiled code */ }
 
    public final boolean equals(java.lang.Object o) { /* compiled code */ }
 
    public java.time.LocalDateTime createdOn() { /* compiled code */ }
 
    public java.lang.String createdBy() { /* compiled code */ }
 
    public java.time.LocalDateTime updatedOn() { /* compiled code */ }
 
    public java.lang.String updatedBy() { /* compiled code */ }
}

Notice that the constructor, accessor methods, as well as equals, hashCode, and toString are created for you, so it's very convenient to use Java Records.

A Java Record can be created like any other Java object:

PostInfo postInfo = new PostInfo(
    1L,
    "High-Performance Java Persistence",
    new AuditInfo(
        LocalDateTime.of(2016, 11, 2, 12, 0, 0),
        "Vlad Mihalcea",
        LocalDateTime.now(),
        "Vlad Mihalcea"
    )
);

Flask-SQLalchemy update a row's information

Just assigning the value and committing them will work for all the data types but JSON and Pickled attributes. Since pickled type is explained above I'll note down a slightly different but easy way to update JSONs.

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True)
    data = db.Column(db.JSON)

def __init__(self, name, data):
    self.name = name
    self.data = data

Let's say the model is like above.

user = User("Jon Dove", {"country":"Sri Lanka"})
db.session.add(user)
db.session.flush()
db.session.commit()

This will add the user into the MySQL database with data {"country":"Sri Lanka"}

Modifying data will be ignored. My code that didn't work is as follows.

user = User.query().filter(User.name=='Jon Dove')
data = user.data
data["province"] = "south"
user.data = data
db.session.merge(user)
db.session.flush()
db.session.commit()

Instead of going through the painful work of copying the JSON to a new dict (not assigning it to a new variable as above), which should have worked I found a simple way to do that. There is a way to flag the system that JSONs have changed.

Following is the working code.

from sqlalchemy.orm.attributes import flag_modified
user = User.query().filter(User.name=='Jon Dove')
data = user.data
data["province"] = "south"
user.data = data
flag_modified(user, "data")
db.session.merge(user)
db.session.flush()
db.session.commit()

This worked like a charm. There is another method proposed along with this method here Hope I've helped some one.

How do I list all remote branches in Git 1.7+?

I would use:

git branch -av

This command not only shows you the list of all branches, including remote branches starting with /remote, but it also provides you the * feedback on what you updated and the last commit comments.

UITableView set to static cells. Is it possible to hide some of the cells programmatically?

Answer in swift:

Add the following method in your TableViewController:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return indexPathOfCellYouWantToHide == indexPath ? 0 : super.tableView(tableView, heightForRowAtIndexPath: indexPath)
}

if the tableView tries to draw the cell you wish to hide, then it won't display it because its height will be set to 0pt thanks to the method above, everything else stays unaltered.

Please note that indexPathOfCellYouWantToHide can be changed at anytime :)

check if a std::vector contains a certain object?

If searching for an element is important, I'd recommend std::set instead of std::vector. Using this:

std::find(vec.begin(), vec.end(), x) runs in O(n) time, but std::set has its own find() member (ie. myset.find(x)) which runs in O(log n) time - that's much more efficient with large numbers of elements

std::set also guarantees all the added elements are unique, which saves you from having to do anything like if not contained then push_back()....

How to set the opacity/alpha of a UIImage?

If you're experimenting with Metal rendering & you're extracting the CGImage generated by imageByApplyingAlpha in the first reply, you may end up with a Metal rendering that's larger than you expect. While experimenting with Metal, you may want to change one line of code in imageByApplyingAlpha:

    UIGraphicsBeginImageContextWithOptions (self.size, NO, 1.0f);
//  UIGraphicsBeginImageContextWithOptions (self.size, NO, 0.0f);

If you're using a device with a scale factor of 3.0, like the iPhone 11 Pro Max, the 0.0 scale factor shown above will give you an CGImage that's three times larger than you're expecting. Changing the scale factor to 1.0 should avoid any scaling.

Hopefully, this reply will save beginners a lot of aggravation.

Disable nginx cache for JavaScript files

I have the following nginx virtual host (static content) for local development work to disable all browser caching:

server {
    listen 8080;
    server_name localhost;

    location / {
        root /your/site/public;
        index index.html;

        # kill cache
        add_header Last-Modified $date_gmt;
        add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
        if_modified_since off;
        expires off;
        etag off;
    }
}

No cache headers sent:

$ curl -I http://localhost:8080
HTTP/1.1 200 OK
Server: nginx/1.12.1
Date: Mon, 24 Jul 2017 16:19:30 GMT
Content-Type: text/html
Content-Length: 2076
Connection: keep-alive
Last-Modified: Monday, 24-Jul-2017 16:19:30 GMT
Cache-Control: no-store
Accept-Ranges: bytes

Last-Modified is always current time.

ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

I ran this on MacOS /Applications/Python\ 3.6/Install\ Certificates.command

A good Sorted List for Java

It seems that you want a list structure with very fast removal and random access by index (not by key) times. An ArrayList gives you the latter and a HashMap or TreeMap give you the former.

There is one structure in Apache Commons Collections that may be what you are looking for, the TreeList. The JavaDoc specifies that it is optimized for quick insertion and removal at any index in the list. If you also need generics though, this will not help you.

Best way to add Gradle support to IntelliJ Project

There is no need to remove any .iml files. Follow this:

  • close the project
  • File -> Open... and choose your newly created build.gradle
  • IntelliJ will ask you whether you want:
    • Open Existing Project
    • Delete Existing Project and Import
  • Choose the second option and you are done

How can I get the concatenation of two lists in Python without modifying either one?

And if you have more than two lists to concatenate:

import operator
from functools import reduce  # For Python 3
list1, list2, list3 = [1,2,3], ['a','b','c'], [7,8,9]
reduce(operator.add, [list1, list2, list3])

# or with an existing list
all_lists = [list1, list2, list3]
reduce(operator.add, all_lists)

It doesn't actually save you any time (intermediate lists are still created) but nice if you have a variable number of lists to flatten, e.g., *args.

Move an array element from one array position to another

_x000D_
_x000D_
    let oldi, newi, arr;_x000D_
    _x000D_
    if(newi !== oldi) {_x000D_
      let el = this.arr.splice(oldi, 1);_x000D_
      if(newi > oldi && newi === (this.arr.length + 2)) {_x000D_
        this.arr.push("");_x000D_
      }_x000D_
      this.arr.splice(newi, 0, el);_x000D_
      if(newi > oldi && newi === (this.arr.length + 2)) {_x000D_
        this.arr.pop();_x000D_
      }_x000D_
    }
_x000D_
_x000D_
_x000D_

Entity Framework - Include Multiple Levels of Properties

EF Core: Using "ThenInclude" to load mutiple levels: For example:

var blogs = context.Blogs
    .Include(blog => blog.Posts)
        .ThenInclude(post => post.Author)
        .ThenInclude(author => author.Photo)
    .ToList();

Can't install gems on OS X "El Capitan"

Looks like when upgrading to OS X El Capitain, the /usr/local directory is modified in multiple ways :

  1. user permissions are reset (this is also a problem for people using Homebrew)
  2. binaries and symlinks might have been deleted or altered

[Edit] There's also a preliminary thing to do : upgrade Xcode...

Solution for #1 :

$ sudo chown -R $(whoami):admin /usr/local

This will fix permissions on the /usr/local directory which will then help both gem install and brew install|link|... commands working properly.

Solution to #2 :

Ruby based issues

Make sure you have fixed the permissions of the /usr/local directory (see #1 above)

First try to reinstall your gem using :

sudo gem install <gemname>

Note that it will install the latest version of the specified gem.

If you don't want to face backward-compatibility issues, I suggest that you first determine which version of which gem you want to get and then reinstall it with the -v version. See an exemple below to make sure that the system won't get a new version of capistrano.

$ gem list | grep capistrano
capistrano (3.4.0, 3.2.1, 2.14.2)
$ sudo gem install capistrano -v 3.4.0

Brew based issues

Update brew and upgrade your formulas

$ brew update
$ brew upgrade

You might also need to re-link some of them manually

$ brew link <formula>

How do I Validate the File Type of a File Upload?

As an alternative option, could you use the "accept" attribute of HTML File Input which defines which MIME types are acceptable.

Definition here

What is the best java image processing library/approach?

I know this question is quite old, but as new software comes out it does help to get some new links to projects that might be interesting for folks.

imgscalr is pure-Java image resizing (and simple ops like padding, cropping, rotating, brighten/dimming, etc.) library that is painfully simple to use - a single class consists of a set of simple graphics operations all defined as static methods that you pass an image and get back a result.

The most basic example of using the library would look like this:

BufferedImage thumbnail = Scalr.resize(image, 150);

And a more typical usage to generate image thumbnails using a few quality tweaks and the like might look like this:

import static org.imgscalr.Scalr.*;

public static BufferedImage createThumbnail(BufferedImage img) {
    // Create quickly, then smooth and brighten it.
    img = resize(img, Method.SPEED, 125, OP_ANTIALIAS, OP_BRIGHTER);

    // Let's add a little border before we return result.
    return pad(img, 4);
}

All image-processing operations use the raw Java2D pipeline (which is hardware accelerated on major platforms) and won't introduce the pain of calling out via JNI like library contention in your code.

imgscalr has also been deployed in large-scale productions in quite a few places - the inclusion of the AsyncScalr class makes it a perfect drop-in for any server-side image processing.

There are numerous tweaks to image-quality you can use to trade off between speed and quality with the highest ULTRA_QUALITY mode providing a scaled result that looks better than GIMP's Lancoz3 implementation.

change image opacity using javascript

In fact, you need to use CSS.

document.getElementById("myDivId").setAttribute("style","opacity:0.5; -moz-opacity:0.5; filter:alpha(opacity=50)");

It works on FireFox, Chrome and IE.

How to pass multiple arguments in processStartInfo?

Remember to include System.Diagnostics

ProcessStartInfo startInfo = new ProcessStartInfo("myfile.exe");        // exe file
startInfo.WorkingDirectory = @"C:\..\MyFile\bin\Debug\netcoreapp3.1\"; // exe folder

//here you add your arguments
startInfo.ArgumentList.Add("arg0");       // First argument          
startInfo.ArgumentList.Add("arg2");       // second argument
startInfo.ArgumentList.Add("arg3");       // third argument
Process.Start(startInfo);                 

<button> vs. <input type="button" />. Which to use?

I just want to add something to the rest of the answers here. Input elements are considered empty or void elements (other empty elements are area , base , br , col , hr , img , input , link , meta , and param. You can also check here), meaning they cannot have any content. In addition to not having any content, empty elements cannot have any pseudo-elements like ::after and ::before, which I consider a major drawback.

Bootstrap 3 Multi-column within a single ul not floating properly

Thanks, Varun Rathore. It works perfectly!

For those who want graceful collapse from 4 items per row to 2 items per row depending on the screen width:

<ul class="list-group row">
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_1</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_2</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_3</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_4</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_5</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_6</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_7</li>
</ul>

How to validate inputs dynamically created using ng-repeat, ng-show (angular)

Here an example of how I do that, I don't know if it is the best solution, but works perfectly.

First, code in HTML. Look at ng-class, it's calling hasError function. Look also to the input's name declaration. I use the $index to create different input names.

<div data-ng-repeat="tipo in currentObject.Tipo"
    ng-class="{'has-error': hasError(planForm, 'TipoM', 'required', $index) || hasError(planForm, 'TipoM', 'maxlength', $index)}">
    <input ng-model="tipo.Nombre" maxlength="100" required
        name="{{'TipoM' + $index}}"/>

And now, here is the hasError function:

$scope.hasError = function (form, elementName, errorType, index) {
           if (form == undefined
               || elementName == undefined
               || errorType == undefined
               || index == undefined)
               return false;

           var element = form[elementName + index];
           return (element != null && element.$error[errorType] && element.$touched);
       };

Using openssl to get the certificate from a server

With SNI

If the remote server is using SNI (that is, sharing multiple SSL hosts on a single IP address) you will need to send the correct hostname in order to get the right certificate.

openssl s_client -showcerts -servername www.example.com -connect www.example.com:443 </dev/null

Without SNI

If the remote server is not using SNI, then you can skip -servername parameter:

openssl s_client -showcerts -connect www.example.com:443 </dev/null


To view the full details of a site's cert you can use this chain of commands as well:

$ echo | \
    openssl s_client -servername www.example.com -connect www.example.com:443 2>/dev/null | \
    openssl x509 -text

Download all stock symbol list of a market

You can download a list of symbols from here. You have an option to download the whole list directly into excel file. You will have to register though.

"multiple target patterns" Makefile error

Besides having to escape colons as in the original answer, I have found if the indentation is off you could potentially get the same problem. In one makefile, I had to replace spaces with a tab and that allowed me to get past the error.

How to get just one file from another branch

Another way is to create a patch with the differences and apply it in the master branch For instance. Let's say the last commit before you started working on app.js is 00000aaaaa and the commit containg the version you want is 00000bbbbb

The you run this on the experiment branch:

git diff 00000aaaaa 00000bbbbb app.js > ~/app_changes.git

This will create a file with all the differences between those two commits for app.js that you can apply wherever you want. You can keep that file anywhere outside the project

Then, in master you just run:

git apply ~/app_changes.git

now you are gonna see the changes in the projects as if you had made them manually.

Getting Data from Android Play Store

There's an unofficial open-source API for the Android Market you may try to use to get the information you need. Hope this helps.

Single quotes vs. double quotes in Python

I aim to minimize both pixels and surprise. I typically prefer ' in order to minimize pixels, but " instead if the string has an apostrophe, again to minimize pixels. For a docstring, however, I prefer """ over ''' because the latter is non-standard, uncommon, and therefore surprising. If now I have a bunch of strings where I used " per the above logic, but also one that can get away with a ', I may still use " in it to preserve consistency, only to minimize surprise.

Perhaps it helps to think of the pixel minimization philosophy in the following way. Would you rather that English characters looked like A B C or AA BB CC? The latter choice wastes 50% of the non-empty pixels.

Temporarily disable all foreign key constraints

Disable all table constraints

ALTER TABLE TableName NOCHECK CONSTRAINT ConstraintName

-- Enable all table constraints

ALTER TABLE TableName CHECK CONSTRAINT ConstraintName

sql query distinct with Row_Number

This article covers an interesting relationship between ROW_NUMBER() and DENSE_RANK() (the RANK() function is not treated specifically). When you need a generated ROW_NUMBER() on a SELECT DISTINCT statement, the ROW_NUMBER() will produce distinct values before they are removed by the DISTINCT keyword. E.g. this query

SELECT DISTINCT
  v, 
  ROW_NUMBER() OVER (ORDER BY v) row_number
FROM t
ORDER BY v, row_number

... might produce this result (DISTINCT has no effect):

+---+------------+
| V | ROW_NUMBER |
+---+------------+
| a |          1 |
| a |          2 |
| a |          3 |
| b |          4 |
| c |          5 |
| c |          6 |
| d |          7 |
| e |          8 |
+---+------------+

Whereas this query:

SELECT DISTINCT
  v, 
  DENSE_RANK() OVER (ORDER BY v) row_number
FROM t
ORDER BY v, row_number

... produces what you probably want in this case:

+---+------------+
| V | ROW_NUMBER |
+---+------------+
| a |          1 |
| b |          2 |
| c |          3 |
| d |          4 |
| e |          5 |
+---+------------+

Note that the ORDER BY clause of the DENSE_RANK() function will need all other columns from the SELECT DISTINCT clause to work properly.

All three functions in comparison

Using PostgreSQL / Sybase / SQL standard syntax (WINDOW clause):

SELECT
  v,
  ROW_NUMBER() OVER (window) row_number,
  RANK()       OVER (window) rank,
  DENSE_RANK() OVER (window) dense_rank
FROM t
WINDOW window AS (ORDER BY v)
ORDER BY v

... you'll get:

+---+------------+------+------------+
| V | ROW_NUMBER | RANK | DENSE_RANK |
+---+------------+------+------------+
| a |          1 |    1 |          1 |
| a |          2 |    1 |          1 |
| a |          3 |    1 |          1 |
| b |          4 |    4 |          2 |
| c |          5 |    5 |          3 |
| c |          6 |    5 |          3 |
| d |          7 |    7 |          4 |
| e |          8 |    8 |          5 |
+---+------------+------+------------+

Auto Scale TextView Text to Fit within Bounds

AppcompatTextView now supports auto sizing starting from Support Library 26.0. TextView in Android O also works same way. More info can be found here. A simple demo app can be found here.

<LinearLayout
      xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      android:layout_width="match_parent"
      android:layout_height="wrap_content">

      <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:autoSizeTextType="uniform"
        app:autoSizeMinTextSize="12sp"
        app:autoSizeMaxTextSize="100sp"
        app:autoSizeStepGranularity="2sp"
      />

</LinearLayout>

ssh server connect to host xxx port 22: Connection timed out on linux-ubuntu

Update the security group of that instance. Your local IP must have updated. Every time it’s IP flips. You will have to go update the Security group.

Copy data into another table

This is the proper way to do it:

INSERT INTO destinationTable
SELECT * FROM sourceTable

Select top 1 result using JPA

Try like this

String sql = "SELECT t FROM table t";
Query query = em.createQuery(sql);
query.setFirstResult(firstPosition);
query.setMaxResults(numberOfRecords);
List result = query.getResultList();

It should work

UPDATE*

You can also try like this

query.setMaxResults(1).getResultList();

HTML - Change\Update page contents without refreshing\reloading the page

jQuery will do the job. You can use either jQuery.ajax function, which is general one for performing ajax calls, or its wrappers: jQuery.get, jQuery.post for getting/posting data. Its very easy to use, for example, check out this tutorial, which shows how to use jQuery with PHP.

Compare two objects in Java with possible null values

boolean compare(String str1, String str2) {
  return (str1==null || str2==null) ? str1 == str2 : str1.equals(str2);
}

Running two projects at once in Visual Studio

Go to Solution properties ? Common Properties ? Startup Project and select Multiple startup projects.

Solution properties dialog

PHP Using RegEx to get substring of a string

Unfortunately, you have a malformed url query string, so a regex technique is most appropriate. See what I mean.

There is no need for capture groups. Just match id= then forget those characters with \K, then isolate the following one or more digital characters.

Code (Demo)

$str = 'producturl.php?id=736375493?=tm';
echo preg_match('~id=\K\d+~', $str, $out) ? $out[0] : 'no match';

Output:

736375493

How to convert Java String to JSON Object

Converting the String to JsonNode using ObjectMapper object :

ObjectMapper mapper = new ObjectMapper();

// For text string
JsonNode = mapper.readValue(mapper.writeValueAsString("Text-string"), JsonNode.class)

// For Array String
JsonNode = mapper.readValue("[\"Text-Array\"]"), JsonNode.class)

// For Json String 
String json = "{\"id\" : \"1\"}";
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getFactory();
JsonParser jsonParser = factory.createParser(json);
JsonNode node = mapper.readTree(jsonParser);

How to change lowercase chars to uppercase using the 'keyup' event?

Solution 1 (Elegant approach with great user experience)

HTML

<input id="inputID" class="uppercase" name="inputName" value="" />

CSS

.uppercase{
    text-transform: uppercase;
}

JS

$('#inputID').on('blur', function(){
    this.value = this.value.toUpperCase();
});

By using CSS text-transform: uppercase; you'll eliminate the animation of lower to uppercase as the user types into the field.

Use blur event to handle converting to uppercase. This happens behind the scene as CSS took care of the user's visually appealing masking.

Solution 2 (Great, but less elegant)

If you insist on using keyup, here it is...

$('#inputID').on('keyup', function(){
    var caretPos = this.selectionStart;
    this.value = this.value.toUpperCase();
    this.setSelectionRange(caretPos, caretPos);
});

User would notice the animation of lowercase to uppercase as they type into the field. It gets the job done.

Solution 3 (Just get the job done)

$('#inputID').on('keyup', function(){
    this.value = this.value.toUpperCase();
});

This method is most commonly suggested but I do not recommend.

The downside of this solution is you'll be annoying the user as the cursor's caret position keeps jumping to the end of the text after every key input. Unless you know your users will never encounter typos or they will always clear the text and retype every single time, this method works.

Convert object to JSON in Android

download the library Gradle:

compile 'com.google.code.gson:gson:2.8.2'

To use the library in a method.

Gson gson = new Gson();

//transform a java object to json
System.out.println("json =" + gson.toJson(Object.class).toString());

//Transform a json to java object
String json = string_json;
List<Object> lstObject = gson.fromJson(json_ string, Object.class);

Set the value of a variable with the result of a command in a Windows batch file

Set "dateTime="
For /F %%A In ('powershell get-date -format "{yyyyMMdd_HHmm}"') Do Set "dateTime=%%A"
echo %dateTime%
pause

enter image description here Official Microsoft docs for for command

Copy Data from a table in one Database to another separate database

Try this

INSERT INTO dbo.DB1.TempTable
    (COLUMNS)
    SELECT COLUMNS_IN_SAME_ORDER FROM dbo.DB2.TempTable

This will only fail if an item in dbo.DB2.TempTable is in already in dbo.DB1.TempTable.