Programs & Examples On #Openwysiwyg

What are sessions? How do they work?

Think of HTTP as a person(A) who has SHORT TERM MEMORY LOSS and forgets every person as soon as that person goes out of sight.

Now, to remember different persons, A takes a photo of that person and keeps it. Each Person's pic has an ID number. When that person comes again in sight, that person tells it's ID number to A and A finds their picture by ID number. And voila !!, A knows who is that person.

Same is with HTTP. It is suffering from SHORT TERM MEMORY LOSS. It uses Sessions to record everything you did while using a website, and then, when you come again, it identifies you with the help of Cookies(Cookie is like a token). Picture is the Session here, and ID is the Cookie here.

How do I fix a NoSuchMethodError?

I ran into a similar problem when I was changing method signatures in my application. Cleaning and rebuilding my project resolved the "NoSuchMethodError".

What is “the inverse side of the association” in a bidirectional JPA OneToMany/ManyToOne association?

For two Entity Classes Customer and Order , hibernate will create two tables.

Possible Cases:

  1. mappedBy is not used in Customer.java and Order.java Class then->

    At customer side a new table will be created[name = CUSTOMER_ORDER] which will keep mapping of CUSTOMER_ID and ORDER_ID. These are primary keys of Customer and Order Tables. At Order side an additional column is required to save the corresponding Customer_ID record mapping.

  2. mappedBy is used in Customer.java [As given in problem statement] Now additional table[CUSTOMER_ORDER] is not created. Only one column in Order Table

  3. mappedby is used in Order.java Now additional table will be created by hibernate.[name = CUSTOMER_ORDER] Order Table will not have additional column [Customer_ID ] for mapping.

Any Side can be made Owner of the relationship. But its better to choose xxxToOne side.

Coding effect - > Only Owning side of entity can change relationship status. In below example BoyFriend class is owner of the relationship. even if Girlfriend wants to break-up , she can't.

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

@Entity
@Table(name = "BoyFriend21")
public class BoyFriend21 {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "Boy_ID")
    @SequenceGenerator(name = "Boy_ID", sequenceName = "Boy_ID_SEQUENCER", initialValue = 10,allocationSize = 1)
    private Integer id;

    @Column(name = "BOY_NAME")
    private String name;

    @OneToOne(cascade = { CascadeType.ALL })
    private GirlFriend21 girlFriend;

    public BoyFriend21(String name) {
        this.name = name;
    }

    public BoyFriend21() {
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public BoyFriend21(String name, GirlFriend21 girlFriend) {
        this.name = name;
        this.girlFriend = girlFriend;
    }

    public GirlFriend21 getGirlFriend() {
        return girlFriend;
    }

    public void setGirlFriend(GirlFriend21 girlFriend) {
        this.girlFriend = girlFriend;
    }
}

import org.hibernate.annotations.*;
import javax.persistence.*;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.ArrayList;
import java.util.List;

@Entity 
@Table(name = "GirlFriend21")
public class GirlFriend21 {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "Girl_ID")
    @SequenceGenerator(name = "Girl_ID", sequenceName = "Girl_ID_SEQUENCER", initialValue = 10,allocationSize = 1)
    private Integer id;

    @Column(name = "GIRL_NAME")
    private String name;

    @OneToOne(cascade = {CascadeType.ALL},mappedBy = "girlFriend")
    private BoyFriend21 boyFriends = new BoyFriend21();

    public GirlFriend21() {
    }

    public GirlFriend21(String name) {
        this.name = name;
    }


    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public GirlFriend21(String name, BoyFriend21 boyFriends) {
        this.name = name;
        this.boyFriends = boyFriends;
    }

    public BoyFriend21 getBoyFriends() {
        return boyFriends;
    }

    public void setBoyFriends(BoyFriend21 boyFriends) {
        this.boyFriends = boyFriends;
    }
}


import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import java.util.Arrays;

public class Main578_DS {

    public static void main(String[] args) {
        final Configuration configuration = new Configuration();
         try {
             configuration.configure("hibernate.cfg.xml");
         } catch (HibernateException e) {
             throw new RuntimeException(e);
         }
        final SessionFactory sessionFactory = configuration.buildSessionFactory();
        final Session session = sessionFactory.openSession();
        session.beginTransaction();

        final BoyFriend21 clinton = new BoyFriend21("Bill Clinton");
        final GirlFriend21 monica = new GirlFriend21("monica lewinsky");

        clinton.setGirlFriend(monica);
        session.save(clinton);

        session.getTransaction().commit();
        session.close();
    }
}

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import java.util.List;

public class Main578_Modify {

    public static void main(String[] args) {
        final Configuration configuration = new Configuration();
        try {
            configuration.configure("hibernate.cfg.xml");
        } catch (HibernateException e) {
            throw new RuntimeException(e);
        }
        final SessionFactory sessionFactory = configuration.buildSessionFactory();
        final Session session1 = sessionFactory.openSession();
        session1.beginTransaction();

        GirlFriend21 monica = (GirlFriend21)session1.load(GirlFriend21.class,10);  // Monica lewinsky record has id  10.
        BoyFriend21 boyfriend = monica.getBoyFriends();
        System.out.println(boyfriend.getName()); // It will print  Clinton Name
        monica.setBoyFriends(null); // It will not impact relationship

        session1.getTransaction().commit();
        session1.close();

        final Session session2 = sessionFactory.openSession();
        session2.beginTransaction();

        BoyFriend21 clinton = (BoyFriend21)session2.load(BoyFriend21.class,10);  // Bill clinton record

        GirlFriend21 girlfriend = clinton.getGirlFriend();
        System.out.println(girlfriend.getName()); // It will print Monica name.
        //But if Clinton[Who owns the relationship as per "mappedby" rule can break this]
        clinton.setGirlFriend(null);
        // Now if Monica tries to check BoyFriend Details, she will find Clinton is no more her boyFriend
        session2.getTransaction().commit();
        session2.close();

        final Session session3 = sessionFactory.openSession();
        session1.beginTransaction();

        monica = (GirlFriend21)session3.load(GirlFriend21.class,10);  // Monica lewinsky record has id  10.
        boyfriend = monica.getBoyFriends();

        System.out.println(boyfriend.getName()); // Does not print Clinton Name

        session3.getTransaction().commit();
        session3.close();
    }
}

How to printf uint64_t? Fails with: "spurious trailing ‘%’ in format"

Since you've included the C++ tag, you could use the {fmt} library and avoid the PRIu64 macro and other printf issues altogether:

#include <fmt/core.h>

int main() {
  uint64_t ui64 = 90;
  fmt::print("test uint64_t : {}\n", ui64);
}

The formatting facility based on this library is proposed for standardization in C++20: P0645.

Disclaimer: I'm the author of {fmt}.

How to move from one fragment to another fragment on click of an ImageView in Android?

purple.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        Fragment fragment = new tasks();
        FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.content_frame, fragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }
});

you write the above code...there we are replacing R.id.content_frame with our fragment. hope this helps you

Angular 6 Material mat-select change method removed

The changed it from change to selectionChange.

<mat-select (change)="doSomething($event)">

is now

<mat-select (selectionChange)="doSomething($event)">

https://material.angular.io/components/select/api

SQL Client for Mac OS X that works with MS SQL Server

Let's work together on a canonical answer.

Native Apps

Java-Based

Electron-Based

(TODO: Add others mentioned below)

What's the difference between fill_parent and wrap_content?

fill_parent (deprecated) = match_parent
The border of the child view expands to match the border of the parent view.

wrap_content
The border of the child view wraps snugly around its own content.

Here are some images to make things more clear. The green and red are TextViews. The white is a LinearLayout showing through.

enter image description here

Every View (a TextView, an ImageView, a Button, etc.) needs to set the width and the height of the view. In the xml layout file, that might look like this:

android:layout_width="wrap_content"
android:layout_height="match_parent"

Besides setting the width and height to match_parent or wrap_content, you could also set them to some absolute value:

android:layout_width="100dp"
android:layout_height="200dp"

Generally that is not as good, though, because it is not as flexible for different sized devices. After you have understood wrap_content and match_parent, the next thing to learn is layout_weight.

See also

XML for above images

Vertical LinearLayout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="width=wrap height=wrap"
        android:background="#c5e1b0"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="width=match height=wrap"
        android:background="#f6c0c0"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="width=match height=match"
        android:background="#c5e1b0"/>

</LinearLayout>

Horizontal LinearLayout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="WrapWrap"
        android:background="#c5e1b0"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="WrapMatch"
        android:background="#f6c0c0"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="MatchMatch"
        android:background="#c5e1b0"/>

</LinearLayout>

Note

The explanation in this answer assumes there is no margin or padding. But even if there is, the basic concept is still the same. The view border/spacing is just adjusted by the value of the margin or padding.

Unlink of file Failed. Should I try again?

After trying various solutions finally git clean -f helped me.

EDIT: I hit the problem again few times - closing all processes dependent on git seems to help (like gitbash, Eclipse IDE, etc.)

Detect the Internet connection is offline?

The problem of some methods like navigator.onLine is that they are not compatible with some browsers and mobile versions, an option that helped me a lot was to use the classic XMLHttpRequest method and also foresee the possible case that the file was stored in cache with response XMLHttpRequest.status is greater than 200 and less than 304.

Here is my code:

 var xhr = new XMLHttpRequest();
 //index.php is in my web
 xhr.open('HEAD', 'index.php', true);
 xhr.send();

 xhr.addEventListener("readystatechange", processRequest, false);

 function processRequest(e) {
     if (xhr.readyState == 4) {
         //If you use a cache storage manager (service worker), it is likely that the
         //index.php file will be available even without internet, so do the following validation
         if (xhr.status >= 200 && xhr.status < 304) {
             console.log('On line!');
         } else {
             console.log('Offline :(');
         }
     }
}

How to read a Parquet file into Pandas DataFrame?

Aside from pandas, Apache pyarrow also provides way to transform parquet to dataframe

The code is simple, just type:

import pyarrow.parquet as pq

df = pq.read_table(source=your_file_path).to_pandas()

For more information, see the document from Apache pyarrow Reading and Writing Single Files

Visual Studio 2010 always thinks project is out of date, but nothing has changed

Another one on Visual Studio 2015 SP3, but I have encountered a similar issue on Visual Studio 2013 a few years back.

My issue was that somehow a wrong cpp file was used for precompiled headers (so I had two cpp files that created the precompiled headers). Now why did Visual Studio change the flags on the wrong cpp to 'create precompiled headers' without my request I have no clue, but it did happen... maybe some plugin or something???

Anyway, the wrong cpp file includes the version.h file which is changed on every build. So Visual Studio rebuilds all headers and because of that the whole project.

Well, now it's back to normal behavior.

How can I find the OWNER of an object in Oracle?

You can query the ALL_OBJECTS view:

select owner
     , object_name
     , object_type
  from ALL_OBJECTS
 where object_name = 'FOO'

To find synonyms:

select *
  from ALL_SYNONYMS
 where synonym_name = 'FOO'

Just to clarify, if a user user's SQL statement references an object name with no schema qualification (e.g. 'FOO'), Oracle FIRST checks the user's schema for an object of that name (including synonyms in that user's schema). If Oracle can't resolve the reference from the user's schema, Oracle then checks for a public synonym.

If you are looking specifically for constraints on a particular table_name:

select c.*
  from all_constraints c 
 where c.table_name = 'FOO'
 union all
select cs.*
  from all_constraints cs
  join all_synonyms s 
    on (s.table_name = cs.table_name
     and s.table_owner = cs.owner 
     and s.synonym_name = 'FOO'
       )

HTH

-- addendum:

If your user is granted access to the DBA_ views (e.g. if your user has been granted SELECT_CATALOG_ROLE), you can substitute 'DBA_' in place of 'ALL_' in the preceding SQL examples. The ALL_x views only show objects which you have been granted privileges. The DBA_x views will show all database objects, whether you have privileges on them or not.

How do I get the raw request body from the Request.Content object using .net 4 api endpoint

In your comment on @Kenneth's answer you're saying that ReadAsStringAsync() is returning empty string.

That's because you (or something - like model binder) already read the content, so position of internal stream in Request.Content is on the end.

What you can do is this:

public static string GetRequestBody()
{
    var bodyStream = new StreamReader(HttpContext.Current.Request.InputStream);
    bodyStream.BaseStream.Seek(0, SeekOrigin.Begin);
    var bodyText = bodyStream.ReadToEnd();
    return bodyText;
}

Generating a unique machine id

Parse the SMBIOS yourself and hash it to an arbitrary length. See the PDF specification for all SMBIOS structures available.

To query the SMBIOS info from Windows you could use EnumSystemFirmwareEntries, EnumSystemFirmwareTables and GetSystemFirmwareTable.

IIRC, the "unique id" from the CPUID instruction is deprecated from P3 and newer.

The provider is not compatible with the version of Oracle client

This issue could by happen while using unmanaged oracle reference if you have more than one oracle client , or sometimes if you reference different version
There is two way to solve it :

  1. First and fast solution is to remove unmanaged reference and use the managed one from NuGet see this before to go with this option Differences between the ODP.NET Managed Driver and Unmanaged Driver

  2. Second solution is to fix project unmanaged target version like the below :

  • First Check oracle project reference version (from project references/(dependencies > assemblies ) > Oracle.DataAccess right click > properties):

    enter image description here

    enter image description here

Then check oracle GAC version

  • got to gac from run (Win+R) "%windir%\Microsoft.NET\assembly"
    enter image description here

  • Check the platform that matches with you project platform

    enter image description here

  • to check you target platform (right click on your project > properties)

    enter image description here

  • From gac folder search to Oracle.DataAccess

    enter image description here

  • Right Click on Oracle.DataAccess > properties > details and check version

    enter image description here

  • if you notice the versions are different this is an the issue and to fix it we need to redirect assembly version (in startup project go to config file and add the below section )

<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Oracle.DataAccess" publicKeyToken="89b483f429c47342" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="4.121.2.0" />
      </dependentAssembly>
</assemblyBinding>

like this enter image description here

oldVersion : should be cover your project version newVersion : GAC version publicKeyToken : From GAC

enter image description here

When to use self over $this?

To really understand what we're talking about when we talk about self versus $this, we need to actually dig into what's going on at a conceptual and a practical level. I don't really feel any of the answers do this appropriately, so here's my attempt.

Let's start off by talking about what a class and an object is.

Classes And Objects, Conceptually

So, what is a class? A lot of people define it as a blueprint or a template for an object. In fact, you can read more About Classes In PHP Here. And to some extent that's what it really is. Let's look at a class:

class Person {
    public $name = 'my name';
    public function sayHello() {
        echo "Hello";
    }
}

As you can tell, there is a property on that class called $name and a method (function) called sayHello().

It's very important to note that the class is a static structure. Which means that the class Person, once defined, is always the same everywhere you look at it.

An object on the other hand is what's called an instance of a Class. What that means is that we take the "blueprint" of the class, and use it to make a dynamic copy. This copy is now specifically tied to the variable it's stored in. Therefore, any changes to an instance is local to that instance.

$bob = new Person;
$adam = new Person;
$bob->name = 'Bob';
echo $adam->name; // "my name"

We create new instances of a class using the new operator.

Therefore, we say that a Class is a global structure, and an Object is a local structure. Don't worry about that funny -> syntax, we're going to go into that in a little bit.

One other thing we should talk about, is that we can check if an instance is an instanceof a particular class: $bob instanceof Person which returns a boolean if the $bob instance was made using the Person class, or a child of Person.

Defining State

So let's dig a bit into what a class actually contains. There are 5 types of "things" that a class contains:

  1. Properties - Think of these as variables that each instance will contain.

    class Foo {
        public $bar = 1;
    }
    
  2. Static Properties - Think of these as variables that are shared at the class level. Meaning that they are never copied by each instance.

    class Foo {
        public static $bar = 1;
    }
    
  3. Methods - These are functions which each instance will contain (and operate on instances).

    class Foo {
        public function bar() {}
    }
    
  4. Static Methods - These are functions which are shared across the entire class. They do not operate on instances, but instead on the static properties only.

    class Foo {
        public static function bar() {}
    }
    
  5. Constants - Class resolved constants. Not going any deeper here, but adding for completeness:

    class Foo {
        const BAR = 1;
    }
    

So basically, we're storing information on the class and object container using "hints" about static which identify whether the information is shared (and hence static) or not (and hence dynamic).

State and Methods

Inside of a method, an object's instance is represented by the $this variable. The current state of that object is there, and mutating (changing) any property will result in a change to that instance (but not others).

If a method is called statically, the $this variable is not defined. This is because there's no instance associated with a static call.

The interesting thing here is how static calls are made. So let's talk about how we access the state:

Accessing State

So now that we have stored that state, we need to access it. This can get a bit tricky (or way more than a bit), so let's split this into two viewpoints: from outside of an instance/class (say from a normal function call, or from the global scope), and inside of an instance/class (from within a method on the object).

From Outside Of An Instance/Class

From the outside of an instance/class, our rules are quite simple and predictable. We have two operators, and each tells us immediately if we're dealing with an instance or a class static:

  • -> - object-operator - This is always used when we're accessing an instance.

    $bob = new Person;
    echo $bob->name;
    

    It's important to note that calling Person->foo does not make sense (since Person is a class, not an instance). Therefore, that is a parse error.

  • :: - scope-resolution-operator - This is always used to access a Class static property or method.

    echo Foo::bar()
    

    Additionally, we can call a static method on an object in the same way:

    echo $foo::bar()
    

    It's extremely important to note that when we do this from outside, the object's instance is hidden from the bar() method. Meaning that it's the exact same as running:

    $class = get_class($foo);
    $class::bar();
    

Therefore, $this is not defined in the static call.

From Inside Of An Instance/Class

Things change a bit here. The same operators are used, but their meaning becomes significantly blurred.

The object-operator -> is still used to make calls to the object's instance state.

class Foo {
    public $a = 1;
    public function bar() {
        return $this->a;
    }
}

Calling the bar() method on $foo (an instance of Foo) using the object-operator: $foo->bar() will result in the instance's version of $a.

So that's how we expect.

The meaning of the :: operator though changes. It depends on the context of the call to the current function:

  • Within a static context

    Within a static context, any calls made using :: will also be static. Let's look at an example:

    class Foo {
        public function bar() {
            return Foo::baz();
        }
        public function baz() {
            return isset($this);
        }
    }
    

    Calling Foo::bar() will call the baz() method statically, and hence $this will not be populated. It's worth noting that in recent versions of PHP (5.3+) this will trigger an E_STRICT error, because we're calling non-static methods statically.

  • Within an instance context

    Within an instance context on the other hand, calls made using :: depend on the receiver of the call (the method we're calling). If the method is defined as static, then it will use a static call. If it's not, it will forward the instance information.

    So, looking at the above code, calling $foo->bar() will return true, since the "static" call happens inside of an instance context.

Make sense? Didn't think so. It's confusing.

Short-Cut Keywords

Because tying everything together using class names is rather dirty, PHP provides 3 basic "shortcut" keywords to make scope resolving easier.

  • self - This refers to the current class name. So self::baz() is the same as Foo::baz() within the Foo class (any method on it).

  • parent - This refers to the parent of the current class.

  • static - This refers to the called class. Thanks to inheritance, child classes can override methods and static properties. So calling them using static instead of a class name allows us to resolve where the call came from, rather than the current level.

Examples

The easiest way to understand this is to start looking at some examples. Let's pick a class:

class Person {
    public static $number = 0;
    public $id = 0;
    public function __construct() {
        self::$number++;
        $this->id = self::$number;
    }
    public $name = "";
    public function getName() {
        return $this->name;
    }
    public function getId() {
        return $this->id;
    }
}

class Child extends Person {
    public $age = 0;
    public function __construct($age) {
        $this->age = $age;
        parent::__construct();
    }
    public function getName() {
        return 'child: ' . parent::getName();
    }
}

Now, we're also looking at inheritance here. Ignore for a moment that this is a bad object model, but let's look at what happens when we play with this:

$bob = new Person;
$bob->name = "Bob";
$adam = new Person;
$adam->name = "Adam";
$billy = new Child;
$billy->name = "Billy";
var_dump($bob->getId()); // 1
var_dump($adam->getId()); // 2
var_dump($billy->getId()); // 3

So the ID counter is shared across both instances and the children (because we're using self to access it. If we used static, we could override it in a child class).

var_dump($bob->getName()); // Bob
var_dump($adam->getName()); // Adam
var_dump($billy->getName()); // child: Billy

Note that we're executing the Person::getName() instance method every time. But we're using the parent::getName() to do it in one of the cases (the child case). This is what makes this approach powerful.

Word Of Caution #1

Note that the calling context is what determines if an instance is used. Therefore:

class Foo {
    public function isFoo() {
        return $this instanceof Foo;
    }
}

Is not always true.

class Bar {
    public function doSomething() {
        return Foo::isFoo();
    }
}
$b = new Bar;
var_dump($b->doSomething()); // bool(false)

Now it is really weird here. We're calling a different class, but the $this that gets passed to the Foo::isFoo() method is the instance of $bar.

This can cause all sorts of bugs and conceptual WTF-ery. So I'd highly suggest avoiding the :: operator from within instance methods on anything except those three virtual "short-cut" keywords (static, self, and parent).

Word Of Caution #2

Note that static methods and properties are shared by everyone. That makes them basically global variables. With all the same problems that come with globals. So I would be really hesitant to store information in static methods/properties unless you're comfortable with it being truly global.

Word Of Caution #3

In general you'll want to use what's known as Late-Static-Binding by using static instead of self. But note that they are not the same thing, so saying "always use static instead of self is really short-sighted. Instead, stop and think about the call you want to make and think if you want child classes to be able to override that static resolved call.

TL/DR

Too bad, go back and read it. It may be too long, but it's that long because this is a complex topic

TL/DR #2

Ok, fine. In short, self is used to reference the current class name within a class, where as $this refers to the current object instance. Note that self is a copy/paste short-cut. You can safely replace it with your class name, and it'll work fine. But $this is a dynamic variable that can't be determined ahead of time (and may not even be your class).

TL/DR #3

If the object-operator is used (->), then you always know you're dealing with an instance. If the scope-resolution-operator is used (::), you need more information about the context (are we in an object-context already? Are we outside of an object? etc).

Python 3: ImportError "No Module named Setuptools"

Make sure you are running latest version of pip

Tried to install ansible and it failed with ModuleNotFoundError: No module named 'setuptools_rust'

python3-setuptools already in place so upgrading pip solved it.

pip3 install -U pip 

How to debug PDO database queries?

To log MySQL in WAMP, you will need to edit the my.ini (e.g. under wamp\bin\mysql\mysql5.6.17\my.ini)

and add to [mysqld]:

general_log = 1
general_log_file="c:\\tmp\\mysql.log"

How to recover a dropped stash in Git?

Once you know the hash of the stash commit you dropped, you can apply it as a stash:

git stash apply $stash_hash

Or, you can create a separate branch for it with

git branch recovered $stash_hash

After that, you can do whatever you want with all the normal tools. When you’re done, just blow the branch away.

Finding the hash

If you have only just popped it and the terminal is still open, you will still have the hash value printed by git stash pop on screen (thanks, Dolda).

Otherwise, you can find it using this for Linux, Unix or Git Bash for Windows:

git fsck --no-reflog | awk '/dangling commit/ {print $3}'

...or using Powershell for Windows:

git fsck --no-reflog | select-string 'dangling commit' | foreach { $_.ToString().Split(" ")[2] }

This will show you all the commits at the tips of your commit graph which are no longer referenced from any branch or tag – every lost commit, including every stash commit you’ve ever created, will be somewhere in that graph.

The easiest way to find the stash commit you want is probably to pass that list to gitk:

gitk --all $( git fsck --no-reflog | awk '/dangling commit/ {print $3}' )

...or see the answer from emragins if using Powershell for Windows.

This will launch a repository browser showing you every single commit in the repository ever, regardless of whether it is reachable or not.

You can replace gitk there with something like git log --graph --oneline --decorate if you prefer a nice graph on the console over a separate GUI app.

To spot stash commits, look for commit messages of this form:

        WIP on somebranch: commithash Some old commit message

Note: The commit message will only be in this form (starting with "WIP on") if you did not supply a message when you did git stash.

round a single column in pandas

No need to use for loop. It can be directly applied to a column of a dataframe

sleepstudy['Reaction'] = sleepstudy['Reaction'].round(1)

Conda uninstall one package and one package only

You can use conda remove --force.

The documentation says:

--force               Forces removal of a package without removing packages
                      that depend on it. Using this option will usually
                      leave your environment in a broken and inconsistent
                      state

How to add MVC5 to Visual Studio 2013?

With respect to other answers, it's not always there. Sometimes on setup process people forget to select the Web Developer Tools.

In order to fix that, one should:

  1. Open Programs and Features find Visual Studios related version there, click on it,
  2. Click to Change. Then the setup window will appear,
  3. Select Web Developer Tools there and continue to setup.

It will download or use the setup media if exist. After the setup windows may restart, and you are ready to have fun with your Web Developer Tools now.

adding directory to sys.path /PYTHONPATH

As to me, i need to caffe to my python path. I can add it's path to the file /home/xy/.bashrc by add

export PYTHONPATH=/home/xy/caffe-master/python:$PYTHONPATH.

to my /home/xy/.bashrc file.

But when I use pycharm, the path is still not in.

So I can add path to PYTHONPATH variable, by run -> edit Configuration.

enter image description here

Maintain model of scope when changing between views in AngularJS

A bit late for an answer but just updated fiddle with some best practice

jsfiddle

var myApp = angular.module('myApp',[]);
myApp.factory('UserService', function() {
    var userService = {};

    userService.name = "HI Atul";

    userService.ChangeName = function (value) {

       userService.name = value;
    };

    return userService;
});

function MyCtrl($scope, UserService) {
    $scope.name = UserService.name;
    $scope.updatedname="";
    $scope.changeName=function(data){
        $scope.updateServiceName(data);
    }
    $scope.updateServiceName = function(name){
        UserService.ChangeName(name);
        $scope.name = UserService.name;
    }
}

How (and why) to use display: table-cell (CSS)

After days trying to find the answer, I finally found

display: table;

There was surprisingly very little information available online about how to actually getting it to work, even here, so on to the "How":

To use this fantastic piece of code, you need to think back to when tables were the only real way to structure HTML, namely the syntax. To get a table with 2 rows and 3 columns, you'd have to do the following:

<table>
    <tr>
        <td></td>
        <td></td>
        <td></td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
    </tr>
</table>

Similarly to get CSS to do it, you'd use the following:

HTML

<div id="table">
    <div class="tr">
        <div class="td"></div>
        <div class="td"></div>
        <div class="td"></div>
    </div>
    <div class="tr">
        <div class="td"></div>
        <div class="td"></div>
        <div class="td"></div>
    </div>
</div>

CSS

#table{ 
    display: table; 
}
.tr{ 
    display: table-row; 
}
.td{ 
    display: table-cell; }

As you can see in the JSFiddle example below, the divs in the 3rd column have no content, yet are respecting the auto height set by the text in the first 2 columns. WIN!

http://jsfiddle.net/blyzz/1djs97yv/1/

It's worth noting that display: table; does not work in IE6 or 7 (thanks, FelipeAls), so depending on your needs with regards to browser compatibility, this may not be the answer that you are seeking.

SQL, How to Concatenate results?

Small update on Marc we will have additional " , " at the end. i used stuff function to remove extra semicolon .

       SELECT STUFF((  SELECT ',' + ModuleValue AS ModuleValue
                           FROM ModuleValue WHERE ModuleID=@ModuleID
                      FOR XML PATH('') 
                     ), 1, 1, '' )

Match multiline text using regular expression

This has nothing to do with the MULTILINE flag; what you're seeing is the difference between the find() and matches() methods. find() succeeds if a match can be found anywhere in the target string, while matches() expects the regex to match the entire string.

Pattern p = Pattern.compile("xyz");

Matcher m = p.matcher("123xyzabc");
System.out.println(m.find());    // true
System.out.println(m.matches()); // false

Matcher m = p.matcher("xyz");
System.out.println(m.matches()); // true

Furthermore, MULTILINE doesn't mean what you think it does. Many people seem to jump to the conclusion that you have to use that flag if your target string contains newlines--that is, if it contains multiple logical lines. I've seen several answers here on SO to that effect, but in fact, all that flag does is change the behavior of the anchors, ^ and $.

Normally ^ matches the very beginning of the target string, and $ matches the very end (or before a newline at the end, but we'll leave that aside for now). But if the string contains newlines, you can choose for ^ and $ to match at the start and end of any logical line, not just the start and end of the whole string, by setting the MULTILINE flag.

So forget about what MULTILINE means and just remember what it does: changes the behavior of the ^ and $ anchors. DOTALL mode was originally called "single-line" (and still is in some flavors, including Perl and .NET), and it has always caused similar confusion. We're fortunate that the Java devs went with the more descriptive name in that case, but there was no reasonable alternative for "multiline" mode.

In Perl, where all this madness started, they've admitted their mistake and gotten rid of both "multiline" and "single-line" modes in Perl 6 regexes. In another twenty years, maybe the rest of the world will have followed suit.

This Activity already has an action bar supplied by the window decor

If you get the error on this line:

setSupportActionBar(...);

You need to check if your activity is referring to a theme that contains a toolbar. Your application's AppTheme might already contain a toolbar, such as

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

and you are trying to add a second one. If you want to use your application's AppTheme, you need to remove the theme from your activity, in the manifest.xml file.

For example:

<activity
    android:name=".ui.activities.SettingsActivity"
    android:theme="@style/AppTheme1" /> --> remove this theme

500.21 Bad module "ManagedPipelineHandler" in its module list

I got this error on my ASP.Net 4.5 app on Windows Server 2012 R2.

Go to start menu -> "Turn windows features on or off". A wizard popped up for me.

Click Next to Server Roles

I had to check these to get this to work, located under Web Server IIS->Web Server-> Application Development (these are based on Jeremy Cook's answer above):

enter image description here

Then click next to Features and make sure the following is checked:

enter image description here

Then click next and Install. At this point, the error went away for me. Good luck!

How do I set the timeout for a JAX-WS webservice client?

In case your appserver is WebLogic (for me it was 10.3.6) then properties responsible for timeouts are:

com.sun.xml.ws.connect.timeout 
com.sun.xml.ws.request.timeout

How to set multiple commands in one yaml file with Kubernetes?

I am not sure if the question is still active but due to the fact that I did not find the solution in the above answers I decided to write it down.

I use the following approach:

readinessProbe:
  exec:
    command:
    - sh
    - -c
    - |
      command1
      command2 && command3

I know my example is related to readinessProbe, livenessProbe, etc. but suspect the same case is for the container commands. This provides flexibility as it mirrors a standard script writing in Bash.

Run MySQLDump without Locking Tables

Due to https://dev.mysql.com/doc/refman/5.7/en/mysqldump.html#option_mysqldump_lock-tables :

Some options, such as --opt (which is enabled by default), automatically enable --lock-tables. If you want to override this, use --skip-lock-tables at the end of the option list.

List of ANSI color escape sequences

For these who don't get proper results other than mentioned languages, if you're using C# to print a text into console(terminal) window you should replace "\033" with "\x1b". In Visual Basic it would be Chrw(27).

How to concatenate multiple column values into a single column in Panda dataframe

df = DataFrame({'foo':['a','b','c'], 'bar':[1, 2, 3], 'new':['apple', 'banana', 'pear']})

df['combined'] = df['foo'].astype(str)+'_'+df['bar'].astype(str)

If you concatenate with string('_') please you convert the column to string which you want and after you can concatenate the dataframe.

What's the reason I can't create generic array types in Java?

Quote:

Arrays of generic types are not allowed because they're not sound. The problem is due to the interaction of Java arrays, which are not statically sound but are dynamically checked, with generics, which are statically sound and not dynamically checked. Here is how you could exploit the loophole:

class Box<T> {
    final T x;
    Box(T x) {
        this.x = x;
    }
}

class Loophole {
    public static void main(String[] args) {
        Box<String>[] bsa = new Box<String>[3];
        Object[] oa = bsa;
        oa[0] = new Box<Integer>(3); // error not caught by array store check
        String s = bsa[0].x; // BOOM!
    }
}

We had proposed to resolve this problem using statically safe arrays (aka Variance) bute that was rejected for Tiger.

-- gafter

(I believe it is Neal Gafter, but am not sure)

See it in context here: http://forums.sun.com/thread.jspa?threadID=457033&forumID=316

How to define two angular apps / modules in one page?

You can bootstrap multiple angular applications, but:

1) You need to manually bootstrap them

2) You should not use "document" as the root, but the node where the angular interface is contained to:

var todoRootNode = jQuery('[ng-controller=TodoController]');
angular.bootstrap(todoRootNode, ['TodoApp']);

This would be safe.

Remove composer

During the installation you got a message Composer successfully installed to: ... this indicates where Composer was installed. But you might also search for the file composer.phar on your system.

Then simply:

  1. Delete the file composer.phar.
  2. Delete the Cache Folder:
    • Linux: /home/<user>/.composer
    • Windows: C:\Users\<username>\AppData\Roaming\Composer

That's it.

How to switch a user per task or set of tasks?

You can specify become_method to override the default method set in ansible.cfg (if any), and which can be set to one of sudo, su, pbrun, pfexec, doas, dzdo, ksu.

- name: I am confused
  command: 'whoami'
  become: true
  become_method: su
  become_user: some_user
  register: myidentity

- name: my secret identity
  debug:
    msg: '{{ myidentity.stdout }}'

Should display

TASK [my-task : my secret identity] ************************************************************
ok: [my_ansible_server] => {
    "msg": "some_user"
}

Javascript decoding html entities

There is a jQuery solution in this thread. Try something like this:

var decoded = $("<div/>").html('your string').text();

This sets the innerHTML of a new <div> element (not appended to the page), causing jQuery to decode it into HTML, which is then pulled back out with .text().

How to use KeyListener

Here is an SSCCE,

package experiment;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class KeyListenerTester extends JFrame implements KeyListener {

    JLabel label;

    public KeyListenerTester(String s) {
        super(s);
        JPanel p = new JPanel();
        label = new JLabel("Key Listener!");
        p.add(label);
        add(p);
        addKeyListener(this);
        setSize(200, 100);
        setVisible(true);

    }

    @Override
    public void keyTyped(KeyEvent e) {

        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            System.out.println("Right key typed");
        }
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            System.out.println("Left key typed");
        }

    }

    @Override
    public void keyPressed(KeyEvent e) {

        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            System.out.println("Right key pressed");
        }
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            System.out.println("Left key pressed");
        }

    }

    @Override
    public void keyReleased(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            System.out.println("Right key Released");
        }
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            System.out.println("Left key Released");
        }
    }

    public static void main(String[] args) {
        new KeyListenerTester("Key Listener Tester");
    }
}

Additionally read upon these links : How to Write a Key Listener and How to Use Key Bindings

How do I force a favicon refresh?

More than likely a web browser issue. You will have to delete your cache from your browser, close your browser and reopen it. That should fix it.

I don't believe your favicons will get refreshed on your favorites until you revisit that page, and assuming that you had previously cleared your browsers cache.

Your web browser will not go out to the internet to check for a new favicon on its own... thank goodness.

Why is the apt-get function not working in the terminal on Mac OS X v10.9 (Mavericks)?

Alternatively You can use the brew or curl command for installing things, wherever apt-get is mentioned with a URL...

For example,

curl -O http://www.magentocommerce.com/downloads/assets/1.8.1.0/magento-1.8.1.0.tar.gz

How to identify which columns are not "NA" per row in a matrix?

Try:

which( !is.na(p), arr.ind=TRUE)

Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:

> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3

[[2]]
[1] 4 7

[[3]]
integer(0)

[[4]]
[1] 5

[[5]]
integer(0)

Or even with smushing together with paste:

lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")

The output from which function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:

> which( !is.na(p), arr.ind=TRUE)
     row col
[1,]   1   2
[2,]   1   3
[3,]   2   4
[4,]   4   5
[5,]   2   7

Without the arr.ind parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".

> which( !is.na(p) )
[1]  6 11 17 24 32

AngularJS ui-router login authentication

I wanted to share another solution working with the ui router 1.0.0.X

As you may know, stateChangeStart and stateChangeSuccess are now deprecated. https://github.com/angular-ui/ui-router/issues/2655

Instead you should use $transitions http://angular-ui.github.io/ui-router/1.0.0-alpha.1/interfaces/transition.ihookregistry.html

This is how I achieved it:

First I have and AuthService with some useful functions

angular.module('myApp')

        .factory('AuthService',
                ['$http', '$cookies', '$rootScope',
                    function ($http, $cookies, $rootScope) {
                        var service = {};

                        // Authenticates throug a rest service
                        service.authenticate = function (username, password, callback) {

                            $http.post('api/login', {username: username, password: password})
                                    .success(function (response) {
                                        callback(response);
                                    });
                        };

                        // Creates a cookie and set the Authorization header
                        service.setCredentials = function (response) {
                            $rootScope.globals = response.token;

                            $http.defaults.headers.common['Authorization'] = 'Bearer ' + response.token;
                            $cookies.put('globals', $rootScope.globals);
                        };

                        // Checks if it's authenticated
                        service.isAuthenticated = function() {
                            return !($cookies.get('globals') === undefined);
                        };

                        // Clear credentials when logout
                        service.clearCredentials = function () {
                            $rootScope.globals = undefined;
                            $cookies.remove('globals');
                            $http.defaults.headers.common.Authorization = 'Bearer ';
                        };

                        return service;
                    }]);

Then I have this configuration:

angular.module('myApp', [
    'ui.router',
    'ngCookies'
])
        .config(['$stateProvider', '$urlRouterProvider',
            function ($stateProvider, $urlRouterProvider) {
                $urlRouterProvider.otherwise('/resumen');
                $stateProvider
                        .state("dashboard", {
                            url: "/dashboard",
                            templateUrl: "partials/dashboard.html",
                            controller: "dashCtrl",
                            data: {
                                authRequired: true
                            }
                        })
                        .state("login", {
                            url: "/login",
                            templateUrl: "partials/login.html",
                            controller: "loginController"
                        })
            }])

        .run(['$rootScope', '$transitions', '$state', '$cookies', '$http', 'AuthService',
            function ($rootScope, $transitions, $state, $cookies, $http, AuthService) {

                // keep user logged in after page refresh
                $rootScope.globals = $cookies.get('globals') || {};
                $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.globals;

                $transitions.onStart({
                    to: function (state) {
                        return state.data != null && state.data.authRequired === true;
                    }
                }, function () {
                    if (!AuthService.isAuthenticated()) {
                        return $state.target("login");
                    }
                });
            }]);

You can see that I use

data: {
   authRequired: true
}

to mark the state only accessible if is authenticated.

then, on the .run I use the transitions to check the autheticated state

$transitions.onStart({
    to: function (state) {
        return state.data != null && state.data.authRequired === true;
    }
}, function () {
    if (!AuthService.isAuthenticated()) {
        return $state.target("login");
    }
});

I build this example using some code found on the $transitions documentation. I'm pretty new with the ui router but it works.

Hope it can helps anyone.

How can I get a file's size in C++?

Have you considered not computing the file size and just growing the array if necessary? Here's an example (with error checking ommitted):

#define CHUNK 1024

/* Read the contents of a file into a buffer.  Return the size of the file 
 * and set buf to point to a buffer allocated with malloc that contains  
 * the file contents.
 */
int read_file(FILE *fp, char **buf) 
{
  int n, np;
  char *b, *b2;

  n = CHUNK;
  np = n;
  b = malloc(sizeof(char)*n);
  while ((r = fread(b, sizeof(char), CHUNK, fp)) > 0) {
    n += r;
    if (np - n < CHUNK) { 
      np *= 2;                      // buffer is too small, the next read could overflow!
      b2 = malloc(np*sizeof(char));
      memcpy(b2, b, n * sizeof(char));
      free(b);
      b = b2;
    }
  }
  *buf = b;
  return n;
}

This has the advantage of working even for streams in which it is impossible to get the file size (like stdin).

Android Studio - Importing external Library/Jar

Easy way and it works for me. Using Android Studio 0.8.2.

  1. Drag jar file under libs.
  2. Press "Sync Project with Gradle Files" button.

enter image description here

What is the meaning of git reset --hard origin/master?

git reset --hard origin/master

says: throw away all my staged and unstaged changes, forget everything on my current local branch and make it exactly the same as origin/master.

You probably wanted to ask this before you ran the command. The destructive nature is hinted at by using the same words as in "hard reset".

Set line spacing

Try this property

line-height:200%;

or

line-height:17px;

use the increase & decrease the volume

Undo a particular commit in Git that's been pushed to remote repos

I don't like the auto-commit that git revert does, so this might be helpful for some.

If you just want the modified files not the auto-commit, you can use --no-commit

% git revert --no-commit <commit hash>

which is the same as the -n

% git revert -n <commit hash>

Reading string from input with space character?

scanf("%s",name);

use & with scanf input

Remove privileges from MySQL database

The USAGE-privilege in mysql simply means that there are no privileges for the user 'phpadmin'@'localhost' defined on global level *.*. Additionally the same user has ALL-privilege on database phpmyadmin phpadmin.*.

So if you want to remove all the privileges and start totally from scratch do the following:

  • Revoke all privileges on database level:

    REVOKE ALL PRIVILEGES ON phpmyadmin.* FROM 'phpmyadmin'@'localhost';

  • Drop the user 'phpmyadmin'@'localhost'

    DROP USER 'phpmyadmin'@'localhost';

Above procedure will entirely remove the user from your instance, this means you can recreate him from scratch.

To give you a bit background on what described above: as soon as you create a user the mysql.user table will be populated. If you look on a record in it, you will see the user and all privileges set to 'N'. If you do a show grants for 'phpmyadmin'@'localhost'; you will see, the allready familliar, output above. Simply translated to "no privileges on global level for the user". Now your grant ALL to this user on database level, this will be stored in the table mysql.db. If you do a SELECT * FROM mysql.db WHERE db = 'nameofdb'; you will see a 'Y' on every priv.

Above described shows the scenario you have on your db at the present. So having a user that only has USAGE privilege means, that this user can connect, but besides of SHOW GLOBAL VARIABLES; SHOW GLOBAL STATUS; he has no other privileges.

S3 Static Website Hosting Route All Paths to Index.html

If you landed here looking for solution that works with React Router and AWS Amplify Console - you already know that you can't use CloudFront redirection rules directly since Amplify Console does not expose CloudFront Distribution for the app.

Solution, however, is very simple - you just need to add a redirect/rewrite rule in Amplify Console like this:

Amplify Console Rewrite rule for React Router

See the following links for more info (and copy-friendly rule from the screenshot):

How to convert a negative number to positive?

If you are working with numpy you can use

import numpy as np
np.abs(-1.23)
>> 1.23

It will provide absolute values.

How to trigger event when a variable's value is changed?

A simple method involves using the get and set functions on the variable


    using System;
    public string Name{
    get{
     return name;
    }
    
    set{
     name= value;
     OnVarChange?.Invoke();
    }
    }
    private string name;
    
    public event System.Action OnVarChange;

How to save a Python interactive session?

there is another option --- pyslice. in the "wxpython 2.8 docs demos and tools", there is a open source program named "pyslices".

you can use it like a editor, and it also support using like a console ---- executing each line like a interactive interpreter with immediate echo.

of course, all the blocks of codes and results of each block will be recorded into a txt file automatically.

the results are logged just behind the corresponding block of code. very convenient.

the overview of pyslices

Anyway to prevent the Blue highlighting of elements in Chrome when clicking quickly?

But, sometimes, even with user-select and touch-callout turned off, cursor: pointer; may cause this effect, so, just set cursor: default; and it'll work.

How to resolve git's "not something we can merge" error

It may happen because that branch is not on your local. before merging use

git fetch origin

YouTube embedded video: set different thumbnail

This tool gave me following results which helps me achieve the task as following code.

<div onclick="play();" id="vidwrap" style="height:315px;width:560px;background: black url('http://example.com/image.jpg') no-repeat center;overflow:hidden;cursor:pointer;"></div>
<script type="text/javascript">
    function play(){
        document.getElementById('vidwrap').innerHTML = '<iframe width="560" height="315" src="http://www.youtube.com/embed/xxxxxxxxx?autoplay=1" frameborder="0"></iframe>';
    }
</script>

How to comment in Vim's config files: ".vimrc"?

"This is a comment in vimrc. It does not have a closing quote 

Source: http://vim.wikia.com/wiki/Backing_up_and_commenting_vimrc

close fxml window by code, javafx

I found a nice solution which does not need an event to be triggered:

@FXML
private Button cancelButton;

close(new Event(cancelButton, stage, null));

@FXML
private void close(Event event) {
    ((Node)(event.getSource())).getScene().getWindow().hide();                      
}

JQuery or JavaScript: How determine if shift key being pressed while clicking anchor tag hyperlink?

If anyone's looking to detect a given key and needs to know the status of the "modifiers" (as they are called in Java), i.e. Shift, Alt and Control keys, you can do something like this, which responds to keydown on key F9, but only if none of the Shift, Alt or Control keys is currently pressed.

jqMyDiv.on( 'keydown', function( e ){
    if( ! e.shiftKey && ! e.altKey && ! e.ctrlKey ){
        console.log( e );
        if( e.originalEvent.code === 'F9' ){
          // do something 
        }
    }
});

vue.js 'document.getElementById' shorthand

Theres no shorthand way in vue 2.

Jeff's method seems already deprecated in vue 2.

Heres another way u can achieve your goal.

_x000D_
_x000D_
 var app = new Vue({_x000D_
    el:'#app',_x000D_
    methods: {    _x000D_
        showMyDiv() {_x000D_
           console.log(this.$refs.myDiv);_x000D_
        }_x000D_
    }_x000D_
    _x000D_
   });
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>_x000D_
<div id='app'>_x000D_
   <div id="myDiv" ref="myDiv"></div>_x000D_
   <button v-on:click="showMyDiv" >Show My Div</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

AngularJS : Custom filters and ng-repeat

If you want to run some custom filter logic you can create a function which takes the array element as an argument and returns true or false based on whether it should be in the search results. Then pass it to the filter instruction just like you do with the search object, for example:

JS:

$scope.filterFn = function(car)
{
    // Do some tests

    if(car.carDetails.doors > 2)
    {
        return true; // this will be listed in the results
    }

    return false; // otherwise it won't be within the results
};

HTML:

...
<article data-ng-repeat="result in results | filter:search | filter:filterFn" class="result">
...

As you can see you can chain many filters together, so adding your custom filter function doesn't force you to remove the previous filter using the search object (they will work together seamlessly).

How to completely hide the navigation bar in iPhone / HTML5

The problem with all of the answers given so far is that on the something borrowed site, the Mac bar remains totally hidden when scrolling up, and the provided answers don't accomplish that.

If you just use scrollTo and then the user later scrolls up, the nav bar is revealed again, so it seems you have to put the whole site inside of a div and force scrolling to happen inside of that div rather than on the body which keeps the nav bar hidden during scrolling in any direction.

You can, however, still reveal the nav bar by touching near the top of the screen on apple devices.

Cast from VARCHAR to INT - MySQL

As described in Cast Functions and Operators:

The type for the result can be one of the following values:

  • BINARY[(N)]
  • CHAR[(N)]
  • DATE
  • DATETIME
  • DECIMAL[(M[,D])]
  • SIGNED [INTEGER]
  • TIME
  • UNSIGNED [INTEGER]

Therefore, you should use:

SELECT CAST(PROD_CODE AS UNSIGNED) FROM PRODUCT

How to check visibility of software keyboard in Android?

The InputMethodManager has information about the soft keyboard. You get it from an activity via:

((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))

You might play around with that to see what it can tell you. You can use it to show or hide the soft input...

How does database indexing work?

Why is it needed?

When data is stored on disk-based storage devices, it is stored as blocks of data. These blocks are accessed in their entirety, making them the atomic disk access operation. Disk blocks are structured in much the same way as linked lists; both contain a section for data, a pointer to the location of the next node (or block), and both need not be stored contiguously.

Due to the fact that a number of records can only be sorted on one field, we can state that searching on a field that isn’t sorted requires a Linear Search which requires N/2 block accesses (on average), where N is the number of blocks that the table spans. If that field is a non-key field (i.e. doesn’t contain unique entries) then the entire tablespace must be searched at N block accesses.

Whereas with a sorted field, a Binary Search may be used, which has log2 N block accesses. Also since the data is sorted given a non-key field, the rest of the table doesn’t need to be searched for duplicate values, once a higher value is found. Thus the performance increase is substantial.

What is indexing?

Indexing is a way of sorting a number of records on multiple fields. Creating an index on a field in a table creates another data structure which holds the field value, and a pointer to the record it relates to. This index structure is then sorted, allowing Binary Searches to be performed on it.

The downside to indexing is that these indices require additional space on the disk since the indices are stored together in a table using the MyISAM engine, this file can quickly reach the size limits of the underlying file system if many fields within the same table are indexed.

How does it work?

Firstly, let’s outline a sample database table schema;

Field name       Data type      Size on disk
id (Primary key) Unsigned INT   4 bytes
firstName        Char(50)       50 bytes
lastName         Char(50)       50 bytes
emailAddress     Char(100)      100 bytes

Note: char was used in place of varchar to allow for an accurate size on disk value. This sample database contains five million rows and is unindexed. The performance of several queries will now be analyzed. These are a query using the id (a sorted key field) and one using the firstName (a non-key unsorted field).

Example 1 - sorted vs unsorted fields

Given our sample database of r = 5,000,000 records of a fixed size giving a record length of R = 204 bytes and they are stored in a table using the MyISAM engine which is using the default block size B = 1,024 bytes. The blocking factor of the table would be bfr = (B/R) = 1024/204 = 5 records per disk block. The total number of blocks required to hold the table is N = (r/bfr) = 5000000/5 = 1,000,000 blocks.

A linear search on the id field would require an average of N/2 = 500,000 block accesses to find a value, given that the id field is a key field. But since the id field is also sorted, a binary search can be conducted requiring an average of log2 1000000 = 19.93 = 20 block accesses. Instantly we can see this is a drastic improvement.

Now the firstName field is neither sorted nor a key field, so a binary search is impossible, nor are the values unique, and thus the table will require searching to the end for an exact N = 1,000,000 block accesses. It is this situation that indexing aims to correct.

Given that an index record contains only the indexed field and a pointer to the original record, it stands to reason that it will be smaller than the multi-field record that it points to. So the index itself requires fewer disk blocks than the original table, which therefore requires fewer block accesses to iterate through. The schema for an index on the firstName field is outlined below;

Field name       Data type      Size on disk
firstName        Char(50)       50 bytes
(record pointer) Special        4 bytes

Note: Pointers in MySQL are 2, 3, 4 or 5 bytes in length depending on the size of the table.

Example 2 - indexing

Given our sample database of r = 5,000,000 records with an index record length of R = 54 bytes and using the default block size B = 1,024 bytes. The blocking factor of the index would be bfr = (B/R) = 1024/54 = 18 records per disk block. The total number of blocks required to hold the index is N = (r/bfr) = 5000000/18 = 277,778 blocks.

Now a search using the firstName field can utilize the index to increase performance. This allows for a binary search of the index with an average of log2 277778 = 18.08 = 19 block accesses. To find the address of the actual record, which requires a further block access to read, bringing the total to 19 + 1 = 20 block accesses, a far cry from the 1,000,000 block accesses required to find a firstName match in the non-indexed table.

When should it be used?

Given that creating an index requires additional disk space (277,778 blocks extra from the above example, a ~28% increase), and that too many indices can cause issues arising from the file systems size limits, careful thought must be used to select the correct fields to index.

Since indices are only used to speed up the searching for a matching field within the records, it stands to reason that indexing fields used only for output would be simply a waste of disk space and processing time when doing an insert or delete operation, and thus should be avoided. Also given the nature of a binary search, the cardinality or uniqueness of the data is important. Indexing on a field with a cardinality of 2 would split the data in half, whereas a cardinality of 1,000 would return approximately 1,000 records. With such a low cardinality the effectiveness is reduced to a linear sort, and the query optimizer will avoid using the index if the cardinality is less than 30% of the record number, effectively making the index a waste of space.

Reverting to a previous revision using TortoiseSVN

In the TortoiseSVN context menu, select 'Update to Revision', enter the desired revision number, and voilà :)

Remove blue border from css custom-styled button in Chrome

Simply write outline:none;. No need to use pseudo element focus

Return the characters after Nth character in a string

Alternately, you could do a Text to Columns with space as the delimiter.

Importing data from a JSON file into R

If the URL is https, like used for Amazon S3, then use getURL

json <- fromJSON(getURL('https://s3.amazonaws.com/bucket/my.json'))

How to copy directory recursively in python and overwrite all?

In Python 3.8 the dirs_exist_ok keyword argument was added to shutil.copytree():

dirs_exist_ok dictates whether to raise an exception in case dst or any missing parent directory already exists.

So, the following will work in recent versions of Python, even if the destination directory already exists:

shutil.copytree(src, dest, dirs_exist_ok=True)  # 3.8+ only!

One major benefit is that it's more flexible than distutils.dir_util.copy_tree() as it takes additional arguments on files to ignore, etc. There is also a draft PEP (PEP 632, associated discussion), which suggests that distutils may be deprecated and then removed in future versions of Python 3.

connecting to MySQL from the command line

This worked for me ::-

mysql --host=hostNameorIp --user=username --password=password  

or

mysql --host=hostNameorIp --user=username --password=password database_name

java.sql.SQLException: Fail to convert to internal representation

I had the same problem and this is my solution. I had the following code:

se.GiftDescription = rs.getString(1);
se.GiftAmount = rs.getInt(2);

And I changed it to:

se.GiftDescription = rs.getString("DESCRIPTION");
se.GiftAmount = rs.getInt("AMOUNT");

And the problem was, after I restarted my PC, the column positions changed. That's why I got this error.

LINQ .Any VS .Exists - What's the difference?

TLDR; Performance-wise Any seems to be slower (if I have set this up properly to evaluate both values at almost same time)

        var list1 = Generate(1000000);
        var forceListEval = list1.SingleOrDefault(o => o == "0123456789012");
        if (forceListEval != "sdsdf")
        {
            var s = string.Empty;
            var start2 = DateTime.Now;
            if (!list1.Exists(o => o == "0123456789012"))
            {
                var end2 = DateTime.Now;
                s += " Exists: " + end2.Subtract(start2);
            }

            var start1 = DateTime.Now;
            if (!list1.Any(o => o == "0123456789012"))
            {
                var end1 = DateTime.Now;
                s +=" Any: " +end1.Subtract(start1);
            }

            if (!s.Contains("sdfsd"))
            {

            }

testing list generator:

private List<string> Generate(int count)
    {
        var list = new List<string>();
        for (int i = 0; i < count; i++)
        {
            list.Add( new string(
            Enumerable.Repeat("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 13)
                .Select(s =>
                {
                    var cryptoResult = new byte[4];
                    new RNGCryptoServiceProvider().GetBytes(cryptoResult);
                    return s[new Random(BitConverter.ToInt32(cryptoResult, 0)).Next(s.Length)];
                })
                .ToArray())); 
        }

        return list;
    }

With 10M records

" Any: 00:00:00.3770377 Exists: 00:00:00.2490249"

With 5M records

" Any: 00:00:00.0940094 Exists: 00:00:00.1420142"

With 1M records

" Any: 00:00:00.0180018 Exists: 00:00:00.0090009"

With 500k, (I also flipped around order in which they get evaluated to see if there is no additional operation associated with whichever runs first.)

" Exists: 00:00:00.0050005 Any: 00:00:00.0100010"

With 100k records

" Exists: 00:00:00.0010001 Any: 00:00:00.0020002"

It would seem Any to be slower by magnitude of 2.

Edit: For 5 and 10M records I changed the way it generates the list and Exists suddenly became slower than Any which implies there's something wrong in the way I am testing.

New testing mechanism:

private static IEnumerable<string> Generate(int count)
    {
        var cripto = new RNGCryptoServiceProvider();
        Func<string> getString = () => new string(
            Enumerable.Repeat("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 13)
                .Select(s =>
                {
                    var cryptoResult = new byte[4];
                    cripto.GetBytes(cryptoResult);
                    return s[new Random(BitConverter.ToInt32(cryptoResult, 0)).Next(s.Length)];
                })
                .ToArray());

        var list = new ConcurrentBag<string>();
        var x = Parallel.For(0, count, o => list.Add(getString()));
        return list;
    }

    private static void Test()
    {
        var list = Generate(10000000);
        var list1 = list.ToList();
        var forceListEval = list1.SingleOrDefault(o => o == "0123456789012");
        if (forceListEval != "sdsdf")
        {
            var s = string.Empty;

            var start1 = DateTime.Now;
            if (!list1.Any(o => o == "0123456789012"))
            {
                var end1 = DateTime.Now;
                s += " Any: " + end1.Subtract(start1);
            }

            var start2 = DateTime.Now;
            if (!list1.Exists(o => o == "0123456789012"))
            {
                var end2 = DateTime.Now;
                s += " Exists: " + end2.Subtract(start2);
            }

            if (!s.Contains("sdfsd"))
            {

            }
        }

Edit2: Ok so to eliminate any influence from generating test data I wrote it all to file and now read it from there.

 private static void Test()
    {
        var list1 = File.ReadAllLines("test.txt").Take(500000).ToList();
        var forceListEval = list1.SingleOrDefault(o => o == "0123456789012");
        if (forceListEval != "sdsdf")
        {
            var s = string.Empty;
            var start1 = DateTime.Now;
            if (!list1.Any(o => o == "0123456789012"))
            {
                var end1 = DateTime.Now;
                s += " Any: " + end1.Subtract(start1);
            }

            var start2 = DateTime.Now;
            if (!list1.Exists(o => o == "0123456789012"))
            {
                var end2 = DateTime.Now;
                s += " Exists: " + end2.Subtract(start2);
            }

            if (!s.Contains("sdfsd"))
            {
            }
        }
    }

10M

" Any: 00:00:00.1640164 Exists: 00:00:00.0750075"

5M

" Any: 00:00:00.0810081 Exists: 00:00:00.0360036"

1M

" Any: 00:00:00.0190019 Exists: 00:00:00.0070007"

500k

" Any: 00:00:00.0120012 Exists: 00:00:00.0040004"

enter image description here

Visualizing branch topology in Git

Take a look at Gitkraken - a cross-platform GUI that shows topology in a lucid way.

Topology

Here's a quick video tutorial on some advanced features.

Note: registration is required.

Python timedelta in years

If you're trying to check if someone is 18 years of age, using timedelta will not work correctly on some edge cases because of leap years. For example, someone born on January 1, 2000, will turn 18 exactly 6575 days later on January 1, 2018 (5 leap years included), but someone born on January 1, 2001, will turn 18 exactly 6574 days later on January 1, 2019 (4 leap years included). Thus, you if someone is exactly 6574 days old, you can't determine if they are 17 or 18 without knowing a little more information about their birthdate.

The correct way to do this is to calculate the age directly from the dates, by subtracting the two years, and then subtracting one if the current month/day precedes the birth month/day.

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

the problem is in url pattern of servlet-mapping.

 <url-pattern>/DispatcherServlet</url-pattern>

let's say our controller is

@Controller
public class HomeController {
    @RequestMapping("/home")
    public String home(){
        return "home";
    }
}

when we hit some URL on our browser. the dispatcher servlet will try to map this url.

the url pattern of our serlvet currently is /Dispatcher which means resources are served from {contextpath}/Dispatcher

but when we request http://localhost:8080/home we are actually asking resources from / which is not available. so either we need to say dispatcher servlet to serve from / by doing

<url-pattern>/</url-pattern>

our make it serve from /Dispatcher by doing /Dispatcher/*

E.g

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" 
version="3.1">
  <display-name>springsecuritydemo</display-name>

  <servlet>
    <description></description>
    <display-name>offers</display-name>
    <servlet-name>offers</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>offers</servlet-name>
    <url-pattern>/Dispatcher/*</url-pattern>
  </servlet-mapping>

</web-app>

and request it with http://localhost:8080/Dispatcher/home or put just / to request like

http://localhost:8080/home

How can I pass an Integer class correctly by reference?

There are 2 ways to pass by reference

  1. Use org.apache.commons.lang.mutable.MutableInt from Apache Commons library.
  2. Create custom class as shown below

Here's a sample code to do it:

public class Test {
    public static void main(String args[]) {
        Integer a = new Integer(1);
        Integer b = a;
        Test.modify(a);
        System.out.println(a);
        System.out.println(b);

        IntegerObj ao = new IntegerObj(1);
        IntegerObj bo = ao;
        Test.modify(ao);
        System.out.println(ao.value);
        System.out.println(bo.value);
    }


    static void modify(Integer x) {
        x=7;
    }
    static void modify(IntegerObj x) {
        x.value=7;
    }   
}

class IntegerObj {
    int value;
    IntegerObj(int val) {
        this.value = val;
    }
}

Output:

1
1
7
7

How to change active class while click to another link in bootstrap use jquery?

<script type="text/javascript">
$(document).ready(function(){
    $('.nav li').click(function(){
        $(this).addClass('active');
        $(this).siblings().removeClass('active');

    });

});

Lambda expression to convert array/List of String to array/List of Integers

You could create helper methods that would convert a list (array) of type T to a list (array) of type U using the map operation on stream.

//for lists
public static <T, U> List<U> convertList(List<T> from, Function<T, U> func) {
    return from.stream().map(func).collect(Collectors.toList());
}

//for arrays
public static <T, U> U[] convertArray(T[] from, 
                                      Function<T, U> func, 
                                      IntFunction<U[]> generator) {
    return Arrays.stream(from).map(func).toArray(generator);
}

And use it like this:

//for lists
List<String> stringList = Arrays.asList("1","2","3");
List<Integer> integerList = convertList(stringList, s -> Integer.parseInt(s));

//for arrays
String[] stringArr = {"1","2","3"};
Double[] doubleArr = convertArray(stringArr, Double::parseDouble, Double[]::new);


Note that s -> Integer.parseInt(s) could be replaced with Integer::parseInt (see Method references)

How to tell if JRE or JDK is installed

A generic, pure Java solution..

For Windows and MacOS, the following can be inferred (most of the time)...

public static boolean isJDK() {
    String path = System.getProperty("sun.boot.library.path");
    if(path != null && path.contains("jdk")) {
        return true;
    }
    return false;
}

However... on Linux this isn't as reliable... For example...

  • Many JREs on Linux contain openjdk the path
  • There's no guarantee that the JRE doesn't also contain a JDK.

So a more fail-safe approach is to check for the existence of the javac executable.

public static boolean isJDK() {
    String path = System.getProperty("sun.boot.library.path");
    if(path != null) {
        String javacPath = "";
        if(path.endsWith(File.separator + "bin")) {
            javacPath = path;
        } else {
            int libIndex = path.lastIndexOf(File.separator + "lib");
            if(libIndex > 0) {
                javacPath = path.substring(0, libIndex) + File.separator + "bin";
            }
        }
        if(!javacPath.isEmpty()) {
            return new File(javacPath, "javac").exists() || new File(javacPath, "javac.exe").exists();
        }
    }
    return false;
}

Warning: This will still fail for JRE + JDK combos which report the JRE's sun.boot.library.path identically between the JRE and the JDK. For example, Fedora's JDK will fail (or pass depending on how you look at it) when the above code is run. See unit tests below for more info...

Unit tests:

# Unix
java -XshowSettings:properties -version 2>&1|grep "sun.boot.library.path"
# Windows
java -XshowSettings:properties -version 2>&1|find "sun.boot.library.path"
    # PASS: MacOS AdoptOpenJDK JDK11
    /Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home/lib

    # PASS: Windows Oracle JDK12
    c:\Program Files\Java\jdk-12.0.2\bin

    # PASS: Windows Oracle JRE8
    C:\Program Files\Java\jre1.8.0_181\bin

    # PASS: Windows Oracle JDK8
    C:\Program Files\Java\jdk1.8.0_181\bin

    # PASS: Ubuntu AdoptOpenJDK JDK11
    /usr/lib/jvm/adoptopenjdk-11-hotspot-amd64/lib

    # PASS: Ubuntu Oracle JDK11
    /usr/lib/jvm/java-11-oracle/lib

    # PASS: Fedora OpenJDK JDK8
    /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.141-1.b16.fc24.x86_64/jre/lib/amd64

    #### FAIL: Fedora OpenJDK JDK8
    /usr/java/jdk1.8.0_231-amd64/jre/lib/amd64

Python 3 Online Interpreter / Shell

Ideone supports Python 2.6 and Python 3

Which header file do you include to use bool type in c in linux?

bool is just a macro that expands to _Bool. You can use _Bool with no #include very much like you can use int or double; it is a C99 keyword.

The macro is defined in <stdbool.h> along with 3 other macros.

The macros defined are

  • bool: macro expands to _Bool
  • false: macro expands to 0
  • true: macro expands to 1
  • __bool_true_false_are_defined: macro expands to 1

Disable dragging an image from an HTML page

Since my images were created using ajax, and therefore not available on windows.load.

$("#page").delegate('img', 'dragstart', function (event) { event.preventDefault(); });

This way I can control which section blocks the behavior, it only uses one event binding and it works for future ajax created images without having to do anything.

With jQuery new on binding:

$('#page').on('dragstart', 'img', function(event) { event.preventDefault(); }); (thanks @ialphan)

How to define custom exception class in Java, the easiest way?

Exception class has two constructors

  • public Exception() -- This constructs an Exception without any additional information.Nature of the exception is typically inferred from the class name.
  • public Exception(String s) -- Constructs an exception with specified error message.A detail message is a String that describes the error condition for this particular exception.

Swift - how to make custom header for UITableView?

add label to subview of custom view, no need of self.view.addSubview(view), because viewForHeaderInSection return the UIView

view.addSubview(label)

Converting ArrayList to Array in java

public T[] toArray(T[] a) - In this method we create a array with size of arraylist and pass it as argument and it will return array of element of arraylist

    String[] arr = new String[list.size()]; 

    arr = list.toArray(arr);

Checking if a number is a prime number in Python

There are many efficient ways to test primality (and this isn't one of them), but the loop you wrote can be concisely rewritten in Python:

def is_prime(a):
    return all(a % i for i in xrange(2, a))

That is, a is prime if all numbers between 2 and a (not inclusive) give non-zero remainder when divided into a.

How to create javascript delay function

You can create a delay using the following example

setInterval(function(){alert("Hello")},3000);

Replace 3000 with # of milliseconds

You can place the content of what you want executed inside the function.

Double % formatting question for printf in Java

Yes, %d is for decimal (integer), double expect %f. But simply using %f will default to up to precision 6. To print all of the precision digits for a double, you can pass it via string as:

System.out.printf("%s \r\n",String.valueOf(d));

or

System.out.printf("%s \r\n",Double.toString(d));

This is what println do by default:

System.out.println(d) 

(and terminates the line)

Adding click event for a button created dynamically using jQuery

Use

$(document).on("click", "#btn_a", function(){
  alert ('button clicked');
});

to add the listener for the dynamically created button.

alert($("#btn_a").val());

will give you the value of the button

How to destroy a DOM element with jQuery?

Is $target.remove(); what you're looking for?

https://api.jquery.com/remove/

How to iterate through an ArrayList of Objects of ArrayList of Objects?

Edit:

Well, he edited his post.

If an Object inherits Iterable, you are given the ability to use the for-each loop as such:

for(Object object : objectListVar) {
     //code here
}

So in your case, if you wanted to update your Guns and their Bullets:

for(Gun g : guns) {
     //invoke any methods of each gun
     ArrayList<Bullet> bullets = g.getBullets()
     for(Bullet b : bullets) {
          System.out.println("X: " + b.getX() + ", Y: " + b.getY());
          //update, check for collisions, etc
     }
}

First get your third Gun object:

Gun g = gunList.get(2);

Then iterate over the third gun's bullets:

ArrayList<Bullet> bullets = g.getBullets();

for(Bullet b : bullets) {
     //necessary code here
}

Error importing SQL dump into MySQL: Unknown database / Can't create database

This is a known bug at MySQL.

bug 42996
bug 40477

As you can see this has been a known issue since 2008 and they have not fixed it yet!!!

WORK AROUND
You first need to create the database to import. It doesn't need any tables. Then you can import your database.

  1. first start your MySQL command line (apply username and password if you need to)
    C:\>mysql -u user -p

  2. Create your database and exit

    mysql> DROP DATABASE database;  
    mysql> CREATE DATABASE database;  
    mysql> Exit  
    
  3. Import your selected database from the dump file
    C:\>mysql -u user -p -h localhost -D database -o < dumpfile.sql

You can replace localhost with an IP or domain for any MySQL server you want to import to. The reason for the DROP command in the mysql prompt is to be sure we start with an empty and clean database.

What does '?' do in C++?

It's the conditional operator.

a ? b : c

It's a shortcut for IF/THEN/ELSE.

means: if a is true, return b, else return c. In this case, if f==r, return 1, else return 0.

ggplot geom_text font size control

Here are a few options for changing text / label sizes

library(ggplot2)

# Example data using mtcars

a <- aggregate(mpg ~ vs + am , mtcars, function(i) round(mean(i)))

p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
            geom_bar(stat="identity",position="dodge") + 
            geom_text(data = a, aes(label = mpg), 
                            position = position_dodge(width=0.9),  size=20)

The size in the geom_text changes the size of the geom_text labels.

p <- p + theme(axis.text = element_text(size = 15)) # changes axis labels

p <- p + theme(axis.title = element_text(size = 25)) # change axis titles

p <- p + theme(text = element_text(size = 10)) # this will change all text size 
                                                             # (except geom_text)


For this And why size of 10 in geom_text() is different from that in theme(text=element_text()) ?

Yes, they are different. I did a quick manual check and they appear to be in the ratio of ~ (14/5) for geom_text sizes to theme sizes.

So a horrible fix for uniform sizes is to scale by this ratio

geom.text.size = 7
theme.size = (14/5) * geom.text.size

ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
  geom_bar(stat="identity",position="dodge") + 
  geom_text(data = a, aes(label = mpg), 
            position = position_dodge(width=0.9),  size=geom.text.size) + 
  theme(axis.text = element_text(size = theme.size, colour="black")) 

This of course doesn't explain why? and is a pita (and i assume there is a more sensible way to do this)

What is the fastest way to send 100,000 HTTP requests in Python?

A solution:

from twisted.internet import reactor, threads
from urlparse import urlparse
import httplib
import itertools


concurrent = 200
finished=itertools.count(1)
reactor.suggestThreadPoolSize(concurrent)

def getStatus(ourl):
    url = urlparse(ourl)
    conn = httplib.HTTPConnection(url.netloc)   
    conn.request("HEAD", url.path)
    res = conn.getresponse()
    return res.status

def processResponse(response,url):
    print response, url
    processedOne()

def processError(error,url):
    print "error", url#, error
    processedOne()

def processedOne():
    if finished.next()==added:
        reactor.stop()

def addTask(url):
    req = threads.deferToThread(getStatus, url)
    req.addCallback(processResponse, url)
    req.addErrback(processError, url)   

added=0
for url in open('urllist.txt'):
    added+=1
    addTask(url.strip())

try:
    reactor.run()
except KeyboardInterrupt:
    reactor.stop()

Testtime:

[kalmi@ubi1:~] wc -l urllist.txt
10000 urllist.txt
[kalmi@ubi1:~] time python f.py > /dev/null 

real    1m10.682s
user    0m16.020s
sys 0m10.330s
[kalmi@ubi1:~] head -n 6 urllist.txt
http://www.google.com
http://www.bix.hu
http://www.godaddy.com
http://www.google.com
http://www.bix.hu
http://www.godaddy.com
[kalmi@ubi1:~] python f.py | head -n 6
200 http://www.bix.hu
200 http://www.bix.hu
200 http://www.bix.hu
200 http://www.bix.hu
200 http://www.bix.hu
200 http://www.bix.hu

Pingtime:

bix.hu is ~10 ms away from me
godaddy.com: ~170 ms
google.com: ~30 ms

Experimental decorators warning in TypeScript compilation

If you using Deno JavaScript and TypeScript runtime and you enable experimentalDecorators:true in tsconfig.json or the VSCode ide settings. It will not work. According to Deno requirement, you need to provide tsconfig as a flag when running a Deno file. See Custom TypeScript Compiler Options

In my particular case I was running a Deno test and used.

$ deno test -c tsconfig.json

If it is a file, you have something like

 $ deno run -c tsconfig.json mod.ts

my tsconfig.json

{
  "compilerOptions": {
    "allowJs": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "module": "esnext"
  }
}

ldconfig error: is not a symbolic link

I have also faced the same issue, The solution for it is : the file for which you are getting the error is probably a duplicated file of the actual file with another version. So just the removal of a particular file on which errors are thrown can resolve the issue.

Save Dataframe to csv directly to s3 Python

You can also use the AWS Data Wrangler:

import awswrangler as wr
    
wr.s3.to_csv(
    df=df,
    path="s3://...",
)

Note that it will handle multipart upload for you to make the upload faster.

Convert INT to VARCHAR SQL

Use the convert function.

SELECT CONVERT(varchar(10), field_name) FROM table_name

How do I remove blank pages coming between two chapters in Appendix?

Your problem is that all chapters, whether they're in the appendix or not, default to starting on an odd-numbered page when you're in two-sided layout mode. A few possible solutions:

The simplest solution is to use the openany option to your document class, which makes chapters start on the next page, irrespective of whether it's an odd or even numbered page. This is supported in the standard book documentclass, eg \documentclass[openany]{book}. (memoir also supports using this as a declaration \openany which can be used in the middle of a document to change the behavior for subsequent pages.)

Another option is to try the \let\cleardoublepage\clearpage command before your appendices to avoid the behavior.

Or, if you don't care using a two-sided layout, using the option oneside to your documentclass (eg \documentclass[oneside]{book}) will switch to using a one-sided layout.

Non-numeric Argument to Binary Operator Error in R

Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.

- is the 'binary operator' your error is referencing, and either CurrentDay or MA (or both) are non-numeric.

A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). + is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).

R only knows how to apply + (and other binary operators, such as -) to numeric arguments:

> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator

When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.

EDIT:

Your error lies in the use of [ instead of [[. Because Day is a list, subsetting with [ will return a list, not a numeric vector. [[, however, returns an object of the class of the item contained in the list:

> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator

> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3

Transaction, as you've defined it, returns a list of two vectors. Above, Day is a list contain one vector. Day2, however, is simply a vector.

jquery .on() method with load event

Refer to http://api.jquery.com/on/

It says

In all browsers, the load, scroll, and error events (e.g., on an <img> element) do not bubble. In Internet Explorer 8 and lower, the paste and reset events do not bubble. Such events are not supported for use with delegation, but they can be used when the event handler is directly attached to the element generating the event.

If you want to do something when a new input box is added then you can simply write the code after appending it.

$('#add').click(function(){
        $('body').append(x);
        // Your code can be here
    });

And if you want the same code execute when the first input box within the document is loaded then you can write a function and call it in both places i.e. $('#add').click and document's ready event

JavaScript: filter() for Objects

How about:

function filterObj(keys, obj) {
  const newObj = {};
  for (let key in obj) {
    if (keys.includes(key)) {
      newObj[key] = obj[key];
    }
  }
  return newObj;
}

Or...

function filterObj(keys, obj) {
  const newObj = {};
  Object.keys(obj).forEach(key => {
    if (keys.includes(key)) {
      newObj[key] = obj[key];
    }
  });
  return newObj;
}

jQuery 'each' loop with JSON array

Brief code but full-featured

The following is a hybrid jQuery solution that formats each data "record" into an HTML element and uses the data's properties as HTML attribute values.

The jquery each runs the inner loop; I needed the regular JavaScript for on the outer loop to be able to grab the property name (instead of value) for display as the heading. According to taste it can be modified for slightly different behaviour.

This is only 5 main lines of code but wrapped onto multiple lines for display:

$.get("data.php", function(data){

    for (var propTitle in data) {

        $('<div></div>') 
            .addClass('heading')
            .insertBefore('#contentHere')
            .text(propTitle);

            $(data[propTitle]).each(function(iRec, oRec) {

                $('<div></div>')
                    .addClass(oRec.textType)
                    .attr('id', 'T'+oRec.textId)
                    .insertBefore('#contentHere')
                    .text(oRec.text);
            });
    }

});

Produces the output

(Note: I modified the JSON data text values by prepending a number to ensure I was displaying the proper records in the proper sequence - while "debugging")

<div class="heading">
    justIn
</div>
<div id="T123" class="Greeting">
    1Hello
</div>
<div id="T514" class="Question">
    1What's up?
</div>
<div id="T122" class="Order">
    1Come over here
</div>
<div class="heading">
    recent
</div>
<div id="T1255" class="Greeting">
    2Hello
</div>
<div id="T6564" class="Question">
    2What's up?
</div>
<div id="T0192" class="Order">
    2Come over here
</div>
<div class="heading">
    old
</div>
<div id="T5213" class="Greeting">
    3Hello
</div>
<div id="T9758" class="Question">
    3What's up?
</div>
<div id="T7655" class="Order">
    3Come over here
</div>
<div id="contentHere"></div>

Apply a style sheet

<style>
.heading { font-size: 24px; text-decoration:underline }
.Greeting { color: green; }
.Question { color: blue; }
.Order { color: red; }
</style>

to get a "beautiful" looking set of data

alt text

More Info
The JSON data was used in the following way:

for each category (key name the array is held under):

  • the key name is used as the section heading (e.g. justIn)

for each object held inside an array:

  • 'text' becomes the content of a div
  • 'textType' becomes the class of the div (hooked into a style sheet)
  • 'textId' becomes the id of the div
  • e.g. <div id="T122" class="Order">Come over here</div>

hardcoded string "row three", should use @string resource

A good practice is write text inside String.xml

example:

String.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="yellow">Yellow</string>
</resources>

and inside layout:

<TextView android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="@string/yellow" />

Server configuration is missing in Eclipse

this worked for me

  1. In the Server's tab in Eclipse, Stop the Tomcat server

  2. Right-click the server and select "Clean..."

  3. Right-click the server again and select "Clean Tomcat Work Directory..."

  4. In the Eclipse, select the top-level menu option, Project > Clean ...

  5. Be sure your project is selected and click Ok

  6. Restart Eclipse

What is the best way to iterate over a dictionary?

You can also try this on big dictionaries for multithreaded processing.

dictionary
.AsParallel()
.ForAll(pair => 
{ 
    // Process pair.Key and pair.Value here
});

How can I convert a std::string to int?

My Code:

#include <iostream>
using namespace std;

int main()
{
    string s="32";  //String
    int n=stoi(s);  //Convert to int
    cout << n + 1 << endl;

    return 0;
}

Search for a string in all tables, rows and columns of a DB

I think this can be an easiest way to find a string in all rows of your database -without using cursors and FOR XML-.

CREATE PROCEDURE SPFindAll (@find VARCHAR(max) = '')
AS
BEGIN
    SET NOCOUNT ON;
    --
    DECLARE @query VARCHAR(max) = ''

    SELECT  @query = @query + 
            CASE 
                WHEN @query = '' THEN '' 
                ELSE ' UNION ALL '
            END +
            'SELECT ''' + s.name + ''' As schemaName, ''' + t.name + ''' As tableName, ''' + c.name + ''' As ColumnName, [' + c.name + '] COLLATE DATABASE_DEFAULT As [Data] FROM [' + s.name + '].[' + t.name + '] WHERE [' + c.name + '] Like ''%' + @find + '%'''
    FROM 
        sys.schemas s
        INNER JOIN
        sys.tables t ON s.[schema_id] = t.[schema_id]
        INNER JOIN 
        sys.columns c ON t.[object_id] = c.[object_id]
        INNER JOIN
        sys.types ty ON c.user_type_id = ty.user_type_id
    WHERE
        ty.name LIKE '%char'

    EXEC(@query)
END

By creating this stored procedure you can run it for any string you want to find like this:

EXEC SPFindAll 'Hello World'

The result will be like this:

schemaName | tableName | columnName | Data
-----------+-----------+------------+-----------------------
schema1    | Table1    | Column1    | Hello World
schema1    | Table1    | Column1    | Hello World!
schema1    | Table2    | Column1    | I say "Hello World".
schema1    | Table2    | Column2    | Hello World

Error: org.testng.TestNGException: Cannot find class in classpath: EmpClass

I had the same error when tried to run my tests in a JSF project.

I´m using Eclipse IDE (kepler). So, I did "project > clean" and then ran the tests again of the same project.

It worked!

What IDE to use for Python?

Results

Spreadsheet version

spreadsheet screenshot

Alternatively, in plain text: (also available as a a screenshot)

                         Bracket Matching -.  .- Line Numbering
                          Smart Indent -.  |  |  .- UML Editing / Viewing
         Source Control Integration -.  |  |  |  |  .- Code Folding
                    Error Markup -.  |  |  |  |  |  |  .- Code Templates
  Integrated Python Debugging -.  |  |  |  |  |  |  |  |  .- Unit Testing
    Multi-Language Support -.  |  |  |  |  |  |  |  |  |  |  .- GUI Designer (Qt, Eric, etc)
   Auto Code Completion -.  |  |  |  |  |  |  |  |  |  |  |  |  .- Integrated DB Support
     Commercial/Free -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  .- Refactoring
   Cross Platform -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom              |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |  |  |  |  |*many plugins
Editra            |Y |F |Y |Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |
Emacs             |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
Eric Ide          |Y |F |Y |  |Y |Y |  |Y |  |Y |  |Y |  |Y |  |  |  |
Geany             |Y |F |Y*|Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |*very limited
Gedit             |Y |F |Y¹|Y |  |  |  |Y |Y |Y |  |  |Y²|  |  |  |  |¹with plugin; ²sort of
Idle              |Y |F |Y |  |Y |  |  |Y |Y |  |  |  |  |  |  |  |  |
IntelliJ          |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit             |Y |F |  |Y |  |  |  |  |Y |Y |  |Y |  |  |  |  |  |
KDevelop          |Y |F |Y*|Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |*no type inference
Komodo            |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |Y |  |
NetBeans*         |Y |F |Y |Y |Y |  |Y |Y |Y |Y |Y |Y |Y |Y |  |  |Y |*pre-v7.0
Notepad++         |W |F |Y |Y |  |Y*|Y*|Y*|Y |Y |  |Y |Y*|  |  |  |  |*with plugin
Pfaide            |W |C |Y |Y |  |  |  |Y |Y |Y |  |Y |Y |  |  |  |  |
PIDA              |LW|F |Y |Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |VIM based
PTVS              |W |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |  |  |Y*|  |Y |*WPF bsed
PyCharm           |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse)   |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
PyScripter        |W |F |Y |  |Y |Y |  |Y |Y |Y |  |Y |Y |Y |  |  |  |
PythonWin         |W |F |Y |  |Y |  |  |Y |Y |  |  |Y |  |  |  |  |  |
SciTE             |Y |F¹|  |Y |  |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |¹Mac version is
ScriptDev         |W |C |Y |Y |Y |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |    commercial
Spyder            |Y |F |Y |  |Y |Y |  |Y |Y |Y |  |  |  |  |  |  |  |
Sublime Text      |Y |CF|Y |Y |  |Y |Y |Y |Y |Y |  |Y |Y |Y*|  |  |  |extensible w/Python,
TextMate          |M |F |  |Y |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |    *PythonTestRunner
UliPad            |Y |F |Y |Y |Y |  |  |Y |Y |  |  |  |Y |Y |  |  |  |
Vim               |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |
Visual Studio     |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde           |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |*support for C
Zeus              |W |C |  |  |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
   Cross Platform -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
     Commercial/Free -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  '- Refactoring
   Auto Code Completion -'  |  |  |  |  |  |  |  |  |  |  |  |  '- Integrated DB Support
    Multi-Language Support -'  |  |  |  |  |  |  |  |  |  |  '- GUI Designer (Qt, Eric, etc)
  Integrated Python Debugging -'  |  |  |  |  |  |  |  |  '- Unit Testing
                    Error Markup -'  |  |  |  |  |  |  '- Code Templates
         Source Control Integration -'  |  |  |  |  '- Code Folding
                          Smart Indent -'  |  |  '- UML Editing / Viewing
                         Bracket Matching -'  '- Line Numbering

Acronyms used:

 L  - Linux
 W  - Windows
 M  - Mac
 C  - Commercial
 F  - Free
 CF - Commercial with Free limited edition
 ?  - To be confirmed

I don't mention basics like syntax highlighting as I expect these by default.


This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.

PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?

We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments

Submit edits to the spreadsheet

Converting JSON to XML in Java

Use the (excellent) JSON-Java library from json.org then

JSONObject json = new JSONObject(str);
String xml = XML.toString(json);

toString can take a second argument to provide the name of the XML root node.

This library is also able to convert XML to JSON using XML.toJSONObject(java.lang.String string)

Check the Javadoc

Link to the the github repository

POM

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20160212</version>
</dependency>

original post updated with new links

Get the distance between two geo points

There are a couple of methods you could use, but to determine which one is best we first need to know if you are aware of the user's altitude, as well as the altitude of the other points?

Depending on the level of accuracy you are after, you could look into either the Haversine or Vincenty formulae...

These pages detail the formulae, and, for the less mathematically inclined also provide an explanation of how to implement them in script!

Haversine Formula: http://www.movable-type.co.uk/scripts/latlong.html

Vincenty Formula: http://www.movable-type.co.uk/scripts/latlong-vincenty.html

If you have any problems with any of the meanings in the formulae, just comment and I'll do my best to answer them :)

What is the easiest way to initialize a std::vector with hardcoded elements?

If the array is:

int arr[] = {1, 2, 3};
int len = (sizeof(arr)/sizeof(arr[0])); // finding length of array
vector < int > v;
std:: v.assign(arr, arr+len); // assigning elements from array to vector 

How to select the last record from MySQL table using SQL syntax

SELECT * FROM your_table ORDER BY id ASC LIMIT 0, 1

The ASC will return resultset in ascending order thereby leaving you with the latest or most recent record. The DESC counterpart will do the exact opposite. That is, return the oldest record.

jquery ajax function not working

I am doing a code like this

_x000D_
_x000D_
<!-- Optional JavaScript -->_x000D_
<!-- jQuery first, then Popper.js, then Bootstrap JS -->_x000D_
<script_x000D_
    src="http://code.jquery.com/jquery-3.3.1.min.js"_x000D_
    integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="_x000D_
    crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>_x000D_
<script>_x000D_
    $(document).ready(function () {_x000D_
_x000D_
        $(".work-category a").click(function (e) {_x000D_
            e.preventDefault();_x000D_
            var id = $(this).attr('data-id');_x000D_
            $.ajax({_x000D_
                url: 'process.php',_x000D_
                method: 'POST',_x000D_
                data: {_x000D_
                    clickCategoryID : id_x000D_
                },_x000D_
                dataType: 'JSON',_x000D_
                success: function (data) {_x000D_
                    $("#content-area").html(data.Content);_x000D_
                    $(".container-area").animate({top: '100px'}, 1000);_x000D_
                    $(".single-content").animate({opacity:1}, 1000);_x000D_
                }_x000D_
            });_x000D_
        });_x000D_
_x000D_
    });_x000D_
</script>
_x000D_
_x000D_
_x000D_

But the code is not running and the console saya process.php not found though I have the code on it.

PHP is not recognized as an internal or external command in command prompt

Set "C:\xampp\php" in your PATH Environment Variable. Then restart CMD prompt.

formGroup expects a FormGroup instance

There are a few issues in your code

  • <div [formGroup]="form"> outside of a <form> tag
  • <form [formGroup]="form"> but the name of the property containing the FormGroup is loginForm therefore it should be <form [formGroup]="loginForm">
  • [formControlName]="dob" which passes the value of the property dob which doesn't exist. What you need is to pass the string dob like [formControlName]="'dob'" or simpler formControlName="dob"

Plunker example

GridView - Show headers on empty data source

You can use HeaderTemplate property to setup the head programatically or use ListView instead if you are using .NET 3.5.

Personally, I prefer ListView over GridView and DetailsView if possible, it gives you more control over your html.

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.

Encode a FileStream to base64 with c#

When dealing with large streams, like a file sized over 4GB - you don't want to load the file into memory (as a Byte[]) because not only is it very slow, but also may cause a crash as even in 64-bit processes a Byte[] cannot exceed 2GB (or 4GB with gcAllowVeryLargeObjects).

Fortunately there's a neat helper in .NET called ToBase64Transform which processes a stream in chunks. For some reason Microsoft put it in System.Security.Cryptography and it implements ICryptoTransform (for use with CryptoStream), but disregard that ("a rose by any other name...") just because you aren't performing any cryprographic tasks.

You use it with CryptoStream like so:

using System.Security.Cryptography;
using System.IO;

//

using( FileStream   inputFile    = new FileStream( @"C:\VeryLargeFile.bin", FileMode.Open, FileAccess.Read, FileShare.None, bufferSize: 1024 * 1024, useAsync: true ) ) // When using `useAsync: true` you get better performance with buffers much larger than the default 4096 bytes.
using( CryptoStream base64Stream = new CryptoStream( inputFile, new ToBase64Transform(), CryptoStreamMode.Read ) )
using( FileStream   outputFile   = new FileStream( @"C:\VeryLargeBase64File.txt", FileMode.CreateNew, FileAccess.Write, FileShare.None, bufferSize: 1024 * 1024, useAsync: true ) )
{
    await base64Stream.CopyToAsync( outputFile ).ConfigureAwait(false);
}

Floating point inaccuracy examples

Another example, in C

printf (" %.20f \n", 3.6);

incredibly gives

3.60000000000000008882

How to store file name in database, with other info while uploading image to server using PHP?

Your part:

$result = mysql_connect("localhost", "******", "*****") or die ("Could not save image name

Error: " . mysql_error());

mysql_select_db("project") or die("Could not select database");
mysql_query("INSERT into dbProfiles (photo) VALUES('".$_FILES['filep']['name']."')");
if($result) { echo "Image name saved into database

";

Doesn't make much sense, your connection shouldn't be named $result but that is a naming issue not a coding one.

What is a coding issue is if($result), your saying if you can connect to the database regardless of the insert query failing or succeeding you will output "Image saved into database".

Try adding do

$realresult = mysql_query("INSERT into dbProfiles (photo) VALUES('".$_FILES['filep']['name']."')");

and change the if($result) to $realresult

I suspect your query is failing, perhaps you have additional columns or something?

Try copy/pasting your query, replacing the ".$_FILES['filep']['name']." with test and running it in your query browser and see if it goes in.

Android difference between Two Dates

This works and convert to String as a Bonus ;)

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    try {
        //Dates to compare
        String CurrentDate=  "09/24/2015";
        String FinalDate=  "09/26/2015";

        Date date1;
        Date date2;

        SimpleDateFormat dates = new SimpleDateFormat("MM/dd/yyyy");

        //Setting dates
        date1 = dates.parse(CurrentDate);
        date2 = dates.parse(FinalDate);

        //Comparing dates
        long difference = Math.abs(date1.getTime() - date2.getTime());
        long differenceDates = difference / (24 * 60 * 60 * 1000);

        //Convert long to String
        String dayDifference = Long.toString(differenceDates);

        Log.e("HERE","HERE: " + dayDifference);

    } catch (Exception exception) {
        Log.e("DIDN'T WORK", "exception " + exception);
    }
}

Counting words in string

Use square brackets, not parentheses:

str[i] === " "

Or charAt:

str.charAt(i) === " "

You could also do it with .split():

return str.split(' ').length;

Java, How do I get current index/key in "for each" loop

Not possible in Java.


Here's the Scala way:

val m = List(5, 4, 2, 89)

for((el, i) <- m.zipWithIndex)
  println(el +" "+ i)

What is the difference between MacVim and regular Vim?

MacVim is just Vim. Anything you are used to do in Vim will work exactly the same way in MacVim.

MacVim is more integrated in the whole OS than Vim in the Terminal or even GVim in Linux, it follows a lot of Mac OS X's conventions.

If you work mainly with GUI apps (YummyFTP + GitX + Charles, for example) you may prefer MacVim.

If you work mainly with CLI apps (ssh + svn + tcpdump, for example) you may prefer vim in the terminal.

Entering and leaving one realm (CLI) for the other (GUI) and vice-versa can be "expensive".

I use both MacVim and Vim depending on the task and the context: if I'm in CLI-land I'll just type vim filename and if I'm in GUI-land I'll just invoke Quicksilver and launch MacVim.

When I switched from TextMate I kind of liked the fact that MacVim supported almost all of the regular shortcuts Mac users are accustomed to. I added some of my own, mimiking TextMate but, since I was working in multiple environments I forced my self to learn the vim way. Now I use both MacVim and Vim almost exactly the same way. Using one or the other is just a question of context for me.

Also, like El Isra said, the default vim (CLI) in OS X is slightly outdated. You may install an up-to-date version via MacPorts or you can install MacVim and add an alias to your .profile:

alias vim='/path/to/MacVim.app/Contents/MacOS/Vim'

to have the same vim in MacVim and Terminal.app.

Another difference is that many great colorschemes out there work out of the box in MacVim but look terrible in the Terminal.app which only supports 8 colors (+ highlights) but you can use iTerm — which can be set up to support 256 colors — instead of Terminal.

So… basically my advice is to just use both.

EDIT: I didn't try it but the latest version of Terminal.app (in 10.7) is supposed to support 256 colors. I'm still on 10.6.x at work so I'll still use iTerm2 for a while.

EDIT: An even better way to use MacVim's CLI executable in your shell is to move the mvim script bundled with MacVim somewhere in your $PATH and use this command:

$ mvim -v

EDIT: Yes, Terminal.app now supports 256 colors. So if you don't need iTerm2's advanced features you can safely use the default terminal emulator.

How to split a comma-separated string?

You can split it and make an array then access like array

String names = "prappo,prince";
String[] namesList = names.split(",");

you can access like

String name1 = namesList [0];
String name2 = namesList [1];

or using loop

for(String name : namesList){
System.out.println(name);
}

hope it will help you .

datetime.parse and making it work with a specific format

Thanks for the tip, i used this to get my date "20071122" parsed, I needed to add datetimestyles, I used none and it worked:

DateTime dt = DateTime.MinValue;

DateTime.TryParseExact("20071122", "yyyyMMdd", null,System.Globalization.DateTimeStyles.None, out dt);

How to make certain text not selectable with CSS

Use a simple background image for the textarea suffice.

Or

<div onselectstart="return false">your text</div>

Hive cast string to date dd-MM-yyyy

try:

from_unixtime(unix_timestamp('12-03-2010' , 'dd-MM-yyyy'))

CSS '>' selector; what is it?

It declares parent reference, look at this page for definition:

http://www.w3.org/TR/CSS2/selector.html#child-selectors

jQuery detect if string contains something

You could use String.prototype.indexOf to accomplish that. Try something like this:

_x000D_
_x000D_
$('.type').keyup(function() {_x000D_
  var v = $(this).val();_x000D_
  if (v.indexOf('> <') !== -1) {_x000D_
    console.log('contains > <');_x000D_
  }_x000D_
  console.log(v);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea class="type"></textarea>
_x000D_
_x000D_
_x000D_

Update

Modern browsers also have a String.prototype.includes method.

filter out multiple criteria using excel vba

I think (from experimenting - MSDN is unhelpful here) that there is no direct way of doing this. Setting Criteria1 to an Array is equivalent to using the tick boxes in the dropdown - as you say it will only filter a list based on items that match one of those in the array.

Interestingly, if you have the literal values "<>A" and "<>B" in the list and filter on these the macro recorder comes up with

Range.AutoFilter Field:=1, Criteria1:="=<>A", Operator:=xlOr, Criteria2:="=<>B"

which works. But if you then have the literal value "<>C" as well and you filter for all three (using tick boxes) while recording a macro, the macro recorder replicates precisely your code which then fails with an error. I guess I'd call that a bug - there are filters you can do using the UI which you can't do with VBA.

Anyway, back to your problem. It is possible to filter values not equal to some criteria, but only up to two values which doesn't work for you:

Range("$A$1:$A$9").AutoFilter Field:=1, Criteria1:="<>A", Criteria2:="<>B", Operator:=xlAnd

There are a couple of workarounds possible depending on the exact problem:

  1. Use a "helper column" with a formula in column B and then filter on that - e.g. =ISNUMBER(A2) or =NOT(A2="A", A2="B", A2="C") then filter on TRUE
  2. If you can't add a column, use autofilter with Criteria1:=">-65535" (or a suitable number lower than any you expect) which will filter out non-numeric values - assuming this is what you want
  3. Write a VBA sub to hide rows (not exactly the same as an autofilter but it may suffice depending on your needs).

For example:

Public Sub hideABCRows(rangeToFilter As Range)
  Dim oCurrentCell As Range
  On Error GoTo errHandler

  Application.ScreenUpdating = False
  For Each oCurrentCell In rangeToFilter.Cells
    If oCurrentCell.Value = "A" Or oCurrentCell.Value = "B" Or oCurrentCell.Value = "C" Then
      oCurrentCell.EntireRow.Hidden = True
    End If
  Next oCurrentCell

  Application.ScreenUpdating = True
  Exit Sub

errHandler:
    Application.ScreenUpdating = True
End Sub

jQuery hover and class selector

Always keep things easy and simple by creating a class

.bcolor{ background:#F00; }

THEN USE THE addClass() & removeClass() to finish it up

How can I remove or replace SVG content?

I had two charts.

<div id="barChart"></div>
<div id="bubbleChart"></div>

This removed all charts.

d3.select("svg").remove(); 

This worked for removing the existing bar chart, but then I couldn't re-add the bar chart after

d3.select("#barChart").remove();

Tried this. It not only let me remove the existing bar chart, but also let me re-add a new bar chart.

d3.select("#barChart").select("svg").remove();

var svg = d3.select('#barChart')
       .append('svg')
       .attr('width', width + margins.left + margins.right)
       .attr('height', height + margins.top + margins.bottom)
       .append('g')
       .attr('transform', 'translate(' + margins.left + ',' + margins.top + ')');

Not sure if this is the correct way to remove, and re-add a chart in d3. It worked in Chrome, but have not tested in IE.

Change the "No file chosen":

I'm pretty sure you cannot change the default labels on buttons, they are hard-coded in browsers (each browser rendering the buttons captions its own way). Check out this button styling article

PySpark 2.0 The size or shape of a DataFrame

I think there is not similar function like data.shape in Spark. But I will use len(data.columns) rather than len(data.dtypes)

How to refer to relative paths of resources when working with a code repository

In Python, paths are relative to the current working directory, which in most cases is the directory from which you run your program. The current working directory is very likely not as same as the directory of your module file, so using a path relative to your current module file is always a bad choice.

Using absolute path should be the best solution:

import os
package_dir = os.path.dirname(os.path.abspath(__file__))
thefile = os.path.join(package_dir,'test.cvs')

What's wrong with foreign keys?

I can see a few reasons to use foreign keys (Orphaned rows, as someone mentioned, are annoying) but I never use them either. With a relatively sane DB schema, I don't think they are 100% needed. Constraints are good, but enforcing them via software is a better method, I think.

Alex

How to get std::vector pointer to the raw data?

Take a pointer to the first element instead:

process_data (&something [0]);

Call to undefined function oci_connect()

I had the same issue, the solution on this page helped me, it's caused by using incompatible oci ddl files.

Hope it helps.

Is not an enclosing class Java

As stated in the docs:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

Is there a way to get a <button> element to link to a location without wrapping it in an <a href ... tag?

You can make it a non-submitting button (<button type="button">) and hook something like window.location = 'http://where.you.want/to/go' into its onclick handler. This does not work without javascript enabled though.

Or you can make it a submit button, and do a redirect on the server, although this obviously requires some kind of server-side logic, but the upside is that is doesn't require javascript.

(actually, forget the second solution - if you can't use a form, the submit button is out)

How to change dot size in gnuplot

The pointsize command scales the size of points, but does not affect the size of dots.

In other words, plot ... with points ps 2 will generate points of twice the normal size, but for plot ... with dots ps 2 the "ps 2" part is ignored.

You could use circular points (pt 7), which look just like dots.

access denied for user @ 'localhost' to database ''

Try this: Adding users to MySQL

You need grant privileges to the user if you want external acess to database(ie. web pages).

how to setup ssh keys for jenkins to publish via ssh

You don't need to create the SSH keys on the Jenkins server, nor do you need to store the SSH keys on the Jenkins server's filesystem. This bit of information is crucial in environments where Jenkins servers instances may be created and destroyed frequently.

Generating the SSH Key Pair

On any machine (Windows, Linux, MacOS ...doesn't matter) generate an SSH key pair. Use this article as guide:

On the Target Server

On the target server, you will need to place the content of the public key (id_rsa.pub per the above article) into the .ssh/authorized_keys file under the home directory of the user which Jenkins will be using for deployment.

In Jenkins

Using "Publish over SSH" Plugin

Ref: https://plugins.jenkins.io/publish-over-ssh/

Visit: Jenkins > Manage Jenkins > Configure System > Publish over SSH

  • If the private key is encrypted, then you will need to enter the passphrase for the key into the "Passphrase" field, otherwise leave it alone.
  • Leave the "Path to key" field empty as this will be ignored anyway when you use a pasted key (next step)
  • Copy and paste the contents of the private key (id_rsa per the above article) into the "Key" field
  • Under "SSH Servers", "Add" a new server configuration for your target server.

Using Stored Global Credentials

Visit: Jenkins > Credentials > System > Global credentials (unrestricted) > Add Credentials

  • Kind: "SSH Username with private key"
  • Scope: "Global"
  • ID: [CREAT A UNIQUE ID FOR THIS KEY]
  • Description: [optionally, enter a decription]
  • Username: [USERNAME JENKINS WILL USE TO CONNECT TO REMOTE SERVER]
  • Private Key: [select "Enter directly"]
  • Key: [paste the contents of the private key (id_rsa per the above article)]
  • Passphrase: [enter the passphrase for the key, or leave it blank if the key is not encrypted]

Using "label for" on radio buttons

Either structure is valid and accessible, but the for attribute should be equal to the id of the input element:

<input type="radio" ... id="r1" /><label for="r1">button text</label>

or

<label for="r1"><input type="radio" ... id="r1" />button text</label>

The for attribute is optional in the second version (label containing input), but IIRC there were some older browsers that didn't make the label text clickable unless you included it. The first version (label after input) is easier to style with CSS using the adjacent sibling selector +:

input[type="radio"]:checked+label {font-weight:bold;}

Regex for quoted string with escaping quotes

One has to remember that regexps aren't a silver bullet for everything string-y. Some stuff are simpler to do with a cursor and linear, manual, seeking. A CFL would do the trick pretty trivially, but there aren't many CFL implementations (afaik).

Java File - Open A File And Write To It

Suggestions:

  • Create a File object that refers to the already existing file on disk.
  • Use a FileWriter object, and use the constructor that takes the File object and a boolean, the latter if true would allow appending text into the File if it exists.
  • Then initialize a PrintWriter passing in the FileWriter into its constructor.
  • Then call println(...) on your PrintWriter, writing your new text into the file.
  • As always, close your resources (the PrintWriter) when you are done with it.
  • As always, don't ignore exceptions but rather catch and handle them.
  • The close() of the PrintWriter should be in the try's finally block.

e.g.,

  PrintWriter pw = null;

  try {
     File file = new File("fubars.txt");
     FileWriter fw = new FileWriter(file, true);
     pw = new PrintWriter(fw);
     pw.println("Fubars rule!");
  } catch (IOException e) {
     e.printStackTrace();
  } finally {
     if (pw != null) {
        pw.close();
     }
  }

Easy, no?

iPad/iPhone hover problem causes the user to double click a link

Haven't tested this fully but since iOS fires touch events, this could work, assuming you are in a jQuery setting.

$('a').on('click touchend', function(e) {
    var el = $(this);
    var link = el.attr('href');
    window.location = link;
});

The idea is that Mobile WebKit fires a touchend event at the end of a tap so we listen for that and then redirect the browser as soon as a touchend event has been fired on a link.

Cell color changing in Excel using C#

Note: This assumes that you will declare constants for row and column indexes named COLUMN_HEADING_ROW, FIRST_COL, and LAST_COL, and that _xlSheet is the name of the ExcelSheet (using Microsoft.Interop.Excel)

First, define the range:

var columnHeadingsRange = _xlSheet.Range[
    _xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
    _xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];

Then, set the background color of that range:

columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;

Finally, set the font color:

columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;

And here's the code combined:

var columnHeadingsRange = _xlSheet.Range[
    _xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
    _xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];

columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;

columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;

Django Multiple Choice Field / Checkbox Select Multiple

ManyToManyField isn`t a good choice.You can use some snippets to implement MultipleChoiceField.You can be inspired by MultiSelectField with comma separated values (Field + FormField) But it has some bug in it.And you can install django-multiselectfield.This is more prefect.

Changing website favicon dynamically

The only way to make this work for IE is to set you web server to treat requests for *.ico to call your server side scripting language (PHP, .NET, etc). Also setup *.ico to redirect to a single script and have this script deliver the correct favicon file. I'm sure there is still going to be some interesting issues with cache if you want to be able to bounce back and forth in the same browser between different favicons.

How to filter an array from all elements of another array

The OA can also be implemented in ES6 as follows

ES6:

 const filtered = [1, 2, 3, 4].filter(e => {
    return this.indexOf(e) < 0;
  },[2, 4]);

How to determine the Schemas inside an Oracle Data Pump Export file

If you open the DMP file with an editor that can handle big files, you might be able to locate the areas where the schema names are mentioned. Just be sure not to change anything. It would be better if you opened a copy of the original dump.

How to make a simple popup box in Visual C#?

System.Windows.Forms.MessageBox.Show("My message here");

Make sure the System.Windows.Forms assembly is referenced your project.

Select values from XML field in SQL Server 2008

This may answer your question:

select cast(xmlField as xml) xmlField into tmp from (
select '<person><firstName>Jon</firstName><lastName>Johnson</lastName></person>' xmlField
union select '<person><firstName>Kathy</firstName><lastName>Carter</lastName></person>'
union select '<person><firstName>Bob</firstName><lastName>Burns</lastName></person>'
) tb

SELECT
    xmlField.value('(person/firstName)[1]', 'nvarchar(max)') as FirstName
    ,xmlField.value('(person/lastName)[1]', 'nvarchar(max)') as LastName
FROM tmp

drop table tmp

Embed ruby within URL : Middleman Blog

<%= link_to "http://www.facebook.com/sharer.php?u=" + article_url(article, :text => article.title), :class => "btn btn-primary" do %>   <i class="fa fa-facebook">     Facebook Share    </i> <%end%> 

I am assuming that current_article_url is http://0.0.0.0:4567/link_to_title

How to send email from SQL Server?

You can do it with a cursor also. Assuming that you have created an Account and a Profile e.g. "profile" and an Account and you have the table that holds the emails ready e.g. "EmailMessageTable" you can do the following:

USE database_name
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE mass_email AS
declare @email nvarchar (50) 
declare @body nvarchar (255)  

declare test_cur cursor for             
SELECT email from [dbo].[EmailMessageTable]

open test_cur                                        

fetch next from test_cur into   
@email     
while @@fetch_status = 0       
begin                                    

set @body = (SELECT body from [dbo].[EmailMessageTable] where email = @email)
EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'profile',
    @recipients = @email,
    @body = @body,
    @subject = 'Credentials for Web';
fetch next from test_cur into  
@email 
end    
close test_cur   
deallocate test_cur

After that all you have to do is execute the Stored Procedure

EXECUTE mass_email
GO

Dialog throwing "Unable to add window — token null is not for an application” with getApplication() as context

***** kotlin version *****

You should pass this@YourActivity instead of applicationContext or baseContext

How exactly does binary code get converted into letters?

Here's a way to convert binary numbers to ASCII characters that is often simple enough to do in your head.

1 - Convert every 4 binary digits into one hex digit.

Here's a binary to hex conversion chart:

0001 = 1 
0010 = 2 
0011 = 3 
0100 = 4 
0101 = 5
0110 = 6
0111 = 7
1000 = 8

1001 = 9
1010 = a (the hex number a, not the letter a)
1011 = b
1100 = c
1101 = d
1110 = e
1111 = f

(The hexadecimal numbers a through f are the decimal numbers 10 through 15. That's what hexadecimal, or "base 16" is - instead of each digit being capable of representing 10 different numbers [0 - 9], like decimal or "base 10" does, each digit is instead capable of representing 16 different numbers [0 - f].)

Once you know that chart, converting any string of binary digits into a string of hex digits is simple.

For example,

01000100 = 0100 0100 = 44 hex
1010001001110011 = 1010 0010 0111 0011 = a273 hex

Simple enough, right? It is a simple matter to convert a binary number of any length into its hexadecimal equivalent.

(This works because hexadecimal is base 16 and binary is base 2 and 16 is the 4th power of 2, so it takes 4 binary digits to make 1 hex digit. 10, on the other hand, is not a power of 2, so we can't convert binary to decimal nearly as easily.)

2 - Split the string of hex digits into pairs.

When converting a number into ASCII, every 2 hex digits is a character. So break the hex string into sets of 2 digits.

You would split a hex number like 7340298b392 this into 6 pairs, like this:

7340298b392 = 07 34 02 98 b3 92

(Notice I prepended a 0, since I had an odd number of hex digits.)

That's 6 pairs of hex digits, so its going to be 6 letters. (Except I know right away that 98, b3 and 92 aren't letters. I'll explain why in a minute.)

3 - Convert each pair of hex digits into a decimal number.

Do this by multiplying the (decimal equivalent of the) left digit by 16, and adding the 2nd.

For example, b3 hex = 11*16 + 3, which is 110 + 66 + 3, which is 179. (b hex is 11 decimal.)

4 - Convert the decimal numbers into ASCII characters.

Now, to get the ASCII letters for the decimal numbers, simply keep in mind that in ASCII, 65 is an uppercase 'A', and 97 is a lowercase 'a'.

So what letter is 68?

68 is the 4th letter of the alphabet in uppercase, right?
65 = A, 66 = B, 67 = C, 68 = D.

So 68 is 'D'.

You take the decimal number, subtract 64 for uppercase letters if the number is less than 97, or 96 for lowercase letters if the number is 97 or larger, and that's the number of the letter of the alphabet associated with that set of 2 hex digits.


Alternatively, if you're not afraid of a little bit of easy hex arithmetic, you can skip step 3, and just go straight from hex to ASCII, by remembering, for example, that

hex 41 = 'A' 
hex 61 = 'a'

So subtract 40 hex for uppercase letters or 60 hex for lowercase letters, and convert what's left to decimal to get the alphabet letter number.

For example

01101100 = 6c, 6c - 60 = c = 12 decimal = 'l'
01010010 = 52, 52 - 40 = 12 hex = 18 decimal = 'R'

(When doing this, it's helpful to remember that 'm' (or 'M') is the 13 letter of the alphabet. So you can count up or down from 13 to find a letter that's nearer to the middle than to either end.)

I saw this on a shirt once, and was able to read it in my head:

01000100
01000001
01000100

I did it like this:

01000100 = 0100 0100 = 44 hex, - 40 hex = ucase letter 4 = D
01000001 = 0100 0001 = 41 hex, - 40 hex = ucase letter 1 = A
01000100 = 0100 0100 = 44 hex, - 40 hex = ucase letter 4 = D

The shirt said "DAD", which I thought was kinda cool, since it was being purchased by a pregnant woman. Her husband must be a geek like me.


How did I know right away that 92, b3, and 98 were not letters?

Because the ASCII code for a lowercase 'z' is 96 + 26 = 122, which in hex is 7a. 7a is the largest hex number for a letter. Anything larger than 7a is not a letter.


So that's how you can do it as a human.

How do computer programs do it?

For each set of 8 binary digits, convert it to a number, and look it up in an ASCII table.

(That's one pretty obvious and straight forward way. A typical programmer could probably think of 10 or 15 other ways in the space of a few minutes. The details depend on the computer language environment.)

SQL Server equivalent of MySQL's NOW()?

You can also use CURRENT_TIMESTAMP, if you feel like being more ANSI compliant (though if you're porting code between database vendors, that'll be the least of your worries). It's exactly the same as GetDate() under the covers (see this question for more on that).

There's no ANSI equivalent for GetUTCDate(), however, which is probably the one you should be using if your app operates in more than a single time zone ...

What is the proper use of an EventEmitter?

There is no: nono and no: yesyes. The truth is in the middle And no reasons to be scared because of the next version of Angular.

From a logical point of view, if You have a Component and You want to inform other components that something happens, an event should be fired and this can be done in whatever way You (developer) think it should be done. I don't see the reason why to not use it and i don't see the reason why to use it at all costs. Also the EventEmitter name suggests to me an event happening. I usually use it for important events happening in the Component. I create the Service but create the Service file inside the Component Folder. So my Service file becomes a sort of Event Manager or an Event Interface, so I can figure out at glance to which event I can subscribe on the current component.

I know..Maybe I'm a bit an old fashioned developer. But this is not a part of Event Driven development pattern, this is part of the software architecture decisions of Your particular project.

Some other guys may think that use Observables directly is cool. In that case go ahead with Observables directly. You're not a serial killer doing this. Unless you're a psychopath developer, So far the Program works, do it.

href="javascript:" vs. href="javascript:void(0)"

Why have all the click events as a href links?

If instead you use span tags with :hover CSS and the appropriate onclick events, this will get around the issue completely.

arranging div one below the other

You don't even need the float:left;

It seems the default behavior is to render one below the other, if it doesn't happen it's because they are inheriting some style from above.

CSS:

#wrapper{
    margin-left:auto;
    margin-right:auto;
    height:auto; 
    width:auto;
}
</style>

HTML:

<div id="wrapper">
    <div id="inner1">inner1</div>
    <div id="inner2">inner2</div>
</div>

Programmatically shut down Spring Boot application

In the application you can use SpringApplication. This has a static exit() method that takes two arguments: the ApplicationContext and an ExitCodeGenerator:

i.e. you can declare this method:

@Autowired
public void shutDown(ExecutorServiceExitCodeGenerator exitCodeGenerator) {
    SpringApplication.exit(applicationContext, exitCodeGenerator);
}

Inside the Integration tests you can achieved it by adding @DirtiesContext annotation at class level:

  • @DirtiesContext(classMode=ClassMode.AFTER_CLASS) - The associated ApplicationContext will be marked as dirty after the test class.
  • @DirtiesContext(classMode=ClassMode.AFTER_EACH_TEST_METHOD) - The associated ApplicationContext will be marked as dirty after each test method in the class.

i.e.

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {Application.class},
    webEnvironment= SpringBootTest.WebEnvironment.DEFINED_PORT, properties = {"server.port:0"})
@DirtiesContext(classMode= DirtiesContext.ClassMode.AFTER_CLASS)
public class ApplicationIT {
...

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

For SQL Server Management Studio 2008

  1. You need to go C:\Documents and Settings\%username%\Application Data\Microsoft\Microsoft SQL Server\100\Tools\Shell

  2. Delete SqlStudio.bin

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

I found elegant work around for me to remove symbols and continue to keep string as string in follows:

yourstring = yourstring.encode('ascii', 'ignore').decode('ascii')

It's important to notice that using the ignore option is dangerous because it silently drops any unicode(and internationalization) support from the code that uses it, as seen here (convert unicode):

>>> u'City: Malmö'.encode('ascii', 'ignore').decode('ascii')
'City: Malm'

Fastest way to convert an iterator to a list

since python 3.5 you can use * iterable unpacking operator:

user_list = [*your_iterator]

but the pythonic way to do it is:

user_list  = list(your_iterator)

Simulate a specific CURL in PostMan

As per the above answers, it works well.

If we paste curl requests with Authorization data in import, Postman will set all headers automatically. We only just pass row JSON data in the request body if needed or Upload images through form-data in the body.

This is just an example. Your API should be a different one (if your API allows)

curl -X POST 'https://verifyUser.abc.com/api/v1/verification' \
    -H 'secret: secret' \
    -H 'email: [email protected]' \
    -H 'accept: application/json, text/plain, */*' \
    -H 'authorizationtoken: bearer' \
    -F 'referenceFilePath= Add file path' \
    --compressed

Creating an instance of class

  1. Allocates some dynamic memory from the free store, and creates an object in that memory using its default constructor. You never delete it, so the memory is leaked.
  2. Does exactly the same as 1; in the case of user-defined types, the parentheses are optional.
  3. Allocates some automatic memory, and creates an object in that memory using its default constructor. The memory is released automatically when the object goes out of scope.
  4. Similar to 3. Notionally, the named object foo4 is initialised by default-constructing, copying and destroying a temporary object; usually, this is elided giving the same result as 3.
  5. Allocates a dynamic object, then initialises a second by copying the first. Both objects are leaked; and there's no way to delete the first since you don't keep a pointer to it.
  6. Does exactly the same as 5.
  7. Does not compile. Foo foo5 is a declaration, not an expression; function (and constructor) arguments must be expressions.
  8. Creates a temporary object, and initialises a dynamic object by copying it. Only the dynamic object is leaked; the temporary is destroyed automatically at the end of the full expression. Note that you can create the temporary with just Foo() rather than the equivalent Foo::Foo() (or indeed Foo::Foo::Foo::Foo::Foo())

When do I use each?

  1. Don't, unless you like unnecessary decorations on your code.
  2. When you want to create an object that outlives the current scope. Remember to delete it when you've finished with it, and learn how to use smart pointers to control the lifetime more conveniently.
  3. When you want an object that only exists in the current scope.
  4. Don't, unless you think 3 looks boring and what to add some unnecessary decoration.
  5. Don't, because it leaks memory with no chance of recovery.
  6. Don't, because it leaks memory with no chance of recovery.
  7. Don't, because it won't compile
  8. When you want to create a dynamic Bar from a temporary Foo.

hide/show a image in jquery

With image class name:

$('.img_class').hide(); // to hide image
$('.img_class').show(); // to show image

With image Id :

$('#img_id').hide(); // to hide image
$('#img_id').show(); // to show image

jQuery textbox change event doesn't fire until textbox loses focus?

$(this).bind('input propertychange', function() {
        //your code here
    });

This is works for typing, paste, right click mouse paste etc.

How to implement an STL-style iterator and avoid common pitfalls?

The iterator_facade documentation from Boost.Iterator provides what looks like a nice tutorial on implementing iterators for a linked list. Could you use that as a starting point for building a random-access iterator over your container?

If nothing else, you can take a look at the member functions and typedefs provided by iterator_facade and use it as a starting point for building your own.

WPF: ItemsControl with scrollbar (ScrollViewer)

Put your ScrollViewer in a DockPanel and set the DockPanel MaxHeight property

[...]
<DockPanel MaxHeight="700">
  <ScrollViewer VerticalScrollBarVisibility="Auto">
   <ItemsControl ItemSource ="{Binding ...}">
     [...]
   </ItemsControl>
  </ScrollViewer>
</DockPanel>
[...]

How to change values in a tuple?

You can't. If you want to change it, you need to use a list instead of a tuple.

Note that you could instead make a new tuple that has the new value as its first element.

Jenkins: Is there any way to cleanup Jenkins workspace?

IMPORTANT: It is safe to remove the workspace for a given Jenkins job as long as the job is not currently running!

NOTE: I am assuming your $JENKINS_HOME is set to the default: /var/jenkins_home.

Clean up one workspace

rm -rf /var/jenkins_home/workspaces/<workspace>

Clean up all workspaces

rm -rf /var/jenkins_home/workspaces/*

Clean up all workspaces with a few exceptions

This one uses grep to create a whitelist:

ls /var/jenkins_home/workspace \ 
  | grep -v -E '(job-to-skip|another-job-to-skip)$' \
  | xargs -I {} rm -rf /var/jenkins_home/workspace/{}

Clean up 10 largest workspaces

This one uses du and sort to list workspaces in order of largest to smallest. Then, it uses head to grab the first 10:

du -d 1 /var/jenkins_home/workspace \
  | sort -n -r \
  | head -n 10 \
  | xargs -I {} rm -rf /var/jenkins_home/workspace/{}

MSBUILD : error MSB1008: Only one project can be specified

For me adding the path to the solution file in double quotes solved the issue. One of the folders in the path had a blank space in the name and this caused it to consider 2 solution files instead of one. I executed in the following was and it worked.

MSBuild.exe "C:\Folder Name With Space\Project\project.sln"

Update multiple columns in SQL

I did this in MySql and it updated multiple columns in a single record, so try this if you are using MySql as your server:

"UPDATE creditor_tb SET credit_amount='" & CDbl(cur_amount) & "'
                   , totalamount_to_pay='" & current_total & "',   
        WHERE credit_id='" & lbcreditId.Text & "'". 

However, I was coding in vb.net using MySql server, but you can take it to your favorite programming language as far as you are using MySql as your server.

Visual Studio can't build due to rc.exe

This can be caused by a vcxproj that originated in previous versions of Visual Studio OR changing the Platform Toolset in Configuration Properties -> General.

If so, possible Solution:

1) Go to Configuration Properties -> VC++ Directories

2) Select drop down for Executable Directories

3) Select "Inherit from parent or Project Defaults"

MySQL select all rows from last month until (now() - 1 month), for comparative purposes

SELECT *
FROM table
WHERE myDtate BETWEEN now()
    , DATE_SUB(NOW()
    , INTERVAL 1 MONTH)

Check for special characters in string

_x000D_
_x000D_
var format = /[`!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/;
//            ^                                       ^   
document.write(format.test("My @string-with(some%text)") + "<br/>");
document.write(format.test("My string with spaces") + "<br/>");
document.write(format.test("My StringContainingNoSpecialChars"));
_x000D_
_x000D_
_x000D_

How to retrieve Request Payload

Also you can setup extJs writer with encode: true and it will send data regularly (and, hence, you will be able to retrieve data via $_POST and $_GET).

... the values will be sent as part of the request parameters as opposed to a raw post (via docs for encode config of Ext.data.writer.Json)

UPDATE

Also docs say that:

The encode option should only be set to true when a root is defined

So, probably, writer's root config is required.

How to write "Html.BeginForm" in Razor

The following code works fine:

@using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
}

and generates as expected:

<form action="/Upload/Upload" enctype="multipart/form-data" method="post">    
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
</form>

On the other hand if you are writing this code inside the context of other server side construct such as an if or foreach you should remove the @ before the using. For example:

@if (SomeCondition)
{
    using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
    {
        @Html.ValidationSummary(true)
        <fieldset>
            Select a file <input type="file" name="file" />
            <input type="submit" value="Upload" />
        </fieldset>
    }
}

As far as your server side code is concerned, here's how to proceed:

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file) 
{
    if (file != null && file.ContentLength > 0) 
    {
        var fileName = Path.GetFileName(file.FileName);
        var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
        file.SaveAs(path);
    }
    return RedirectToAction("Upload");
}

Numpy, multiply array with scalar

You can multiply numpy arrays by scalars and it just works.

>>> import numpy as np
>>> np.array([1, 2, 3]) * 2
array([2, 4, 6])
>>> np.array([[1, 2, 3], [4, 5, 6]]) * 2
array([[ 2,  4,  6],
       [ 8, 10, 12]])

This is also a very fast and efficient operation. With your example:

>>> a_1 = np.array([1.0, 2.0, 3.0])
>>> a_2 = np.array([[1., 2.], [3., 4.]])
>>> b = 2.0
>>> a_1 * b
array([2., 4., 6.])
>>> a_2 * b
array([[2., 4.],
       [6., 8.]])

How do you install an APK file in the Android emulator?

Let's suppose you have to install Facebook APK on your emulator.

You can use adb to install the APK to the running emulator in OS X like this:

./adb install ~/FBAndroid-2.1.apk

And on Windows, like this:

adb install %HOMEPATH%\FBAndroid-2.1.apk

Once complete, check the apps screen of the emulator to check that the app has been installed correctly. If you need to force the upgrade of this app from a previous version, add the -r flag, like this on OS X:

./adb install -r ~/FBAndroid-2.1.apk

Can Python test the membership of multiple values in a list?

If you want to check all of your input matches,

>>> all(x in ['b', 'a', 'foo', 'bar'] for x in ['a', 'b'])

if you want to check at least one match,

>>> any(x in ['b', 'a', 'foo', 'bar'] for x in ['a', 'b'])

Best way to format if statement with multiple conditions

The second one is a classic example of the Arrow Anti-pattern So I'd avoid it...

If your conditions are too long extract them into methods/properties.

Run git pull over all subdirectories

I use this

for dir in $(find . -name ".git")
do cd ${dir%/*}
    echo $PWD
    git pull
    echo ""
    cd - > /dev/null
done

Github