Programs & Examples On #Orm

Object-relational mapping (ORM) is a technique for mapping object-oriented systems to relational databases.

Doctrine - How to print out the real sql, not just the prepared statement?

You can check the query executed by your app if you log all the queries in mysql:

http://dev.mysql.com/doc/refman/5.1/en/query-log.html

there will be more queries not only the one that you are looking for but you can grep for it.

but usually ->getSql(); works

Edit:

to view all the mysql queries I use

sudo vim /etc/mysql/my.cnf 

and add those 2 lines:

general_log = on
general_log_file = /tmp/mysql.log

and restart mysql

Specifying an Index (Non-Unique Key) Using JPA

With JPA 2.1 you should be able to do it.

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Index;
import javax.persistence.Table;

@Entity
@Table(name = "region",
       indexes = {@Index(name = "my_index_name",  columnList="iso_code", unique = true),
                  @Index(name = "my_index_name2", columnList="name",     unique = false)})
public class Region{

    @Column(name = "iso_code", nullable = false)
    private String isoCode;

    @Column(name = "name", nullable = false)
    private String name;

} 

Update: If you ever need to create and index with two or more columns you may use commas. For example:

@Entity
@Table(name    = "company__activity", 
       indexes = {@Index(name = "i_company_activity", columnList = "activity_id,company_id")})
public class CompanyActivity{

How to select specific columns in laravel eloquent

Get value of one column:

Table_Name::find($id)->column_name;

you can use this method with where clause:

Table_Name::where('id',$id)->first()->column_name;

or use this method for bypass PhpStorm "Method where not found in App\Models":

Table_Name::query()->where('id','=',$id)->first()->column_name;

in query builder:

DB::table('table_names')->find($id)->column_name;

with where cluase:

DB::table('table_names')->where('id',$id)->first()->column_name;

or

DB::table('table_names')->where('id',$id)->first('column_name');

last method result is array

How to fix the Hibernate "object references an unsaved transient instance - save the transient instance before flushing" error

Or, if you want to use minimal "powers" (e.g. if you don't want a cascade delete) to achieve what you want, use

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;

...

@Cascade({CascadeType.SAVE_UPDATE})
private Set<Child> children;

What Java ORM do you prefer, and why?

I had a really good experience with Avaje Ebean when I was writing a medium sized JavaSE application.

It uses standard JPA annotations to define entities, but exposes a much simpler API (No EntityManager or any of that attached/detached entities crap). It also lets you easily use SQL queries or event plain JDBC calls when necessary.

It also has a very nice fluid and type-safe API for queries. You can write things like:

List<Person> boys = Ebean.find(Person.class)
                                  .where()
                                       .eq("gender", "M")
                                       .le("age", 18)
                                  .orderBy("firstName")
                                  .findList();

What is the difference between persist() and merge() in JPA and Hibernate?

JPA specification contains a very precise description of semantics of these operations, better than in javadoc:

The semantics of the persist operation, applied to an entity X are as follows:

  • If X is a new entity, it becomes managed. The entity X will be entered into the database at or before transaction commit or as a result of the flush operation.

  • If X is a preexisting managed entity, it is ignored by the persist operation. However, the persist operation is cascaded to entities referenced by X, if the relationships from X to these other entities are annotated with the cascade=PERSIST or cascade=ALL annotation element value or specified with the equivalent XML descriptor element.

  • If X is a removed entity, it becomes managed.

  • If X is a detached object, the EntityExistsException may be thrown when the persist operation is invoked, or the EntityExistsException or another PersistenceException may be thrown at flush or commit time.

  • For all entities Y referenced by a relationship from X, if the relationship to Y has been annotated with the cascade element value cascade=PERSIST or cascade=ALL, the persist operation is applied to Y.


The semantics of the merge operation applied to an entity X are as follows:

  • If X is a detached entity, the state of X is copied onto a pre-existing managed entity instance X' of the same identity or a new managed copy X' of X is created.

  • If X is a new entity instance, a new managed entity instance X' is created and the state of X is copied into the new managed entity instance X'.

  • If X is a removed entity instance, an IllegalArgumentException will be thrown by the merge operation (or the transaction commit will fail).

  • If X is a managed entity, it is ignored by the merge operation, however, the merge operation is cascaded to entities referenced by relationships from X if these relationships have been annotated with the cascade element value cascade=MERGE or cascade=ALL annotation.

  • For all entities Y referenced by relationships from X having the cascade element value cascade=MERGE or cascade=ALL, Y is merged recursively as Y'. For all such Y referenced by X, X' is set to reference Y'. (Note that if X is managed then X is the same object as X'.)

  • If X is an entity merged to X', with a reference to another entity Y, where cascade=MERGE or cascade=ALL is not specified, then navigation of the same association from X' yields a reference to a managed object Y' with the same persistent identity as Y.

What is Persistence Context?

While @pritam kumar gives a good overview the 5th point is not true.

Persistence Context can be either Transaction Scoped-- the Persistence Context 'lives' for the length of the transaction, or Extended-- the Persistence Context spans multiple transactions.

https://blogs.oracle.com/carolmcdonald/entry/jpa_caching

JPA's EntityManager and Hibernate's Session offer an extended Persistence Context.

How to map a composite key with JPA and Hibernate?

The primary key class must define equals and hashCode methods

  1. When implementing equals you should use instanceof to allow comparing with subclasses. If Hibernate lazy loads a one to one or many to one relation, you will have a proxy for the class instead of the plain class. A proxy is a subclass. Comparing the class names would fail.
    More technically: You should follow the Liskows Substitution Principle and ignore symmetricity.
  2. The next pitfall is using something like name.equals(that.name) instead of name.equals(that.getName()). The first will fail, if that is a proxy.

http://www.laliluna.de/jpa-hibernate-guide/ch06s06.html

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing

Instead of passing reference object passed the saved object, below is explanation which solve my issue:

//wrong
entityManager.persist(role);
user.setRole(role);
entityManager.persist(user)

//right
Role savedEntity= entityManager.persist(role);
user.setRole(savedEntity);
entityManager.persist(user)

How to auto generate migrations with Sequelize CLI from Sequelize models?

You cannot create migration scripts for existing models.

Resources:

If going the classic way, you'll have to recreate the models via the CLI:

sequelize model:create --name MyUser --attributes first_name:string,last_name:string,bio:text

It will generate these files:

models/myuser.js:

_x000D_
_x000D_
"use strict";_x000D_
module.exports = function(sequelize, DataTypes) {_x000D_
  var MyUser = sequelize.define("MyUser", {_x000D_
    first_name: DataTypes.STRING,_x000D_
    last_name: DataTypes.STRING,_x000D_
    bio: DataTypes.TEXT_x000D_
  }, {_x000D_
    classMethods: {_x000D_
      associate: function(models) {_x000D_
        // associations can be defined here_x000D_
      }_x000D_
    }_x000D_
  });_x000D_
  return MyUser;_x000D_
};
_x000D_
_x000D_
_x000D_

migrations/20150210104840-create-my-user.js:

_x000D_
_x000D_
"use strict";_x000D_
module.exports = {_x000D_
  up: function(migration, DataTypes, done) {_x000D_
    migration.createTable("MyUsers", {_x000D_
      id: {_x000D_
        allowNull: false,_x000D_
        autoIncrement: true,_x000D_
        primaryKey: true,_x000D_
        type: DataTypes.INTEGER_x000D_
      },_x000D_
      first_name: {_x000D_
        type: DataTypes.STRING_x000D_
      },_x000D_
      last_name: {_x000D_
        type: DataTypes.STRING_x000D_
      },_x000D_
      bio: {_x000D_
        type: DataTypes.TEXT_x000D_
      },_x000D_
      createdAt: {_x000D_
        allowNull: false,_x000D_
        type: DataTypes.DATE_x000D_
      },_x000D_
      updatedAt: {_x000D_
        allowNull: false,_x000D_
        type: DataTypes.DATE_x000D_
      }_x000D_
    }).done(done);_x000D_
  },_x000D_
  down: function(migration, DataTypes, done) {_x000D_
    migration.dropTable("MyUsers").done(done);_x000D_
  }_x000D_
};
_x000D_
_x000D_
_x000D_

javax.persistence.PersistenceException: No Persistence provider for EntityManager named customerManager

my experience tells me that missing persistence.xml,will generate the same exception too.

i caught the same error msg today when i tried to run a jar package packed by ant.

when i used jar tvf to check the content of the jar file, i realized that "ant" forgot to pack the persistnece.xml for me.

after I manually repacked the jar file ,the error msg disappered.

so i believe maybe you should try simplely putting META-INF under src directory and placing your persistence.xml there.

JPA - Persisting a One to Many relationship

One way to do that is to set the cascade option on you "One" side of relationship:

class Employee {
   // 

   @OneToMany(cascade = {CascadeType.PERSIST})
   private Set<Vehicles> vehicles = new HashSet<Vehicles>();

   //
}

by this, when you call

Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);

it will save the vehicles too.

Using Eloquent ORM in Laravel to perform search of database using LIKE

If you do not like double quotes like me, this will work for you with single quotes:

$value = Input::get('q');
$books = Book::where('name', 'LIKE', '%' . $value . '%')->limit(25)->get();

return view('pages/search/index', compact('books'));

What's the best strategy for unit-testing database-driven applications?

For JDBC based project (directly or indirectly, e.g. JPA, EJB, ...) you can mockup not the entire database (in such case it would be better to use a test db on a real RDBMS), but only mockup at JDBC level.

Advantage is abstraction which comes with that way, as JDBC data (result set, update count, warning, ...) are the same whatever is the backend: your prod db, a test db, or just some mockup data provided for each test case.

With JDBC connection mocked up for each case there is no need to manage test db (cleanup, only one test at time, reload fixtures, ...). Every mockup connection is isolated and there is no need to clean up. Only minimal required fixtures are provided in each test case to mock up JDBC exchange, which help to avoid complexity of managing a whole test db.

Acolyte is my framework which includes a JDBC driver and utility for this kind of mockup: http://acolyte.eu.org .

Good PHP ORM Library?

Try PHP ADOdb.

I can't say it's the best, because I haven't used the others. But it's fast, it supports Memcached and caching.

And it's waaaay faster than Zend Framework's DB/Select.

Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?

With

with() is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.

Example:

User > hasMany > Post

$users = User::with('posts')->get();
foreach($users as $user){
    $users->posts; // posts is already loaded and no additional DB query is run
}

Has

has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.

Example:

User > hasMany > Post

$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection

WhereHas

whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.

Example:

User > hasMany > Post

$users = User::whereHas('posts', function($q){
    $q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned

Efficiently updating database using SQLAlchemy ORM

There are several ways to UPDATE using sqlalchemy

1) for c in session.query(Stuff).all():
       c.foo += 1
   session.commit()

2) session.query().\
       update({"foo": (Stuff.foo + 1)})
   session.commit()

3) conn = engine.connect()
   stmt = Stuff.update().\
       values(Stuff.foo = (Stuff.foo + 1))
   conn.execute(stmt)

How to make join queries using Sequelize on Node.js

While the accepted answer isn't technically wrong, it doesn't answer the original question nor the follow up question in the comments, which was what I came here looking for. But I figured it out, so here goes.

If you want to find all Posts that have Users (and only the ones that have users) where the SQL would look like this:

SELECT * FROM posts INNER JOIN users ON posts.user_id = users.id

Which is semantically the same thing as the OP's original SQL:

SELECT * FROM posts, users WHERE posts.user_id = users.id

then this is what you want:

Posts.findAll({
  include: [{
    model: User,
    required: true
   }]
}).then(posts => {
  /* ... */
});

Setting required to true is the key to producing an inner join. If you want a left outer join (where you get all Posts, regardless of whether there's a user linked) then change required to false, or leave it off since that's the default:

Posts.findAll({
  include: [{
    model: User,
//  required: false
   }]
}).then(posts => {
  /* ... */
});

If you want to find all Posts belonging to users whose birth year is in 1984, you'd want:

Posts.findAll({
  include: [{
    model: User,
    where: {year_birth: 1984}
   }]
}).then(posts => {
  /* ... */
});

Note that required is true by default as soon as you add a where clause in.

If you want all Posts, regardless of whether there's a user attached but if there is a user then only the ones born in 1984, then add the required field back in:

Posts.findAll({
  include: [{
    model: User,
    where: {year_birth: 1984}
    required: false,
   }]
}).then(posts => {
  /* ... */
});

If you want all Posts where the name is "Sunshine" and only if it belongs to a user that was born in 1984, you'd do this:

Posts.findAll({
  where: {name: "Sunshine"},
  include: [{
    model: User,
    where: {year_birth: 1984}
   }]
}).then(posts => {
  /* ... */
});

If you want all Posts where the name is "Sunshine" and only if it belongs to a user that was born in the same year that matches the post_year attribute on the post, you'd do this:

Posts.findAll({
  where: {name: "Sunshine"},
  include: [{
    model: User,
    where: ["year_birth = post_year"]
   }]
}).then(posts => {
  /* ... */
});

I know, it doesn't make sense that somebody would make a post the year they were born, but it's just an example - go with it. :)

I figured this out (mostly) from this doc:

Map enum in JPA with fixed values?

From JPA 2.1 you can use AttributeConverter.

Create an enumerated class like so:

public enum NodeType {

    ROOT("root-node"),
    BRANCH("branch-node"),
    LEAF("leaf-node");

    private final String code;

    private NodeType(String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }
}

And create a converter like this:

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

@Converter(autoApply = true)
public class NodeTypeConverter implements AttributeConverter<NodeType, String> {

    @Override
    public String convertToDatabaseColumn(NodeType nodeType) {
        return nodeType.getCode();
    }

    @Override
    public NodeType convertToEntityAttribute(String dbData) {
        for (NodeType nodeType : NodeType.values()) {
            if (nodeType.getCode().equals(dbData)) {
                return nodeType;
            }
        }

        throw new IllegalArgumentException("Unknown database value:" + dbData);
    }
}

On the entity you just need:

@Column(name = "node_type_code")

You luck with @Converter(autoApply = true) may vary by container but tested to work on Wildfly 8.1.0. If it doesn't work you can add @Convert(converter = NodeTypeConverter.class) on the entity class column.

Location of hibernate.cfg.xml in project?

Somehow placing under "src" folder didn't work for me.

Instead placing cfg.xml as below:

[Project Folder]\src\main\resources\hibernate.cfg.xml

worked. Using this code

new Configuration().configure().buildSessionFactory().openSession();

in a file under

    [Project Folder]/src/main/java/com/abc/xyz/filename.java

In addition have this piece of code in hibernate.cfg.xml

<mapping resource="hibernate/Address.hbm.xml" />
<mapping resource="hibernate/Person.hbm.xml" />

Placed the above hbm.xml files under:

EDIT:

[Project Folder]/src/main/resources/hibernate/Address.hbm.xml
[Project Folder]/src/main/resources/hibernate/Person.hbm.xml

Above structure worked.

Get the last insert id with doctrine 2?

If you're not using entities but Native SQL as shown here then you might want to get the last inserted id as shown below:

$entityManager->getConnection()->lastInsertId()

For databases with sequences such as PostgreSQL please note that you can provide the sequence name as the first parameter of the lastInsertId method.

$entityManager->getConnection()->lastInsertId($seqName = 'my_sequence')

For more information take a look at the code on GitHub here and here.

Which ORM should I use for Node.js and MySQL?

I would choose Sequelize because of it's excellent documentation. It's just a honest opinion (I never really used MySQL with Node that much).

What's the difference between JPA and Hibernate?

JPA is the interface while Hibernate is the implementation.

Traditionally there have been multiple Java ORM solutions:

each implementation defining its own mapping definition or client API. The JPA expert group gathered the best of all these tools and so they created the Java Persistence API standard.

A standard persistence API is very convenient from a client point of view, making it relatively easy to switch one implementation with the other (although in practice it's not that simple because on large projects you'll have to use specific non-standard features anyway).

The standard JPA has pushed Java ORM competition to a new level and this can only lead to better implementations.

As explained in my book, High-Performance Java Persistence, Hibernate offers features that are not yet supported by JPA:

These extra features allow Hibernate to address many persistence requirements demanded by large enterprise applications.

How to persist a property of type List<String> in JPA?

This answer was made pre-JPA2 implementations, if you're using JPA2, see the ElementCollection answer above:

Lists of objects inside a model object are generally considered "OneToMany" relationships with another object. However, a String is not (by itself) an allowable client of a One-to-Many relationship, as it doesn't have an ID.

So, you should convert your list of Strings to a list of Argument-class JPA objects containing an ID and a String. You could potentially use the String as the ID, which would save a little space in your table both from removing the ID field and by consolidating rows where the Strings are equal, but you would lose the ability to order the arguments back into their original order (as you didn't store any ordering information).

Alternatively, you could convert your list to @Transient and add another field (argStorage) to your class that is either a VARCHAR() or a CLOB. You'll then need to add 3 functions: 2 of them are the same and should convert your list of Strings into a single String (in argStorage) delimited in a fashion that you can easily separate them. Annotate these two functions (that each do the same thing) with @PrePersist and @PreUpdate. Finally, add the third function that splits the argStorage into the list of Strings again and annotate it @PostLoad. This will keep your CLOB updated with the strings whenever you go to store the Command, and keep the argStorage field updated before you store it to the DB.

I still suggest doing the first case. It's good practice for real relationships later.

How to annotate MYSQL autoincrement field with JPA annotations

For anyone reading this who is using EclipseLink for JPA 2.0, here are the two annotations I had to use to get JPA to persist data, where "MySequenceGenerator" is whatever name you want to give the generator, "myschema" is the name of the schema in your database that contains the sequence object, and "mysequence" is the name of the sequence object in the database.

@GeneratedValue(strategy= GenerationType.SEQUENCE, generator="MySequenceGenerator")
@SequenceGenerator(allocationSize=1, schema="myschema",  name="MySequenceGenerator", sequenceName = "mysequence")

For those using EclipseLink (and possibly other JPA providers), it is CRITICAL that you set the allocationSize attribute to match the INCREMENT value defined for your sequence in the database. If you don't, you'll get a generic persistence failure, and waste a good deal of time trying to track it down, like I did. Here is the reference page that helped me overcome this challenge:

http://wiki.eclipse.org/EclipseLink/Examples/JPA/PrimaryKey#Using_Sequence_Objects

Also, to give context, here is what we're using:

Java 7 Glassfish 3.1 PostgreSQL 9.1 PrimeFaces 3.2/JSF 2.1

Also, for laziness' sake, I built this in Netbeans with the wizards for generating Entities from DB, Controllers from Entities, and JSF from Entities, and the wizards (obviously) do not know how to deal with sequence-based ID columns, so you'll have to manually add these annotations.

Entity Framework .Remove() vs. .DeleteObject()

If you really want to use Deleted, you'd have to make your foreign keys nullable, but then you'd end up with orphaned records (which is one of the main reasons you shouldn't be doing that in the first place). So just use Remove()

ObjectContext.DeleteObject(entity) marks the entity as Deleted in the context. (It's EntityState is Deleted after that.) If you call SaveChanges afterwards EF sends a SQL DELETE statement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.

EntityCollection.Remove(childEntity) marks the relationship between parent and childEntity as Deleted. If the childEntity itself is deleted from the database and what exactly happens when you call SaveChanges depends on the kind of relationship between the two:

A thing worth noting is that setting .State = EntityState.Deleted does not trigger automatically detected change. (archive)

How to Make Laravel Eloquent "IN" Query?

Here is how you do in Eloquent

$users = User::whereIn('id', array(1, 2, 3))->get();

And if you are using Query builder then :

$users = DB::table('users')->whereIn('id', array(1, 2, 3))->get();

What is referencedColumnName used for in JPA?

It is there to specify another column as the default id column of the other table, e.g. consider the following

TableA
  id int identity
  tableb_key varchar


TableB
  id int identity
  key varchar unique

// in class for TableA
@JoinColumn(name="tableb_key", referencedColumnName="key")

Select the first 10 rows - Laravel Eloquent

Another way to do it is using a limit method:

Listing::limit(10)->get();

This can be useful if you're not trying to implement pagination, but for example, return 10 random rows from a table:

Listing::inRandomOrder()->limit(10)->get();

Getting Database connection in pure JPA setup

Below is the code that worked for me. We use jpa 1.0, Apache openjpa implementation.

import java.sql.Connection;
import org.apache.openjpa.persistence.OpenJPAEntityManager;
import org.apache.openjpa.persistence.OpenJPAPersistence;

public final class MsSqlDaoFactory {


       public static final Connection getConnection(final EntityManager entityManager) {
              OpenJPAEntityManager openJPAEntityManager = OpenJPAPersistence.cast(entityManager);
              Connection connection = (Connection) openJPAEntityManager.getConnection();
              return connection;

        }

}

No operator matches the given name and argument type(s). You might need to add explicit type casts. -- Netbeans, Postgresql 8.4 and Glassfish

In my case, I used a keyword as a column name, which resulted in ERROR: operator does not exist: name = bigint

The solution was to use double quotes around the column name.

How To Define a JPA Repository Query with a Join

You are experiencing this issue for two reasons.

  • The JPQL Query is not valid.
  • You have not created an association between your entities that the underlying JPQL query can utilize.

When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)

User.java

@Entity
@Table(name="user")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="iduser")
    private Long idUser;

    @Column(name="user_name")
    private String userName;

    @OneToOne()
    @JoinColumn(name="idarea")
    private Area area;

    public Long getIdUser() {
        return idUser;
    }

    public void setIdUser(Long idUser) {
        this.idUser = idUser;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Area getArea() {
        return area;
    }

    public void setArea(Area area) {
        this.area = area;
    }
}

Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:

@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")

While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.

Area.java

@Entity
@Table(name = "area")
public class Area {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="idarea")
    private Long idArea;

    @Column(name="area_name")
    private String areaName;

    @OneToOne(fetch=FetchType.LAZY, mappedBy="area")
    private User user;

    public Long getIdArea() {
        return idArea;
    }

    public void setIdArea(Long idArea) {
        this.idArea = idArea;
    }

    public String getAreaName() {
        return areaName;
    }

    public void setAreaName(String areaName) {
        this.areaName = areaName;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

Infinite Recursion with Jackson JSON and Hibernate JPA issue

I'm a late comer and it's such a long thread already. But I spent a couple of hours trying to figure this out too, and would like to give my case as another example.

I tried both JsonIgnore, JsonIgnoreProperties and BackReference solutions, but strangely enough it was like they weren't picked up.

I used Lombok and thought that maybe it interferes, since it creates constructors and overrides toString (saw toString in stackoverflowerror stack).

Finally it wasn't Lombok's fault - I used automatic NetBeans generation of JPA entities from database tables, without giving it much thought - well, and one of the annotations that were added to the generated classes was @XmlRootElement. Once I removed it everything started working. Oh well.

Get the Query Executed in Laravel 3/4

In Laravel 8.x you can listen to the event by registering your query listener in a service provider as documented in laravel.com website.

//header
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

public function boot()
{
   
  DB::listen(function ($query) {            
   Log::debug("SQL : " . $query->sql);
  });

}

You can then see all the queries in the laravel.log file inside storage\logs\laravel.log

What's the use of session.flush() in Hibernate

Flushing the session forces Hibernate to synchronize the in-memory state of the Session with the database (i.e. to write changes to the database). By default, Hibernate will flush changes automatically for you:

  • before some query executions
  • when a transaction is committed

Allowing to explicitly flush the Session gives finer control that may be required in some circumstances (to get an ID assigned, to control the size of the Session,...).

javax.naming.NameNotFoundException: Name is not bound in this Context. Unable to find

Ok found out the Tomcat file server.xml must be configured as well for the data source to work. So just add:

<Resource 
auth="Container" 
driverClassName="org.apache.derby.jdbc.EmbeddedDriver" 
maxActive="20" 
maxIdle="10" 
maxWait="-1" 
name="ds/flexeraDS" 
type="javax.sql.DataSource" 
url="jdbc:derby:flexeraDB;create=true" 
  />

What is the "N+1 selects problem" in ORM (Object-Relational Mapping)?

One millionaire has N cars. You want to get all (4) wheels.

One (1) query loads all the cars, but for each (N) car a separate query is submitted for loading wheels.

Costs:

Assume indexes fit into ram.

1 + N query parsing and planing + index searching AND 1 + N + (N * 4) plate access for loading payload.

Assume indexes don't fit into ram.

Additional costs in worst case 1 + N plate accesses for loading index.

Summary

Bottle neck is plate access (ca. 70 times per second random access on hdd) An eager join select would also access the plate 1 + N + (N * 4) times for payload. So if the indexes fit into ram - no problem, its fast enough because only ram operations involved.

Hibernate Annotations - Which is better, field or property access?

I prefer fields, but I've run into one situation that seems to force me to place the annotations on getters.

With the Hibernate JPA implementation, @Embedded doesn't seem to work on fields. So that has to go on the getter. And once you put that on the getter, then the various @Column annotations have to go on the getters too. (I think Hibernate doesn't want mixing fields and getters here.) And once you're putting @Column on getters in one class, it probably makes sense to do that throughout.

JPA CascadeType.ALL does not delete orphans

According to Java Persistence with Hibernate, cascade orphan delete is not available as a JPA annotation.

It is also not supported in JPA XML.

The EntityManager is closed

Same problem, solved with a simple code refactoring. The problem is sometime present when a required field is null, before do anithing, try to refactor your code. A better workflow can solve the problem.

Error : java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V

There is a lot of incompatibility between different versions of cglib and lots of poor advice that can be googled on this subject (use ancient versions of cglib-nodeb, etc). After wrestling with this nonsense for 3 days with an ancient version of Spring (2.5.6)I have discovered:

  • if Spring is throwing exceptions about NoSuchMethodError based on Enhancer from cglib missing setInterceptDuringConstruction(boolean), check your dependencies in maven (Dependency Hierarchy tab should list all the versions of cglib your project is polluted by). You probably have a dependency that is bringing in a pre-2.2 version of cglib, which Spring Cglib2AopProxy will grab Enhancer from to do the proxying. Add 2.2+ version to your dependencies but make sure to put in exclusions for these other versions. If you don't it will just keep blowing up.
  • Make sure you have a high enough version of cglib in the current project's maven dependencies but beware of picking too high a version because then you'll get IncompatibleClassChangeError(s) instead.
  • Verify that your pom changes have made it into the project correctly by doing a maven update on the project in question and then looking at Project > preferences > Java Build Path > Libraries > Maven Dependencies. If you see the wrong cglib versions in there, time to edit the pom again.

What's the difference between @JoinColumn and mappedBy when using a JPA @OneToMany association

The annotation @JoinColumn indicates that this entity is the owner of the relationship (that is: the corresponding table has a column with a foreign key to the referenced table), whereas the attribute mappedBy indicates that the entity in this side is the inverse of the relationship, and the owner resides in the "other" entity. This also means that you can access the other table from the class which you've annotated with "mappedBy" (fully bidirectional relationship).

In particular, for the code in the question the correct annotations would look like this:

@Entity
public class Company {
    @OneToMany(mappedBy = "company",
               orphanRemoval = true,
               fetch = FetchType.LAZY,
               cascade = CascadeType.ALL)
    private List<Branch> branches;
}

@Entity
public class Branch {
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "companyId")
    private Company company;
}

What is an ORM, how does it work, and how should I use one?

Can anyone give me a brief explanation...

Sure.

ORM stands for "Object to Relational Mapping" where

  • The Object part is the one you use with your programming language ( python in this case )

  • The Relational part is a Relational Database Manager System ( A database that is ) there are other types of databases but the most popular is relational ( you know tables, columns, pk fk etc eg Oracle MySQL, MS-SQL )

  • And finally the Mapping part is where you do a bridge between your objects and your tables.

In applications where you don't use a ORM framework you do this by hand. Using an ORM framework would allow you do reduce the boilerplate needed to create the solution.

So let's say you have this object.

 class Employee:
      def __init__( self, name ): 
          self.__name = name

       def getName( self ):
           return self.__name

       #etc.

and the table

   create table employee(
          name varcar(10),
          -- etc  
    )

Using an ORM framework would allow you to map that object with a db record automagically and write something like:

   emp = Employee("Ryan")

   orm.save( emp )

And have the employee inserted into the DB.

Oops it was not that brief but I hope it is simple enough to catch other articles you read.

How to select a record and update it, with a single queryset in Django?

Use the queryset object update method:

MyModel.objects.filter(pk=some_value).update(field1='some value')

How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session

There are several good answers here that handle this error in a broad scope. I ran into a specific situation with Spring Security which had a quick, although probably not optimal, fix.

During user authorization (immediately after logging in and passing authentication) I was testing a user entity for a specific authority in a custom class that extends SimpleUrlAuthenticationSuccessHandler.

My user entity implements UserDetails and has a Set of lazy loaded Roles which threw the "org.hibernate.LazyInitializationException - could not initialize proxy - no Session" exception. Changing that Set from "fetch=FetchType.LAZY" to "fetch=FetchType.EAGER" fixed this for me.

What is the difference between Unidirectional and Bidirectional JPA and Hibernate associations?

I'm not 100% sure this is the only difference, but it is the main difference. It is also recommended to have bi-directional associations by the Hibernate docs:

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/best-practices.html

Specifically:

Prefer bidirectional associations: Unidirectional associations are more difficult to query. In a large application, almost all associations must be navigable in both directions in queries.

I personally have a slight problem with this blanket recommendation -- it seems to me there are cases where a child doesn't have any practical reason to know about its parent (e.g., why does an order item need to know about the order it is associated with?), but I do see value in it a reasonable portion of the time as well. And since the bi-directionality doesn't really hurt anything, I don't find it too objectionable to adhere to.

Hibernate: flush() and commit()

flush() will synchronize your database with the current state of object/objects held in the memory but it does not commit the transaction. So, if you get any exception after flush() is called, then the transaction will be rolled back. You can synchronize your database with small chunks of data using flush() instead of committing a large data at once using commit() and face the risk of getting an OutOfMemoryException.

commit() will make data stored in the database permanent. There is no way you can rollback your transaction once the commit() succeeds.

How to set a default entity property value with Hibernate

If you want to set default value in terms of database, just set @Column( columnDefinition = "int default 1")

But if what you intend is to set a default value in your java app you can set it on your class attribute like this: private Integer attribute = 1;

Entity Framework Code First - two Foreign Keys from same table

InverseProperty in EF Core makes the solution easy and clean.

InverseProperty

So the desired solution would be:

public class Team
{
    [Key]
    public int TeamId { get; set;} 
    public string Name { get; set; }

    [InverseProperty(nameof(Match.HomeTeam))]
    public ICollection<Match> HomeMatches{ get; set; }

    [InverseProperty(nameof(Match.GuestTeam))]
    public ICollection<Match> AwayMatches{ get; set; }
}


public class Match
{
    [Key]
    public int MatchId { get; set; }

    [ForeignKey(nameof(HomeTeam)), Column(Order = 0)]
    public int HomeTeamId { get; set; }
    [ForeignKey(nameof(GuestTeam)), Column(Order = 1)]
    public int GuestTeamId { get; set; }

    public float HomePoints { get; set; }
    public float GuestPoints { get; set; }
    public DateTime Date { get; set; }

    public Team HomeTeam { get; set; }
    public Team GuestTeam { get; set; }
}

mappedBy reference an unknown target entity property

The mappedBy attribute is referencing customer while the property is mCustomer, hence the error message. So either change your mapping into:

/** The collection of stores. */
@OneToMany(mappedBy = "mCustomer", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Collection<Store> stores;

Or change the entity property into customer (which is what I would do).

The mappedBy reference indicates "Go look over on the bean property named 'customer' on the thing I have a collection of to find the configuration."

how to configure hibernate config file for sql server

Keep the jar files under web-inf lib incase you included jar and it is not able to identify .

It worked in my case where everything was ok but it was not able to load the driver class.

org.hibernate.MappingException: Could not determine type for: java.util.List, at table: College, for columns: [org.hibernate.mapping.Column(students)]

@Access(AccessType.PROPERTY)
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name="userId")
public User getUser() {
    return user;
}

I have the same problems, I solved it by add @Access(AccessType.PROPERTY)

Entity Framework is Too Slow. What are my options?

The fact of the matter is that products such as Entity Framework will ALWAYS be slow and inefficient, because they are executing lot more code.

I also find it silly that people are suggesting that one should optimize LINQ queries, look at the SQL generated, use debuggers, pre-compile, take many extra steps, etc. i.e. waste a lot of time. No one says - Simplify! Everyone wants to comlicate things further by taking even more steps (wasting time).

A common sense approach would be not to use EF or LINQ at all. Use plain SQL. There is nothing wrong with it. Just because there is herd mentality among programmers and they feel the urge to use every single new product out there, does not mean that it is good or it will work. Most programmers think if they incorporate every new piece of code released by a large company, it is making them a smarter programmer; not true at all. Smart programming is mostly about how to do more with less headaches, uncertainties, and in the least amount of time. Remember - Time! That is the most important element, so try to find ways not to waste it on solving problems in bad/bloated code written simply to conform with some strange so called 'patterns'

Relax, enjoy life, take a break from coding and stop using extra features, code, products, 'patterns'. Life is short and the life of your code is even shorter, and it is certainly not rocket science. Remove layers such as LINQ, EF and others, and your code will run efficiently, will scale, and yes, it will still be easy to maintain. Too much abstraction is a bad 'pattern'.

And that is the solution to your problem.

How to query between two dates using Laravel and Eloquent?

The following should work:

$now = date('Y-m-d');
$reservations = Reservation::where('reservation_from', '>=', $now)
                           ->where('reservation_from', '<=', $to)
                           ->get();

org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person]

What do we mean by org.hibernate.exception.SQLGrammarException?

Implementation of JDBCException indicating that the SQL sent to the database server was invalid (syntax error, invalid object references, etc).

and in my words there is a kind of Grammar mistake inside of your hibernate.cfg.xml configuration file,

it happens when you write wrong schema defination property name inside, like below example:

<property name="hibernate.connection.hbm2ddl.auto">create</property>

which supposed to be like:

<property name="hibernate.hbm2ddl.auto">create</property>

Bulk insert with SQLAlchemy ORM

This is a way:

values = [1, 2, 3]
Foo.__table__.insert().execute([{'bar': x} for x in values])

This will insert like this:

INSERT INTO `foo` (`bar`) VALUES (1), (2), (3)

Reference: The SQLAlchemy FAQ includes benchmarks for various commit methods.

What is lazy loading in Hibernate?

Lazy loading allows you to defer the association retrieval or to have a better control over the fetching strategy.

When you use EAGER loading, you define a global fetch plan which cannot be overridden at query time, meaning you are limited to a decision you took while designing your entity model. The EAGER fetching is a code smell, because the fetching strategy is a query-time policy and it might differ from a business use case to another.

The fetching strategy is a very important aspect, as too much EAGER fetching can cause serious performance related issues.

Doctrine 2 ArrayCollection filter method

The Collection#filter method really does eager load all members. Filtering at the SQL level will be added in doctrine 2.3.

JPA CriteriaBuilder - How to use "IN" comparison operator

If I understand well, you want to Join ScheduleRequest with User and apply the in clause to the userName property of the entity User.

I'd need to work a bit on this schema. But you can try with this trick, that is much more readable than the code you posted, and avoids the Join part (because it handles the Join logic outside the Criteria Query).

List<String> myList = new ArrayList<String> ();
for (User u : usersList) {
    myList.add(u.getUsername());
}
Expression<String> exp = scheduleRequest.get("createdBy");
Predicate predicate = exp.in(myList);
criteria.where(predicate);

In order to write more type-safe code you could also use Metamodel by replacing this line:

Expression<String> exp = scheduleRequest.get("createdBy");

with this:

Expression<String> exp = scheduleRequest.get(ScheduleRequest_.createdBy);

If it works, then you may try to add the Join logic into the Criteria Query. But right now I can't test it, so I prefer to see if somebody else wants to try.


Not a perfect answer though may be code snippets might help.

public <T> List<T> findListWhereInCondition(Class<T> clazz,
            String conditionColumnName, Serializable... conditionColumnValues) {
        QueryBuilder<T> queryBuilder = new QueryBuilder<T>(clazz);
        addWhereInClause(queryBuilder, conditionColumnName,
                conditionColumnValues);
        queryBuilder.select();
        return queryBuilder.getResultList();

    }


private <T> void addWhereInClause(QueryBuilder<T> queryBuilder,
            String conditionColumnName, Serializable... conditionColumnValues) {

        Path<Object> path = queryBuilder.root.get(conditionColumnName);
        In<Object> in = queryBuilder.criteriaBuilder.in(path);
        for (Serializable conditionColumnValue : conditionColumnValues) {
            in.value(conditionColumnValue);
        }
        queryBuilder.criteriaQuery.where(in);

    }

JPQL IN clause: Java-Arrays (or Lists, Sets...)?

The oracle limit is 1000 parameters. The issue has been resolved by hibernate in version 4.1.7 although by splitting the passed parameter list in sets of 500 see JIRA HHH-1123

How to map calculated properties with JPA and Hibernate

JPA doesn't offer any support for derived property so you'll have to use a provider specific extension. As you mentioned, @Formula is perfect for this when using Hibernate. You can use an SQL fragment:

@Formula("PRICE*1.155")
private float finalPrice;

Or even complex queries on other tables:

@Formula("(select min(o.creation_date) from Orders o where o.customer_id = id)")
private Date firstOrderDate;

Where id is the id of the current entity.

The following blog post is worth the read: Hibernate Derived Properties - Performance and Portability.

Without more details, I can't give a more precise answer but the above link should be helpful.

See also:

How to print a query string with parameter values when using Hibernate

<appender name="console" class="org.apache.log4j.ConsoleAppender">
    <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern" 
      value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
    </layout>
</appender>

<logger name="org.hibernate" additivity="false">
    <level value="INFO" />
    <appender-ref ref="console" />
</logger>

<logger name="org.hibernate.type" additivity="false">
    <level value="TRACE" />
    <appender-ref ref="console" />
</logger>

Hibernate throws org.hibernate.AnnotationException: No identifier specified for entity: com..domain.idea.MAE_MFEView

I think this issue following model class wrong import.

    import org.springframework.data.annotation.Id;

Normally, it should be:

    import javax.persistence.Id;

Get Specific Columns Using “With()” Function in Laravel Eloquent

So, similar to other solutions here is mine:

// For example you have this relation defined with "user()" method
public function user()
{
    return $this->belongsTo('User');
}
// Just make another one defined with "user_frontend()" method
public function user_frontend()
{
    return $this->belongsTo('User')->select(array('id', 'username'));
}

// Then use it later like this
$thing = new Thing();
$thing->with('user_frontend');

// This way, you get only id and username, 
// and if you want all fields you can do this

$thing = new Thing();
$thing->with('user');

Doctrine2: Best way to handle many-to-many with extra columns in reference table

The solution is in the documentation of Doctrine. In the FAQ you can see this :

http://docs.doctrine-project.org/en/2.1/reference/faq.html#how-can-i-add-columns-to-a-many-to-many-table

And the tutorial is here :

http://docs.doctrine-project.org/en/2.1/tutorials/composite-primary-keys.html

So you do not anymore do a manyToMany but you have to create an extra Entity and put manyToOne to your two entities.

ADD for @f00bar comment :

it's simple, you have just to to do something like this :

Article  1--N  ArticleTag  N--1  Tag

So you create an entity ArticleTag

ArticleTag:
  type: entity
  id:
    id:
      type: integer
      generator:
        strategy: AUTO
  manyToOne:
    article:
      targetEntity: Article
      inversedBy: articleTags
  fields: 
    # your extra fields here
  manyToOne:
    tag:
      targetEntity: Tag
      inversedBy: articleTags

I hope it helps

What are some good Python ORM solutions?

SQLAlchemy's declarative extension, which is becoming standard in 0.5, provides an all in one interface very much like that of Django or Storm. It also integrates seamlessly with classes/tables configured using the datamapper style:

Base = declarative_base()

class Foo(Base):
    __tablename__ = 'foos'
    id = Column(Integer, primary_key=True)

class Thing(Base):
    __tablename__ = 'things'

    id = Column(Integer, primary_key=True)
    name = Column(Unicode)
    description = Column(Unicode)
    foo_id = Column(Integer, ForeignKey('foos.id'))
    foo = relation(Foo)

engine = create_engine('sqlite://')

Base.metadata.create_all(engine)  # issues DDL to create tables

session = sessionmaker(bind=engine)()

foo = Foo()
session.add(foo)
thing = Thing(name='thing1', description='some thing')
thing.foo = foo  # also adds Thing to session
session.commit()

Is there a way to call a stored procedure with Dapper?

With multiple return and multi parameter

string ConnectionString = CommonFunctions.GetConnectionString();
using (IDbConnection conn = new SqlConnection(ConnectionString))
{
    IEnumerable<dynamic> results = conn.Query(sql: "ProductSearch", 
        param: new { CategoryID = 1, SubCategoryID="", PageNumber=1 }, 
        commandType: CommandType.StoredProcedure);.  // single result

    var reader = conn.QueryMultiple("ProductSearch", 
        param: new { CategoryID = 1, SubCategoryID = "", PageNumber = 1 }, 
        commandType: CommandType.StoredProcedure); // multiple result

    var userdetails = reader.Read<dynamic>().ToList(); // instead of dynamic, you can use your objects
    var salarydetails = reader.Read<dynamic>().ToList();
}

public static string GetConnectionString()
{
    // Put the name the Sqlconnection from WebConfig..
    return ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
}

Performing Inserts and Updates with Dapper

You can also use dapper with a stored procedure and generic way by which everything easily manageable.

Define your connection:

public class Connection: IDisposable
{
    private static SqlConnectionStringBuilder ConnectionString(string dbName)
    {
        return new SqlConnectionStringBuilder
            {
                ApplicationName = "Apllication Name",
                DataSource = @"Your source",
                IntegratedSecurity = false,
                InitialCatalog = Database Name,
                Password = "Your Password",
                PersistSecurityInfo = false,
                UserID = "User Id",
                Pooling = true
            };
    }

    protected static IDbConnection LiveConnection(string dbName)
    {
        var connection = OpenConnection(ConnectionString(dbName));
        connection.Open();
        return connection;
    }

    private static IDbConnection OpenConnection(DbConnectionStringBuilder connectionString)
    {
        return new SqlConnection(connectionString.ConnectionString);
    }

    protected static bool CloseConnection(IDbConnection connection)
    {
        if (connection.State != ConnectionState.Closed)
        {
            connection.Close();
            // connection.Dispose();
        }
        return true;
    }

    private static void ClearPool()
    {
        SqlConnection.ClearAllPools();
    }

    public void Dispose()
    {
        ClearPool();
    }
}

Create an interface to define Dapper methods those you actually need:

 public interface IDatabaseHub
    {
   long Execute<TModel>(string storedProcedureName, TModel model, string dbName);

        /// <summary>
        /// This method is used to execute the stored procedures with parameter.This is the generic version of the method.
        /// </summary>
        /// <param name="storedProcedureName">This is the type of POCO class that will be returned. For more info, refer to https://msdn.microsoft.com/en-us/library/vstudio/dd456872(v=vs.100).aspx. </param>
        /// <typeparam name="TModel"></typeparam>
        /// <param name="model">The model object containing all the values that passes as Stored Procedure's parameter.</param>
        /// <returns>Returns how many rows have been affected.</returns>
        Task<long> ExecuteAsync<TModel>(string storedProcedureName, TModel model, string dbName);

        /// <summary>
        /// This method is used to execute the stored procedures with parameter. This is the generic version of the method.
        /// </summary>
        /// <param name="storedProcedureName">Stored Procedure's name. Expected to be a Verbatim String, e.g. @"[Schema].[Stored-Procedure-Name]"</param>
        /// <param name="parameters">Parameter required for executing Stored Procedure.</param>        
        /// <returns>Returns how many rows have been affected.</returns>         
        long Execute(string storedProcedureName, DynamicParameters parameters, string dbName);

        /// <summary>
        /// 
        /// </summary>
        /// <param name="storedProcedureName"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        Task<long> ExecuteAsync(string storedProcedureName, DynamicParameters parameters, string dbName);
}

Implement the interface:

     public class DatabaseHub : Connection, IDatabaseHub
        {

 /// <summary>
        /// This function is used for validating if the Stored Procedure's name is correct.
        /// </summary>
        /// <param name="storedProcedureName">Stored Procedure's name. Expected to be a Verbatim String, e.g. @"[Schema].[Stored-Procedure-Name]"</param>
        /// <returns>Returns true if name is not empty and matches naming patter, otherwise returns false.</returns>

        private static bool IsStoredProcedureNameCorrect(string storedProcedureName)
        {
            if (string.IsNullOrEmpty(storedProcedureName))
            {
                return false;
            }

            if (storedProcedureName.StartsWith("[") && storedProcedureName.EndsWith("]"))
            {
                return Regex.IsMatch(storedProcedureName,
                    @"^[\[]{1}[A-Za-z0-9_]+[\]]{1}[\.]{1}[\[]{1}[A-Za-z0-9_]+[\]]{1}$");
            }
            return Regex.IsMatch(storedProcedureName, @"^[A-Za-z0-9]+[\.]{1}[A-Za-z0-9]+$");
        }

     /// <summary>
            /// This method is used to execute the stored procedures without parameter.
            /// </summary>
            /// <param name="storedProcedureName">Stored Procedure's name. Expected to be a Verbatim String, e.g. @"[Schema].[Stored-Procedure-Name]"</param>
            /// <param name="model">The model object containing all the values that passes as Stored Procedure's parameter.</param>
            /// <typeparam name="TModel">This is the type of POCO class that will be returned. For more info, refer to https://msdn.microsoft.com/en-us/library/vstudio/dd456872(v=vs.100).aspx. </typeparam>
            /// <returns>Returns how many rows have been affected.</returns>

            public long Execute<TModel>(string storedProcedureName, TModel model, string dbName)
            {
                if (!IsStoredProcedureNameCorrect(storedProcedureName))
                {
                    return 0;
                }

                using (var connection = LiveConnection(dbName))
                {
                    try
                    {
                        return connection.Execute(
                            sql: storedProcedureName,
                            param: model,
                            commandTimeout: null,
                            commandType: CommandType.StoredProcedure
                            );

                    }
                    catch (Exception exception)
                    {
                        throw exception;
                    }
                    finally
                    {
                        CloseConnection(connection);
                    }
                }
            }

            public async Task<long> ExecuteAsync<TModel>(string storedProcedureName, TModel model, string dbName)
            {
                if (!IsStoredProcedureNameCorrect(storedProcedureName))
                {
                    return 0;
                }

                using (var connection = LiveConnection(dbName))
                {
                    try
                    {
                        return await connection.ExecuteAsync(
                            sql: storedProcedureName,
                            param: model,
                            commandTimeout: null,
                            commandType: CommandType.StoredProcedure
                            );

                    }
                    catch (Exception exception)
                    {
                        throw exception;
                    }
                    finally
                    {
                        CloseConnection(connection);
                    }
                }
            }

            /// <summary>
            /// This method is used to execute the stored procedures with parameter. This is the generic version of the method.
            /// </summary>
            /// <param name="storedProcedureName">Stored Procedure's name. Expected to be a Verbatim String, e.g. @"[Schema].[Stored-Procedure-Name]"</param>
            /// <param name="parameters">Parameter required for executing Stored Procedure.</param>        
            /// <returns>Returns how many rows have been affected.</returns>

            public long Execute(string storedProcedureName, DynamicParameters parameters, string dbName)
            {
                if (!IsStoredProcedureNameCorrect(storedProcedureName))
                {
                    return 0;
                }

                using (var connection = LiveConnection(dbName))
                {
                    try
                    {
                        return connection.Execute(
                            sql: storedProcedureName,
                            param: parameters,
                            commandTimeout: null,
                            commandType: CommandType.StoredProcedure
                            );
                    }
                    catch (Exception exception)
                    {
                        throw exception;
                    }
                    finally
                    {
                        CloseConnection(connection);
                    }
                }
            }



            public async Task<long> ExecuteAsync(string storedProcedureName, DynamicParameters parameters, string dbName)
            {
                if (!IsStoredProcedureNameCorrect(storedProcedureName))
                {
                    return 0;
                }

                using (var connection = LiveConnection(dbName))
                {
                    try
                    {
                        return await connection.ExecuteAsync(
                            sql: storedProcedureName,
                            param: parameters,
                            commandTimeout: null,
                            commandType: CommandType.StoredProcedure
                            );

                    }
                    catch (Exception exception)
                    {
                        throw exception;
                    }
                    finally
                    {
                        CloseConnection(connection);
                    }
                }
            }

    }

You can now call from model as your need:

public class DeviceDriverModel : Base
    {
 public class DeviceDriverSaveUpdate
        {
            public string DeviceVehicleId { get; set; }
            public string DeviceId { get; set; }
            public string DriverId { get; set; }
            public string PhoneNo { get; set; }
            public bool IsActive { get; set; }
            public string UserId { get; set; }
            public string HostIP { get; set; }
        }


        public Task<long> DeviceDriver_SaveUpdate(DeviceDriverSaveUpdate obj)
        {

            return DatabaseHub.ExecuteAsync(
                    storedProcedureName: "[dbo].[sp_SaveUpdate_DeviceDriver]", model: obj, dbName: AMSDB);//Database name defined in Base Class.
        }
}

You can also passed parameters as well:

public Task<long> DeleteFuelPriceEntryByID(string FuelPriceId, string UserId)
        {


            var parameters = new DynamicParameters();
            parameters.Add(name: "@FuelPriceId", value: FuelPriceId, dbType: DbType.Int32, direction: ParameterDirection.Input);
            parameters.Add(name: "@UserId", value: UserId, dbType: DbType.String, direction: ParameterDirection.Input);

            return DatabaseHub.ExecuteAsync(
                    storedProcedureName: @"[dbo].[sp_Delete_FuelPriceEntryByID]", parameters: parameters, dbName: AMSDB);

        }

Now call from your controllers:

var queryData = new DeviceDriverModel().DeviceInfo_Save(obj);

Hope it's prevent your code repetition and provide security;

SQLAlchemy: how to filter date field?

In fact, your query is right except for the typo: your filter is excluding all records: you should change the <= for >= and vice versa:

qry = DBSession.query(User).filter(
        and_(User.birthday <= '1988-01-17', User.birthday >= '1985-01-17'))
# or same:
qry = DBSession.query(User).filter(User.birthday <= '1988-01-17').\
        filter(User.birthday >= '1985-01-17')

Also you can use between:

qry = DBSession.query(User).filter(User.birthday.between('1985-01-17', '1988-01-17'))

Hibernate Error: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session

I'm new to NHibernate, and my problem was that I used a different session to query my object than I did to save it. So the saving session didn't know about the object.

It seems obvious, but from reading the previous answers I was looking everywhere for 2 objects, not 2 sessions.

Hibernate show real SQL

If you can already see the SQL being printed, that means you have the code below in your hibernate.cfg.xml:

<property name="show_sql">true</property>

To print the bind parameters as well, add the following to your log4j.properties file:

log4j.logger.net.sf.hibernate.type=debug

Do I need <class> elements in persistence.xml?

The persistence.xml has a jar-file that you can use. From the Java EE 5 tutorial:

<persistence>
    <persistence-unit name="OrderManagement">
        <description>This unit manages orders and customers.
            It does not rely on any vendor-specific features and can
            therefore be deployed to any persistence provider.
        </description>
        <jta-data-source>jdbc/MyOrderDB</jta-data-source>
        <jar-file>MyOrderApp.jar</jar-file>
        <class>com.widgets.Order</class>
        <class>com.widgets.Customer</class>
    </persistence-unit>
</persistence>

This file defines a persistence unit named OrderManagement, which uses a JTA-aware data source jdbc/MyOrderDB. The jar-file and class elements specify managed persistence classes: entity classes, embeddable classes, and mapped superclasses. The jar-file element specifies JAR files that are visible to the packaged persistence unit that contain managed persistence classes, while the class element explicitly names managed persistence classes.

In the case of Hibernate, have a look at the Chapter2. Setup and configuration too for more details.

EDIT: Actually, If you don't mind not being spec compliant, Hibernate supports auto-detection even in Java SE. To do so, add the hibernate.archive.autodetection property:

<persistence-unit name="eventractor" transaction-type="RESOURCE_LOCAL">
  <!-- This is required to be spec compliant, Hibernate however supports
       auto-detection even in JSE.
  <class>pl.michalmech.eventractor.domain.User</class>
  <class>pl.michalmech.eventractor.domain.Address</class>
  <class>pl.michalmech.eventractor.domain.City</class>
  <class>pl.michalmech.eventractor.domain.Country</class>
   -->

  <properties>
    <!-- Scan for annotated classes and Hibernate mapping XML files -->
    <property name="hibernate.archive.autodetection" value="class, hbm"/>

    <property name="hibernate.hbm2ddl.auto" value="validate" />
    <property name="hibernate.show_sql" value="true" />
  </properties>
</persistence-unit>

JPA: how do I persist a String into a database field, type MYSQL Text

Since you're using JPA, use the Lob annotation (and optionally the Column annotation). Here is what the JPA specification says about it:

9.1.19 Lob Annotation

A Lob annotation specifies that a persistent property or field should be persisted as a large object to a database-supported large object type. Portable applications should use the Lob annotation when mapping to a database Lob type. The Lob annotation may be used in conjunction with the Basic annotation. A Lob may be either a binary or character type. The Lob type is inferred from the type of the persistent field or property, and except for string and character-based types defaults to Blob.

So declare something like this:

@Lob 
@Column(name="CONTENT", length=512)
private String content;

References

  • JPA 1.0 specification:
    • Section 9.1.19 "Lob Annotation"

Difference between FetchType LAZY and EAGER in Java Persistence API?

Both FetchType.LAZY and FetchType.EAGER are used to define the default fetch plan.

Unfortunately, you can only override the default fetch plan for LAZY fetching. EAGER fetching is less flexible and can lead to many performance issues.

My advice is to restrain the urge of making your associations EAGER because fetching is a query-time responsibility. So all your queries should use the fetch directive to only retrieve what's necessary for the current business case.

How to remove entity with ManyToMany relationship in JPA (and corresponding join table rows)?

This is what I ended up doing. Hopefully someone might find it useful.

@Transactional
public void deleteGroup(Long groupId) {
    Group group = groupRepository.findById(groupId).orElseThrow();
    group.getUsers().forEach(u -> u.getGroups().remove(group));
    userRepository.saveAll(group.getUsers());
    groupRepository.delete(group);
}

Hibernate vs JPA vs JDO - pros and cons of each?

I've been looking into this myself and can't find a strong difference between the two. I think the big choice is in which implementation you use. For myself I've been considering the DataNucleus platform as it is a data-store agnostic implementation of both.

Default value in Doctrine

While setting the value in the constructor would work, using the Doctrine Lifecycle events might be a better solution.

By leveraging the prePersist Lifecycle Event, you could set your default value on your entity only on initial persist.

Add a custom attribute to a Laravel / Eloquent model on load?

I had something simular: I have an attribute picture in my model, this contains the location of the file in the Storage folder. The image must be returned base64 encoded

//Add extra attribute
protected $attributes = ['picture_data'];

//Make it available in the json response
protected $appends = ['picture_data'];

//implement the attribute
public function getPictureDataAttribute()
{
    $file = Storage::get($this->picture);
    $type = Storage::mimeType($this->picture);
    return "data:" . $type . ";base64," . base64_encode($file);
}

Conversion of a datetime2 data type to a datetime data type results out-of-range value

I found this post trying to figure why I kept getting the following error which is explained by the other answers.

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.

Use a nullable DateTime object.
public DateTime? PurchaseDate { get; set; }

If you are using entity framework Set the nullable property in the edmx file to True

Set the nullable property in the edmx file to **True**

Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

I got the same error and changing the following

SessionFactory sessionFactory =
    new Configuration().configure().buildSessionFactory();

to this

SessionFactory sessionFactory =
    new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();

worked for me.

Difference Between One-to-Many, Many-to-One and Many-to-Many?

this would probably call for a many-to-many relation ship as follows



public class Person{

    private Long personId;
    @manytomany

    private Set skills;
    //Getters and setters
}

public class Skill{
    private Long skillId;
    private String skillName;
    @manyToMany(MappedBy="skills,targetClass="Person")
    private Set persons; // (people would not be a good convenion)
    //Getters and setters
}

you may need to define a joinTable + JoinColumn but it will possible work also without...

How to read attribute value from XmlNode in C#?

If you use chldNode as XmlElement instead of XmlNode, you can use

var attributeValue = chldNode.GetAttribute("Name");

The return value will just be an empty string, in case the attribute name does not exist.

So your loop could look like this:

XmlDocument document = new XmlDocument();
var nodes = document.SelectNodes("//Node/N0de/node");

foreach (XmlElement node in nodes)
{
    var attributeValue = node.GetAttribute("Name");
}

This will select all nodes <node> surrounded by <Node><N0de></N0de><Node> tags and subsequently loop through them and read the attribute "Name".

How to show grep result with complete path or file name

For me

grep -b "searchsomething" *.log

worked as I wanted

jQuery checkbox event handling

Acknowledging the fact that the asker specifically requested jQuery and that the answer selected is correct, it should be noted that this problem doesn't actually need jQuery per say. If one desires to solve this problem without it, one can simply set the onClick attribute of the checkboxes that he or she wants to add additional functionality to, like so:

HTML:

<form id="myform">
  <input type="checkbox" name="check1" value="check1" onClick="cbChanged(this);">
  <input type="checkbox" name="check2" value="check2" onClick="cbChanged(this);">
</form>

javascript:

function cbChanged(checkboxElem) {
  if (checkboxElem.checked) {
    // Do something special
  } else {
    // Do something else
  }
}

Fiddle: http://jsfiddle.net/Y9f66/1/

How to fix "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS" error?

Try this one -

"SELECT 
       ID, Salt, password, BannedEndDate
     , (
          SELECT COUNT(1)
          FROM dbo.LoginFails l
          WHERE l.UserName = u.UserName
               AND IP = '" + Request.ServerVariables["REMOTE_ADDR"] + "'
      ) AS cnt
FROM dbo.Users u
WHERE u.UserName = '" + LoginModel.Username + "'"

Angular2 get clicked element id

You can retrieve the value of an attribute by its name, enabling you to get the value of a custom attribute such as an attribute from a Directive:

<button (click)="toggle($event)" id="btn1" myCustomAttribute="somevalue"></button>


toggle( event: Event ) {
  const eventTarget: Element = event.target as Element;
  const elementId: string = eventTarget.id;
  const attribVal: string = eventTarget.attributes['myCustomAttribute'].nodeValue;
}

Proper way to use AJAX Post in jquery to pass model from strongly typed MVC3 view

I found 3 ways to implement this:

C# class:

public class AddressInfo {
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }
    public string Country { get; set; }
}

Action:

[HttpPost]
public ActionResult Check(AddressInfo addressInfo)
{
    return Json(new { success = true });
}

JavaScript you can do it three ways:

1) Query String:

$.ajax({
    url: '/en/Home/Check',
    data: $('#form').serialize(),
    type: 'POST',
});

Data here is a string.

"Address1=blah&Address2=blah&City=blah&State=blah&ZipCode=blah&Country=blah"

2) Object Array:

$.ajax({
    url: '/en/Home/Check',
    data: $('#form').serializeArray(),
    type: 'POST',
});

Data here is an array of key/value pairs :

=[{name: 'Address1', value: 'blah'}, {name: 'Address2', value: 'blah'}, {name: 'City', value: 'blah'}, {name: 'State', value: 'blah'}, {name: 'ZipCode', value: 'blah'}, {name: 'Country', value: 'blah'}]

3) JSON:

$.ajax({
      url: '/en/Home/Check',
      data: JSON.stringify({ addressInfo:{//missing brackets
          Address1: $('#address1').val(),
          Address2: $('#address2').val(),
          City: $('#City').val(),
          State: $('#State').val(),
          ZipCode: $('#ZipCode').val()}}),
      type: 'POST',
      contentType: 'application/json; charset=utf-8'
});

Data here is a serialized JSON string. Note that the name has to match the parameter name in the server!!

='{"addressInfo":{"Address1":"blah","Address2":"blah","City":"blah","State":"blah", "ZipCode", "blah", "Country", "blah"}}'

Is there a Google Voice API?

I looked for a C/C++ API for Google Voice for quite a while and never found anything close (the closest was a C# API). Since I really needed it, I decided to just write one myself:

http://github.com/mastermind202/GoogleVoice

I hope others find it useful. Feedback and suggestions welcome.

How to get all of the immediate subdirectories in Python

import os
def get_immediate_subdirectories(a_dir):
    return [name for name in os.listdir(a_dir)
            if os.path.isdir(os.path.join(a_dir, name))]

How can I view all historical changes to a file in SVN

The oddly named "blame" command does this. If you use Tortoise, it gives you a "from revision" dialog, then a file listing with a line by line indicator of Revision number and author next to it.

If you right click on the revision info, you can bring up a "Show log" dialog that gives full checkin information, along with other files that were part of the checkin.

Adding and using header (HTTP) in nginx

You can use upstream headers (named starting with $http_) and additional custom headers. For example:

add_header X-Upstream-01 $http_x_upstream_01;
add_header X-Hdr-01  txt01;

next, go to console and make request with user's header:

curl -H "X-Upstream-01: HEADER1" -I http://localhost:11443/

the response contains X-Hdr-01, seted by server and X-Upstream-01, seted by client:

HTTP/1.1 200 OK
Server: nginx/1.8.0
Date: Mon, 30 Nov 2015 23:54:30 GMT
Content-Type: text/html;charset=UTF-8
Connection: keep-alive
X-Hdr-01: txt01
X-Upstream-01: HEADER1

AngularJs ReferenceError: angular is not defined

I ran into this because I made a copy-and-paste of ngBoilerplate into my project on a Mac without Finder showing hidden files. So .bower was not copied with the rest of ngBoilerplate. Thus bower moved resources to bower_components (defult) instead of vendor (as configured) and my app didn't get angular. Probably a corner case, but it might help someone here.

How do I find out my MySQL URL, host, port and username?

If you're already logged into the command line client try this:

mysql> select user();

It will output something similar to this:

+----------------+
| user()         |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.41 sec)

In my example above, I was logged in as root from localhost.

To find port number and other interesting settings use this command:

mysql> show variables;

How to cache data in a MVC application

I have used it in this way and it works for me. https://msdn.microsoft.com/en-us/library/system.web.caching.cache.add(v=vs.110).aspx parameters info for system.web.caching.cache.add.

public string GetInfo()
{
     string name = string.Empty;
     if(System.Web.HttpContext.Current.Cache["KeyName"] == null)
     {
         name = GetNameMethod();
         System.Web.HttpContext.Current.Cache.Add("KeyName", name, null, DateTime.Noew.AddMinutes(5), Cache.NoSlidingExpiration, CacheitemPriority.AboveNormal, null);
     }
     else
     {
         name = System.Web.HttpContext.Current.Cache["KeyName"] as string;
     }

      return name;

}

Is there an eval() function in Java?

You can use the ScriptEngine class and evaluate it as a Javascript string.

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
Object result = engine.eval("4*5");

There may be a better way, but this one works.

Transferring files over SSH

You need to scp something somewhere. You have scp ./styles/, so you're saying secure copy ./styles/, but not where to copy it to.

Generally, if you want to download, it will go:

# download: remote -> local
scp user@remote_host:remote_file local_file 

where local_file might actually be a directory to put the file you're copying in. To upload, it's the opposite:

# upload: local -> remote
scp local_file user@remote_host:remote_file

If you want to copy a whole directory, you will need -r. Think of scp as like cp, except you can specify a file with user@remote_host:file as well as just local files.

Edit: As noted in a comment, if the usernames on the local and remote hosts are the same, then the user can be omitted when specifying a remote file.

proper way to sudo over ssh

I faced a problem,

user1@server1$ ssh -q user1@server2 sudo -u user2 rm -f /some/file/location.txt

Output:
sudo: no tty present and no askpass program specified

Then I tried with

#1
vim /etc/sudoers
Defaults:user1    !requiretty

didn't work

#2
user1   ALL=(user2)         NOPASSWD: ALL

that worked properly!

Pandas merge two dataframes with different columns

I had this problem today using any of concat, append or merge, and I got around it by adding a helper column sequentially numbered and then doing an outer join

helper=1
for i in df1.index:
    df1.loc[i,'helper']=helper
    helper=helper+1
for i in df2.index:
    df2.loc[i,'helper']=helper
    helper=helper+1
df1.merge(df2,on='helper',how='outer')

Android BroadcastReceiver within Activity

You forget to write .show() at the end, which is used to show the toast message.

Toast.makeText(getApplicationContext(), "received", Toast.LENGTH_SHORT).show();

It is a common mistake that programmer does, but i am sure after this you won't repeat the mistake again... :D

How do I set the default Java installation/runtime (Windows)?

This is a bit of a pain on Windows. Here's what I do.

Install latest Sun JDK, e.g. 6u11, in path like c:\install\jdk\sun\6u11, then let the installer install public JRE in the default place (c:\program files\blah). This will setup your default JRE for the majority of things.

Install older JDKs as necessary, like 5u18 in c:\install\jdk\sun\5u18, but don't install the public JREs.

When in development, I have a little batch file that I use to setup a command prompt for each JDK version. Essentially just set JAVA_HOME=c:\jdk\sun\JDK_DESIRED and then set PATH=%JAVA_HOME%\bin;%PATH%. This will put the desired JDK first in the path and any secondary tools like Ant or Maven can use the JAVA_HOME variable.

The path is important because most public JRE installs put a linked executable at c:\WINDOWS\System32\java.exe, which usually overrides most other settings.

Android: adb pull file on desktop

Note need root than:

  • adb root
  • adb pull /data/data/com.google.android.apps.nexuslauncher/databases/launcher.db launcher.db

How to a convert a date to a number and back again in MATLAB

Use DATESTR

>> datestr(40189)
ans =
12-Jan-0110

Unfortunately, Excel starts counting at 1-Jan-1900. Find out how to convert serial dates from Matlab to Excel by using DATENUM

>> datenum(2010,1,11)
ans =
      734149
>> datenum(2010,1,11)-40189
ans =
      693960
>> datestr(40189+693960)
ans =
11-Jan-2010

In other words, to convert any serial Excel date, call

datestr(excelSerialDate + 693960)

EDIT

To get the date in mm/dd/yyyy format, call datestr with the specified format

excelSerialDate = 40189;
datestr(excelSerialDate + 693960,'mm/dd/yyyy')
ans =
01/11/2010

Also, if you want to get rid of the leading zero for the month, you can use REGEXPREP to fix things

excelSerialDate = 40189;
regexprep(datestr(excelSerialDate + 693960,'mm/dd/yyyy'),'^0','')
ans =
1/11/2010

Programmatically find the number of cores on a machine

One more Windows recipe: use system-wide environment variable NUMBER_OF_PROCESSORS:

printf("%d\n", atoi(getenv("NUMBER_OF_PROCESSORS")));

How do you read from stdin?

The problem I have with solution

import sys

for line in sys.stdin:
    print(line)

is that if you don't pass any data to stdin, it will block forever. That's why I love this answer: check if there is some data on stdin first, and then read it. This is what I ended up doing:

import sys
import select

# select(files to read from, files to write to, magic, timeout)
# timeout=0.0 is essential b/c we want to know the asnwer right away
if select.select([sys.stdin], [], [], 0.0)[0]:
    help_file_fragment = sys.stdin.read()
else:
    print("No data passed to stdin", file=sys.stderr)
    sys.exit(2)

Using Linq select list inside list

You have to use the SelectMany extension method or its equivalent syntax in pure LINQ.

(from model in list
 where model.application == "applicationname"
 from user in model.users
 where user.surname == "surname"
 select new { user, model }).ToList();

How do I make the return type of a method generic?

 private static T[] prepareArray<T>(T[] arrayToCopy, T value)
    {
        Array.Copy(arrayToCopy, 1, arrayToCopy, 0, arrayToCopy.Length - 1);
        arrayToCopy[arrayToCopy.Length - 1] = value;
        return (T[])arrayToCopy;
    }

I was performing this throughout my code and wanted a way to put it into a method. I wanted to share this here because I didn't have to use the Convert.ChangeType for my return value. This may not be a best practice but it worked for me. This method takes in an array of generic type and a value to add to the end of the array. The array is then copied with the first value stripped and the value taken into the method is added to the end of the array. The last thing is that I return the generic array.

Matplotlib scatterplot; colour as a function of a third variable

In matplotlib grey colors can be given as a string of a numerical value between 0-1.
For example c = '0.1'

Then you can convert your third variable in a value inside this range and to use it to color your points.
In the following example I used the y position of the point as the value that determines the color:

from matplotlib import pyplot as plt

x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [125, 32, 54, 253, 67, 87, 233, 56, 67]

color = [str(item/255.) for item in y]

plt.scatter(x, y, s=500, c=color)

plt.show()

enter image description here

How can I combine multiple rows into a comma-delimited list in Oracle?

you can use this query to do the above task

DECLARE @test NVARCHAR(max)
SELECT @test = COALESCE(@test + ',', '') + field2 FROM #test SELECT field2= @test

for detail and step by step explanation visit the following link
http://oops-solution.blogspot.com/2011/11/sql-server-convert-table-column-data.html

How can I change or remove HTML5 form validation default error messages?

This is a very good link I found about checking various attributes of html5 validations.

https://dzone.com/articles/custom-validation-messages

Hope it helps someone.

Convert datetime to Unix timestamp and convert it back in python

def dt2ts(dt, utc=False):
    if utc:
        return calendar.timegm(dt.timetuple())
    if dt.tzinfo is None:
        return int(time.mktime(dt.timetuple()))
    utc_dt = dt.astimezone(tz.tzutc()).timetuple()
    return calendar.timegm(utc_dt)

If you want UTC timestamp :time.mktime just for local dt .Use calendar.timegm is safe but dt must the utc zone so change the zone to utc. If dt in UTC just use calendar.timegm.

Apache Proxy: No protocol handler was valid

This can happen if you don't have mod_proxy_http enabled

sudo a2enmod proxy_http

For me to get my https based load balancer working, i had to enable the following:

sudo a2enmod ssl
sudo a2enmod proxy
sudo a2enmod proxy_balancer
sudo a2enmod proxy_http

Best way to Bulk Insert from a C# DataTable

If using SQL Server, SqlBulkCopy.WriteToServer(DataTable)

Or also with SQL Server, you can write it to a .csv and use BULK INSERT

If using MySQL, you could write it to a .csv and use LOAD DATA INFILE

If using Oracle, you can use the array binding feature of ODP.NET

If SQLite:

Ignoring directories in Git repositories on Windows

By default, Windows Explorer will display .gitignore when in fact the file name is .gitignore.txt.

Git will not use .gitignore.txt

And you can't rename the file to .gitignore, because Windows Explorer thinks it's a file of type gitignore without a name.

Non command line solution:

You can rename a file to ".gitignore.", and it will create ".gitignore"

Best XML Parser for PHP

It depends on what you are trying to do with the XML files. If you are just trying to read the XML file (like a configuration file), The Wicked Flea is correct in suggesting SimpleXML since it creates what amounts to nested ArrayObjects. e.g. value will be accessible by $xml->root->child.

If you are looking to manipulate the XML files you're probably best off using DOM XML

Adding integers to an int array

org.apache.commons.lang.ArrayUtils can do this

num = (int []) ArrayUtils.add(num, 12);     // builds new array with 12 appended

How do I export (and then import) a Subversion repository?

I found an article about how to move svn repositories from a hosting service to another, and how to do local backups:

  1. Define where you will store your repositories:

    mkdir ~/repo
    MYREPO=/home/me/someplace ## you should use full path here
    
  2. Now create a empty svn repository with svnadmin create $MYREPO
  3. Create a hook file and make it executable:

    echo '#!/bin/sh' > $MYREPO/hooks/pre-revprop-change
    chmod +x $MYREPO/hooks/pre-revprop-change
    
  4. Now we can start importing the repository with svnsync, that will initialize a destination repository for synchronization from another repository:

    svnsync init file://$MYREPO http://your.svn.repo.here/
    
  5. And the finishing touch to transfer all pending revisions to the destination from the source with which it was initialized:

    svnsync sync file://$MYREPO
    

There now you have a local svn repository in the ~/repo directory.

Source:

Npm install cannot find module 'semver'

I faced with same trouble after brew installs yarn on my MacOs Sierra 10.12.6. (And the first try of installation fall after brew update self with a message " Homebrew must be run under Ruby 2.3! You're running 2.0.0. (RuntimeError)". So I re-run it.)

So I use n manager to reinstall npm.

  • switch to another node version (for my case to 8.0) by "n" command with empty parameters
  • or install new by "n x.x.x" where x.x.x the node version number (i need 6.9.1)
  • delete working version by "n rm x.x.x" where x.x.x the node version number. use sudo if need
  • install working version by "n x.x.x" where x.x.x the node version number. use sudo if need
  • switch by to the working version of node. (see first step for reference)

I think the trouble can be caused that node was installed under sudo for case.

Best practice for instantiating a new Android Fragment

use this code 100% fix your problem

enter this code in firstFragment

public static yourNameParentFragment newInstance() {

    Bundle args = new Bundle();
    args.putBoolean("yourKey",yourValue);
    YourFragment fragment = new YourFragment();
    fragment.setArguments(args);
    return fragment;
}

this sample send boolean data

and in SecendFragment

yourNameParentFragment name =yourNameParentFragment.newInstance();
   Bundle bundle;
   bundle=sellDiamondFragments2.getArguments();
  boolean a= bundle.getBoolean("yourKey");

must value in first fragment is static

happy code

html 5 audio tag width

For those looking for an inline example, here is one:

<audio controls style="width: 200px;">
   <source src="http://somewhere.mp3" type="audio/mpeg">
</audio>

It doesn't seem to respect a "height" setting, at least not awesomely. But you can always "customize" the controls but creating your own controls (instead of using the built-in ones) or using somebody's widget that similarly creates its own :)

Could not reliably determine the server's fully qualified domain name

I was NOT getting the ServerName wrong. Inside your VirtualHost configuration that is causing this warning message, it is the generic one near the top of your httpd.conf which is by default commented out.

Change

#ServerName www.example.com:80

to:

  ServerName 127.0.0.1:80

Count a list of cells with the same background color

Yes VBA is the way to go.

But, if you don't need to have a cell with formula that auto-counts/updates the number of cells with a particular colour, an alternative is simply to use the 'Find and Replace' function and format the cell to have the appropriate colour fill.

Hitting 'Find All' will give you the total number of cells found at the bottom left of the dialogue box.

enter image description here

This becomes especially useful if your search range is massive. The VBA script will be very slow but the 'Find and Replace' function will still be very quick.

Running EXE with parameters

System.Diagnostics.Process.Start("PATH to exe", "Command Line Arguments");

How do I upload a file to an SFTP server in C# (.NET)?

For another un-free option try edtFTPnet/PRO. It has comprehensive support for SFTP, and also supports FTPS (and of course FTP) if required.

Is there an embeddable Webkit component for Windows / C# development?

Haven't tried yet but found WebKit.NET on SourceForge. It was moved to GitHub.

Warning: Not maintained anymore, last commits are from early 2013

Laravel Escaping All HTML in Blade Template

There is no problem with displaying HTML code in blade templates.

For test, you can add to routes.php only one route:

Route::get('/', function () {

        $data = new stdClass();
        $data->page_desc
            = '<strong>aaa</strong><em>bbb</em>
               <p>New paragaph</p><script>alert("Hello");</script>';

        return View::make('hello')->with('content', $data);
    }
);

and in hello.blade.php file:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>

{{ $content->page_desc }}

</body>
</html>

For the following code you will get output as on image

Output

So probably page_desc in your case is not what you expect. But as you see it can be potential dangerous if someone uses for example '` tag so you should probably in your route before assigning to blade template filter some tags

EDIT

I've also tested it with putting the same code into database:

Route::get('/', function () {

        $data = User::where('id','=',1)->first();

        return View::make('hello')->with('content', $data);
    }
);

Output is exactly the same in this case

Edit2

I also don't know if Pages is your model or it's a vendor model. For example it can have accessor inside:

public function getPageDescAttribute($value)
{
    return htmlspecialchars($value);
}

and then when you get page_desc attribute you will get modified page_desc with htmlspecialchars. So if you are sure that data in database is with raw html (not escaped) you should look at this Pages class

How to enable file upload on React's Material UI simple input?

newer MUI version:

<input
  accept="image/*"
  className={classes.input}
  style={{ display: 'none' }}
  id="raised-button-file"
  multiple
  type="file"
/>
<label htmlFor="raised-button-file">
  <Button variant="raised" component="span" className={classes.button}>
    Upload
  </Button>
</label> 

Efficient way to apply multiple filters to pandas DataFrame or Series

Since pandas 0.22 update, comparison options are available like:

  • gt (greater than)
  • lt (lesser than)
  • eq (equals to)
  • ne (not equals to)
  • ge (greater than or equals to)

and many more. These functions return boolean array. Let's see how we can use them:

# sample data
df = pd.DataFrame({'col1': [0, 1, 2,3,4,5], 'col2': [10, 11, 12,13,14,15]})

# get values from col1 greater than or equals to 1
df.loc[df['col1'].ge(1),'col1']

1    1
2    2
3    3
4    4
5    5

# where co11 values is better 0 and 2
df.loc[df['col1'].between(0,2)]

 col1 col2
0   0   10
1   1   11
2   2   12

# where col1 > 1
df.loc[df['col1'].gt(1)]

 col1 col2
2   2   12
3   3   13
4   4   14
5   5   15

COPY with docker but with exclusion

In my case, my Dockerfile contained an installation step, which produced the vendor directory (the PHP equivalent of node_modules). I then COPY this directory over to the final application image. Therefore, I could not put vendor in my .dockerignore. My solution was simply to delete the directory before performing composer install (the PHP equivalent of npm install).

FROM composer AS composer
WORKDIR /app
COPY . .
RUN rm -rf vendor \
    && composer install 

FROM richarvey/nginx-php-fpm
WORKDIR /var/www/html
COPY --from=composer /app .

This solution works and does not bloat the final image, but it is not ideal, because the vendor directory on the host is copied into the Docker context during the build process, which adds time.

php resize image on upload

I followed the steps at https://www.w3schools.com/php/php_file_upload.asp and http://www.w3bees.com/2013/03/resize-image-while-upload-using-php.html to produce this solution:

In my view (I am using the MVC paradigm, but it could be your .html or .php file, or the technology that you use for your front-end):

<form action="../../photos/upload.php" method="post" enctype="multipart/form-data">
<label for="quantity">Width:</label>
  <input type="number" id="picture_width" name="picture_width" min="10" max="800" step="1" value="500">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>

My upload.php:

<?php
/* Get original image x y*/
list($w, $h) = getimagesize($_FILES['fileToUpload']['tmp_name']);
$new_height=$h*$_POST['picture_width']/$w;
/* calculate new image size with ratio */
$ratio = max($_POST['picture_width']/$w, $new_height/$h);
$h = ceil($new_height / $ratio);
$x = ($w - $_POST['picture_width'] / $ratio) / 2;
$w = ceil($_POST['picture_width'] / $ratio);
/* new file name */
//$path = 'uploads/'.$_POST['picture_width'].'x'.$new_height.'_'.basename($_FILES['fileToUpload']['name']);
$path = 'uploads/'.basename($_FILES['fileToUpload']['name']);
/* read binary data from image file */
$imgString = file_get_contents($_FILES['fileToUpload']['tmp_name']);
/* create image from string */
$image = imagecreatefromstring($imgString);
$tmp = imagecreatetruecolor($_POST['picture_width'], $new_height);
imagecopyresampled($tmp, $image,
    0, 0,
    $x, 0,
    $_POST['picture_width'], $new_height,
    $w, $h);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($path,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        //echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        //echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($path)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
} else {
    /* Save image */
    switch ($_FILES['fileToUpload']['type']) {
        case 'image/jpeg':
            imagejpeg($tmp, $path, 100);
            break;
        case 'image/png':
            imagepng($tmp, $path, 0);
            break;
        case 'image/gif':
            imagegif($tmp, $path);
            break;
        default:
            exit;
            break;
    }
    echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    /* cleanup memory */
    imagedestroy($image);
    imagedestroy($tmp);
}
?>

The name of the folder where pictures are stored is called 'uploads/'. You need to have that folder previously created and that is where you will see your pictures. It works great for me.

NOTE: This is my form:

enter image description here

The code is uploading and resizing pictures properly. I used this link as a guide: http://www.w3bees.com/2013/03/resize-image-while-upload-using-php.html. I modified it because in that code they specify both width and height of resized pictures. In my case, I only wanted to specify width. The height I automatically calculated it proportionally, just keeping proper picture proportions. Everything works perfectly. I hope this helps.

For each row return the column name of the largest value

Based on the above suggestions, the following data.table solution worked very fast for me:

library(data.table)

set.seed(45)
DT <- data.table(matrix(sample(10, 10^7, TRUE), ncol=10))

system.time(
  DT[, col_max := colnames(.SD)[max.col(.SD, ties.method = "first")]]
)
#>    user  system elapsed 
#>    0.15    0.06    0.21
DT[]
#>          V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 col_max
#>       1:  7  4  1  2  3  7  6  6  6   1      V1
#>       2:  4  6  9 10  6  2  7  7  1   3      V4
#>       3:  3  4  9  8  9  9  8  8  6   7      V3
#>       4:  4  8  8  9  7  5  9  2  7   1      V4
#>       5:  4  3  9 10  2  7  9  6  6   9      V4
#>      ---                                       
#>  999996:  4  6 10  5  4  7  3  8  2   8      V3
#>  999997:  8  7  6  6  3 10  2  3 10   1      V6
#>  999998:  2  3  2  7  4  7  5  2  7   3      V4
#>  999999:  8 10  3  2  3  4  5  1  1   4      V2
#> 1000000: 10  4  2  6  6  2  8  4  7   4      V1

And also comes with the advantage that can always specify what columns .SD should consider by mentioning them in .SDcols:

DT[, MAX2 := colnames(.SD)[max.col(.SD, ties.method="first")], .SDcols = c("V9", "V10")]

In case we need the column name of the smallest value, as suggested by @lwshang, one just needs to use -.SD:

DT[, col_min := colnames(.SD)[max.col(-.SD, ties.method = "first")]]

Java HTTP Client Request with defined timeout

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

...

    // set the connection timeout value to 30 seconds (30000 milliseconds)
    final HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
    client = new DefaultHttpClient(httpParams);

How do I set a path in Visual Studio?

None of the answers solved exactly my problem (the solution file I was running was trying to find xcopy to copy a dll after generation).

What solved it for me was going into menu "Project -> Properties"

Then in the window that opens choosing on the left pane: "Configuration Properties -> VC++ Directories

On the right pane under "General" choosing "Executable Directories "

And then adding:

$(SystemRoot)\system32;$(SystemRoot);$(SystemRoot)\System32\Wbem;$(SystemRoot)\System32\WindowsPowerShell\v1.0\;$(ExecutablePath)

Composer: Command Not Found

Step 1 : Open Your terminal

Step 2 : Run bellow command

          curl -sS https://getcomposer.org/installer | php

Step 3 : After installation run bellow command

          sudo mv composer.phar /usr/local/bin/

Step 4 : Open bash_profile file create alias follow bellow steps

           vim ~/.bash_profile

Step 5 : Add bellow line in bash_profile file

          alias composer="php /usr/local/bin/composer.phar"

Step 6 : Close your terminal and reopen your terminal and run bellow command composer

Two arrays in foreach loop

I think the simplest way is just to use the for loop this way:

$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');

for($i = 0; $i < sizeof($codes); $i++){
    echo '<option value="' . $codes[$i] . '">' . $names[$i] . '</option>';
}

How do I install and use the ASP.NET AJAX Control Toolkit in my .NET 3.5 web applications?

If you are using MasterPages and Content pages in your app - you also have the option of putting the ScriptManager on the Masterpage and then every ContentPage that uses that MasterPage will NOT need a script manager added. If you need some of the special configurations of the ScriptManager - like javascript file references - you can use a ScriptManagerProxy control on the content page that needs it.

How to get a vCard (.vcf file) into Android contacts from website

I'm running 2.2 and there is no change, reports from others on 2.3 say the same. Android (bug) does not handle a .vcf nor a link to such a file on a web page via port 80, neither via http headers or direct streaming. It just is NOT SUPPORTED AT ALL.

With Twitter Bootstrap, how can I customize the h1 text color of one page and leave the other pages to be default?

The best way to solve this problem would be by starting with customizing Bootstrap using their customization tools.

http://getbootstrap.com/customize/

Go down to @headings-color and change it from "inherit" to something that you would like your headers to be across the site (if you like the default just change it to #333).

Note that this will keep all your headings the same color, as you requested.

Now in order to accomplish what you want that after you make this change you can now overwrite them specifically in your own CSS to apply your own color to them. The "inherit" keyword I always have found to be a pain in frameworks.

How to use Google fonts in React.js?

If you are using Create React App environment simply add @import rule to index.css as such:

@import url('https://fonts.googleapis.com/css?family=Anton');

Import index.css in your main React app:

import './index.css'

React gives you a choice of Inline styling, CSS Modules or Styled Components in order to apply CSS:

font-family: 'Anton', sans-serif;

PLS-00103: Encountered the symbol "CREATE"

For me / had to be in a new line.

For example

create type emp_t;/

didn't work

but

create type emp_t;

/

worked.

How can I change a button's color on hover?

Seems your selector is wrong, try using:

a.button:hover{
     background: #383;
}

Your code

a.button a:hover

Means it is going to search for an a element inside a with class button.

How to pretty-print a numpy.array without scientific notation and with given precision?

Years later, another one is below. But for everyday use I just

np.set_printoptions( threshold=20, edgeitems=10, linewidth=140,
    formatter = dict( float = lambda x: "%.3g" % x ))  # float arrays %.3g

''' printf( "... %.3g ... %.1f  ...", arg, arg ... ) for numpy arrays too

Example:
    printf( """ x: %.3g   A: %.1f   s: %s   B: %s """,
                   x,        A,        "str",  B )

If `x` and `A` are numbers, this is like `"format" % (x, A, "str", B)` in python.
If they're numpy arrays, each element is printed in its own format:
    `x`: e.g. [ 1.23 1.23e-6 ... ]  3 digits
    `A`: [ [ 1 digit after the decimal point ... ] ... ]
with the current `np.set_printoptions()`. For example, with
    np.set_printoptions( threshold=100, edgeitems=3, suppress=True )
only the edges of big `x` and `A` are printed.
`B` is printed as `str(B)`, for any `B` -- a number, a list, a numpy object ...

`printf()` tries to handle too few or too many arguments sensibly,
but this is iffy and subject to change.

How it works:
numpy has a function `np.array2string( A, "%.3g" )` (simplifying a bit).
`printf()` splits the format string, and for format / arg pairs
    format: % d e f g
    arg: try `np.asanyarray()`
-->  %s  np.array2string( arg, format )
Other formats and non-ndarray args are left alone, formatted as usual.

Notes:

`printf( ... end= file= )` are passed on to the python `print()` function.

Only formats `% [optional width . precision] d e f g` are implemented,
not `%(varname)format` .

%d truncates floats, e.g. 0.9 and -0.9 to 0; %.0f rounds, 0.9 to 1 .
%g is the same as %.6g, 6 digits.
%% is a single "%" character.

The function `sprintf()` returns a long string. For example,
    title = sprintf( "%s  m %g  n %g  X %.3g",
                    __file__, m, n, X )
    print( title )
    ...
    pl.title( title )

Module globals:
_fmt = "%.3g"  # default for extra args
_squeeze = np.squeeze  # (n,1) (1,n) -> (n,) print in 1 line not n

See also:
http://docs.scipy.org/doc/numpy/reference/generated/numpy.set_printoptions.html
http://docs.python.org/2.7/library/stdtypes.html#string-formatting

'''
# http://stackoverflow.com/questions/2891790/pretty-printing-of-numpy-array


#...............................................................................
from __future__ import division, print_function
import re
import numpy as np

__version__ = "2014-02-03 feb denis"

_splitformat = re.compile( r'''(
    %
    (?<! %% )  # not %%
    -? [ \d . ]*  # optional width.precision
    \w
    )''', re.X )
    # ... %3.0f  ... %g  ... %-10s ...
    # -> ['...' '%3.0f' '...' '%g' '...' '%-10s' '...']
    # odd len, first or last may be ""

_fmt = "%.3g"  # default for extra args
_squeeze = np.squeeze  # (n,1) (1,n) -> (n,) print in 1 line not n

#...............................................................................
def printf( format, *args, **kwargs ):
    print( sprintf( format, *args ), **kwargs )  # end= file=

printf.__doc__ = __doc__


def sprintf( format, *args ):
    """ sprintf( "text %.3g text %4.1f ... %s ... ", numpy arrays or ... )
        %[defg] array -> np.array2string( formatter= )
    """
    args = list(args)
    if not isinstance( format, basestring ):
        args = [format] + args
        format = ""

    tf = _splitformat.split( format )  # [ text %e text %f ... ]
    nfmt = len(tf) // 2
    nargs = len(args)
    if nargs < nfmt:
        args += (nfmt - nargs) * ["?arg?"]
    elif nargs > nfmt:
        tf += (nargs - nfmt) * [_fmt, " "]  # default _fmt

    for j, arg in enumerate( args ):
        fmt = tf[ 2*j + 1 ]
        if arg is None \
        or isinstance( arg, basestring ) \
        or (hasattr( arg, "__iter__" ) and len(arg) == 0):
            tf[ 2*j + 1 ] = "%s"  # %f -> %s, not error
            continue
        args[j], isarray = _tonumpyarray(arg)
        if isarray  and fmt[-1] in "defgEFG":
            tf[ 2*j + 1 ] = "%s"
            fmtfunc = (lambda x: fmt % x)
            formatter = dict( float_kind=fmtfunc, int=fmtfunc )
            args[j] = np.array2string( args[j], formatter=formatter )
    try:
        return "".join(tf) % tuple(args)
    except TypeError:  # shouldn't happen
        print( "error: tf %s  types %s" % (tf, map( type, args )))
        raise


def _tonumpyarray( a ):
    """ a, isarray = _tonumpyarray( a )
        ->  scalar, False
            np.asanyarray(a), float or int
            a, False
    """
    a = getattr( a, "value", a )  # cvxpy
    if np.isscalar(a):
        return a, False
    if hasattr( a, "__iter__" )  and len(a) == 0:
        return a, False
    try:
        # map .value ?
        a = np.asanyarray( a )
    except ValueError:
        return a, False
    if hasattr( a, "dtype" )  and a.dtype.kind in "fi":  # complex ?
        if callable( _squeeze ):
            a = _squeeze( a )  # np.squeeze
        return a, True
    else:
        return a, False


#...............................................................................
if __name__ == "__main__":
    import sys

    n = 5
    seed = 0
        # run this.py n= ...  in sh or ipython
    for arg in sys.argv[1:]:
        exec( arg )
    np.set_printoptions( 1, threshold=4, edgeitems=2, linewidth=80, suppress=True )
    np.random.seed(seed)

    A = np.random.exponential( size=(n,n) ) ** 10
    x = A[0]

    printf( "x: %.3g  \nA: %.1f  \ns: %s  \nB: %s ",
                x,         A,         "str",   A )
    printf( "x %%d: %d", x )
    printf( "x %%.0f: %.0f", x )
    printf( "x %%.1e: %.1e", x )
    printf( "x %%g: %g", x )
    printf( "x %%s uses np printoptions: %s", x )

    printf( "x with default _fmt: ", x )
    printf( "no args" )
    printf( "too few args: %g %g", x )
    printf( x )
    printf( x, x )
    printf( None )
    printf( "[]:", [] )
    printf( "[3]:", [3] )
    printf( np.array( [] ))
    printf( [[]] )  # squeeze

How to close Browser Tab After Submitting a Form?

Window.close( ) does not work as it used to. Can be seen here:

window.close and self.close do not close the window in Chrome

In my case, I realized that I didn't need to close the page. So you can redirect the user to another page with:

window.location.replace("https://stackoverflow.com/");

How can I pass variable to ansible playbook in the command line?

ansible-playbook release.yml -e "version=1.23.45 other_variable=foo"

Uploading files to file server using webclient class

when you manually open the IP address (via the RUN command or mapping a network drive), your PC will send your credentials over the pipe and the file server will receive authorization from the DC.

When ASP.Net tries, then it is going to try to use the IIS worker user (unless impersonation is turned on which will list a few other issues). Traditionally, the IIS worker user does not have authorization to work across servers (or even in other folders on the web server).

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) on dispatch_semaphore_dispose

My problem was took IBOutlet but didn't connect with interface builder and using in swift file.

How do you do relative time in Rails?

I've written a gem that does this for Rails ActiveRecord objects. The example uses created_at, but it will also work on updated_at or anything with the class ActiveSupport::TimeWithZone.

Just gem install and call the 'pretty' method on your TimeWithZone instance.

https://github.com/brettshollenberger/hublot

How to set timeout in Retrofit library?

For Retrofit1.9 with OkHttp3 users, here is the solution,

.setClient(new Ok3Client(new OkHttpClient.Builder().readTimeout(60, TimeUnit.SECONDS).build()))

WPF Binding StringFormat Short Date String

Just use:

<TextBlock Text="{Binding Date, StringFormat=\{0:d\}}" />

How to convert Seconds to HH:MM:SS using T-SQL

SELECT substring(convert (varchar(23),Dateadd(s,10000,LEFT(getdate(),11)),121),12,8)

10000 is your value in sec

What does %s and %d mean in printf in the C language?

%s is for string %d is for decimal (or int) %c is for character

It appears to be chewing through an array of characters, and printing out whatever string exists starting at each subsequent position. The strings will stop at the first null in each case.

The commas are just separating the arguments to a function that takes a variable number of args; this number corresponds to the number of % args in the format descriptor at the front.

Split text file into smaller multiple text file using command line

here is one in c# that doesn't run out of memory when splitting into large chunks! I needed to split 95M file into 10M x line files.

var fileSuffix = 0;
int lines = 0;
Stream fstream = File.OpenWrite($"{filename}.{(++fileSuffix)}");
StreamWriter sw = new StreamWriter(fstream);

using (var file = File.OpenRead(filename))
using (var reader = new StreamReader(file))
{
    while (!reader.EndOfStream)
    {
        sw.WriteLine(reader.ReadLine());
        lines++;

        if (lines >= 10000000)
        {
              sw.Close();
              fstream.Close();
              lines = 0;
              fstream = File.OpenWrite($"{filename}.{(++fileSuffix)}");
              sw = new StreamWriter(fstream);
        }
    }
}

sw.Close();
fstream.Close();

When should an IllegalArgumentException be thrown?

Treat IllegalArgumentException as a preconditions check, and consider the design principle: A public method should both know and publicly document its own preconditions.

I would agree this example is correct:

void setPercentage(int pct) {
    if( pct < 0 || pct > 100) {
         throw new IllegalArgumentException("bad percent");
     }
}

If EmailUtil is opaque, meaning there's some reason the preconditions cannot be described to the end-user, then a checked exception is correct. The second version, corrected for this design:

import com.someoneelse.EmailUtil;

public void scanEmail(String emailStr, InputStream mime) throws ParseException {
    EmailAddress parsedAddress = EmailUtil.parseAddress(emailStr);
}

If EmailUtil is transparent, for instance maybe it's a private method owned by the class under question, IllegalArgumentException is correct if and only if its preconditions can be described in the function documentation. This is a correct version as well:

/** @param String email An email with an address in the form [email protected]
 * with no nested comments, periods or other nonsense.
 */
public String scanEmail(String email)
  if (!addressIsProperlyFormatted(email)) {
      throw new IllegalArgumentException("invalid address");
  }
  return parseEmail(emailAddr);
}
private String parseEmail(String emailS) {
  // Assumes email is valid
  boolean parsesJustFine = true;
  // Parse logic
  if (!parsesJustFine) {
    // As a private method it is an internal error if address is improperly
    // formatted. This is an internal error to the class implementation.
    throw new AssertError("Internal error");
  }
}

This design could go either way.

  • If preconditions are expensive to describe, or if the class is intended to be used by clients who don't know whether their emails are valid, then use ParseException. The top level method here is named scanEmail which hints the end user intends to send unstudied email through so this is likely correct.
  • If preconditions can be described in function documentation, and the class does not intent for invalid input and therefore programmer error is indicated, use IllegalArgumentException. Although not "checked" the "check" moves to the Javadoc documenting the function, which the client is expected to adhere to. IllegalArgumentException where the client can't tell their argument is illegal beforehand is wrong.

A note on IllegalStateException: This means "this object's internal state (private instance variables) is not able to perform this action." The end user cannot see private state so loosely speaking it takes precedence over IllegalArgumentException in the case where the client call has no way to know the object's state is inconsistent. I don't have a good explanation when it's preferred over checked exceptions, although things like initializing twice, or losing a database connection that isn't recovered, are examples.

How to output JavaScript with PHP

Another option is to do like this:

<html>
    <body>
    <?php
    //...php code...  
    ?>
    <script type="text/javascript">
        document.write("Hello World!");
    </script>
    <?php
    //....php code...
    ?>
    </body>
</html>

and if you want to use PHP inside your JavaScript, do like this:

<html>
    <body>
    <?php
        $text = "Hello World!";
    ?>
    <script type="text/javascript">
        document.write("<?php echo $text ?>");
    </script>
    <?php
    //....php code...
    ?>
    </body>
</html>

Hope this can help.

Wait one second in running program

Busy waiting won't be a severe drawback if it is short. In my case there was the need to give visual feedback to the user by flashing a control (it is a chart control that can be copied to clipboard, which changes its background for some milliseconds). It works fine this way:

using System.Threading;
...
Clipboard.SetImage(bm);   // some code
distribution_chart.BackColor = Color.Gray;
Application.DoEvents();   // ensure repaint, may be not needed
Thread.Sleep(50);
distribution_chart.BackColor = Color.OldLace;
....

Plot a horizontal line using matplotlib

A nice and easy way for those people who always forget the command axhline is the following

plt.plot(x, [y]*len(x))

In your case xs = x and y = 40. If len(x) is large, then this becomes inefficient and you should really use axhline.

How to execute only one test spec with angular-cli

In a bash terminal I like to use the double dash. Using VS Code, you can right click on the spec file in the explorer, or on the open tab. Then select 'Copy Relative Path'. Run the command below pasting the relative path in from the clipboard.

npm t -- --include relative/path/to/file.spec.ts

The double dash signals the end of your command options for npm t and passes anything after that to the next command which is pointing to ng t. It's doesn't require any modification and quickly gives desired results.

How to get table cells evenly spaced?

You can use CSS. One way is to set table-layout to fixed, which stops the table and it's children from sizing according to their content. You can then set a fixed width on the relevant td elements. This should do the trick:

table.PerformanceTable {
    table-layout: fixed;
    width: 500px;
}
    table.PerformanceTable td.PerformanceCell {
        width: 75px;
    }

Suggestions for for tidying up? You don't need the cellpadding or cellspacing attributes, or the TableRow and TableHeader classes. You can cover those off in CSS:

table {
    /* cellspacing */
    border-collapse: collapse;
    border-spacing: 0;
}
th {
    /* This covers the th elements */
}
tr {
    /* This covers the tr elements */
}
th, td {
    /* cellpadding */
    padding: 0;
}

You should use a heading (e.g. <h2>) instead of <span class="Emphasis"> and a <p> or a table <caption> instead of the Source <span>. You wouldn't need the <br> elements either, because you'd be using proper block level elements.

Convert Array to Object

Use the javascript lodash library. There is a simple method _.mapKeys(object, [iteratee=_.identity]) that can do the conversion.

Creating a UIImage from a UIColor to use as a background image for UIButton

CGContextSetFillColorWithColor(context,[[UIColor colorWithRed:(255/255.f) green:(0/255.f) blue: (0/255.f) alpha:1] CGColor]);

Possible to make labels appear when hovering over a point in matplotlib?

showing object information in matplotlib statusbar

enter image description here

Features

  • no extra libraries needed
  • clean plot
  • no overlap of labels and artists
  • supports multi artist labeling
  • can handle artists from different plotting calls (like scatter, plot, add_patch)
  • code in library style

Code

### imports
import matplotlib as mpl
import matplotlib.pylab as plt
import numpy as np


# https://stackoverflow.com/a/47166787/7128154
# https://matplotlib.org/3.3.3/api/collections_api.html#matplotlib.collections.PathCollection
# https://matplotlib.org/3.3.3/api/path_api.html#matplotlib.path.Path
# https://stackoverflow.com/questions/15876011/add-information-to-matplotlib-navigation-toolbar-status-bar
# https://stackoverflow.com/questions/36730261/matplotlib-path-contains-point
# https://stackoverflow.com/a/36335048/7128154
class StatusbarHoverManager:
    """
    Manage hover information for mpl.axes.Axes object based on appearing
    artists.

    Attributes
    ----------
    ax : mpl.axes.Axes
        subplot to show status information
    artists : list of mpl.artist.Artist
        elements on the subplot, which react to mouse over
    labels : list (list of strings) or strings
        each element on the top level corresponds to an artist.
        if the artist has items
        (i.e. second return value of contains() has key 'ind'),
        the element has to be of type list.
        otherwise the element if of type string
    cid : to reconnect motion_notify_event
    """
    def __init__(self, ax):
        assert isinstance(ax, mpl.axes.Axes)


        def hover(event):
            if event.inaxes != ax:
                return
            info = 'x={:.2f}, y={:.2f}'.format(event.xdata, event.ydata)
            ax.format_coord = lambda x, y: info
        cid = ax.figure.canvas.mpl_connect("motion_notify_event", hover)

        self.ax = ax
        self.cid = cid
        self.artists = []
        self.labels = []

    def add_artist_labels(self, artist, label):
        if isinstance(artist, list):
            assert len(artist) == 1
            artist = artist[0]

        self.artists += [artist]
        self.labels += [label]

        def hover(event):
            if event.inaxes != self.ax:
                return
            info = 'x={:.2f}, y={:.2f}'.format(event.xdata, event.ydata)
            for aa, artist in enumerate(self.artists):
                cont, dct = artist.contains(event)
                if not cont:
                    continue
                inds = dct.get('ind')
                if inds is not None:  # artist contains items
                    for ii in inds:
                        lbl = self.labels[aa][ii]
                        info += ';   artist [{:d}, {:d}]: {:}'.format(
                            aa, ii, lbl)
                else:
                    lbl = self.labels[aa]
                    info += ';   artist [{:d}]: {:}'.format(aa, lbl)
            self.ax.format_coord = lambda x, y: info

        self.ax.figure.canvas.mpl_disconnect(self.cid)
        self.cid = self.ax.figure.canvas.mpl_connect(
            "motion_notify_event", hover)



def demo_StatusbarHoverManager():
    fig, ax = plt.subplots()
    shm = StatusbarHoverManager(ax)

    poly = mpl.patches.Polygon(
        [[0,0], [3, 5], [5, 4], [6,1]], closed=True, color='green', zorder=0)
    artist = ax.add_patch(poly)
    shm.add_artist_labels(artist, 'polygon')

    artist = ax.scatter([2.5, 1, 2, 3], [6, 1, 1, 7], c='blue', s=10**2)
    lbls = ['point ' + str(ii) for ii in range(4)]
    shm.add_artist_labels(artist, lbls)

    artist = ax.plot(
        [0, 0, 1, 5, 3], [0, 1, 1, 0, 2], marker='o', color='red')
    lbls = ['segment ' + str(ii) for ii in range(5)]
    shm.add_artist_labels(artist, lbls)

    plt.show()


# --- main
if __name__== "__main__":
    demo_StatusbarHoverManager()

How to change a PG column to NULLABLE TRUE?

From the fine manual:

ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;

There's no need to specify the type when you're just changing the nullability.

Could not resolve Spring property placeholder

Your property file location is classpath:idm.properties

This is rather unusual, it means that idm.properties must be located either at the top level of WEB-INF/classes or at the top-level of one of the jars inside WEB-INF/lib. Usually it's good practice to either use a dedicated folder for properties or keep them close to the context files that use them.

So my suggestion is this: Is your properties file perhaps next to your context file? If so, it's not on the classpath (see this question: Is WEB-INF in the CLASSPATH?).

The classpath: prefix maps to a ClassPathResource, but you probably need a ServletContextResource, and you'll get that from a WebApplicationContext using the syntax without prefix:

<context:property-placeholder location="idm.properties" />

Reference:

UTF-8 text is garbled when form is posted as multipart/form-data

In case someone stumbled upon this problem when working on Grails (or pure Spring) web application, here is the post that helped me:

http://forum.spring.io/forum/spring-projects/web/2491-solved-character-encoding-and-multipart-forms

To set default encoding to UTF-8 (instead of the ISO-8859-1) for multipart requests, I added the following code in resources.groovy (Spring DSL):

multipartResolver(ContentLengthAwareCommonsMultipartResolver) {
    defaultEncoding = 'UTF-8'
}

Changing route doesn't scroll to top in the new page

I have finally gotten what I needed.

I needed to scroll to the top, but wanted some transitions not to

You can control this on a route-by-route level.
I'm combining the above solution by @wkonkel and adding a simple noScroll: true parameter to some route declarations. Then I'm catching that in the transition.

All in all: This floats to the top of the page on new transitions, it doesn't float to the top on Forward / Back transitions, and it allows you to override this behavior if necessary.

The code: (previous solution plus an extra noScroll option)

  // hack to scroll to top when navigating to new URLS but not back/forward
  let wrap = function(method) {
    let orig = $window.window.history[method];
    $window.window.history[method] = function() {
      let retval = orig.apply(this, Array.prototype.slice.call(arguments));
      if($state.current && $state.current.noScroll) {
        return retval;
      }
      $anchorScroll();
      return retval;
    };
  };
  wrap('pushState');
  wrap('replaceState');

Put that in your app.run block and inject $state... myApp.run(function($state){...})

Then, If you don't want to scroll to the top of the page, create a route like this:

.state('someState', {
  parent: 'someParent',
  url: 'someUrl',
  noScroll : true // Notice this parameter here!
})

Command line: search and replace in all filenames matched by grep

This appears to be what you want, based on the example you gave:

sed -i 's/foo/bar/g' *

It is not recursive (it will not descend into subdirectories). For a nice solution replacing in selected files throughout a tree I would use find:

find . -name '*.html' -print -exec sed -i.bak 's/foo/bar/g' {} \;

The *.html is the expression that files must match, the .bak after the -i makes a copy of the original file, with a .bak extension (it can be any extension you like) and the g at the end of the sed expression tells sed to replace multiple copies on one line (rather than only the first one). The -print to find is a convenience to show which files were being matched. All this depends on the exact versions of these tools on your system.

jQuery fade out then fade in

With async functions and promises, it now can work as simply as this:

async function foobar() {
  await $("#example").fadeOut().promise();
  doSomethingElse();
  await $("#example").fadeIn().promise();
}

How to change password using TortoiseSVN?

Password changes are handled by the subversion server administrator. As a user there is no password change option.

Check with your server admin.

If you are the admin, find your SVN Server installation. If you don't know where it is, it could be listed in Start->Programs, running under services in Start->Control Panel->Services or it could be listed under C:\Program Files.

The SVN Server should have an application to run to add/change/delete authentication and users.

How to use google maps without api key

Hey You can Use this insted

<iframe width="100%" height="100%" class="absolute inset-0" frameborder="0" title="map" marginheight="0" marginwidth="0" scrolling="no" src="https://maps.google.com/maps?width=100%&amp;height=600&amp;hl=en&amp;q=%C4%B0ikaneir+(Mumma's%20Bakery)&amp;ie=UTF8&amp;t=&amp;z=14&amp;iwloc=B&amp;output=embed" style="filter: scale(100) contrast(1.2) opacity(0.4);"></iframe>

HTML character codes for this ? or this ?

I usually use the excellent Gucharmap to look up Unicode characters. It's installed on all recent Linux installations with Gnome under the name "Character Map". I don't know of any equivalent tools for Windows or Mac OS X, but its homepage lists a few.

How to fix error "Updating Maven Project". Unsupported IClasspathEntry kind=4?

Before importing the project, it should be converted into eclipse project mvn eclipse: eclipse Then i found the following error. An internal error occurred during: "Importing Maven projects".Unsupported IClasspathEntry kind=4

Where is the value kind = "var" that M2E does not recognize and therefore throws the error.

Now type this. mvn eclipse: clean

Now refresh the project in eclipse or re-import.

If list index exists, do X

Oneliner:

do_X() if len(your_list) > your_index else do_something_else()  

Full example:

In [10]: def do_X(): 
    ...:     print(1) 
    ...:                                                                                                                                                                                                                                      

In [11]: def do_something_else(): 
    ...:     print(2) 
    ...:                                                                                                                                                                                                                                      

In [12]: your_index = 2                                                                                                                                                                                                                       

In [13]: your_list = [1,2,3]                                                                                                                                                                                                                  

In [14]: do_X() if len(your_list) > your_index else do_something_else()                                                                                                                                                                      
1

Just for info. Imho, try ... except IndexError is better solution.

Get value from SimpleXMLElement Object

This is the function that has always helped me convert the xml related values to array

function _xml2array ( $xmlObject, $out = array () ){
    foreach ( (array) $xmlObject as $index => $node )
        $out[$index] = ( is_object ( $node ) ) ? _xml2array ( $node ) : $node;

    return $out;
}

Break string into list of characters in Python

I'm a bit late it seems to be, but...

a='hello'
print list(a)
# ['h','e','l','l', 'o']

Setup a Git server with msysgit on Windows

Bonobo Git Server for Windows

From the Bonobo Git Server web page:

Bonobo Git Server for Windows is a web application you can install on your IIS and easily manage and connect to your git repositories.

Bonobo Git Server is a open-source project and you can find the source on github.

Features:

  • Secure and anonymous access to your git repositories
  • User friendly web interface for management
  • User and team based repository access management
  • Repository file browser
  • Commit browser
  • Localization

Brad Kingsley has a nice tutorial for installing and configuring Bonobo Git Server.

GitStack

Git Stack is another option. Here is a description from their web site:

GitStack is a software that lets you setup your own private Git server for Windows. This means that you create a leading edge versioning system without any prior Git knowledge. GitStack also makes it super easy to secure and keep your server up to date. GitStack is built on the top of the genuine Git for Windows and is compatible with any other Git clients. GitStack is completely free for small teams1.

1 the basic edition is free for up to 2 users

Syntax for a for loop in ruby

To iterate a loop a fixed number of times, try:

n.times do
  #Something to be done n times
end

How can I download a specific Maven artifact in one command line?

To copy artifact in specified location use copy instead of get.

mvn org.apache.maven.plugins:maven-dependency-plugin:3.1.2:copy \
  -DrepoUrl=someRepositoryUrl \
  -Dartifact="com.acme:foo:RELEASE:jar" -Dmdep.stripVersion -DoutputDirectory=/tmp/

d3.select("#element") not working when code above the html element

<script>$(function(){var svg = d3.select("#chart").append("svg:svg");});</script>
<div id="chart"></div>

In other words, it's not happening because you can't query against something that doesn't exist yet-- so just do it after the page loads (here via jquery).

Btw, its recommended that you place your JS files before the close of your body tag.

What are the best use cases for Akka framework

Disclaimer: I am the PO for Akka

Besides offering a concurrency smorgasbord that is much simpler to reason about and to get correct (actors, agents, dataflow concurrency) and with concurrency control in the form of STM.

Here are some use-cases you might consider:

  1. Transaction processing (online gaming, finance, statistics, betting, social media, telecom, ...)
    • scale up, scale out, fault-tolerance / HA
  2. Service backend (any industry, any app)
    • service REST, SOAP, cometd etc
    • act as message hub / integration layer
    • scale up, scale out, fault-tolerance / HA
  3. Snap-in concurrency/parallelism ( any app )
    • Correct
    • Simple to work with and understand
    • Just add the jars to your existing JVM project (use Scala, Java, Groovy or JRuby)
  4. Batch processing ( any industry )
    • Camel integration to hook up with batch data sources
    • Actors divide and conquer the batch workloads
  5. Communications hub ( telecom, web media, mobile media )
    • scale up, scale out, fault-tolerance / HA
  6. Game server (online gaming, betting)
    • scale up, scale out, fault-tolerance / HA
  7. BI/datamining/general purpose crunching
    • scale up, scale out, fault-tolerance / HA
  8. insert other nice use cases here

Android Studio not showing modules in project structure

Update 19 March 2019

A new experience someone has just faced recently even though he/she did add a library module in app module, and include in Setting gradle as described below. One more thing worth trying is to make sure your app module and your library module have the same compileSdkVersion (which is in each its gradle)!

Please follow this link for more details.

Ref: Imported module in Android Studio can't find imported class

Original answer

Sometimes you use import module function, then the module does appear in Project mode but not in Android mode

enter image description here

enter image description here So the thing works for me is to go to Setting gradle, add my module manually, and sync a gradle again:

enter image description here

Select the first row by group

A simple ddply option:

ddply(test,.(id),function(x) head(x,1))

If speed is an issue, a similar approach could be taken with data.table:

testd <- data.table(test)
setkey(testd,id)
testd[,.SD[1],by = key(testd)]

or this might be considerably faster:

testd[testd[, .I[1], by = key(testd]$V1]

Installing Google Protocol Buffers on mac

For v3 users.

http://google.github.io/proto-lens/installing-protoc.html

PROTOC_ZIP=protoc-3.7.1-osx-x86_64.zip
curl -OL https://github.com/protocolbuffers/protobuf/releases/download/v3.7.1/$PROTOC_ZIP
sudo unzip -o $PROTOC_ZIP -d /usr/local bin/protoc
sudo unzip -o $PROTOC_ZIP -d /usr/local 'include/*'
rm -f $PROTOC_ZIP

How can I save an image with PIL?

I know that this is old, but I've found that (while using Pillow) opening the file by using open(fp, 'w') and then saving the file will work. E.g:

with open(fp, 'w') as f:
    result.save(f)

fp being the file path, of course.

React Native - Image Require Module using Dynamic Names

First, create a file with image required - React native images must be loaded this way.

assets/index.js

export const friendsandfoe = require('./friends-and-foe.png'); 
export const lifeanddeath = require('./life-and-death.png'); 
export const homeandgarden = require('./home-and-garden.png');

Now import all your assets

App.js

import * as All  from '../../assets';

You can now use your image as an interpolated value where imageValue (coming in from backend) is the same as named local file ie: 'homeandgarden':

<Image style={styles.image} source={All[`${imageValue}`]}></Image>

libstdc++.so.6: cannot open shared object file: No such file or directory

/usr/local/cilk/bin/../lib32/pinbin is dynamically linked to a library libstdc++.so.6 which is not present anymore. You need to recompile Cilk

What is a "cache-friendly" code?

It needs to be clarified that not only data should be cache-friendly, it is just as important for the code. This is in addition to branch predicition, instruction reordering, avoiding actual divisions and other techniques.

Typically the denser the code, the fewer cache lines will be required to store it. This results in more cache lines being available for data.

The code should not call functions all over the place as they typically will require one or more cache lines of their own, resulting in fewer cache lines for data.

A function should begin at a cache line-alignment-friendly address. Though there are (gcc) compiler switches for this be aware that if the the functions are very short it might be wasteful for each one to occupy an entire cache line. For example, if three of the most often used functions fit inside one 64 byte cache line, this is less wasteful than if each one has its own line and results in two cache lines less available for other usage. A typical alignment value could be 32 or 16.

So spend some extra time to make the code dense. Test different constructs, compile and review the generated code size and profile.

How do I add a submodule to a sub-directory?

For those of you who share my weird fondness of manually editing config files, adding (or modifying) the following would also do the trick.

.git/config (personal config)

[submodule "cookbooks/apt"]
    url = https://github.com/opscode-cookbooks/apt

.gitmodules (committed shared config)

[submodule "cookbooks/apt"]
    path = cookbooks/apt
    url = https://github.com/opscode-cookbooks/apt

See this as well - difference between .gitmodules and specifying submodules in .git/config?

Exporting the values in List to excel

the one easy way to do it is to open Excel create sheet containing test data you want to export then say to excel save as xml open the xml see the xml format excel is expecting and generate it by head replacing the test data with export data

SpreadsheetML Markup Spec

@lan this is xml fo a simle execel file with one column value i genereted with office 2003 this format is for office 2003 and above

<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:o="urn:schemas-microsoft-com:office:office"
 xmlns:x="urn:schemas-microsoft-com:office:excel"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:html="http://www.w3.org/TR/REC-html40">
 <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
  <Author>Dancho</Author>
  <LastAuthor>Dancho</LastAuthor>
  <Created>2010-02-05T10:15:54Z</Created>
  <Company>cc</Company>
  <Version>11.9999</Version>
 </DocumentProperties>
 <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
  <WindowHeight>13800</WindowHeight>
  <WindowWidth>24795</WindowWidth>
  <WindowTopX>480</WindowTopX>
  <WindowTopY>105</WindowTopY>
  <ProtectStructure>False</ProtectStructure>
  <ProtectWindows>False</ProtectWindows>
 </ExcelWorkbook>
 <Styles>
  <Style ss:ID="Default" ss:Name="Normal">
   <Alignment ss:Vertical="Bottom"/>
   <Borders/>
   <Font/>
   <Interior/>
   <NumberFormat/>
   <Protection/>
  </Style>
 </Styles>
 <Worksheet ss:Name="Sheet1">
  <Table ss:ExpandedColumnCount="1" ss:ExpandedRowCount="6" x:FullColumns="1"
   x:FullRows="1">
   <Row>
    <Cell><Data ss:Type="String">Value1</Data></Cell>
   </Row>
   <Row>
    <Cell><Data ss:Type="String">Value2</Data></Cell>
   </Row>
   <Row>
    <Cell><Data ss:Type="String">Value3</Data></Cell>
   </Row>
   <Row>
    <Cell><Data ss:Type="String">Value4</Data></Cell>
   </Row>
   <Row>
    <Cell><Data ss:Type="String">Value5</Data></Cell>
   </Row>
   <Row>
    <Cell><Data ss:Type="String">Value6</Data></Cell>
   </Row>
  </Table>
  <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
   <Selected/>
   <Panes>
    <Pane>
     <Number>3</Number>
     <ActiveRow>5</ActiveRow>
    </Pane>
   </Panes>
   <ProtectObjects>False</ProtectObjects>
   <ProtectScenarios>False</ProtectScenarios>
  </WorksheetOptions>
 </Worksheet>
 <Worksheet ss:Name="Sheet2">
  <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
   <ProtectObjects>False</ProtectObjects>
   <ProtectScenarios>False</ProtectScenarios>
  </WorksheetOptions>
 </Worksheet>
 <Worksheet ss:Name="Sheet3">
  <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
   <ProtectObjects>False</ProtectObjects>
   <ProtectScenarios>False</ProtectScenarios>
  </WorksheetOptions>
 </Worksheet>
</Workbook>

Calling variable defined inside one function from another function

Yes, you should think of defining both your functions in a Class, and making word a member. This is cleaner :

class Spam:
    def oneFunction(self,lists):
        category=random.choice(list(lists.keys()))
        self.word=random.choice(lists[category])

    def anotherFunction(self):
        for letter in self.word:              
            print("_", end=" ")

Once you make a Class you have to Instantiate it to an Object and access the member functions

s = Spam()
s.oneFunction(lists)
s.anotherFunction()

Another approach would be to make oneFunction return the word so that you can use oneFunction instead of word in anotherFunction

>>> def oneFunction(lists):
        category=random.choice(list(lists.keys()))
        return random.choice(lists[category])

    
>>> def anotherFunction():
        for letter in oneFunction(lists):              
            print("_", end=" ")

And finally, you can also make anotherFunction, accept word as a parameter which you can pass from the result of calling oneFunction

>>> def anotherFunction(words):
        for letter in words:              
            print("_",end=" ")
>>> anotherFunction(oneFunction(lists))

How to apply bold text style for an entire row using Apache POI?

A worked, completed and simple example:

package io.github.baijifeilong.excel;

import lombok.SneakyThrows;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;

/**
 * Created by [email protected] at 2019/12/6 11:41
 */
public class ExcelBoldTextDemo {

    @SneakyThrows
    public static void main(String[] args) {

        new XSSFWorkbook() {{
            XSSFRow row = createSheet().createRow(0);
            row.setRowStyle(createCellStyle());
            row.getRowStyle().getFont().setBold(true);
            row.createCell(0).setCellValue("Alpha");
            row.createCell(1).setCellValue("Beta");
            row.createCell(2).setCellValue("Gamma");
        }}.write(new FileOutputStream("demo.xlsx"));
    }
}

Hide particular div onload and then show div after click

The second time you're referring to div2, you're not using the # id selector.

There's no element named div2.

How to convert ASCII code (0-255) to its corresponding character?

This is an example, which shows that by converting an int to char, one can determine the corresponding character to an ASCII code.

public class sample6
{
    public static void main(String... asf)
    {

        for(int i =0; i<256; i++)
        {
            System.out.println( i + ". " + (char)i);
        }
    }
}

What is HTTP "Host" header?

The Host Header tells the webserver which virtual host to use (if set up). You can even have the same virtual host using several aliases (= domains and wildcard-domains). In this case, you still have the possibility to read that header manually in your web app if you want to provide different behavior based on different domains addressed. This is possible because in your webserver you can (and if I'm not mistaken you must) set up one vhost to be the default host. This default vhost is used whenever the host header does not match any of the configured virtual hosts.

That means: You get it right, although saying "multiple hosts" may be somewhat misleading: The host (the addressed machine) is the same, what really gets resolved to the IP address are different domain names (including subdomains) that are also referred to as hostnames (but not hosts!).


Although not part of the question, a fun fact: This specification led to problems with SSL in early days because the web server has to deliver the certificate that corresponds to the domain the client has addressed. However, in order to know what certificate to use, the webserver should have known the addressed hostname in advance. But because the client sends that information only over the encrypted channel (which means: after the certificate has already been sent), the server had to assume you browsed the default host. That meant one ssl-secured domain per IP address / port-combination.

This has been overcome with Server Name Indication; however, that again breaks some privacy, as the server name is now transferred in plain text again, so every man-in-the-middle would see which hostname you are trying to connect to.

Although the webserver would know the hostname from Server Name Indication, the Host header is not obsolete, because the Server Name Indication information is only used within the TLS handshake. With an unsecured connection, there is no Server Name Indication at all, so the Host header is still valid (and necessary).

Another fun fact: Most webservers (if not all) reject your HTTP request if it does not contain exactly one Host header, even if it could be omitted because there is only the default vhost configured. That means the minimum required information in an http-(get-)request is the first line containing METHOD RESOURCE and PROTOCOL VERSION and at least the Host header, like this:

GET /someresource.html HTTP/1.1
Host: www.example.com

In the MDN Documentation on the "Host" header they actually phrase it like this:

A Host header field must be sent in all HTTP/1.1 request messages. A 400 (Bad Request) status code will be sent to any HTTP/1.1 request message that lacks a Host header field or contains more than one.

As mentioned by Darrel Miller, the complete specs can be found in RFC7230.

How to include Authorization header in cURL POST HTTP Request in PHP?

You have most of the code…

CURLOPT_HTTPHEADER for curl_setopt() takes an array with each header as an element. You have one element with multiple headers.

You also need to add the Authorization header to your $header array.

$header = array();
$header[] = 'Content-length: 0';
$header[] = 'Content-type: application/json';
$header[] = 'Authorization: OAuth SomeHugeOAuthaccess_tokenThatIReceivedAsAString';

How do you open a file in C++?

#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream file;
  file.open ("codebind.txt");
  file << "Please writr this text to a file.\n this text is written using C++\n";
  file.close();
  return 0;
}

How do I get whole and fractional parts from double in JSP/Java?

The mantissa and exponent of an IEEE double floating point number are the values such that

value = sign * (1 + mantissa) * pow(2, exponent)

if the mantissa is of the form 0.101010101_base 2 (ie its most sigificant bit is shifted to be after the binary point) and the exponent is adjusted for bias.

Since 1.6, java.lang.Math also provides a direct method to get the unbiased exponent (called getExponent(double))

However, the numbers you're asking for are the integral and fractional parts of the number, which can be obtained using

integral = Math.floor(x)
fractional = x - Math.floor(x)

though you may you want to treat negative numbers differently (floor(-3.5) == -4.0), depending why you want the two parts.

I'd strongly suggest that you don't call these mantissa and exponent.

How to find out whether a file is at its `eof`?

read returns an empty string when EOF is encountered. Docs are here.

How to print object array in JavaScript?

If you are using Chrome, you could also use

console.log( yourArray );

How to write inside a DIV box with javascript

HTML:

<div id="log"></div>

JS:

document.getElementById("log").innerHTML="WHATEVER YOU WANT...";

What is the difference between json.dump() and json.dumps() in python?

In memory usage and speed.

When you call jsonstr = json.dumps(mydata) it first creates a full copy of your data in memory and only then you file.write(jsonstr) it to disk. So this is a faster method but can be a problem if you have a big piece of data to save.

When you call json.dump(mydata, file) -- without 's', new memory is not used, as the data is dumped by chunks. But the whole process is about 2 times slower.

Source: I checked the source code of json.dump() and json.dumps() and also tested both the variants measuring the time with time.time() and watching the memory usage in htop.

How to recursively list all the files in a directory in C#?

To avoid the UnauthorizedAccessException, I use:

var files = GetFiles(@"C:\", "*.*", SearchOption.AllDirectories);
foreach (var file in files)
{
    Console.WriteLine($"{file}");
}

public static IEnumerable<string> GetFiles(string path, string searchPattern, SearchOption searchOption)
{
    var foldersToProcess = new List<string>()
    {
        path
    };

    while (foldersToProcess.Count > 0)
    {
        string folder = foldersToProcess[0];
        foldersToProcess.RemoveAt(0);

        if (searchOption.HasFlag(SearchOption.AllDirectories))
        {
            //get subfolders
            try
            {
                var subfolders = Directory.GetDirectories(folder);
                foldersToProcess.AddRange(subfolders);
            }
            catch (Exception ex)
            {
                //log if you're interested
            }
        }

        //get files
        var files = new List<string>();
        try
        {
            files = Directory.GetFiles(folder, searchPattern, SearchOption.TopDirectoryOnly).ToList();
        }
        catch (Exception ex)
        {
            //log if you're interested
        }

        foreach (var file in files)
        {
            yield return file;
        }
    }
}

string.IsNullOrEmpty(string) vs. string.IsNullOrWhiteSpace(string)

Check this out with IsNullOrEmpty and IsNullOrwhiteSpace

string sTestes = "I like sweat peaches";
    Stopwatch stopWatch = new Stopwatch();
    stopWatch.Start();
    for (int i = 0; i < 5000000; i++)
    {
        for (int z = 0; z < 500; z++)
        {
            var x = string.IsNullOrEmpty(sTestes);// OR string.IsNullOrWhiteSpace
        }
    }

    stopWatch.Stop();
    // Get the elapsed time as a TimeSpan value.
    TimeSpan ts = stopWatch.Elapsed;
    // Format and display the TimeSpan value. 
    string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
        ts.Hours, ts.Minutes, ts.Seconds,
        ts.Milliseconds / 10);
    Console.WriteLine("RunTime " + elapsedTime);
    Console.ReadLine();

You'll see that IsNullOrWhiteSpace is much slower :/

How to upload & Save Files with Desired name

This would work very well -- You can use HTML5 to allow only image files to be uploaded. This is the code for uploader.htm --

<html>    
    <head>
        <script>
            function validateForm(){
                var image = document.getElementById("image").value;
                var name = document.getElementById("name").value;
                if (image =='')
                {
                    return false;
                }
                if(name =='')
                {
                    return false;
                } 
                else 
                {
                    return true;
                } 
                return false;
            }
        </script>
    </head>

    <body>
        <form method="post" action="upload.php" enctype="multipart/form-data">
            <input type="text" name="ext" size="30"/>
            <input type="text" name="name" id="name" size="30"/>
            <input type="file" accept="image/*" name="image" id="image" />
            <input type="submit" value='Save' onclick="return validateForm()"/>
        </form>
    </body>
</html>

Now the code for upload.php --

<?php  
$name = $_POST['name'];
$ext = $_POST['ext'];
if (isset($_FILES['image']['name']))
{
    $saveto = "$name.$ext";
    move_uploaded_file($_FILES['image']['tmp_name'], $saveto);
    $typeok = TRUE;
    switch($_FILES['image']['type'])
    {
        case "image/gif": $src = imagecreatefromgif($saveto); break;
        case "image/jpeg": // Both regular and progressive jpegs
        case "image/pjpeg": $src = imagecreatefromjpeg($saveto); break;
        case "image/png": $src = imagecreatefrompng($saveto); break;
        default: $typeok = FALSE; break;
    }
    if ($typeok)
    {
        list($w, $h) = getimagesize($saveto);
        $max = 100;
        $tw = $w;
        $th = $h;
        if ($w > $h && $max < $w)
        {
            $th = $max / $w * $h;
            $tw = $max;
        }
        elseif ($h > $w && $max < $h)
        {
            $tw = $max / $h * $w;
            $th = $max;
        }
        elseif ($max < $w)
        {
            $tw = $th = $max;
        }

        $tmp = imagecreatetruecolor($tw, $th);      
        imagecopyresampled($tmp, $src, 0, 0, 0, 0, $tw, $th, $w, $h);
        imageconvolution($tmp, array( // Sharpen image
            array(-1, -1, -1),
            array(-1, 16, -1),
            array(-1, -1, -1)      
        ), 8, 0);
        imagejpeg($tmp, $saveto);
        imagedestroy($tmp);
        imagedestroy($src);
    }
}
?>

Exiting from python Command Line

This works for me, best way to come out of python prompt.

exit()

get value from DataTable

You can try changing it to this:

If myTableData.Rows.Count > 0 Then
  For i As Integer = 0 To myTableData.Rows.Count - 1
    ''Dim DataType() As String = myTableData.Rows(i).Item(1)
    ListBox2.Items.Add(myTableData.Rows(i)(1))
  Next
End If

Note: Your loop needs to be one less than the row count since it's a zero-based index.

Visual Studio breakpoints not being hit

In my case this solution is useful:

Solution: Disable the "Just My Code" option in the Debugging/General settings.

![enter image description here

Reference: c-sharpcorner

Android YouTube app Play Video Intent

This will work on a device but not the emulator per Lemmy's answer.

startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=cxLG2wtE7TM")));

ActiveXObject creation error " Automation server can't create object"

Well you can not run code from notepad so that means you are opening up the page from the file system. aka c:/foo/bar/hello.html

When you run the code from the asp.net page, you are running it from localhost. aka http://loalhost:1234/assdf.html

Each of these run in different security zones on IE.

What in layman's terms is a Recursive Function using PHP

It work a simple example recursive (Y)

<?php 


function factorial($y,$x) { 

    if ($y < $x) { 
        echo $y; 
    } else { 
        echo $x; 
        factorial($y,$x+1);
    } 
}

$y=10;

$x=0;
factorial($y,$x);

 ?>

XPath test if node value is number

Test the value against NaN:

<xsl:if test="string(number(myNode)) != 'NaN'">
    <!-- myNode is a number -->
</xsl:if>

This is a shorter version (thanks @Alejandro):

<xsl:if test="number(myNode) = myNode">
    <!-- myNode is a number -->
</xsl:if>

Android: Remove all the previous activities from the back stack

One possible solution what I can suggest you is to add android:launchMode="singleTop" in the manifest for my ProfileActivity. and when log out is clicked u can logoff starting again you LoginActivity. on logout u can call this.

Intent in = new Intent(Profile.this,Login.class);
                in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(in);
                finish();

Call-time pass-by-reference has been removed

Only call time pass-by-reference is removed. So change:

call_user_func($func, &$this, &$client ...

To this:

call_user_func($func, $this, $client ...

&$this should never be needed after PHP4 anyway period.

If you absolutely need $client to be passed by reference, update the function ($func) signature instead (function func(&$client) {)

socket connect() vs bind()

Too Long; Don't Read: The difference is whether the source (local) or the destination address/port is being set. In short, bind() set the source and connect() set the destination. Regardless of TCP or UDP.

bind()

bind() set the socket's local (source) address. This is the address where packets are received. Packets sent by the socket carry this as the source address, so the other host will know where to send back its packets.

If receive is not needed the socket source address is useless. Protocols like TCP require receiving enabled in order to send properly, as the destination host send back a confirmation when one or more packets have arrived (i.e. acknowledgement).

connect()

  • TCP has a "connected" state. connect() triggers the TCP code to try to establish a connection to the other side.
  • UDP has no "connected" state. connect() only set a default address to where packets are sent when no address is specified. When connect() is not used, sendto() or sendmsg() must be used containing the destination address.

When connect() or a send function is called, and no address is bound, Linux automatically bind the socket to a random port. For technical details, take a look at inet_autobind() in Linux kernel source code.

Side notes

  • listen() is TCP only.
  • In AF_INET family, the socket's source or destination address (struct sockaddr_in) is composed by an IP address (see IP header), and TCP or UDP port (see TCP and UDP header).

Encapsulation vs Abstraction?

Encapsulation protects to collapse the internal behaviour of object/instance from external entity. So, a control should be provided to confirm that the data which is being supplied is not going to harm the internal system of instance/object to survive its existance.

Good example, Divider is a class which has two instance variable dividend and divisor and a method getDividedValue.

Can you please think, if the divisor is set to 0 then internal system/behaviour (getDivided ) will break.

So, the object internal behaviour could be protected by throwing exception through a method.

How to get the browser viewport dimensions?

A solution that would conform to W3C standards would be to create a transparent div (for example dynamically with JavaScript), set its width and height to 100vw/100vh (Viewport units) and then get its offsetWidth and offsetHeight. After that, the element can be removed again. This will not work in older browsers because the viewport units are relatively new, but if you don't care about them but about (soon-to-be) standards instead, you could definitely go this way:

var objNode = document.createElement("div");
objNode.style.width  = "100vw";
objNode.style.height = "100vh";
document.body.appendChild(objNode);
var intViewportWidth  = objNode.offsetWidth;
var intViewportHeight = objNode.offsetHeight;
document.body.removeChild(objNode);

Of course, you could also set objNode.style.position = "fixed" and then use 100% as width/height - this should have the same effect and improve compatibility to some extent. Also, setting position to fixed might be a good idea in general, because otherwise the div will be invisible but consume some space, which will lead to scrollbars appearing etc.

Difference between onLoad and ng-init in angular

From angular's documentation,

ng-init SHOULD NOT be used for any initialization. It should be used only for aliasing. https://docs.angularjs.org/api/ng/directive/ngInit

onload should be used if any expression needs to be evaluated after a partial view is loaded (by ng-include). https://docs.angularjs.org/api/ng/directive/ngInclude

The major difference between them is when used with ng-include.

<div ng-include="partialViewUrl" onload="myFunction()"></div>

In this case, myFunction is called everytime the partial view is loaded.

<div ng-include="partialViewUrl" ng-init="myFunction()"></div>

Whereas, in this case, myFunction is called only once when the parent view is loaded.

Can someone explain how to append an element to an array in C programming?

You can have a counter (freePosition), which will track the next free place in an array of size n.

JavaScript/jQuery - "$ is not defined- $function()" error

Try:

(function($) {
    $(function() {
        $('.update').live('change', function() {
            formObject.run($(this));
        });
    });
})(jQuery);

By using this way you ensure the global variable jQuery will be bound to the "$" inside the closure. Just make sure jQuery is properly loaded into the page by inserting:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>

Replace "http://code.jquery.com/jquery-1.7.1.min.js" to the path where your jQuery source is located within the page context.

Wpf control size to content?

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

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

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

Passing variable from Form to Module in VBA

Don't declare the variable in the userform. Declare it as Public in the module.

Public pass As String

In the Userform

Private Sub CommandButton1_Click()
    pass = UserForm1.TextBox1
    Unload UserForm1
End Sub

In the Module

Public pass As String

Public Sub Login()
    '
    '~~> Rest of the code
    '
    UserForm1.Show
    driver.findElementByName("PASSWORD").SendKeys pass
    '
    '~~> Rest of the code
    '
End Sub

You might want to also add an additional check just before calling the driver.find... line?

If Len(Trim(pass)) <> 0 Then

This will ensure that a blank string is not passed.

python pandas: Remove duplicates by columns A, keeping the row with the highest value in column B

Easiest way to do this:

# First you need to sort this DF as Column A as ascending and column B as descending 
# Then you can drop the duplicate values in A column 
# Optional - you can reset the index and get the nice data frame again
# I'm going to show you all in one step. 

d = {'A': [1,1,2,3,1,2,3,1], 'B': [30, 40,50,42,38,30,25,32]}
df = pd.DataFrame(data=d)
df

    A   B
0   1   30
1   1   40
2   2   50
3   3   42
4   1   38
5   2   30
6   3   25
7   1   32


df = df.sort_values(['A','B'], ascending =[True,False]).drop_duplicates(['A']).reset_index(drop=True)

df

    A   B
0   1   40
1   2   50
2   3   42

How to hide underbar in EditText

You can set EditText's backgroundTint value to a specific color. If you set transparent color, underbar should gone.

android:backgroundTint="@color/Transparent"

<color name="Transparent">#00000000</color>

But you can use this in Api v21(Lollipop) or higher

How can I add a space in between two outputs?

Like this?

 System.out.println(Name + " " + Income);

Why do you create a View in a database?

Views also break down very complex configuration and tables into managable chunks that are easily queried against. In our database, our entire table managment system is broken down into views from one large table.

JPA OneToMany not deleting child

In addition to cletus' answer, JPA 2.0, final since december 2010, introduces an orphanRemoval attribute on @OneToMany annotations. For more details see this blog entry.

Note that since the spec is relatively new, not all JPA 1 provider have a final JPA 2 implementation. For example, the Hibernate 3.5.0-Beta-2 release does not yet support this attribute.

"register" keyword in C?

It hasn't been relevant for at least 15 years as optimizers make better decisions about this than you can. Even when it was relevant, it made a lot more sense on a CPU architecture with a lot of registers, like SPARC or M68000 than it did on Intel with its paucity of registers, most of which are reserved by the compiler for its own purposes.

How to split one string into multiple strings separated by at least one space in bash shell?

For checking spaces just with bash:

[[ "$str" = "${str% *}" ]] && echo "no spaces" || echo "has spaces"

How to list active connections on PostgreSQL?

Oh, I just found that command on PostgreSQL forum:

SELECT * FROM pg_stat_activity;

Is HTML considered a programming language?

On some level Chris Pietschmann is correct. SQL isn't Turing complete (at least without stored procedures) yet people will list that as a language, TeX is Turing complete but most people regard it as a markup language.

Having said that: if you are just applying for jobs, not arguing formal logic, I would just list them all as technologies. Things like .NET aren't languages but would probably be listed as well.

send mail to multiple receiver with HTML mailto

"There are no safe means of assigning multiple recipients to a single mailto: link via HTML. There are safe, non-HTML, ways of assigning multiple recipients from a mailto: link."

http://www.sightspecific.com/~mosh/www_faq/multrec.html

For a quick fix to your problem, change your ; to a comma , and eliminate the spaces between email addresses

<a href='mailto:[email protected],[email protected]'>Email Us</a>

Pure CSS animation visibility with delay

Use animation-delay:

div {
    width: 100px;
    height: 100px;
    background: red;
    opacity: 0;

    animation: fadeIn 3s;
    animation-delay: 5s;
    animation-fill-mode: forwards;
}

@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

Fiddle

Base64 encoding and decoding in client-side Javascript

Short and fast Base64 JavaScript Decode Function without Failsafe:

function decode_base64 (s)
{
    var e = {}, i, k, v = [], r = '', w = String.fromCharCode;
    var n = [[65, 91], [97, 123], [48, 58], [43, 44], [47, 48]];

    for (z in n)
    {
        for (i = n[z][0]; i < n[z][1]; i++)
        {
            v.push(w(i));
        }
    }
    for (i = 0; i < 64; i++)
    {
        e[v[i]] = i;
    }

    for (i = 0; i < s.length; i+=72)
    {
        var b = 0, c, x, l = 0, o = s.substring(i, i+72);
        for (x = 0; x < o.length; x++)
        {
            c = e[o.charAt(x)];
            b = (b << 6) + c;
            l += 6;
            while (l >= 8)
            {
                r += w((b >>> (l -= 8)) % 256);
            }
         }
    }
    return r;
}

Execute a terminal command from a Cocoa app

Custos Mortem said:

I'm surprised no one really got into blocking/non-blocking call issues

For blocking/non-blocking call issues regarding NSTask read below:

asynctask.m -- sample code that shows how to implement asynchronous stdin, stdout & stderr streams for processing data with NSTask

Source code of asynctask.m is available at GitHub.

INSERT VALUES WHERE NOT EXISTS

More of a comment link for suggested further reading...A really good blog article which benchmarks various ways of accomplishing this task can be found here.

They use a few techniques: "Insert Where Not Exists", "Merge" statement, "Insert Except", and your typical "left join" to see which way is the fastest to accomplish this task.

The example code used for each technique is as follows (straight copy/paste from their page) :

INSERT INTO #table1 (Id, guidd, TimeAdded, ExtraData)
SELECT Id, guidd, TimeAdded, ExtraData
FROM #table2
WHERE NOT EXISTS (Select Id, guidd From #table1 WHERE #table1.id = #table2.id)
-----------------------------------
MERGE #table1 as [Target]
USING  (select Id, guidd, TimeAdded, ExtraData from #table2) as [Source]
(id, guidd, TimeAdded, ExtraData)
    on [Target].id =[Source].id
WHEN NOT MATCHED THEN
    INSERT (id, guidd, TimeAdded, ExtraData)
    VALUES ([Source].id, [Source].guidd, [Source].TimeAdded, [Source].ExtraData);
------------------------------
INSERT INTO #table1 (id, guidd, TimeAdded, ExtraData)
SELECT id, guidd, TimeAdded, ExtraData from #table2
EXCEPT
SELECT id, guidd, TimeAdded, ExtraData from #table1
------------------------------
INSERT INTO #table1 (id, guidd, TimeAdded, ExtraData)
SELECT #table2.id, #table2.guidd, #table2.TimeAdded, #table2.ExtraData
FROM #table2
LEFT JOIN #table1 on #table1.id = #table2.id
WHERE #table1.id is null

It's a good read for those who are looking for speed! On SQL 2014, the Insert-Except method turned out to be the fastest for 50 million or more records.

WPF: ItemsControl with scrollbar (ScrollViewer)

You have to modify the control template instead of ItemsPanelTemplate:

<ItemsControl >
    <ItemsControl.Template>
        <ControlTemplate>
            <ScrollViewer x:Name="ScrollViewer" Padding="{TemplateBinding Padding}">
                <ItemsPresenter />
            </ScrollViewer>
        </ControlTemplate>
    </ItemsControl.Template>
</ItemsControl>

Maybe, your code does not working because StackPanel has own scrolling functionality. Try to use StackPanel.CanVerticallyScroll property.

Cleaning up old remote git branches

If git branch -r shows a lot of remote-tracking branches that you're not interested in and you want to remove them only from local, use the following command:

git branch -r | grep -Ev 'HEAD|master|develop'  | xargs -r git branch -rd

A safer version would be to only remove the merged ones:

git branch -r --merged | grep -Ev 'HEAD|master|develop'  | xargs -r git branch -rd

This might be useful for large projects, where you don't need the feature branches of other teammates but there're lots of remote-tracking branches fetched upon the initial clone.

However, this step alone is not sufficient, because those deleted remote-tracking branches would come back upon next git fetch.

To stop fetching those remote-tracking branches you need to explicitly specify the refs to fetch in .git/config:

[remote "origin"]
  # fetch = +refs/heads/*:refs/remotes/origin/*    ### don't fetch everything
  fetch = +refs/heads/master:refs/remotes/origin/master
  fetch = +refs/heads/develop:refs/remotes/origin/develop
  fetch = +refs/heads/release/*:refs/remotes/origin/release/*

In the above example we only fetch master, develop and release branches, feel free to adapt as you need.

Properly embedding Youtube video into bootstrap 3.0 page

It also depend on how you style your site with bootstrap. In my example, I am using col-md-12 for my video div, and add class col-sm-12 for the iframe, so when resize to smaller screen, the video will not view squeezed. I add also height to the iframe:

<div class="col-md-12">
<iframe class="col-sm-12" height="333" frameborder="0" wmode="Opaque" allowfullscreen="" src="https://www.youtube.com/embed/oqDRPoPDehE?wmode=transparent">
</div>

How to get current working directory in Java?

Use CodeSource#getLocation(). This works fine in JAR files as well. You can obtain CodeSource by ProtectionDomain#getCodeSource() and the ProtectionDomain in turn can be obtained by Class#getProtectionDomain().

public class Test {
    public static void main(String... args) throws Exception {
        URL location = Test.class.getProtectionDomain().getCodeSource().getLocation();
        System.out.println(location.getFile());
    }
}

Update as per the comment of the OP:

I want to dump a bunch of CSV files in a folder, have the program recognize all the files, then load the data and manipulate them. I really just want to know how to navigate to that folder.

That would require hardcoding/knowing their relative path in your program. Rather consider adding its path to the classpath so that you can use ClassLoader#getResource()

File classpathRoot = new File(classLoader.getResource("").getPath());
File[] csvFiles = classpathRoot.listFiles(new FilenameFilter() {
    @Override public boolean accept(File dir, String name) {
        return name.endsWith(".csv");
    }
});

Or to pass its path as main() argument.

Fatal error: Call to a member function prepare() on null

@delato468 comment must be listed as a solution as it worked for me.

In addition to defining the parameter, the user must pass it too at the time of calling the function

fetch_data(PDO $pdo, $cat_id)

Trying to use INNER JOIN and GROUP BY SQL with SUM Function, Not Working

Use subquery

SELECT * FROM RES_DATA inner join (SELECT [CUSTOMER ID], sum([TOTAL AMOUNT]) FROM INV_DATA group by [CUSTOMER ID]) T on RES_DATA.[CUSTOMER ID] = t.[CUSTOMER ID]

Create controller for partial view in ASP.NET MVC

Why not use Html.RenderAction()?

Then you could put the following into any controller (even creating a new controller for it):

[ChildActionOnly]
public ActionResult MyActionThatGeneratesAPartial(string parameter1)
{
    var model = repository.GetThingByParameter(parameter1);
    var partialViewModel = new PartialViewModel(model);
    return PartialView(partialViewModel); 
}

Then you could create a new partial view and have your PartialViewModel be what it inherits from.

For Razor, the code block in the view would look like this:

@{ Html.RenderAction("Index", "Home"); }

For the WebFormsViewEngine, it would look like this:

<% Html.RenderAction("Index", "Home"); %>

How to create named and latest tag in Docker?

Variation of Aaron's answer. Using sed without temporary files

#!/bin/bash
VERSION=1.0.0
IMAGE=company/image
ID=$(docker build  -t ${IMAGE}  .  | tail -1 | sed 's/.*Successfully built \(.*\)$/\1/')

docker tag ${ID} ${IMAGE}:${VERSION}
docker tag -f ${ID} ${IMAGE}:latest

How to format a URL to get a file from Amazon S3?

Perhaps not what the OP was after, but for those searching the URL to simply access a readable object on S3 is more like:

https://<region>.amazonaws.com/<bucket-name>/<key>

Where <region> is something like s3-ap-southeast-2.

Click on the item in the S3 GUI to get the link for your bucket.

Remove duplicates from a List<T> in C#

Another way in .Net 2.0

    static void Main(string[] args)
    {
        List<string> alpha = new List<string>();

        for(char a = 'a'; a <= 'd'; a++)
        {
            alpha.Add(a.ToString());
            alpha.Add(a.ToString());
        }

        Console.WriteLine("Data :");
        alpha.ForEach(delegate(string t) { Console.WriteLine(t); });

        alpha.ForEach(delegate (string v)
                          {
                              if (alpha.FindAll(delegate(string t) { return t == v; }).Count > 1)
                                  alpha.Remove(v);
                          });

        Console.WriteLine("Unique Result :");
        alpha.ForEach(delegate(string t) { Console.WriteLine(t);});
        Console.ReadKey();
    }

CSV with comma or semicolon?

In Windows it is dependent on the "Regional and Language Options" customize screen where you find a List separator. This is the char Windows applications expect to be the CSV separator.

Of course this only has effect in Windows applications, for example Excel will not automatically split data into columns if the file is not using the above mentioned separator. All applications that use Windows regional settings will have this behavior.

If you are writing a program for Windows that will require importing the CSV in other applications and you know that the list separator set for your target machines is ,, then go for it, otherwise I prefer ; since it causes less problems with decimal points, digit grouping and does not appear in much text.

How do I remove duplicates from a C# array?

Generic Extension method :

public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer)
{
    if (source == null)
        throw new ArgumentNullException(nameof(source));

    HashSet<TSource> set = new HashSet<TSource>(comparer);
    foreach (TSource item in source)
    {
        if (set.Add(item))
        {
            yield return item;
        }
    }
}

Execute CMD command from code

How about you creat a batch file with the command you want, and call it with Process.Start

dir.bat content:

dir

then call:

Process.Start("dir.bat");

Will call the bat file and execute the dir

How to get all the AD groups for a particular user?

If you have a LDAP connection with a username and password to connect to Active Directory, here is the code I used to connect properly:

using System.DirectoryServices.AccountManagement;

// ...

// Connection information
var connectionString = "LDAP://domain.com/DC=domain,DC=com";
var connectionUsername = "your_ad_username";
var connectionPassword = "your_ad_password";

// Get groups for this user
var username = "myusername";

// Split the LDAP Uri
var uri = new Uri(connectionString);
var host = uri.Host;
var container = uri.Segments.Count() >=1 ? uri.Segments[1] : "";

// Create context to connect to AD
var princContext = new PrincipalContext(ContextType.Domain, host, container, connectionUsername, connectionPassword);

// Get User
UserPrincipal user = UserPrincipal.FindByIdentity(princContext, IdentityType.SamAccountName, username);

// Browse user's groups
foreach (GroupPrincipal group in user.GetGroups())
{
    Console.Out.WriteLine(group.Name);
}

String contains another two strings

Are you looking for the string contains a certain number of words or contains specific words? Your example leads towards the latter.

In that case, you may wish to look into parsing strings or at least use regex.
Learn regex - it will be useful 1000x over in programming. I cannot emphasize this too much. Using contains and if statements will turn into a mess very quickly.

If you are just trying to count words, then :

string d = "You hit someone for 50 damage";  
string[] words = d.Split(' ');  // Break up the string into words
Console.Write(words.Length);  

PHP - Extracting a property from an array of objects

The create_function() function is deprecated as of php v7.2.0. You can use the array_map() as given,

function getObjectID($obj){
    return $obj->id;
}

$IDs = array_map('getObjectID' , $array_of_object);

Alternatively, you can use array_column() function which returns the values from a single column of the input, identified by the column_key. Optionally, an index_key may be provided to index the values in the returned array by the values from the index_key column of the input array. You can use the array_column as given,

$IDs = array_column($array_of_object , 'id');

Can't import org.apache.http.HttpResponse in Android Studio

According to the Apache site this is the Gradle dependency you need to include, if you use Android API 23 or newer:

dependencies {
    compile group: 'cz.msebera.android' , name: 'httpclient', version: '4.4.1.1'
}

Source: https://hc.apache.org/httpcomponents-client-4.5.x/android-port.html

How to solve SyntaxError on autogenerated manage.py?

For running Python version 3, you need to use python3 instead of python.

So, the final command will be:

python3 manage.py runserver

How do I change a PictureBox's image?

Assign a new Image object to your PictureBox's Image property. To load an Image from a file, you may use the Image.FromFile method. In your particular case, assuming the current directory is one under bin, this should load the image bin/Pics/image1.jpg, for example:

pictureBox1.Image = Image.FromFile("../Pics/image1.jpg");

Additionally, if these images are static and to be used only as resources in your application, resources would be a much better fit than files.

Adding a default value in dropdownlist after binding with database

design

<asp:DropDownList ID="ddlArea" DataSourceID="ldsArea" runat="server" ondatabound="ddlArea_DataBound" />

codebehind

protected void ddlArea_DataBound(object sender, EventArgs e)
{
    ddlArea.Items.Insert(0, new ListItem("--Select--", "0"));
}

How can I find all the subsets of a set, with exactly n elements?

Here's a function that gives you all subsets of the integers [0..n], not just the subsets of a given length:

from itertools import combinations, chain

def allsubsets(n):
    return list(chain(*[combinations(range(n), ni) for ni in range(n+1)]))

so e.g.

>>> allsubsets(3)
[(), (0,), (1,), (2,), (0, 1), (0, 2), (1, 2), (0, 1, 2)]

How to remove a package in sublime text 2

There are several answers, First IF you are using Package Control simply use Package Control's Remove Package command...

Ctrl+Shift+P

Package Control: Remove Package

If you installed the package manually, and are on a Windows machine...have no fear; Just modify the files manually.

First navigate to

C:\users\[Name]\AppData\Roaming\Sublime Text [version]\

There will be 4 directories:

  1. Installed Packages (Holds the Package Control config file, ignore)
  2. Packages (Holds Package source)
  3. Pristine Packages (Holds the versioning info, ignore)
  4. Settings (Sublime Setting Info, ignore)

First open ..\Packages folder and locate the folder named the same as your package; Delete it.

Secondly, open Sublime and navigate to the Preferences > Package Settings > Package Control > Settings-user

Third, locate the line where the package name you want to "uninstall"

{
    "installed_packages":
    [
        "Alignment",
        "All Autocomplete",
        "AngularJS",
        "AutoFileName",
        "BracketHighlighter",
        "Browser Support",
        "Case Conversion",
        "ColorPicker",
        "Emmet",
        "FileDiffs",
        "Format SQL",
        "Git",
        "Github Tools",
        "HTML-CSS-JS Prettify",
        "HTML5",
        "HTMLBeautify",
        "jQuery",
        "JsFormat",
        "JSHint",
        "JsMinifier",
        "LiveReload",
        "LoremIpsum",
        "LoremPixel",
        "Oracle PL SQL",
        "Package Control",
        "Placehold.it Image Tag Generator",
        "Placeholders",
        "Prefixr",
        "Search Stack Overflow",
        "SublimeAStyleFormatter",
        "SublimeCodeIntel",
        "Tag",
        "Theme - Centurion",
        "TortoiseSVN",
        "Zen Tabs"
    ]
}

NOTE Say the package you are removing is "Zen Tabs", you MUST also remove the , after "TortoiseSVN" or it will error.

Thus concludes the easiest way to remove or Install a Sublime Text Package.

Simple mediaplayer play mp3 from file path?

Here is the code to set up a MediaPlayer to play off of the SD card:

String PATH_TO_FILE = "/sdcard/music.mp3";    
mediaPlayer = new  MediaPlayer();
mediaPlayer.setDataSource(PATH_TO_FILE);
mediaPlayer.prepare();   
mediaPlayer.start()

You can see the full example here. Let me know if you have any problems.

Android emulator: How to monitor network traffic?

Yes, wireshark will work.

I don't think there is any easy way to filter out solely emulator traffic, since it is coming from the same src IP.

Perhaps the best way would be to set up a very bare VMware environment and only run the emulator in there, at least that way there wouldn't be too much background traffic.

Process escape sequences in a string in Python

The (currently) accepted answer by Jerub is correct for python2, but incorrect and may produce garbled results (as Apalala points out in a comment to that solution), for python3. That's because the unicode_escape codec requires its source to be coded in latin-1, not utf-8, as per the official python docs. Hence, in python3 use:

>>> myString="špåm\\nëðþ\\x73"
>>> print(myString)
špåm\nëðþ\x73
>>> decoded_string = myString.encode('latin-1','backslashreplace').decode('unicode_escape')
>>> print(decoded_string)
špåm
ëðþs

This method also avoids the extra unnecessary roundtrip between strings and bytes in metatoaster's comments to Jerub's solution (but hats off to metatoaster for recognizing the bug in that solution).

How to watch for form changes in Angular

UPD. The answer and demo are updated to align with latest Angular.


You can subscribe to entire form changes due to the fact that FormGroup representing a form provides valueChanges property which is an Observerable instance:

this.form.valueChanges.subscribe(data => console.log('Form changes', data));

In this case you would need to construct form manually using FormBuilder. Something like this:

export class App {
  constructor(private formBuilder: FormBuilder) {
    this.form = formBuilder.group({
      firstName: 'Thomas',
      lastName: 'Mann'
    })

    this.form.valueChanges.subscribe(data => {
      console.log('Form changes', data)
      this.output = data
    })
  }
}

Check out valueChanges in action in this demo: http://plnkr.co/edit/xOz5xaQyMlRzSrgtt7Wn?p=preview

Function stoi not declared

The answers above are correct, but not well explained.

g++ -std=c++11 my_cpp_code.cpp

Add -std=c++11 to your compiler options since you are most likely using an older version of debian or ubuntu which is not using by default the new c++11 standard of g++/gcc. I had the same problem on Debian Wheezy.

http://en.cppreference.com/w/cpp/string/basic_string/stol

shows in really small writing to the right in green that c++11 is required.

How to detect simple geometric shapes using OpenCV

You can also use template matching to detect shapes inside an image.

UILabel with text of two different colors

In my case I'm using Xcode 10.1. There is a option of switching between plain text and Attributed text in Label text in Interface Builder

enter image description here

Hope this may help someone else..!

Delete the first three rows of a dataframe in pandas

I think a more explicit way of doing this is to use drop.

The syntax is:

df.drop(label)

And as pointed out by @tim and @ChaimG, this can be done in-place:

df.drop(label, inplace=True)

One way of implementing this could be:

df.drop(df.index[:3], inplace=True)

And another "in place" use:

df.drop(df.head(3).index, inplace=True)

How to convert milliseconds to seconds with precision

I had this problem too, somehow my code did not present the exact values but rounded the number in seconds to 0.0 (if milliseconds was under 1 second). What helped me out is adding the decimal to the division value.

double time_seconds = time_milliseconds / 1000.0;   // add the decimal
System.out.println(time_milliseconds);              // Now this should give you the right value.

ERROR 1115 (42000): Unknown character set: 'utf8mb4'

As some suggested here, replacing utf8mb4 with utf8 will help you resolve the issue. IMHO, I used sed to find and replace them to avoid losing data. In addition, opening a large file into any graphical editor is potential pain. My MySQL data grows up 2 GB. The ultimate command is

sed 's/utf8mb4_unicode_520_ci/utf8_unicode_ci/g' original-mysql-data.sql > updated-mysql-data.sql
sed 's/utf8mb4/utf8/g' original-mysql-data.sql > updated-mysql-data.sql

Done!

Escape double quotes in parameter

Try this:

myscript """test"""

"" escape to a single " in the parameter.

Is there a way to detach matplotlib plots so that the computation can continue?

In many cases it is more convenient til save the image as a .png file on the hard drive. Here is why:

Advantages:

  • You can open it, have a look at it and close it down any time in the process. This is particularly convenient when your application is running for a long time.
  • Nothing pops up and you are not forced to have the windows open. This is particularly convenient when you are dealing with many figures.
  • Your image is accessible for later reference and is not lost when closing the figure window.

Drawback:

  • The only thing I can think of is that you will have to go and finder the folder and open the image yourself.

Check for false

You can use something simpler:

if(!var){
    console.log('var is false'); 
}

Differences between INDEX, PRIMARY, UNIQUE, FULLTEXT in MySQL?

Differences

  • KEY or INDEX refers to a normal non-unique index. Non-distinct values for the index are allowed, so the index may contain rows with identical values in all columns of the index. These indexes don't enforce any restraints on your data so they are used only for access - for quickly reaching certain ranges of records without scanning all records.

  • UNIQUE refers to an index where all rows of the index must be unique. That is, the same row may not have identical non-NULL values for all columns in this index as another row. As well as being used to quickly reach certain record ranges, UNIQUE indexes can be used to enforce restraints on data, because the database system does not allow the distinct values rule to be broken when inserting or updating data.

    Your database system may allow a UNIQUE index to be applied to columns which allow NULL values, in which case two rows are allowed to be identical if they both contain a NULL value (the rationale here is that NULL is considered not equal to itself). Depending on your application, however, you may find this undesirable: if you wish to prevent this, you should disallow NULL values in the relevant columns.

  • PRIMARY acts exactly like a UNIQUE index, except that it is always named 'PRIMARY', and there may be only one on a table (and there should always be one; though some database systems don't enforce this). A PRIMARY index is intended as a primary means to uniquely identify any row in the table, so unlike UNIQUE it should not be used on any columns which allow NULL values. Your PRIMARY index should be on the smallest number of columns that are sufficient to uniquely identify a row. Often, this is just one column containing a unique auto-incremented number, but if there is anything else that can uniquely identify a row, such as "countrycode" in a list of countries, you can use that instead.

    Some database systems (such as MySQL's InnoDB) will store a table's records on disk in the order in which they appear in the PRIMARY index.

  • FULLTEXT indexes are different from all of the above, and their behaviour differs significantly between database systems. FULLTEXT indexes are only useful for full text searches done with the MATCH() / AGAINST() clause, unlike the above three - which are typically implemented internally using b-trees (allowing for selecting, sorting or ranges starting from left most column) or hash tables (allowing for selection starting from left most column).

    Where the other index types are general-purpose, a FULLTEXT index is specialised, in that it serves a narrow purpose: it's only used for a "full text search" feature.

Similarities

  • All of these indexes may have more than one column in them.

  • With the exception of FULLTEXT, the column order is significant: for the index to be useful in a query, the query must use columns from the index starting from the left - it can't use just the second, third or fourth part of an index, unless it is also using the previous columns in the index to match static values. (For a FULLTEXT index to be useful to a query, the query must use all columns of the index.)

Click a button programmatically

Best implementation depends of what you are attempting to do exactly. Nadeem_MK gives you a valid one. Know you can also:

  1. raise the Button2_Click event using PerformClick() method:

    Private Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
        'do stuff
        Me.Button2.PerformClick()
    End Sub
    
  2. attach the same handler to many buttons:

    Private Sub Button1_Click(sender As Object, e As System.EventArgs) _
        Handles Button1.Click, Button2.Click
        'do stuff
    End Sub
    
  3. call the Button2_Click method using the same arguments than Button1_Click(...) method (IF you need to know which is the sender, for example) :

    Private Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
        'do stuff
         Button2_Click(sender, e)
    End Sub
    

Add to integers in a list

fooList = [1,3,348,2]
fooList.append(3)
fooList.append(2734)
print(fooList) # [1,3,348,2,3,2734]

Format specifier %02x

%x is a format specifier that format and output the hex value. If you are providing int or long value, it will convert it to hex value.

%02x means if your provided value is less than two digits then 0 will be prepended.

You provided value 16843009 and it has been converted to 1010101 which a hex value.

How can I get the ID of an element using jQuery?

Maybe useful for others that find this thread. The code below will only work if you already use jQuery. The function returns always an identifier. If the element doesn't have an identifier the function generates the identifier and append this to the element.

var generatedIdCounter = 0;

$.fn.id = function() {
    var identifier = this.attr('id');

    if(!identifier) {
        generatedIdCounter++;
        identifier = 'isGenerated_' + generatedIdCounter;

        this.attr('id', identifier);
    }

    return identifier;
}

How to use:

$('.classname').id();

$('#elementId').id();

How do I run a PowerShell script when the computer starts?

Be sure, whenever you want PowerShell to run automatically / in the background / non-interactive, it’s a good idea to specify the parameters -ExecutionPolicy Bypass to PowerShell.exe

PowerShell.exe -ExecutionPolicy Bypass

Loading another html page from javascript

You can include a .js file which has the script to set the

window.location.href = url;

Where url would be the url you wish to load.

How to use moment.js library in angular 2 typescript app?

My own version of using Moment in Angular

npm i moment --save

import * as _moment from 'moment';

...

moment: _moment.Moment = _moment();

constructor() { }

ngOnInit() {

    const unix = this.moment.format('X');
    console.log(unix);    

}

First import moment as _moment, then declare moment variable with type _moment.Moment with an initial value of _moment().

Plain import of moment wont give you any auto completion but if you will declare moment with type Moment interface from _moment namespace from 'moment' package initialized with moment namespace invoked _moment() gives you auto completion of moment's api's.

I think this is the most angular way of using moment without using @types typings or angular providers, if you're looking auto completion for vanilla javascript libraries like moment.

Prevent multiple instances of a given app in .NET?

Use Mutex. One of the examples above using GetProcessByName has many caveats. Here is a good article on the subject:

http://odetocode.com/Blogs/scott/archive/2004/08/20/401.aspx

[STAThread]
static void Main() 
{
   using(Mutex mutex = new Mutex(false, "Global\\" + appGuid))
   {
      if(!mutex.WaitOne(0, false))
      {
         MessageBox.Show("Instance already running");
         return;
      }

      Application.Run(new Form1());
   }
}

private static string appGuid = "c0a76b5a-12ab-45c5-b9d9-d693faa6e7b9";

Unlink of file Failed. Should I try again?

I ran into this issue in Windows, you might want to run the git bash as an administrator and then perform the desire commands, that solved the issue for me.

Minimum Hardware requirements for Android development

I use DUAL CORE 3-GHZ with 2GB RAM, windows 8 OS.

I can run eclipse and AVD (even running 2 AVD is still good) smoothly, as long as i dont open too much other tabs (Game, Browser, MS Word, etc).

Multi-line bash commands in makefile

What's wrong with just invoking the commands?

foo:
       echo line1
       echo line2
       ....

And for your second question, you need to escape the $ by using $$ instead, i.e. bash -c '... echo $$a ...'.

EDIT: Your example could be rewritten to a single line script like this:

gcc $(for i in `find`; do echo $i; done)