Programs & Examples On #Comparator

A Common interface to create an object that specifies the way of comparing other objects. When using this tag on implementation heavy questions - tag the code language the implementation is written in.

Java TreeMap Comparator

you can swipe the key and the value. For example

        String[] k = {"Elena", "Thomas", "Hamilton", "Suzie", "Phil"};
        int[] v = {341, 273, 278, 329, 445};
        TreeMap<Integer,String>a=new TreeMap();
        for (int i = 0; i < k.length; i++) 
           a.put(v[i],k[i]);            
        System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());
        a.remove(a.firstEntry().getKey());
        System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());

Java get String CompareTo as a comparator object

If you do find yourslef needing a Comparator, and you already use Guava, you can use Ordering.natural().

When should a class be Comparable and/or Comparator?

Comparable lets a class implement its own comparison:

  • it's in the same class (it is often an advantage)
  • there can be only one implementation (so you can't use that if you want two different cases)

By comparison, Comparator is an external comparison:

  • it is typically in a unique instance (either in the same class or in another place)
  • you name each implementation with the way you want to sort things
  • you can provide comparators for classes that you do not control
  • the implementation is usable even if the first object is null

In both implementations, you can still choose to what you want to be compared. With generics, you can declare so, and have it checked at compile-time. This improves safety, but it is also a challenge to determine the appropriate value.

As a guideline, I generally use the most general class or interface to which that object could be compared, in all use cases I envision... Not very precise a definition though ! :-(

  • Comparable<Object> lets you use it in all codes at compile-time (which is good if needed, or bad if not and you loose the compile-time error) ; your implementation has to cope with objects, and cast as needed but in a robust way.
  • Comparable<Itself> is very strict on the contrary.

Funny, when you subclass Itself to Subclass, Subclass must also be Comparable and be robust about it (or it would break Liskov Principle, and give you runtime errors).

Sort ArrayList of custom Objects by property

Best easy way with JAVA 8 is for English Alphabetic sort

Class Implementation

public class NewspaperClass implements Comparable<NewspaperClass>{
   public String name;

   @Override
   public int compareTo(NewspaperClass another) {
      return name.compareTo(another.name);
   }
}

Sort

  Collections.sort(Your List);

If you want to sort for alphabet that contains non English characters you can use Locale... Below code use Turkish character sort...

Class Implementation

public class NewspaperClass implements Comparator<NewspaperClass> {
   public String name;
   public Boolean isUserNewspaper=false;
   private Collator trCollator = Collator.getInstance(new Locale("tr_TR"));



   @Override
   public int compare(NewspaperClass lhs, NewspaperClass rhs) {
      trCollator.setStrength(Collator.PRIMARY);
      return trCollator.compare(lhs.name,rhs.name);
   }
}

Sort

Collections.sort(your array list,new NewspaperClass());

Java error: Comparison method violates its general contract

You can use the following class to pinpoint transitivity bugs in your Comparators:

/**
 * @author Gili Tzabari
 */
public final class Comparators
{
    /**
     * Verify that a comparator is transitive.
     *
     * @param <T>        the type being compared
     * @param comparator the comparator to test
     * @param elements   the elements to test against
     * @throws AssertionError if the comparator is not transitive
     */
    public static <T> void verifyTransitivity(Comparator<T> comparator, Collection<T> elements)
    {
        for (T first: elements)
        {
            for (T second: elements)
            {
                int result1 = comparator.compare(first, second);
                int result2 = comparator.compare(second, first);
                if (result1 != -result2)
                {
                    // Uncomment the following line to step through the failed case
                    //comparator.compare(first, second);
                    throw new AssertionError("compare(" + first + ", " + second + ") == " + result1 +
                        " but swapping the parameters returns " + result2);
                }
            }
        }
        for (T first: elements)
        {
            for (T second: elements)
            {
                int firstGreaterThanSecond = comparator.compare(first, second);
                if (firstGreaterThanSecond <= 0)
                    continue;
                for (T third: elements)
                {
                    int secondGreaterThanThird = comparator.compare(second, third);
                    if (secondGreaterThanThird <= 0)
                        continue;
                    int firstGreaterThanThird = comparator.compare(first, third);
                    if (firstGreaterThanThird <= 0)
                    {
                        // Uncomment the following line to step through the failed case
                        //comparator.compare(first, third);
                        throw new AssertionError("compare(" + first + ", " + second + ") > 0, " +
                            "compare(" + second + ", " + third + ") > 0, but compare(" + first + ", " + third + ") == " +
                            firstGreaterThanThird);
                    }
                }
            }
        }
    }

    /**
     * Prevent construction.
     */
    private Comparators()
    {
    }
}

Simply invoke Comparators.verifyTransitivity(myComparator, myCollection) in front of the code that fails.

Simple way to sort strings in the (case sensitive) alphabetical order

The simple way to solve the problem is to use ComparisonChain from Guava http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ComparisonChain.html

private static Comparator<String> stringAlphabeticalComparator = new Comparator<String>() {
        public int compare(String str1, String str2) {
            return ComparisonChain.start().
                                compare(str1,str2, String.CASE_INSENSITIVE_ORDER).
                                compare(str1,str2).
                                result();
         }
 };
Collections.sort(list, stringAlphabeticalComparator);

The first comparator from the chain will sort strings according to the case insensitive order, and the second comparator will sort strings according to the case insensitive order. As excepted strings appear in the result according to the alphabetical order:

"AA","Aa","aa","Development","development"

Reverse a comparator in Java 8

You can use Comparator.reverseOrder() to have a comparator giving the reverse of the natural ordering.

If you want to reverse the ordering of an existing comparator, you can use Comparator.reversed().

Sample code:

Stream.of(1, 4, 2, 5)
    .sorted(Comparator.reverseOrder()); 
    // stream is now [5, 4, 2, 1]

Stream.of("foo", "test", "a")
    .sorted(Comparator.comparingInt(String::length).reversed()); 
    // stream is now [test, foo, a], sorted by descending length

Java : Comparable vs Comparator

Comparator provides a way for you to provide custom comparison logic for types that you have no control over.

Comparable allows you to specify how objects that you are implementing get compared.

Obviously, if you don't have control over a class (or you want to provide multiple ways to compare objects that you do have control over) then use Comparator.

Otherwise you can use Comparable.

Android-java- How to sort a list of objects by a certain value within the object

I think this will help you better

Person p = new Person("Bruce", "Willis");
Person p1  = new Person("Tom", "Hanks");
Person p2 = new Person("Nicolas", "Cage");
Person p3 = new Person("John", "Travolta");

ArrayList<Person> list = new ArrayList<Person>();
list.add(p);
list.add(p1);
list.add(p2);
list.add(p3);

Collections.sort(list, new Comparator() {
    @Override
    public int compare(Object o1, Object o2) {
        Person p1 = (Person) o1;
        Person p2 = (Person) o2;
        return p1.getFirstName().compareToIgnoreCase(p2.getFirstName());
    }
});

How to use Comparator in Java to sort

Java 8 added a new way of making Comparators that reduces the amount of code you have to write, Comparator.comparing. Also check out Comparator.reversed

Here's a sample

import org.junit.Test;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import static org.junit.Assert.assertTrue;

public class ComparatorTest {

    @Test
    public void test() {
        List<Person> peopleList = new ArrayList<>();
        peopleList.add(new Person("A", 1000));
        peopleList.add(new Person("B", 1));
        peopleList.add(new Person("C", 50));
        peopleList.add(new Person("Z", 500));
        //sort by name, ascending
        peopleList.sort(Comparator.comparing(Person::getName));
        assertTrue(peopleList.get(0).getName().equals("A"));
        assertTrue(peopleList.get(peopleList.size() - 1).getName().equals("Z"));
        //sort by name, descending
        peopleList.sort(Comparator.comparing(Person::getName).reversed());
        assertTrue(peopleList.get(0).getName().equals("Z"));
        assertTrue(peopleList.get(peopleList.size() - 1).getName().equals("A"));
        //sort by age, ascending
        peopleList.sort(Comparator.comparing(Person::getAge));
        assertTrue(peopleList.get(0).getAge() == 1);
        assertTrue(peopleList.get(peopleList.size() - 1).getAge() == 1000);
        //sort by age, descending
        peopleList.sort(Comparator.comparing(Person::getAge).reversed());
        assertTrue(peopleList.get(0).getAge() == 1000);
        assertTrue(peopleList.get(peopleList.size() - 1).getAge() == 1);
    }

    class Person {

        String name;
        int age;

        Person(String n, int a) {
            name = n;
            age = a;
        }

        public String getName() {
            return name;
        }

        public int getAge() {
            return age;
        }

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

        public void setAge(int age) {
            this.age = age;
        }
    }



}

When to use Comparable and Comparator

There had been a similar question here: When should a class be Comparable and/or Comparator?

I would say the following: Implement Comparable for something like a natural ordering, e.g. based on an internal ID

Implement a Comparator if you have a more complex comparing algorithm, e.g. multiple fields and so on.

how to sort an ArrayList in ascending order using Collections and Comparator

Use the default version:

Collections.sort(myarrayList);

Of course this requires that your Elements implement Comparable, but the same holds true for the version you mentioned.

BTW: you should use generics in your code, that way you get compile-time errors if your class doesn't implement Comparable. And compile-time errors are much better than the runtime errors you'll get otherwise.

List<MyClass> list = new ArrayList<MyClass>();
// now fill up the list

// compile error here unless MyClass implements Comparable
Collections.sort(list); 

"Comparison method violates its general contract!"

If compareParents(s1, s2) == -1 then compareParents(s2, s1) == 1 is expected. With your code it's not always true.

Specifically if s1.getParent() == s2 && s2.getParent() == s1. It's just one of the possible problems.

java comparator, how to sort by integer?

From Java 8 you can use :

Comparator.comparingInt(Dog::getDogAge).reversed();

Java Comparator class to sort arrays

Just tried this solution, we don't have to even write int.

int[][] twoDim = { { 1, 2 }, { 3, 7 }, { 8, 9 }, { 4, 2 }, { 5, 3 } };
Arrays.sort(twoDim, (a1,a2) -> a2[0] - a1[0]);

This thing will also work, it automatically detects the type of string.

Case Insensitive String comp in C

static int ignoreCaseComp (const char *str1, const char *str2, int length)
{
    int k;
    for (k = 0; k < length; k++)
    {

        if ((str1[k] | 32) != (str2[k] | 32))
            break;
    }

    if (k != length)
        return 1;
    return 0;
}

Reference

Setting action for back button in navigation controller

At least in Xcode 5, there is a simple and pretty good (not perfect) solution. In IB, drag a Bar Button Item off the Utilities pane and drop it on the left side of the Navigation Bar where the Back button would be. Set the label to "Back." You will have a functioning button that you can tie to your IBAction and close your viewController. I'm doing some work and then triggering an unwind segue and it works perfectly.

What isn't ideal is that this button does not get the < arrow and does not carry forward the previous VCs title, but I think this can be managed. For my purposes, I set the new Back button to be a "Done" button so it's purpose is clear.

You also end up with two Back buttons in the IB navigator, but it is easy enough to label it for clarity.

enter image description here

C/C++ maximum stack size of program

I just ran out of stack at work, it was a database and it was running some threads, basically the previous developer had thrown a big array on the stack, and the stack was low anyway. The software was compiled using Microsoft Visual Studio 2015.

Even though the thread had run out of stack, it silently failed and continued on, it only stack overflowed when it came to access the contents of the data on the stack.

The best advice i can give is to not declare arrays on the stack - especially in complex applications and particularly in threads, instead use heap. That's what it's there for ;)

Also just keep in mind it may not fail immediately when declaring the stack, but only on access. My guess is that the compiler declares stack under windows "optimistically", i.e. it will assume that the stack has been declared and is sufficiently sized until it comes to use it and then finds out that the stack isn't there.

Different operating systems may have different stack declaration policies. Please leave a comment if you know what these policies are.

How do you import a large MS SQL .sql file?

I had similar problem. My file with sql script was over 150MB of size (with almost 900k of very simple INSERTs). I used solution advised by Takuro (as the answer in this question) but I still got error with message saying that there was not enough memory ("There is insufficient system memory in resource pool 'internal' to run this query").

What helped me was that I put GO command after every 50k INSERTs.

(It's not directly addressing the question (file size) but I believe it resolves problem that is indirectly connected with large size of sql script itself. In my case many insert commands)

Unable to ping vmware guest from another vmware guest

You can ping ip from one virtual machine to another machine by using these steps:

  1. Go to menu VM -> Setting -> select network adapter: NAT
  2. Go to menu VM -> setting -> select options Tab and select

Guest Isolation : ENABLED, ENABLED and select box : ENABLE VMCI

can not find module "@angular/material"

That's what solved this problem for me.

I used:

npm install --save @angular/material @angular/cdk
npm install --save @angular/animations

but INSIDE THE APPLICATION'S FOLDER.

Source: https://medium.com/@ismapro/first-steps-with-angular-cli-and-angular-material-5a90406e9a4

How to correctly implement custom iterators and const_iterators?

Boost has something to help: the Boost.Iterator library.

More precisely this page: boost::iterator_adaptor.

What's very interesting is the Tutorial Example which shows a complete implementation, from scratch, for a custom type.

template <class Value>
class node_iter
  : public boost::iterator_adaptor<
        node_iter<Value>                // Derived
      , Value*                          // Base
      , boost::use_default              // Value
      , boost::forward_traversal_tag    // CategoryOrTraversal
    >
{
 private:
    struct enabler {};  // a private type avoids misuse

 public:
    node_iter()
      : node_iter::iterator_adaptor_(0) {}

    explicit node_iter(Value* p)
      : node_iter::iterator_adaptor_(p) {}

    // iterator convertible to const_iterator, not vice-versa
    template <class OtherValue>
    node_iter(
        node_iter<OtherValue> const& other
      , typename boost::enable_if<
            boost::is_convertible<OtherValue*,Value*>
          , enabler
        >::type = enabler()
    )
      : node_iter::iterator_adaptor_(other.base()) {}

 private:
    friend class boost::iterator_core_access;
    void increment() { this->base_reference() = this->base()->next(); }
};

The main point, as has been cited already, is to use a single template implementation and typedef it.

Object passed as parameter to another class, by value or reference?

An Object if passed as a value type then changes made to the members of the object inside the method are impacted outside the method also. But if the object itself is set to another object or reinitialized then it will not be reflected outside the method. So i would say object as a whole is passed as Valuetype only but object members are still reference type.

        private void button1_Click(object sender, EventArgs e)
    {
        Class1 objc ;
         objc = new Class1();
        objc.empName = "name1";
        checkobj( objc);
        MessageBox.Show(objc.empName);  //propert value changed; but object itself did not change
    }
    private void checkobj ( Class1 objc)
    {
        objc.empName = "name 2";
        Class1 objD = new Class1();
        objD.empName ="name 3";
        objc = objD ;
        MessageBox.Show(objc.empName);  //name 3
    }

Switch case: can I use a range instead of a one number

If the question was about C (you didn't say), then the answer is no, but: GCC and Clang (maybe others) support a range syntax, but it's not valid ISO C:

switch (number) {
    case 1 ... 4:
        // Do something.
        break;

    case 5 ... 9:
        // Do something else.
        break;
}

Be sure to have a space before and after the ... or else you'll get a syntax error.

Escape string for use in Javascript regex

Short 'n Sweet

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

Example

escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");

>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "

(NOTE: the above is not the original answer; it was edited to show the one from MDN. This means it does not match what you will find in the code in the below npm, and does not match what is shown in the below long answer. The comments are also now confusing. My recommendation: use the above, or get it from MDN, and ignore the rest of this answer. -Darren,Nov 2019)

Install

Available on npm as escape-string-regexp

npm install --save escape-string-regexp

Note

See MDN: Javascript Guide: Regular Expressions

Other symbols (~`!@# ...) MAY be escaped without consequence, but are not required to be.

.

.

.

.

Test Case: A typical url

escapeRegExp("/path/to/resource.html?search=query");

>>> "\/path\/to\/resource\.html\?search=query"

The Long Answer

If you're going to use the function above at least link to this stack overflow post in your code's documentation so that it doesn't look like crazy hard-to-test voodoo.

var escapeRegExp;

(function () {
  // Referring to the table here:
  // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
  // these characters should be escaped
  // \ ^ $ * + ? . ( ) | { } [ ]
  // These characters only have special meaning inside of brackets
  // they do not need to be escaped, but they MAY be escaped
  // without any adverse effects (to the best of my knowledge and casual testing)
  // : ! , = 
  // my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)

  var specials = [
        // order matters for these
          "-"
        , "["
        , "]"
        // order doesn't matter for any of these
        , "/"
        , "{"
        , "}"
        , "("
        , ")"
        , "*"
        , "+"
        , "?"
        , "."
        , "\\"
        , "^"
        , "$"
        , "|"
      ]

      // I choose to escape every character with '\'
      // even though only some strictly require it when inside of []
    , regex = RegExp('[' + specials.join('\\') + ']', 'g')
    ;

  escapeRegExp = function (str) {
    return str.replace(regex, "\\$&");
  };

  // test escapeRegExp("/path/to/res?search=this.that")
}());

Tomcat: java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens

In case someone is using swagger:

Change the Scheme to HTTP or HTTPS, depend on needs, prior to hit the execute.

Postman:

Change the URL Path to http:// or https:// in the url address

invalid use of incomplete type

You can get around this by using a traits class:
It requires you set up a specialsed traits class for each actuall class you use.

template<typename SubClass>
class SubClass_traits
{};

template<typename Subclass>
class A {
    public:
        void action(typename SubClass_traits<Subclass>::mytype var)
        {
                (static_cast<Subclass*>(this))->do_action(var);
        }
};


// Definitions for B
class B;   // Forward declare

template<> // Define traits for B. So other classes can use it.
class SubClass_traits<B>
{
    public:
        typedef int mytype;
};

// Define B
class B : public A<B>
{
    // Define mytype in terms of the traits type.
    typedef SubClass_traits<B>::mytype  mytype;
    public:

        B() {}

        void do_action(mytype var) {
                // Do stuff
        }
};

int main(int argc, char** argv)
{
    B myInstance;
    return 0;
} 

mysql query result into php array

What about this:

while ($row = mysql_fetch_array($result)) 
{
    $new_array[$row['id']]['id'] = $row['id'];
    $new_array[$row['id']]['link'] = $row['link'];
}

To retrieve link and id:

foreach($new_array as $array)
{       
   echo $array['id'].'<br />';
   echo $array['link'].'<br />';
}

How to map with index in Ruby?

I have always enjoyed the syntax of this style:

a = [1, 2, 3, 4]
a.each_with_index.map { |el, index| el + index }
# => [1, 3, 5, 7]

Invoking each_with_index gets you an enumerator you can easily map over with your index available.

How to export table as CSV with headings on Postgresql?

The simplest way (using psql) seems to be by using --csv flag:

psql --csv -c "SELECT * FROM products_273" > '/tmp/products_199.csv'

formatFloat : convert float number to string

Try this

package main

import "fmt"
import "strconv"

func FloatToString(input_num float64) string {
    // to convert a float number to a string
    return strconv.FormatFloat(input_num, 'f', 6, 64)
}

func main() {
    fmt.Println(FloatToString(21312421.213123))
}

If you just want as many digits precision as possible, then the special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly. Eg

strconv.FormatFloat(input_num, 'f', -1, 64)

Personally I find fmt easier to use. (Playground link)

fmt.Printf("x = %.6f\n", 21312421.213123)

Or if you just want to convert the string

fmt.Sprintf("%.6f", 21312421.213123)

How can I keep a container running on Kubernetes?

  1. In your Dockerfile use this command:

    CMD ["sh", "-c", "tail -f /dev/null"]
    
  2. Build your docker image.

  3. Push it to your cluster or similar, just to make sure the image it's available.
  4. kubectl run debug-container -it --image=<your-image>
    

How can I export the schema of a database in PostgreSQL?

In Linux you can do like this

pg_dump -U postgres -s postgres > exportFile.dmp

Maybe it can work in Windows too, if not try the same with pg_dump.exe

pg_dump.exe -U postgres -s postgres > exportFile.dmp

How to add target="_blank" to JavaScript window.location?

window.location sets the URL of your current window. To open a new window, you need to use window.open. This should work:

function ToKey(){
    var key = document.tokey.key.value.toLowerCase();
    if (key == "smk") {
        window.open('http://www.smkproduction.eu5.org', '_blank');
    } else {
        alert("Kodi nuk është valid!");
    }
}

Split an NSString to access one particular piece

Use [myString componentsSeparatedByString:@"/"]

IE9 JavaScript error: SCRIPT5007: Unable to get value of the property 'ui': object is null or undefined

Well, you should also try adding the Javascript code into a function, then calling the function after document body has loaded..it worked for me :)

PHP: How do I display the contents of a textfile on my page?

I have to display files of computer code. If special characters are inside the file like less than or greater than, a simple "include" will not display them. Try:

$file = 'code.ino';
$orig = file_get_contents($file);
$a = htmlentities($orig);

echo '<code>';
echo '<pre>';

echo $a;

echo '</pre>';
echo '</code>';

How to set proper codeigniter base url?

If you leave it blank the framework will try to autodetect it since version 2.0.0.

But not in 3.0.0, see here: config.php

Best way to list files in Java, sorted by Date Modified?

In Java 8:

Arrays.sort(files, (a, b) -> Long.compare(a.lastModified(), b.lastModified()));

How to check postgres user and password?

You may change the pg_hba.conf and then reload the postgresql. something in the pg_hba.conf may be like below:

# "local" is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             127.0.0.1/32            trust

then you change your user to postgresql, you may login successfully.

su postgresql

Is there a download function in jsFiddle?

Okay, the easiest way, I found out was just changing the url (jsfiddle[dot]net) to fiddle[dot]jshell[dot]net/ There u have a clear html code, without any kind of iframe... Example: https://jsfiddle[dot]net/mfvmoy64/27/show/light/ -> http://fiddle[dot]jshell[dot]net/mfvmoy64/27/show/light/

(Must change the '.''s to "[dot]" because of stackeroverflow... :c) PS: sry 4 bad english

new Runnable() but no new thread?

A thread is something like some branch. Multi-branched means when there are at least two branches. If the branches are reduced, then the minimum remains one. This one is although like the branches removed, but in general we do not consider it branch.

Similarly when there are at least two threads we call it multi-threaded program. If the threads are reduced, the minimum remains one. Hello program is a single threaded program, but no one needs to know multi-threading to write or run it.

In simple words when a program is not said to be having threads, it means that the program is not a multi-threaded program, more over in true sense it is a single threaded program, in which YOU CAN put your code as if it is multi-threaded.

Below a useless code is given, but it will suffice to do away with your some confusions about Runnable. It will print "Hello World".

class NamedRunnable implements Runnable {

    public void run() { // The run method prints a message to standard output.
        System.out.println("Hello World");
    }

    public static void main(String[]arg){ 
        NamedRunnable namedRunnable = new NamedRunnable( );
        namedRunnable.run();
    } 
}

super() fails with error: TypeError "argument 1 must be type, not classobj" when parent does not inherit from object

Your problem is that class B is not declared as a "new-style" class. Change it like so:

class B(object):

and it will work.

super() and all subclass/superclass stuff only works with new-style classes. I recommend you get in the habit of always typing that (object) on any class definition to make sure it is a new-style class.

Old-style classes (also known as "classic" classes) are always of type classobj; new-style classes are of type type. This is why you got the error message you saw:

TypeError: super() argument 1 must be type, not classobj

Try this to see for yourself:

class OldStyle:
    pass

class NewStyle(object):
    pass

print type(OldStyle)  # prints: <type 'classobj'>

print type(NewStyle) # prints <type 'type'>

Note that in Python 3.x, all classes are new-style. You can still use the syntax from the old-style classes but you get a new-style class. So, in Python 3.x you won't have this problem.

Bootstrap 3, 4 and 5 .container-fluid with grid adding unwanted padding

Use px-0 on the container and no-gutters on the row to remove the paddings.

Quoting from Bootstrap 4 - Grid system:

Rows are wrappers for columns. Each column has horizontal padding (called a gutter) for controlling the space between them. This padding is then counteracted on the rows with negative margins. This way, all the content in your columns is visually aligned down the left side.

Columns have horizontal padding to create the gutters between individual columns, however, you can remove the margin from rows and padding from columns with .no-gutters on the .row.

Following is a live demo:

_x000D_
_x000D_
h1 {
  background-color: tomato;
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" />

<div class="container-fluid" id="div1">
  <div class="row">
    <div class="col">
        <h1>With padding : (</h1>
    </div>
  </div>
</div>

<div class="container-fluid px-0" id="div1">
  <div class="row no-gutters">
    <div class="col">
        <h1>No padding : > </h1>
    </div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

The reason this works is that container-fluid and col both have following padding:

padding-right: 15px;
padding-left: 15px;

px-0 can remove the horizontal padding from container-fluid and no-gutters can remove the padding from col.

Java: How can I compile an entire directory structure of code ?

There is a way to do this without using a pipe character, which is convenient if you are forking a process from another programming language to do this:

find $JAVA_SRC_DIR -name '*.java' -exec javac -d $OUTPUT_DIR {} +

Though if you are in Bash and/or don't mind using a pipe, then you can do:

find $JAVA_SRC_DIR -name '*.java' | xargs javac -d $OUTPUT_DIR

How to loop over a Class attributes in Java?

While I agree with Jörn's answer if your class conforms to the JavaBeabs spec, here is a good alternative if it doesn't and you use Spring.

Spring has a class named ReflectionUtils that offers some very powerful functionality, including doWithFields(class, callback), a visitor-style method that lets you iterate over a classes fields using a callback object like this:

public void analyze(Object obj){
    ReflectionUtils.doWithFields(obj.getClass(), field -> {

        System.out.println("Field name: " + field.getName());
        field.setAccessible(true);
        System.out.println("Field value: "+ field.get(obj));

    });
}

But here's a warning: the class is labeled as "for internal use only", which is a pity if you ask me

How to paste yanked text into the Vim command line

OS X

If you are using Vim in Mac OS X, unfortunately it comes with older version, and not complied with clipboard options. Luckily, Homebrew can easily solve this problem.

Install Vim:

brew install vim --with-lua --with-override-system-vi

Install the GUI version of Vim:

brew install macvim --with-lua --with-override-system-vi

Restart the terminal for it to take effect.


Append the following line to ~/.vimrc
set clipboard=unnamed

Now you can copy the line in Vim with yy and paste it system-wide.

How do I add a new class to an element dynamically?

Since everyone has given you jQuery/JS answers to this, I will provide an additional solution. The answer to your question is still no, but using LESS (a CSS Pre-processor) you can do this easily.

.first-class {
  background-color: yellow;
}
.second-class:hover {
  .first-class;
}

Quite simply, any time you hover over .second-class it will give it all the properties of .first-class. Note that it won't add the class permanently, just on hover. You can learn more about LESS here: Getting Started with LESS

Here is a SASS way to do it as well:

.first-class {
  background-color: yellow;
}
.second-class {
  &:hover {
    @extend .first-class;
  }
}

Finding a substring within a list in Python

All the answers work but they always traverse the whole list. If I understand your question, you only need the first match. So you don't have to consider the rest of the list if you found your first match:

mylist = ['abc123', 'def456', 'ghi789']
sub = 'abc'
next((s for s in mylist if sub in s), None) # returns 'abc123'

If the match is at the end of the list or for very small lists, it doesn't make a difference, but consider this example:

import timeit

mylist = ['abc123'] + ['xyz123']*1000
sub = 'abc'

timeit.timeit('[s for s in mylist if sub in s]', setup='from __main__ import mylist, sub', number=100000)
# for me 7.949463844299316 with Python 2.7, 8.568840944994008 with Python 3.4
timeit.timeit('next((s for s in mylist if sub in s), None)', setup='from __main__ import mylist, sub', number=100000) 
# for me 0.12696599960327148 with Python 2.7, 0.09955992100003641 with Python 3.4

What is the best way to know if all the variables in a Class are null?

This can be done fairly easily using a Lombok generated equals and a static EMPTY object:

import lombok.Data;

public class EmptyCheck {
    public static void main(String[] args) {
        User user1 = new User();

        User user2 = new User();
        user2.setName("name");

        System.out.println(user1.isEmpty()); // prints true
        System.out.println(user2.isEmpty()); // prints false
    }

    @Data
    public static class User {
        private static final User EMPTY = new User();

        private String id;
        private String name;
        private int age;

        public boolean isEmpty() {
            return this.equals(EMPTY);
        }
    }
}

Prerequisites:

  • Default constructor should not be implemented with custom behavior as that is used to create the EMPTY object
  • All fields of the class should have an implemented equals (built-in Java types are usually not a problem, in case of custom types you can use Lombok)

Advantages:

  • No reflection involved
  • As new fields added to the class, this does not require any maintenance as due to Lombok they will be automatically checked in the equals implementation
  • Unlike some other answers this works not just for null checks but also for primitive types which have a non-null default value (e.g. if field is int it checks for 0, in case of boolean for false, etc.)

How to implement "select all" check box in HTML?

You can use this simple code

$('.checkall').click(function(){
    var checked = $(this).prop('checked');
    $('.checkme').prop('checked', checked);
});

How do I use CREATE OR REPLACE?

You can use CORT (www.softcraftltd.co.uk/cort). This tool allows to CREATE OR REPLACE table in Oracle. It looks like:

create /*# or replace */ table MyTable(
  ... -- standard table definition
);

It preserves data.

How to change line color in EditText

To change Edittext’s underline color:

If you want the entire app to share this style, then you can do the following way.

(1) go to styles.xml file. Your AppTheme that inherits the parent of Theme.AppCompat.Light.DarkActionBar (in my case) will be the base parent of all they style files in your app. Change the name of it to “AppBaseTheme’. Make another style right under it that has the name of AppTheme and inherits from AppBaseTheme that you just edited. It will look like following:

<!-- Base application theme. -->
<style name="AppBaseTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="windowActionBar">false</item>
    <!--see http://www.google.com/design/spec/style/color.html#color-color-palette-->
    <item name="colorPrimary">@color/material_brown_500</item>
    <item name="colorPrimaryDark">@color/material_brown_700</item>
    <item name="colorAccent">@color/flamingo</item>

<style name="AppTheme" parent="AppBaseTheme">
    <!-- Customize your theme here. -->
</style>

Then change the “colorAccent” to whatever the color you want your EditText line color to be.

(2) If you have other values folders with style.xml, this step is very important. Because that file will inherit from your previous parent xml file. For example, I have values-19/styles.xml. This is specifically for Kitkat and above. Change its parent to AppBaseTheme and make sure to get rid of “colorAccent” so that it doesn’t override the parent’s color. Also you need to keep the items that are specific to version 19. Then it will look like this.

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="AppBaseTheme">
        <item name="android:windowTranslucentStatus">true</item>
    </style>
</resources>

OR, AND Operator

There is a distinction between the conditional operators && and || and the boolean operators & and |. Mainly it is a difference of precendence (which operators get evaluated first) and also the && and || are 'escaping'. This means that is a sequence such as...

cond1 && cond2 && cond3

If cond1 is false, neither cond2 or cond3 are evaluated as the code rightly assumes that no matter what their value, the expression cannot be true. Likewise...

cond1 || cond2 || cond3

If cond1 is true, neither cond2 or cond3 are evaluated as the expression must be true no matter what their value is.

The bitwise counterparts, & and | are not escaping.

Hope that helps.

How to check null objects in jQuery

jquery $() function always return non null value - mean elements matched you selector cretaria. If the element was not found it will return an empty array. So your code will look something like this -

if ($("#btext" + i).length){
        //alert($("#btext" + i).text());
    $("#btext" + i).text("Branch " + i);
}

Instantiating a generic class in Java

I really need to instantiate a T in Foo using a parameter-less constructor

Simple answer is "you cant do that" java uses type erasure to implment generics which would prevent you from doing this.

How can one work around Java's limitation?

One way (there could be others) is to pass the object that you would pass the instance of T to the constructor of Foo<T>. Or you could have a method setBar(T theInstanceofT); to get your T instead of instantiating in the class it self.

Allowing Untrusted SSL Certificates with HttpClient

Most answers here suggest to use the typical pattern:

using (var httpClient = new HttpClient())
{
 // do something
}

because of the IDisposable interface. Please don't!

Microsoft tells you why:

And here you can find a detailed analysis whats going on behind the scenes: You're using HttpClient wrong and it is destabilizing your software

Regarding your SSL question and based on Improper Instantiation antipattern # How to fix the problem

Here is your pattern:

class HttpInterface
{
 // https://docs.microsoft.com/en-us/azure/architecture/antipatterns/improper-instantiation/#how-to-fix-the-problem
 // https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient#remarks
 private static readonly HttpClient client;

 // static initialize
 static HttpInterface()
 {
  // choose one of these depending on your framework
  
  // HttpClientHandler is an HttpMessageHandler with a common set of properties
  var handler = new HttpClientHandler()
  {
      ServerCertificateCustomValidationCallback = delegate { return true; },
  };
  // derives from HttpClientHandler but adds properties that generally only are available on full .NET
  var handler = new WebRequestHandler()
  {
      ServerCertificateValidationCallback = delegate { return true; },
      ServerCertificateCustomValidationCallback = delegate { return true; },
  };

  client = new HttpClient(handler);
 }
 
 .....
 
 // in your code use the static client to do your stuff
 var jsonEncoded = new StringContent(someJsonString, Encoding.UTF8, "application/json");

 // here in sync
 using (HttpResponseMessage resultMsg = client.PostAsync(someRequestUrl, jsonEncoded).Result)
 {
  using (HttpContent respContent = resultMsg.Content)
  {
   return respContent.ReadAsStringAsync().Result;
  }
 }
}

How can I pop-up a print dialog box using Javascript?

You could do

<body onload="window.print()">
...
</body>

dynamically add and remove view to viewpager

There are quite a few discussions around this topic

Although we see it often, using POSITION_NONE does not seem to be the way to go as it is very inefficient memory-wise.

Here in this question, we should consider using Alvaro's approach:

... is to setTag() method in instantiateItem() when instantiating a new view. Then instead of using notifyDataSetChanged(), you can use findViewWithTag() to find the view you want to update.

Here is a SO answer with code based on this idea

Does file_get_contents() have a timeout setting?

For me work when i change my php.ini in my host:

; Default timeout for socket based streams (seconds)
default_socket_timeout = 300

How to get date and time from server

No need to use date_default_timezone_set for the whole script, just specify the timezone you want with a DateTime object:

$now = new DateTime(null, new DateTimeZone('America/New_York'));
$now->setTimezone(new DateTimeZone('Europe/London'));    // Another way
echo $now->format("Y-m-d\TH:i:sO"); // something like "2015-02-11T06:16:47+0100" (ISO 8601)

What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?

I'd guess foreign key constraint problem. Is country_id used as a foreign key in another table?

I'm not DB guru but I think I solved a problem like this (where there was a fk constraint) by removing the fk, doing my alter table stuff and then redoing the fk stuff.

I'll be interested to hear what the outcome is - sometime mysql is pretty cryptic.

Where do I find old versions of Android NDK?

http://dl.google.com/android/ndk/android-ndk-r9d-linux-x86_64.tar.bz2

I successfully opened gstreamer SDK tutorials in Eclipse.

All I needed is to use an older version of ndk. specificly 9d.

(10c and 10d does not work, 10b - works just for tutorial-1 )

9d does work for all tutorials ! and you can:

  1. Download it from: http://dl.google.com/android/ndk/android-ndk-r9d-linux-x86_64.tar.bz2

  2. Extract it.

  3. set it in eclipse->window->preferences->Android->NDK->NDK location.

  4. build - (ctrl+b).

Shell command to sum integers, one per line?

BASH solution, if you want to make this a command (e.g. if you need to do this frequently):

addnums () {
  local total=0
  while read val; do
    (( total += val ))
  done
  echo $total
}

Then usage:

addnums < /tmp/nums

jquery $.each() for objects

$.each() works for objects and arrays both:

var data = { "programs": [ { "name":"zonealarm", "price":"500" }, { "name":"kaspersky", "price":"200" } ] };

$.each(data.programs, function (i) {
    $.each(data.programs[i], function (key, val) {
        alert(key + val);
    });
});

...and since you will get the current array element as second argument:

$.each(data.programs, function (i, currProgram) {
    $.each(currProgram, function (key, val) {
        alert(key + val);
    });
});

Why can't I duplicate a slice with `copy()`?

The Go Programming Language Specification

Appending to and copying slices

The function copy copies slice elements from a source src to a destination dst and returns the number of elements copied. Both arguments must have identical element type T and must be assignable to a slice of type []T. The number of elements copied is the minimum of len(src) and len(dst). As a special case, copy also accepts a destination argument assignable to type []byte with a source argument of a string type. This form copies the bytes from the string into the byte slice.

copy(dst, src []T) int
copy(dst []byte, src string) int

tmp needs enough room for arr. For example,

package main

import "fmt"

func main() {
    arr := []int{1, 2, 3}
    tmp := make([]int, len(arr))
    copy(tmp, arr)
    fmt.Println(tmp)
    fmt.Println(arr)
}

Output:

[1 2 3]
[1 2 3]

Auto Scale TextView Text to Fit within Bounds

I combined some of the above suggestions to make one that scales up and down, with bisection method. It also scales within the width.

/**
 *               DO WHAT YOU WANT TO PUBLIC LICENSE
 *                    Version 2, December 2004
 *
 * Copyright (C) 2004 Sam Hocevar <[email protected]>
 *
 * Everyone is permitted to copy and distribute verbatim or modified
 * copies of this license document, and changing it is allowed as long
 * as the name is changed.
 *
 *            DO WHAT YOU WANT TO PUBLIC LICENSE
 *   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
 *
 *  0. You just DO WHAT YOU WANT TO.
 */

import android.content.Context;
import android.text.Layout.Alignment;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;

/**
 * Text view that auto adjusts text size to fit within the view. If the text
 * size equals the minimum text size and still does not fit, append with an
 * ellipsis.
 * 
 * @author Chase Colburn
 * @since Apr 4, 2011
 */
public class AutoResizeTextView extends TextView {

    // Minimum text size for this text view
    public static final float MIN_TEXT_SIZE = 10;

    // Minimum text size for this text view
    public static final float MAX_TEXT_SIZE = 128;

    private static final int BISECTION_LOOP_WATCH_DOG = 30;

    // Interface for resize notifications
    public interface OnTextResizeListener {
        public void onTextResize(TextView textView, float oldSize, float newSize);
    }

    // Our ellipse string
    private static final String mEllipsis = "...";

    // Registered resize listener
    private OnTextResizeListener mTextResizeListener;

    // Flag for text and/or size changes to force a resize
    private boolean mNeedsResize = false;

    // Text size that is set from code. This acts as a starting point for
    // resizing
    private float mTextSize;

    // Temporary upper bounds on the starting text size
    private float mMaxTextSize = MAX_TEXT_SIZE;

    // Lower bounds for text size
    private float mMinTextSize = MIN_TEXT_SIZE;

    // Text view line spacing multiplier
    private float mSpacingMult = 1.0f;

    // Text view additional line spacing
    private float mSpacingAdd = 0.0f;

    // Add ellipsis to text that overflows at the smallest text size
    private boolean mAddEllipsis = true;

    // Default constructor override
    public AutoResizeTextView(Context context) {
        this(context, null);
    }

    // Default constructor when inflating from XML file
    public AutoResizeTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    // Default constructor override
    public AutoResizeTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mTextSize = getTextSize();
    }

    /**
     * When text changes, set the force resize flag to true and reset the text
     * size.
     */
    @Override
    protected void onTextChanged(final CharSequence text, final int start,
            final int before, final int after) {
        mNeedsResize = true;
        // Since this view may be reused, it is good to reset the text size
        resetTextSize();
    }

    /**
     * If the text view size changed, set the force resize flag to true
     */
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        if (w != oldw || h != oldh) {
            mNeedsResize = true;
        }
    }

    /**
     * Register listener to receive resize notifications
     * 
     * @param listener
     */
    public void setOnResizeListener(OnTextResizeListener listener) {
        mTextResizeListener = listener;
    }

    /**
     * Override the set text size to update our internal reference values
     */
    @Override
    public void setTextSize(float size) {
        super.setTextSize(size);
        mTextSize = getTextSize();
    }

    /**
     * Override the set text size to update our internal reference values
     */
    @Override
    public void setTextSize(int unit, float size) {
        super.setTextSize(unit, size);
        mTextSize = getTextSize();
    }

    /**
     * Override the set line spacing to update our internal reference values
     */
    @Override
    public void setLineSpacing(float add, float mult) {
        super.setLineSpacing(add, mult);
        mSpacingMult = mult;
        mSpacingAdd = add;
    }

    /**
     * Set the upper text size limit and invalidate the view
     * 
     * @param maxTextSize
     */
    public void setMaxTextSize(float maxTextSize) {
        mMaxTextSize = maxTextSize;
        requestLayout();
        invalidate();
    }

    /**
     * Return upper text size limit
     * 
     * @return
     */
    public float getMaxTextSize() {
        return mMaxTextSize;
    }

    /**
     * Set the lower text size limit and invalidate the view
     * 
     * @param minTextSize
     */
    public void setMinTextSize(float minTextSize) {
        mMinTextSize = minTextSize;
        requestLayout();
        invalidate();
    }

    /**
     * Return lower text size limit
     * 
     * @return
     */
    public float getMinTextSize() {
        return mMinTextSize;
    }

    /**
     * Set flag to add ellipsis to text that overflows at the smallest text size
     * 
     * @param addEllipsis
     */
    public void setAddEllipsis(boolean addEllipsis) {
        mAddEllipsis = addEllipsis;
    }

    /**
     * Return flag to add ellipsis to text that overflows at the smallest text
     * size
     * 
     * @return
     */
    public boolean getAddEllipsis() {
        return mAddEllipsis;
    }

    /**
     * Reset the text to the original size
     */
    public void resetTextSize() {
        if (mTextSize > 0) {
            super.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize);
            // mMaxTextSize = mTextSize;
        }
    }

    /**
     * Resize text after measuring
     */

    @Override
    protected void onLayout(boolean changed, int left, int top, int right,
            int bottom) {
        if (changed || mNeedsResize) {
            int widthLimit = (right - left) - getCompoundPaddingLeft()
                    - getCompoundPaddingRight();
            int heightLimit = (bottom - top) - getCompoundPaddingBottom()
                    - getCompoundPaddingTop();
            resizeText(widthLimit, heightLimit);
        }
        super.onLayout(changed, left, top, right, bottom);
    }

    /**
     * Resize the text size with default width and height
     */
    public void resizeText() {

        // Height and width with a padding as a percentage of height
        int heightLimit = getHeight() - getPaddingBottom() - getPaddingTop();
        int widthLimit = getWidth() - getPaddingLeft() - getPaddingRight();
        resizeText(widthLimit, heightLimit);
    }

    /**
     * Resize the text size with specified width and height
     * 
     * @param width
     * @param height
     */
    public void resizeText(int width, int height) {
        CharSequence text = getText();

        // Do not resize if the view does not have dimensions or there is no
        // text
        if (text == null || text.length() == 0 || height <= 0 || width <= 0
                || mTextSize == 0) {
            return;
        }

        // Get the text view's paint object
        TextPaint textPaint = getPaint();

        // Store the current text size
        float oldTextSize = textPaint.getTextSize();

        // Bisection method: fast & precise
        float lower = mMinTextSize;
        float upper = mMaxTextSize;
        int loop_counter = 1;
        float targetTextSize = (lower + upper) / 2;
        int textHeight = getTextHeight(text, textPaint, width, targetTextSize);
        int textWidth = getTextWidth(text, textPaint, width, targetTextSize);

        while (loop_counter < BISECTION_LOOP_WATCH_DOG && upper - lower > 1) {
            targetTextSize = (lower + upper) / 2;
            textHeight = getTextHeight(text, textPaint, width, targetTextSize);
            textWidth = getTextWidth(text, textPaint, width, targetTextSize);
            if (textHeight > (height) || textWidth > (width))
                upper = targetTextSize;
            else
                lower = targetTextSize;
            loop_counter++;
        }

        targetTextSize = lower;
        textHeight = getTextHeight(text, textPaint, width, targetTextSize);

        // If we had reached our minimum text size and still don't fit, append
        // an ellipsis
        if (mAddEllipsis && targetTextSize == mMinTextSize
                && textHeight > height) {
            // Draw using a static layout
            // modified: use a copy of TextPaint for measuring
            TextPaint paintCopy = new TextPaint(textPaint);
            paintCopy.setTextSize(targetTextSize);
            StaticLayout layout = new StaticLayout(text, paintCopy, width,
                    Alignment.ALIGN_NORMAL, mSpacingMult, mSpacingAdd, false);
            // Check that we have a least one line of rendered text
            if (layout.getLineCount() > 0) {
                // Since the line at the specific vertical position would be cut
                // off,
                // we must trim up to the previous line
                int lastLine = layout.getLineForVertical(height) - 1;
                // If the text would not even fit on a single line, clear it
                if (lastLine < 0) {
                    setText("");
                }
                // Otherwise, trim to the previous line and add an ellipsis
                else {
                    int start = layout.getLineStart(lastLine);
                    int end = layout.getLineEnd(lastLine);
                    float lineWidth = layout.getLineWidth(lastLine);
                    float ellipseWidth = paintCopy.measureText(mEllipsis);

                    // Trim characters off until we have enough room to draw the
                    // ellipsis
                    while (width < lineWidth + ellipseWidth) {
                        lineWidth = paintCopy.measureText(text.subSequence(
                                start, --end + 1).toString());
                    }
                    setText(text.subSequence(0, end) + mEllipsis);
                }
            }
        }

        // Some devices try to auto adjust line spacing, so force default line
        // spacing
        // and invalidate the layout as a side effect
        setTextSize(TypedValue.COMPLEX_UNIT_PX, targetTextSize);
        setLineSpacing(mSpacingAdd, mSpacingMult);

        // Notify the listener if registered
        if (mTextResizeListener != null) {
            mTextResizeListener.onTextResize(this, oldTextSize, targetTextSize);
        }

        // Reset force resize flag
        mNeedsResize = false;
    }

    // Set the text size of the text paint object and use a static layout to
    // render text off screen before measuring
    private int getTextHeight(CharSequence source, TextPaint originalPaint,
            int width, float textSize) {
        // modified: make a copy of the original TextPaint object for measuring
        // (apparently the object gets modified while measuring, see also the
        // docs for TextView.getPaint() (which states to access it read-only)
        TextPaint paint = new TextPaint(originalPaint);
        // Update the text paint object
        paint.setTextSize(textSize);
        // Measure using a static layout
        StaticLayout layout = new StaticLayout(source, paint, width,
                Alignment.ALIGN_NORMAL, mSpacingMult, mSpacingAdd, true);
        return layout.getHeight();
    }

    // Set the text size of the text paint object and use a static layout to
    // render text off screen before measuring
    private int getTextWidth(CharSequence source, TextPaint originalPaint,
            int width, float textSize) {
        // Update the text paint object
        TextPaint paint = new TextPaint(originalPaint);
        // Draw using a static layout
        paint.setTextSize(textSize);

        StaticLayout layout = new StaticLayout(source, paint, width,
                Alignment.ALIGN_NORMAL, mSpacingMult, mSpacingAdd, true);

        return (int) layout.getLineWidth(0);
    }
}

Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails

This also happens when setting a foreign key to parent.id to child.column if the child.column has a value of 0 already and no parent.id value is 0

You would need to ensure that each child.column is NULL or has value that exists in parent.id

And now that I read the statement nos wrote, that's what he is validating.

How to read and write INI file with Python3?

contents in my backup_settings.ini file

[Settings]
year = 2020

python code for reading

import configparser
config = configparser.ConfigParser()
config.read('backup_settings.ini') #path of your .ini file
year = config.get("Settings","year") 
print(year)

for writing or updating

from pathlib import Path
import configparser
myfile = Path('backup_settings.ini')  #Path of your .ini file
config.read(myfile)
config.set('Settings', 'year','2050') #Updating existing entry 
config.set('Settings', 'day','sunday') #Writing new entry
config.write(myfile.open("w"))

output

[Settings]
year = 2050
day = sunday

How to get full REST request body using Jersey?

It does seem you would have to use a MessageBodyReader here. Here's an example, using jdom:

import org.jdom.Document;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.ext.MediaType;
import javax.ws.rs.ext.MultivaluedMap;
import java.lang.reflect.Type;
import java.lang.annotation.Annotation;
import java.io.InputStream;

@Provider // this annotation is necessary!
@ConsumeMime("application/xml") // this is a hint to the system to only consume xml mime types
public class XMLMessageBodyReader implements MessageBodyReader<Document> {
  private SAXBuilder builder = new SAXBuilder();

  public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    // check if we're requesting a jdom Document
    return Document.class.isAssignableFrom(type);
  }

  public Document readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) {
    try {
      return builder.build(entityStream);
    }
    catch (Exception e) {
      // handle error somehow
    }
  } 
}

Add this class to the list of resources your jersey deployment will process (usually configured via web.xml, I think). You can then use this reader in one of your regular resource classes like this:

@Path("/somepath") @POST
public void handleXMLData(Document doc) {
  // do something with the document
}

I haven't verified that this works exactly as typed, but that's the gist of it. More reading here:

Why use Ruby's attr_accessor, attr_reader and attr_writer?

You may use the different accessors to communicate your intent to someone reading your code, and make it easier to write classes which will work correctly no matter how their public API is called.

class Person
  attr_accessor :age
  ...
end

Here, I can see that I may both read and write the age.

class Person
  attr_reader :age
  ...
end

Here, I can see that I may only read the age. Imagine that it is set by the constructor of this class and after that remains constant. If there were a mutator (writer) for age and the class were written assuming that age, once set, does not change, then a bug could result from code calling that mutator.

But what is happening behind the scenes?

If you write:

attr_writer :age

That gets translated into:

def age=(value)
  @age = value
end

If you write:

attr_reader :age

That gets translated into:

def age
  @age
end

If you write:

attr_accessor :age

That gets translated into:

def age=(value)
  @age = value
end

def age
  @age
end

Knowing that, here's another way to think about it: If you did not have the attr_... helpers, and had to write the accessors yourself, would you write any more accessors than your class needed? For example, if age only needed to be read, would you also write a method allowing it to be written?

How to get the EXIF data from a file using C#

Here is a link to another similar SO question, which has an answer pointing to this good article on "Reading, writing and photo metadata" in .Net.

Bootstrap fullscreen layout with 100% height

Here's an answer using the latest Bootstrap 4.0.0. This layout is easier using the flexbox and sizing utility classes that are all provided in Bootstrap 4. This layout is possible with very little extra CSS.

#mmenu_screen > .row {
    min-height: 100vh;
}

.flex-fill {
    flex:1 1 auto;
}

<div id="mmenu_screen" class="container-fluid main_container d-flex">
    <div class="row flex-fill">
        <div class="col-sm-6 h-100">
            <div class="row h-50">
                <div class="col-sm-12" id="mmenu_screen--book">
                    <!-- Button for booking -->
                    Booking
                </div>
            </div>
            <div class="row h-50">
                <div class="col-sm-12" id="mmenu_screen--information">
                    <!-- Button for information -->
                    Info
                </div>
            </div>
        </div>
        <div class="col-sm-6 mmenu_screen--direktaction flex-fill">
            <!-- Button for direktaction -->
            Action
        </div>
    </div>
</div>

Demo

The flex-fill and vh-100 classes are included in Bootstrap 4.1 (and later)

How do I send a POST request with PHP?

CURL-less method with PHP5:

$url = 'http://server.com/path';
$data = array('key1' => 'value1', 'key2' => 'value2');

// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data)
    )
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }

var_dump($result);

See the PHP manual for more information on the method and how to add headers, for example:

Syntax for creating a two-dimensional array in Java

You can create them just the way others have mentioned. One more point to add: You can even create a skewed two-dimensional array with each row, not necessarily having the same number of collumns, like this:

int array[][] = new int[3][];
array[0] = new int[3];
array[1] = new int[2];
array[2] = new int[5];

Python timedelta in years

I would use datetime.date data type instead, as it is simpler when it comes to checking how many years, months and days have passed:

now = date.today()
birthday = date(1993, 4, 4)
print("you are", now.year - birthday.year, "years,", now.month - birthday.month, "months and",
  now.day - birthday.day, "days old")

Output:

you are 27 years, 7 months and 11 days old

I use timedelta when I need to perform arithmetic on a specific date:

age = now - birthday
print("addition of days to a date: ", birthday + timedelta(days=age.days))

Output:

addition of days to a date:  2020-11-15

Creating and Naming Worksheet in Excel VBA

Are you using an error handler? If you're ignoring errors and try to name a sheet the same as an existing sheet or a name with invalid characters, it could be just skipping over that line. See the CleanSheetName function here

http://www.dailydoseofexcel.com/archives/2005/01/04/naming-a-sheet-based-on-a-cell/

for a list of invalid characters that you may want to check for.

Update

Other things to try: Fully qualified references, throwing in a Doevents, code cleaning. This code qualifies your Sheets reference to ThisWorkbook (you can change it to ActiveWorkbook if that suits). It also adds a thousand DoEvents (stupid overkill, but if something's taking a while to get done, this will allow it to - you may only need one DoEvents if this actually fixes anything).

Dim WS As Worksheet
Dim i As Long

With ThisWorkbook
    Set WS = .Worksheets.Add(After:=.Sheets(.Sheets.Count))
End With

For i = 1 To 1000
    DoEvents
Next i

WS.Name = txtSheetName.Value

Finally, whenever I have a goofy VBA problem that just doesn't make sense, I use Rob Bovey's CodeCleaner. It's an add-in that exports all of your modules to text files then re-imports them. You can do it manually too. This process cleans out any corrupted p-code that's hanging around.

Solving Quadratic Equation

Here you go this should give you the correct answers every time!

a = int(input("Enter the coefficients of a: "))
b = int(input("Enter the coefficients of b: "))
c = int(input("Enter the coefficients of c: "))

d = b**2-4*a*c # discriminant

if d < 0:
    print ("This equation has no real solution")
elif d == 0:
    x = (-b+math.sqrt(b**2-4*a*c))/2*a
    print ("This equation has one solutions: "), x
else:
    x1 = (-b+math.sqrt((b**2)-(4*(a*c))))/(2*a)
    x2 = (-b-math.sqrt((b**2)-(4*(a*c))))/(2*a)
    print ("This equation has two solutions: ", x1, " or", x2)

How to find tags with only certain attributes - BeautifulSoup

if you want to only search with attribute name with any value

from bs4 import BeautifulSoup
import re

soup= BeautifulSoup(html.text,'lxml')
results = soup.findAll("td", {"valign" : re.compile(r".*")})

as per Steve Lorimer better to pass True instead of regex

results = soup.findAll("td", {"valign" : True})

How to create a delay in Swift?

Using a dispatch_after block is in most cases better than using sleep(time) as the thread on which the sleep is performed is blocked from doing other work. when using dispatch_after the thread which is worked on does not get blocked so it can do other work in the meantime.
If you are working on the main thread of your application, using sleep(time) is bad for the user experience of your app as the UI is unresponsive during that time.

Dispatch after schedules the execution of a block of code instead of freezing the thread:

Swift = 3.0

let seconds = 4.0
DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
    // Put your code which should be executed with a delay here
}

Swift < 3.0

let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), 4 * Int64(NSEC_PER_SEC))
dispatch_after(time, dispatch_get_main_queue()) {
    // Put your code which should be executed with a delay here
}

String.equals versus ==

Instead of

datos[0] == usuario

use

datos[0].equals(usuario)

== compares the reference of the variable where .equals() compares the values which is what you want.

How to query data out of the box using Spring data JPA by both Sort and Pageable?

 public List<Model> getAllData(Pageable pageable){
       List<Model> models= new ArrayList<>();
       modelRepository.findAllByOrderByIdDesc(pageable).forEach(models::add);
       return models;
   }

Find the files existing in one directory but not in the other

Meld (http://meldmerge.org/) does a great job at comparing directories and the files within.

Meld comparing directories

How to add class active on specific li on user click with jQuery

Slightly off topic but having arrived here while developing an Angular2 app I would like to share that Angular2 automatically adds the class "router-link-active" to active router links such as this one:

<li><a [routerLink]="['Dashboard']">Dashboard</a></li>

You can therefore easily style such links using CSS:

.router-link-active {
    color: red;
}

hasOwnProperty in JavaScript

hasOwnProperty() is a nice property to validate object keys. Example:

var obj = {a:1, b:2};

obj.hasOwnProperty('a') // true

"ORA-01438: value larger than specified precision allowed for this column" when inserting 3

NUMBER (precision, scale) means precision number of total digits, of which scale digits are right of the decimal point.

NUMBER(2,2) in other words means a number with 2 digits, both of which are decimals. You may mean to use NUMBER(4,2) to get 4 digits, of which 2 are decimals. Currently you can just insert values with a zero integer part.

More info at the Oracle docs.

How to show current time in JavaScript in the format HH:MM:SS?

new Date().toLocaleTimeString('it-IT')

The it-IT locale happens to pad the hour if needed and omits PM or AM 01:33:01

How can I check if a Perl array contains a particular value?

You certainly want a hash here. Place the bad parameters as keys in the hash, then decide whether a particular parameter exists in the hash.

our %bad_params = map { $_ => 1 } qw(badparam1 badparam2 badparam3)

if ($bad_params{$new_param}) {
  print "That is a bad parameter\n";
}

If you are really interested in doing it with an array, look at List::Util or List::MoreUtils

Read next word in java

Using Scanners, you will end up spawning a lot of objects for every line. You will generate a decent amount of garbage for the GC with large files. Also, it is nearly three times slower than using split().

On the other hand, If you split by space (line.split(" ")), the code will fail if you try to read a file with a different whitespace delimiter. If split() expects you to write a regular expression, and it does matching anyway, use split("\\s") instead, that matches a "bit" more whitespace than just a space character.

P.S.: Sorry, I don't have right to comment on already given answers.

Find the smallest positive integer that does not occur in a given sequence

The code below will run in O(N) time and O(N) space complexity. Check this codility link for complete running report.

The program first put all the values inside a HashMap meanwhile finding the max number in the array. The reason for doing this is to have only unique values in provided array and later check them in constant time. After this, another loop will run until the max found number and will return the first integer that is not present in the array.

   static int solution(int[] A) {
      int max = -1;
      HashMap<Integer, Boolean> dict = new HashMap<>();
      for(int a : A) {
         if(dict.get(a) == null) {
            dict.put(a, Boolean.TRUE);
         }
         if(max<a) {
            max = a;
         }
      }
      for(int i = 1; i<max; i++) {
         if(dict.get(i) == null) {
            return i;
         }
      }
      return max>0 ? max+1 : 1;
   }

Converting String array to java.util.List

List<String> strings = Arrays.asList(new String[]{"one", "two", "three"});

This is a list view of the array, the list is partly unmodifiable, you can't add or delete elements. But the time complexity is O(1).

If you want a modifiable a List:

List<String> strings = 
     new ArrayList<String>(Arrays.asList(new String[]{"one", "two", "three"}));

This will copy all elements from the source array into a new list (complexity: O(n))

Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file

If you downloaded the file from the internet, either separately or inside a .zip file or similar, it may have been "locked" because it is flagged as coming from the internet zone. Many programs will use this as a sign that the content should not be trusted.

The simplest solution is to right-click the file in Windows Explorer, select Properties, and along the bottom of this dialog, you should have an "Unblock" option. Remember to click OK to accept the change.

If you got the file from an archive, it is usually better to unblock the archive first, if the file is flagged as coming from the internet zone, and you unzip it, that flag might propagate to many of the files you just unarchived. If you unblock first, the unarchived files should be fine.

There's also a Powershell command for this, Unblock-File:

> Unblock-File *

Additionally, there are ways to write code that will remove the lock as well.

From the comments by @Defcon1: You can also combine Unblock-File with Get-ChildItem to create a pipeline that unblocks file recursively. Since Unblock-File has no way to find files recursively by itself, you have to use Get-ChildItem to do that part.

> Get-ChildItem -Path '<YOUR-SOLUTION-PATH>' -Recurse | Unblock-File

How to set div's height in css and html

To write inline styling use:

<div style="height: 100px;">
asdfashdjkfhaskjdf
</div>

Inline styling serves a purpose however, it is not recommended in most situations.

The more "proper" solution, would be to make a separate CSS sheet, include it in your HTML document, and then use either an ID or a class to reference your div.

if you have the file structure:

index.html
>>/css/
>>/css/styles.css

Then in your HTML document between <head> and </head> write:

<link href="css/styles.css" rel="stylesheet" />

Then, change your div structure to be:

<div id="someidname" class="someclassname">
    asdfashdjkfhaskjdf
</div>

In css, you can reference your div from the ID or the CLASS.

To do so write:

.someclassname { height: 100px; }

OR

#someidname { height: 100px; }

Note that if you do both, the one that comes further down the file structure will be the one that actually works.

For example... If you have:

.someclassname { height: 100px; }

.someclassname { height: 150px; }

Then in this situation the height will be 150px.

EDIT:

To answer your secondary question from your edit, probably need overflow: hidden; or overflow: visible; . You could also do this:

<div class="span12">
    <div style="height:100px;">
        asdfashdjkfhaskjdf
    </div>
</div>

What is a good regular expression to match a URL?

These are the droids you're looking for. This is taken from validator.js which is the library you should really use to do this. But if you want to roll your own, who am I to stop you? If you want pure regex then you can just take out the length check. I think it's a good idea to test the length of the URL though if you really want to determine compliance with the spec.

 function isURL(str) {
     var urlRegex = '^(?!mailto:)(?:(?:http|https|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$';
     var url = new RegExp(urlRegex, 'i');
     return str.length < 2083 && url.test(str);
}

Create sequence of repeated values, in sequence?

You missed the each= argument to rep():

R> n <- 3
R> rep(1:5, each=n)
 [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
R> 

so your example can be done with a simple

R> rep(1:8, each=20)

javascript: pause setTimeout();

You can do like below to make setTimeout pausable on server side (Node.js)

const PauseableTimeout = function(callback, delay) {
    var timerId, start, remaining = delay;

    this.pause = function() {
        global.clearTimeout(timerId);
        remaining -= Date.now() - start;
    };

    this.resume = function() {
        start = Date.now();
        global.clearTimeout(timerId);
        timerId = global.setTimeout(callback, remaining);
    };

    this.resume();
};

and you can check it as below

var timer = new PauseableTimeout(function() {
    console.log("Done!");
}, 3000);
setTimeout(()=>{
    timer.pause();
    console.log("setTimeout paused");
},1000);

setTimeout(()=>{
    console.log("setTimeout time complete");
},3000)

setTimeout(()=>{
    timer.resume();
    console.log("setTimeout resume again");
},5000)

Redis: How to access Redis log file

Found it with:

sudo tail /var/log/redis/redis-server.log -n 100

So if the setup was more standard that should be:

sudo tail /var/log/redis_6379.log -n 100

This outputs the last 100 lines of the file.

Where your log file is located is in your configs that you can access with:

redis-cli CONFIG GET *

The log file may not always be shown using the above. In that case use

tail -f `less  /etc/redis/redis.conf | grep logfile|cut -d\  -f2`

How to remove decimal values from a value of type 'double' in Java

String truncatedValue = String.format("%f", percentageValue).split("\\.")[0]; solves the purpose

The problem is two fold-

  1. To retain the integral (mathematical integer) part of the double. Hence can't typecast (int) percentageValue
  2. Truncate (and not round) the decimal part. Hence can't use String.format("%.0f", percentageValue) or new java.text.DecimalFormat("#").format(percentageValue) as both of these round the decimal part.

MySql : Grant read only options?

Even user has got answer and @Michael - sqlbot has covered mostly points very well in his post but one point is missing, so just trying to cover it.

If you want to provide read permission to a simple user (Not admin kind of)-

GRANT SELECT, EXECUTE ON DB_NAME.* TO 'user'@'localhost' IDENTIFIED BY 'PASSWORD';

Note: EXECUTE is required here, so that user can read data if there is a stored procedure which produce a report (have few select statements).

Replace localhost with specific IP from which user will connect to DB.

Additional Read Permissions are-

  • SHOW VIEW : If you want to show view schema.
  • REPLICATION CLIENT : If user need to check replication/slave status. But need to give permission on all DB.
  • PROCESS : If user need to check running process. Will work with all DB only.

Passing arguments to require (when loading module)

I'm not sure if this will still be useful to people, but with ES6 I have a way to do it that I find clean and useful.

class MyClass { 
  constructor ( arg1, arg2, arg3 )
  myFunction1 () {...}
  myFunction2 () {...}
  myFunction3 () {...}
}

module.exports = ( arg1, arg2, arg3 ) => { return new MyClass( arg1,arg2,arg3 ) }

And then you get your expected behaviour.

var MyClass = require('/MyClass.js')( arg1, arg2, arg3 )

Looping through rows in a DataView

The DataView object itself is used to loop through DataView rows.

DataView rows are represented by the DataRowView object. The DataRowView.Row property provides access to the original DataTable row.

C#

foreach (DataRowView rowView in dataView)
{
    DataRow row = rowView.Row;
    // Do something //
}

VB.NET

For Each rowView As DataRowView in dataView
    Dim row As DataRow = rowView.Row
    ' Do something '
Next

Initialize Array of Objects using NSArray

There is also a shorthand of doing this:

NSArray *persons = @[person1, person2, person3];

It's equivalent to

NSArray *persons = [NSArray arrayWithObjects:person1, person2, person3, nil];

As iiFreeman said, you still need to do proper memory management if you're not using ARC.

How do you loop through each line in a text file using a windows batch file?

I needed to process the entire line as a whole. Here is what I found to work.

for /F "tokens=*" %%A in (myfile.txt) do [process] %%A

The tokens keyword with an asterisk (*) will pull all text for the entire line. If you don't put in the asterisk it will only pull the first word on the line. I assume it has to do with spaces.

For Command on TechNet


If there are spaces in your file path, you need to use usebackq. For example.

for /F "usebackq tokens=*" %%A in ("my file.txt") do [process] %%A

Vertical align text in block element

with thanks to Vlad's answer for inspiration; tested & working on IE11, FF49, Opera40, Chrome53

li > a {
  height: 100px;
  width: 300px;
  display: table-cell;
  text-align: center; /* H align */
  vertical-align: middle;
}

centers in all directions nicely even with text wrapping, line breaks, images, etc.

I got fancy and made a snippet

_x000D_
_x000D_
li > a {_x000D_
  height: 100px;_x000D_
  width: 300px;_x000D_
  display: table-cell;_x000D_
  /*H align*/_x000D_
  text-align: center;_x000D_
  /*V align*/_x000D_
  vertical-align: middle;_x000D_
}_x000D_
a.thin {_x000D_
  width: 40px;_x000D_
}_x000D_
a.break {_x000D_
  /*force text wrap, otherwise `width` is treated as `min-width` when encountering a long word*/_x000D_
  word-break: break-all;_x000D_
}_x000D_
/*more css so you can see this easier*/_x000D_
_x000D_
li {_x000D_
  display: inline-block;_x000D_
}_x000D_
li > a {_x000D_
  padding: 10px;_x000D_
  margin: 30px;_x000D_
  background: aliceblue;_x000D_
}_x000D_
li > a:hover {_x000D_
  padding: 10px;_x000D_
  margin: 30px;_x000D_
  background: aqua;_x000D_
}
_x000D_
<li><a href="">My menu item</a>_x000D_
</li>_x000D_
<li><a href="">My menu <br> break item</a>_x000D_
</li>_x000D_
<li><a href="">My menu item that is really long and unweildly</a>_x000D_
</li>_x000D_
<li><a href="" class="thin">Good<br>Menu<br>Item</a>_x000D_
</li>_x000D_
<li><a href="" class="thin">Fantastically Menu Item</a>_x000D_
</li>_x000D_
<li><a href="" class="thin break">Fantastically Menu Item</a>_x000D_
</li>_x000D_
<br>_x000D_
note: if using "break-all" need to also use "&lt;br>" or suffer the consequences
_x000D_
_x000D_
_x000D_

Update div with jQuery ajax response html

You are setting the html of #showresults of whatever data is, and then replacing it with itself, which doesn't make much sense ?
I'm guessing you where really trying to find #showresults in the returned data, and then update the #showresults element in the DOM with the html from the one from the ajax call :

$('#submitform').click(function () {
    $.ajax({
        url: "getinfo.asp",
        data: {
            txtsearch: $('#appendedInputButton').val()
        },
        type: "GET",
        dataType: "html",
        success: function (data) {
            var result = $('<div />').append(data).find('#showresults').html();
            $('#showresults').html(result);
        },
        error: function (xhr, status) {
            alert("Sorry, there was a problem!");
        },
        complete: function (xhr, status) {
            //$('#showresults').slideDown('slow')
        }
    });
});

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0

Uninstall node-sass

npm uninstall node-sass

use sass by:

npm install -g sass
npm install --save-dev sass

Grid of responsive squares

You can make responsive grid of squares with verticaly and horizontaly centered content only with CSS. I will explain how in a step by step process but first here are 2 demos of what you can achieve :

Responsive 3x3 square grid Responsive square images in a 3x3 grid

Now let's see how to make these fancy responsive squares!



1. Making the responsive squares :

The trick for keeping elements square (or whatever other aspect ratio) is to use percent padding-bottom.
Side note: you can use top padding too or top/bottom margin but the background of the element won't display.

As top padding is calculated according to the width of the parent element (See MDN for reference), the height of the element will change according to its width. You can now Keep its aspect ratio according to its width.
At this point you can code :

HTML :

 <div></div>

CSS

div {
    width: 30%;
    padding-bottom: 30%; /* = width for a square aspect ratio */
}

Here is a simple layout example of 3*3 squares grid using the code above.

With this technique, you can make any other aspect ratio, here is a table giving the values of bottom padding according to the aspect ratio and a 30% width.

 Aspect ratio  |  padding-bottom  |  for 30% width
------------------------------------------------
    1:1        |  = width         |    30%
    1:2        |  width x 2       |    60%
    2:1        |  width x 0.5     |    15%
    4:3        |  width x 0.75    |    22.5%
    16:9       |  width x 0.5625  |    16.875%




2. Adding content inside the squares

As you can't add content directly inside the squares (it would expand their height and squares wouldn't be squares anymore) you need to create child elements (for this example I am using divs) inside them with position: absolute; and put the content inside them. This will take the content out of the flow and keep the size of the square.

Don't forget to add position:relative; on the parent divs so the absolute children are positioned/sized relatively to their parent.

Let's add some content to our 3x3 grid of squares :

HTML :

<div class="square">
    <div class="content">
        .. CONTENT HERE ..
    </div>
</div>
... and so on 9 times for 9 squares ...

CSS :

.square {
    float:left;
    position: relative;
    width: 30%;
    padding-bottom: 30%; /* = width for a 1:1 aspect ratio */
    margin:1.66%;
    overflow:hidden;
}

.content {
    position:absolute;
    height:80%; /* = 100% - 2*10% padding */
    width:90%; /* = 100% - 2*5% padding */
    padding: 10% 5%;
}

RESULT <-- with some formatting to make it pretty!



3.Centering the content

Horizontally :

This is pretty easy, you just need to add text-align:center to .content.
RESULT

Vertical alignment

This becomes serious! The trick is to use

display:table;
/* and */
display:table-cell;
vertical-align:middle;

but we can't use display:table; on .square or .content divs because it conflicts with position:absolute; so we need to create two children inside .content divs. Our code will be updated as follow :

HTML :

<div class="square">
    <div class="content">
        <div class="table">
            <div class="table-cell">
                ... CONTENT HERE ...
            </div>
        </div>
    </div>
</div>
... and so on 9 times for 9 squares ...

CSS :

.square {
    float:left;
    position: relative;
    width: 30%;
    padding-bottom : 30%; /* = width for a 1:1 aspect ratio */
    margin:1.66%;
    overflow:hidden;
}

.content {
    position:absolute;
    height:80%; /* = 100% - 2*10% padding */
    width:90%; /* = 100% - 2*5% padding */
    padding: 10% 5%;
}
.table{
    display:table;
    height:100%;
    width:100%;
}
.table-cell{
    display:table-cell;
    vertical-align:middle;
    height:100%;
    width:100%;
}




We have now finished and we can take a look at the result here :

LIVE FULLSCREEN RESULT

editable fiddle here


How to find foreign key dependencies in SQL Server?

USE information_schema;

SELECT COLUMN_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME
FROM KEY_COLUMN_USAGE
WHERE (table_name = *tablename*) AND NOT (REFERENCED_TABLE_NAME IS NULL)

Implicit type conversion rules in C++ operators

Since the other answers don't talk about the rules in C++11 here's one. From C++11 standard (draft n3337) §5/9 (emphasized the difference):

This pattern is called the usual arithmetic conversions, which are defined as follows:

— If either operand is of scoped enumeration type, no conversions are performed; if the other operand does not have the same type, the expression is ill-formed.

— If either operand is of type long double, the other shall be converted to long double.

— Otherwise, if either operand is double, the other shall be converted to double.

— Otherwise, if either operand is float, the other shall be converted to float.

— Otherwise, the integral promotions shall be performed on both operands. Then the following rules shall be applied to the promoted operands:

— If both operands have the same type, no further conversion is needed.

— Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank shall be converted to the type of the operand with greater rank.

— Otherwise, if the operand that has unsigned integer type has rank greater than or equal to the rank of the type of the other operand, the operand with signed integer type shall be converted to the type of the operand with unsigned integer type.

— Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, the operand with unsigned integer type shall be converted to the type of the operand with signed integer type.

— Otherwise, both operands shall be converted to the unsigned integer type corresponding to the type of the operand with signed integer type.

See here for a list that's frequently updated.

How to create cron job using PHP?

Added to Alister, you can edit the crontab usually (not always the case) by entering crontab -e in a ssh session on the server.

The stars represent (* means every of this unit):

[Minute] [Hour] [Day] [Month] [Day of week (0 =sunday to 6 =saturday)] [Command]

You could read some more about this here.

Http Get using Android HttpURLConnection

I have created with callBack(delegate) response to Activity class.

public class WebService extends AsyncTask<String, Void, String> {

    private Context mContext;
    private OnTaskDoneListener onTaskDoneListener;
    private String urlStr = "";

    public WebService(Context context, String url, OnTaskDoneListener onTaskDoneListener) {
        this.mContext = context;
        this.urlStr = url;
        this.onTaskDoneListener = onTaskDoneListener;
    }

    @Override
    protected String doInBackground(String... params) {
        try {

            URL mUrl = new URL(urlStr);
            HttpURLConnection httpConnection = (HttpURLConnection) mUrl.openConnection();
            httpConnection.setRequestMethod("GET");
            httpConnection.setRequestProperty("Content-length", "0");
            httpConnection.setUseCaches(false);
            httpConnection.setAllowUserInteraction(false);
            httpConnection.setConnectTimeout(100000);
            httpConnection.setReadTimeout(100000);

            httpConnection.connect();

            int responseCode = httpConnection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
                br.close();
                return sb.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        if (onTaskDoneListener != null && s != null) {
            onTaskDoneListener.onTaskDone(s);
        } else
            onTaskDoneListener.onError();
    }
}

where

public interface OnTaskDoneListener {
    void onTaskDone(String responseData);

    void onError();
}

You can modify according to your needs. It's for get

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

I wanted to set a specific date so have used this to do stuff before 2nd December 2013

if(mktime(0,0,0,12,2,2013) > strtotime('now')) {
    // do stuff
}

The 0,0,0 is midnight, the 12 is the month, the 2 is the day and the 2013 is the year.

How to make an AlertDialog in Flutter?

If you want beautiful and responsive alert dialog then you can use flutter packages like

rflutter alert ,fancy dialog,rich alert,sweet alert dialogs,easy dialog & easy alert

These alerts are good looking and responsive. Among them rflutter alert is the best. currently I am using rflutter alert for my apps.

Find methods calls in Eclipse project

Right click on method and click on Open call Hierarchy

eclipse right click call hierarchy

<strong> vs. font-weight:bold & <em> vs. font-style:italic

The problem is an issue of semantic meaning (as BoltClock mentions) and visual rendering.

Originally HTML used <b> and <i> for these purposes, entirely stylistic commands, laid down in the semantic environment of the document markup. CSS is an attempt to separate out as far as possible the stylistic elements of the medium. Thus style information such as bold and italics should go in CSS.

<strong> and <em> were introduced to fill the semantic need for text to be marked as more important or stressed. They have default stylistic interpretations akin to bold and italic, but they are not bound to that fate.

How can I autoformat/indent C code in vim?

Their is a tool called indent. You can download it with apt-get install indent, then run indent my_program.c.

Illegal pattern character 'T' when parsing a date string to java.util.Date

tl;dr

Use java.time.Instant class to parse text in standard ISO 8601 format, representing a moment in UTC.

Instant.parse( "2010-10-02T12:23:23Z" )

ISO 8601

That format is defined by the ISO 8601 standard for date-time string formats.

Both:

…use ISO 8601 formats by default for parsing and generating strings.

You should generally avoid using the old java.util.Date/.Calendar & java.text.SimpleDateFormat classes as they are notoriously troublesome, confusing, and flawed. If required for interoperating, you can convert to and fro.

java.time

Built into Java 8 and later is the new java.time framework. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.

Instant instant = Instant.parse( "2010-10-02T12:23:23Z" );  // `Instant` is always in UTC.

Convert to the old class.

java.util.Date date = java.util.Date.from( instant );  // Pass an `Instant` to the `from` method.

Time Zone

If needed, you can assign a time zone.

ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Define a time zone rather than rely implicitly on JVM’s current default time zone.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );  // Assign a time zone adjustment from UTC.

Convert.

java.util.Date date = java.util.Date.from( zdt.toInstant() );  // Extract an `Instant` from the `ZonedDateTime` to pass to the `from` method.

Joda-Time

UPDATE: The Joda-Time project is now in maintenance mode. The team advises migration to the java.time classes.

Here is some example code in Joda-Time 2.8.

org.joda.time.DateTime dateTime_Utc = new DateTime( "2010-10-02T12:23:23Z" , DateTimeZone.UTC );  // Specifying a time zone to apply, rather than implicitly assigning the JVM’s current default.

Convert to old class. Note that the assigned time zone is lost in conversion, as j.u.Date cannot be assigned a time zone.

java.util.Date date = dateTime_Utc.toDate(); // The `toDate` method converts to old class.

Time Zone

If needed, you can assign a time zone.

DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTime_Montreal = dateTime_Utc.withZone ( zone );

Table of date-time types in Java, both modern and legacy.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android.

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to display hidden characters by default (ZERO WIDTH SPACE ie. &#8203)

Not sure what you meant, but you can permanently turn showing whitespaces on and off in Settings -> Editor -> General -> Appearance -> Show whitespaces.

Also, you can set it for a current file only in View -> Active Editor -> Show WhiteSpaces.

Edit:

Had some free time since it looks like a popular issue, I had written a plugin to inspect the code for such abnormalities. It is called Zero Width Characters locator and you're welcome to give it a try.

CSS - how to make image container width fixed and height auto stretched

Try width:inherit to make the image take the width of it's container <div>. It will stretch/shrink it's height to maintain proportion. Don't set the height in the <div>, it will size to fit the image height.

img {
    width:inherit;
}

.item {
    border:1px solid pink;
    width: 120px;
    float: left;
    margin: 3px;
    padding: 3px;
}

JSFiddle example

jQuery Screen Resolution Height Adjustment

var space = $(window).height();
var diff = space - HEIGHT;
var margin = (diff > 0) ? (space - HEIGHT)/2 : 0;
$('#container').css({'margin-top': margin});

Amazon products API - Looking for basic overview and information

I found a good alternative for requesting amazon product information here: http://api-doc.axesso.de/

Its an free rest api which return alle relevant information related to the requested product.

Should I use px or rem value units in my CSS?

EMs are the ONLY thing that scales for media queries that handle +/- scaling, which people do all the time, not just blind people. Here's another very well written professional demonstration of why this matters.

By the way, this is why Zurb Foundation uses ems, while the inferior Bootstrap 3 still uses pixels.

Android: TextView: Remove spacing and padding on top and bottom

This trick worked for me (for min-sdk >= 18).

I used android:includeFontPadding="false" and a negative margin like android:layout_marginTop="-11dp" and put my TextView inside a FrameLayout ( or any ViewGroup...)

enter image description here

and finally sample codes:

<LinearLayout
    android:layout_width="60dp"
    android:layout_height="wrap_content"
    >

    <TextView
        style="@style/MyTextViews.Bold"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/yellow"
        android:textSize="48sp"
        android:layout_marginTop="-11dp"
        android:includeFontPadding="false"
        tools:text="1"/>
</LinearLayout>

Sharing a variable between multiple different threads

You can use lock variables "a" and "b" and synchronize them for locking the "critical section" in reverse order. Eg. Notify "a" then Lock "b" ,"PRINT", Notify "b" then Lock "a".

Please refer the below the code :

public class EvenOdd {

    static int a = 0;

    public static void main(String[] args) {

        EvenOdd eo = new EvenOdd();

        A aobj = eo.new A();
        B bobj = eo.new B();

        aobj.a = Lock.lock1;
        aobj.b = Lock.lock2;

        bobj.a = Lock.lock2;
        bobj.b = Lock.lock1;

        Thread t1 = new Thread(aobj);
        Thread t2 = new Thread(bobj);

        t1.start();
        t2.start();
    }

    static class Lock {
        final static Object lock1 = new Object();
        final static Object lock2 = new Object();
    }

    class A implements Runnable {

        Object a;
        Object b;

        public void run() {
            while (EvenOdd.a < 10) {
                try {
                    System.out.println(++EvenOdd.a + " A ");
                    synchronized (a) {
                        a.notify();
                    }
                    synchronized (b) {
                        b.wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    class B implements Runnable {

        Object a;
        Object b;

        public void run() {
            while (EvenOdd.a < 10) {

                try {
                    synchronized (b) {
                        b.wait();
                        System.out.println(++EvenOdd.a + " B ");
                    }
                    synchronized (a) {
                        a.notify();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

OUTPUT :

1 A 
2 B 
3 A 
4 B 
5 A 
6 B 
7 A 
8 B 
9 A 
10 B 

Find duplicate characters in a String and count the number of occurances using Java

public static void main(String args[]) {
    char Char;
    int count;
    String a = "Hi my name is Rahul";
    a = a.toLowerCase();
    for (Char = 'a'; Char <= 'z'; Char++) {
        count = 0;
        for (int i = 0; i < a.length(); i++) {
            if (a.charAt(i) == Char) {
                count++;
            }
        }
        System.out.println("Number of occurences of " + Char + " is " + count);
    }
}

Matching a space in regex

In Perl the switch is \s (whitespace).

Android setOnClickListener method - How does it work?

It works by same principle of anonymous inner class where we can instantiate an interface without actually defining a class :

Ref: https://www.geeksforgeeks.org/anonymous-inner-class-java/

Make an Installation program for C# applications and include .NET Framework installer into the setup

Include an Setup Project (New Project > Other Project Types > Setup and Deployment > Visual Studio Installer) in your solution. It has options to include the framework installer. Check out this Deployment Guide MSDN post.

How to Generate Unique Public and Private Key via RSA

What I ended up doing is create a new KeyContainer name based off of the current DateTime (DateTime.Now.Ticks.ToString()) whenever I need to create a new key and save the container name and public key to the database. Also, whenever I create a new key I would do the following:

public static string ConvertToNewKey(string oldPrivateKey)
{

    // get the current container name from the database...

    rsa.PersistKeyInCsp = false;
    rsa.Clear();
    rsa = null;

    string privateKey = AssignNewKey(true); // create the new public key and container name and write them to the database...

       // re-encrypt existing data to use the new keys and write to database...

    return privateKey;
}
public static string AssignNewKey(bool ReturnPrivateKey){
     string containerName = DateTime.Now.Ticks.ToString();
     // create the new key...
     // saves container name and public key to database...
     // and returns Private Key XML.
}

before creating the new key.

Best Practice to Organize Javascript Library & CSS Folder Structure

 root/
   assets/
      lib/-------------------------libraries--------------------
          bootstrap/--------------Libraries can have js/css/images------------
              css/
              js/
              images/  
          jquery/
              js/
          font-awesome/
              css/
              images/
     common/--------------------common section will have application level resources             
          css/
          js/
          img/

 index.html

This is how I organized my application's static resources.

Having issues with a MySQL Join that needs to meet multiple conditions

SELECT 
    u . *
FROM
    room u
        JOIN
    facilities_r fu ON fu.id_uc = u.id_uc
        AND (fu.id_fu = '4' OR fu.id_fu = '3')
WHERE
    1 and vizibility = '1'
GROUP BY id_uc
ORDER BY u_premium desc , id_uc desc

You must use OR here, not AND.

Since id_fu cannot be equal to 4 and 3, both at once.

Hexadecimal value 0x00 is a invalid character

In my case, it took some digging, but found it.

My Context

I'm looking at exception/error logs from the website using Elmah. Elmah returns the state of the server at the of time the exception, in the form of a large XML document. For our reporting engine I pretty-print the XML with XmlWriter.

During a website attack, I noticed that some xmls weren't parsing and was receiving this '.', hexadecimal value 0x00, is an invalid character. exception.

NON-RESOLUTION: I converted the document to a byte[] and sanitized it of 0x00, but it found none.

When I scanned the xml document, I found the following:

...
<form>
...
<item name="SomeField">
   <value
     string="C:\boot.ini&#x0;.htm" />
 </item>
...

There was the nul byte encoded as an html entity &#x0; !!!

RESOLUTION: To fix the encoding, I replaced the &#x0; value before loading it into my XmlDocument, because loading it will create the nul byte and it will be difficult to sanitize it from the object. Here's my entire process:

XmlDocument xml = new XmlDocument();
details.Xml = details.Xml.Replace("&#x0;", "[0x00]");  // in my case I want to see it, otherwise just replace with ""
xml.LoadXml(details.Xml);

string formattedXml = null;

// I have this in a helper function, but for this example I have put it in-line
StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings {
    OmitXmlDeclaration = true,
    Indent = true,
    IndentChars = "\t",
    NewLineHandling = NewLineHandling.None,
};
using (XmlWriter writer = XmlWriter.Create(sb, settings)) {
    xml.Save(writer);
    formattedXml = sb.ToString();
}

LESSON LEARNED: sanitize for illegal bytes using the associated html entity, if your incoming data is html encoded on entry.

Open a selected file (image, pdf, ...) programmatically from my Android Application?

Try this one add this code to your manifest file

 <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>

provide your path type path.xml

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

and add this code to your functionality

File file = new File(tempPathNameFileString);
Intent viewPdf = new Intent(Intent.ACTION_VIEW);
viewPdf.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
Uri URI = FileProvider.getUriForFile(ReportsActivity.this, ReportsActivity.this.getApplicationContext().getPackageName() + ".provider", file);
viewPdf.setDataAndType(URI, "application/pdf");
viewPdf.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
ReportsActivity.this.startActivity(viewPdf);

What's the location of the JavaFX runtime JAR file, jfxrt.jar, on Linux?

On Ubuntu with OpenJDK, it installed in /usr/lib/jvm/default-java/jre/lib/ext/jfxrt.jar (technically its a symlink to /usr/share/java/openjfx/jre/lib/ext/jfxrt.jar, but it is probably better to use the default-java link)

Export DataBase with MySQL Workbench with INSERT statements

In MySQL Workbench 6.1.

I had to click on the Apply changes button in the insertion panel (only once, because twice and MWB crashes...).

You have to do it for each of your table.

Apply changes button

Then export your schema :

Export schema

Check Generate INSERT statements for table

Check INSERT

It is okay !

Inserts ok

Python: Removing spaces from list objects

List comprehension [num.strip() for num in hello] is the fastest.

>>> import timeit
>>> hello = ['999 ',' 666 ']

>>> t1 = lambda: map(str.strip, hello)
>>> timeit.timeit(t1)
1.825870468015296

>>> t2 = lambda: list(map(str.strip, hello))
>>> timeit.timeit(t2)
2.2825958750515269

>>> t3 = lambda: [num.strip() for num in hello]
>>> timeit.timeit(t3)
1.4320335103944899

>>> t4 = lambda: [num.replace(' ', '') for num in hello]
>>> timeit.timeit(t4)
1.7670568718943969

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

So, the answers here are all a bit incomplete. The use of a '%20' to encode a space in URLs is explicitly defined in RFC3986, which defines how a URI is built. There is no mention in this specification of using a '+' for encoding spaces - if you go solely by this specification, a space must be encoded as '%20'.

The mention of using '+' for encoding spaces comes from the various incarnations of the HTML specification - specifically in the section describing content type 'application/x-www-form-urlencoded'. This is used for posting form data.

Now, the HTML 2.0 Specification (RFC1866) explicitly said, in section 8.2.2, that the Query part of a GET request's URL string should be encoded as 'application/x-www-form-urlencoded'. This, in theory, suggests that it's legal to use a '+' in the URL in the query string (after the '?').

But... does it really? Remember, HTML is itself a content specification, and URLs with query strings can be used with content other than HTML. Further, while the later versions of the HTML spec continue to define '+' as legal in 'application/x-www-form-urlencoded' content, they completely omit the part saying that GET request query strings are defined as that type. There is, in fact, no mention whatsoever about the query string encoding in anything after the HTML 2.0 spec.

Which leaves us with the question - is it valid? Certainly there's a LOT of legacy code which supports '+' in query strings, and a lot of code which generates it as well. So odds are good you won't break if you use '+'. (And, in fact, I did all the research on this recently because I discovered a major site which failed to accept '%20' in a GET query as a space. They actually failed to decode ANY percent encoded character. So the service you're using may be relevant as well.)

But from a pure reading of the specifications, without the language from the HTML 2.0 specification carried over into later versions, URLs are covered entirely by RFC3986, which means spaces ought to be converted to '%20'. And definitely that should be the case if you are requesting anything other than an HTML document.

CharSequence VS String in Java?

CharSequence

A CharSequence is an interface, not an actual class. An interface is just a set of rules (methods) that a class must contain if it implements the interface. In Android a CharSequence is an umbrella for various types of text strings. Here are some of the common ones:

(You can read more about the differences between these here.)

If you have a CharSequence object, then it is actually an object of one of the classes that implement CharSequence. For example:

CharSequence myString = "hello";
CharSequence mySpannableStringBuilder = new SpannableStringBuilder();

The benefit of having a general umbrella type like CharSequence is that you can handle multiple types with a single method. For example, if I have a method that takes a CharSequence as a parameter, I could pass in a String or a SpannableStringBuilder and it would handle either one.

public int getLength(CharSequence text) {
    return text.length();
}

String

You could say that a String is just one kind of CharSequence. However, unlike CharSequence, it is an actual class, so you can make objects from it. So you could do this:

String myString = new String();

but you can't do this:

CharSequence myCharSequence = new CharSequence(); // error: 'CharSequence is abstract; cannot be instantiated

Since CharSequence is just a list of rules that String conforms to, you could do this:

CharSequence myString = new String();

That means that any time a method asks for a CharSequence, it is fine to give it a String.

String myString = "hello";
getLength(myString); // OK

// ...

public int getLength(CharSequence text) {
    return text.length();
}

However, the opposite is not true. If the method takes a String parameter, you can't pass it something that is only generally known to be a CharSequence, because it might actually be a SpannableString or some other kind of CharSequence.

CharSequence myString = "hello";
getLength(myString); // error

// ...

public int getLength(String text) {
    return text.length();
}

how to return a char array from a function in C

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char *substring(int i,int j,char *ch)
{
    int n,k=0;
    char *ch1;
    ch1=(char*)malloc((j-i+1)*1);
    n=j-i+1;

    while(k<n)
    {
        ch1[k]=ch[i];
        i++;k++;
    }

    return (char *)ch1;
}

int main()
{
    int i=0,j=2;
    char s[]="String";
    char *test;

    test=substring(i,j,s);
    printf("%s",test);
    free(test); //free the test 
    return 0;
}

This will compile fine without any warning

  1. #include stdlib.h
  2. pass test=substring(i,j,s);
  3. remove m as it is unused
  4. either declare char substring(int i,int j,char *ch) or define it before main

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

Me, I'd do it something like this:

HTML:

onclick="myfunction({path:'/myController/myAction', ok:myfunctionOnOk, okArgs:['/myController2/myAction2','myParameter2'], cancel:myfunctionOnCancel, cancelArgs:['/myController3/myAction3','myParameter3']);"

JS:

function myfunction(params)
{
  var path = params.path;

  /* do stuff */

  // on ok condition 
  params.ok(params.okArgs);

  // on cancel condition
  params.cancel(params.cancelArgs);  
}

But then I'd also probable be binding a closure to a custom subscribed event. You need to add some detail to the question really, but being first-class functions are easily passable and getting params to them can be done any number of ways. I would avoid passing them as string labels though, the indirection is error prone.

Remove unwanted parts from strings in a column

A very simple method would be to use the extract method to select all the digits. Simply supply it the regular expression '\d+' which extracts any number of digits.

df['result'] = df.result.str.extract(r'(\d+)', expand=True).astype(int)
df

    time  result
1  09:00      52
2  10:00      62
3  11:00      44
4  12:00      30
5  13:00     110

converting Java bitmap to byte array

Try this to convert String-Bitmap or Bitmap-String

/**
 * @param bitmap
 * @return converting bitmap and return a string
 */
public static String BitMapToString(Bitmap bitmap){
    ByteArrayOutputStream baos=new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG,100, baos);
    byte [] b=baos.toByteArray();
    String temp=Base64.encodeToString(b, Base64.DEFAULT);
    return temp;
}

/**
 * @param encodedString
 * @return bitmap (from given string)
 */
public static Bitmap StringToBitMap(String encodedString){
    try{
        byte [] encodeByte=Base64.decode(encodedString,Base64.DEFAULT);
        Bitmap bitmap= BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
        return bitmap;
    }catch(Exception e){
        e.getMessage();
        return null;
    }
}

Go test string contains substring

Use the function Contains from the strings package.

import (
    "strings"
)
strings.Contains("something", "some") // true

How to add some non-standard font to a website?

I did a bit of research and dug up Dynamic Text Replacement (published 2004-06-15).

This technique uses images, but it appears to be "hands free". You write your text, and you let a few automated scripts do automated find-and-replace on the page for you on the fly.

It has some limitations, but it is probably one of the easier choices (and more browser compatible) than all the rest I've seen.

Python assigning multiple variables to same value? list behavior

in your first example a = b = c = [1, 2, 3] you are really saying:

 'a' is the same as 'b', is the same as 'c' and they are all [1, 2, 3]

If you want to set 'a' equal to 1, 'b' equal to '2' and 'c' equal to 3, try this:

a, b, c = [1, 2, 3]

print(a)
--> 1
print(b)
--> 2
print(c)
--> 3

Hope this helps!

Using Spring MVC Test to unit test multipart POST request

Have a look at this example taken from the spring MVC showcase, this is the link to the source code:

@RunWith(SpringJUnit4ClassRunner.class)
public class FileUploadControllerTests extends AbstractContextControllerTests {

    @Test
    public void readString() throws Exception {

        MockMultipartFile file = new MockMultipartFile("file", "orig", null, "bar".getBytes());

        webAppContextSetup(this.wac).build()
            .perform(fileUpload("/fileupload").file(file))
            .andExpect(model().attribute("message", "File 'orig' uploaded successfully"));
    }

}

Popup window in winform c#

"But the thing is I also want to be able to add textboxes etc in this popup window thru the form designer."

It's unclear from your description at what stage in the development process you're in. If you haven't already figured it out, to create a new Form you click on Project --> Add Windows Form, then type in a name for the form and hit the "Add" button. Now you can add controls to your form as you'd expect.

When it comes time to display it, follow the advice of the other posts to create an instance and call Show() or ShowDialog() as appropriate.

How to represent a DateTime in Excel

Some versions of Excel don't have date-time formats available in the standard pick lists, but you can just enter a custom format string such as yyyy-mm-dd hh:mm:ss by:

  1. Right click -> Format Cells
  2. Number tab
  3. Choose Category Custom
  4. Enter your custom format string into the "Type" field

This works on my Excel 2010

Extract a substring from a string in Ruby using a regular expression

String1.scan(/<([^>]*)>/).last.first

scan creates an array which, for each <item> in String1 contains the text between the < and the > in a one-element array (because when used with a regex containing capturing groups, scan creates an array containing the captures for each match). last gives you the last of those arrays and first then gives you the string in it.

Edit and Continue: "Changes are not allowed when..."

I'm adding my answer because the thing that solved it for me isn't clearly mentioned yet. Actually what helped me was this article:

http://www.rubencanton.com/blog/2012/02/how-to-fix-error-changes-are-not-allowed-while-code-is-running-in-net.html

and here is a short description of the solution:

  1. Stop running your app.
  2. Go to Tools > Options > Debugging > Edit and Continue
  3. Disable “Enable Edit and Continue”

Note how counter-intuitive this is: I had to disable (uncheck) "Enable Edit and Continue".

This will then allow you to change code in your editor without getting that message "Changes are not allowed while code is running".

Note however that the code changes you make will NOT be reflected in your running program - for that you need to stop and restart your program (off the top of my head I think that template/ASPX changes do get reflected, but not VB/C# changes, i.e. "code behind" code).

How to prevent form from submitting multiple times from client side?

This allow submit every 2 seconds. In case of front validation.

$(document).ready(function() {
    $('form[debounce]').submit(function(e) {
        const submiting = !!$(this).data('submiting');

        if(!submiting) {
            $(this).data('submiting', true);

            setTimeout(() => {
                $(this).data('submiting', false);
            }, 2000);

            return true;
        }

        e.preventDefault();
        return false;
    });
})

array.select() in javascript

There's also Array.find() in ES6 which returns the first matching element it finds.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

const myArray = [1, 2, 3]

const myElement = myArray.find((element) => element === 2)

console.log(myElement)
// => 2

Can a Windows batch file determine its own file name?

Below is my initial code:

@echo off
Set z=%%
echo.
echo %z%0.......%0
echo %z%~0......%~0
echo %z%n0......%n0
echo %z%x0......%x0
echo %z%~n0.....%~n0
echo %z%dp0.....%dp0
echo %z%~dp0....%~dp0
echo.

I noticed that file name given by %~0 and %0 is the way it was entered in the command-shell and not how that file is actually named. So if you want the literal case used for the file name you should use %~n0. However, this will leave out the file extension. But if you know the file name you could add the following code.

set b=%~0
echo %~n0%b:~8,4%

I have learned that ":~8,4%" means start at the 9th character of the variable and then show show the next 4 characters. The range is 0 to the end of the variable string. So %Path% would be very long!

fIlEnAmE.bat
012345678901

However, this is not as sound as Jool's solution (%~x0) above.

My Evidence:

C:\bin>filename.bat

%0.......filename.bat
%~0......filename.bat
. . .

C:\bin>fIlEnAmE.bat

%0.......fIlEnAmE.bat
%~0......fIlEnAmE.bat
%n0......n0
%x0......x0
%~n0.....FileName
%dp0.....dp0
%~dp0....C:\bin\

%~n0%b:~8,4%...FileName.bat

Press any key to continue . . .

C:\bin>dir
 Volume in drive C has no label.
 Volume Serial Number is CE18-5BD0

 Directory of C:\bin
. . .
05/02/2018  11:22 PM               208 FileName.bat

Here is the final code

@echo off
Set z=%%
set b=%~0
echo.
echo %z%0.......%0
echo %z%~0......%~0
echo %z%n0......%n0
echo %z%x0......%x0
echo %z%~n0.....%~n0
echo %z%dp0.....%dp0
echo %z%~dp0....%~dp0
echo.
echo A complex solution:
echo ===================================
echo %z%~n0%z%b:~8,4%z%...%~n0%b:~8,4%
echo ===================================
echo.
echo The preferred solution:
echo ===================================
echo %z%~n0%z%~x0.......%~n0%~x0
echo ===================================
pause

Add single element to array in numpy

a[0] isn't an array, it's the first element of a and therefore has no dimensions.

Try using a[0:1] instead, which will return the first element of a inside a single item array.

File.separator vs FileSystem.getSeparator() vs System.getProperty("file.separator")?

System.getProperties() can be overridden by calls to System.setProperty(String key, String value) or with command line parameters -Dfile.separator=/

File.separator gets the separator for the default filesystem.

FileSystems.getDefault() gets you the default filesystem.

FileSystem.getSeparator() gets you the separator character for the filesystem. Note that as an instance method you can use this to pass different filesystems to your code other than the default, in cases where you need your code to operate on multiple filesystems in the one JVM.

Recommendation for compressing JPG files with ImageMagick

Once I needed to resize photos from camera for developing:

  • Original filesize: 2800 kB
  • Resolution: 3264x2448

Command:

mogrify -quality "97%" -resize 2048x2048 -filter Lanczos -interlace Plane -gaussian-blur 0.05 
  • Result filesize 753 kB
  • Resolution 2048x2048

and I can't see any changes in full screen with my 1920x1080 resolution monitor. 2048 resolution is the best for developing 10 cm photos at maximum quality of 360 dpi. I don't want to strip it.

edit: I noticed that I even get much better results without blurring. Without blurring filesize is 50% of original, but quality is better (when zooming).

Using a custom typeface in Android

Hey i also need 2 different fonts in my app for different widgeds! I use this way:

In my Application class i create an static method:

public static Typeface getTypeface(Context context, String typeface) {
    if (mFont == null) {
        mFont = Typeface.createFromAsset(context.getAssets(), typeface);
    }
    return mFont;
}

The String typeface represents the xyz.ttf in the asset folder. (i created an Constants Class) Now you can use this everywhere in your app:

mTextView = (TextView) findViewById(R.id.text_view);
mTextView.setTypeface(MyApplication.getTypeface(this, Constants.TYPEFACE_XY));

The only problem is, you need this for every widget where you want to use the Font! But i think this is the best way.

Difficulty with ng-model, ng-repeat, and inputs

This seems to be a binding issue.

The advice is don't bind to primitives.

Your ngRepeat is iterating over strings inside a collection, when it should be iterating over objects. To fix your problem

<body ng-init="models = [{name:'Sam'},{name:'Harry'},{name:'Sally'}]">
    <h1>Fun with Fields and ngModel</h1>
    <p>names: {{models}}</p>
    <h3>Binding to each element directly:</h3>
    <div ng-repeat="model in models">
        Value: {{model.name}}
        <input ng-model="model.name">                         
    </div>

jsfiddle: http://jsfiddle.net/jaimem/rnw3u/5/

Get list of JSON objects with Spring RestTemplate

For me this worked

Object[] forNow = template.getForObject("URL", Object[].class);
    searchList= Arrays.asList(forNow);

Where Object is the class you want

How to install grunt and how to build script with it

To setup GruntJS build here is the steps:

  1. Make sure you have setup your package.json or setup new one:

    npm init
    
  2. Install Grunt CLI as global:

    npm install -g grunt-cli
    
  3. Install Grunt in your local project:

    npm install grunt --save-dev
    
  4. Install any Grunt Module you may need in your build process. Just for sake of this sample I will add Concat module for combining files together:

    npm install grunt-contrib-concat --save-dev
    
  5. Now you need to setup your Gruntfile.js which will describe your build process. For this sample I just combine two JS files file1.js and file2.js in the js folder and generate app.js:

    module.exports = function(grunt) {
    
        // Project configuration.
        grunt.initConfig({
            concat: {
                "options": { "separator": ";" },
                "build": {
                    "src": ["js/file1.js", "js/file2.js"],
                    "dest": "js/app.js"
                }
            }
        });
    
        // Load required modules
        grunt.loadNpmTasks('grunt-contrib-concat');
    
        // Task definitions
        grunt.registerTask('default', ['concat']);
    };
    
  6. Now you'll be ready to run your build process by following command:

    grunt
    

I hope this give you an idea how to work with GruntJS build.

NOTE:

You can use grunt-init for creating Gruntfile.js if you want wizard-based creation instead of raw coding for step 5.

To do so, please follow these steps:

npm install -g grunt-init
git clone https://github.com/gruntjs/grunt-init-gruntfile.git ~/.grunt-init/gruntfile
grunt-init gruntfile

For Windows users: If you are using cmd.exe you need to change ~/.grunt-init/gruntfile to %USERPROFILE%\.grunt-init\. PowerShell will recognize the ~ correctly.

Is a new line = \n OR \r\n?

\n is used for Unix systems (including Linux, and OSX).

\r\n is mainly used on Windows.

\r is used on really old Macs.

PHP_EOL constant is used instead of these characters for portability between platforms.

glm rotate usage in Opengl

GLM has good example of rotation : http://glm.g-truc.net/code.html

glm::mat4 Projection = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.f);
glm::mat4 ViewTranslate = glm::translate(
    glm::mat4(1.0f),
    glm::vec3(0.0f, 0.0f, -Translate)
);
glm::mat4 ViewRotateX = glm::rotate(
    ViewTranslate,
    Rotate.y,
    glm::vec3(-1.0f, 0.0f, 0.0f)
);
glm::mat4 View = glm::rotate(
    ViewRotateX,
    Rotate.x,
    glm::vec3(0.0f, 1.0f, 0.0f)
);
glm::mat4 Model = glm::scale(
    glm::mat4(1.0f),
    glm::vec3(0.5f)
);
glm::mat4 MVP = Projection * View * Model;
glUniformMatrix4fv(LocationMVP, 1, GL_FALSE, glm::value_ptr(MVP));

Callback to a Fragment from a DialogFragment

Activity involved is completely unaware of the DialogFragment.

Fragment class:

public class MyFragment extends Fragment {
int mStackLevel = 0;
public static final int DIALOG_FRAGMENT = 1;

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

    if (savedInstanceState != null) {
        mStackLevel = savedInstanceState.getInt("level");
    }
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("level", mStackLevel);
}

void showDialog(int type) {

    mStackLevel++;

    FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
    Fragment prev = getActivity().getFragmentManager().findFragmentByTag("dialog");
    if (prev != null) {
        ft.remove(prev);
    }
    ft.addToBackStack(null);

    switch (type) {

        case DIALOG_FRAGMENT:

            DialogFragment dialogFrag = MyDialogFragment.newInstance(123);
            dialogFrag.setTargetFragment(this, DIALOG_FRAGMENT);
            dialogFrag.show(getFragmentManager().beginTransaction(), "dialog");

            break;
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode) {
            case DIALOG_FRAGMENT:

                if (resultCode == Activity.RESULT_OK) {
                    // After Ok code.
                } else if (resultCode == Activity.RESULT_CANCELED){
                    // After Cancel code.
                }

                break;
        }
    }
}

}

DialogFragment class:

public class MyDialogFragment extends DialogFragment {

public static MyDialogFragment newInstance(int num){

    MyDialogFragment dialogFragment = new MyDialogFragment();
    Bundle bundle = new Bundle();
    bundle.putInt("num", num);
    dialogFragment.setArguments(bundle);

    return dialogFragment;

}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    return new AlertDialog.Builder(getActivity())
            .setTitle(R.string.ERROR)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setPositiveButton(R.string.ok_button,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, getActivity().getIntent());
                        }
                    }
            )
            .setNegativeButton(R.string.cancel_button, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_CANCELED, getActivity().getIntent());
                }
            })
            .create();
}
}

Convert string in base64 to image and save on filesystem in Python

You can also save it to a string buffer and then do as you wish with it,

import cStringIO
data = json.loads(request.POST['imgData'])  # Getting the object from the post request
image_output = cStringIO.StringIO()
image_output.write(data.decode('base64'))   # Write decoded image to buffer
image_output.seek(0)  # seek beginning of the image string
# image_output.read()  # Do as you wish with it!

In django, you can save it as an uploaded file to save to a model:

from django.core.files.uploadedfile import SimpleUploadedFile
suf = SimpleUploadedFile('uploaded_file.png', image_output.read(), content_type='image/png')

Or send it as an email:

email = EmailMessage('Hello', 'Body goes here', '[email protected]',
                                     ['[email protected]', ])
                email.attach('design.png', image_output.read(), 'image/png')
                email.send()

How can I compare two time strings in the format HH:MM:SS?

I'm not so comfortable with regular expressions, and my example results from a datetimepicker field formatted m/d/Y h:mA. In this legal example, you have to arrive before the actual deposition hearing. I use replace function to clean up the dates so that I can process them as Date objects and compare them.

function compareDateTimes() {
    //date format ex "04/20/2017 01:30PM"
    //the problem is that this format results in Invalid Date
    //var d0 = new Date("04/20/2017 01:30PM"); => Invalid Date

    var start_date = $(".letter #depo_arrival_time").val();
    var end_date = $(".letter #depo_dateandtime").val();

    if (start_date=="" || end_date=="") {
        return;
    }
    //break it up for processing
    var d1 = stringToDate(start_date);
    var d2 = stringToDate(end_date);

    var diff = d2.getTime() - d1.getTime();
    if (diff < 0) {
        end_date = moment(d2).format("MM/DD/YYYY hh:mA");
        $(".letter #depo_arrival_time").val(end_date);
    }
}

function stringToDate(the_date) {
    var arrDate = the_date.split(" ");
    var the_date = arrDate[0];
    var the_time = arrDate[1];
    var arrTime = the_time.split(":");
    var blnPM = (arrTime[1].indexOf("PM") > -1);
    //first fix the hour
    if (blnPM) {
        if (arrTime[0].indexOf("0")==0) {
            var clean_hour = arrTime[0].substr(1,1);
            arrTime[0] = Number(clean_hour) + 12;
        }
        arrTime[1] = arrTime[1].replace("PM", ":00");
    } else {
        arrTime[1] = arrTime[1].replace("AM", ":00");
    }
    var date_object =  new Date(the_date);
    //now replace the time
    date_object = String(date_object).replace("00:00:00", arrTime.join(":"));
    date_object =  new Date(date_object);

    return date_object;
}

What are the lesser known but useful data structures?

Burrows–Wheeler transform (block-sorting compression)

Its essential algorithm for compression. Let say that you want to compress lines on text files. You would say that if you sort the lines, you lost information. But BWT works like this - it reduces entropy a lot by sorting input, keeping integer indexes to recover the original order.

Math.random() versus Random.nextInt(int)

According to this example Random.nextInt(n) has less predictable output then Math.random() * n. According to [sorted array faster than an unsorted array][1] I think we can say Random.nextInt(n) is hard to predict.

usingRandomClass : time:328 milesecond.

usingMathsRandom : time:187 milesecond.

package javaFuction;
import java.util.Random;
public class RandomFuction 
{
    static int array[] = new int[9999];
    static long sum = 0;
    public static void usingMathsRandom() {
        for (int i = 0; i < 9999; i++) {
         array[i] = (int) (Math.random() * 256);
       }

        for (int i = 0; i < 9999; i++) {
            for (int j = 0; j < 9999; j++) {
                if (array[j] >= 128) {
                    sum += array[j];
                }
            }
        }
    }

    public static void usingRandomClass() {
        Random random = new Random();
        for (int i = 0; i < 9999; i++) {
            array[i] = random.nextInt(256);
        }

        for (int i = 0; i < 9999; i++) {
            for (int j = 0; j < 9999; j++) {
                if (array[j] >= 128) {
                    sum += array[j];
                }
            }

        }

    }

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        usingRandomClass();
        long end = System.currentTimeMillis();
        System.out.println("usingRandomClass " + (end - start));
        start = System.currentTimeMillis();
        usingMathsRandom();
        end = System.currentTimeMillis();
        System.out.println("usingMathsRandom " + (end - start));

    }

}

Pass Additional ViewData to a Strongly-Typed Partial View

I know this is an old post but I came across it when faced with a similar issue using core 3.0, hope it helps someone.

@{
Layout = null;
ViewData["SampleString"] = "some string need in the partial";
}

<partial name="_Partial" for="PartialViewModel" view-data="ViewData" />

HTTP Headers for File Downloads

Acoording to RFC 2046 (Multipurpose Internet Mail Extensions):

The recommended action for an implementation that receives an
"application/octet-stream" entity is to simply offer to put the data in a file

So I'd go for that one.

Vertically centering Bootstrap modal window

No need to us javascript. Boostrap modal adds .in class when it appears. Just modify this class combination with modalclassName.fade.in with flex css and you are done.

add this css to center your modal vertically and horizontally.

.modal.fade.in {
    display: flex !important;
    justify-content: center;
    align-items: center;
}
.modal.fade.in .modal-dialog {
    width: 100%;
}

Why can I not switch branches?

Since the file is modified by both, Either you need to add it by

git add Whereami.xcodeproj/project.xcworkspace/xcuserdatauser.xcuserdatad/UserInterfaceState.xcuserstate

Or if you would like to ignore yoyr changes, then do

git reset HEAD Whereami.xcodeproj/project.xcworkspace/xcuserdatauser.xcuserdatad/UserInterfaceState.xcuserstate

After that just switch your branch.This should do the trick.

Loading and parsing a JSON file with multiple JSON objects

You have a JSON Lines format text file. You need to parse your file line by line:

import json

data = []
with open('file') as f:
    for line in f:
        data.append(json.loads(line))

Each line contains valid JSON, but as a whole, it is not a valid JSON value as there is no top-level list or object definition.

Note that because the file contains JSON per line, you are saved the headaches of trying to parse it all in one go or to figure out a streaming JSON parser. You can now opt to process each line separately before moving on to the next, saving memory in the process. You probably don't want to append each result to one list and then process everything if your file is really big.

If you have a file containing individual JSON objects with delimiters in-between, use How do I use the 'json' module to read in one JSON object at a time? to parse out individual objects using a buffered method.

Mean filter for smoothing images in Matlab

and the convolution is defined through a multiplication in transform domain:

conv2(x,y) = fftshift(ifft2(fft2(x).*fft2(y)))

if one channel is considered... for more channels this has to be done every channel

Getting URL hash location, and using it in jQuery

Editor's note: the approach below has serious security implications and, depending upon the version of jQuery you are using, may expose your users to XSS attacks. For more detail, see the discussion of the possible attack in the comments on this answer or this explanation on Security Stack Exchange.

You can use the location.hash property to grab the hash of the current page:

var hash = window.location.hash;
$('ul'+hash+':first').show();

Note that this property already contains the # symbol at the beginning.

Actually you don't need the :first pseudo-selector since you are using the ID selector, is assumed that IDs are unique within the DOM.

In case you want to get the hash from an URL string, you can use the String.substring method:

var url = "http://example.com/file.htm#foo";
var hash = url.substring(url.indexOf('#')); // '#foo'

Advice: Be aware that the user can change the hash as he wants, injecting anything to your selector, you should check the hash before using it.

Font scaling based on width of container

I've prepared a simple scale function using CSS transform instead of font-size. You can use it inside of any container, you don't have to set media queries, etc. :)

Blog post: Full width CSS & JS scalable header

The code:

function scaleHeader() {
  var scalable = document.querySelectorAll('.scale--js');
  var margin = 10;
  for (var i = 0; i < scalable.length; i++) {
    var scalableContainer = scalable[i].parentNode;
    scalable[i].style.transform = 'scale(1)';
    var scalableContainerWidth = scalableContainer.offsetWidth - margin;
    var scalableWidth = scalable[i].offsetWidth;
    scalable[i].style.transform = 'scale(' + scalableContainerWidth / scalableWidth + ')';
    scalableContainer.style.height = scalable[i].getBoundingClientRect().height + 'px';
  }
}

Working demo: https://codepen.io/maciejkorsan/pen/BWLryj

Add numpy array as column to Pandas data frame

You can add and retrieve a numpy array from dataframe using this:

import numpy as np
import pandas as pd

df = pd.DataFrame({'b':range(10)}) # target dataframe
a = np.random.normal(size=(10,2)) # numpy array
df['a']=a.tolist() # save array
np.array(df['a'].tolist()) # retrieve array

This builds on the previous answer that confused me because of the sparse part and this works well for a non-sparse numpy arrray.

The current .NET SDK does not support targeting .NET Standard 2.0 error in Visual Studio 2017 update 15.3

I had the same problem as the current .NET SDK does not support targeting .NET Core 3.1. Either target .NET Core 1.1 or lower, or use a version of the .NET SDK that supports .NET Core 3.1

1) Make sure .Net core SDK installed on your machine. Download .NET!

2) set PATH environment variables as below Path

Button that refreshes the page on click

<button onclick=location=URL>Refresh</button>

This might look funny but it really does the trick.

Copy existing project with a new name in Android Studio

The purpose of this is so I can have a second version of my app which is ad supported in the app store.

Currently the best way to do it is without copying the project.
You can do it using diffent flavors in your build.gradle file.

 productFlavors {
        flavor1 {
            applicationId = "com.example.my.pkg.flavor1"
        }
        flavorAdSUpport {
            applicationId = "com.example.my.pkg.flavor2"
        }
  }

In this way you have only a copy of the files and you can handle the difference easily.

HTML input fields does not get focus when clicked

When you say

and nope, they don't have attributes: disabled="disabled" or readonly ;-)

Is this through viewing your html, the source code of the page, or the DOM?

If you inspect the DOM with Chrome or Firefox, then you will be able to see any attributes added to the input fields through javasript, or even an overlaying div

An existing connection was forcibly closed by the remote host

For anyone getting this exception while reading data from the stream, this may help. I was getting this exception when reading the HttpResponseMessage in a loop like this:

using (var remoteStream = await response.Content.ReadAsStreamAsync())
using (var content = File.Create(DownloadPath))
{
    var buffer = new byte[1024];
    int read;

    while ((read = await remoteStream.ReadAsync(buffer, 0, buffer.Length)) != 0)
    {
        await content.WriteAsync(buffer, 0, read);
        await content.FlushAsync();
    }
}

After some time I found out the culprit was the buffer size, which was too small and didn't play well with my weak Azure instance. What helped was to change the code to:

using (Stream remoteStream = await response.Content.ReadAsStreamAsync())
using (FileStream content = File.Create(DownloadPath))
{
    await remoteStream.CopyToAsync(content);
}

CopyTo() method has a default buffer size of 81920. The bigger buffer sped up the process and the errors stopped immediately, most likely because the overall download speeds increased. But why would download speed matter in preventing this error?

It is possible that you get disconnected from the server because the download speeds drop below minimum threshold the server is configured to allow. For example, in case the application you are downloading the file from is hosted on IIS, it can be a problem with http.sys configuration:

"Http.sys is the http protocol stack that IIS uses to perform http communication with clients. It has a timer called MinBytesPerSecond that is responsible for killing a connection if its transfer rate drops below some kb/sec threshold. By default, that threshold is set to 240 kb/sec."

The issue is described in this old blogpost from TFS development team and concerns IIS specifically, but may point you in a right direction. It also mentions an old bug related to this http.sys attribute: link

In case you are using Azure app services and increasing the buffer size does not eliminate the problem, try to scale up your machine as well. You will be allocated more resources including connection bandwidth.

Comparing user-inputted characters in C

answer shouldn't be a pointer, the intent is obviously to hold a character. scanf takes the address of this character, so it should be called as

char answer;
scanf(" %c", &answer);

Next, your "or" statement is formed incorrectly.

if (answer == 'Y' || answer == 'y')

What you wrote originally asks to compare answer with the result of 'Y' || 'y', which I'm guessing isn't quite what you wanted to do.

ORA-12505, TNS:listener does not currently know of SID given in connect descriptor

I fixed this issue by changing "SID" to "SERVICE_NAME" in my TNSNAMES.ora file.

Please see if your DB asks for SID or SERVICE_NAME.

Cheers

Bootstrap 4 img-circle class not working

In Bootstrap 4 it was renamed to .rounded-circle

Usage :

<div class="col-xs-7">
    <img src="img/gallery2.JPG" class="rounded-circle" alt="HelPic>
</div>

See migration docs from bootstrap.

Are the decimal places in a CSS width respected?

The width will be rounded to an integer number of pixels.

I don't know if every browser will round it the same way though. They all seem to have a different strategy when rounding sub-pixel percentages. If you're interested in the details of sub-pixel rounding in different browsers, there's an excellent article on ElastiCSS.

edit: I tested @Skilldrick's demo in some browsers for the sake of curiosity. When using fractional pixel values (not percentages, they work as suggested in the article I linked) IE9p7 and FF4b7 seem to round to the nearest pixel, while Opera 11b, Chrome 9.0.587.0 and Safari 5.0.3 truncate the decimal places. Not that I hoped that they had something in common after all...

Is try-catch like error handling possible in ASP Classic?

There are two approaches, you can code in JScript or VBScript which do have the construct or you can fudge it in your code.

Using JScript you'd use the following type of construct:

<script language="jscript" runat="server">
try  {
    tryStatements
}
catch(exception) {
    catchStatements
}
finally {
    finallyStatements
}
</script>

In your ASP code you fudge it by using on error resume next at the point you'd have a try and checking err.Number at the point of a catch like:

<%
' Turn off error Handling
On Error Resume Next


'Code here that you want to catch errors from

' Error Handler
If Err.Number <> 0 Then
   ' Error Occurred - Trap it
   On Error Goto 0 ' Turn error handling back on for errors in your handling block
   ' Code to cope with the error here
End If
On Error Goto 0 ' Reset error handling.

%>

How do you dynamically add elements to a ListView on Android?

If you want to have the ListView in an AppCompatActivity instead of ListActivity, you can do the following (Modifying @Shardul's answer):

public class ListViewDemoActivity extends AppCompatActivity {
    //LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
    ArrayList<String> listItems=new ArrayList<String>();

    //DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LISTVIEW
    ArrayAdapter<String> adapter;

    //RECORDING HOW MANY TIMES THE BUTTON HAS BEEN CLICKED
    int clickCounter=0;
    private ListView mListView;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.activity_list_view_demo);

        if (mListView == null) {
            mListView = (ListView) findViewById(R.id.listDemo);
        }

        adapter=new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1,
                listItems);
        setListAdapter(adapter);
    }

    //METHOD WHICH WILL HANDLE DYNAMIC INSERTION
    public void addItems(View v) {
        listItems.add("Clicked : "+clickCounter++);
        adapter.notifyDataSetChanged();
    }

    protected ListView getListView() {
        if (mListView == null) {
            mListView = (ListView) findViewById(R.id.listDemo);
        }
        return mListView;
    }

    protected void setListAdapter(ListAdapter adapter) {
        getListView().setAdapter(adapter);
    }

    protected ListAdapter getListAdapter() {
        ListAdapter adapter = getListView().getAdapter();
        if (adapter instanceof HeaderViewListAdapter) {
            return ((HeaderViewListAdapter)adapter).getWrappedAdapter();
        } else {
            return adapter;
        }
    }
}

And in you layout instead of using android:id="@android:id/list" you can use android:id="@+id/listDemo"

So now you can have a ListView inside a normal AppCompatActivity.

How to convert a date to milliseconds

You don't have a Date, you have a String representation of a date. You should convert the String into a Date and then obtain the milliseconds. To convert a String into a Date and vice versa you should use SimpleDateFormat class.

Here's an example of what you want/need to do (assuming time zone is not involved here):

String myDate = "2014/10/29 18:10:45";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = sdf.parse(myDate);
long millis = date.getTime();

Still, be careful because in Java the milliseconds obtained are the milliseconds between the desired epoch and 1970-01-01 00:00:00.


Using the new Date/Time API available since Java 8:

String myDate = "2014/10/29 18:10:45";
LocalDateTime localDateTime = LocalDateTime.parse(myDate,
    DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss") );
/*
  With this new Date/Time API, when using a date, you need to
  specify the Zone where the date/time will be used. For your case,
  seems that you want/need to use the default zone of your system.
  Check which zone you need to use for specific behaviour e.g.
  CET or America/Lima
*/
long millis = localDateTime
    .atZone(ZoneId.systemDefault())
    .toInstant().toEpochMilli();

Quick Sort Vs Merge Sort

For Merge sort worst case is O(n*log(n)), for Quick sort: O(n2). For other cases (avg, best) both have O(n*log(n)). However Quick sort is space constant where Merge sort depends on the structure you're sorting.

See this comparison.

You can also see it visually.

Select columns based on string match - dplyr::select

No need to use select just use [ instead

data[,grepl("search_string", colnames(data))]

Let's try with iris dataset

>iris[,grepl("Sepal", colnames(iris))]
  Sepal.Length Sepal.Width
1          5.1         3.5
2          4.9         3.0
3          4.7         3.2
4          4.6         3.1
5          5.0         3.6
6          5.4         3.9

jQuery - Illegal invocation

If you want to submit a form using Javascript FormData API with uploading files you need to set below two options:

processData: false,
contentType: false

You can try as follows:

//Ajax Form Submission
$(document).on("click", ".afs", function (e) {
    e.preventDefault();
    e.stopPropagation();
    var thisBtn = $(this);
    var thisForm = thisBtn.closest("form");
    var formData = new FormData(thisForm[0]);
    //var formData = thisForm.serializeArray();

    $.ajax({
        type: "POST",
        url: "<?=base_url();?>assignment/createAssignment",
        data: formData,
        processData: false,
        contentType: false,
        success:function(data){
            if(data=='yes')
            {
                alert('Success! Record inserted successfully');
            }
            else if(data=='no')
            {
                alert('Error! Record not inserted successfully')
            }
            else
            {
                alert('Error! Try again');
            }
        }
    });
});

ngrok command not found

Ngrok can be installed with Yarn , then you can run by power Sheel. it's was the only way that worked for me in windows 10 . In the begin you need to install the Node : https://nodejs.org/en/. and the yarn: https://nodejs.org/en/.

how to activate a textbox if I select an other option in drop down box

Simply

<select id = 'color2'
        name = 'color'
        onchange = "if ($('#color2').val() == 'others') {
                      $('#color').show();
                    } else {
                      $('#color').hide();
                    }">
  <option value="red">RED</option>
  <option value="blue">BLUE</option>
  <option value="others">others</option>
</select>

<input type = 'text'
       name = 'color'
       id = 'color' />

edit: requires JQuery plugin

write() versus writelines() and concatenated strings

  • writelines expects an iterable of strings
  • write expects a single string.

line1 + "\n" + line2 merges those strings together into a single string before passing it to write.

Note that if you have many lines, you may want to use "\n".join(list_of_lines).

Pass an array of integers to ASP.NET Web API?

I just added the Query key (Refit lib) in the property for the request.

[Query(CollectionFormat.Multi)]

public class ExampleRequest
{
       
        [FromQuery(Name = "name")]
        public string Name { get; set; }               
       
        [AliasAs("category")]
        [Query(CollectionFormat.Multi)]
        public List<string> Categories { get; set; }
}

jQuery Refresh/Reload Page if Ajax Success after time

$.ajax("youurl", function(data){
    if (data.success == true)
    setTimeout(function(){window.location = window.location}, 5000); 
    })
)

html script src="" triggering redirection with button

I was having this problem but i found out that it was a permissions problem I changed my permissions to 0744 and now it works. I don't know if this was your problem but it worked for me.

What is the order of precedence for CSS?

Also important to note is that when you have two styles on an HTML element with equal precedence, the browser will give precedence to the styles that were written to the DOM last ... so if in the DOM:

<html>
<head>
<style>.container-ext { width: 100%; }</style>
<style>.container { width: 50px; }</style>
</head>
<body>
<div class="container container-ext">Hello World</div>
</body>

...the width of the div will be 50px

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

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

Git - Pushing code to two remotes

To send to both remote with one command, you can create a alias for it:

git config alias.pushall '!git push origin devel && git push github devel'

With this, when you use the command git pushall, it will update both repositories.

How do I show the schema of a table in a MySQL database?

Perhaps the question needs to be slightly more precise here about what is required because it can be read it two different ways. i.e.

  1. How do I get the structure/definition for a table in mysql?
  2. How do I get the name of the schema/database this table resides in?

Given the accepted answer, the OP clearly intended it to be interpreted the first way. For anybody reading the question the other way try

SELECT `table_schema` 
FROM `information_schema`.`tables` 
WHERE `table_name` = 'whatever';

How do I measure the execution time of JavaScript code with callbacks?

Surprised no one had mentioned yet the new built in libraries:

Available in Node >= 8.5, and should be in Modern Browers

https://developer.mozilla.org/en-US/docs/Web/API/Performance

https://nodejs.org/docs/latest-v8.x/api/perf_hooks.html#

Node 8.5 ~ 9.x (Firefox, Chrome)

_x000D_
_x000D_
// const { performance } = require('perf_hooks'); // enable for node
const delay = time => new Promise(res=>setTimeout(res,time))
async function doSomeLongRunningProcess(){
  await delay(1000);
}
performance.mark('A');
(async ()=>{
  await doSomeLongRunningProcess();
  performance.mark('B');
  performance.measure('A to B', 'A', 'B');
  const measure = performance.getEntriesByName('A to B')[0];
  // firefox appears to only show second precision.
  console.log(measure.duration);
  // apparently you should clean up...
  performance.clearMarks();
  performance.clearMeasures();         
  // Prints the number of milliseconds between Mark 'A' and Mark 'B'
})();
_x000D_
_x000D_
_x000D_

https://repl.it/@CodyGeisler/NodeJsPerformanceHooks

Node 12.x

https://nodejs.org/docs/latest-v12.x/api/perf_hooks.html

const { PerformanceObserver, performance } = require('perf_hooks');
const delay = time => new Promise(res => setTimeout(res, time))
async function doSomeLongRunningProcess() {
    await delay(1000);
}
const obs = new PerformanceObserver((items) => {
    console.log('PerformanceObserver A to B',items.getEntries()[0].duration);
      // apparently you should clean up...
      performance.clearMarks();
      // performance.clearMeasures(); // Not a function in Node.js 12
});
obs.observe({ entryTypes: ['measure'] });

performance.mark('A');

(async function main(){
    try{
        await performance.timerify(doSomeLongRunningProcess)();
        performance.mark('B');
        performance.measure('A to B', 'A', 'B');
    }catch(e){
        console.log('main() error',e);
    }
})();

C default arguments

Wow, everybody is such a pessimist around here. The answer is yes.

It ain't trivial: by the end, we'll have the core function, a supporting struct, a wrapper function, and a macro around the wrapper function. In my work I have a set of macros to automate all this; once you understand the flow it'll be easy for you to do the same.

I've written this up elsewhere, so here's a detailed external link to supplement the summary here: http://modelingwithdata.org/arch/00000022.htm

We'd like to turn

double f(int i, double x)

into a function that takes defaults (i=8, x=3.14). Define a companion struct:

typedef struct {
    int i;
    double x;
} f_args;

Rename your function f_base, and define a wrapper function that sets defaults and calls the base:

double var_f(f_args in){
    int i_out = in.i ? in.i : 8;
    double x_out = in.x ? in.x : 3.14;
    return f_base(i_out, x_out);
}

Now add a macro, using C's variadic macros. This way users don't have to know they're actually populating a f_args struct and think they're doing the usual:

#define f(...) var_f((f_args){__VA_ARGS__});

OK, now all of the following would work:

f(3, 8);      //i=3, x=8
f(.i=1, 2.3); //i=1, x=2.3
f(2);         //i=2, x=3.14
f(.x=9.2);    //i=8, x=9.2

Check the rules on how compound initializers set defaults for the exact rules.

One thing that won't work: f(0), because we can't distinguish between a missing value and zero. In my experience, this is something to watch out for, but can be taken care of as the need arises---half the time your default really is zero.

I went through the trouble of writing this up because I think named arguments and defaults really do make coding in C easier and even more fun. And C is awesome for being so simple and still having enough there to make all this possible.

What is Python Whitespace and how does it work?

Whitespace is used to denote blocks. In other languages curly brackets ({ and }) are common. When you indent, it becomes a child of the previous line. In addition to the indentation, the parent also has a colon following it.

im_a_parent:
    im_a_child:
        im_a_grandchild
    im_another_child:
        im_another_grand_child

Off the top of my head, def, if, elif, else, try, except, finally, with, for, while, and class all start blocks. To end a block, you simple outdent, and you will have siblings. In the above im_a_child and im_another_child are siblings.

git: patch does not apply

Try using the solution suggested here: https://www.drupal.org/node/1129120

patch -p1 < example.patch

This helped me .

How do I handle a click anywhere in the page, even when a certain element stops the propagation?

this is the key (vs evt.target). See example.

_x000D_
_x000D_
document.body.addEventListener("click", function (evt) {_x000D_
    console.dir(this);_x000D_
    //note evt.target can be a nested element, not the body element, resulting in misfires_x000D_
    console.log(evt.target);_x000D_
    alert("body clicked");_x000D_
});
_x000D_
<h4>This is a heading.</h4>_x000D_
<p>this is a paragraph.</p>
_x000D_
_x000D_
_x000D_

#pragma once vs include guards?

After engaging in an extended discussion about the supposed performance tradeoff between #pragma once and #ifndef guards vs. the argument of correctness or not (I was taking the side of #pragma once based on some relatively recent indoctrination to that end), I decided to finally test the theory that #pragma once is faster because the compiler doesn't have to try to re-#include a file that had already been included.

For the test, I automatically generated 500 header files with complex interdependencies, and had a .c file that #includes them all. I ran the test three ways, once with just #ifndef, once with just #pragma once, and once with both. I performed the test on a fairly modern system (a 2014 MacBook Pro running OSX, using XCode's bundled Clang, with the internal SSD).

First, the test code:

#include <stdio.h>

//#define IFNDEF_GUARD
//#define PRAGMA_ONCE

int main(void)
{
    int i, j;
    FILE* fp;

    for (i = 0; i < 500; i++) {
        char fname[100];

        snprintf(fname, 100, "include%d.h", i);
        fp = fopen(fname, "w");

#ifdef IFNDEF_GUARD
        fprintf(fp, "#ifndef _INCLUDE%d_H\n#define _INCLUDE%d_H\n", i, i);
#endif
#ifdef PRAGMA_ONCE
        fprintf(fp, "#pragma once\n");
#endif


        for (j = 0; j < i; j++) {
            fprintf(fp, "#include \"include%d.h\"\n", j);
        }

        fprintf(fp, "int foo%d(void) { return %d; }\n", i, i);

#ifdef IFNDEF_GUARD
        fprintf(fp, "#endif\n");
#endif

        fclose(fp);
    }

    fp = fopen("main.c", "w");
    for (int i = 0; i < 100; i++) {
        fprintf(fp, "#include \"include%d.h\"\n", i);
    }
    fprintf(fp, "int main(void){int n;");
    for (int i = 0; i < 100; i++) {
        fprintf(fp, "n += foo%d();\n", i);
    }
    fprintf(fp, "return n;}");
    fclose(fp);
    return 0;
}

And now, my various test runs:

folio[~/Desktop/pragma] fluffy$ gcc pragma.c -DIFNDEF_GUARD
folio[~/Desktop/pragma] fluffy$ ./a.out 
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.164s
user    0m0.105s
sys 0m0.041s
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.140s
user    0m0.097s
sys 0m0.018s
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.193s
user    0m0.143s
sys 0m0.024s
folio[~/Desktop/pragma] fluffy$ gcc pragma.c -DPRAGMA_ONCE
folio[~/Desktop/pragma] fluffy$ ./a.out 
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.153s
user    0m0.101s
sys 0m0.031s
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.170s
user    0m0.109s
sys 0m0.033s
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.155s
user    0m0.105s
sys 0m0.027s
folio[~/Desktop/pragma] fluffy$ gcc pragma.c -DPRAGMA_ONCE -DIFNDEF_GUARD
folio[~/Desktop/pragma] fluffy$ ./a.out 
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.153s
user    0m0.101s
sys 0m0.027s
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.181s
user    0m0.133s
sys 0m0.020s
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.167s
user    0m0.119s
sys 0m0.021s
folio[~/Desktop/pragma] fluffy$ gcc --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/usr/include/c++/4.2.1
Apple LLVM version 8.1.0 (clang-802.0.42)
Target: x86_64-apple-darwin17.0.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

As you can see, the versions with #pragma once were indeed slightly faster to preprocess than the #ifndef-only one, but the difference was quite negligible, and would be far overshadowed by the amount of time that actually building and linking the code would take. Perhaps with a large enough codebase it might actually lead to a difference in build times of a few seconds, but between modern compilers being able to optimize #ifndef guards, the fact that OSes have good disk caches, and the increasing speeds of storage technology, it seems that the performance argument is moot, at least on a typical developer system in this day and age. Older and more exotic build environments (e.g. headers hosted on a network share, building from tape, etc.) may change the equation somewhat but in those circumstances it seems more useful to simply make a less fragile build environment in the first place.

The fact of the matter is, #ifndef is standardized with standard behavior whereas #pragma once is not, and #ifndef also handles weird filesystem and search path corner cases whereas #pragma once can get very confused by certain things, leading to incorrect behavior which the programmer has no control over. The main problem with #ifndef is programmers choosing bad names for their guards (with name collisions and so on) and even then it's quite possible for the consumer of an API to override those poor names using #undef - not a perfect solution, perhaps, but it's possible, whereas #pragma once has no recourse if the compiler is erroneously culling an #include.

Thus, even though #pragma once is demonstrably (slightly) faster, I don't agree that this in and of itself is a reason to use it over #ifndef guards.

EDIT: Thanks to feedback from @LightnessRacesInOrbit I've increased the number of header files and changed the test to only run the preprocessor step, eliminating whatever small amount of time was being added in by the compile and link process (which was trivial before and nonexistent now). As expected, the differential is about the same.

in querySelector: how to get the first and get the last elements? what traversal order is used in the dom?

Example to get last article or any other element:

document.querySelector("article:last-child")

Rails find_or_create_by more than one attribute?

Multiple attributes can be connected with an and:

GroupMember.find_or_create_by_member_id_and_group_id(4, 7)

(use find_or_initialize_by if you don't want to save the record right away)

Edit: The above method is deprecated in Rails 4. The new way to do it will be:

GroupMember.where(:member_id => 4, :group_id => 7).first_or_create

and

GroupMember.where(:member_id => 4, :group_id => 7).first_or_initialize

Edit 2: Not all of these were factored out of rails just the attribute specific ones.

https://github.com/rails/rails/blob/4-2-stable/guides/source/active_record_querying.md

Example

GroupMember.find_or_create_by_member_id_and_group_id(4, 7)

became

GroupMember.find_or_create_by(member_id: 4, group_id: 7)

Remove characters before character "."

String input = ....;
int index = input.IndexOf('.');
if(index >= 0)
{
    return input.Substring(index + 1);
}

This will return the new word.