Programs & Examples On #Join

A JOIN is a general operation in relational algebra for a combining operation on two or more relations in a relational database system. JOIN is also keyword of the SQL language for performing this operation.

Count with IF condition in MySQL query

Replace this line:

count(if(ccc_news_comments.id = 'approved', ccc_news_comments.id, 0)) AS comments

With this one:

coalesce(sum(ccc_news_comments.id = 'approved'), 0) comments

Can I use CASE statement in a JOIN condition?

I think you need two case statements:

SELECT  *
FROM    sys.indexes i
    JOIN sys.partitions p
        ON i.index_id = p.index_id 
    JOIN sys.allocation_units a
        ON 
        -- left side of join on statement
            CASE
               WHEN a.type IN (1, 3)
                   THEN a.container_id
               WHEN a.type IN (2)
                   THEN a.container_id
            END 
        = 
        -- right side of join on statement
            CASE
               WHEN a.type IN (1, 3)
                   THEN p.hobt_id
               WHEN a.type IN (2)
                   THEN p.partition_id
            END             

This is because:

  • the CASE statement returns a single value at the END
  • the ON statement compares two values
  • your CASE statement was doing the comparison inside of the CASE statement. I would guess that if you put your CASE statement in your SELECT you would get a boolean '1' or '0' indicating whether the CASE statement evaluated to True or False

SQL join: selecting the last records in a one-to-many relationship

I found this thread as a solution to my problem.

But when I tried them the performance was low. Bellow is my suggestion for better performance.

With MaxDates as (
SELECT  customer_id,
                MAX(date) MaxDate
        FROM    purchase
        GROUP BY customer_id
)

SELECT  c.*, M.*
FROM    customer c INNER JOIN
        MaxDates as M ON c.id = M.customer_id 

Hope this will be helpful.

INNER JOIN vs INNER JOIN (SELECT . FROM)

Seems to be identical just in case that SQL server will not try to read data which is not required for the query, the optimizer is clever enough

It can have sense when join on complex query (i.e which have joings, groupings etc itself) then, yes, it is better to specify required fields.

But there is one more point. If the query is simple there is no difference but EVERY extra action even which is supposed to improve performance makes optimizer works harder and optimizer can fail to get the best plan in time and will run not optimal query. So extras select can be a such action which can even decrease performance

How do I perform the SQL Join equivalent in MongoDB?

As of Mongo 3.2 the answers to this question are mostly no longer correct. The new $lookup operator added to the aggregation pipeline is essentially identical to a left outer join:

https://docs.mongodb.org/master/reference/operator/aggregation/lookup/#pipe._S_lookup

From the docs:

{
   $lookup:
     {
       from: <collection to join>,
       localField: <field from the input documents>,
       foreignField: <field from the documents of the "from" collection>,
       as: <output array field>
     }
}

Of course Mongo is not a relational database, and the devs are being careful to recommend specific use cases for $lookup, but at least as of 3.2 doing join is now possible with MongoDB.

What is the difference between JOIN and UNION?

1. The SQL Joins clause is used to combine records from two or more tables in a database. A JOIN is a means for combining fields from two tables by using values common to each.

2. The SQL UNION operator combines the result of two or more SELECT statements. Each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order.

for example: table 1 customers/table 2 orders

inner join:

SELECT ID, NAME, AMOUNT, DATE

FROM CUSTOMERS?

INNER JOIN ORDERS?

ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

union:

SELECT ID, NAME, AMOUNT, DATE

?FROM CUSTOMERS?

LEFT JOIN ORDERS?

ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID

UNION

SELECT ID, NAME, AMOUNT, DATE ? FROM CUSTOMERS?

RIGHT JOIN ORDERS?

ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

Oracle SQL - select within a select (on the same table!)

I'm a bit confused by the quotes, however, below should work for you:

SELECT "Gc_Staff_Number",
       "Start_Date", x.end_date
FROM   "Employment_History" eh,
(SELECT "End_Date"
        FROM   "Employment_History"
        WHERE  "Current_Flag" != 'Y'
               AND ROWNUM = 1
               AND "Employee_Number" = eh.Employee_Number
        ORDER  BY "End_Date" ASC) x
WHERE  "Current_Flag" = 'Y'

MySQL how to join tables on two fields

JOIN t2 ON (t2.id = t1.id AND t2.date = t1.date)

JPA eager fetch does not join

The fetchType attribute controls whether the annotated field is fetched immediately when the primary entity is fetched. It does not necessarily dictate how the fetch statement is constructed, the actual sql implementation depends on the provider you are using toplink/hibernate etc.

If you set fetchType=EAGER This means that the annotated field is populated with its values at the same time as the other fields in the entity. So if you open an entitymanager retrieve your person objects and then close the entitymanager, subsequently doing a person.address will not result in a lazy load exception being thrown.

If you set fetchType=LAZY the field is only populated when it is accessed. If you have closed the entitymanager by then a lazy load exception will be thrown if you do a person.address. To load the field you need to put the entity back into an entitymangers context with em.merge(), then do the field access and then close the entitymanager.

You might want lazy loading when constructing a customer class with a collection for customer orders. If you retrieved every order for a customer when you wanted to get a customer list this may be a expensive database operation when you only looking for customer name and contact details. Best to leave the db access till later.

For the second part of the question - how to get hibernate to generate optimised SQL?

Hibernate should allow you to provide hints as to how to construct the most efficient query but I suspect there is something wrong with your table construction. Is the relationship established in the tables? Hibernate may have decided that a simple query will be quicker than a join especially if indexes etc are missing.

Entityframework Join using join method and lambdas

Generally i prefer the lambda syntax with LINQ, but Join is one example where i prefer the query syntax - purely for readability.

Nonetheless, here is the equivalent of your above query (i think, untested):

var query = db.Categories         // source
   .Join(db.CategoryMaps,         // target
      c => c.CategoryId,          // FK
      cm => cm.ChildCategoryId,   // PK
      (c, cm) => new { Category = c, CategoryMaps = cm }) // project result
   .Select(x => x.Category);  // select result

You might have to fiddle with the projection depending on what you want to return, but that's the jist of it.

pandas: merge (join) two data frames on multiple columns

Try this

new_df = pd.merge(A_df, B_df,  how='left', left_on=['A_c1','c2'], right_on = ['B_c1','c2'])

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html

left_on : label or list, or array-like Field names to join on in left DataFrame. Can be a vector or list of vectors of the length of the DataFrame to use a particular vector as the join key instead of columns

right_on : label or list, or array-like Field names to join on in right DataFrame or vector/list of vectors per left_on docs

Join two sql queries

Some DBMSs support the FROM (SELECT ...) AS alias_name syntax.

Think of your two original queries as temporary tables. You can query them like so:

SELECT t1.Activity, t1."Total Amount 2009", t2."Total Amount 2008"
FROM (query1) as t1, (query2) as t2
WHERE t1.Activity = t2.Activity

MySQL select rows where left join is null

One of the best approach if you do not want to return any columns from table2 is to use the NOT EXISTS

SELECT  table1.id 
FROM    table1 T1
WHERE
  NOT EXISTS (SELECT *
              FROM table2 T2
              WHERE T1.id = T2.user_one
                  OR T1.id = T2.user_two)

Semantically this says what you want to query: Select every row where there is no matching record in the second table.

MySQL is optimized for EXISTS: It returns as soon as it finds the first matching record.

Joining pairs of elements of a list

Without building temporary lists:

>>> import itertools
>>> s = 'abcdefgh'
>>> si = iter(s)
>>> [''.join(each) for each in itertools.izip(si, si)]
['ab', 'cd', 'ef', 'gh']

or:

>>> import itertools
>>> s = 'abcdefgh'
>>> si = iter(s)
>>> map(''.join, itertools.izip(si, si))
['ab', 'cd', 'ef', 'gh']

MySQL: Quick breakdown of the types of joins

Based on your comment, simple definitions of each is best found at W3Schools The first line of each type gives a brief explanation of the join type

  • JOIN: Return rows when there is at least one match in both tables
  • LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
  • RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
  • FULL JOIN: Return rows when there is a match in one of the tables

END EDIT

In a nutshell, the comma separated example you gave of

SELECT * FROM a, b WHERE b.id = a.beeId AND ...

is selecting every record from tables a and b with the commas separating the tables, this can be used also in columns like

SELECT a.beeName,b.* FROM a, b WHERE b.id = a.beeId AND ...

It is then getting the instructed information in the row where the b.id column and a.beeId column have a match in your example. So in your example it will get all information from tables a and b where the b.id equals a.beeId. In my example it will get all of the information from the b table and only information from the a.beeName column when the b.id equals the a.beeId. Note that there is an AND clause also, this will help to refine your results.

For some simple tutorials and explanations on mySQL joins and left joins have a look at Tizag's mySQL tutorials. You can also check out Keith J. Brown's website for more information on joins that is quite good also.

I hope this helps you

Can we use join for two different database tables?

SQL Server allows you to join tables from different databases as long as those databases are on the same server. The join syntax is the same; the only difference is that you must fully specify table names.

Let's suppose you have two databases on the same server - Db1 and Db2. Db1 has a table called Clients with a column ClientId and Db2 has a table called Messages with a column ClientId (let's leave asside why those tables are in different databases).

Now, to perform a join on the above-mentioned tables you will be using this query:

select *
from Db1.dbo.Clients c
join Db2.dbo.Messages m on c.ClientId = m.ClientId

Multiple INNER JOIN SQL ACCESS

Access requires parentheses in the FROM clause for queries which include more than one join. Try it this way ...

FROM
    ((tbl_employee
    INNER JOIN tbl_netpay
    ON tbl_employee.emp_id = tbl_netpay.emp_id)
    INNER JOIN tbl_gross
    ON tbl_employee.emp_id = tbl_gross.emp_ID)
    INNER JOIN tbl_tax
    ON tbl_employee.emp_id = tbl_tax.emp_ID;

If possible, use the Access query designer to set up your joins. The designer will add parentheses as required to keep the db engine happy.

Difference between JOIN and INNER JOIN

As the other answers already state there is no difference in your example.

The relevant bit of grammar is documented here

<join_type> ::= 
    [ { INNER | { { LEFT | RIGHT | FULL } [ OUTER ] } } [ <join_hint> ] ]
    JOIN

Showing that all are optional. The page further clarifies that

INNER Specifies all matching pairs of rows are returned. Discards unmatched rows from both tables. When no join type is specified, this is the default.

The grammar does also indicate that there is one time where the INNER is required though. When specifying a join hint.

See the example below

CREATE TABLE T1(X INT);
CREATE TABLE T2(Y INT);

SELECT *
FROM   T1
       LOOP JOIN T2
         ON X = Y;

SELECT *
FROM   T1
       INNER LOOP JOIN T2
         ON X = Y;

enter image description here

How to get multiple counts with one SQL query?

One way which works for sure

SELECT a.distributor_id,
    (SELECT COUNT(*) FROM myTable WHERE level='personal' and distributor_id = a.distributor_id) as PersonalCount,
    (SELECT COUNT(*) FROM myTable WHERE level='exec' and distributor_id = a.distributor_id) as ExecCount,
    (SELECT COUNT(*) FROM myTable WHERE distributor_id = a.distributor_id) as TotalCount
FROM (SELECT DISTINCT distributor_id FROM myTable) a ;

EDIT:
See @KevinBalmforth's break down of performance for why you likely don't want to use this method and instead should opt for @Taryn?'s answer. I'm leaving this so people can understand their options.

JOIN two SELECT statement results

SELECT t1.ks, t1.[# Tasks], COALESCE(t2.[# Late], 0) AS [# Late]
FROM 
    (SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks) t1
LEFT JOIN
    (SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks) t2
ON (t1.ks = t2.ks);

Update a table using JOIN in SQL Server?

Try it like this:

    UPDATE a 
    SET a.CalculatedColumn= b.[Calculated Column]
    FROM table1 a INNER JOIN table2 b ON a.commonfield = b.[common field] 
    WHERE a.BatchNO = '110'

How to use the COLLATE in a JOIN in SQL Server?

Correct syntax looks like this. See MSDN.

SELECT *
  FROM [FAEB].[dbo].[ExportaComisiones] AS f
  JOIN [zCredifiel].[dbo].[optPerson] AS p

  ON p.vTreasuryId COLLATE Latin1_General_CI_AS = f.RFC COLLATE Latin1_General_CI_AS 

lambda expression join multiple tables with select and where clause

I was looking for something and I found this post. I post this code that managed many-to-many relationships in case someone needs it.

    var UserInRole = db.UsersInRoles.Include(u => u.UserProfile).Include(u => u.Roles)
    .Select (m => new 
    {
        UserName = u.UserProfile.UserName,
        RoleName = u.Roles.RoleName
    });

Hibernate Criteria Join with 3 Tables

The fetch mode only says that the association must be fetched. If you want to add restrictions on an associated entity, you must create an alias, or a subcriteria. I generally prefer using aliases, but YMMV:

Criteria c = session.createCriteria(Dokument.class, "dokument");
c.createAlias("dokument.role", "role"); // inner join by default
c.createAlias("role.contact", "contact");
c.add(Restrictions.eq("contact.lastName", "Test"));
return c.list();

This is of course well explained in the Hibernate reference manual, and the javadoc for Criteria even has examples. Read the documentation: it has plenty of useful information.

What is the difference between Left, Right, Outer and Inner Joins?

Check out Join (SQL) on Wikipedia

  • Inner join - Given two tables an inner join returns all rows that exist in both tables
  • left / right (outer) join - Given two tables returns all rows that exist in either the left or right table of your join, plus the rows from the other side will be returned when the join clause is a match or null will be returned for those columns

  • Full Outer - Given two tables returns all rows, and will return nulls when either the left or right column is not there

  • Cross Joins - Cartesian join and can be dangerous if not used carefully

How can I join multiple SQL tables using the IDs?

SELECT 
    a.nameA, /* TableA.nameA */
    d.nameD /* TableD.nameD */
FROM TableA a 
    INNER JOIN TableB b on b.aID = a.aID 
    INNER JOIN TableC c on c.cID = b.cID 
    INNER JOIN TableD d on d.dID = a.dID 
WHERE DATE(c.`date`) = CURDATE()

Does the join order matter in SQL?

If you try joining C on a field from B before joining B, i.e.:

SELECT A.x, 
       A.y, 
       A.z 
FROM A 
   INNER JOIN C
       on B.x = C.x
   INNER JOIN B
       on A.x = B.x

your query will fail, so in this case the order matters.

JPA Criteria API - How to add JOIN clause (as general sentence as possible)

Actually you don't have to deal with the static metamodel if you had your annotations right.

With the following entities :

@Entity
public class Pet {
  @Id
  protected Long id;
  protected String name;
  protected String color;
  @ManyToOne
  protected Set<Owner> owners;
}

@Entity
public class Owner {
  @Id
  protected Long id;
  protected String name;
}

You can use this :

CriteriaQuery<Pet> cq = cb.createQuery(Pet.class);
Metamodel m = em.getMetamodel();
EntityType<Pet> petMetaModel = m.entity(Pet.class);

Root<Pet> pet = cq.from(Pet.class);
Join<Pet, Owner> owner = pet.join(petMetaModel.getSet("owners", Owner.class));

INNER JOIN ON vs WHERE clause

I have two points for the implicit join (The second example):

  1. Tell the database what you want, not what it should do.
  2. You can write all tables in a clear list that is not cluttered by join conditions. Then you can much easier read what tables are all mentioned. The conditions come all in the WHERE part, where they are also all lined up one below the other. Using the JOIN keyword mixes up tables and conditions.

How to do joins in LINQ on multiple fields in single join

I think a more readable and flexible option is to use Where function:

var result = from x in entity1
             from y in entity2
                 .Where(y => y.field1 == x.field1 && y.field2 == x.field2)

This also allows to easily change from inner join to left join by appending .DefaultIfEmpty().

SQL Server: Multiple table joins with a WHERE clause

SELECT p.Name, v.Name
FROM Production.Product p
JOIN Purchasing.ProductVendor pv
ON p.ProductID = pv.ProductID
JOIN Purchasing.Vendor v
ON pv.BusinessEntityID = v.BusinessEntityID
WHERE ProductSubcategoryID = 15
ORDER BY v.Name;

How to use mysql JOIN without ON condition?

MySQL documentation covers this topic.

Here is a synopsis. When using join or inner join, the on condition is optional. This is different from the ANSI standard and different from almost any other database. The effect is a cross join. Similarly, you can use an on clause with cross join, which also differs from standard SQL.

A cross join creates a Cartesian product -- that is, every possible combination of 1 row from the first table and 1 row from the second. The cross join for a table with three rows ('a', 'b', and 'c') and a table with four rows (say 1, 2, 3, 4) would have 12 rows.

In practice, if you want to do a cross join, then use cross join:

from A cross join B

is much better than:

from A, B

and:

from A join B -- with no on clause

The on clause is required for a right or left outer join, so the discussion is not relevant for them.

If you need to understand the different types of joins, then you need to do some studying on relational databases. Stackoverflow is not an appropriate place for that level of discussion.

Multiple SQL joins

It will be something like this:

SELECT b.Title, b.Edition, b.Year, b.Pages, b.Rating, c.Category, p.Publisher, w.LastName
FROM
    Books b
    JOIN Categories_Book cb ON cb._ISBN = b._Books_ISBN
    JOIN Category c ON c._CategoryID = cb._Categories_Category_ID
    JOIN Publishers p ON p._PublisherID = b.PublisherID
    JOIN Writers_Books wb ON wb._Books_ISBN = b._ISBN
    JOIN Writer w ON w._WritersID = wb._Writers_WriterID

You use the join statement to indicate which fields from table A map to table B. I'm using aliases here thats why you see Books b the Books table will be referred to as b in the rest of the query. This makes for less typing.

FYI your naming convention is very strange, I would expect it to be more like this:

Book: ID, ISBN , BookTitle, Edition, Year, PublisherID, Pages, Rating
Category: ID, [Name]
BookCategory: ID, CategoryID, BookID
Publisher: ID, [Name]
Writer: ID, LastName
BookWriter: ID, WriterID, BookID

How to merge multiple lists into one list in python?

Just add them:

['it'] + ['was'] + ['annoying']

You should read the Python tutorial to learn basic info like this.

Difference between natural join and inner join

One significant difference between INNER JOIN and NATURAL JOIN is the number of columns returned.

Consider:

TableA                           TableB
+------------+----------+        +--------------------+    
|Column1     | Column2  |        |Column1  |  Column3 |
+-----------------------+        +--------------------+
| 1          |  2       |        | 1       |   3      |
+------------+----------+        +---------+----------+

The INNER JOIN of TableA and TableB on Column1 will return

SELECT * FROM TableA AS a INNER JOIN TableB AS b USING (Column1);
SELECT * FROM TableA AS a INNER JOIN TableB AS b ON a.Column1 = b.Column1;
+------------+-----------+---------------------+    
| a.Column1  | a.Column2 | b.Column1| b.Column3|
+------------------------+---------------------+
| 1          |  2        | 1        |   3      |
+------------+-----------+----------+----------+

The NATURAL JOIN of TableA and TableB on Column1 will return:

SELECT * FROM TableA NATURAL JOIN TableB
+------------+----------+----------+    
|Column1     | Column2  | Column3  |
+-----------------------+----------+
| 1          |  2       |   3      |
+------------+----------+----------+

The repeated column is avoided.

(AFAICT from the standard grammar, you can't specify the joining columns in a natural join; the join is strictly name-based. See also Wikipedia.)

(There's a cheat in the inner join output; the a. and b. parts would not be in the column names; you'd just have column1, column2, column1, column3 as the headings.)

LINQ Joining in C# with multiple conditions

Your and should be a && in the where clause.

where epl.DepartAirportAfter >  sd.UTCDepartureTime 
and epl.ArriveAirportBy > sd.UTCArrivalTime

should be

where epl.DepartAirportAfter >  sd.UTCDepartureTime 
&& epl.ArriveAirportBy > sd.UTCArrivalTime

CakePHP find method with JOIN

        $services = $this->Service->find('all', array(
            'limit' =>4,
            'fields' => array('Service.*','ServiceImage.*'),
            'joins' => array(
                array(
                        'table' => 'services_images',
                        'alias' => 'ServiceImage',
                        'type' => 'INNER',
                        'conditions' => array(
                        'ServiceImage.service_id' =>'Service.id'
                        )
                    ),
                ),
            )
        );

It goges to array is null.

How to JOIN three tables in Codeigniter

Try as follows:

public function funcname($id)
{
    $this->db->select('*');
    $this->db->from('Album a'); 
    $this->db->join('Category b', 'b.cat_id=a.cat_id', 'left');
    $this->db->join('Soundtrack c', 'c.album_id=a.album_id', 'left');
    $this->db->where('c.album_id',$id);
    $this->db->order_by('c.track_title','asc');         
    $query = $this->db->get(); 
    return $query->result_array();
}

If no result found CI returns false otherwise true

1052: Column 'id' in field list is ambiguous

SELECT tbl_names.id, tbl_names.name, tbl_names.section
  FROM tbl_names, tbl_section 
 WHERE tbl_names.id = tbl_section.id

MySQL join with where clause

Try this

  SELECT *
    FROM categories
    LEFT JOIN user_category_subscriptions 
         ON user_category_subscriptions.category_id = categories.category_id 
   WHERE user_category_subscriptions.user_id = 1 
          or user_category_subscriptions.user_id is null

Inner join with count() on three tables

select pe_name,count( distinct b.ord_id),count(c.item_id) 
 from people  a, order1 as b ,item as c
 where a.pe_id=b.pe_id and
b.ord_id=c.order_id   group by a.pe_id,pe_name

FULL OUTER JOIN vs. FULL JOIN

It's true that some databases recognize the OUTER keyword. Some do not. Where it is recognized, it is usually an optional keyword. Almost always, FULL JOIN and FULL OUTER JOIN do exactly the same thing. (I can't think of an example where they do not. Can anyone else think of one?)

This may leave you wondering, "Why would it even be a keyword if it has no meaning?" The answer boils down to programming style.

In the old days, programmers strived to make their code as compact as possible. Every character meant longer processing time. We used 1, 2, and 3 letter variables. We used 2 digit years. We eliminated all unnecessary white space. Some people still program that way. It's not about processing time anymore. It's more about fast coding.

Modern programmers are learning to use more descriptive variables and put more remarks and documentation into their code. Using extra words like OUTER make sure that other people who read the code will have an easier time understanding it. There will be less ambiguity. This style is much more readable and kinder to the people in the future who will have to maintain that code.

Java function for arrays like PHP's join()?

Nothing built-in that I know of.

Apache Commons Lang has a class called StringUtils which contains many join functions.

JOIN queries vs multiple queries

Here is a link with 100 useful queries, these are tested in Oracle database but remember SQL is a standard, what differ between Oracle, MS SQL Server, MySQL and other databases are the SQL dialect:

http://javaforlearn.com/100-sql-queries-learn/

How to return rows from left table not found in right table?

Try This

SELECT f.*
FROM first_table f LEFT JOIN second_table s ON f.key=s.key
WHERE s.key is NULL

For more please read this article : Joins in Sql Server

enter image description here

Why do multiple-table joins produce duplicate rows?

This might sound like a really basic "DUH" answer, but make sure that the column you're using to Lookup from on the merging file is actually full of unique values!

I noticed earlier today that PowerQuery won't throw you an error (like in PowerPivot) and will happily allow you to run a Many-Many merge. This will result in multiple rows being produced for each record that matches with a non-unique value.

What is the difference between a hash join and a merge join (Oracle RDBMS )?

I just want to edit this for posterity that the tags for oracle weren't added when I answered this question. My response was more applicable to MS SQL.

Merge join is the best possible as it exploits the ordering, resulting in a single pass down the tables to do the join. IF you have two tables (or covering indexes) that have their ordering the same such as a primary key and an index of a table on that key then a merge join would result if you performed that action.

Hash join is the next best, as it's usually done when one table has a small number (relatively) of items, its effectively creating a temp table with hashes for each row which is then searched continuously to create the join.

Worst case is nested loop which is order (n * m) which means there is no ordering or size to exploit and the join is simply, for each row in table x, search table y for joins to do.

LEFT OUTER JOIN in LINQ

take look at this example

class Person
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Phone { get; set; }
}

class Pet
{
    public string Name { get; set; }
    public Person Owner { get; set; }
}

public static void LeftOuterJoinExample()
{
    Person magnus = new Person {ID = 1, FirstName = "Magnus", LastName = "Hedlund"};
    Person terry = new Person {ID = 2, FirstName = "Terry", LastName = "Adams"};
    Person charlotte = new Person {ID = 3, FirstName = "Charlotte", LastName = "Weiss"};
    Person arlene = new Person {ID = 4, FirstName = "Arlene", LastName = "Huff"};

    Pet barley = new Pet {Name = "Barley", Owner = terry};
    Pet boots = new Pet {Name = "Boots", Owner = terry};
    Pet whiskers = new Pet {Name = "Whiskers", Owner = charlotte};
    Pet bluemoon = new Pet {Name = "Blue Moon", Owner = terry};
    Pet daisy = new Pet {Name = "Daisy", Owner = magnus};

    // Create two lists.
    List<Person> people = new List<Person> {magnus, terry, charlotte, arlene};
    List<Pet> pets = new List<Pet> {barley, boots, whiskers, bluemoon, daisy};

    var query = from person in people
        where person.ID == 4
        join pet in pets on person equals pet.Owner  into personpets
        from petOrNull in personpets.DefaultIfEmpty()
        select new { Person=person, Pet = petOrNull}; 



    foreach (var v in query )
    {
        Console.WriteLine("{0,-15}{1}", v.Person.FirstName + ":", (v.Pet == null ? "Does not Exist" : v.Pet.Name));
    }
}

// This code produces the following output:
//
// Magnus:        Daisy
// Terry:         Barley
// Terry:         Boots
// Terry:         Blue Moon
// Charlotte:     Whiskers
// Arlene:

now you are able to include elements from the left even if that element has no matches in the right, in our case we retrived Arlene even he has no matching in the right

here is the reference

How to: Perform Left Outer Joins (C# Programming Guide)

MongoDB query multiple collections at once

Trying to JOIN in MongoDB would defeat the purpose of using MongoDB. You could, however, use a DBref and write your application-level code (or library) so that it automatically fetches these references for you.

Or you could alter your schema and use embedded documents.

Your final choice is to leave things exactly the way they are now and do two queries.

How to specify names of columns for x and y when joining in dplyr?

This feature has been added in dplyr v0.3. You can now pass a named character vector to the by argument in left_join (and other joining functions) to specify which columns to join on in each data frame. With the example given in the original question, the code would be:

left_join(test_data, kantrowitz, by = c("first_name" = "name"))

sqlalchemy: how to join several tables by one query?

Try this

q = Session.query(
         User, Document, DocumentPermissions,
    ).filter(
         User.email == Document.author,
    ).filter(
         Document.name == DocumentPermissions.document,
    ).filter(
        User.email == 'someemail',
    ).all()

What's the best way to join on the same table twice?

You could use UNION to combine two joins:

SELECT Table1.PhoneNumber1 as PhoneNumber, Table2.SomeOtherField as OtherField
  FROM Table1
  JOIN Table2
    ON Table1.PhoneNumber1 = Table2.PhoneNumber
 UNION
SELECT Table1.PhoneNumber2 as PhoneNumber, Table2.SomeOtherField as OtherField
  FROM Table1
  JOIN Table2
    ON Table1.PhoneNumber2 = Table2.PhoneNumber

INNER JOIN same table

You can also use UNION like

SELECT  user_fname ,
        user_lname
FROM    users 
WHERE   user_id = $_GET[id]
UNION
SELECT  user_fname ,
        user_lname
FROM    users 
WHERE   user_parent_id = $_GET[id]

Rails :include vs. :joins

.joins will just joins the tables and brings selected fields in return. if you call associations on joins query result, it will fire database queries again

:includes will eager load the included associations and add them in memory. :includes loads all the included tables attributes. If you call associations on include query result, it will not fire any queries

Join/Where with LINQ and Lambda

1 equals 1 two different table join

var query = from post in database.Posts
            join meta in database.Post_Metas on 1 equals 1
            where post.ID == id
            select new { Post = post, Meta = meta };

How to perform Join between multiple tables in LINQ lambda

it has been a while but my answer may help someone:

if you already defined the relation properly you can use this:

        var res = query.Products.Select(m => new
        {
            productID = product.Id,
            categoryID = m.ProductCategory.Select(s => s.Category.ID).ToList(),
        }).ToList();

Merge two rows in SQL

My case is I have a table like this

---------------------------------------------
|company_name|company_ID|CA        |   WA   |
---------------------------------------------
|Costco      |   1      |NULL      | 2      |
---------------------------------------------
|Costco      |   1      |3         |Null    |
---------------------------------------------

And I want it to be like below:

---------------------------------------------
|company_name|company_ID|CA        |   WA   |
---------------------------------------------
|Costco      |   1      |3         | 2      |
---------------------------------------------

Most code is almost the same:

SELECT
    FK,
    MAX(CA) AS CA,
    MAX(WA) AS WA
FROM
    table1
GROUP BY company_name,company_ID

The only difference is the group by, if you put two column names into it, you can group them in pairs.

SQL join on multiple columns in same tables

Join like this:

ON a.userid = b.sourceid AND a.listid = b.destinationid;

Unable to create a constant value of type Only primitive types or enumeration types are supported in this context

Just add AsEnumerable() andToList() , so it looks like this

db.Favorites
    .Where(x => x.userId == userId)
    .Join(db.Person, x => x.personId, y => y.personId, (x, y).ToList().AsEnumerable()

ToList().AsEnumerable()

Explicit vs implicit SQL joins

Performance wise, it should not make any difference. The explicit join syntax seems cleaner to me as it clearly defines relationships between tables in the from clause and does not clutter up the where clause.

SQL Query with Join, Count and Where

I have used sub-query and it worked great!

SELECT *,(SELECT count(*) FROM $this->tbl_news WHERE
$this->tbl_news.cat_id=$this->tbl_categories.cat_id) as total_news FROM
$this->tbl_categories

Combine Multiple child rows into one row MYSQL

If you know you're going to have a limited number of max options then I would try this (example for max of 4 options per order):

Select OI.ID, OI.Item_Name, OO1.Value, OO2.Value, OO3.Value, OO4.Value

FROM Ordered_Items OI
    LEFT JOIN Ordered_Options OO1 ON OO1.Ordered_Item_ID = OI.ID
    LEFT JOIN Ordered_Options OO2 ON OO2.Ordered_Item_ID = OI.ID AND OO2.ID != OO1.ID
    LEFT JOIN Ordered_Options OO3 ON OO3.Ordered_Item_ID = OI.ID AND OO3.ID != OO1.ID AND OO3.ID != OO2.ID
    LEFT JOIN Ordered_Options OO4 ON OO4.Ordered_Item_ID = OI.ID AND OO4.ID != OO1.ID AND OO4.ID != OO2.ID AND OO4.ID != OO3.ID

GROUP BY OI.ID, OI.Item_Name

The group by condition gets rid of all of the duplicates that you would otherwise get. I've just implemented something similar on a site I'm working on where I knew I'd always have 1 or 2 matched in my child table, and I wanted to make sure I only had 1 row for each parent item.

How to do 3 table JOIN in UPDATE query?

An alternative General Plan, which I'm only adding as an independent Answer because the blasted "comment on an answer" won't take newlines without posting the entire edit, even though it isn't finished yet.

UPDATE table A
JOIN table B ON {join fields}
JOIN table C ON {join fields}
JOIN {as many tables as you need}
SET A.column = {expression}

Example:

UPDATE person P
JOIN address A ON P.home_address_id = A.id
JOIN city C ON A.city_id = C.id
SET P.home_zip = C.zipcode;

SQL JOIN - WHERE clause vs. ON clause

I think this distinction can best be explained via the logical order of operations in SQL, which is, simplified:

  • FROM (including joins)
  • WHERE
  • GROUP BY
  • Aggregations
  • HAVING
  • WINDOW
  • SELECT
  • DISTINCT
  • UNION, INTERSECT, EXCEPT
  • ORDER BY
  • OFFSET
  • FETCH

Joins are not a clause of the select statement, but an operator inside of FROM. As such, all ON clauses belonging to the corresponding JOIN operator have "already happened" logically by the time logical processing reaches the WHERE clause. This means that in the case of a LEFT JOIN, for example, the outer join's semantics has already happend by the time the WHERE clause is applied.

I've explained the following example more in depth in this blog post. When running this query:

SELECT a.actor_id, a.first_name, a.last_name, count(fa.film_id)
FROM actor a
LEFT JOIN film_actor fa ON a.actor_id = fa.actor_id
WHERE film_id < 10
GROUP BY a.actor_id, a.first_name, a.last_name
ORDER BY count(fa.film_id) ASC;

The LEFT JOIN doesn't really have any useful effect, because even if an actor did not play in a film, the actor will be filtered, as its FILM_ID will be NULL and the WHERE clause will filter such a row. The result is something like:

ACTOR_ID  FIRST_NAME  LAST_NAME  COUNT
--------------------------------------
194       MERYL       ALLEN      1
198       MARY        KEITEL     1
30        SANDRA      PECK       1
85        MINNIE      ZELLWEGER  1
123       JULIANNE    DENCH      1

I.e. just as if we inner joined the two tables. If we move the filter predicate in the ON clause, it now becomes a criteria for the outer join:

SELECT a.actor_id, a.first_name, a.last_name, count(fa.film_id)
FROM actor a
LEFT JOIN film_actor fa ON a.actor_id = fa.actor_id
  AND film_id < 10
GROUP BY a.actor_id, a.first_name, a.last_name
ORDER BY count(fa.film_id) ASC;

Meaning the result will contain actors without any films, or without any films with FILM_ID < 10

ACTOR_ID  FIRST_NAME  LAST_NAME     COUNT
-----------------------------------------
3         ED          CHASE         0
4         JENNIFER    DAVIS         0
5         JOHNNY      LOLLOBRIGIDA  0
6         BETTE       NICHOLSON     0
...
1         PENELOPE    GUINESS       1
200       THORA       TEMPLE        1
2         NICK        WAHLBERG      1
198       MARY        KEITEL        1

In short

Always put your predicate where it makes most sense, logically.

SQL Joins Vs SQL Subqueries (Performance)?

I know this is an old post, but I think this is a very important topic, especially nowadays where we have 10M+ records and talk about terabytes of data.

I will also weight in with the following observations. I have about 45M records in my table ([data]), and about 300 records in my [cats] table. I have extensive indexing for all of the queries I am about to talk about.

Consider Example 1:

UPDATE d set category = c.categoryname
FROM [data] d
JOIN [cats] c on c.id = d.catid

versus Example 2:

UPDATE d set category = (SELECT TOP(1) c.categoryname FROM [cats] c where c.id = d.catid)
FROM [data] d

Example 1 took about 23 mins to run. Example 2 took around 5 mins.

So I would conclude that sub-query in this case is much faster. Of course keep in mind that I am using M.2 SSD drives capable of i/o @ 1GB/sec (thats bytes not bits), so my indexes are really fast too. So this may affect the speeds too in your circumstance

If its a one-off data cleansing, probably best to just leave it run and finish. I use TOP(10000) and see how long it takes and multiply by number of records before I hit the big query.

If you are optimizing production databases, I would strongly suggest pre-processing data, i.e. use triggers or job-broker to async update records, so that real-time access retrieves static data.

MySQL LEFT JOIN 3 tables

You are trying to join Person_Fear.PersonID onto Person_Fear.FearID - This doesn't really make sense. You probably want something like:

SELECT Persons.Name, Persons.SS, Fears.Fear FROM Persons
LEFT JOIN Person_Fear
    INNER JOIN Fears
    ON Person_Fear.FearID = Fears.FearID
ON Person_Fear.PersonID = Persons.PersonID

This joins Persons onto Fears via the intermediate table Person_Fear. Because the join between Persons and Person_Fear is a LEFT JOIN, you will get all Persons records.

Alternatively:

SELECT Persons.Name, Persons.SS, Fears.Fear FROM Persons
LEFT JOIN Person_Fear ON Person_Fear.PersonID = Persons.PersonID
LEFT JOIN Fears ON Person_Fear.FearID = Fears.FearID

How to join on multiple columns in Pyspark?

You should use & / | operators and be careful about operator precedence (== has lower precedence than bitwise AND and OR):

df1 = sqlContext.createDataFrame(
    [(1, "a", 2.0), (2, "b", 3.0), (3, "c", 3.0)],
    ("x1", "x2", "x3"))

df2 = sqlContext.createDataFrame(
    [(1, "f", -1.0), (2, "b", 0.0)], ("x1", "x2", "x3"))

df = df1.join(df2, (df1.x1 == df2.x1) & (df1.x2 == df2.x2))
df.show()

## +---+---+---+---+---+---+
## | x1| x2| x3| x1| x2| x3|
## +---+---+---+---+---+---+
## |  2|  b|3.0|  2|  b|0.0|
## +---+---+---+---+---+---+

How to join (merge) data frames (inner, outer, left, right)

There are some good examples of doing this over at the R Wiki. I'll steal a couple here:

Merge Method

Since your keys are named the same the short way to do an inner join is merge():

merge(df1,df2)

a full inner join (all records from both tables) can be created with the "all" keyword:

merge(df1,df2, all=TRUE)

a left outer join of df1 and df2:

merge(df1,df2, all.x=TRUE)

a right outer join of df1 and df2:

merge(df1,df2, all.y=TRUE)

you can flip 'em, slap 'em and rub 'em down to get the other two outer joins you asked about :)

Subscript Method

A left outer join with df1 on the left using a subscript method would be:

df1[,"State"]<-df2[df1[ ,"Product"], "State"]

The other combination of outer joins can be created by mungling the left outer join subscript example. (yeah, I know that's the equivalent of saying "I'll leave it as an exercise for the reader...")

What is the difference between join and merge in Pandas?

I always use join on indices:

import pandas as pd
left = pd.DataFrame({'key': ['foo', 'bar'], 'val': [1, 2]}).set_index('key')
right = pd.DataFrame({'key': ['foo', 'bar'], 'val': [4, 5]}).set_index('key')
left.join(right, lsuffix='_l', rsuffix='_r')

     val_l  val_r
key            
foo      1      4
bar      2      5

The same functionality can be had by using merge on the columns follows:

left = pd.DataFrame({'key': ['foo', 'bar'], 'val': [1, 2]})
right = pd.DataFrame({'key': ['foo', 'bar'], 'val': [4, 5]})
left.merge(right, on=('key'), suffixes=('_l', '_r'))

   key  val_l  val_r
0  foo      1      4
1  bar      2      5

Joining 2 SQL SELECT result sets into one

Use a FULL OUTER JOIN:

select 
   a.col_a,
   a.col_b,
   b.col_c
from
   (select col_a,col_bfrom tab1) a
join 
   (select col_a,col_cfrom tab2) b 
on a.col_a= b.col_a

How to join multiple collections with $lookup in mongodb

You can actually chain multiple $lookup stages. Based on the names of the collections shared by profesor79, you can do this :

db.sivaUserInfo.aggregate([
    {
        $lookup: {
           from: "sivaUserRole",
           localField: "userId",
           foreignField: "userId",
           as: "userRole"
        }
    },
    {
        $unwind: "$userRole"
    },
    {
        $lookup: {
            from: "sivaUserInfo",
            localField: "userId",
            foreignField: "userId",
            as: "userInfo"
        }
    },
    {
        $unwind: "$userInfo"
    }
])

This will return the following structure :

{
    "_id" : ObjectId("56d82612b63f1c31cf906003"),
    "userId" : "AD",
    "phone" : "0000000000",
    "userRole" : {
        "_id" : ObjectId("56d82612b63f1c31cf906003"),
        "userId" : "AD",
        "role" : "admin"
    },
    "userInfo" : {
        "_id" : ObjectId("56d82612b63f1c31cf906003"),
        "userId" : "AD",
        "phone" : "0000000000"
    }
}

Maybe this could be considered an anti-pattern because MongoDB wasn't meant to be relational but it is useful.

SQL left join vs multiple tables on FROM line?

I think there are some good reasons on this page to adopt the second method -using explicit JOINs. The clincher though is that when the JOIN criteria are removed from the WHERE clause it becomes much easier to see the remaining selection criteria in the WHERE clause.

In really complex SELECT statements it becomes much easier for a reader to understand what is going on.

What is the difference between JOIN and JOIN FETCH when using JPA and Hibernate

In this two queries, you are using JOIN to query all employees that have at least one department associated.

But, the difference is: in the first query you are returning only the Employes for the Hibernate. In the second query, you are returning the Employes and all Departments associated.

So, if you use the second query, you will not need to do a new query to hit the database again to see the Departments of each Employee.

You can use the second query when you are sure that you will need the Department of each Employee. If you not need the Department, use the first query.

I recomend read this link if you need to apply some WHERE condition (what you probably will need): How to properly express JPQL "join fetch" with "where" clause as JPA 2 CriteriaQuery?

Update

If you don't use fetch and the Departments continue to be returned, is because your mapping between Employee and Department (a @OneToMany) are setted with FetchType.EAGER. In this case, any HQL (with fetch or not) query with FROM Employee will bring all Departments. Remember that all mapping *ToOne (@ManyToOne and @OneToOne) are EAGER by default.

What is the difference between "INNER JOIN" and "OUTER JOIN"?

1.Inner Join: Also called as Join. It returns the rows present in both the Left table, and right table only if there is a match. Otherwise, it returns zero records.

Example:

SELECT
  e1.emp_name,
  e2.emp_salary    
FROM emp1 e1
INNER JOIN emp2 e2
  ON e1.emp_id = e2.emp_id

output1

2.Full Outer Join: Also called as Full Join. It returns all the rows present in both the Left table, and right table.

Example:

SELECT
  e1.emp_name,
  e2.emp_salary    
FROM emp1 e1
FULL OUTER JOIN emp2 e2
  ON e1.emp_id = e2.emp_id

output2

3.Left Outer join: Or simply called as Left Join. It returns all the rows present in the Left table and matching rows from the right table (if any).

4.Right Outer Join: Also called as Right Join. It returns matching rows from the left table (if any), and all the rows present in the Right table.

joins

Advantages of Joins

  1. Executes faster.

MySQL Multiple Joins in one query?

Multi joins in SQL work by progressively creating derived tables one after the other. See this link explaining the process:

https://www.interfacett.com/blogs/multiple-joins-work-just-like-single-joins/

How to use multiple LEFT JOINs in SQL?

You have two choices, depending on your table order

create table aa (sht int)
create table cc (sht int)
create table cd (sht int)
create table ab (sht int)

-- type 1    
select * from cd
inner join cc on cd.sht = cc.sht
LEFT JOIN ab ON ab.sht = cd.sht
LEFT JOIN aa ON aa.sht = cc.sht

-- type 2
select * from cc
inner join cc on cd.sht = cc.sht
LEFT JOIN ab
LEFT JOIN aa
ON aa.sht = ab.sht
ON ab.sht = cd.sht

LINQ: combining join and group by

Once you've done this

group p by p.SomeId into pg  

you no longer have access to the range variables used in the initial from. That is, you can no longer talk about p or bp, you can only talk about pg.

Now, pg is a group and so contains more than one product. All the products in a given pg group have the same SomeId (since that's what you grouped by), but I don't know if that means they all have the same BaseProductId.

To get a base product name, you have to pick a particular product in the pg group (As you are doing with SomeId and CountryCode), and then join to BaseProducts.

var result = from p in Products                         
 group p by p.SomeId into pg                         
 // join *after* group
 join bp in BaseProducts on pg.FirstOrDefault().BaseProductId equals bp.Id         
 select new ProductPriceMinMax { 
       SomeId = pg.FirstOrDefault().SomeId, 
       CountryCode = pg.FirstOrDefault().CountryCode, 
       MinPrice = pg.Min(m => m.Price), 
       MaxPrice = pg.Max(m => m.Price),
       BaseProductName = bp.Name  // now there is a 'bp' in scope
 };

That said, this looks pretty unusual and I think you should step back and consider what you are actually trying to retrieve.

Multiple left joins on multiple tables in one query

This kind of query should work - after rewriting with explicit JOIN syntax:

SELECT something
FROM   master      parent
JOIN   master      child ON child.parent_id = parent.id
LEFT   JOIN second parentdata ON parentdata.id = parent.secondary_id
LEFT   JOIN second childdata ON childdata.id = child.secondary_id
WHERE  parent.parent_id = 'rootID'

The tripping wire here is that an explicit JOIN binds before "old style" CROSS JOIN with comma (,). I quote the manual here:

In any case JOIN binds more tightly than the commas separating FROM-list items.

After rewriting the first, all joins are applied left-to-right (logically - Postgres is free to rearrange tables in the query plan otherwise) and it works.

Just to make my point, this would work, too:

SELECT something
FROM   master parent
LEFT   JOIN second parentdata ON parentdata.id = parent.secondary_id
,      master child
LEFT   JOIN second childdata ON childdata.id = child.secondary_id
WHERE  child.parent_id = parent.id
AND    parent.parent_id = 'rootID'

But explicit JOIN syntax is generally preferable, as your case illustrates once again.

And be aware that multiple (LEFT) JOIN can multiply rows:

SQL Inner-join with 3 tables?

SELECT 
A.P_NAME AS [INDIVIDUAL NAME],B.F_DETAIL AS [INDIVIDUAL FEATURE],C.PL_PLACE AS [INDIVIDUAL LOCATION]
FROM 
[dbo].[PEOPLE] A
INNER JOIN 
[dbo].[FEATURE] B ON A.P_FEATURE = B.F_ID
INNER JOIN 
[dbo].[PEOPLE_LOCATION] C ON A.P_LOCATION = C.PL_ID

MySQL LEFT JOIN Multiple Conditions

SELECT * FROM a WHERE a.group_id IN 
(SELECT group_id FROM b WHERE b.user_id!=$_SESSION{'[user_id']} AND b.group_id = a.group_id)
WHERE a.keyword LIKE '%".$keyword."%';

Python: How exactly can you take a string, split it, reverse it and join it back together again?

Not fitting 100% to this particular question but if you want to split from the back you can do it like this:

theStringInQuestion[::-1].split('/', 1)[1][::-1]

This code splits once at symbol '/' from behind.

SQL update from one Table to another based on a ID match

For SQL Server 2008 + Using MERGE rather than the proprietary UPDATE ... FROM syntax has some appeal.

As well as being standard SQL and thus more portable it also will raise an error in the event of there being multiple joined rows on the source side (and thus multiple possible different values to use in the update) rather than having the final result be undeterministic.

MERGE INTO Sales_Import
   USING RetrieveAccountNumber
      ON Sales_Import.LeadID = RetrieveAccountNumber.LeadID
WHEN MATCHED THEN
   UPDATE 
      SET AccountNumber = RetrieveAccountNumber.AccountNumber;

Unfortunately the choice of which to use may not come down purely to preferred style however. The implementation of MERGE in SQL Server has been afflicted with various bugs. Aaron Bertrand has compiled a list of the reported ones here.

T-SQL: Selecting rows to delete via joins

Let's say you have 2 tables, one with a Master set (eg. Employees) and one with a child set (eg. Dependents) and you're wanting to get rid of all the rows of data in the Dependents table that cannot key up with any rows in the Master table.

delete from Dependents where EmpID in (
select d.EmpID from Employees e 
    right join Dependents d on e.EmpID = d.EmpID
    where e.EmpID is null)

The point to notice here is that you're just collecting an 'array' of EmpIDs from the join first, the using that set of EmpIDs to do a Deletion operation on the Dependents table.

Trying to use INNER JOIN and GROUP BY SQL with SUM Function, Not Working

If you need to retrieve more columns other than columns which are in group by then you can consider below query. Check it once whether it is performing well or not.

SELECT 
a.[CUSTOMER ID], 
a.[NAME], 
(select SUM(b.[AMOUNT]) from INV_DATA b
where b.[CUSTOMER ID] = a.[CUSTOMER ID]
GROUP BY b.[CUSTOMER ID]) AS [TOTAL AMOUNT]
FROM RES_DATA a

joining two select statements

SELECT *
FROM
  (First_query) AS ONE
LEFT OUTER JOIN
  (Second_query ) AS TWO ON ONE.First_query_ID = TWO.Second_Query_ID;

Difference between left join and right join in SQL Server

select fields 
from tableA --left
left join tableB --right
on tableA.key = tableB.key

The table in the from in this example tableA, is on the left side of relation.

tableA <- tableB
[left]------[right]

So if you want to take all rows from the left table (tableA), even if there are no matches in the right table (tableB), you'll use the "left join".

And if you want to take all rows from the right table (tableB), even if there are no matches in the left table (tableA), you will use the right join.

Thus, the following query is equivalent to that used above.

select fields
from tableB 
right join tableA on tableB.key = tableA.key

How to exclude rows that don't join with another table?

Another solution is:

SELECT * FROM TABLE1 WHERE id NOT IN (SELECT id FROM TABLE2)

What is the syntax for an inner join in LINQ to SQL?

try instead this,

var dealer = from d in Dealer
             join dc in DealerContact on d.DealerID equals dc.DealerID
             select d;

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

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

You must use OR here, not AND.

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

MySQL Join Where Not Exists

I'd probably use a LEFT JOIN, which will return rows even if there's no match, and then you can select only the rows with no match by checking for NULLs.

So, something like:

SELECT V.*
FROM voter V LEFT JOIN elimination E ON V.id = E.voter_id
WHERE E.voter_id IS NULL

Whether that's more or less efficient than using a subquery depends on optimization, indexes, whether its possible to have more than one elimination per voter, etc.

Pandas join issue: columns overlap but no suffix specified

Mainly join is used exclusively to join based on the index,not on the attribute names,so change the attributes names in two different dataframes,then try to join,they will be joined,else this error is raised

Join between tables in two different databases?

SELECT *
FROM A.tableA JOIN B.tableB 

or

SELECT *
  FROM A.tableA JOIN B.tableB
  ON A.tableA.id = B.tableB.a_id;

pandas three-way joining multiple dataframes on columns

This can also be done as follows for a list of dataframes df_list:

df = df_list[0]
for df_ in df_list[1:]:
    df = df.merge(df_, on='join_col_name')

or if the dataframes are in a generator object (e.g. to reduce memory consumption):

df = next(df_list)
for df_ in df_list:
    df = df.merge(df_, on='join_col_name')

SQL Inner Join On Null Values

I'm pretty sure that the join doesn't even do what you want. If there are 100 records in table a with a null qid and 100 records in table b with a null qid, then the join as written should make a cross join and give 10,000 results for those records. If you look at the following code and run the examples, I think that the last one is probably more the result set you intended:

create table #test1 (id int identity, qid int)
create table #test2 (id int identity, qid int)

Insert #test1 (qid)
select null
union all
select null
union all
select 1
union all
select 2
union all
select null

Insert #test2 (qid)
select null
union all
select null
union all
select 1
union all
select 3
union all
select null


select * from #test2 t2
join #test1 t1 on t2.qid = t1.qid

select * from #test2 t2
join #test1 t1 on isnull(t2.qid, 0) = isnull(t1.qid, 0)


select * from #test2 t2
join #test1 t1 on 
 t1.qid = t2.qid OR ( t1.qid IS NULL AND t2.qid IS NULL )


select t2.id, t2.qid, t1.id, t1.qid from #test2 t2
join #test1 t1 on t2.qid = t1.qid
union all
select null, null,id, qid from #test1 where qid is null
union all
select id, qid, null, null from #test2  where qid is null

Pandas Merging 101

A supplemental visual view of pd.concat([df0, df1], kwargs). Notice that, kwarg axis=0 or axis=1 's meaning is not as intuitive as df.mean() or df.apply(func)


on pd.concat([df0, df1])

What is difference between INNER join and OUTER join

Inner join matches tables on keys, but outer join matches keys just for one side. For example when you use left outer join the query brings the whole left side table and matches the right side to the left table primary key and where there is not matched places null.

How to do join on multiple criteria, returning all combinations of both criteria

select one.*, two.meal
from table1 as one
left join table2 as two
on (one.weddingtable = two.weddingtable and one.tableseat = two.tableseat)

LINQ Join with Multiple Conditions in On Clause

You can't do it like that. The join clause (and the Join() extension method) supports only equijoins. That's also the reason, why it uses equals and not ==. And even if you could do something like that, it wouldn't work, because join is an inner join, not outer join.

MySQL JOIN the most recent row only?

If you are working with heavy queries, you better move the request for the latest row in the where clause. It is a lot faster and looks cleaner.

SELECT c.*,
FROM client AS c
LEFT JOIN client_calling_history AS cch ON cch.client_id = c.client_id
WHERE
   cch.cchid = (
      SELECT MAX(cchid)
      FROM client_calling_history
      WHERE client_id = c.client_id AND cal_event_id = c.cal_event_id
   )

What's the most concise way to read query parameters in AngularJS?

It can be done by two ways:

  1. Using $routeParams

Best and recommended solution is to use $routeParams into your controller. It Requires the ngRoute module to be installed.

   function MyController($scope, $routeParams) {
      // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
      // Route: /Chapter/:chapterId/Section/:sectionId
      // $routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}
      var search = $routeParams.search;
  }
  1. Using $location.search().

There is a caveat here. It will work only with HTML5 mode. By default, it does not work for the URL which does not have hash(#) in it http://localhost/test?param1=abc&param2=def

You can make it work by adding #/ in the URL. http://localhost/test#/?param1=abc&param2=def

$location.search() to return an object like:

{
  param1: 'abc',
  param2: 'def'
}

UIImage: Resize, then Crop

Swift version:

    static func imageWithImage(image:UIImage, newSize:CGSize) ->UIImage {
    UIGraphicsBeginImageContextWithOptions(newSize, true, UIScreen.mainScreen().scale);
    image.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))

    let newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();
    return newImage
}

What is the difference between "#!/usr/bin/env bash" and "#!/usr/bin/bash"?

Running a command through /usr/bin/env has the benefit of looking for whatever the default version of the program is in your current environment.

This way, you don't have to look for it in a specific place on the system, as those paths may be in different locations on different systems. As long as it's in your path, it will find it.

One downside is that you will be unable to pass more than one argument (e.g. you will be unable to write /usr/bin/env awk -f) if you wish to support Linux, as POSIX is vague on how the line is to be interpreted, and Linux interprets everything after the first space to denote a single argument. You can use /usr/bin/env -S on some versions of env to get around this, but then the script will become even less portable and break on fairly recent systems (e.g. even Ubuntu 16.04 if not later).

Another downside is that since you aren't calling an explicit executable, it's got the potential for mistakes, and on multiuser systems security problems (if someone managed to get their executable called bash in your path, for example).

#!/usr/bin/env bash #lends you some flexibility on different systems
#!/usr/bin/bash     #gives you explicit control on a given system of what executable is called

In some situations, the first may be preferred (like running python scripts with multiple versions of python, without having to rework the executable line). But in situations where security is the focus, the latter would be preferred, as it limits code injection possibilities.

How to copy folders to docker image from Dockerfile?

Use ADD (docs)

The ADD command can accept as a <src> parameter:

  1. A folder within the build folder (the same folder as your Dockerfile). You would then add a line in your Dockerfile like this:
ADD folder /path/inside/your/container

or

  1. A single-file archive anywhere in your host filesystem. To create an archive use the command:
tar -cvzf newArchive.tar.gz /path/to/your/folder

You would then add a line to your Dockerfile like this:

ADD /path/to/archive/newArchive.tar.gz  /path/inside/your/container

Notes:

  • ADD will automatically extract your archive.
  • presence/absence of trailing slashes is important, see the linked docs

How do I set the default locale in the JVM?

In the answers here, up to now, we find two ways of changing the JRE locale setting:

  • Programatically, using Locale.setDefault() (which, in my case, was the solution, since I didn't want to require any action of the user):

    Locale.setDefault(new Locale("pt", "BR"));
    
  • Via arguments to the JVM:

    java -jar anApp.jar -Duser.language=pt-BR
    

But, just as reference, I want to note that, on Windows, there is one more way of changing the locale used by the JRE, as documented here: changing the system-wide language.

Note: You must be logged in with an account that has Administrative Privileges.

  1. Click Start > Control Panel.

  2. Windows 7 and Vista: Click Clock, Language and Region > Region and Language.

    Windows XP: Double click the Regional and Language Options icon.

    The Regional and Language Options dialog box appears.

  3. Windows 7: Click the Administrative tab.

    Windows XP and Vista: Click the Advanced tab.

    (If there is no Advanced tab, then you are not logged in with administrative privileges.)

  4. Under the Language for non-Unicode programs section, select the desired language from the drop down menu.

  5. Click OK.

    The system displays a dialog box asking whether to use existing files or to install from the operating system CD. Ensure that you have the CD ready.

  6. Follow the guided instructions to install the files.

  7. Restart the computer after the installation is complete.

Certainly on Linux the JRE also uses the system settings to determine which locale to use, but the instructions to set the system-wide language change from distro to distro.

Aborting a shell script if any command returns a non-zero value

If you have cleanup you need to do on exit, you can also use 'trap' with the pseudo-signal ERR. This works the same way as trapping INT or any other signal; bash throws ERR if any command exits with a nonzero value:

# Create the trap with   
#    trap COMMAND SIGNAME [SIGNAME2 SIGNAME3...]
trap "rm -f /tmp/$MYTMPFILE; exit 1" ERR INT TERM
command1
command2
command3
# Partially turn off the trap.
trap - ERR
# Now a control-C will still cause cleanup, but
# a nonzero exit code won't:
ps aux | grep blahblahblah

Or, especially if you're using "set -e", you could trap EXIT; your trap will then be executed when the script exits for any reason, including a normal end, interrupts, an exit caused by the -e option, etc.

What is the best way to call a script from another script?

Use import test1 for the 1st use - it will execute the script. For later invocations, treat the script as an imported module, and call the reload(test1) method.

When reload(module) is executed:

  • Python modules’ code is recompiled and the module-level code reexecuted, defining a new set of objects which are bound to names in the module’s dictionary. The init function of extension modules is not called

A simple check of sys.modules can be used to invoke the appropriate action. To keep referring to the script name as a string ('test1'), use the 'import()' builtin.

import sys
if sys.modules.has_key['test1']:
    reload(sys.modules['test1'])
else:
    __import__('test1')

SOAP PHP fault parsing WSDL: failed to load external entity?

The problem may lie in you don't have enabled openssl extention in your php.ini file

go to your php.ini file end remove ; in line where extension=openssl is

Of course in question code there is a part of code responsible for checking whether extension is loaded or not but maybe some uncautious forget about it

File upload progress bar with jQuery

Kathir's answer is great as he solves that problem with just jQuery. I just wanted to make some additions to his answer to work his code with a beautiful HTML progress bar:

$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();

xhr.upload.addEventListener("progress", function(evt) {
  if (evt.lengthComputable) {
    var percentComplete = evt.loaded / evt.total;
    percentComplete = parseInt(percentComplete * 100);

    $('.progress-bar').width(percentComplete+'%');
    $('.progress-bar').html(percentComplete+'%');

  }
}, false);

return xhr;
},
url: posturlfile,
type: "POST",
data: JSON.stringify(fileuploaddata),
contentType: "application/json",
dataType: "json",
success: function(result) {
console.log(result);
}
});

Here is the HTML code of progress bar, I used Bootstrap 3 for the progress bar element:

<div class="progress" style="display:none;">
<div class="progress-bar progress-bar-success progress-bar-striped 
active" role="progressbar"
aria-valuemin="0" aria-valuemax="100" style="width:0%">
0%
</div>
</div>

Bootstrap 3 jquery event for active tab change

To add to Mosh Feu answer, if the tabs where created on the fly like in my case, you would use the following code

$(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
    var tab = $(e.target);
    var contentId = tab.attr("href");

    //This check if the tab is active
    if (tab.parent().hasClass('active')) {
         console.log('the tab with the content id ' + contentId + ' is visible');
    } else {
         console.log('the tab with the content id ' + contentId + ' is NOT visible');
    }

});

I hope this helps someone

URL rewriting with PHP

this is an .htaccess file that forward almost all to index.php

# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_URI} !-l
RewriteCond %{REQUEST_FILENAME} !\.(ico|css|png|jpg|gif|js)$ [NC]
# otherwise forward it to index.php
RewriteRule . index.php

then is up to you parse $_SERVER["REQUEST_URI"] and route to picture.php or whatever

How to automatically insert a blank row after a group of data

Select your array, including column labels, DATA > Outline -Subtotal, At each change in: column1, Use function: Count, Add subtotal to: column3, check Replace current subtotals and Summary below data, OK.

Filter and select for Column1, Text Filters, Contains..., Count, OK. Select all visible apart from the labels and delete contents. Remove filter and, if desired, ungroup rows.

Bootstrap 3 .img-responsive images are not responsive inside fieldset in FireFox

just add .col-xs-12 to your responsive image. It's should work.

#1062 - Duplicate entry for key 'PRIMARY'

I solved it by changing the "lock" property from "shared" to "exclusive":

ALTER TABLE `table` 
CHANGE COLUMN `ID` `ID` INT(11) NOT NULL AUTO_INCREMENT COMMENT '' , LOCK = EXCLUSIVE;

How to set the size of button in HTML

If using the following HTML:

<button id="submit-button"></button>

Style can be applied through JS using the style object available on an HTMLElement.

To set height and width to 200px of the above example button, this would be the JS:

var myButton = document.getElementById('submit-button');
myButton.style.height = '200px';
myButton.style.width= '200px';

I believe with this method, you are not directly writing CSS (inline or external), but using JavaScript to programmatically alter CSS Declarations.

How do you plot bar charts in gnuplot?

You can directly use the style histograms provide by gnuplot. This is an example if you have two file in output:

set style data histograms
 set style fill solid
 set boxwidth 0.5
 plot "file1.dat" using 5 title "Total1" lt rgb "#406090",\
      "file2.dat" using 5 title "Total2" lt rgb "#40FF00"

Using crontab to execute script every minute and another every 24 hours

This is the format of /etc/crontab:

# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed

I recommend copy & pasting that into the top of your crontab file so that you always have the reference handy. RedHat systems are setup that way by default.

To run something every minute:

* * * * * username /var/www/html/a.php

To run something at midnight of every day:

0 0 * * * username /var/www/html/reset.php

You can either include /usr/bin/php in the command to run, or you can make the php scripts directly executable:

chmod +x file.php

Start your php file with a shebang so that your shell knows which interpreter to use:

#!/usr/bin/php
<?php
// your code here

Calculating distance between two points (Latitude, Longitude)

As you're using SQL 2008 or later, I'd recommend checking out the GEOGRAPHY data type. SQL has built in support for geospatial queries.

e.g. you'd have a column in your table of type GEOGRAPHY which would be populated with a geospatial representation of the coordinates (check out the MSDN reference linked above for examples). This datatype then exposes methods allowing you to perform a whole host of geospatial queries (e.g. finding the distance between 2 points)

How can I set multiple CSS styles in JavaScript?

We can add styles function to Node prototype:

Node.prototype.styles=function(obj){ for (var k in obj)    this.style[k] = obj[k];}

Then, simply call styles method on any Node:

elem.styles({display:'block', zIndex:10, transitionDuration:'1s', left:0});

It will preserve any other existing styles and overwrite values present in the object parameter.

Top 1 with a left join

The key to debugging situations like these is to run the subquery/inline view on its' own to see what the output is:

  SELECT TOP 1 
         dm.marker_value, 
         dum.profile_id
    FROM DPS_USR_MARKERS dum (NOLOCK)
    JOIN DPS_MARKERS dm (NOLOCK) ON dm.marker_id= dum.marker_id 
                                AND dm.marker_key = 'moneyBackGuaranteeLength'
ORDER BY dm.creation_date

Running that, you would see that the profile_id value didn't match the u.id value of u162231993, which would explain why any mbg references would return null (thanks to the left join; you wouldn't get anything if it were an inner join).

You've coded yourself into a corner using TOP, because now you have to tweak the query if you want to run it for other users. A better approach would be:

   SELECT u.id, 
          x.marker_value 
     FROM DPS_USER u
LEFT JOIN (SELECT dum.profile_id,
                  dm.marker_value,
                  dm.creation_date
             FROM DPS_USR_MARKERS dum (NOLOCK)
             JOIN DPS_MARKERS dm (NOLOCK) ON dm.marker_id= dum.marker_id 
                                         AND dm.marker_key = 'moneyBackGuaranteeLength'
           ) x ON x.profile_id = u.id
     JOIN (SELECT dum.profile_id,
                  MAX(dm.creation_date) 'max_create_date'
             FROM DPS_USR_MARKERS dum (NOLOCK)
             JOIN DPS_MARKERS dm (NOLOCK) ON dm.marker_id= dum.marker_id 
                                         AND dm.marker_key = 'moneyBackGuaranteeLength'
         GROUP BY dum.profile_id) y ON y.profile_id = x.profile_id
                                   AND y.max_create_date = x.creation_date
    WHERE u.id = 'u162231993'

With that, you can change the id value in the where clause to check records for any user in the system.

download file using an ajax request

Your needs are covered by window.location('download.php');
But I think that you need to pass the file to be downloaded, not always download the same file, and that's why you are using a request, one option is to create a php file as simple as showfile.php and do a request like

var myfile = filetodownload.txt
var url = "shofile.php?file=" + myfile ;
ajaxRequest.open("GET", url, true);

showfile.php

<?php
$file = $_GET["file"] 
echo $file;

where file is the file name passed via Get or Post in the request and then catch the response in a function simply

if(ajaxRequest.readyState == 4){
                        var file = ajaxRequest.responseText;
                        window.location = 'downfile.php?file=' + file;  
                    }
                }

How to remove all white space from the beginning or end of a string?

use the String.Trim() function.

string foo = "   hello ";
string bar = foo.Trim();

Console.WriteLine(bar); // writes "hello"

Simplest way to form a union of two lists

If it is a list, you can also use AddRange method.

var listB = new List<int>{3, 4, 5};  
var listA = new List<int>{1, 2, 3, 4, 5};

listA.AddRange(listB); // listA now has elements of listB also.

If you need new list (and exclude the duplicate), you can use Union

  var listB = new List<int>{3, 4, 5};  
  var listA = new List<int>{1, 2, 3, 4, 5};
  var listFinal = listA.Union(listB);

If you need new list (and include the duplicate), you can use Concat

  var listB = new List<int>{3, 4, 5};  
  var listA = new List<int>{1, 2, 3, 4, 5};
  var listFinal = listA.Concat(listB);

If you need common items, you can use Intersect.

var listB = new List<int>{3, 4, 5};  
var listA = new List<int>{1, 2, 3, 4};  
var listFinal = listA.Intersect(listB); //3,4

How do you close/hide the Android soft keyboard using Java?

KOTLIN SOLUTION IN A FRAGMENT:

fun hideSoftKeyboard() {
        val view = activity?.currentFocus
        view?.let { v ->
            val imm =
                activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager // or context
            imm.hideSoftInputFromWindow(v.windowToken, 0)
        }
}

Check your manifest doesn't have this parameter associated with your activity:

android:windowSoftInputMode="stateAlwaysHidden"

Merging Cells in Excel using C#

Worksheet["YourRange"].Merge();

How to programmatically move, copy and delete files and directories on SD?

Function for moving files:

private void moveFile(File file, File dir) throws IOException {
    File newFile = new File(dir, file.getName());
    FileChannel outputChannel = null;
    FileChannel inputChannel = null;
    try {
        outputChannel = new FileOutputStream(newFile).getChannel();
        inputChannel = new FileInputStream(file).getChannel();
        inputChannel.transferTo(0, inputChannel.size(), outputChannel);
        inputChannel.close();
        file.delete();
    } finally {
        if (inputChannel != null) inputChannel.close();
        if (outputChannel != null) outputChannel.close();
    }

}

How to pass the password to su/sudo/ssh without overriding the TTY?

Take a look at expect linux utility.

It allows you to send output to stdio based on simple pattern matching on stdin.

SQL Server Insert Example

To insert a single row of data:

INSERT INTO USERS
VALUES (1, 'Mike', 'Jones');

To do an insert on specific columns (as opposed to all of them) you must specify the columns you want to update.

INSERT INTO USERS (FIRST_NAME, LAST_NAME)
VALUES ('Stephen', 'Jiang');

To insert multiple rows of data in SQL Server 2008 or later:

INSERT INTO USERS VALUES
(2, 'Michael', 'Blythe'),
(3, 'Linda', 'Mitchell'),
(4, 'Jillian', 'Carson'),
(5, 'Garrett', 'Vargas');

To insert multiple rows of data in earlier versions of SQL Server, use "UNION ALL" like so:

INSERT INTO USERS (FIRST_NAME, LAST_NAME)
SELECT 'James', 'Bond' UNION ALL
SELECT 'Miss', 'Moneypenny' UNION ALL
SELECT 'Raoul', 'Silva'

Note, the "INTO" keyword is optional in INSERT queries. Source and more advanced querying can be found here.

List all devices, partitions and volumes in Powershell

This is pretty old, but I found following worth noting:

PS N:\> (measure-command {Get-WmiObject -Class Win32_LogicalDisk|select -property deviceid|%{$_.deviceid}|out-host}).totalmilliseconds
...
928.7403
PS N:\> (measure-command {gdr -psprovider 'filesystem'|%{$_.name}|out-host}).totalmilliseconds
...
169.474

Without filtering properties, on my test system, 4319.4196ms to 1777.7237ms. Unless I need a PS-Drive object returned, I'll stick with WMI.

EDIT: I think we have a winner: PS N:> (measure-command {[System.IO.DriveInfo]::getdrives()|%{$_.name}|out-host}).to??talmilliseconds 110.9819

Get div to take up 100% body height, minus fixed-height header and footer

You can take advatange of the css property Box Sizing.

#content { 
    height: 100%;
    -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
    -moz-box-sizing: border-box;    /* Firefox, other Gecko */
    box-sizing: border-box;         /* Opera/IE 8+ */
    padding-top: 50px;
    margin-top: -50px;
    padding-bottom: 50px;
    margin-bottom: -50px;
}

See the JsFiddle.

"replace" function examples

Here's an example where I found the replace( ) function helpful for giving me insight. The problem required a long integer vector be changed into a character vector and with its integers replaced by given character values.

## figuring out replace( )
(test <- c(rep(1,3),rep(2,2),rep(3,1)))

which looks like

[1] 1 1 1 2 2 3

and I want to replace every 1 with an A and 2 with a B and 3 with a C

letts <- c("A","B","C")

so in my own secret little "dirty-verse" I used a loop

for(i in 1:3)
{test <- replace(test,test==i,letts[i])}

which did what I wanted

test
[1] "A" "A" "A" "B" "B" "C"

In the first sentence I purposefully left out that the real objective was to make the big vector of integers a factor vector and assign the integer values (levels) some names (labels).

So another way of doing the replace( ) application here would be

(test <- factor(test,labels=letts))
[1] A A A B B C
Levels: A B C

jQuery move to anchor location on page load

Description

You can do this using jQuery's .scrollTop() and .offset() method

Check out my sample and this jsFiddle Demonstration

Sample

$(function() {
    $(document).scrollTop( $("#header").offset().top );  
});

More Information

Static Classes In Java

All good answers, but I did not saw a reference to java.util.Collections which uses tons of static inner class for their static factor methods. So adding the same.

Adding an example from java.util.Collections which has multiple static inner class. Inner classes are useful to group code which needs to be accessed via outer class.

/**
 * @serial include
 */
static class UnmodifiableSet<E> extends UnmodifiableCollection<E>
                             implements Set<E>, Serializable {
    private static final long serialVersionUID = -9215047833775013803L;

    UnmodifiableSet(Set<? extends E> s)     {super(s);}
    public boolean equals(Object o) {return o == this || c.equals(o);}
    public int hashCode()           {return c.hashCode();}
}

Here is the static factor method in the java.util.Collections class

public static <T> Set<T> unmodifiableSet(Set<? extends T> s) {
    return new UnmodifiableSet<>(s);
}

How to Identify Microsoft Edge browser via CSS?

More accurate for Edge (do not include latest IE 15) is:

@supports (display:-ms-grid) { ... }

@supports (-ms-ime-align:auto) { ... } works for all Edge versions (currently up to IE15).

How to push a docker image to a private repository

Just three simple steps:

  1. docker login --username username

    • prompts for password if you omit --password which is recommended as it doesn't store it in your command history
  2. docker tag my-image username/my-repo

  3. docker push username/my-repo

Ajax success event not working

Put an alert() in your success callback to make sure it's being called at all.

If it's not, that's simply because the request wasn't successful at all, even though you manage to hit the server. Reasonable causes could be that a timeout expires, or something in your php code throws an exception.

Install the firebug addon for firefox, if you haven't already, and inspect the AJAX callback. You'll be able to see the response, and whether or not it receives a successful (200 OK) response. You can also put another alert() in the complete callback, which should definitely be invoked.

How to convert all tables in database to one collation?

Better option to change also collation of varchar columns inside table also

SELECT CONCAT('ALTER TABLE `', TABLE_NAME,'` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;') AS    mySQL
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA= "myschema"
AND TABLE_TYPE="BASE TABLE"

Additionnaly if you have data with forein key on non utf8 column before launch the bunch script use

SET foreign_key_checks = 0;

It means global SQL will be for mySQL :

SET foreign_key_checks = 0;
ALTER TABLE `table1` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE `table2` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE `tableXXX` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
SET foreign_key_checks = 1;

But take care if according mysql documentation http://dev.mysql.com/doc/refman/5.1/en/charset-column.html,

If you use ALTER TABLE to convert a column from one character set to another, MySQL attempts to map the data values, but if the character sets are incompatible, there may be data loss. "

EDIT: Specially with column type enum, it just crash completly enums set (even if there is no special caracters) https://bugs.mysql.com/bug.php?id=26731

Html helper for <input type="file" />

HTML Upload File ASP MVC 3.

Model: (Note that FileExtensionsAttribute is available in MvcFutures. It will validate file extensions client side and server side.)

public class ViewModel
{
    [Required, Microsoft.Web.Mvc.FileExtensions(Extensions = "csv", 
             ErrorMessage = "Specify a CSV file. (Comma-separated values)")]
    public HttpPostedFileBase File { get; set; }
}

HTML View:

@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new 
                                       { enctype = "multipart/form-data" }))
{
    @Html.TextBoxFor(m => m.File, new { type = "file" })
    @Html.ValidationMessageFor(m => m.File)
}

Controller action:

[HttpPost]
public ActionResult Action(ViewModel model)
{
    if (ModelState.IsValid)
    {
        // Use your file here
        using (MemoryStream memoryStream = new MemoryStream())
        {
            model.File.InputStream.CopyTo(memoryStream);
        }
    }
}

Converting an array to a function arguments list

A very readable example from another post on similar topic:

var args = [ 'p0', 'p1', 'p2' ];

function call_me (param0, param1, param2 ) {
    // ...
}

// Calling the function using the array with apply()
call_me.apply(this, args);

And here a link to the original post that I personally liked for its readability

Lua string to int

here is what you should put

local stringnumber = "10"
local a = tonumber(stringnumber)
print(a + 10)

output:

20

What is the difference between resource and endpoint?

Consider a server which has the information of users, missions and their reward points.

  1. Users and Reward Points are the resources
  2. An end point can relate to more than one resource
  3. Endpoints can be described using either a description or a full or partial URL

enter image description here

Source: API Endpoints vs Resources

What is the default value for enum variable?

It is whatever member of the enumeration represents the value 0. Specifically, from the documentation:

The default value of an enum E is the value produced by the expression (E)0.

As an example, take the following enum:

enum E
{
    Foo, Bar, Baz, Quux
}

Without overriding the default values, printing default(E) returns Foo since it's the first-occurring element.

However, it is not always the case that 0 of an enum is represented by the first member. For example, if you do this:

enum F
{
    // Give each element a custom value
    Foo = 1, Bar = 2, Baz = 3, Quux = 0
}

Printing default(F) will give you Quux, not Foo.

If none of the elements in an enum G correspond to 0:

enum G
{
    Foo = 1, Bar = 2, Baz = 3, Quux = 4
}

default(G) returns literally 0, although its type remains as G (as quoted by the docs above, a cast to the given enum type).

Firebug like plugin for Safari browser

Firebug lite plugin in Safari extensions didn't work (it's made by slicefactory, I don't think it's offical). btw, #2 works for me!

Remove Item in Dictionary based on Value

You can use the following as extension method

 public static void RemoveByValue<T,T1>(this Dictionary<T,T1> src , T1 Value)
    {
        foreach (var item in src.Where(kvp => kvp.Value.Equals( Value)).ToList())
        {
            src.Remove(item.Key);
        }
    }

How to query as GROUP BY in django?

If you mean to do aggregation you can use the aggregation features of the ORM:

from django.db.models import Count
Members.objects.values('designation').annotate(dcount=Count('designation'))

This results in a query similar to

SELECT designation, COUNT(designation) AS dcount
FROM members GROUP BY designation

and the output would be of the form

[{'designation': 'Salesman', 'dcount': 2}, 
 {'designation': 'Manager', 'dcount': 2}]

The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked

public static void DetachEntity<T>(this DbContext dbContext, T entity, string propertyName) where T: class, new()
{
   try
   {
      var dbEntity = dbContext.Find<T>(entity.GetProperty(propertyName));
      if (dbEntity != null)
          dbContext.Entry(dbEntity).State = EntityState.Detached;
      dbContext.Entry(entity).State = EntityState.Modified;
   }
   catch (Exception)
   {
        throw;
   }
}


 public static object GetProperty<T>(this T entity, string propertyName) where T : class, new()
 {
    try
    {
        Type type = entity.GetType();
        PropertyInfo propertyInfo = type.GetProperty(propertyName);
        object value = propertyInfo.GetValue(entity);
        return value;
    }
    catch (Exception)
    {
         throw;
    }
 }

I made this 2 extension methods, this is working really well.

Is there a way to use SVG as content in a pseudo element :before or :after

<div class="author_">Lord Byron</div>

_x000D_
_x000D_
.author_ {  font-family: 'Playfair Display', serif; font-size: 1.25em; font-weight: 700;letter-spacing: 0.25em; font-style: italic;_x000D_
  position:relative;_x000D_
  margin-top: -0.5em;_x000D_
  color: black;_x000D_
  z-index:1;_x000D_
  overflow:hidden;_x000D_
  text-align:center;_x000D_
 _x000D_
}_x000D_
_x000D_
_x000D_
.author_:after{_x000D_
   left:20px;_x000D_
  margin:0 -100% 0 0;_x000D_
  display: inline-block;_x000D_
  height: 10px;_x000D_
  content: url(data:image/svg+xml,%0A%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22120px%22%20height%3D%2220px%22%20viewBox%3D%220%200%201200%20200%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%3E%0A%20%20%3Cpath%20stroke%3D%22black%22%20stroke-width%3D%223%22%20fill%3D%22none%22%20d%3D%22M1145%2085c17%2C7%208%2C24%20-4%2C29%20-12%2C4%20-40%2C6%20-48%2C-8%20-9%2C-15%209%2C-34%2026%2C-42%2017%2C-7%2045%2C-6%2062%2C2%2017%2C9%2019%2C18%2020%2C27%201%2C9%200%2C29%20-27%2C52%20-28%2C23%20-52%2C34%20-102%2C33%20-49%2C0%20-130%2C-31%20-185%2C-50%20-56%2C-18%20-74%2C-21%20-96%2C-23%20-22%2C-2%20-29%2C-2%20-56%2C7%20-27%2C8%20-44%2C17%20-44%2C17%20-13%2C5%20-15%2C7%20-40%2C16%20-25%2C9%20-69%2C14%20-120%2C11%20-51%2C-3%20-126%2C-23%20-181%2C-32%20-54%2C-9%20-105%2C-20%20-148%2C-23%20-42%2C-3%20-71%2C1%20-104%2C5%20-34%2C5%20-65%2C15%20-98%2C22%22%2F%3E%0A%3C%2Fsvg%3E%0A);_x000D_
}_x000D_
.author_:before {_x000D_
  right:20px;_x000D_
  margin:0 0 0 -100%;_x000D_
  display: inline-block;_x000D_
  height: 10px;_x000D_
  content: url(data:image/svg+xml,%0A%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22120px%22%20height%3D%2220px%22%20viewBox%3D%220%200%201200%20130%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%3E%0A%20%20%3Cpath%20stroke%3D%22black%22%20stroke-width%3D%223%22%20fill%3D%22none%22%20d%3D%22M55%2068c-17%2C6%20-8%2C23%204%2C28%2012%2C5%2040%2C7%2048%2C-8%209%2C-15%20-9%2C-34%20-26%2C-41%20-17%2C-8%20-45%2C-7%20-62%2C2%20-18%2C8%20-19%2C18%20-20%2C27%20-1%2C9%200%2C29%2027%2C52%2028%2C23%2052%2C33%20102%2C33%2049%2C-1%20130%2C-31%20185%2C-50%2056%2C-19%2074%2C-21%2096%2C-23%2022%2C-2%2029%2C-2%2056%2C6%2027%2C8%2043%2C17%2043%2C17%2014%2C6%2016%2C7%2041%2C16%2025%2C9%2069%2C15%20120%2C11%2051%2C-3%20126%2C-22%20181%2C-32%2054%2C-9%20105%2C-20%20148%2C-23%2042%2C-3%2071%2C1%20104%2C6%2034%2C4%2065%2C14%2098%2C22%22%2F%3E%0A%3C%2Fsvg%3E%0A);_x000D_
}
_x000D_
 <div class="author_">Lord Byron</div>
_x000D_
_x000D_
_x000D_

Convenient tool for SVG encoding url-encoder

PHP removing a character in a string

$str = preg_replace('/\?\//', '?', $str);

Edit: See CMS' answer. It's late, I should know better.

Input from the keyboard in command line application

var a;
scanf("%s\n", n);

I tested this out in ObjC, and maybe this will be useful.

How do I escape special characters in MySQL?

You should use single-quotes for string delimiters. The single-quote is the standard SQL string delimiter, and double-quotes are identifier delimiters (so you can use special words or characters in the names of tables or columns).

In MySQL, double-quotes work (nonstandardly) as a string delimiter by default (unless you set ANSI SQL mode). If you ever use another brand of SQL database, you'll benefit from getting into the habit of using quotes standardly.

Another handy benefit of using single-quotes is that the literal double-quote characters within your string don't need to be escaped:

select * from tablename where fields like '%string "hi" %';

Python: Pandas Dataframe how to multiply entire column with a scalar

Note: for those using pandas 0.20.3 and above, and are looking for an answer, all these options will work:

df = pd.DataFrame(np.ones((5,6)),columns=['one','two','three',
                                       'four','five','six'])
df.one *=5
df.two = df.two*5
df.three = df.three.multiply(5)
df['four'] = df['four']*5
df.loc[:, 'five'] *=5
df.iloc[:, 5] = df.iloc[:, 5]*5

which results in

   one  two  three  four  five  six
0  5.0  5.0    5.0   5.0   5.0  5.0
1  5.0  5.0    5.0   5.0   5.0  5.0
2  5.0  5.0    5.0   5.0   5.0  5.0
3  5.0  5.0    5.0   5.0   5.0  5.0
4  5.0  5.0    5.0   5.0   5.0  5.0

What is the difference between JDK and JRE?

JVM, JRE and JDK are platform dependent because configuration of each OS differs. But, Java is platform independent.

Java Virtual Machine (JVM) is a run-time system that executes Java bytecode.

JRE is the environment (standard libraries and JVM) required to run Java applications.

The JDK includes the JRE plus command-line development tools such as compilers and debuggers that are necessary or useful for developing applets and applications.

How to close a JavaFX application on window close?

This seemed to work for me:

EventHandler<ActionEvent> quitHandler = quitEvent -> {

        System.exit(0);

    };
    // Set the handler on the Start/Resume button
    quit.setOnAction(quitHandler);

How can I read Chrome Cache files?

I had some luck with this open-source Python project, seemingly inactive: https://github.com/JRBANCEL/Chromagnon

I ran:

python2 Chromagnon/chromagnonCache.py path/to/Chrome/Cache -o browsable_cache/

And I got a locally-browsable extract of all my open tabs cache.

How to set the height of table header in UITableView?

In case you still need it, have you tried to set the property

self.tableView.tableHeaderView 

If you calculate the heigh you need, and set a new view for tableHeaderView:

CGRect frame = self.tableView.tableHeaderView.frame;
frame.size.height = newHeight;

self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:frame];

It should work.

Download the Android SDK components for offline install

I work behind a firewall on windows and I have the Same problem. But I managed to fix it:

  • Close all your internet applications (browsers, downloading tools etc...)
  • Start -> Execute -> type cmd then hit Enter (displays the command prompt)
  • Type netstat
  • In the results returned, find your Proxy address :

    TCP YOURMACHINENAME:PORT DISTANTMACHINE1:PORT
    TCP YOURMACHINENAME:PORT DISTANTMACHINE2:PORT
    TCP YOURMACHINENAME:PORT DISTANTMACHINE3:PORT
    
  • Your proxy address is one of the DISTANTMACHINEx

  • Your proxy port is the port following the ":"
  • Retype this proxy address and the proxy port in the "setting" page of android SDK manager
  • Tick "force https...http://"
  • Retry

How to get instance variables in Python?

Although not directly an answer to the OP question, there is a pretty sweet way of finding out what variables are in scope in a function. take a look at this code:

>>> def f(x, y):
    z = x**2 + y**2
    sqrt_z = z**.5
    return sqrt_z

>>> f.func_code.co_varnames
('x', 'y', 'z', 'sqrt_z')
>>> 

The func_code attribute has all kinds of interesting things in it. It allows you todo some cool stuff. Here is an example of how I have have used this:

def exec_command(self, cmd, msg, sig):

    def message(msg):
        a = self.link.process(self.link.recieved_message(msg))
        self.exec_command(*a)

    def error(msg):
        self.printer.printInfo(msg)

    def set_usrlist(msg):
        self.client.connected_users = msg

    def chatmessage(msg):
        self.printer.printInfo(msg)

    if not locals().has_key(cmd): return
    cmd = locals()[cmd]

    try:
        if 'sig' in cmd.func_code.co_varnames and \
                       'msg' in cmd.func_code.co_varnames: 
            cmd(msg, sig)
        elif 'msg' in cmd.func_code.co_varnames: 
            cmd(msg)
        else:
            cmd()
    except Exception, e:
        print '\n-----------ERROR-----------'
        print 'error: ', e
        print 'Error proccessing: ', cmd.__name__
        print 'Message: ', msg
        print 'Sig: ', sig
        print '-----------ERROR-----------\n'

HTTP Status 500 - org.apache.jasper.JasperException: java.lang.NullPointerException

In Tomcat a .java and .class file will be created for every jsp files with in the application and the same can be found from the path below, Apache-Tomcat\work\Catalina\localhost\'ApplicationName'\org\apache\jsp\index_jsp.java

In your case the jsp name is error.jsp so the path should be something like below Apache-Tomcat\work\Catalina\localhost\'ApplicationName'\org\apache\jsp\error_jsp.java in line no 124 you are trying to access a null object which results in null pointer exception.

How to check the gradle version in Android Studio?

You can install andle for gradle version management.

It can help you sync to the latest version almost everything in gradle file.

Simple three step to update all project at once.

1. install:

    $ sudo pip install andle

2. set sdk:

    $ andle setsdk -p <sdk_path>

3. update depedency:

    $ andle update -p <project_path> [--dryrun] [--remote] [--gradle]

--dryrun: only print result in console

--remote: check version in jcenter and mavenCentral

--gradle: check gradle version

See https://github.com/Jintin/andle for more information

How does the vim "write with sudo" trick work?

:w - Write a file.

!sudo - Call shell sudo command.

tee - The output of write (vim :w) command redirected using tee. The % is nothing but current file name i.e. /etc/apache2/conf.d/mediawiki.conf. In other words tee command is run as root and it takes standard input and write it to a file represented by %. However, this will prompt to reload file again (hit L to load changes in vim itself):

tutorial link

Can I avoid the native fullscreen video player with HTML5 on iPhone or android?

According to this page https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/Attributes.html it is only available if (Enabled only in a UIWebView with the allowsInlineMediaPlayback property set to YES.) I understand in Mobile Safari this is YES on iPad and NO on iPhone and iPod Touch.

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

Assuming you have the necessary privileges to run svnadmin, you need to use the dump and load commands.

Test if characters are in a string

Use grep or grepl but be aware of whether or not you want to use regular expressions.

By default, grep and related take a regular expression to match, not a literal substring. If you're not expecting that, and you try to match on an invalid regex, it doesn't work:

> grep("[", "abc[")
Error in grep("[", "abc[") : 
  invalid regular expression '[', reason 'Missing ']''

To do a true substring test, use fixed = TRUE.

> grep("[", "abc[", fixed = TRUE)
[1] 1

If you do want regex, great, but that's not what the OP appears to be asking.

How to find substring inside a string (or how to grep a variable)?

You can use "index" if you only want to find a single character, e.g.:

LIST="server1 server2 server3 server4 server5"
SOURCE="3"
if expr index "$LIST" "$SOURCE"; then
    echo "match"
    exit -1
else
    echo "no match"
fi

Output is:

23
match

Cancel a UIView animation?

Even if you cancel the animation in the ways above animation didStopSelector still runs. So if you have logic states in your application driven by animations you will have problems. For this reason with the ways described above I use the context variable of UIView animations. If you pass the current state of your program by the context param to the animation, when the animation stops your didStopSelector function may decide if it should do something or just return based on the current state and the state value passed as context.

Limiting Python input strings to certain characters and lengths

We can use assert here.

def _input(inp_str:str):
    try:
        assert len(inp_str)<=15,print('More than 15 characters present')
        assert all('a'<=i<='z' for i in inp_str),print('Characters other than "a"-"z" are found')
        return inp_str
    except Exception as e:
        pass

_input('abcd')
#abcd
_input('abc d')
#Characters other than "a"-"z" are found
_input('abcdefghijklmnopqrst')
#More than 15 characters present

Create two threads, one display odd & other even numbers

Concurrent Package:

    import java.util.concurrent.ExecutorService;

    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    import java.util.concurrent.locks.Condition;
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    //=========== Task1 class prints odd =====
    class TaskClass1 implements Runnable
    {

    private Condition condition;
    private Lock lock;
    boolean exit = false;
    int i;
    TaskClass1(Condition condition,Lock lock)
    {
        this.condition = condition;
        this.lock = lock;
    }
    @Override
    public void run() {
        try
        {
            lock.lock();
            for(i = 1;i<11;i++)
            {
                if(i%2 == 0)
                {
                    condition.signal();
                    condition.await();

                }
                if(i%2 != 0)
                {
                    System.out.println(Thread.currentThread().getName()+" == "+i);

                }

            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally
        {
            lock.unlock();
        }

    }

}
//==== Task2 : prints even =======
class TaskClass2 implements Runnable
{

    private Condition condition;
    private Lock lock;
    boolean exit = false;
    TaskClass2(Condition condition,Lock lock)
    {
        this.condition = condition;
        this.lock = lock;
    }
    @Override
    public void run() {
        int i;
        // TODO Auto-generated method stub
        try
        {
            lock.lock();
            for(i = 2;i<11;i++)

            {

                if(i%2 != 0)
                {
                    condition.signal();
                    condition.await();
                }
                if(i%2 == 0)
                {
                    System.out.println(Thread.currentThread().getName()+" == "+i);

                }

            }

        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally
        {
            lock.unlock();

        }

    }

}
public class OddEven {

    public static void main(String[] a)
    {
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        Future future1;
        Future future2;
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        future1 = executorService.submit(new TaskClass1(condition,lock));
        future2 = executorService.submit(new TaskClass2(condition,lock));
        executorService.shutdown();


    }


}

Pip freeze vs. pip list

For those looking for a solution. If you accidentally made pip requirements with pip list instead of pip freeze, and want to convert into pip freeze format. I wrote this R script to do so.

library(tidyverse)

pip_list = read_lines("requirements.txt")

pip_freeze = pip_list %>%
  str_replace_all(" \\(", "==") %>%
  str_replace_all("\\)$", "")

pip_freeze %>% write_lines("requirements.txt")

Python list of dictionaries search

One simple way using list comprehensions is , if l is the list

l = [
{"name": "Tom", "age": 10},
{"name": "Mark", "age": 5},
{"name": "Pam", "age": 7}
]

then

[d['age'] for d in l if d['name']=='Tom']

Make text wrap in a cell with FPDF?

Text Wrap:

The MultiCell is used for print text with multiple lines. It has the same atributes of Cell except for ln and link.

$pdf->MultiCell( 200, 40, $reportSubtitle, 1);

Line Height:

What multiCell does is to spread the given text into multiple cells, this means that the second parameter defines the height of each line (individual cell) and not the height of all cells (collectively).

MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])

You can read the full documentation here.

How to detect a route change in Angular?

In angular 6 and RxJS6:

import { filter, debounceTime } from 'rxjs/operators';

 this.router.events.pipe(
      filter((event) => event instanceof NavigationEnd),
      debounceTime(40000)
    ).subscribe(
      x => {
      console.log('val',x);
      this.router.navigate(['/']); /*Redirect to Home*/
}
)

Changing image sizes proportionally using CSS?

this is a known problem with CSS resizing, unless all images have the same proportion, you have no way to do this via CSS.

The best approach would be to have a container, and resize one of the dimensions (always the same) of the images. In my example I resized the width.

If the container has a specified dimension (in my example the width), when telling the image to have the width at 100%, it will make it the full width of the container. The auto at the height will make the image have the height proportional to the new width.

Ex:

HTML:

<div class="container">
<img src="something.png" />
</div>

<div class="container">
<img src="something2.png" />
</div>

CSS:

.container {
    width: 200px;
    height: 120px;
}

/* resize images */
.container img {
    width: 100%;
    height: auto;
}

Creating and Update Laravel Eloquent

$shopOwner = ShopMeta::firstOrNew(array('shopId' => $theID,'metadataKey' => 2001));

Then make your changes and save. Note the firstOrNew doesn't do the insert if its not found, if you do need that then its firstOrCreate.

Difference between .keystore file and .jks file

Ultimately, .keystore and .jks are just file extensions: it's up to you to name your files sensibly. Some application use a keystore file stored in $HOME/.keystore: it's usually implied that it's a JKS file, since JKS is the default keystore type in the Sun/Oracle Java security provider. Not everyone uses the .jks extension for JKS files, because it's implied as the default. I'd recommend using the extension, just to remember which type to specify (if you need).

In Java, the word keystore can have either of the following meanings, depending on the context:

When talking about the file and storage, this is not really a storage facility for key/value pairs (there are plenty or other formats for this). Rather, it's a container to store cryptographic keys and certificates (I believe some of them can also store passwords). Generally, these files are encrypted and password-protected so as not to let this data available to unauthorized parties.

Java uses its KeyStore class and related API to make use of a keystore (whether it's file based or not). JKS is a Java-specific file format, but the API can also be used with other file types, typically PKCS#12. When you want to load a keystore, you must specify its keystore type. The conventional extensions would be:

  • .jks for type "JKS",
  • .p12 or .pfx for type "PKCS12" (the specification name is PKCS#12, but the # is not used in the Java keystore type name).

In addition, BouncyCastle also provides its implementations, in particular BKS (typically using the .bks extension), which is frequently used for Android applications.

Android: show/hide a view using an animation

I have used this two function to hide and show view with transition animation smoothly.

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public void expand(final View v, int duration, int targetHeight, final int position) {

        int prevHeight = v.getHeight();

        v.setVisibility(View.VISIBLE);
        ValueAnimator valueAnimator = ValueAnimator.ofInt(0, targetHeight);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                v.getLayoutParams().height = (int) animation.getAnimatedValue();
                v.requestLayout();
            }
        });
        valueAnimator.setInterpolator(new DecelerateInterpolator());
        valueAnimator.setDuration(duration);
        valueAnimator.start();
        valueAnimator.addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationEnd(Animator animation) {
                v.clearAnimation();
            }
        });

    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public void collapse(final View v, int duration, int targetHeight, final int position) {
        if (position == (data.size() - 1)) {
            return;
        }
        int prevHeight = v.getHeight();
        ValueAnimator valueAnimator = ValueAnimator.ofInt(prevHeight, targetHeight);
        valueAnimator.setInterpolator(new DecelerateInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                v.getLayoutParams().height = (int) animation.getAnimatedValue();
                v.requestLayout();
            }
        });
        valueAnimator.setInterpolator(new DecelerateInterpolator());
        valueAnimator.setDuration(duration);
        valueAnimator.start();
        valueAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                animBoolArray.put(position, false);
                v.clearAnimation();

            }
        });
    }

Iterating over JSON object in C#

You can use the JsonTextReader to read the JSON and iterate over the tokens:

using (var reader = new JsonTextReader(new StringReader(jsonText)))
{
    while (reader.Read())
    {
        Console.WriteLine("{0} - {1} - {2}", 
                          reader.TokenType, reader.ValueType, reader.Value);
    }
}

Embed YouTube Video with No Ads

If you play the video as a playlist and then single out that video you can get it without ads. Here is what I have done: https://www.youtube.com/v/VIDEO_ID?playlist=VIDEO_ID&autoplay=1&rel=0

Python 3 ImportError: No module named 'ConfigParser'

I got further with Valeres answer:

pip install configparser sudo cp /usr/lib/python3.6/configparser.py /usr/lib/python3.6/ConfigParser.py Then try to install the MYSQL-python again. That Worked for me

I would suggest to link the file instead of copy it. It is save to update. I linked the file to /usr/lib/python3/ directory.

$_SERVER['HTTP_REFERER'] missing

SOLUTION

As stated by others very well, HTTP_REFERER is set by the local machine of the user, specifically the browser, which means it's not reliable for security. However, this still is entirely the way in which Google Analytics monitors where you're getting your visitors from, so, it can actually be useful to check, exclude, include, etc..

If you think you should see an HTTP_REFERER and do not, add this to your PHP code, preferably at the top:

ini_set('session.referer_check', 'TRUE');

A more appropriate long-term solution, of course, is to actually update your php.ini or equivalent file. This is a nice and quick way of verifying, though.

TESTING

Run print($_SERVER['HTTP_REFERER']); on your site, go to google.com, inspect some text, edit it to be <a href="https://example.com">LINK!</a>, apply the change, then click the link. If it works, all is well and running precisely!

But maybe $_SERVER is wrong, or the test above says it's broken. Update your page with this, and then test again...

<script type="text/javascript">
    console.log("REFER!" + document.referrer + "|" + location.referrer + "|");
</script>

USES

I use HTTP REFERER to block spam sites in GoogleAnalytics. Below is a graph focusing on one particular website's referrals. From 0 to 44 in one day, it wasn't caused by real users. It was caused by a botted site trying to get my attention to buy their services. But it just started because php.ini was updated to ignore the referer, which meant these spam, junk garbage sites were not getting their appropriate ERROR 403, "Access Denied."

Writing numerical values on the plot with Matplotlib

Use pyplot.text() (import matplotlib.pyplot as plt)

import matplotlib.pyplot as plt

x=[1,2,3]
y=[9,8,7]

plt.plot(x,y)
for a,b in zip(x, y): 
    plt.text(a, b, str(b))
plt.show()

What does the variable $this mean in PHP?

Generally, this keyword is used inside a class, generally with in the member functions to access non-static members of a class(variables or functions) for the current object.

  1. this keyword should be preceded with a $ symbol.
  2. In case of this operator, we use the -> symbol.
  3. Whereas, $this will refer the member variables and function for a particular instance.

Let's take an example to understand the usage of $this.

<?php
class Hero {
    // first name of hero
    private $name;
    
    // public function to set value for name (setter method)
    public function setName($name) {
        $this->name = $name;
    }
    
    // public function to get value of name (getter method)
    public function getName() {
        return $this->name;
    }
}

// creating class object
$stark = new Hero();

// calling the public function to set fname
$stark->setName("IRON MAN");

// getting the value of the name variable
echo "I Am " . $stark->getName();
?>

OUTPUT: I am IRON MAN

NOTE: A static variable acts as a global variable and is shared among all the objects of the class. A non-static variables are specific to instance object in which they are created.

MVC: How to Return a String as JSON

You just need to return standard ContentResult and set ContentType to "application/json". You can create custom ActionResult for it:

public class JsonStringResult : ContentResult
{
    public JsonStringResult(string json)
    {
        Content = json;
        ContentType = "application/json";
    }
}

And then return it's instance:

[HttpPost]
public JsonResult UpdateBatchSearchMembers()
{
    string returntext;
    if (!System.IO.File.Exists(path))
        returntext = Properties.Settings.Default.EmptyBatchSearchUpdate;
    else
        returntext = Properties.Settings.Default.ResponsePath;

    return new JsonStringResult(returntext);
}

How to read a text file directly from Internet using Java?

Use this code to read an Internet resource into a String:

public static String readToString(String targetURL) throws IOException
{
    URL url = new URL(targetURL);
    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(url.openStream()));

    StringBuilder stringBuilder = new StringBuilder();

    String inputLine;
    while ((inputLine = bufferedReader.readLine()) != null)
    {
        stringBuilder.append(inputLine);
        stringBuilder.append(System.lineSeparator());
    }

    bufferedReader.close();
    return stringBuilder.toString().trim();
}

This is based on here.

Get all LI elements in array

You can get a NodeList to iterate through by using getElementsByTagName(), like this:

var lis = document.getElementById("navbar").getElementsByTagName("li");

You can test it out here. This is a NodeList not an array, but it does have a .length and you can iterate over it like an array.

oracle diff: how to compare two tables?

Fast solution:

SELECT * FROM TABLE1
MINUS
SELECT * FROM TABLE2

No records should show...

best practice font size for mobile

Based on my comment to the accepted answer, there are a lot potential pitfalls that you may encounter by declaring font-sizes smaller than 12px. By declaring styles that lead to computed font-sizes of less than 12px, like so:

html {
  font-size: 8px;
}
p {
  font-size: 1.4rem;
}
// Computed p size: 11px.

You'll run into issues with browsers, like Chrome with a Chinese language pack that automatically renders any font sizes computed under 12px as 12px. So, the following is true:

h6 {
    font-size: 12px;
}
p {
   font-size: 8px;
}
// Both render at 12px in Chrome with a Chinese language pack.   
// How unpleasant of a surprise.

I would also argue that for accessibility reasons, you generally shouldn't use sizes under 12px. You might be able to make a case for captions and the like, but again--prepare to be surprised under some browser setups, and prepared to make your grandma squint when she's trying to read your content.

I would instead, opt for something like this:

h1 {
    font-size: 2.5rem;
}

h2 {
    font-size: 2.25rem;
}

h3 {
    font-size: 2rem;
}

h4 {
    font-size: 1.75rem;
}

h5 {
    font-size: 1.5rem;
}

h6 {
    font-size: 1.25rem;
}

p {
    font-size: 1rem;
}

@media (max-width: 480px) {
    html {
        font-size: 12px;
    }
}

@media (min-width: 480px) {
    html {
        font-size: 13px;
    }
}

@media (min-width: 768px) {
    html {
        font-size: 14px;
    }
}

@media (min-width: 992px) {
    html {
        font-size: 15px;
    }
}

@media (min-width: 1200px) {
    html {
        font-size: 16px;
    }
}

You'll find that tons of sites that have to focus on accessibility use rather large font sizes, even for p elements.

As a side note, setting margin-bottom equal to the font-size usually also tends to be attractive, i.e.:

h1 {
    font-size: 2.5rem;
    margin-bottom: 2.5rem;
}

Good luck.

Concatenate String in String Objective-c

Variations on a theme:

NSString *varying = @"whatever it is";
NSString *final = [NSString stringWithFormat:@"first part %@ third part", varying];

NSString *varying = @"whatever it is";
NSString *final = [[@"first part" stringByAppendingString:varying] stringByAppendingString:@"second part"];

NSMutableString *final = [NSMutableString stringWithString:@"first part"];
[final appendFormat:@"%@ third part", varying];

NSMutableString *final = [NSMutableString stringWithString:@"first part"];
[final appendString:varying];
[final appendString:@"third part"];

Changing the size of a column referenced by a schema-bound view in SQL Server

ALTER TABLE [table_name] ALTER COLUMN [column_name] varchar(150)

Create intermediate folders if one doesn't exist

Use this code spinet for create intermediate folders if one doesn't exist while creating/editing file:

File outFile = new File("/dir1/dir2/dir3/test.file");
outFile.getParentFile().mkdirs();
outFile.createNewFile();

Android Paint: .measureText() vs .getTextBounds()

The different between getTextBounds and measureText is described with the image below.

In short,

  1. getTextBounds is to get the RECT of the exact text. The measureText is the length of the text, including the extra gap on the left and right.

  2. If there are spaces between the text, it is measured in measureText but not including in the length of the TextBounds, although the coordinate get shifted.

  3. The text could be tilted (Skew) left. In this case, the bounding box left side would exceed outside the measurement of the measureText, and the overall length of the text bound would be bigger than measureText

  4. The text could be tilted (Skew) right. In this case, the bounding box right side would exceed outside the measurement of the measureText, and the overall length of the text bound would be bigger than measureText

enter image description here

What does -XX:MaxPermSize do?

The permanent space is where the classes, methods, internalized strings, and similar objects used by the VM are stored and never deallocated (hence the name).

This Oracle article succinctly presents the working and parameterization of the HotSpot GC and advises you to augment this space if you load many classes (this is typically the case for application servers and some IDE like Eclipse) :

The permanent generation does not have a noticeable impact on garbage collector performance for most applications. However, some applications dynamically generate and load many classes; for example, some implementations of JavaServer Pages (JSP) pages. These applications may need a larger permanent generation to hold the additional classes. If so, the maximum permanent generation size can be increased with the command-line option -XX:MaxPermSize=.

Note that this other Oracle documentation lists the other HotSpot arguments.

Update : Starting with Java 8, both the permgen space and this setting are gone. The memory model used for loaded classes and methods is different and isn't limited (with default settings). You should not see this error any more.

Add another class to a div

I am facing the same issue. If parent element is hidden then after showing the element chosen drop down are not showing. This is not a perfect solution but it solved my issue. After showing the element you can use following code.

function onshowelement() { $('.chosen').chosen('destroy'); $(".chosen").chosen({ width: '100%' }); }

Android Image View Pinch Zooming

I made my own custom imageview with pinch to zoom. There is no limits/borders on Chirag Ravals code, so user can drag the image off the screen. This will fix it.

Here is the CustomImageView class:

    public class CustomImageVIew extends ImageView implements OnTouchListener {


    private Matrix matrix = new Matrix();
    private Matrix savedMatrix = new Matrix();

    static final int NONE = 0;
    static final int DRAG = 1;
    static final int ZOOM = 2;

    private int mode = NONE;

    private PointF mStartPoint = new PointF();
    private PointF mMiddlePoint = new PointF();
    private Point mBitmapMiddlePoint = new Point();

    private float oldDist = 1f;
    private float matrixValues[] = {0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f};
    private float scale;
    private float oldEventX = 0;
    private float oldEventY = 0;
    private float oldStartPointX = 0;
    private float oldStartPointY = 0;
    private int mViewWidth = -1;
    private int mViewHeight = -1;
    private int mBitmapWidth = -1;
    private int mBitmapHeight = -1;
    private boolean mDraggable = false;


    public CustomImageVIew(Context context) {
        this(context, null, 0);
    }

    public CustomImageVIew(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomImageVIew(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.setOnTouchListener(this);
    }

    @Override
    public void onSizeChanged (int w, int h, int oldw, int oldh){
        super.onSizeChanged(w, h, oldw, oldh);
        mViewWidth = w;
        mViewHeight = h;
    }

    public void setBitmap(Bitmap bitmap){
        if(bitmap != null){
            setImageBitmap(bitmap);

            mBitmapWidth = bitmap.getWidth();
            mBitmapHeight = bitmap.getHeight();
            mBitmapMiddlePoint.x = (mViewWidth / 2) - (mBitmapWidth /  2);
            mBitmapMiddlePoint.y = (mViewHeight / 2) - (mBitmapHeight / 2);

            matrix.postTranslate(mBitmapMiddlePoint.x, mBitmapMiddlePoint.y);
            this.setImageMatrix(matrix);
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event){
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:
            savedMatrix.set(matrix);
            mStartPoint.set(event.getX(), event.getY());
            mode = DRAG;
            break;
        case MotionEvent.ACTION_POINTER_DOWN:
            oldDist = spacing(event);
            if(oldDist > 10f){
                savedMatrix.set(matrix);
                midPoint(mMiddlePoint, event);
                mode = ZOOM;
            }
            break;
        case MotionEvent.ACTION_UP:
        case MotionEvent.ACTION_POINTER_UP:
            mode = NONE;
            break;
        case MotionEvent.ACTION_MOVE:
            if(mode == DRAG){
                drag(event);
            } else if(mode == ZOOM){
                zoom(event);
            } 
            break;
        }

        return true;
    }



   public void drag(MotionEvent event){
       matrix.getValues(matrixValues);

       float left = matrixValues[2];
       float top = matrixValues[5];
       float bottom = (top + (matrixValues[0] * mBitmapHeight)) - mViewHeight;
       float right = (left + (matrixValues[0] * mBitmapWidth)) -mViewWidth;

       float eventX = event.getX();
       float eventY = event.getY();
       float spacingX = eventX - mStartPoint.x;
       float spacingY = eventY - mStartPoint.y;
       float newPositionLeft = (left  < 0 ? spacingX : spacingX * -1) + left;
       float newPositionRight = (spacingX) + right;
       float newPositionTop = (top  < 0 ? spacingY : spacingY * -1) + top;
       float newPositionBottom = (spacingY) + bottom;
       boolean x = true;
       boolean y = true;

       if(newPositionRight < 0.0f || newPositionLeft > 0.0f){
           if(newPositionRight < 0.0f && newPositionLeft > 0.0f){
               x = false;
           } else{
               eventX = oldEventX;
               mStartPoint.x = oldStartPointX;
           }
       }
       if(newPositionBottom < 0.0f || newPositionTop > 0.0f){
           if(newPositionBottom < 0.0f && newPositionTop > 0.0f){
               y = false;
           } else{
               eventY = oldEventY;
               mStartPoint.y = oldStartPointY;
           }
       }

       if(mDraggable){
           matrix.set(savedMatrix);
           matrix.postTranslate(x? eventX - mStartPoint.x : 0, y? eventY - mStartPoint.y : 0);
           this.setImageMatrix(matrix);
           if(x)oldEventX = eventX;
           if(y)oldEventY = eventY;
           if(x)oldStartPointX = mStartPoint.x;
           if(y)oldStartPointY = mStartPoint.y;
       }

   }

   public void zoom(MotionEvent event){
       matrix.getValues(matrixValues);

       float newDist = spacing(event);
       float bitmapWidth = matrixValues[0] * mBitmapWidth;
       float bimtapHeight = matrixValues[0] * mBitmapHeight;
       boolean in = newDist > oldDist;

       if(!in && matrixValues[0] < 1){
           return;
       }
       if(bitmapWidth > mViewWidth || bimtapHeight > mViewHeight){
           mDraggable = true;
       } else{
           mDraggable = false;
       }

       float midX = (mViewWidth / 2);
       float midY = (mViewHeight / 2);

       matrix.set(savedMatrix);
       scale = newDist / oldDist;
       matrix.postScale(scale, scale, bitmapWidth > mViewWidth ? mMiddlePoint.x : midX, bimtapHeight > mViewHeight ? mMiddlePoint.y : midY); 

       this.setImageMatrix(matrix);


   }





    /** Determine the space between the first two fingers */
    private float spacing(MotionEvent event) {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);

        return (float)Math.sqrt(x * x + y * y);
    }

    /** Calculate the mid point of the first two fingers */
    private void midPoint(PointF point, MotionEvent event) {
        float x = event.getX(0) + event.getX(1);
        float y = event.getY(0) + event.getY(1);
        point.set(x / 2, y / 2);
    }


}

This is how you can use it in your activity:

CustomImageVIew mImageView = (CustomImageVIew)findViewById(R.id.customImageVIew1);
mImage.setBitmap(your bitmap);

And layout:

<your.package.name.CustomImageVIew
        android:id="@+id/customImageVIew1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginBottom="15dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:layout_marginTop="15dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" 
        android:scaleType="matrix"/> // important

How to create checkbox inside dropdown?

This can't be done in just HTML (with form elements into option elements).

Or you can just use a standard select multiple field.

<select multiple>
  <option value="a">a</option>
  <option value="b">b</option>
  <option value="c">c</option>
</select>

Constructor of an abstract class in C#

It's there to enforce some initialization logic required by all implementations of your abstract class, or any methods you have implemented on your abstract class (not all the methods on your abstract class have to be abstract, some can be implemented).

Any class which inherits from your abstract base class will be obliged to call the base constructor.

How to cherry-pick multiple commits

Actually, the simplest way to do it could be to:

  1. record the merge-base between the two branches: MERGE_BASE=$(git merge-base branch-a branch-b)
  2. fast-forward or rebase the older branch onto the newer branch
  3. rebase the resulting branch onto itself, starting at the merge base from step 1, and manually remove commits that are not desired:

    git rebase ${SAVED_MERGE_BASE} -i
    

    Alternatively, if there are only a few new commits, skip step 1, and simply use

    git rebase HEAD^^^^^^^ -i
    

    in the first step, using enough ^ to move past the merge-base.

You will see something like this in the interactive rebase:

pick 3139276 commit a
pick c1b421d commit b
pick 7204ee5 commit c
pick 6ae9419 commit d
pick 0152077 commit e
pick 2656623 commit f

Then remove lines b (and any others you want)

SELECT COUNT in LINQ to SQL C#

You should be able to do the count on the purch variable:

purch.Count();

e.g.

var purch = from purchase in myBlaContext.purchases
select purchase;

purch.Count();

How to truncate float values?

At my Python 2.7 prompt:

>>> int(1.923328437452 * 1000)/1000.0 1.923

Adding a column to an existing table in a Rails migration

If you have already run your original migration (before editing it), then you need to generate a new migration (rails generate migration add_email_to_users email:string will do the trick). It will create a migration file containing line: add_column :users, email, string Then do a rake db:migrate and it'll run the new migration, creating the new column.

If you have not yet run the original migration you can just edit it, like you're trying to do. Your migration code is almost perfect: you just need to remove the add_column line completely (that code is trying to add a column to a table, before the table has been created, and your table creation code has already been updated to include a t.string :email anyway).

Cannot create Maven Project in eclipse

I am using Spring STS 3.8.3. I had a similar problem. I fixed it by using information from this thread And also by fixing some maven settings. click Spring Tool Suite -> Preferences -> Maven and uncheck the box that says "Do not automatically update dependencies from remote depositories" Also I checked the boxes that say "Download Artifact Sources" and "download Artifact javadoc".

The simplest way to resize an UIImage?

(Swift 4 compatible) iOS 10+ and iOS < 10 solution (using UIGraphicsImageRenderer if possible, UIGraphicsGetImageFromCurrentImageContext otherwise)

/// Resizes an image
///
/// - Parameter newSize: New size
/// - Returns: Resized image
func scaled(to newSize: CGSize) -> UIImage {
    let rect = CGRect(origin: .zero, size: newSize)

    if #available(iOS 10, *) {
        let renderer = UIGraphicsImageRenderer(size: newSize)
        return renderer.image { _ in
            self.draw(in: rect)
        }
    } else {
        UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
        self.draw(in: rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage!
    }
}

Hadoop cluster setup - java.net.ConnectException: Connection refused

Check your firewall setting and set

  <property>
  <name>fs.default.name</name>
  <value>hdfs://MachineName:9000</value>
  </property>

replace localhost to machine name

how to write an array to a file Java

Just loop over the elements in your array.

Ex:

for(int i=0; numOfElements > i; i++)
{
outputWriter.write(array[i]);
}
//finish up down here

How to sum a variable by group

Just to add a third option:

require(doBy)
summaryBy(Frequency~Category, data=yourdataframe, FUN=sum)

EDIT: this is a very old answer. Now I would recommend the use of group_by and summarise from dplyr, as in @docendo answer.

Get counts of all tables in a schema

select owner, table_name, num_rows, sample_size, last_analyzed from all_tables;

This is the fastest way to retrieve the row counts but there are a few important caveats:

  1. NUM_ROWS is only 100% accurate if statistics were gathered in 11g and above with ESTIMATE_PERCENT => DBMS_STATS.AUTO_SAMPLE_SIZE (the default), or in earlier versions with ESTIMATE_PERCENT => 100. See this post for an explanation of how the AUTO_SAMPLE_SIZE algorithm works in 11g.
  2. Results were generated as of LAST_ANALYZED, the current results may be different.

What is your favorite C programming trick?

Two good source books for this sort of stuff are The Practice of Programming and Writing Solid Code. One of them (I don't remember which) says: Prefer enum to #define where you can, because enum gets checked by the compiler.

Error: class X is public should be declared in a file named X.java

To avoid this error you should follow the following steps:

1) You should make a new java class

You should make a new java class.

2) Name that class

Name that class

3) And a new java class is made

And a new java class is made

How to ignore the first line of data when processing CSV data?

For me the easiest way to go is to use range.

import csv

with open('files/filename.csv') as I:
    reader = csv.reader(I)
    fulllist = list(reader)

# Starting with data skipping header
for item in range(1, len(fulllist)): 
    # Print each row using "item" as the index value
    print (fulllist[item])  

How to read and write INI file with Python3?

Use nested dictionaries. Take a look:

INI File: example.ini

[Section]
Key = Value

Code:

class IniOpen:
    def __init__(self, file):
        self.parse = {}
        self.file = file
        self.open = open(file, "r")
        self.f_read = self.open.read()
        split_content = self.f_read.split("\n")

        section = ""
        pairs = ""

        for i in range(len(split_content)):
            if split_content[i].find("[") != -1:
                section = split_content[i]
                section = string_between(section, "[", "]")  # define your own function
                self.parse.update({section: {}})
            elif split_content[i].find("[") == -1 and split_content[i].find("="):
                pairs = split_content[i]
                split_pairs = pairs.split("=")
                key = split_pairs[0].trim()
                value = split_pairs[1].trim()
                self.parse[section].update({key: value})

    def read(self, section, key):
        try:
            return self.parse[section][key]
        except KeyError:
            return "Sepcified Key Not Found!"

    def write(self, section, key, value):
        if self.parse.get(section) is  None:
            self.parse.update({section: {}})
        elif self.parse.get(section) is not None:
            if self.parse[section].get(key) is None:
                self.parse[section].update({key: value})
            elif self.parse[section].get(key) is not None:
                return "Content Already Exists"

Apply code like so:

ini_file = IniOpen("example.ini")
print(ini_file.parse) # prints the entire nested dictionary
print(ini_file.read("Section", "Key") # >> Returns Value
ini_file.write("NewSection", "NewKey", "New Value"

How to find time complexity of an algorithm

How to find time complexity of an algorithm

You add up how many machine instructions it will execute as a function of the size of its input, and then simplify the expression to the largest (when N is very large) term and can include any simplifying constant factor.

For example, lets see how we simplify 2N + 2 machine instructions to describe this as just O(N).

Why do we remove the two 2s ?

We are interested in the performance of the algorithm as N becomes large.

Consider the two terms 2N and 2.

What is the relative influence of these two terms as N becomes large? Suppose N is a million.

Then the first term is 2 million and the second term is only 2.

For this reason, we drop all but the largest terms for large N.

So, now we have gone from 2N + 2 to 2N.

Traditionally, we are only interested in performance up to constant factors.

This means that we don't really care if there is some constant multiple of difference in performance when N is large. The unit of 2N is not well-defined in the first place anyway. So we can multiply or divide by a constant factor to get to the simplest expression.

So 2N becomes just N.

Detect If Browser Tab Has Focus

While searching about this problem, I found a recommendation that Page Visibility API should be used. Most modern browsers support this API according to Can I Use: http://caniuse.com/#feat=pagevisibility.

Here's a working example (derived from this snippet):

$(document).ready(function() {
  var hidden, visibilityState, visibilityChange;

  if (typeof document.hidden !== "undefined") {
    hidden = "hidden", visibilityChange = "visibilitychange", visibilityState = "visibilityState";
  } else if (typeof document.msHidden !== "undefined") {
    hidden = "msHidden", visibilityChange = "msvisibilitychange", visibilityState = "msVisibilityState";
  }

  var document_hidden = document[hidden];

  document.addEventListener(visibilityChange, function() {
    if(document_hidden != document[hidden]) {
      if(document[hidden]) {
        // Document hidden
      } else {
        // Document shown
      }

      document_hidden = document[hidden];
    }
  });
});

Update: The example above used to have prefixed properties for Gecko and WebKit browsers, but I removed that implementation because these browsers have been offering Page Visibility API without a prefix for a while now. I kept Microsoft specific prefix in order to stay compatible with IE10.

C# : Passing a Generic Object

You cannot access var with the generic.

Try something like

Console.WriteLine("Generic : {0}", test);

And override ToString method [1]

[1] http://msdn.microsoft.com/en-us/library/system.object.tostring.aspx

Difference between fprintf, printf and sprintf?

You can also do very useful things with vsnprintf() function:

$ cat test.cc
#include <exception>
#include <stdarg.h>
#include <stdio.h>

struct exception_fmt : std::exception
{
    exception_fmt(char const* fmt, ...) __attribute__ ((format(printf,2,3)));
    char const* what() const throw() { return msg_; }
    char msg_[0x800];
};

exception_fmt::exception_fmt(char const* fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    vsnprintf(msg_, sizeof msg_, fmt, ap);
    va_end(ap);
}

int main(int ac, char** av)
{
    throw exception_fmt("%s: bad number of arguments %d", *av, ac);
}

$ g++ -Wall -o test test.cc

$ ./test
terminate called after throwing an instance of 'exception_fmt'
  what():  ./test: bad number of arguments 1
Aborted (core dumped)

How can I force users to access my page over HTTPS instead of HTTP?

Ok.. Now there is tons of stuff on this now but no one really completes the "Secure" question. For me it is rediculous to use something that is insecure.

Unless you use it as bait.

$_SERVER propagation can be changed at the will of someone who knows how.

Also as Sazzad Tushar Khan and the thebigjc stated you can also use httaccess to do this and there are a lot of answers here containing it.

Just add:

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://example.com/$1 [R,L]

to the end of what you have in your .httaccess and thats that.

Still we are not as secure as we possibly can be with these 2 tools.

The rest is simple. If there are missing attributes ie...

if(empty($_SERVER["HTTPS"])){ // SOMETHING IS FISHY
}

if(strstr($_SERVER['HTTP_HOST'],"mywebsite.com") === FALSE){// Something is FISHY
}


Also say you have updated your httaccess file and you check:

if($_SERVER["HTTPS"] !== "on"){// Something is fishy
}

There are a lot more variables you can check ie..

HOST_URI (If there are static atributes about it to check)

HTTP_USER_AGENT (Same session different values)

So all Im saying is dont just settle for one or the other when the answer lies in a combination.

For more httaccess rewriting info see the docs-> http://httpd.apache.org/docs/2.0/misc/rewriteguide.html

Some Stacks here -> Force SSL/https using .htaccess and mod_rewrite
and
Getting the full URL of the current page (PHP)
to name a couple.

Why am I seeing "TypeError: string indices must be integers"?

As a rule of thumb, when I receive this error in Python I compare the function signature with the function execution.

For example:

def print_files(file_list, parent_id):
    for file in file_list:
        print(title: %s, id: %s' % (file['title'], file['id']

So if I'll call this function with parameters placed in the wrong order and pass the list as the 2nd argument and a string as the 1st argument:

print_files(parent_id, list_of_files) # <----- Accidentally switching arguments location

The function will try to iterate over the parent_id string instead of file_list and it will expect to see the index as an integer pointing to the specific character in string and not an index which is a string (title or id).

This will lead to the TypeError: string indices must be integers error.

Due to its dynamic nature (as opposed to languages like Java, C# or Typescript), Python will not inform you about this syntax error.

How to make an unaware datetime timezone aware in python

quite new to Python and I encountered the same issue. I find this solution quite simple and for me it works fine (Python 3.6):

unaware=parser.parse("2020-05-01 0:00:00")
aware=unaware.replace(tzinfo=tz.tzlocal()).astimezone(tz.tzlocal())

How do you execute SQL from within a bash script?

Here is a simple way of running MySQL queries in the bash shell

mysql -u [database_username] -p [database_password] -D [database_name] -e "SELECT * FROM [table_name]"

How to convert java.lang.Object to ArrayList?

An interesting note: it appears that attempting to cast from an object to a list on the JavaFX Application thread always results in a ClassCastException.

I had the same issue as you, and no answer helped. After playing around for a while, the only thing I could narrow it down to was the thread. Running the code to cast on any other thread other than the UI thread succeeds as expected, and as the other answers in this section suggest.

Thus, be careful that your source isn't running on the JavaFX application thread.

Remove numbers from string sql server

Remove everything after first digit (was adequate for my use case): LEFT(field,PATINDEX('%[0-9]%',field+'0')-1)

Remove trailing digits: LEFT(field,len(field)+1-PATINDEX('%[^0-9]%',reverse('0'+field))

Is there a workaround for ORA-01795: maximum number of expressions in a list is 1000 error?

I realize this is an old question and referring to TOAD but if you need to code around this using c# you can split up the list through a for loop. You can essentially do the same with Java using subList();

    List<Address> allAddresses = GetAllAddresses();
    List<Employee> employees = GetAllEmployees(); // count > 1000

    List<Address> addresses = new List<Address>();

    for (int i = 0; i < employees.Count; i += 1000)
    {
        int count = ((employees.Count - i) < 1000) ? (employees.Count - i) - 1 : 1000;
        var query = (from address in allAddresses
                     where employees.GetRange(i, count).Contains(address.EmployeeId)
                     && address.State == "UT"
                     select address).ToList();

        addresses.AddRange(query);
    }

Hope this helps someone.

Simple UDP example to send and receive data from same socket

I'll try to keep this short, I've done this a few months ago for a game I was trying to build, it does a UDP "Client-Server" connection that acts like TCP, you can send (message) (message + object) using this. I've done some testing with it and it works just fine, feel free to modify it if needed.

Android Studio 3.0 Flavor Dimension Issue

I have used flavorDimensions for my application in build.gradle (Module: app)

flavorDimensions "tier"

productFlavors {
    production {
        flavorDimensions "tier"
        //manifestPlaceholders = [appName: APP_NAME]
        //signingConfig signingConfigs.config
    }
    staging {
        flavorDimensions "tier"
        //manifestPlaceholders = [appName: APP_NAME_STAGING]
        //applicationIdSuffix ".staging"
        //versionNameSuffix "-staging"
        //signingConfig signingConfigs.config
    }
}

Check this link for more info

// Specifies two flavor dimensions.
flavorDimensions "tier", "minApi"

productFlavors {
     free {
            // Assigns this product flavor to the "tier" flavor dimension. Specifying
            // this property is optional if you are using only one dimension.
            dimension "tier"
            ...
     }

     paid {
            dimension "tier"
            ...
     }

     minApi23 {
            dimension "minApi"
            ...
     }

     minApi18 {
            dimension "minApi"
            ...
     }
}

How do I load an HTML page in a <div> using JavaScript?

You can use the jQuery load function:

<div id="topBar">
    <a href ="#" id="load_home"> HOME </a>
</div>
<div id ="content">        
</div>

<script>
$(document).ready( function() {
    $("#load_home").on("click", function() {
        $("#content").load("content.html");
    });
});
</script>

Sorry. Edited for the on click instead of on load.

offsetTop vs. jQuery.offset().top

It is possible that the offset could be a non-integer, using em as the measurement unit, relative font-sizes in %.

I also theorise that the offset might not be a whole number when the zoom isn't 100% but that depends how the browser handles scaling.

ansible : how to pass multiple commands

If a value in YAML begins with a curly brace ({), the YAML parser assumes that it is a dictionary. So, for cases like this where there is a (Jinja2) variable in the value, one of the following two strategies needs to be adopted to avoiding confusing the YAML parser:

Quote the whole command:

- command: "{{ item }} chdir=/src/package/"
  with_items:
  - ./configure
  - /usr/bin/make
  - /usr/bin/make install    

or change the order of the arguments:

- command: chdir=/src/package/ {{ item }}
  with_items:
  - ./configure
  - /usr/bin/make
  - /usr/bin/make install

Thanks for @RamondelaFuente alternative suggestion.

how to use python2.7 pip instead of default pip

as noted here, this is what worked best for me:

sudo apt-get install python3 python3-pip python3-setuptools

sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 10

how to remove only one style property with jquery

You can also replace "-moz-user-select:none" with "-moz-user-select:inherit". This will inherit the style value from any parent style or from the default style if no parent style was defined.

How to align entire html body to the center?

If I have one thing that I love to share with respect to CSS, it's MY FAVE WAY OF CENTERING THINGS ALONG BOTH AXES!!!

Advantages of this method:

  1. Full compatibility with browsers that people actually use
  2. No tables required
  3. Highly reusable for centering any other elements inside their parent
  4. Accomodates parents and children with dynamic (changing) dimensions!

I always do this by using 2 classes: One to specify the parent element, whose content will be centered (.centered-wrapper), and the 2nd one to specify which child of the parent is centered (.centered-content). This 2nd class is useful in the case where the parent has multiple children, but only 1 needs to be centered). In this case, body will be the .centered-wrapper, and an inner div will be .centered-content.

<html>
    <head>...</head>
    <body class="centered-wrapper">
        <div class="centered-content">...</div>
    </body>
</html>

The idea for centering will now be to make .centered-content an inline-block. This will easily facilitate horizontal centering, through text-align: center;, and also allows for vertical centering as you shall see.

.centered-wrapper {
    position: relative;
    text-align: center;
}
.centered-wrapper:before {
    content: "";
    position: relative;
    display: inline-block;
    width: 0; height: 100%;
    vertical-align: middle;
}
.centered-content {
    display: inline-block;
    vertical-align: middle;
}

This gives you 2 really reusable classes for centering any child inside of any parent! Just add the .centered-wrapper and .centered-content classes.

So, what's up with that :before element? It facilitates vertical-align: middle; and is necessary because vertical alignment isn't relative to the height of the parent - vertical alignment is relative to the height of the tallest sibling!!!. Therefore, by ensuring that there is a sibling whose height is the parent's height (100% height, 0 width to make it invisible), we know that vertical alignment will be with respect to the parent's height.

One last thing: You need to ensure that your html and body tags are the size of the window so that centering to them is the same as centering to the browser!

html, body {
    width: 100%;
    height: 100%;
    padding: 0;
    margin: 0;
}

Fiddle: https://jsfiddle.net/gershy/g121g72a/

What exactly is the 'react-scripts start' command?

"start" is a name of a script, in npm you run scripts like this npm run scriptName, npm start is also a short for npm run start

As for "react-scripts" this is a script related specifically to create-react-app

Can't subtract offset-naive and offset-aware datetimes

You don't need anything outside the std libs

datetime.datetime.now().astimezone()

If you just replace the timezone it will not adjust the time. If your system is already UTC then .replace(tz='UTC') is fine.

>>> x=datetime.datetime.now()
datetime.datetime(2020, 11, 16, 7, 57, 5, 364576)

>>> print(x)
2020-11-16 07:57:05.364576

>>> print(x.astimezone()) 
2020-11-16 07:57:05.364576-07:00

>>> print(x.replace(tzinfo=datetime.timezone.utc)) # wrong
2020-11-16 07:57:05.364576+00:00

HTML: Is it possible to have a FORM tag in each TABLE ROW in a XHTML valid way?

You can't. Your only option is to divide this into multiple tables and put the form tag outside of it. You could end up nesting your tables, but this is not recommended:

<table>
  <tr><td><form>
    <table><tr><td>id</td><td>name</td>...</tr></table>
  </form></td></tr>
</table>

I would remove the tables entirely and replace it with styled html elements like divs and spans.

How to present UIAlertController when not in a view controller?

The following solution did not work even though it looked quite promising with all the versions. This solution is generating WARNING.

Warning: Attempt to present on whose view is not in the window hierarchy!

https://stackoverflow.com/a/34487871/2369867 => This is looked promising then. But it was not in Swift 3. So I am answering this in Swift 3 and this is not template example.

This is rather fully functional code by itself once you paste inside any function.

Quick Swift 3 self-contained code

let alertController = UIAlertController(title: "<your title>", message: "<your message>", preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.cancel, handler: nil))

let alertWindow = UIWindow(frame: UIScreen.main.bounds)
alertWindow.rootViewController = UIViewController()
alertWindow.windowLevel = UIWindowLevelAlert + 1;
alertWindow.makeKeyAndVisible()
alertWindow.rootViewController?.present(alertController, animated: true, completion: nil)

This is tested and working code in Swift 3.

Displaying a webcam feed using OpenCV and Python

change import cv to import cv2.cv as cv See also the post here.

Oracle 'Partition By' and 'Row_Number' keyword

PARTITION BY segregate sets, this enables you to be able to work(ROW_NUMBER(),COUNT(),SUM(),etc) on related set independently.

In your query, the related set comprised of rows with similar cdt.country_code, cdt.account, cdt.currency. When you partition on those columns and you apply ROW_NUMBER on them. Those other columns on those combination/set will receive sequential number from ROW_NUMBER

But that query is funny, if your partition by some unique data and you put a row_number on it, it will just produce same number. It's like you do an ORDER BY on a partition that is guaranteed to be unique. Example, think of GUID as unique combination of cdt.country_code, cdt.account, cdt.currency

newid() produces GUID, so what shall you expect by this expression?

select
   hi,ho,
   row_number() over(partition by newid() order by hi,ho)
from tbl;

...Right, all the partitioned(none was partitioned, every row is partitioned in their own row) rows' row_numbers are all set to 1

Basically, you should partition on non-unique columns. ORDER BY on OVER needed the PARTITION BY to have a non-unique combination, otherwise all row_numbers will become 1

An example, this is your data:

create table tbl(hi varchar, ho varchar);

insert into tbl values
('A','X'),
('A','Y'),
('A','Z'),
('B','W'),
('B','W'),
('C','L'),
('C','L');

Then this is analogous to your query:

select
   hi,ho,
   row_number() over(partition by hi,ho order by hi,ho)
from tbl;

What will be the output of that?

HI  HO  COLUMN_2
A   X   1
A   Y   1
A   Z   1
B   W   1
B   W   2
C   L   1
C   L   2

You see thee combination of HI HO? The first three rows has unique combination, hence they are set to 1, the B rows has same W, hence different ROW_NUMBERS, likewise with HI C rows.

Now, why is the ORDER BY needed there? If the previous developer merely want to put a row_number on similar data (e.g. HI B, all data are B-W, B-W), he can just do this:

select
   hi,ho,
   row_number() over(partition by hi,ho)
from tbl;

But alas, Oracle(and Sql Server too) doesn't allow partition with no ORDER BY; whereas in Postgresql, ORDER BY on PARTITION is optional: http://www.sqlfiddle.com/#!1/27821/1

select
   hi,ho,
   row_number() over(partition by hi,ho)
from tbl;

Your ORDER BY on your partition look a bit redundant, not because of the previous developer's fault, some database just don't allow PARTITION with no ORDER BY, he might not able find a good candidate column to sort on. If both PARTITION BY columns and ORDER BY columns are the same just remove the ORDER BY, but since some database don't allow it, you can just do this:

SELECT cdt.*,
        ROW_NUMBER ()
        OVER (PARTITION BY cdt.country_code, cdt.account, cdt.currency
              ORDER BY newid())
           seq_no
   FROM CUSTOMER_DETAILS cdt

You cannot find a good column to use for sorting similar data? You might as well sort on random, the partitioned data have the same values anyway. You can use GUID for example(you use newid() for SQL Server). So that has the same output made by previous developer, it's unfortunate that some database doesn't allow PARTITION with no ORDER BY

Though really, it eludes me and I cannot find a good reason to put a number on the same combinations (B-W, B-W in example above). It's giving the impression of database having redundant data. Somehow reminded me of this: How to get one unique record from the same list of records from table? No Unique constraint in the table

It really looks arcane seeing a PARTITION BY with same combination of columns with ORDER BY, can not easily infer the code's intent.

Live test: http://www.sqlfiddle.com/#!3/27821/6


But as dbaseman have noticed also, it's useless to partition and order on same columns.

You have a set of data like this:

create table tbl(hi varchar, ho varchar);

insert into tbl values
('A','X'),
('A','X'),
('A','X'),
('B','Y'),
('B','Y'),
('C','Z'),
('C','Z');

Then you PARTITION BY hi,ho; and then you ORDER BY hi,ho. There's no sense numbering similar data :-) http://www.sqlfiddle.com/#!3/29ab8/3

select
   hi,ho,
   row_number() over(partition by hi,ho order by hi,ho) as nr
from tbl;

Output:

HI  HO  ROW_QUERY_A
A   X   1
A   X   2
A   X   3
B   Y   1
B   Y   2
C   Z   1
C   Z   2

See? Why need to put row numbers on same combination? What you will analyze on triple A,X, on double B,Y, on double C,Z? :-)


You just need to use PARTITION on non-unique column, then you sort on non-unique column(s)'s unique-ing column. Example will make it more clear:

create table tbl(hi varchar, ho varchar);

insert into tbl values
('A','D'),
('A','E'),
('A','F'),
('B','F'),
('B','E'),
('C','E'),
('C','D');

select
   hi,ho,
   row_number() over(partition by hi order by ho) as nr
from tbl;

PARTITION BY hi operates on non unique column, then on each partitioned column, you order on its unique column(ho), ORDER BY ho

Output:

HI  HO  NR
A   D   1
A   E   2
A   F   3
B   E   1
B   F   2
C   D   1
C   E   2

That data set makes more sense

Live test: http://www.sqlfiddle.com/#!3/d0b44/1

And this is similar to your query with same columns on both PARTITION BY and ORDER BY:

select
   hi,ho,
   row_number() over(partition by hi,ho order by hi,ho) as nr
from tbl;

And this is the ouput:

HI  HO  NR
A   D   1
A   E   1
A   F   1
B   E   1
B   F   1
C   D   1
C   E   1

See? no sense?

Live test: http://www.sqlfiddle.com/#!3/d0b44/3


Finally this might be the right query:

SELECT cdt.*,
     ROW_NUMBER ()
     OVER (PARTITION BY cdt.country_code, cdt.account -- removed: cdt.currency
           ORDER BY 
               -- removed: cdt.country_code, cdt.account, 
               cdt.currency) -- keep
        seq_no
FROM CUSTOMER_DETAILS cdt

Export MySQL data to Excel in PHP

Posts by John Peter and Dileep kurahe helped me to develop what I consider as being a simpler and cleaner solution, just in case anyone else is still looking. (I am not showing any database code because I actually used a $_SESSION variable.)

The above solutions invariably caused an error upon loading in Excel, about the extension not matching the formatting type. And some of these solutions create a spreadsheet with the data across the page in columns where it would be more traditional to have column headings and list the data down the rows. So here is my simple solution:

$filename = "webreport.csv";
header("Content-Type: application/xls");    
header("Content-Disposition: attachment; filename=$filename");  
header("Pragma: no-cache"); 
header("Expires: 0");
foreach($results as $x => $x_value){
    echo '"'.$x.'",' . '"'.$x_value.'"' . "\r\n";
}
  1. Change to .csv (which Excel instantly updates to .xls and there is no error upon loading.)
  2. Use the comma as delimiter.
  3. Double quote the Key and Value to escape any commas in the data.
  4. I also prepended column headers to $results so the spreadsheet looked even nicer.

How to find what code is run by a button or element in Chrome using Developer Tools

Sounds like the "...and I jump line by line..." part is wrong. Do you StepOver or StepIn and are you sure you don't accidentally miss the relevant call?

That said, debugging frameworks can be tedious for exactly this reason. To alleviate the problem, you can enable the "Enable frameworks debugging support" experiment. Happy debugging! :)

Put Excel-VBA code in module or sheet?

In my experience it's best to put as much code as you can into well-named modules, and only put as much code as you need to into the actual worksheet objects.

Example: Any code that uses worksheet events like Worksheet_SelectionChange or Worksheet_Calculate.

How to install package from github repo in Yarn

You can add any Git repository (or tarball) as a dependency to yarn by specifying the remote URL (either HTTPS or SSH):

yarn add <git remote url> installs a package from a remote git repository.
yarn add <git remote url>#<branch/commit/tag> installs a package from a remote git repository at specific git branch, git commit or git tag.
yarn add https://my-project.org/package.tgz installs a package from a remote gzipped tarball.

Here are some examples:

yarn add https://github.com/fancyapps/fancybox [remote url]
yarn add ssh://github.com/fancyapps/fancybox#3.0  [branch]
yarn add https://github.com/fancyapps/fancybox#5cda5b529ce3fb6c167a55d42ee5a316e921d95f [commit]

(Note: Fancybox v2.6.1 isn't available in the Git version.)

To support both npm and yarn, you can use the git+url syntax:

git+https://github.com/owner/package.git#commithashortagorbranch
git+ssh://github.com/owner/package.git#commithashortagorbranch

How to git ignore subfolders / subdirectories?

The only way I got this to work on my machine was to do it this way:

# Ignore all directories, and all sub-directories, and it's contents:
*/*

#Now ignore all files in the current directory 
#(This fails to ignore files without a ".", for example 
#'file.txt' works, but 
#'file' doesn't):
/*.*

#Only Include these specific directories and subdirectories:
!wordpress/
!wordpress/*/
!wordpress/*/wp-content/
!wordpress/*/wp-content/themes/

Notice how you have to explicitly allow content for each level you want to include. So if I have subdirectories 5 deep under themes, I still need to spell that out.

This is from @Yarin's comment here: https://stackoverflow.com/a/5250314/1696153

These were useful topics:

I also tried

*
*/*
**/**

and **/wp-content/themes/**

or /wp-content/themes/**/*

None of that worked for me, either. Lots of trail and error!

Instant run in Android Studio 2.0 (how to turn off)

UPDATE

In Android Studio Version 3.5 and Above

Now Instant Run is removed, It has "Apply Changes". See official blog for more about the change.

we removed Instant Run and re-architectured and implemented from the ground-up a more practical approach in Android Studio 3.5 called Apply Changes.Apply Changes uses platform-specific APIs from Android Oreo and higher to ensure reliable and consistent behavior; unlike Instant Run, Apply Changes does not modify your APK. To support the changes, we re-architected the entire deployment pipeline to improve deployment speed, and also tweaked the run and deployment toolbar buttons for a more streamlined experience.

Now, As per stable available version 3.0 of Android studio,

If you need to turn off Instant Run, go to

File ? Settings ? Build, Execution, Deployment ? Instant Run and uncheck Enable Instant Run.

enter image description here

Case insensitive 'Contains(string)'

Using a RegEx is a straight way to do this:

Regex.IsMatch(title, "string", RegexOptions.IgnoreCase);

How to import classes defined in __init__.py

Add something like this to lib/__init__.py

from .helperclass import Helper

now you can import it directly:

from lib import Helper

Nexus 7 (2013) and Win 7 64 - cannot install USB driver despite checking many forums and online resources

You can do this go to Settings > Storage, clicking on the setting menu icon in the top right hand corner and selecting "USB computer connection". I then changed the storage mode to "Camera (PTP)". Done try re installing the driver from device manager.

Undefined symbols for architecture x86_64 on Xcode 6.1

Yes, I think the library you are using is not compatible with 64 bit version but you can solve the problem -

Just navigate to Build Settings>Architectures & replace $(ARCHS_STANDARD) to $(ARCHS_STANDARD_32_BIT)

So that your xcode build your project with 32 bit supported version.

mysql_fetch_array() expects parameter 1 to be resource problem

In your database what is the type of "IDNO"? You may need to escape the sql here:

$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);

How to remove trailing whitespaces with sed?

In the specific case of sed, the -i option that others have already mentioned is far and away the simplest and sanest one.

In the more general case, sponge, from the moreutils collection, does exactly what you want: it lets you replace a file with the result of processing it, in a way specifically designed to keep the processing step from tripping over itself by overwriting the very file it's working on. To quote the sponge man page:

sponge reads standard input and writes it out to the specified file. Unlike a shell redirect, sponge soaks up all its input before writing the output file. This allows constructing pipelines that read from and write to the same file.

https://joeyh.name/code/moreutils/

Check date between two other dates spring data jpa

You can also write a custom query using @Query

@Query(value = "from EntityClassTable t where yourDate BETWEEN :startDate AND :endDate")
public List<EntityClassTable> getAllBetweenDates(@Param("startDate")Date startDate,@Param("endDate")Date endDate);

Change CSS class properties with jQuery

$(document)[0].styleSheets[styleSheetIndex].insertRule(rule, lineIndex);


styleSheetIndex is the index value that corresponds to which order you loaded the file in the <head> (e.g. 0 is the first file, 1 is the next, etc. if there is only one CSS file, use 0).

rule is a text string CSS rule. Like this: "body { display:none; }".

lineIndex is the line number in that file. To get the last line number, use $(document)[0].styleSheets[styleSheetIndex].cssRules.length. Just console.log that styleSheet object, it's got some interesting properties/methods.

Because CSS is a "cascade", whatever rule you're trying to insert for that selector you can just append to the bottom of the CSS file and it will overwrite anything that was styled at page load.

In some browsers, after manipulating the CSS file, you have to force CSS to "redraw" by calling some pointless method in DOM JS like document.offsetHeight (it's abstracted up as a DOM property, not method, so don't use "()") -- simply adding that after your CSSOM manipulation forces the page to redraw in older browsers.


So here's an example:

var stylesheet = $(document)[0].styleSheets[0]; stylesheet.insertRule('body { display:none; }', stylesheet.cssRules.length);

How to round float numbers in javascript?

Number((6.688689).toFixed(1)); // 6.7

var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;

Use toFixed() function.

(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"

HTML5 image icon to input placeholder

I don't know whether there's a better answer out there as time goes by but this is simple and it works;

input[type='email'] {
  background: white url(images/mail.svg) no-repeat ;
}
input[type='email']:focus {
  background-image: none;
}

Style it up to suit.

Apply global variable to Vuejs

A possibility is to declare the variable at the index.html because it is really global. It can be done adding a javascript method to return the value of the variable, and it will be READ ONLY. I did like that:

Supposing that I have 2 global variables (var1 and var2). Just add to the index.html header this code:

  <script>
      function getVar1() {
          return 123;
      }
      function getVar2() {
          return 456;
      }
      function getGlobal(varName) {
          switch (varName) {
              case 'var1': return 123;
              case 'var2': return 456;
              // ...
              default: return 'unknown'
          }
      }
  </script>

It's possible to do a method for each variable or use one single method with a parameter.

This solution works between different vuejs mixins, it a really global value.

How to compute the sum and average of elements in an array?

A solution I consider more elegant:

const sum = times.reduce((a, b) => a + b, 0);
const avg = (sum / times.length) || 0;

console.log(`The sum is: ${sum}. The average is: ${avg}.`);

Resize image in the wiki of GitHub using Markdown

Almost 5 years after only the direct HTML formatting works for images on GitHub and other markdown options still prevent images from loading when specifying some custom sizes even with the wrong dimensions. I prefer to specify the desired width and get the height calculated automatically, for example,

_x000D_
_x000D_
<img src="https://github.com/your_image.png" alt="Your image title" width="250"/>
_x000D_
_x000D_
_x000D_

Adding machineKey to web.config on web-farm sites

Make sure to learn from the padding oracle asp.net vulnerability that just happened (you applied the patch, right? ...) and use protected sections to encrypt the machine key and any other sensitive configuration.

An alternative option is to set it in the machine level web.config, so its not even in the web site folder.

To generate it do it just like the linked article in David's answer.

How to select all rows which have same value in some column

You can do this without a JOIN:

SELECT *
FROM (SELECT *,COUNT(*) OVER(PARTITION BY phone_number) as Phone_CT
      FROM YourTable
      )sub
WHERE Phone_CT > 1
ORDER BY phone_number, employee_ids

Demo: SQL Fiddle

Why did I get the compile error "Use of unassigned local variable"?

A very dummy mistake, but you can get this with a class too if you didn't instantiate it.

BankAccount account;
account.addMoney(5);

The above will produce the same error whereas:

class BankAccount
{
    int balance = 0;
    public void addMoney(int amount)
    {
        balance += amount;
    }
}

Do the following to eliminate the error:

BankAccount account = new BankAccount();
account.addMoney(5);

How to use jQuery in AngularJS

You have to do binding in a directive. Look at this:

angular.module('ng', []).
directive('sliderRange', function($parse, $timeout){
    return {
        restrict: 'A',
        replace: true,
        transclude: false,
        compile: function(element, attrs) {            
            var html = '<div class="slider-range"></div>';
            var slider = $(html);
            element.replaceWith(slider);
            var getterLeft = $parse(attrs.ngModelLeft), setterLeft = getterLeft.assign;
            var getterRight = $parse(attrs.ngModelRight), setterRight = getterRight.assign;

            return function (scope, slider, attrs, controller) {
                var vsLeft = getterLeft(scope), vsRight = getterRight(scope), f = vsLeft || 0, t = vsRight || 10;                        

                var processChange = function() {
                    var vs = slider.slider("values"), f = vs[0], t = vs[1];                                        
                    setterLeft(scope, f);
                    setterRight(scope, t);                    
                }                 
                slider.slider({
                    range: true,
                    min: 0,
                    max: 10,
                    step: 1,
                    change: function() { setTimeout(function () { scope.$apply(processChange); }, 1) }
                }).slider("values", [f, t]);                    
            };            
        }
    };
});

This shows you an example of a slider range, done with jQuery UI. Example usage:

<div slider-range ng-model-left="question.properties.range_from" ng-model-right="question.properties.range_to"></div>

Parse JSON response using jQuery

jQuery.ajax({
            type: 'GET',
            url: "../struktur2/load.php",
            async: false,
            contentType: "application/json",
            dataType: 'json',
            success: function(json) {
              items = json;
            },
            error: function(e) {
              console.log("jQuery error message = "+e.message);
            }
        });

From ND to 1D arrays

One of the simplest way is to use flatten(), like this example :

 import numpy as np

 batch_y =train_output.iloc[sample, :]
 batch_y = np.array(batch_y).flatten()

My array it was like this :

    0
0   6
1   6
2   5
3   4
4   3
.
.
.

After using flatten():

array([6, 6, 5, ..., 5, 3, 6])

It's also the solution of errors of this type :

Cannot feed value of shape (100, 1) for Tensor 'input/Y:0', which has shape '(?,)' 

Is "&#160;" a replacement of "&nbsp;"?

Those do both mean non-breaking space, yes. &#xA0; is another synonym, in hex.

Measure string size in Bytes in php

Do you mean byte size or string length?

Byte size is measured with strlen(), whereas string length is queried using mb_strlen(). You can use substr() to trim a string to X bytes (note that this will break the string if it has a multi-byte encoding - as pointed out by Darhazer in the comments) and mb_substr() to trim it to X characters in the encoding of the string.

SQL - HAVING vs. WHERE

First we should know the order of execution of Clauses i.e FROM > WHERE > GROUP BY > HAVING > DISTINCT > SELECT > ORDER BY. Since WHERE Clause gets executed before GROUP BY Clause the records cannot be filtered by applying WHERE to a GROUP BY applied records.

"HAVING is same as the WHERE clause but is applied on grouped records".

first the WHERE clause fetches the records based on the condition then the GROUP BY clause groups them accordingly and then the HAVING clause fetches the group records based on the having condition.

Most efficient way to remove special characters from string

Well, unless you really need to squeeze the performance out of your function, just go with what is easiest to maintain and understand. A regular expression would look like this:

For additional performance, you can either pre-compile it or just tell it to compile on first call (subsequent calls will be faster.)

public static string RemoveSpecialCharacters(string str)
{
    return Regex.Replace(str, "[^a-zA-Z0-9_.]+", "", RegexOptions.Compiled);
}

Why Local Users and Groups is missing in Computer Management on Windows 10 Home?

Windows 10 Home Edition does not have Local Users and Groups option so that is the reason you aren't able to see that in Computer Management.

You can use User Accounts by pressing Window+R, typing netplwiz and pressing OK as described here.

Why doesn't RecyclerView have onItemClickListener()?

Following up MLProgrammer-CiM's excellent RxJava solution

Consume / Observe clicks

Consumer<String> mClickConsumer = new Consumer<String>() {
        @Override
        public void accept(@NonNull String element) throws Exception {
            Toast.makeText(getApplicationContext(), element +" was clicked", Toast.LENGTH_LONG).show();
        }
    };

ReactiveAdapter rxAdapter = new ReactiveAdapter();
rxAdapter.getPositionClicks().subscribe(mClickConsumer);

RxJava 2.+

Modify the original tl;dr as:

public Observable<String> getPositionClicks(){
    return onClickSubject;
}

PublishSubject#asObservable() was removed. Just return the PublishSubject which is an Observable.

Execute a large SQL script (with GO commands)

I hit this same issue and eventually just solved it by a simple string replace, replacing the word GO with a semi-colon (;)

All seems to be working fine while executing scripts with in-line comments, block comments, and GO commands

public static bool ExecuteExternalScript(string filePath)
{
    using (StreamReader file = new StreamReader(filePath))
    using (SqlConnection conn = new SqlConnection(dbConnStr))
    {
        StringBuilder sql = new StringBuilder();

        string line;
        while ((line = file.ReadLine()) != null)
        {
            // replace GO with semi-colon
            if (line == "GO")
                sql.Append(";");
            // remove inline comments
            else if (line.IndexOf("--") > -1)
                sql.AppendFormat(" {0} ", line.Split(new string[] { "--" }, StringSplitOptions.None)[0]);
            // just the line as it is
            else
                sql.AppendFormat(" {0} ", line);
        }
        conn.Open();

        SqlCommand cmd = new SqlCommand(sql.ToString(), conn);
        cmd.ExecuteNonQuery();
    }

    return true;
}

How are booleans formatted in Strings in Python?

To update this for Python-3 you can do this

"{} {}".format(True, False)

However if you want to actually format the string (e.g. add white space), you encounter Python casting the boolean into the underlying C value (i.e. an int), e.g.

>>> "{:<8} {}".format(True, False)
'1        False'

To get around this you can cast True as a string, e.g.

>>> "{:<8} {}".format(str(True), False)
'True     False'

How to install sklearn?

I would recommend you look at getting the anaconda package, it will install and configure Sklearn and its dependencies.

https://www.continuum.io

jquery mobile background image

Here is how I scale <img> tags. If you want to make it a background image you can set it's position to absolute, place the image where you want (using the: top, bottom, left, right declarations), and set it's z-index below the rest of your page.

//simple example
.your_class_name {
    width: 100%;
    height:auto;
}
//background image example
.your_background_class_name {
    width: 100%;
    height:auto;
    top: 0px;
    left: 0px;
    z-index: -1;
    position: absolute;
}

To implement this you would simply place an image tag inside the data-role="page" element of your page(s) that has the ".your_background_class_name" class and the src attribute set to the image you want to have as your background.

I hope this helps.

How can I find out if an .EXE has Command-Line Options?

Just use IDA PRO (https://www.hex-rays.com/products/ida/index.shtml) to disassemble the file, and search for some known command line option (using Search...Text) - in that section you will then typically see all the command line options - for the program (LIB2NIST.exe) in the screenshot below, for example, it shows a documented command line option (/COM2TAG) but also some undocumented ones, like /L. Hope this helps?

enter image description here

Could not find module "@angular-devkit/build-angular"

npm i --save-dev @angular-devkit/build-angular

This code install @angular-devkit/build-angular as dev dependency.

100% TESTED.

The target ... overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig

There is a conflict between your build settings and the default build settings that Cocoapods wants. To see the Cocoapods build settings, view the .xcconfig file(s) in Pods/Target Support Files/Pods-${PROJECTNAME}/ in your project. For me this file contains:

GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers" "${PODS_ROOT}/Headers/Commando"
OTHER_LDFLAGS = -ObjC -framework Foundation -framework QuartzCore -framework UIKit
PODS_ROOT = ${SRCROOT}/Pods

If you are happy with the Cocoapods settings, then go to Build Settings for your project, find the appropriate setting and hit the Delete key. This will use the setting from Cocoapods.

On the other hand, if you have a custom setting that you need to use, then add $(inherited) to that setting.

How to create a temporary directory?

Use mktemp -d. It creates a temporary directory with a random name and makes sure that file doesn't already exist. You need to remember to delete the directory after using it though.

Get selected row item in DataGrid WPF

If you're using the MVVM pattern you can bind a SelectedRecord property of your VM with SelectedItem of the DataGrid, this way you always have the SelectedValue in you VM. Otherwise you should use the SelectedIndex property of the DataGrid.

Access to ES6 array element index inside for-of loop

Another approach could be using Array.prototype.forEach() as

_x000D_
_x000D_
Array.from({_x000D_
  length: 5_x000D_
}, () => Math.floor(Math.random() * 5)).forEach((val, index) => {_x000D_
  console.log(val, index)_x000D_
})
_x000D_
_x000D_
_x000D_

Consider defining a bean of type 'package' in your configuration [Spring-Boot]

Your Applicant class is not scanned it seems. By default all packages starting with the root as the class where you have put @SpringBootApplication will be scanned.

suppose your main class "WebServiceApplication" is in "com.service.something", then all components that fall under "com.service.something" is scanned, and "com.service.applicant" will not be scanned.

You can either restructure your packages such that "WebServiceApplication" falls under a root package and all other components becomes part of that root package. Or you can include @SpringBootApplication(scanBasePackages={"com.service.something","com.service.application"}) etc such that "ALL" components are scanned and initialized in the spring container.

Update based on comment

If you have multiple modules that are being managed by maven/gradle, all spring needs is the package to scan. You tell spring to scan "com.module1" and you have another module which has its root package name as "com.module2", those components wont be scanned. You can even tell spring to scan "com" which will then scan all components in "com.module1." and "com.module2."

Ping site and return result in PHP

ping is available on almost every OS. So you could make a system call and fetch the result.

How do I set up Visual Studio Code to compile C++ code?

With an updated VS Code you can do it in the following manner:

  1. Hit (Ctrl+P) and type:

    ext install cpptools
    
  2. Open a folder (Ctrl+K & Ctrl+O) and create a new file inside the folder with the extension .cpp (ex: hello.cpp):

  3. Type in your code and hit save.

  4. Hit (Ctrl+Shift+P and type, Configure task runner and then select other at the bottom of the list.

  5. Create a batch file in the same folder with the name build.bat and include the following code to the body of the file:

    @echo off
    call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x64     
    set compilerflags=/Od /Zi /EHsc
    set linkerflags=/OUT:hello.exe
    cl.exe %compilerflags% hello.cpp /link %linkerflags%
    
  6. Edit the task.json file as follows and save it:

    {
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "0.1.0",
    "command": "build.bat",
    "isShellCommand": true,
    //"args": ["Hello World"],
    "showOutput": "always"
    }
    
  7. Hit (Ctrl+Shift+B to run Build task. This will create the .obj and .exe files for the project.

  8. For debugging the project, Hit F5 and select C++(Windows).

  9. In launch.json file, edit the following line and save the file:

    "program": "${workspaceRoot}/hello.exe",
    
  10. Hit F5.

NuGet behind a proxy

Here's what I did to get this working with my corporate proxy that uses NTLM authentication. I downloaded NuGet.exe and then ran the following commands (which I found in the comments to this discussion on CodePlex):

nuget.exe config -set http_proxy=http://my.proxy.address:port
nuget.exe config -set http_proxy.user=mydomain\myUserName
nuget.exe config -set http_proxy.password=mySuperSecretPassword

This put the following in my NuGet.config located at %appdata%\NuGet (which maps to C:\Users\myUserName\AppData\Roaming on my Windows 7 machine):

<configuration>
    <!-- stuff -->
    <config>
        <add key="http_proxy" value="http://my.proxy.address:port" />
        <add key="http_proxy.user" value="mydomain\myUserName" />
        <add key="http_proxy.password" value="base64encodedHopefullyEncryptedPassword" />
    </config>
    <!-- stuff -->
</configuration>

Incidentally, this also fixed my issue with NuGet only working the first time I hit the package source in Visual Studio.

Note that some people who have tried this approach have reported through the comments that they have been able to omit setting the http_proxy.password key from the command line, or delete it after-the-fact from the config file, and were still able to have NuGet function across the proxy.

If you find, however, that you must specify your password in the NuGet config file, remember that you have to update the stored password in the NuGet config from the command line when you change your network login, if your proxy credentials are also your network credentials.

How can git be installed on CENTOS 5.5?

If you are using CentOS the built in yum repositories don't seem to have git included and as such, you will need to add an additional repository to the system. For my servers I found that the Webtatic repository seems to be reasonably up to date and the installation for git will then be as follows:

# Add the repository
rpm -Uvh http://repo.webtatic.com/yum/centos/5/latest.rpm

# Install the latest version of git
yum install --enablerepo=webtatic git-all

To work around Missing Dependency: perl(Git) errors:

yum install --enablerepo=webtatic --disableexcludes=main  git-all

php/mySQL on XAMPP: password for phpMyAdmin and mysql_connect different?

You need to change the password directly in the database because at mysql the users and their profiles are saved in the database.

So there are several ways. At phpMyAdmin you simple go to user admin, choose root and change the password.

Concept behind putting wait(),notify() methods in Object class

This is just my 2 cents on this question...not sure if this holds true in its entirety.

Each Object has a monitor and waitset --> set of threads (this is probably more at OS level). This means the monitor and the waitset can be seen as private members of an object. Having wait() and notify() methods in Thread class would mean giving public access to the waitset or using get-set methods to modify the waitset. You wouldnt want to do that because thats bad designing.

Now given that the Object knows the thread/s waiting for its monitor, it should be the job of the Object to go and awaken those threads waiting for it rather than an Object of thread class going and awakening each one of them (which would be possible only if the thread class object is given access to the waitset). However, it is not the job of a particular thread to go and awaken each of the waiting threads. (This is exactly what would happened if all these methods were inside the Thread class). Its job is just to release the lock and move ahead with its own task. A thread works independently and does not need to know whihc other threads are waiting for the objects monitor (it is an unnecessary detail for the thread class object). If it started awakening each thread on its own.. it is moving from away its core functionality and that is to carry out its own task. When you think about a scene where there might 1000's of threads.. you can assume how much of a performance impact it can create. Hence, given that Object Class knows who is waiting on it, it can carry out the job awakening the waiting threads and the thread which sent notify() can carry out with its further processing.

To give an analogy (perhaps not the right one but cant think of anything else). When we have a power outage, we call a customer representative of that company because she knows the right people to contact to fix it. You as a consumer are not allowed to know who are the engineers behind it and even if you know, you cannot possibly call each one of them and tell them of your troubles (that is not ur duty. Your duty is to inform them about the outage and the CR's job is to go and notify(awaken) the right engineers for it).

Let me know if this sounds right... (I do have the ability to confuse sometimes with my words).

jQuery add required to input fields

I found that jquery 1.11.1 does not do this reliably.

I used $('#estimate').attr('required', true) and $('#estimate').removeAttr('required').

Removing required was not reliable. It would sometimes leave the required attribute without value. Since required is a boolean attibute, its mere presence, without value, is seen by the browser as true.

This bug was intermittent, and I got tired of messing with it. Switched to document.getElementById("estimate").required = true and document.getElementById("estimate").required = false.

Start index for iterating Python list

Here's a rotation generator which doesn't need to make a warped copy of the input sequence ... may be useful if the input sequence is much larger than 7 items.

>>> def rotated_sequence(seq, start_index):
...     n = len(seq)
...     for i in xrange(n):
...         yield seq[(i + start_index) % n]
...
>>> s = 'su m tu w th f sa'.split()
>>> list(rotated_sequence(s, s.index('m')))
['m', 'tu', 'w', 'th', 'f', 'sa', 'su']
>>>

What does ${} (dollar sign and curly braces) mean in a string in Javascript?

You're talking about template literals.

They allow for both multiline strings and string interpolation.

Multiline strings:

_x000D_
_x000D_
console.log(`foo_x000D_
bar`);_x000D_
// foo_x000D_
// bar
_x000D_
_x000D_
_x000D_

String interpolation:

_x000D_
_x000D_
var foo = 'bar';_x000D_
console.log(`Let's meet at the ${foo}`);_x000D_
// Let's meet at the bar
_x000D_
_x000D_
_x000D_

Run jar file with command line arguments

For the question

How can i run a jar file in command prompt but with arguments

.

To pass arguments to the jar file at the time of execution

java -jar myjar.jar arg1 arg2

In the main() method of "Main-Class" [mentioned in the manifest.mft file]of your JAR file. you can retrieve them like this:

String arg1 = args[0];
String arg2 = args[1];

sendUserActionEvent() is null

This has to do with having two buttons with the same ID in two different Activities, sometimes Android Studio can't find, You just have to give your button a new ID and re Build the Project

How can I limit possible inputs in a HTML5 "number" element?

You can try this as well for numeric input with length restriction

<input type="tel" maxlength="3" />

Recursive query in SQL Server

Something like this (not tested)

with match_groups as (

  select product_id, 
         matching_product_id,
         product_id as group_id
  from matches
  where product_id not in (select matching_product_id from matches)

  union all

  select m.product_id, m.matching_product_id, p.group_id
  from matches m
    join match_groups p on m.product_id = p.matching_product_id
)
select group_id, product_id
from match_groups
order by group_id;

fork and exec in bash

Use the ampersand just like you would from the shell.

#!/usr/bin/bash
function_to_fork() {
   ...
}

function_to_fork &
# ... execution continues in parent process ...

What is an Intent in Android?

An intent is basically a way of passing data from one activity to other activity

Positive Number to Negative Number in JavaScript?

In vanilla javascript

_x000D_
_x000D_
if(number > 0)_x000D_
  return -1*number;
_x000D_
_x000D_
_x000D_

Where number above is the positive number you intend to convert

This code will convert just positive numbers to negative numbers simple by multiplying by -1

How do I change a tab background color when using TabLayout?

One of simplest solution is to change colorPrimary from colors.xml file.