Programs & Examples On #Subquery

subquery is vague SQL terminology, used to describe when there's either more than one `SELECT` statement in a query, or when used in Data Manipulation Language (DML) statements (IE: DELETE, UPDATE, INSERT, MERGE). The subquery's SELECT statement is always found within brackets/parenthesis.

MySQL - SELECT WHERE field IN (subquery) - Extremely slow why?

I have reformatted your slow sql query with www.prettysql.net

SELECT *
FROM some_table
WHERE
 relevant_field in
 (
  SELECT relevant_field
  FROM some_table
  GROUP BY relevant_field
  HAVING COUNT ( * ) > 1
 );

When using a table in both the query and the subquery, you should always alias both, like this:

SELECT *
FROM some_table as t1
WHERE
 t1.relevant_field in
 (
  SELECT t2.relevant_field
  FROM some_table as t2
  GROUP BY t2.relevant_field
  HAVING COUNT ( t2.relevant_field ) > 1
 );

Does that help?

PostgreSQL 'NOT IN' and subquery

When using NOT IN you should ensure that none of the values are NULL:

SELECT mac, creation_date 
FROM logs 
WHERE logs_type_id=11
AND mac NOT IN (
    SELECT mac
    FROM consols
    WHERE mac IS NOT NULL -- add this
)

SQL LEFT JOIN Subquery Alias

I recognize that the answer works and has been accepted but there is a much cleaner way to write that query. Tested on mysql and postgres.

SELECT wpoi.order_id As No_Commande
FROM  wp_woocommerce_order_items AS wpoi
LEFT JOIN wp_postmeta AS wpp ON wpoi.order_id = wpp.post_id 
                            AND wpp.meta_key = '_shipping_first_name'
WHERE  wpoi.order_id =2198 

Is there a performance difference between CTE , Sub-Query, Temporary Table or Table Variable?

SQL is a declarative language, not a procedural language. That is, you construct a SQL statement to describe the results that you want. You are not telling the SQL engine how to do the work.

As a general rule, it is a good idea to let the SQL engine and SQL optimizer find the best query plan. There are many person-years of effort that go into developing a SQL engine, so let the engineers do what they know how to do.

Of course, there are situations where the query plan is not optimal. Then you want to use query hints, restructure the query, update statistics, use temporary tables, add indexes, and so on to get better performance.

As for your question. The performance of CTEs and subqueries should, in theory, be the same since both provide the same information to the query optimizer. One difference is that a CTE used more than once could be easily identified and calculated once. The results could then be stored and read multiple times. Unfortunately, SQL Server does not seem to take advantage of this basic optimization method (you might call this common subquery elimination).

Temporary tables are a different matter, because you are providing more guidance on how the query should be run. One major difference is that the optimizer can use statistics from the temporary table to establish its query plan. This can result in performance gains. Also, if you have a complicated CTE (subquery) that is used more than once, then storing it in a temporary table will often give a performance boost. The query is executed only once.

The answer to your question is that you need to play around to get the performance you expect, particularly for complex queries that are run on a regular basis. In an ideal world, the query optimizer would find the perfect execution path. Although it often does, you may be able to find a way to get better performance.

subquery in FROM must have an alias

add an ALIAS on the subquery,

SELECT  COUNT(made_only_recharge) AS made_only_recharge
FROM    
    (
        SELECT DISTINCT (identifiant) AS made_only_recharge
        FROM cdr_data
        WHERE CALLEDNUMBER = '0130'
        EXCEPT
        SELECT DISTINCT (identifiant) AS made_only_recharge
        FROM cdr_data
        WHERE CALLEDNUMBER != '0130'
    ) AS derivedTable                           -- <<== HERE

What is the difference between LATERAL and a subquery in PostgreSQL?

The difference between a non-lateral and a lateral join lies in whether you can look to the left hand table's row. For example:

select  *
from    table1 t1
cross join lateral
        (
        select  *
        from    t2
        where   t1.col1 = t2.col1 -- Only allowed because of lateral
        ) sub

This "outward looking" means that the subquery has to be evaluated more than once. After all, t1.col1 can assume many values.

By contrast, the subquery after a non-lateral join can be evaluated once:

select  *
from    table1 t1
cross join
        (
        select  *
        from    t2
        where   t2.col1 = 42 -- No reference to outer query
        ) sub

As is required without lateral, the inner query does not depend in any way on the outer query. A lateral query is an example of a correlated query, because of its relation with rows outside the query itself.

How can I insert values into a table, using a subquery with more than one result?

the sub query looks like

 insert into table_name (col1,col2,....) values (select col1,col2,... FROM table_2 ...)

hope this help

updating table rows in postgres using subquery

@Mayur "4.2 [Using query with complex JOIN]" with Common Table Expressions (CTEs) did the trick for me.

WITH cte AS (
SELECT e.id, e.postcode
FROM employees e
LEFT JOIN locations lc ON lc.postcode=cte.postcode
WHERE e.id=1
)
UPDATE employee_location SET lat=lc.lat, longitude=lc.longi
FROM cte
WHERE employee_location.id=cte.id;

Hope this helps... :D

Subquery returned more than 1 value.This is not permitted when the subquery follows =,!=,<,<=,>,>= or when the subquery is used as an expression

The problem is that these two queries are each returning more than one row:

select isbn from dbo.lending where (act between @fdate and @tdate) and (stat ='close')
select isbn from dbo.lending where lended_date between @fdate and @tdate

You have two choices, depending on your desired outcome. You can either replace the above queries with something that's guaranteed to return a single row (for example, by using SELECT TOP 1), OR you can switch your = to IN and return multiple rows, like this:

select * from dbo.books where isbn IN (select isbn from dbo.lending where (act between @fdate and @tdate) and (stat ='close'))

T-SQL Subquery Max(Date) and Joins

SELECT
    *
FROM
    (SELECT MAX(PriceDate) AS MaxP, Partid FROM MyPrices GROUP BY Partid) MaxP 
    JOIN
    MyPrices MP On MaxP.Partid = MP.Partid AND MaxP.MaxP = MP.PriceDate
    JOIN
    MyParts P ON MP.Partid = P.Partid

You to get the latest pricedate for partid first (a standard aggregate), then join it back to get the prices (which can't be in the aggregate), followed by getting the part details.

What is the error "Every derived table must have its own alias" in MySQL?

Here's a different example that can't be rewritten without aliases ( can't GROUP BY DISTINCT).

Imagine a table called purchases that records purchases made by customers at stores, i.e. it's a many to many table and the software needs to know which customers have made purchases at more than one store:

SELECT DISTINCT customer_id, SUM(1)
  FROM ( SELECT DISTINCT customer_id, store_id FROM purchases)
  GROUP BY customer_id HAVING 1 < SUM(1);

..will break with the error Every derived table must have its own alias. To fix:

SELECT DISTINCT customer_id, SUM(1)
  FROM ( SELECT DISTINCT customer_id, store_id FROM purchases) AS custom
  GROUP BY customer_id HAVING 1 < SUM(1);

( Note the AS custom alias).

Difference between Subquery and Correlated Subquery

A subquery is a select statement that is embedded in a clause of another select statement.

EX:

select ename, sal 
from emp  where sal > (select sal 
                       from emp where ename ='FORD');

A Correlated subquery is a subquery that is evaluated once for each row processed by the outer query or main query. Execute the Inner query based on the value fetched by the Outer query all the values returned by the main query are matched. The INNER Query is driven by the OUTER Query.

Ex:

select empno,sal,deptid 
from emp e 
where sal=(select avg(sal) 
           from emp where deptid=e.deptid);

DIFFERENCE

The inner query executes first and finds a value, the outer query executes once using the value from the inner query (subquery)

Fetch by the outer query, execute the inner query using the value of the outer query, use the values resulting from the inner query to qualify or disqualify the outer query (correlated)

For more information : http://www.oraclegeneration.com/2014/01/sql-interview-questions.html

How to do this in Laravel, subquery where in

The script is tested in Laravel 5.x and 6.x. The static closure can improve performance in some cases.

Product::select(['id', 'name', 'img', 'safe_name', 'sku', 'productstatusid'])
            ->whereIn('id', static function ($query) {
                $query->select(['product_id'])
                    ->from((new ProductCategory)->getTable())
                    ->whereIn('category_id', [15, 223]);
            })
            ->where('active', 1)
            ->get();

generates the SQL

SELECT `id`, `name`, `img`, `safe_name`, `sku`, `productstatusid` FROM `products` 
WHERE `id` IN (SELECT `product_id` FROM `product_category` WHERE 
`category_id` IN (?, ?)) AND `active` = ?

JPA 2.0, Criteria API, Subqueries, In Expressions

Below is the pseudo-code for using sub-query using Criteria API.

CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery();
Root<EMPLOYEE> from = criteriaQuery.from(EMPLOYEE.class);
Path<Object> path = from.get("compare_field"); // field to map with sub-query
from.fetch("name");
from.fetch("id");
CriteriaQuery<Object> select = criteriaQuery.select(from);

Subquery<PROJECT> subquery = criteriaQuery.subquery(PROJECT.class);
Root fromProject = subquery.from(PROJECT.class);
subquery.select(fromProject.get("requiredColumnName")); // field to map with main-query
subquery.where(criteriaBuilder.and(criteriaBuilder.equal("name",name_value),criteriaBuilder.equal("id",id_value)));

select.where(criteriaBuilder.in(path).value(subquery));

TypedQuery<Object> typedQuery = entityManager.createQuery(select);
List<Object> resultList = typedQuery.getResultList();

Also it definitely needs some modification as I have tried to map it according to your query. Here is a link http://www.ibm.com/developerworks/java/library/j-typesafejpa/ which explains concept nicely.

Nested select statement in SQL Server

You need to alias the subquery.

SELECT name FROM (SELECT name FROM agentinformation) a  

or to be more explicit

SELECT a.name FROM (SELECT name FROM agentinformation) a  

Find duplicate entries in a column

Using:

  SELECT t.ctn_no
    FROM YOUR_TABLE t
GROUP BY t.ctn_no
  HAVING COUNT(t.ctn_no) > 1

...will show you the ctn_no value(s) that have duplicates in your table. Adding criteria to the WHERE will allow you to further tune what duplicates there are:

  SELECT t.ctn_no
    FROM YOUR_TABLE t
   WHERE t.s_ind = 'Y'
GROUP BY t.ctn_no
  HAVING COUNT(t.ctn_no) > 1

If you want to see the other column values associated with the duplicate, you'll want to use a self join:

SELECT x.*
  FROM YOUR_TABLE x
  JOIN (SELECT t.ctn_no
          FROM YOUR_TABLE t
      GROUP BY t.ctn_no
        HAVING COUNT(t.ctn_no) > 1) y ON y.ctn_no = x.ctn_no

MySQL Error 1093 - Can't specify target table for update in FROM clause

As far as concerns, you want to delete rows in story_category that do not exist in category.

Here is your original query to identify the rows to delete:

SELECT * 
FROM  story_category 
WHERE category_id NOT IN (
    SELECT DISTINCT category.id 
    FROM category INNER JOIN 
       story_category ON category_id=category.id
);

Combining NOT IN with a subquery that JOINs the original table seems unecessarily convoluted. This can be expressed in a more straight-forward manner with not exists and a correlated subquery:

select sc.*
from story_category sc
where not exists (select 1 from category c where c.id = sc.category_id);

Now it is easy to turn this to a delete statement:

delete from story_category
where not exists (select 1 from category c where c.id = story_category.category_id);    

This quer would run on any MySQL version, as well as in most other databases that I know.

Demo on DB Fiddle:

-- set-up
create table story_category(category_id int);
create table category (id int);
insert into story_category values (1), (2), (3), (4), (5);
insert into category values (4), (5), (6), (7);

-- your original query to identify offending rows
SELECT * 
FROM  story_category 
WHERE category_id NOT IN (
    SELECT DISTINCT category.id 
    FROM category INNER JOIN 
       story_category ON category_id=category.id);
| category_id |
| ----------: |
|           1 |
|           2 |
|           3 |
-- a functionally-equivalent, simpler query for this
select sc.*
from story_category sc
where not exists (select 1 from category c where c.id = sc.category_id)
| category_id |
| ----------: |
|           1 |
|           2 |
|           3 |
-- the delete query
delete from story_category
where not exists (select 1 from category c where c.id = story_category.category_id);

-- outcome
select * from story_category;
| category_id |
| ----------: |
|           4 |
|           5 |

Postgres Error: More than one row returned by a subquery used as an expression

The fundamental problem can often be simply solved by changing an = to IN, in cases where you've got a one-to-many relationship. For example, if you wanted to update or delete a bunch of accounts for a given customer:

WITH accounts_to_delete AS 
    ( 
        SELECT     account_id
        FROM       accounts a
        INNER JOIN customers c
                ON a.customer_id = c.id
        WHERE      c.customer_name='Some Customer'
    )

-- this fails if "Some Customer" has multiple accounts, but works if there's 1:
DELETE FROM accounts
 WHERE accounts.guid = 
( 
    SELECT account_id 
    FROM   accounts_to_delete 
);

-- this succeeds with any number of accounts:
DELETE FROM accounts
 WHERE accounts.guid IN   
( 
    SELECT account_id 
    FROM   accounts_to_delete 
);

Join vs. sub-query

Subqueries have ability to calculate aggregation functions on a fly. E.g. Find minimal price of the book and get all books which are sold with this price. 1) Using Subqueries:

SELECT titles, price
FROM Books, Orders
WHERE price = 
(SELECT MIN(price)
 FROM Orders) AND (Books.ID=Orders.ID);

2) using JOINs

SELECT MIN(price)
     FROM Orders;
-----------------
2.99

SELECT titles, price
FROM Books b
INNER JOIN  Orders o
ON b.ID = o.ID
WHERE o.price = 2.99;

How to delete from select in MySQL?

SELECT (sub)queries return result sets. So you need to use IN, not = in your WHERE clause.

Additionally, as shown in this answer you cannot modify the same table from a subquery within the same query. However, you can either SELECT then DELETE in separate queries, or nest another subquery and alias the inner subquery result (looks rather hacky, though):

DELETE FROM posts WHERE id IN (
    SELECT * FROM (
        SELECT id FROM posts GROUP BY id HAVING ( COUNT(id) > 1 )
    ) AS p
)

Or use joins as suggested by Mchl.

How does Subquery in select statement work in oracle

It's simple-

SELECT empname,
       empid,
       (SELECT COUNT (profileid)
          FROM profile
         WHERE profile.empid = employee.empid)
           AS number_of_profiles
  FROM employee;

It is even simpler when you use a table join like this:

  SELECT e.empname, e.empid, COUNT (p.profileid) AS number_of_profiles
    FROM employee e LEFT JOIN profile p ON e.empid = p.empid
GROUP BY e.empname, e.empid;

Explanation for the subquery:

Essentially, a subquery in a select gets a scalar value and passes it to the main query. A subquery in select is not allowed to pass more than one row and more than one column, which is a restriction. Here, we are passing a count to the main query, which, as we know, would always be only a number- a scalar value. If a value is not found, the subquery returns null to the main query. Moreover, a subquery can access columns from the from clause of the main query, as shown in my query where employee.empid is passed from the outer query to the inner query.


Edit:

When you use a subquery in a select clause, Oracle essentially treats it as a left join (you can see this in the explain plan for your query), with the cardinality of the rows being just one on the right for every row in the left.


Explanation for the left join

A left join is very handy, especially when you want to replace the select subquery due to its restrictions. There are no restrictions here on the number of rows of the tables in either side of the LEFT JOIN keyword.

For more information read Oracle Docs on subqueries and left join or left outer join.

How to do a Postgresql subquery in select clause with join in from clause like SQL Server?

select n1.name, n1.author_id, cast(count_1 as numeric)/total_count
  from (select id, name, author_id, count(1) as count_1
          from names
          group by id, name, author_id) n1
inner join (select distinct(author_id), count(1) as total_count
              from names) n2
  on (n2.author_id = n1.author_id)
Where true

used distinct if more inner join, because more join group performance is slow

MySQL DELETE FROM with subquery as condition

You need to refer to the alias again in the delete statement, like:

DELETE th FROM term_hierarchy AS th
....

As outlined here in MySQL docs.

SQL Joins Vs SQL Subqueries (Performance)?

The performance should be the same; it's much more important to have the correct indexes and clustering applied on your tables (there exist some good resources on that topic).

(Edited to reflect the updated question)

How to wait for a JavaScript Promise to resolve before resuming function?

Another option is to use Promise.all to wait for an array of promises to resolve and then act on those.

Code below shows how to wait for all the promises to resolve and then deal with the results once they are all ready (as that seemed to be the objective of the question); Also for illustrative purposes, it shows output during execution (end finishes before middle).

_x000D_
_x000D_
function append_output(suffix, value) {
  $("#output_"+suffix).append(value)
}

function kickOff() {
  let start = new Promise((resolve, reject) => {
    append_output("now", "start")
    resolve("start")
  })
  let middle = new Promise((resolve, reject) => {
    setTimeout(() => {
      append_output("now", " middle")
      resolve(" middle")
    }, 1000)
  })
  let end = new Promise((resolve, reject) => {
    append_output("now", " end")
    resolve(" end")
  })

  Promise.all([start, middle, end]).then(results => {
    results.forEach(
      result => append_output("later", result))
  })
}

kickOff()
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Updated during execution: <div id="output_now"></div>
Updated after all have completed: <div id="output_later"></div>
_x000D_
_x000D_
_x000D_

Validate email address textbox using JavaScript

<h2>JavaScript Email Validation</h2>

<input id="textEmail">

<button type="button" onclick="myFunction()">Submit</button>

<p id="demo" style="color: red;"></p>

<script>
function myFunction() {
    var email;

    email = document.getElementById("textEmail").value;

        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

        if (reg.test(textEmail.value) == false) 
        {
        document.getElementById("demo").style.color = "red";
            document.getElementById("demo").innerHTML ="Invalid EMail ->"+ email;
            alert('Invalid Email Address ->'+email);
            return false;
        } else{
        document.getElementById("demo").style.color = "DarkGreen";      
        document.getElementById("demo").innerHTML ="Valid Email ->"+email;
        }

   return true;
}
</script>

How to parse JSON response from Alamofire API in Swift?

in swift 5 we do like, Use typealias for the completion. Typlealias nothing just use to clean the code.

typealias response = (Bool,Any?)->()


static func postCall(_ url : String, param : [String : Any],completion : @escaping response){
    Alamofire.request(url, method: .post, parameters: param, encoding: JSONEncoding.default, headers: [:]).responseJSON { (response) in

        switch response.result {
           case .success(let JSON):
               print("\n\n Success value and JSON: \(JSON)")

           case .failure(let error):
               print("\n\n Request failed with error: \(error)")

           }
    }
}

Set background color in PHP?

just insert the following line and use any color you like

    echo "<body style='background-color:pink'>";

Add new field to every document in a MongoDB collection

Same as the updating existing collection field, $set will add a new fields if the specified field does not exist.

Check out this example:

> db.foo.find()
> db.foo.insert({"test":"a"})
> db.foo.find()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "test" : "a" }
> item = db.foo.findOne()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "test" : "a" }
> db.foo.update({"_id" :ObjectId("4e93037bbf6f1dd3a0a9541a") },{$set : {"new_field":1}})
> db.foo.find()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "new_field" : 1, "test" : "a" }

EDIT:

In case you want to add a new_field to all your collection, you have to use empty selector, and set multi flag to true (last param) to update all the documents

db.your_collection.update(
  {},
  { $set: {"new_field": 1} },
  false,
  true
)

EDIT:

In the above example last 2 fields false, true specifies the upsert and multi flags.

Upsert: If set to true, creates a new document when no document matches the query criteria.

Multi: If set to true, updates multiple documents that meet the query criteria. If set to false, updates one document.

This is for Mongo versions prior to 2.2. For latest versions the query is changed a bit

db.your_collection.update({},
                          {$set : {"new_field":1}},
                          {upsert:false,
                          multi:true}) 

How to increase icons size on Android Home Screen?

If you want to change settings in the launcher, change icon size, or grid size just hold down on an empty part of your home screen. Tap the three Dots and there you go.

From https://forums.oneplus.net/threads/how-to-change-icon-and-grid-size-trebuchet-settings.84820/

When configuring the phone for first time I saw something about a grid somewhere, but couldn't find it again. Luckily I found the answer on the link above.

How to programmatically close a JFrame

setVisible(false); //you can't see me!
dispose(); //Destroy the JFrame object

Not too tricky.

IIS w3svc error

I have had this problem after a windows update. Windows Process Activation Service is dependent service for W3SVC. First, make sure that Windows Process Activation Service is running. In my case, it was not running and when I tried to run it manually, I got below error.

Windows Process Activation Service Error 2: The system cannot find the file specified

The issue seems to be, that windows adds an incorrect parameter to the WAS service startup parameters. I fixed the issue using the following steps:

  • Start regedit (just type it into start) Navigate to

  • HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\WAS\Parameters

  • Delete the NanoSetup variable. This variable is preventing WAS from starting

  • Start the WAS service using task manager

  • Now start the W3SVC service

  • You can now start your website in IIS again

I found above WPA service solution in this stack overflow thread.

How to change the height of a <br>?

i Use these methods, but i dont know if cross-browser

================= Method 1 ==================

br {
    display:none;
}

OR

================= Method 2 ==================

br {
    display: block;
    margin-bottom: 2px;
    font-size:2px;
    line-height: 2px;
}
br:before {
    display: block;
    margin-top: 2px;
    content: "";
}
br:after {
    content: ".";
    visibility: hidden;
    display: block;
}

OR

================= Method 3 ==================

br:after { content: "" }
br { content: "" }

server error:405 - HTTP verb used to access this page is not allowed

I've been pulling my hair out over this one for a couple of hours also. fakeartist appears correct though - I changed the file extension from .htm to .php and I can now see my page in Facebook! It also works if you change the extension to .aspx - perhaps it just needs to be a server side extension (I've not tried with .jsp).

Java Date cut off time information

It really annoyed me that the new "improved" calendar constructor doesn't take an int for milliseconds like the "awful" old Date one. I then got really cross and wrote this:

long stuffYou = startTime.getTimeInMillis() % 1000;
startTime.setTimeInMillis(startTime.getTimeInMillis() - stuffYou);

I didn't use the word "stuff" at the time, but then I discovered the happiness of this:

startTime.set(Calendar.MILLISECOND, 0);

But I'm still quite cross about it.

Any way of using frames in HTML5?

I have used frames at my continuing education commercial site for over 15 years. Frames allow the navigation frame to load material into the main frame using the target feature while leaving the navigator frame untouched. Furthermore, Perl scripts operate quite well from a frame form returning the output to the same frame. I love frames and will continue using them. CSS is far too complicated for practical use. I have had no problems using frames with HTML5 with IE, Safari, Chrome, or Firefox.

CSS align images and text on same line

try to insert your img inside your h4 DEMO

<h4 class='liketext'><img style='height: 24px; width: 24px; margin-right: 4px;' src='design/like.png'/>$likes</h4>
<h4 class='liketext'> <img style='height: 24px; width: 24px; margin-right: 4px;' src='design/dislike.png'/>$dislikes</h4>?

simulate background-size:cover on <video> or <img>

This approach just uses css and html. You can actually stack a divs below the video easily. It is cover but not centered while you resize.

HTML:

<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css"> 
</script>
</head>
<body>
<div id = "contain">
<div id="vid">
    <video autoplay>
        <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4" type="video/mp4" />
    </video>
</div>
</div>
</body>
</html>

CCS:

/*
filename:style.css
*/
body {
    margin:0;
}

#vid video{
position: absolute; 
right: 0; 
top: 0;
min-width: 100%; 
min-height: 100%;
width: auto; 
height: auto; 
}

#contain {
width:100%;
height:100%;
zoom:1%;/*Without this the video will be stretched and skewed*/ 
}

wait() or sleep() function in jquery?

You can use the .delay() function.
This is what you're after:

.addClass("load").delay(2000).addClass("done");

How to click a href link using Selenium

Seems like the a tag is hidden. Remember Selenium is not able to interact with hidden element. Javascript is the only option in that case.

By css = By.cssSelector("a[href='/docs/configuration']");
WebElement element = driver.findElement(css);
((JavascriptExecutor)driver).executeScript("arguments[0].click();" , element);

What is the difference between \r and \n?

  • "\r" => Return
  • "\n" => Newline or Linefeed (semantics)

  • Unix based systems use just a "\n" to end a line of text.

  • Dos uses "\r\n" to end a line of text.
  • Some other machines used just a "\r". (Commodore, Apple II, Mac OS prior to OS X, etc..)

Fitting a histogram with python

Here you have an example working on py2.6 and py3.2:

from scipy.stats import norm
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

# read data from a text file. One number per line
arch = "test/Log(2)_ACRatio.txt"
datos = []
for item in open(arch,'r'):
    item = item.strip()
    if item != '':
        try:
            datos.append(float(item))
        except ValueError:
            pass

# best fit of data
(mu, sigma) = norm.fit(datos)

# the histogram of the data
n, bins, patches = plt.hist(datos, 60, normed=1, facecolor='green', alpha=0.75)

# add a 'best fit' line
y = mlab.normpdf( bins, mu, sigma)
l = plt.plot(bins, y, 'r--', linewidth=2)

#plot
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title(r'$\mathrm{Histogram\ of\ IQ:}\ \mu=%.3f,\ \sigma=%.3f$' %(mu, sigma))
plt.grid(True)

plt.show()

enter image description here

How to get JavaScript variable value in PHP

This could be a little tricky thing but the secure way is to set a javascript cookie, then picking it up by php cookie variable.Then Assign this php variable to an php session that will hold the data more securely than cookie.Then delete the cookie using javascript and redirect the page to itself. Given that you have added an php command to catch the variable, you will get it.

Cannot find firefox binary in PATH. Make sure firefox is installed. OS appears to be: VISTA

I got this error message while running tests in Visual Studio: Firefox simply wouldn't load and I got OP's error message.

I manually opened Firefox and found out that it needed to update itself (it did so before loading). Once finished I reran the test suite and Firefox showed up nicely, the tests were properly ran. If you get this error all of a sudden please try this answer before updating anything on your machine.

Postgresql : Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

The error you quote has nothing to do with pg_hba.conf; it's failing to connect, not failing to authorize the connection.

Do what the error message says:

Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

You haven't shown the command that produces the error. Assuming you're connecting on localhost port 5432 (the defaults for a standard PostgreSQL install), then either:

  • PostgreSQL isn't running

  • PostgreSQL isn't listening for TCP/IP connections (listen_addresses in postgresql.conf)

  • PostgreSQL is only listening on IPv4 (0.0.0.0 or 127.0.0.1) and you're connecting on IPv6 (::1) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.

  • PostgreSQL is listening on a different port to the one you're connecting on

  • (unlikely) there's an iptables rule blocking loopback connections

(If you are not connecting on localhost, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).

So ... check those:

  • ps -f -u postgres should list postgres processes

  • sudo lsof -n -u postgres |grep LISTEN or sudo netstat -ltnp | grep postgres should show the TCP/IP addresses and ports PostgreSQL is listening on

BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:

$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 12345?

Labeling file upload button

much easier use it

<input type="button" id="loadFileXml" value="Custom Button Name"onclick="document.getElementById('file').click();" />
<input type="file" style="display:none;" id="file" name="file"/>

With jQuery, how do I capitalize the first letter of a text field while the user is still editing that field?

It's very cool you can capitalize Only the first letter of an input field With this one.. If any one know how to capitalize Like CSS text-transform:capitalize, Please Reply .. Here You go..

$('input-field').keyup(function(event) { $(this).val(($(this).val().substr(0,1).toUpperCase())+($(this).val().substr(1))); });

Pushing from local repository to GitHub hosted remote

open the command prompt Go to project directory

type git remote add origin your git hub repository location with.git

Bootstrap row class contains margin-left and margin-right which creates problems

I used div class="form-control" instead of div class="row"

That fixed for me.

How can I load the contents of a text file into a batch file variable?

If your set command supports the /p switch, then you can pipe input that way.

set /p VAR1=<test.txt
set /? |find "/P"

The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.

This has the added benefit of working for un-registered file types (which the accepted answer does not).

how to use Blob datatype in Postgres

I think this is the most comprehensive answer on the PostgreSQL wiki itself: https://wiki.postgresql.org/wiki/BinaryFilesInDB

Read the part with the title 'What is the best way to store the files in the Database?'

Change type of varchar field to integer: "cannot be cast automatically to type integer"

There is no implicit (automatic) cast from text or varchar to integer (i.e. you cannot pass a varchar to a function expecting integer or assign a varchar field to an integer one), so you must specify an explicit cast using ALTER TABLE ... ALTER COLUMN ... TYPE ... USING:

ALTER TABLE the_table ALTER COLUMN col_name TYPE integer USING (col_name::integer);

Note that you may have whitespace in your text fields; in that case, use:

ALTER TABLE the_table ALTER COLUMN col_name TYPE integer USING (trim(col_name)::integer);

to strip white space before converting.

This shoud've been obvious from an error message if the command was run in psql, but it's possible PgAdmin-III isn't showing you the full error. Here's what happens if I test it in psql on PostgreSQL 9.2:

=> CREATE TABLE test( x varchar );
CREATE TABLE
=> insert into test(x) values ('14'), (' 42  ');
INSERT 0 2
=> ALTER TABLE test ALTER COLUMN x TYPE integer;
ERROR:  column "x" cannot be cast automatically to type integer
HINT:  Specify a USING expression to perform the conversion. 
=> ALTER TABLE test ALTER COLUMN x TYPE integer USING (trim(x)::integer);
ALTER TABLE        

Thanks @muistooshort for adding the USING link.

See also this related question; it's about Rails migrations, but the underlying cause is the same and the answer applies.

If the error still occurs, then it may be related not to column values, but indexes over this column or column default values might fail typecast. Indexes need to be dropped before ALTER COLUMN and recreated after. Default values should be changed appropriately.

How to export specific request to file using postman?

  1. Click on the "Code" button upright of the request page.
  2. From the opened window select cURL.
  3. Copy and share the generated code.

enter image description here

You can use this curl request to import it into Postman.

What is causing ERROR: there is no unique constraint matching given keys for referenced table?

You should have name column as a unique constraint. here is a 3 lines of code to change your issues

  1. First find out the primary key constraints by typing this code

    \d table_name
    

    you are shown like this at bottom "some_constraint" PRIMARY KEY, btree (column)

  2. Drop the constraint:

    ALTER TABLE table_name DROP CONSTRAINT some_constraint
    
  3. Add a new primary key column with existing one:

    ALTER TABLE table_name ADD CONSTRAINT some_constraint PRIMARY KEY(COLUMN_NAME1,COLUMN_NAME2);
    

That's All.

Send FormData with other field in AngularJS

Here is the complete solution

html code,

create the text anf file upload fields as shown below

    <div class="form-group">
        <div>
            <label for="usr">User Name:</label>
            <input type="text" id="usr" ng-model="model.username">
        </div>
        <div>
            <label for="pwd">Password:</label>
            <input type="password" id="pwd" ng-model="model.password">
        </div><hr>
        <div>
            <div class="col-lg-6">
                <input type="file" file-model="model.somefile"/>
            </div>


        </div>
        <div>
            <label for="dob">Dob:</label>
            <input type="date" id="dob" ng-model="model.dob">
        </div>
        <div>
            <label for="email">Email:</label>
            <input type="email"id="email" ng-model="model.email">
        </div>


        <button type="submit" ng-click="saveData(model)" >Submit</button>

directive code

create a filemodel directive to parse file

.directive('fileModel', ['$parse', function ($parse) {
return {
    restrict: 'A',
    link: function(scope, element, attrs) {
        var model = $parse(attrs.fileModel);
        var modelSetter = model.assign;

        element.bind('change', function(){
            scope.$apply(function(){
                modelSetter(scope, element[0].files[0]);
            });
        });
    }
};}]);

Service code

append the file and fields to form data and do $http.post as shown below remember to keep 'Content-Type': undefined

 .service('fileUploadService', ['$http', function ($http) {
    this.uploadFileToUrl = function(file, username, password, dob, email, uploadUrl){
        var myFormData = new FormData();

        myFormData.append('file', file);
        myFormData.append('username', username);
        myFormData.append('password', password);
        myFormData.append('dob', dob);
        myFormData.append('email', email);


        $http.post(uploadUrl, myFormData, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
            .success(function(){

            })
            .error(function(){
            });
    }
}]);

In controller

Now in controller call the service by sending required data to be appended in parameters,

$scope.saveData  = function(model){
    var file = model.myFile;
    var uploadUrl = "/api/createUsers";
    fileUpload.uploadFileToUrl(file, model.username, model.password, model.dob, model.email, uploadUrl);
};

JavaScript or jQuery browser back button click detector

In javascript, navigation type 2 means browser's back or forward button clicked and the browser is actually taking content from cache.

if(performance.navigation.type == 2) {
    //Do your code here
}

How to position a Bootstrap popover?

Maybe you don't need this logic for a responsive behavior.

E.g.

placement: 'auto left'

Bootstrap 3 has auto value for placement. Bootstrap doc:

When "auto" is specified, it will dynamically reorient the tooltip. For example, if placement is "auto left", the tooltip will display to the left when possible, otherwise it will display right.

How to get the caller class in Java

The error message the OP is encountering is just an Eclipse feature. If you are willing to tie your code to a specific maker (and even version) of the JVM, you can effectively use method sun.reflect.Reflection.getCallerClass(). You can then compile the code outside of Eclipse or configure it not to consider this diagnostic an error.

The worse Eclipse configuration is to disable all occurrences of the error by:

Project Properties / Java Compiler / Errors/Warnings / Enable project specific settings set to checked / Deprecated and restrited API / Forbidden reference (access rules) set to Warning or Ignore.

The better Eclipse configuration is to disable a specific occurrence of the error by:

Project Properties / Java Build Path / Libraries / JRE System Library expand / Access rules: select / Edit... / Add... / Resolution: set to Discouraged or Accessible / Rule Pattern set to sun/reflect/Reflection.

EXC_BAD_ACCESS signal received

Just to add another situation where this can happen:

I had the code:

NSMutableString *string;
[string   appendWithFormat:@"foo"];

Obviously I had forgotten to allocate memory for the string:

NSMutableString *string = [[NSMutableString alloc] init];
[string   appendWithFormat:@"foo"];

fixes the problem.

SQLException: No suitable driver found for jdbc:derby://localhost:1527

I just bumped into this problem, tried all above suggestions but still failed. Without repeat what have been suggested above, here are the things I (you) may be missing: In case you are using maven, likely you'll state the dependencies i.e:

<groupId>org.apache.derby</groupId>
<artifactId>derbyclient</artifactId>
<version>10.10.1.1</version>

Please be careful with the version. It must be compatible with the server instance you are running.

I solved my case by giving up on what maven dependencies provided and manually adding external jar from "%JAVA_HOME%\db\lib", the same source of my running server. In this case I'm testing using my Local.

So if you're testing with remote server instance, look for the derbyclient.jar that come with server package.

How to get the current date/time in Java

I'll go ahead and throw this answer in because it is all I needed when I had the same question:

Date currentDate = new Date(System.currentTimeMillis());

currentDate is now your current date in a Java Date object.

Py_Initialize fails - unable to load the file system codec

I had the same issue and found this question. However from the answers here I was not able to solve my problem. I started debugging the cpython code and thought that I might be discovered a bug. Therefore I opened a issue on the python issue tracker.

My mistake was that I did not understand that Py_SetPath clears all inferred paths. So one needs to set all paths when calling this function.

For completion I also copied the most important part of the conversation below.


My original issue text

I compiled the source of CPython 3.7.3 myself on Windows with Visual Studio 2017 together with some packages like e.g numpy. When I start the Python Interpreter I am able to import and use numpy. However when I am running the same script via the C-API I get an ModuleNotFoundError.

So the first thing I did, was to check if numpy is in my site-packages directory and indeed there is a folder named numpy-1.16.2-py3.7-win-amd64.egg. (Makes sense because the python interpreter can find numpy)

The next thing I did was to get some information about the sys.path variable created when running the script via the C-API.

#### sys.path content ####
C:\Work\build\product\python37.zip
C:\Work\build\product\DLLs
C:\Work\build\product\lib
C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO\2017\PROFESSIONAL\COMMON7\IDE\EXTENSIONS\TESTPLATFORM
C:\Users\rvq\AppData\Roaming\Python\Python37\site-packages

Examining the content of sys.path I noticed two things.

  1. C:\Work\build\product\python37.zip has the correct path 'C:\Work\build\product\'. There was just no zip file. All my files and directory were unpacked. So I zipped the files to an archive named python37.zip and this resolved the import error.

  2. C:\Users\rvq\AppData\Roaming\Python\Python37\site-packages is wrong it should be C:\Work\build\product\Lib\site-packages but I dont know how this wrong path is created.

The next thing I tried was to use Py_SetPath(L"C:/Work/build/product/Lib/site-packages") before calling Py_Initialize(). This led to

Fatal Python Error 'unable to load the file system encoding' ModuleNotFoundError: No module named 'encodings'

I created a minimal c++ project with exact these two calls and started to debug Cpython.

int main()
{
  Py_SetPath(L"C:/Work/build/product/Lib/site-packages");
  Py_Initialize();
}

I tracked the call of Py_Initialize() down to the call of

static int
zipimport_zipimporter___init___impl(ZipImporter *self, PyObject *path)

inside of zipimport.c

The comment above this function states the following:

Create a new zipimporter instance. 'archivepath' must be a path-like object to a zipfile, or to a specific path inside a zipfile. For example, it can be '/tmp/myimport.zip', or '/tmp/myimport.zip/mydirectory', if mydirectory is a valid directory inside the archive. 'ZipImportError' is raised if 'archivepath' doesn't point to a valid Zip archive. The 'archive' attribute of the zipimporter object contains the name of the zipfile targeted.

So for me it seems that the C-API expects the path set with Py_SetPath to be a path to a zipfile. Is this expected behaviour or is it a bug? If it is not a bug is there a way to changes this so that it can also detect directories?

PS: The ModuleNotFoundError did not occur for me when using Python 3.5.2+, which was the version I used in my project before. I also checked if I had set any PYTHONHOME or PYTHONPATH environment variables but I did not see one of them on my system.


Answer

This is probably a documentation failure more than anything else. We're in the middle of redesigning initialization though, so it's good timing to contribute this feedback.

The short answer is that you need to make sure Python can find the Lib/encodings directory, typically by putting the standard library in sys.path. Py_SetPath clears all inferred paths, so you need to specify all the places Python should look. (The rules for where Python looks automatically are complicated and vary by platform, which is something I'm keen to fix.)

Paths that don't exist are okay, and that's the zip file. You can choose to put the stdlib into a zip, and it will be found automatically if you name it the default path, but you can also leave it unzipped and reference the directory.

A full walk through on embedding is more than I'm prepared to type on my phone. Hopefully that's enough to get you going for now.

Valid to use <a> (anchor tag) without href attribute?

The <a>nchor element is simply an anchor to or from some content. Originally the HTML specification allowed for named anchors (<a name="foo">) and linked anchors (<a href="#foo">).

The named anchor format is less commonly used, as the fragment identifier is now used to specify an [id] attribute (although for backwards compatibility you can still specify [name] attributes). An <a> element without an [href] attribute is still valid.

As far as semantics and styling is concerned, the <a> element isn't a link (:link) unless it has an [href] attribute. A side-effect of this is that an <a> element without [href] won't be in the tabbing order by default.

The real question is whether the <a> element alone is an appropriate representation of a <button>. On a semantic level, there is a distinct difference between a link and a button.

A button is something that when clicked causes an action to occur.

A link is a button that causes a change in navigation in the current document. The navigation that occurs could be moving within the document in the case of fragment identifiers (#foo) or moving to a new document in the case of urls (/bar).

As links are a special type of button, they have often had their actions overridden to perform alternative functions. Continuing to use an anchor as a button is ok from a consistency standpoint, although it's not quite accurate semantically.

If you're concerned about the semantics and accessibility of using an <a> element (or <span>, or <div>) as a button, you should add the following attributes:

<a role="button" tabindex="0" ...>...</a>

The button role tells the user that the particular element is being treated as a button as an override for whatever semantics the underlying element may have had.

For <span> and <div> elements, you may want to add JavaScript key listeners for Space or Enter to trigger the click event. <a href> and <button> elements do this by default, but non-button elements do not. Sometimes it makes more sense to bind the click trigger to a different key. For example, a "help" button in a web app might be bound to F1.

Using IF..ELSE in UPDATE (SQL server 2005 and/or ACCESS 2007)

this should work

update table_name
  set column_b = case
                  when column_a = 1 then 'Y'
                  else null
                 end,
  set column_c = case
                  when column_a = 2 then 'Y'
                  else null
                 end,
  set column_d = case
                  when column_a = 3 then 'Y'
                  else null
                 end
where
 conditions

the question is why would you want to do that...you may want to rethink the data model. you can replace null with whatever you want.

How to minify php page html output?

I have a GitHub gist contains PHP functions to minify HTML, CSS and JS files → https://gist.github.com/taufik-nurrohman/d7b310dea3b33e4732c0

Here’s how to minify the HTML output on the fly with output buffer:

<?php

include 'path/to/php-html-css-js-minifier.php';

ob_start('minify_html');

?>

<!-- HTML code goes here ... -->

<?php echo ob_get_clean(); ?>

Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)

I had to #include <tchar.h> in my windows service application. I left it as a windows console type subsystem. The "Character Set" was set to UNICODE.

How to "crop" a rectangular image into a square with CSS?

Using background-size:cover - http://codepen.io/anon/pen/RNyKzB

CSS:

.image-container {
  background-image: url('http://i.stack.imgur.com/GA6bB.png');
  background-size:cover;
  background-repeat:no-repeat;
  width:250px;
  height:250px;
}  

Markup:

<div class="image-container"></div>

How to import a new font into a project - Angular 5

You can try creating a css for your font with font-face (like explained here)

Step #1

Create a css file with font face and place it somewhere, like in assets/fonts

customfont.css

@font-face {
    font-family: YourFontFamily;
    src: url("/assets/font/yourFont.otf") format("truetype");
}

Step #2

Add the css to your .angular-cli.json in the styles config

"styles":[
 //...your other styles
 "assets/fonts/customFonts.css"
 ]

Do not forget to restart ng serve after doing this

Step #3

Use the font in your code

component.css

span {font-family: YourFontFamily; }

Making the Android emulator run faster

I've been using the Intel(86) CPU/ABI. I created another emulator using the ARM(armeabi-v7a) and i found quite an improvement with the speed. I'm using platform 4.1.2 API level 16

get UTC timestamp in python with datetime

A simple solution without using external modules:

from datetime import datetime, timezone

dt = datetime(2008, 1, 1, 0, 0, 0, 0)
int(dt.replace(tzinfo=timezone.utc).timestamp())

JavaScript Number Split into individual digits

This also works:

_x000D_
_x000D_
var number = 12354987;_x000D_
console.log(String(number).split('').map(Number));
_x000D_
_x000D_
_x000D_

How to remove responsive features in Twitter Bootstrap 3?

You can do that by using the Bootstrap 3 CSS with non-responsive features

https://github.com/bassjobsen/non-responsive-tb3

How to check if $_GET is empty?

<?php
if (!isset($_GET) || empty($_GET))
{
    // do stuff here
}

Save plot to image file instead of displaying it using Matplotlib

You can either do:

plt.show(hold=False)
plt.savefig('name.pdf')

and remember to let savefig finish before closing the GUI plot. This way you can see the image beforehand.

Alternatively, you can look at it with plt.show() Then close the GUI and run the script again, but this time replace plt.show() with plt.savefig().

Alternatively, you can use

fig, ax = plt.figure(nrows=1, ncols=1)
plt.plot(...)
plt.show()
fig.savefig('out.pdf')

How do I parse an ISO 8601-formatted date?

New in Python 3.7+


The datetime standard library introduced a function for inverting datetime.isoformat().

classmethod datetime.fromisoformat(date_string):

Return a datetime corresponding to a date_string in one of the formats emitted by date.isoformat() and datetime.isoformat().

Specifically, this function supports strings in the format(s):

YYYY-MM-DD[*HH[:MM[:SS[.mmm[mmm]]]][+HH:MM[:SS[.ffffff]]]]

where * can match any single character.

Caution: This does not support parsing arbitrary ISO 8601 strings - it is only intended as the inverse operation of datetime.isoformat().

Example of use:

from datetime import datetime

date = datetime.fromisoformat('2017-01-01T12:30:59.000000')

Changing image size in Markdown

If you are writing MarkDown for PanDoc, you can do this:

![drawing](drawing.jpg){ width=50% }

This adds style="width: 50%;" to the HTML <img> tag, or [width=0.5\textwidth] to \includegraphics in LaTeX.

Source: http://pandoc.org/MANUAL.html#extension-link_attributes

Hibernate: best practice to pull all lazy collections

Try use Gson library to convert objects to Json

Example with servlets :

  List<Party> parties = bean.getPartiesByIncidentId(incidentId);
        String json = "";
        try {
            json = new Gson().toJson(parties);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(json);

Could not load file or assembly Exception from HRESULT: 0x80131040

Try this:

  • Edit the *.pubxml file in the PublishProfiles folder
  • set DeleteExistingFiles true
  • update all nugget packages, rebuild, republish and voila, issue resolved!

...worked for me when I had the same problem.

How to add manifest permission to an application?

You have to use both Network and Access Network State in manifest file while you are trying load or access to the internet through android emulator.

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

If you are giving only .INTERNET permission, it won't access to the internet.

How to get a list of all valid IP addresses in a local network?

Install nmap,

sudo apt-get install nmap

then

nmap -sP 192.168.1.*

or more commonly

nmap -sn 192.168.1.0/24

will scan the entire .1 to .254 range

This does a simple ping scan in the entire subnet to see which hosts are online.

What is the difference between the operating system and the kernel?

The difference between an operating system and a kernel:

The kernel is a part of an operating system. The operating system is the software package that communicates directly to the hardware and our application. The kernel is the lowest level of the operating system. The kernel is the main part of the operating system and is responsible for translating the command into something that can be understood by the computer. The main functions of the kernel are:

  1. memory management
  2. network management
  3. device driver
  4. file management
  5. process management

How do I compile a Visual Studio project from the command-line?

I know of two ways to do it.

Method 1
The first method (which I prefer) is to use msbuild:

msbuild project.sln /Flags...

Method 2
You can also run:

vcexpress project.sln /build /Flags...

The vcexpress option returns immediately and does not print any output. I suppose that might be what you want for a script.

Note that DevEnv is not distributed with Visual Studio Express 2008 (I spent a lot of time trying to figure that out when I first had a similar issue).

So, the end result might be:

os.system("msbuild project.sln /p:Configuration=Debug")

You'll also want to make sure your environment variables are correct, as msbuild and vcexpress are not by default on the system path. Either start the Visual Studio build environment and run your script from there, or modify the paths in Python (with os.putenv).

If conditions in a Makefile, inside a target

You can simply use shell commands. If you want to suppress echoing the output, use the "@" sign. For example:

clean:
    @if [ "test" = "test" ]; then\
        echo "Hello world";\
    fi

Note that the closing ";" and "\" are necessary.

dpi value of default "large", "medium" and "small" text views android

To put it in another way, can we replicate the appearance of these text views without using the android:textAppearance attribute?

Like biegleux already said:

  • small represents 14sp
  • medium represents 18sp
  • large represents 22sp

If you want to use the small, medium or large value on any text in your Android app, you can just create a dimens.xml file in your values folder and define the text size there with the following 3 lines:

<dimen name="text_size_small">14sp</dimen>
<dimen name="text_size_medium">18sp</dimen>
<dimen name="text_size_large">22sp</dimen>

Here is an example for a TextView with large text from the dimens.xml file:

<TextView
  android:id="@+id/hello_world"
  android:text="hello world"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:textSize="@dimen/text_size_large"/>

DateDiff to output hours and minutes

Small change like this can be done

  SELECT  EmplID
        , EmplName
        , InTime
        , [TimeOut]
        , [DateVisited]
        , CASE WHEN minpart=0 
        THEN CAST(hourpart as nvarchar(200))+':00' 
        ELSE CAST((hourpart-1) as nvarchar(200))+':'+ CAST(minpart as nvarchar(200))END as 'total time'
        FROM 
        (
        SELECT   EmplID, EmplName, InTime, [TimeOut], [DateVisited],
        DATEDIFF(Hour,InTime, [TimeOut]) as hourpart, 
        DATEDIFF(minute,InTime, [TimeOut])%60 as minpart  
        from times) source

Comparing a variable with a string python not working when redirecting from bash script

When you read() the file, you may get a newline character '\n' in your string. Try either

if UserInput.strip() == 'List contents': 

or

if 'List contents' in UserInput: 

Also note that your second file open could also use with:

with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile:     if UserInput.strip() == 'List contents': # or if s in f:         UserInputFile.write("ls")     else:         print "Didn't work" 

jQuery `.is(":visible")` not working in Chrome

I don't know why your code doesn't work on chrome, but I suggest you use some workarounds :

$el.is(':visible') === $el.is(':not(:hidden)');

or

$el.is(':visible') === !$el.is(':hidden');  

If you are certain that jQuery gives you some bad results in chrome, you can just rely on the css rule checking :

if($el.css('display') !== 'none') {
    // i'm visible
}

Plus, you might want to use the latest jQuery because it might have bugs from older version fixed.

T-SQL split string

You can Use this function:

        CREATE FUNCTION SplitString
        (    
           @Input NVARCHAR(MAX),
           @Character CHAR(1)
          )
            RETURNS @Output TABLE (
            Item NVARCHAR(1000)
          )
        AS
        BEGIN

      DECLARE @StartIndex INT, @EndIndex INT
      SET @StartIndex = 1
      IF SUBSTRING(@Input, LEN(@Input) - 1, LEN(@Input)) <> @Character
      BEGIN
            SET @Input = @Input + @Character
      END

      WHILE CHARINDEX(@Character, @Input) > 0
      BEGIN
            SET @EndIndex = CHARINDEX(@Character, @Input)

            INSERT INTO @Output(Item)
            SELECT SUBSTRING(@Input, @StartIndex, @EndIndex - 1)

            SET @Input = SUBSTRING(@Input, @EndIndex + 1, LEN(@Input))
      END

      RETURN
END
GO

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R?

I figured out myself.

cmp calls ComputeBetasAndNuHat which returns a list which has objective as minusloglik

So I can change the function cmp to get this value.

Java 8 lambda get and remove element from list

Use can use filter of Java 8, and create another list if you don't want to change the old list:

List<ProducerDTO> result = producersProcedureActive
                            .stream()
                            .filter(producer -> producer.getPod().equals(pod))
                            .collect(Collectors.toList());

Create a hidden field in JavaScript

I've found this to work:

var element1 = document.createElement("input");
element1.type = "hidden";
element1.value = "10";
element1.name = "a";
document.getElementById("chells").appendChild(element1);

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

Your can use DataSourceBuilder for this purpose.

@Primary
@Bean(name = "dataSource")
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource(Environment env) {
    final String datasourceUsername = env.getRequiredProperty("spring.datasource.username");
    final String datasourcePassword = env.getRequiredProperty("spring.datasource.password");
    final String datasourceUrl = env.getRequiredProperty("spring.datasource.url");
    final String datasourceDriver = env.getRequiredProperty("spring.datasource.driver-class-name");
    return DataSourceBuilder
            .create()
            .username(datasourceUsername)
            .password(datasourcePassword)
            .url(datasourceUrl)
            .driverClassName(datasourceDriver)
            .build();
}

How can I loop through a C++ map of maps?

Old question but the remaining answers are outdated as of C++11 - you can use a ranged based for loop and simply do:

std::map<std::string, std::map<std::string, std::string>> mymap;

for(auto const &ent1 : mymap) {
  // ent1.first is the first key
  for(auto const &ent2 : ent1.second) {
    // ent2.first is the second key
    // ent2.second is the data
  }
}

this should be much cleaner than the earlier versions, and avoids unnecessary copies.

Some favour replacing the comments with explicit definitions of reference variables (which get optimised away if unused):

for(auto const &ent1 : mymap) {
  auto const &outer_key = ent1.first;
  auto const &inner_map = ent1.second;
  for(auto const &ent2 : inner_map) {
    auto const &inner_key   = ent2.first;
    auto const &inner_value = ent2.second;
  }
}

How to check if "Radiobutton" is checked?

radiobuttonObj.isChecked() will give you boolean

if(radiobuttonObj1.isChecked()){
//do what you want 
}else if(radiobuttonObj2.isChecked()){
//do what you want 
}

Error: fix the version conflict (google-services plugin)

You must use only one version for all 3 libs

compile 'com.google.firebase:firebase-messaging:11.0.4'
compile 'com.google.android.gms:play-services-maps:11.0.4'
compile 'com.google.android.gms:play-services-location:11.0.4'

OR only use only 10.0.1 for 3 libs

How to delete directory content in Java?

You can't delete an File array. As all of the other answers suggest, you must delete each individual file before deleting the folder...

final File[] files = outputFolder.listFiles();
for (File f: files) f.delete();
outputFolder.delete();

How to continue the code on the next line in VBA

If you want to insert this formula =SUMIFS(B2:B10,A2:A10,F2) into cell G2, here is how I did it.

Range("G2")="=sumifs(B2:B10,A2:A10," & _

"F2)"

To split a line of code, add an ampersand, space and underscore.

Iterate a list with indexes in Python

Yep, that would be the enumerate function! Or more to the point, you need to do:

list(enumerate([3,7,19]))

[(0, 3), (1, 7), (2, 19)]

how I can show the sum of in a datagridview column?

Use LINQ if you can.

  label1.Text =  dataGridView1.Rows.Cast<DataGridViewRow>()
                                   .AsEnumerable()
                                   .Sum(x => int.Parse(x.Cells[1].Value.ToString()))
                                   .ToString();

Click a button programmatically

in c# this is working :D

protect void button1_Click(object sender, EventArgs e){
    button2_Click(button2, null);
}

protect void button2_Click(object sender, EventeArgs e){
    //some codes here
}

for vb.net

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)   Handles Button1.Click
    Button2_Click(Sender, e)
End Sub

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs)   Handles Button2.Click
    //some codes here
End Sub

Parse time of format hh:mm:ss

String time = "12:32:22";
String[] values = time.split(":");

This will take your time and split it where it sees a colon and put the value in an array, so you should have 3 values after this.

Then loop through string array and convert each one. (with Integer.parseInt)

Return Boolean Value on SQL Select Statement

What you have there will return no row at all if the user doesn't exist. Here's what you need:

SELECT CASE WHEN EXISTS (
    SELECT *
    FROM [User]
    WHERE UserID = 20070022
)
THEN CAST(1 AS BIT)
ELSE CAST(0 AS BIT) END

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

You can't update with a number greater than 1 for datatype number(2,2) is because, the first parameter is the total number of digits in the number and the second one (.i.e 2 here) is the number of digits in decimal part. I guess you can insert or update data < 1. i.e. 0.12, 0.95 etc.

Please check NUMBER DATATYPE in NUMBER Datatype.

Javascript replace all "%20" with a space

Check this out: How to replace all occurrences of a string in JavaScript?

Short answer:

str.replace(/%20/g, " ");

EDIT: In this case you could also do the following:

decodeURI(str)

MySQL "WITH" clause

Update: MySQL 8.0 is finally getting the feature of common table expressions, including recursive CTEs.

Here's a blog announcing it: http://mysqlserverteam.com/mysql-8-0-labs-recursive-common-table-expressions-in-mysql-ctes/

Below is my earlier answer, which I originally wrote in 2008.


MySQL 5.x does not support queries using the WITH syntax defined in SQL-99, also called Common Table Expressions.

This has been a feature request for MySQL since January 2006: http://bugs.mysql.com/bug.php?id=16244

Other RDBMS products that support common table expressions:

Use Conditional formatting to turn a cell Red, yellow or green depending on 3 values in another sheet

  1. Highlight the range in question.
  2. On the Home tab, in the Styles Group, Click "Conditional Formatting".
  3. Click "Highlight cell rules"

For the first rule,

Click "greater than", then in the value option box, click on the cell criteria you want it to be less than, than use the format drop-down to select your color.

For the second,

Click "less than", then in the value option box, type "=.9*" and then click the cell criteria, then use the formatting just like step 1.

For the third,

Same as the second, except your formula is =".8*" rather than .9.

Putting GridView data in a DataTable

Copying Grid to datatable

        if (GridView.Rows.Count != 0)
        {
            //Forloop for header
            for (int i = 0; i < GridView.HeaderRow.Cells.Count; i++)
            {
                dt.Columns.Add(GridView.HeaderRow.Cells[i].Text);
            }
            //foreach for datarow
            foreach (GridViewRow row in GridView.Rows)
            {
                DataRow dr = dt.NewRow();
                for (int j = 0; j < row.Cells.Count; j++)
                {
                    dr[GridView.HeaderRow.Cells[j].Text] = row.Cells[j].Text;
                }
                dt.Rows.Add(dr);
            }
            //Loop for footer
            if (GridView.FooterRow.Cells.Count != 0)
            {
                DataRow dr = dt.NewRow();
                for (int i = 0; i < GridView.FooterRow.Cells.Count; i++)
                {
                    //You have to re-do the work if you did anything in databound for footer.  
                }
                dt.Rows.Add(dr);
            }
            dt.TableName = "tb";
        }

Flatten nested dictionaries, compressing keys

I actually wrote a package called cherrypicker recently to deal with this exact sort of thing since I had to do it so often!

I think the following code would give you exactly what you're after:

from cherrypicker import CherryPicker

dct = {
    'a': 1,
    'c': {
        'a': 2,
        'b': {
            'x': 5,
            'y' : 10
        }
    },
    'd': [1, 2, 3]
}

picker = CherryPicker(dct)
picker.flatten().get()

You can install the package with:

pip install cherrypicker

...and there's more docs and guidance at https://cherrypicker.readthedocs.io.

Other methods may be faster, but the priority of this package is to make such tasks easy. If you do have a large list of objects to flatten though, you can also tell CherryPicker to use parallel processing to speed things up.

Spring Boot Java Config Set Session Timeout

  • Spring Boot version 1.0: server.session.timeout=1200
  • Spring Boot version 2.0: server.servlet.session.timeout=10m
    NOTE: If a duration suffix is not specified, seconds will be used.

How to make the script wait/sleep in a simple way in unity

you can

        float Lasttime;
        public float Sec = 3f;
        public int Num;
        void Start(){
        ExampleStart();
        }
        public void ExampleStart(){
        Lasttime = Time.time;
        }
        void Update{

        if(Time.time - Lasttime > sec){
//           if(Num == step){
//             Yourcode
//You Can Change Sec with => sec = YOURTIME(Float)
//             Num++;
//            ExampleStart();
             }
             if(Num == 0){
             TextUI.text = "Welcome to Number Wizard!";
             Num++;
             ExampleStart();
             }
             if(Num == 1){
             TextUI.text = ("The highest number you can pick is " + max);
             Num++;
             ExampleStart();
             }
             if(Num == 2){
             TextUI.text = ("The lowest number you can pick is " + min);
             Num++;
             ExampleStart();
             }
        }

    }  

Khaled Developer
Easy For Gaming

Output to the same line overwriting previous output?

to overwiting the previous line in python all wath you need is to add end='\r' to the print function, test this example:

import time
for j in range(1,5):
   print('waiting : '+j, end='\r')
   time.sleep(1)

Simplest way to merge ES6 Maps/Sets?

You can use the spread syntax to merge them together:

const map1 = {a: 1, b: 2}
const map2 = {b: 1, c: 2, a: 5}

const mergedMap = {...a, ...b}

=> {a: 5, b: 1, c: 2}

How can I remove jenkins completely from linux

if you are ubuntu user than try this:

sudo apt-get remove jenkins
sudo apt-get remove --auto-remove jenkins

'apt-get remove' command is use to remove package.

Status bar and navigation bar appear over my view's bounds in iOS 7

edgesForExtendedLayout does the trick for iOS 7. However, if you build the app across iOS 7 SDK and deploy it in iOS 6, the navigation bar appears translucent and the views go beneath it. So, to fix it for both iOS 7 as well as for iOS 6 do this:

self.navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque;
if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
    self.edgesForExtendedLayout = UIRectEdgeNone;   // iOS 7 specific

How to set up ES cluster?

I tried the steps that @KannarKK suggested on ES 2.0.2, however, I could not bring the cluster up and running. Evidently, I figured out something, as I had set tcp port number on Master, on the Slave configuration discovery.zen.ping.unicast.hosts needs Master's port number along with IP address ( tcp port number ) for discovery. So when I try following configuration it works for me.

Node 1

cluster.name: mycluster
node.name: "node1"
node.master: true
node.data: true
http.port : 9200
tcp.port : 9300
discovery.zen.ping.multicast.enabled: false
# I think unicast.host on master is redundant.
discovery.zen.ping.unicast.hosts: ["node1.example.com"]

Node 2

cluster.name: mycluster
node.name: "node2"
node.master: false
node.data: true
http.port : 9201
tcp.port : 9301
discovery.zen.ping.multicast.enabled: false
# The port number of Node 1
discovery.zen.ping.unicast.hosts: ["node1.example.com:9300"]

How to use MD5 in javascript to transmit a password

crypto-js is a rich javascript library containing many cryptography algorithms.

All you have to do is just call CryptoJS.MD5(password)

$.post(
  'includes/login.php', 
  { user: username, pass: CryptoJS.MD5(password) },
  onLogin, 
  'json' );

Scale Image to fill ImageView width and keep aspect ratio

To create an image with width equals screen width, and height proportionally set according to aspect ratio, do the following.

Glide.with(context).load(url).asBitmap().into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {

                        // creating the image that maintain aspect ratio with width of image is set to screenwidth.
                        int width = imageView.getMeasuredWidth();
                        int diw = resource.getWidth();
                        if (diw > 0) {
                            int height = 0;
                            height = width * resource.getHeight() / diw;
                            resource = Bitmap.createScaledBitmap(resource, width, height, false);
                        }
                                              imageView.setImageBitmap(resource);
                    }
                });

Hope this helps.

Storyboard - refer to ViewController in AppDelegate

Generally, the system should be handling view controller instantiation with a storyboard. What you want is to traverse the viewController hierarchy by grabbing a reference to the self.window.rootViewController as opposed to initializing view controllers, which should already be initialized correctly if you've setup your storyboard properly.

So, let's say your rootViewController is a UINavigationController and then you want to send something to its top view controller, you would do it like this in your AppDelegate's didFinishLaunchingWithOptions:

UINavigationController *nav = (UINavigationController *) self.window.rootViewController;
MyViewController *myVC = (MyViewController *)nav.topViewController;
myVC.data = self.data;

In Swift if would be very similar:

let nav = self.window.rootViewController as! UINavigationController;
let myVC = nav.topViewController as! MyViewController
myVc.data = self.data

You really shouldn't be initializing view controllers using storyboard id's from the app delegate unless you want to bypass the normal way storyboard is loaded and load the whole storyboard yourself. If you're having to initialize scenes from the AppDelegate you're most likely doing something wrong. I mean imagine you, for some reason, want to send data to a view controller way down the stack, the AppDelegate shouldn't be reaching way into the view controller stack to set data. That's not its business. It's business is the rootViewController. Let the rootViewController handle its own children! So, if I were bypassing the normal storyboard loading process by the system by removing references to it in the info.plist file, I would at most instantiate the rootViewController using instantiateViewControllerWithIdentifier:, and possibly its root if it is a container, like a UINavigationController. What you want to avoid is instantiating view controllers that have already been instantiated by the storyboard. This is a problem I see a lot. In short, I disagree with the accepted answer. It is incorrect unless the posters means to remove loading of the storyboard from the info.plist since you will have loaded 2 storyboards otherwise, which makes no sense. It's probably not a memory leak because the system initialized the root scene and assigned it to the window, but then you came along and instantiated it again and assigned it again. Your app is off to a pretty bad start!

Examples for string find in Python

Honestly, this is the sort of situation where I just open up Python on the command line and start messing around:

 >>> x = "Dana Larose is playing with find()"
 >>> x.find("Dana")
 0
 >>> x.find("ana")
 1
 >>> x.find("La")
 5
 >>> x.find("La", 6)
 -1

Python's interpreter makes this sort of experimentation easy. (Same goes for other languages with a similar interpreter)

The transaction manager has disabled its support for remote/network transactions

I had the same error message. For me changing pooling=False to ;pooling=true;Max Pool Size=200 in the connection string fixed the problem.

MYSQL Sum Query with IF Condition

How about this?

SUM(IF(PaymentType = "credit card", totalamount, 0)) AS CreditCardTotal

GlobalConfiguration.Configure() not present after Web API 2 and .NET 4.5.1 migration

None of these solutions worked for me. I had a tangle of Nuget packages that couldn't update because of circular dependencies on each other.

I would up having to fix this the old-fashioned way. I created a new MVC/web api project and manually copied System.Web.Http and System.Web.Http.WebHost from the new project into the Nuget folders of the exisitng solution. From there I updated the references by, OMG, "browsing" and fixed the problem.

Function for 'does matrix contain value X?'

For floating point data, you can use the new ismembertol function, which computes set membership with a specified tolerance. This is similar to the ismemberf function found in the File Exchange except that it is now built-in to MATLAB. Example:

>> pi_estimate = 3.14159;
>> abs(pi_estimate - pi)
ans =
   5.3590e-08
>> tol = 1e-7;
>> ismembertol(pi,pi_estimate,tol)
ans =
     1

List comprehension on a nested list?

Yes, you can do it with such a code:

l = [[float(y) for y in x] for x in l]

How to check if the given string is palindrome?

EDIT: from the comments:

bool palindrome(std::string const& s) 
{ 
  return std::equal(s.begin(), s.end(), s.rbegin()); 
} 

The c++ way.

My naive implementation using the elegant iterators. In reality, you would probably check and stop once your forward iterator has past the halfway mark to your string.

#include <string>
#include <iostream>

using namespace std;
bool palindrome(string foo)
{
    string::iterator front;
    string::reverse_iterator back;
    bool is_palindrome = true;
    for(front = foo.begin(), back = foo.rbegin();
        is_palindrome && front!= foo.end() && back != foo.rend();
        ++front, ++back
        )
    {
        if(*front != *back)
            is_palindrome = false;
    }
    return is_palindrome;
}
int main()
{
    string a = "hi there", b = "laval";

    cout << "String a: \"" << a << "\" is " << ((palindrome(a))? "" : "not ") << "a palindrome." <<endl;
    cout << "String b: \"" << b << "\" is " << ((palindrome(b))? "" : "not ") << "a palindrome." <<endl;

}

how to do file upload using jquery serialization

You can upload files via AJAX by using the FormData method. Although IE7,8 and 9 do not support FormData functionality.

$.ajax({
    url: "ajax.php", 
    type: "POST",             
    data: new FormData('form'),
    contentType: false,       
    cache: false,             
    processData:false, 
    success: function(data) {
        $("#response").html(data);
    }
});

How to check the presence of php and apache on ubuntu server through ssh

You could inspect the available apache2 modules:

$ ls /usr/lib/apache2/modules/

Or try to enable the php module, if you have the appropriate access:

$ a2enmod
Which module would you like to enable?
Your choices are: actions alias asis ...
... php5 proxy_ajp proxy_balancer proxy_connect ..

How to hide a div element depending on Model value? MVC

The below code should apply different CSS classes based on your Model's CanEdit Property value .

<div class="@(Model.CanEdit?"visible-item":"hidden-item")">Some links</div>

But if it is something important like Edit/Delete links, you shouldn't be simply hiding,because people can update the css class/HTML markup in their browser and get access to your important link. Instead you should be simply not Rendering the important stuff to the browser.

@if(Model.CanEdit)
{
  <div>Edit/Delete link goes here</div>
}

Predicate Delegates in C#

The predicate-based searching methods allow a method delegate or lambda expression to decide whether a given element is a “match.” A predicate is simply a delegate accepting an object and returning true or false: public delegate bool Predicate (T object);

   static void Main()
        {
            string[] names = { "Lukasz", "Darek", "Milosz" };
            string match1 = Array.Find(names, delegate(string name) { return name.Contains("L"); });
            //or
            string match2 = Array.Find(names, delegate(string name) { return name.Contains("L"); });
            //or
            string match3 = Array.Find(names, x => x.Contains("L"));


            Console.WriteLine(match1 + " " + match2 + " " + match3);     // Lukasz Lukasz Lukasz
        }
        static bool ContainsL(string name) { return name.Contains("L"); }

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

I had to use nl2br to display the carriage returns correctly and it worked for me:

<?php
echo nl2br(file_get_contents( "filename.php" )); // get the contents, and echo it out.
?>

App.Config Transformation for projects which are not Web Projects in Visual Studio?

Inspired by Oleg and others in this question, I took the solution https://stackoverflow.com/a/5109530/2286801 a step further to enable the following.

  • Works with ClickOnce
  • Works with Setup and Deployment projects in VS 2010
  • Works with VS2010, 2013, 2015 (didn't test 2012 although should work as well).
  • Works with Team Build. (You must install either A) Visual Studio or B) Microsoft.Web.Publishing.targets and Microsoft.Web.Publishing.Tasks.dll)

This solution works by performing the app.config transformation before the app.config is referenced for the first time in the MSBuild process. It uses an external targets file for easier management across multiple projects.

Instructions:

Similar steps to the other solution. I've quoted what remains the same and included it for completeness and easier comparison.

0. Add a new file to your project called AppConfigTransformation.targets

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <!-- Transform the app config per project configuration.-->
  <PropertyGroup>
    <!-- This ensures compatibility across multiple versions of Visual Studio when using a solution file.
         However, when using MSBuild directly you may need to override this property to 11.0 or 12.0 
         accordingly as part of the MSBuild script, ie /p:VisualStudioVersion=11.0;
         See http://blogs.msdn.com/b/webdev/archive/2012/08/22/visual-studio-project-compatability-and-visualstudioversion.aspx -->
    <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
  </PropertyGroup>

  <Import Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.targets" />

  <Target Name="SetTransformAppConfigDestination" BeforeTargets="PrepareForBuild" 
          Condition="exists('app.$(Configuration).config')">
    <PropertyGroup>
      <!-- Force build process to use the transformed configuration file from now on. -->
      <AppConfig>$(IntermediateOutputPath)$(TargetFileName).config</AppConfig>
    </PropertyGroup>
    <Message Text="AppConfig transformation destination: = $(AppConfig)" />
  </Target>

  <!-- Transform the app.config after the prepare for build completes. -->
  <Target Name="TransformAppConfig" AfterTargets="PrepareForBuild" Condition="exists('app.$(Configuration).config')">
    <!-- Generate transformed app config in the intermediate directory -->
    <TransformXml Source="app.config" Destination="$(AppConfig)" Transform="app.$(Configuration).config" />
  </Target>

</Project>

1. Add an XML file for each configuration to the project.

Typically you will have Debug and Release configurations so name your files App.Debug.config and App.Release.config. In my project, I created a configuration for each kind of enironment so you might want to experiment with that.

2. Unload project and open .csproj file for editing

Visual Studio allows you to edit .csproj right in the editor—you just need to unload the project first. Then right-click on it and select Edit .csproj.

3. Bind App.*.config files to main App.config

Find the project file section that contains all App.config and App.*.config references and replace as follows. You'll notice we use None instead of Content.

<ItemGroup>
  <None Include="app.config"/>
  <None Include="app.Production.config">
    <DependentUpon>app.config</DependentUpon>
  </None>
  <None Include="app.QA.config">
    <DependentUpon>app.config</DependentUpon>
  </None>
  <None Include="app.Development.config">
    <DependentUpon>app.config</DependentUpon>
  </None>
</ItemGroup>

4. Activate transformations magic

In the end of file after

<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />

and before final

</Project>

insert the following XML:

<Import Project="AppConfigTransformation.targets" />

Done!

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

Another great way to accomplish this is to use a transparent image with a set aspect ratio. Then set the width of the image to 100% and the height to auto. That unfortunately will push down the original content of the container. So you need to wrap the original content in another div and position it absolutely to the top of the parent div.

<div class="parent">
   <img class="aspect-ratio" src="images/aspect-ratio.png" />
   <div class="content">Content</div>
</div>

CSS

.parent {
  position: relative;
}
.aspect-ratio {
  width: 100%;
  height: auto;
}
.content {
  position: absolute;
  width: 100%;
  top: 0; left: 0;
}

How to control the width of select tag?

Add div wrapper

<div id=myForm>
<select name=countries>
 <option value=af>Afghanistan</option>
 <option value=ax>Åland Islands</option>
 ...
 <option value=gs>South Georgia and the South Sandwich Islands</option>
 ...
</select>
</div>

and then write CSS

#myForm select { 
width:200px; }

#myForm select:focus {
width:auto; }

Hope this will help.

How do I use boolean variables in Perl?

use the following file prefix, this will add to your perl script eTRUE and eFALSE, it will actually be REAL(!) true and false (just like java)

#!/usr/bin/perl
use strict;
use warnings;

use constant { #real true false, compatible with encode_json decode_json for later (we don't want field:false... will be field:0...)
                eTRUE  =>  bless( do{\(my $o = 1)}, 'JSON::PP::Boolean' ),
                eFALSE =>  bless( do{\(my $o = 0)}, 'JSON::PP::Boolean' )
             };

There are, actually, few reasons why you should use that.

My reason is that working with JSON, I've got 0 and 1 as values to keys, but this hack will make sure correct values are kept along your script.

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

In simple words :

Inner join -> Take ONLY common records from parent and child tables WHERE primary key of Parent table matches Foreign key in Child table.

Left join ->

pseudo code

1.Take All records from left Table
2.for(each record in right table,) {
    if(Records from left & right table matching on primary & foreign key){
       use their values as it is as result of join at the right side for 2nd table.
    } else {
       put value NULL values in that particular record as result of join at the right side for 2nd table.
    }
  }

Right join : Exactly opposite of left join . Put name of table in LEFT JOIN at right side in Right join , you get same output as LEFT JOIN.

Outer join : Show all records in Both tables No matter what. If records in Left table are not matching to right table based on Primary , Forieign key , use NULL value as result of join .

Example :

Example

Lets assume now for 2 tables

1.employees , 2.phone_numbers_employees

employees : id , name 

phone_numbers_employees : id , phone_num , emp_id   

Here , employees table is Master table , phone_numbers_employees is child table(it contains emp_id as foreign key which connects employee.id so its child table.)

Inner joins

Take the records of 2 tables ONLY IF Primary key of employees table(its id) matches Foreign key of Child table phone_numbers_employees(emp_id).

So query would be :

SELECT e.id , e.name , p.phone_num FROM employees AS e INNER JOIN phone_numbers_employees AS p ON e.id = p.emp_id;

Here take only matching rows on primary key = foreign key as explained above.Here non matching rows on primary key = foreign key are skipped as result of join.

Left joins :

Left join retains all rows of the left table, regardless of whether there is a row that matches on the right table.

SELECT e.id , e.name , p.phone_num FROM employees AS e LEFT JOIN phone_numbers_employees AS p ON e.id = p.emp_id;

Outer joins :

SELECT e.id , e.name , p.phone_num FROM employees AS e OUTER JOIN phone_numbers_employees AS p ON e.id = p.emp_id;

Diagramatically it looks like :

Diagram

Host 'xxx.xx.xxx.xxx' is not allowed to connect to this MySQL server

Possibly a security precaution. You could try adding a new administrator account:

mysql> CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost'
    ->     WITH GRANT OPTION;
mysql> CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%'
    ->     WITH GRANT OPTION;

Although as Pascal and others have noted it's not a great idea to have a user with this kind of access open to any IP. If you need an administrative user, use root, and leave it on localhost. For any other action specify exactly the privileges you need and limit the accessibility of the user as Pascal has suggest below.

Edit:

From the MySQL FAQ:

If you cannot figure out why you get Access denied, remove from the user table all entries that have Host values containing wildcards (entries that contain '%' or '_' characters). A very common error is to insert a new entry with Host='%' and User='some_user', thinking that this allows you to specify localhost to connect from the same machine. The reason that this does not work is that the default privileges include an entry with Host='localhost' and User=''. Because that entry has a Host value 'localhost' that is more specific than '%', it is used in preference to the new entry when connecting from localhost! The correct procedure is to insert a second entry with Host='localhost' and User='some_user', or to delete the entry with Host='localhost' and User=''. After deleting the entry, remember to issue a FLUSH PRIVILEGES statement to reload the grant tables. See also Section 5.4.4, “Access Control, Stage 1: Connection Verification”.

Replace CRLF using powershell

This is a state-of-the-union answer as of Windows PowerShell v5.1 / PowerShell Core v6.2.0:

  • Andrew Savinykh's ill-fated answer, despite being the accepted one, is, as of this writing, fundamentally flawed (I do hope it gets fixed - there's enough information in the comments - and in the edit history - to do so).

  • Ansgar Wiecher's helpful answer works well, but requires direct use of the .NET Framework (and reads the entire file into memory, though that could be changed). Direct use of the .NET Framework is not a problem per se, but is harder to master for novices and hard to remember in general.

  • A future version of PowerShell Core will have a
    Convert-TextFile cmdlet with a -LineEnding parameter to allow in-place updating of text files with a specific newline style, as being discussed on GitHub.

In PSv5+, PowerShell-native solutions are now possible, because Set-Content now supports the -NoNewline switch, which prevents undesired appending of a platform-native newline[1] :

# Convert CRLFs to LFs only.
# Note:
#  * (...) around Get-Content ensures that $file is read *in full*
#    up front, so that it is possible to write back the transformed content
#    to the same file.
#  * + "`n" ensures that the file has a *trailing LF*, which Unix platforms
#     expect.
((Get-Content $file) -join "`n") + "`n" | Set-Content -NoNewline $file

The above relies on Get-Content's ability to read a text file that uses any combination of CR-only, CRLF, and LF-only newlines line by line.

Caveats:

  • You need to specify the output encoding to match the input file's in order to recreate it with the same encoding. The command above does NOT specify an output encoding; to do so, use -Encoding; without -Encoding:

    • In Windows PowerShell, you'll get "ANSI" encoding, your system's single-byte, 8-bit legacy encoding, such as Windows-1252 on US-English systems.
    • In PowerShell Core, you'll get UTF-8 encoding without a BOM.
  • The input file's content as well as its transformed copy must fit into memory as a whole, which can be problematic with large input files.

  • There's a risk of file corruption, if the process of writing back to the input file gets interrupted.


[1] In fact, if there are multiple strings to write, -NoNewline also doesn't place a newline between them; in the case at hand, however, this is irrelevant, because only one string is written.

Is it possible to set a number to NaN or infinity?

Yes, you can use numpy for that.

import numpy as np
a = arange(3,dtype=float)

a[0] = np.nan
a[1] = np.inf
a[2] = -np.inf

a # is now [nan,inf,-inf]

np.isnan(a[0]) # True
np.isinf(a[1]) # True
np.isinf(a[2]) # True

How do I do word Stemming or Lemmatization?

Look into WordNet, a large lexical database for the English language:

http://wordnet.princeton.edu/

There are APIs for accessing it in several languages.

Get first word of string

An improvement upon previous answers (working on multi-line or tabbed strings):

String.prototype.firstWord = function(){return this.replace(/\s.*/,'')}

Or using search and substr:

String.prototype.firstWord = function(){let sp=this.search(/\s/);return sp<0?this:this.substr(0,sp)}

Or without regex:

String.prototype.firstWord = function(){
  let sps=[this.indexOf(' '),this.indexOf('\u000A'),this.indexOf('\u0009')].
   filter((e)=>e!==-1);
  return sps.length? this.substr(0,Math.min(...sps)) : this;
}

Examples:

_x000D_
_x000D_
String.prototype.firstWord = function(){return this.replace(/\s.*/,'')}_x000D_
console.log(`linebreak_x000D_
example 1`.firstWord()); // -> linebreak_x000D_
console.log('space example 2'.firstWord()); // -> singleline_x000D_
console.log('tab example 3'.firstWord()); // -> tab
_x000D_
_x000D_
_x000D_

How to run a program without an operating system?

Operating System as the inspiration

The operating system is also a program, so we can also create our own program by creating from scratch or changing (limiting or adding) features of one of the small operating systems, and then run it during the boot process (using an ISO image).

For example, this page can be used as a starting point:

How to write a simple operating system

Here, the entire Operating System fit entirely in a 512-byte boot sector (MBR)!

Such or similar simple OS can be used to create a simple framework that will allow us:

make the bootloader load subsequent sectors on the disk into RAM, and jump to that point to continue execution. Or you could read up on FAT12, the filesystem used on floppy drives, and implement that.

There are many possibilities, however. For for example to see a bigger x86 assembly language OS we can explore the MykeOS, x86 operating system which is a learning tool to show the simple 16-bit, real-mode OSes work, with well-commented code and extensive documentation.

Boot Loader as the inspiration

Other common type of programs that run without the operating system are also Boot Loaders. We can create a program inspired by such a concept for example using this site:

How to develop your own Boot Loader

The above article presents also the basic architecture of such a programs:

  1. Correct loading to the memory by 0000:7C00 address.
  2. Calling the BootMain function that is developed in the high-level language.
  3. Show “”Hello, world…”, from low-level” message on the display.

As we can see, this architecture is very flexible and allows us to implement any program, not necessarily a boot loader.

In particular, it shows how to use the "mixed code" technique thanks to which it is possible to combine high-level constructions (from C or C++) with low-level commands (from Assembler). This is a very useful method, but we have to remember that:

to build the program and obtain executable file you will need the compiler and linker of Assembler for 16-bit mode. For C/C++ you will need only the compiler that can create object files for 16-bit mode.

The article shows also how to see the created program in action and how to perform its testing and debug.

UEFI applications as the inspiration

The above examples used the fact of loading the sector MBR on the data medium. However, we can go deeper into the depths by plaing for example with the UEFI applications:

Beyond loading an OS, UEFI can run UEFI applications, which reside as files on the EFI System Partition. They can be executed from the UEFI command shell, by the firmware's boot manager, or by other UEFI applications. UEFI applications can be developed and installed independently of the system manufacturer.

A type of UEFI application is an OS loader such as GRUB, rEFInd, Gummiboot, and Windows Boot Manager; which loads an OS file into memory and executes it. Also, an OS loader can provide a user interface to allow the selection of another UEFI application to run. Utilities like the UEFI shell are also UEFI applications.

If we would like to start creating such programs, we can, for example, start with these websites:

Programming for EFI: Creating a "Hello, World" Program / UEFI Programming - First Steps

Exploring security issues as the inspiration

It is well known that there is a whole group of malicious software (which are programs) that are running before the operating system starts.

A huge group of them operate on the MBR sector or UEFI applications, just like the all above solutions, but there are also those that use another entry point such as the Volume Boot Record (VBR) or the BIOS:

There are at least four known BIOS attack viruses, two of which were for demonstration purposes.

or perhaps another one too.

Attacks before system startup

Bootkits have evolved from Proof-of-Concept development to mass distribution and have now effectively become open-source software.

Different ways to boot

I also think that in this context it is also worth mentioning that there are various forms of booting the operating system (or the executable program intended for this). There are many, but I would like to pay attention to loading the code from the network using Network Boot option (PXE), which allows us to run the program on the computer regardless of its operating system and even regardless of any storage medium that is directly connected to the computer:

What Is Network Booting (PXE) and How Can You Use It?

How to output to the console in C++/Windows

Whether to use subsystem:console or subsystem:windows kind of depends on whether how you want to start your application:

  • If you use subsystem:console, then you get all of the stdout written to the terminal. The trouble is that if you start the application from the Start Menu/Desktop, you (by default) get a console appearing as well as the application window (which can look pretty ugly).
  • If you use subsystem:windows, you won't get stdout/stderr even if you run the application from a DOS window, Cygwin, or other terminal.

If you want the middle way which is to output to the terminal IF the application was started in a terminal, then follow the link that Luke provided in his solution (http://dslweb.nwnexus.com/~ast/dload/guicon.htm)

For reference, I ran into this problem with an application that I want to run in either normal Windows mode or batch mode (that is, as part of a script) depending on command-line switches. The whole differentiation between console and Windows applications is a bit bizarre to Unix folks!

Using union and order by clause in mysql

I got this working on a join plus union.

(SELECT 
   table1.column1,
   table1.column2,
   foo1.column4
 FROM table1, table2, foo1, table5
 WHERE table5.somerecord = table1.column1
 ORDER BY table1.column1 ASC, table1.column2 DESC
)

UNION

(SELECT
    ... Another complex query as above
)

ORDER BY column1 DESC, column2 ASC

How to include layout inside layout?

Edit: As in a comment rightly requested here some more information. Use the include tag

<include
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   layout="@layout/yourlayout" />

to include the layout you want to reuse.

Check this link out...

How can I get a list of all values in select box?

You had two problems:

1) The order in which you included the HTML. Try changing the dropdown from "onLoad" to "no wrap - head" in the JavaScript settings of your fiddle.

2) Your function prints the values. What you're actually after is the text

x.options[i].text; instead of x.options[i].value;

http://jsfiddle.net/WfBRr/5/

How do I compare two variables containing strings in JavaScript?

I used below function to compare two strings and It is working good.

function CompareUserId (first, second)
{

   var regex = new RegExp('^' + first+ '$', 'i');
   if (regex.test(second)) 
   {
        return true;
   }
   else 
   {
        return false;
   }
   return false;
}

How to get MD5 sum of a string using python?

You can do the following:

Python 2.x

import hashlib
print hashlib.md5("whatever your string is").hexdigest()

Python 3.x

import hashlib
print(hashlib.md5("whatever your string is".encode('utf-8')).hexdigest())

However in this case you're probably better off using this helpful Python module for interacting with the Flickr API:

... which will deal with the authentication for you.

Official documentation of hashlib

Chaining multiple filter() in Django, is this a bug?

As you can see in the generated SQL statements the difference is not the "OR" as some may suspect. It is how the WHERE and JOIN is placed.

Example1 (same joined table) :

(example from https://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships)

Blog.objects.filter(entry__headline__contains='Lennon', entry__pub_date__year=2008)

This will give you all the Blogs that have one entry with both (entry_headline_contains='Lennon') AND (entry__pub_date__year=2008), which is what you would expect from this query. Result: Book with {entry.headline: 'Life of Lennon', entry.pub_date: '2008'}

Example 2 (chained)

Blog.objects.filter(entry__headline__contains='Lennon').filter(entry__pub_date__year=2008)

This will cover all the results from Example 1, but it will generate slightly more result. Because it first filters all the blogs with (entry_headline_contains='Lennon') and then from the result filters (entry__pub_date__year=2008).

The difference is that it will also give you results like: Book with {entry.headline: 'Lennon', entry.pub_date: 2000}, {entry.headline: 'Bill', entry.pub_date: 2008}

In your case

I think it is this one you need:

Book.objects.filter(inventory__user__profile__vacation=False, inventory__user__profile__country='BR')

And if you want to use OR please read: https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects

Unable to run 'adb root' on a rooted Android phone

I finally found out how to do this! Basically you need to run adb shell first and then while you're in the shell run su, which will switch the shell to run as root!

$: adb shell
$: su

The one problem I still have is that sqlite3 is not installed so the command is not recognized.

CSS text-transform capitalize on all caps

The PHP solution, in backend:

$string = `UPPERCASE`
$lowercase = strtolower($string);
echo ucwords($lowercase);

How to compare DateTime in C#?

If you have two DateTime that looks the same, but Compare or Equals doesn't return what you expect, this is how to compare them.

Here an example with 1-millisecond precision:

bool areSame = (date1 - date2) > TimeSpan.FromMilliseconds(1d);

How do I get the path of the Python script I am running in?

7.2 of Dive Into Python: Finding the Path.

import sys, os

print('sys.argv[0] =', sys.argv[0])             
pathname = os.path.dirname(sys.argv[0])        
print('path =', pathname)
print('full path =', os.path.abspath(pathname)) 

Converting an integer to a string in PHP

$amount = 2351.25;
$str_amount = "2351.25";

$strCorrectAmount = "$amount";
echo gettype($strCorrectAmount);    //string

So the echo will be return string.

Check if Internet Connection Exists with jQuery?

I wrote a jQuery plugin for doing this. By default it checks the current URL (because that's already loaded once from the Web) or you can specify a URL to use as an argument. Always doing a request to Google isn't the best idea because it's blocked in different countries at different times. Also you might be at the mercy of what the connection across a particular ocean/weather front/political climate might be like that day.

http://tomriley.net/blog/archives/111

How to reset Jenkins security settings from the command line?

Edit the file $JENKINS_HOME/config.xml and change de security configuration with this:

<authorizationStrategy class="hudson.security.AuthorizationStrategy$Unsecured"/>

After that restart Jenkins.

How to quickly test some javascript code?

Following is a free list of tools you can use to check, test and verify your JS code:

  1. Google Code Playground
  2. JavaScript Sandbox
  3. jsbin
  4. jsfiddle
  5. pastebin
  6. jsdo.it
  7. firebug
  8. html5snippet.net

Hope this helps.

How to fix/convert space indentation in Sublime Text?

I wrote a plugin for it. You can find it here or look for "ReIndent" in package control. It mostly does the same thing as Kyle Finley wrote but in a convenient way with shortcuts for converting between 2 and 4 and vice-versa.

Load and execute external js file in node.js with access to local variables?

Expanding on @Shripad's and @Ivan's answer, I would recommend that you use Node.js's standard module.export functionality.

In your file for constants (e.g. constants.js), you'd write constants like this:

const CONST1 = 1;
module.exports.CONST1 = CONST1;

const CONST2 = 2;
module.exports.CONST2 = CONST2;

Then in the file in which you want to use those constants, write the following code:

const {CONST1 , CONST2} = require('./constants.js');

If you've never seen the const { ... } syntax before: that's destructuring assignment.

Where do I find the Instagram media ID of a image

Right click on a photo and open in a new tab/window. Right click on inspect element. Search for:

instagram://media?id=

This will give you:

instagram://media?id=############# /// the ID

The full id construct from

photoID_userID

To get the user id, search for:

instapp:owner_user_id Will be in content=

Error inflating class fragment

I was having the same problem as you are facing. None of the tips on top helped me. Later, I found that all I had to do is fix my imports from:

import android.app.Fragment;

to:

import android.support.v4.app.Fragment;

Favicon dimensions?

The format of favicon must be square otherwise the browser will stretch it. Unfortunatelly, Internet Explorer < 11 do not support .gif, or .png filetypes, but only Microsoft's .ico format. You can use some "favicon generator" app like: http://favicon-generator.org/

How to navigate to to different directories in the terminal (mac)?

To check that the file you're trying to open actually exists, you can change directories in terminal using cd. To change to ~/Desktop/sass/css: cd ~/Desktop/sass/css. To see what files are in the directory: ls.

If you want information about either of those commands, use the man page: man cd or man ls, for example.

Google for "basic unix command line commands" or similar; that will give you numerous examples of moving around, viewing files, etc in the command line.

On Mac OS X, you can also use open to open a finder window: open . will open the current directory in finder. (open ~/Desktop/sass/css will open the ~/Desktop/sass/css).

Returning IEnumerable<T> vs. IQueryable<T>

There is a blog post with brief source code sample about how misuse of IEnumerable<T> can dramatically impact LINQ query performance: Entity Framework: IQueryable vs. IEnumerable.

If we dig deeper and look into the sources, we can see that there are obviously different extension methods are perfomed for IEnumerable<T>:

// Type: System.Linq.Enumerable
// Assembly: System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Core.dll
public static class Enumerable
{
    public static IEnumerable<TSource> Where<TSource>(
        this IEnumerable<TSource> source, 
        Func<TSource, bool> predicate)
    {
        return (IEnumerable<TSource>) 
            new Enumerable.WhereEnumerableIterator<TSource>(source, predicate);
    }
}

and IQueryable<T>:

// Type: System.Linq.Queryable
// Assembly: System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Core.dll
public static class Queryable
{
    public static IQueryable<TSource> Where<TSource>(
        this IQueryable<TSource> source, 
        Expression<Func<TSource, bool>> predicate)
    {
        return source.Provider.CreateQuery<TSource>(
            Expression.Call(
                null, 
                ((MethodInfo) MethodBase.GetCurrentMethod()).MakeGenericMethod(
                    new Type[] { typeof(TSource) }), 
                    new Expression[] 
                        { source.Expression, Expression.Quote(predicate) }));
    }
}

The first one returns enumerable iterator, and the second one creates query through the query provider, specified in IQueryable source.

Expression must have class type

a is a pointer. You need to use->, not .

MySQL timezone change?

This works fine

<?php
      $con=mysqli_connect("localhost","my_user","my_password","my_db");
      $con->query("SET GLOBAL time_zone = 'Asia/Calcutta'");
      $con->query("SET time_zone = '+05:30'");
      $con->query("SET @@session.time_zone = '+05:30'");
?>

Parallel.ForEach vs Task.Factory.StartNew

I did a small experiment of running a method "1,000,000,000 (one billion)" times with "Parallel.For" and one with "Task" objects.

I measured the processor time and found Parallel more efficient. Parallel.For divides your task in to small work items and executes them on all the cores parallely in a optimal way. While creating lot of task objects ( FYI TPL will use thread pooling internally) will move every execution on each task creating more stress in the box which is evident from the experiment below.

I have also created a small video which explains basic TPL and also demonstrated how Parallel.For utilizes your core more efficiently http://www.youtube.com/watch?v=No7QqSc5cl8 as compared to normal tasks and threads.

Experiment 1

Parallel.For(0, 1000000000, x => Method1());

Experiment 2

for (int i = 0; i < 1000000000; i++)
{
    Task o = new Task(Method1);
    o.Start();
}

Processor time comparison

What's the difference between subprocess Popen and call (how can I use them)?

There are two ways to do the redirect. Both apply to either subprocess.Popen or subprocess.call.

  1. Set the keyword argument shell = True or executable = /path/to/the/shell and specify the command just as you have it there.

  2. Since you're just redirecting the output to a file, set the keyword argument

    stdout = an_open_writeable_file_object
    

    where the object points to the output file.

subprocess.Popen is more general than subprocess.call.

Popen doesn't block, allowing you to interact with the process while it's running, or continue with other things in your Python program. The call to Popen returns a Popen object.

call does block. While it supports all the same arguments as the Popen constructor, so you can still set the process' output, environmental variables, etc., your script waits for the program to complete, and call returns a code representing the process' exit status.

returncode = call(*args, **kwargs) 

is basically the same as calling

returncode = Popen(*args, **kwargs).wait()

call is just a convenience function. It's implementation in CPython is in subprocess.py:

def call(*popenargs, timeout=None, **kwargs):
    """Run command with arguments.  Wait for command to complete or
    timeout, then return the returncode attribute.

    The arguments are the same as for the Popen constructor.  Example:

    retcode = call(["ls", "-l"])
    """
    with Popen(*popenargs, **kwargs) as p:
        try:
            return p.wait(timeout=timeout)
        except:
            p.kill()
            p.wait()
            raise

As you can see, it's a thin wrapper around Popen.

Code Sign error: The identity 'iPhone Developer' doesn't match any valid certificate/private key pair in the default keychain

if your certificate is not valid, it will have a red "x" and state the reason why. Generally the reason is "This certificate has expired" or "This certificate was signed by an unknown authority.

to solve this you need to do the following step.

  1. If your certificate has expired, renew it at the iPhone Portal, download it, and double-click it to add it to your Keychain.
  2. If it's "signed by an unknown authority", download the "Apple Worldwide Developer Relations" certificate from the Certificates section of the iPhone Developer portal and double-click it to add it to your Keychain.
  3. If your certificate was revoked, delete the certificate from your Keychain, then follow the "Obtaining your iPhone Development Certificate" or "Obtaining your iPhone Distribution Certificate" section in the iPhone Developer Program Portal User Guide to generate a new certificate.
  4. Make sure you create a backup of your private key. The steps for doing this are described in the iPhone Developer Program Portal User Guide, under "Saving your Private Key and Transferring to other Systems".
  5. If you have the iPhone Developer (or iPhone Distribution) certificate and its associated private key, the Apple WWDR Intermediate certificate is installed, and your certificate is valid, confirm that Online Certificate Status Protocol (OCSP) and Certificate Revocation List (CRL) are set to "Off" in Keychain Access > Preferences > Certificates.
  6. if you still getting problem then contact support apple community.

TOMCAT - HTTP Status 404

  1. Click on Window > Show view > Server or right click on the server in "Servers" view, select "Properties".
  2. In the "General" panel, click on the "Switch Location" button.
  3. The "Location: [workspace metadata]" should replace by something else.
  4. Open the Overview screen for the server by double clicking it.
  5. In the Server locations tab , select "Use Tomcat location".
  6. Save the configurations and restart the Server.

You may want to follow the steps above before starting the server. Because server location section goes grayed-unreachable.

server Locations in eclipse view

How do I pass a value from a child back to the parent form?

Many ways to skin the cat here and @Mitch's suggestion is a good way. If you want the client form to have more 'control', you may want to pass the instance of the parent to the child when created and then you can call any public parent method on the child.

Can I do a max(count(*)) in SQL?

The following code gives you the answer. It essentially implements MAX(COUNT(*)) by using ALL. It has the advantage that it uses very basic commands and operations.

SELECT yr, COUNT(title)
FROM actor
JOIN casting ON actor.id = casting.actorid
JOIN movie ON casting.movieid = movie.id
WHERE name = 'John Travolta'
GROUP BY yr HAVING COUNT(title) >= ALL
  (SELECT COUNT(title)
   FROM actor
   JOIN casting ON actor.id = casting.actorid
   JOIN movie ON casting.movieid = movie.id
   WHERE name = 'John Travolta'
   GROUP BY yr)

Java LinkedHashMap get first or last entry

I would recommend using ConcurrentSkipListMap which has firstKey() and lastKey() methods

How do I break a string in YAML over multiple lines?

1. Block Notation(plain, flow-style, scalar): Newlines become spaces and extra newlines after the block are removed

---
# Note: It has 1 new line after the string
content:
    Arbitrary free text
    over multiple lines stopping
    after indentation changes...

...

Equivalent JSON

{
 "content": "Arbitrary free text over multiple lines stopping after indentation changes..."
}

2. Literal Block Scalar: A Literal Block Scalar | will include the newlines and any trailing spaces. but removes extra

newlines after the block.

---
# After string we have 2 spaces and 2 new lines
content1: |
 Arbitrary free text
 over "multiple lines" stopping
 after indentation changes...  


...

Equivalent JSON

{
 "content1": "Arbitrary free text\nover \"multiple lines\" stopping\nafter indentation changes...  \n"
}

3. + indicator with Literal Block Scalar: keep extra newlines after block

---
# After string we have 2 new lines
plain: |+
 This unquoted scalar
 spans many lines.


...

Equivalent JSON

{
 "plain": "This unquoted scalar\nspans many lines.\n\n\n"
}

4. – indicator with Literal Block Scalar: means that the newline at the end of the string is removed.

---
# After string we have 2 new lines
plain: |-
 This unquoted scalar
 spans many lines.


...

Equivalent JSON

{
 "plain": "This unquoted scalar\nspans many lines."
}

5. Folded Block Scalar(>):

will fold newlines to spaces and but removes extra newlines after the block.

---
folded_newlines: >
 this is really a
 single line of text
 despite appearances


...

Equivalent JSON

{
 "fold_newlines": "this is really a single line of text despite appearances\n"
}

for more you can visit my Blog

What are alternatives to ExtJS?

Nothing compares to in terms of community size and presence on StackOverflow. Despite previous controversy, Ext JS now has a GPLv3 open source license. Its learning curve is long, but it can be quite rewarding once learned. Ext JS lacks a Material Design theme, and the team has repeatedly refused to release the source code on GitHub. For mobile, one must use the separate Sencha Touch library.

Have in mind also that,

large JavaScript libraries, such as YUI, have been receiving less attention from the community. Many developers today look at large JavaScript libraries as walled gardens they don’t want to be locked into.

-- Announcement of YUI development being ceased

That said, below are a number of Ext JS alternatives currently available.

Leading client widget libraries

  1. Blueprint is a React-based UI toolkit developed by big data analytics company Palantir in TypeScript, and "optimized for building complex data-dense interfaces for desktop applications". Actively developed on GitHub as of May 2019, with comprehensive documentation. Components range from simple (chips, toast, icons) to complex (tree, data table, tag input with autocomplete, date range picker. No accordion or resizer.

    Blueprint targets modern browsers (Chrome, Firefox, Safari, IE 11, and Microsoft Edge) and is licensed under a modified Apache license.

    Sandbox / demoGitHubDocs

  2. Webix - an advanced, easy to learn, mobile-friendly, responsive and rich free&open source JavaScript UI components library. Webix spun off from DHTMLX Touch (a project with 8 years of development behind it - see below) and went on to become a standalone UI components framework. The GPL3 edition allows commercial use and lets non-GPL applications using Webix keep their license, e.g. MIT, via a license exemption for FLOSS. Webix has 55 UI widgets, including trees, grids, treegrids and charts. Funding comes from a commercial edition with some advanced widgets (Pivot, Scheduler, Kanban, org chart etc.). Webix has an extensive list of free and commercial widgets, and integrates with most popular frameworks (React, Vue, Meteor, etc) and UI components.

    Webix

    Skins look modern, and include a Material Design theme. The Touch theme also looks quite Material Design-ish. See also the Skin Builder.

    Minimal GitHub presence, but includes the library code, and the documentation (which still needs major improvements). Webix suffers from a having a small team and a lack of marketing. However, they have been responsive to user feedback, both on GitHub and on their forum.

    The library was lean (128Kb gzip+minified for all 55 widgets as of ~2015), faster than ExtJS, dojo and others, and the design is pleasant-looking. The current version of Webix (v6, as of Nov 2018) got heavier (400 - 676kB minified but NOT gzipped).

    The demos on Webix.com look and function great. The developer, XB Software, uses Webix in solutions they build for paying customers, so there's likely a good, funded future ahead of it.

    Webix aims for backwards compatibility down to IE8, and as a result carries some technical debt.

    WikipediaGitHubPlayground/sandboxAdmin dashboard demoDemosWidget samples

  3. react-md - MIT-licensed Material Design UI components library for React. Responsive, accessible. Implements components from simple (buttons, cards) to complex (sortable tables, autocomplete, tags input, calendars). One lead author, ~1900 GitHub stars.

  4. - jQuery-based UI toolkit with 40+ basic open-source widgets, plus commercial professional widgets (grids, trees, charts etc.). Responsive&mobile support. Works with Bootstrap and AngularJS. Modern, with Material Design themes. The documentation is available on GitHub, which has enabled numerous contributions from users (4500+ commits, 500+ PRs as of Jan 2015).

    enter image description here

    Well-supported commercially, claiming millions of developers, and part of a large family of developer tools. Telerik has received many accolades, is a multi-national company (Bulgaria, US), was acquired by Progress Software, and is a thought leader.

    A Kendo UI Professional developer license costs $700 and posting access to most forums is conditioned upon having a license or being in the trial period.

    [Wikipedia] • GitHub/TelerikDemosPlaygroundTools

  5. OpenUI5 - jQuery-based UI framework with 180 widgets, Apache 2.0-licensed and fully-open sourced and funded by German software giant SAP SE.

    OpenUI5

    The community is much larger than that of Webix, SAP is hiring developers to grow OpenUI5, and they presented OpenUI5 at OSCON 2014.

    The desktop themes are rather lackluster, but the Fiori design for web and mobile looks clean and neat.

    WikipediaGitHubMobile-first controls demosDesktop controls demosSO

  6. DHTMLX - JavaScript library for building rich Web and Mobile apps. Looks most like ExtJS - check the demos. Has been developed since 2005 but still looks modern. All components except TreeGrid are available under GPLv2 but advanced features for many components are only available in the commercial PRO edition - see for example the tree. Claims to be used by many Fortune 500 companies.

    DHTMLX

    Minimal presence on GitHub (the main library code is missing) and StackOverflow but active forum. The documentation is not available on GitHub, which makes it difficult to improve by the community.

  7. Polymer, a Web Components polyfill, plus Polymer Paper, Google's implementation of the Material design. Aimed at web and mobile apps. Doesn't have advanced widgets like trees or even grids but the controls it provides are mobile-first and responsive. Used by many big players, e.g. IBM or USA Today.

    Polymer Paper Elements

  8. Ant Design claims it is "a design language for background applications", influenced by "nature" and helping designers "create low-entropy atmosphere for developer team". That's probably a poor translation from Chinese for "UI components for enterprise web applications". It's a React UI library written in TypeScript, with many components, from simple (buttons, cards) to advanced (autocomplete, calendar, tag input, table).

    The project was born in China, is popular with Chinese companies, and parts of the documentation are available only in Chinese. Quite popular on GitHub, yet it makes the mistake of splitting the community into Chinese and English chat rooms. The design looks Material-ish, but fonts are small and the information looks lost in a see of whitespace.

  9. PrimeUI - collection of 45+ rich widgets based on jQuery UI. Apache 2.0 license. Small GitHub community. 35 premium themes available.

  10. qooxdoo - "a universal JavaScript framework with a coherent set of individual components", developed and funded by German hosting provider 1&1 (see the contributors, one of the world's largest hosting companies. GPL/EPL (a business-friendly license).

    Mobile themes look modern but desktop themes look old (gradients).

    Qooxdoo

    WikipediaGitHubWeb/Mobile/Desktop demosWidgets Demo browserWidget browserSOPlaygroundCommunity

  11. jQuery UI - easy to pick up; looks a bit dated; lacks advanced widgets. Of course, you can combine it with independent widgets for particular needs, e.g. trees or other UI components, but the same can be said for any other framework.

  12. + Angular UI. While Angular is backed by Google, it's being radically revamped in the upcoming 2.0 version, and "users will need to get to grips with a new kind of architecture. It's also been confirmed that there will be no migration path from Angular 1.X to 2.0". Moreover, the consensus seems to be that Angular 2 won't really be ready for use until a year or two from now. Angular UI has relatively few widgets (no trees, for example).

  13. DojoToolkit and their powerful Dijit set of widgets. Completely open-sourced and actively developed on GitHub, but development is now (Nov 2018) focused on the new dojo.io framework, which has very few basic widgets. BSD/AFL license. Development started in 2004 and the Dojo Foundation is being sponsored by IBM, Google, and others - see Wikipedia. 7500 questions here on SO.

    Dojo Dijit

    Themes look desktop-oriented and dated - see the theme tester in dijit. The official theme previewer is broken and only shows "Claro". A Bootstrap theme exists, which looks a lot like Bootstrap, but doesn't use Bootstrap classes. In Jan 2015, I started a thread on building a Material Design theme for Dojo, which got quite popular within the first hours. However, there are questions regarding building that theme for the current Dojo 1.10 vs. the next Dojo 2.0. The response to that thread shows an active and wide community, covering many time zones.

    Unfortunately, Dojo has fallen out of popularity and fewer companies appear to use it, despite having (had?) a strong foothold in the enterprise world. In 2009-2012, its learning curve was steep and the documentation needed improvements; while the documentation has substantially improved, it's unclear how easy it is to pick up Dojo nowadays.

    With a Material Design theme, Dojo (2.0?) might be the killer UI components framework.

    WikipediaGitHubThemesDemosDesktop widgetsSO

  14. Enyo - front-end library aimed at mobile and TV apps (e.g. large touch-friendly controls). Developed by LG Electronix and Apache-licensed on GitHub.

  15. The radical Cappuccino - Objective-J (a superset of JavaScript) instead of HTML+CSS+DOM

  16. Mochaui, MooTools UI Library User Interface Library. <300 GitHub stars.

  17. CrossUI - cross-browser JS framework to develop and package the exactly same code and UI into Web Apps, Native Desktop Apps (Windows, OS X, Linux) and Mobile Apps (iOS, Android, Windows Phone, BlackBerry). Open sourced LGPL3. Featured RAD tool (form builder etc.). The UI looks desktop-, not web-oriented. Actively developed, small community. No presence on GitHub.

  18. ZinoUI - simple widgets. The DataTable, for instance, doesn't even support sorting.

  19. Wijmo - good-looking commercial widgets, with old (jQuery UI) widgets open-sourced on GitHub (their development stopped in 2013). Developed by ComponentOne, a division of GrapeCity. See Wijmo Complete vs. Open.

  20. CxJS - commercial JS framework based on React, Babel and webpack offering form elements, form validation, advanced grid control, navigational elements, tooltips, overlays, charts, routing, layout support, themes, culture dependent formatting and more.

CxJS

Widgets - Demo Apps - Examples - GitHub

Full-stack frameworks

  1. SproutCore - developed by Apple for web applications with native performance, handling large data sets on the client. Powers iCloud.com. Not intended for widgets.

  2. Wakanda: aimed at business/enterprise web apps - see What is Wakanda?. Architecture:

  3. Servoy - "a cross platform frontend development and deployment environment for SQL databases". Boasts a "full WYSIWIG (What You See Is What You Get) UI designer for HTML5 with built-in data-binding to back-end services", responsive design, support for HTML6 Web Components, Websockets and mobile platforms. Written in Java and generates JavaScript code using various JavaBeans.

  4. SmartClient/SmartGWT - mobile and cross-browser HTML5 UI components combined with a Java server. Aimed at building powerful business apps - see demos.

  5. Vaadin - full-stack Java/GWT + JavaScript/HTML3 web app framework

  6. Backbase - portal software

  7. Shiny - front-end library on top R, with visualization, layout and control widgets

  8. ZKOSS: Java+jQuery+Bootstrap framework for building enterprise web and mobile apps.

CSS libraries + minimal widgets

These libraries don't implement complex widgets such as tables with sorting/filtering, autocompletes, or trees.

  1. Bootstrap

  2. Foundation for Apps - responsive front-end framework on top of AngularJS; more of a grid/layout/navigation library

  3. UI Kit - similar to Bootstrap, with fewer widgets, but with official off-canvas.

Libraries using HTML Canvas

Using the canvas elements allows for complete control over the UI, and great cross-browser compatibility, but comes at the cost of missing native browser functionality, e.g. page search via Ctrl/Cmd+F.

  1. Zebra - demos

No longer developed as of Dec 2014

  1. Yahoo! User Interface - YUI, launched in 2005, but no longer maintained by the core contributors - see the announcement, which highlights reasons why large UI widget libraries are perceived as walled gardens that developers don't want to be locked into.
  2. echo3, GitHub. Supports writing either server-side Java applications that don't require developer knowledge of HTML, HTTP, or JavaScript, or client-side JavaScript-based applications do not require a server, but can communicate with one via AJAX. Last update: July 2013.
  3. ampleSDK
  4. Simpler widgets livepipe.net
  5. JxLib
  6. rialto
  7. Simple UI kit
  8. Prototype-ui

Other lists

PHP regular expressions: No ending delimiter '^' found in

You can use T-Regx library, that doesn't need delimiters

pattern('^([0-9]+)$')->match($input);

How do you set a default value for a MySQL Datetime column?

MySQL 5.6 has fixed this problem.

ALTER TABLE mytable CHANGE mydate datetime NOT NULL DEFAULT 'CURRENT_TIMESTAMP'

How to validate date with format "mm/dd/yyyy" in JavaScript?

I would use Moment.js for date validation.

alert(moment("05/22/2012", 'MM/DD/YYYY',true).isValid()); //true

Jsfiddle: http://jsfiddle.net/q8y9nbu5/

true value is for strict parsing credit to @Andrey Prokhorov which means

you may specify a boolean for the last argument to make Moment use strict parsing. Strict parsing requires that the format and input match exactly, including delimeters.

What is Mocking?

Mocking is generating pseudo-objects that simulate real objects behaviour for tests

CSS-moving text from left to right

I am not sure if this is the correct solution but I have achieved this by redefining .marquee class just after animation CSS.

Check below:

<style>
#marquee-wrapper{
    width:700px;
    display:block;
    border:1px solid red;
}

div.marquee{
width:100px;
height:100px;
background:red;
position:relative;
animation:myfirst 5s;
-moz-animation:myfirst 5s; /* Firefox */
}

@-moz-keyframes myfirst /* Firefox */{
0%   {background:red; left:0px; top:0px;}
100% {background:red; left:100%; top:0px}
}
div.marquee{ 
left:700px; top:0px
}
</style>

<!-- HTMl COde -->

<p><b>Note:</b> This example does not work in Internet Explorer and Opera.</p>
<div id="marquee-wrapper">
<div class="marquee"></div>

How to check if an object is an array?

The following could be used if you know that your object doesn't have a concat method.

_x000D_
_x000D_
var arr = [];_x000D_
if (typeof arr.concat === 'function') {_x000D_
    console.log("It's an array");_x000D_
}
_x000D_
_x000D_
_x000D_

Error: vector does not name a type

You need to either qualify vector with its namespace (which is std), or import the namespace at the top of your CPP file:

using namespace std;

How to know if two arrays have the same values

Answering after long time but hope this will help somebody who looking for a simple solution and modern newbies.

Now we can achieve this using multiple libraries like lodash, underscore, etc. (These becomes part of the project nowadays due to simplicity, multiple features and high usage)

You can use intersection from lodash library.

_.intersection(['2-1', '1'], ['2-2', '3-1', '2-1']); 
// => ['2-1']

This will work for any data type..

How to squash commits in git after they have been pushed?

A lot of problems can be avoided by only creating a branch to work on & not working on master:

git checkout -b mybranch

The following works for remote commits already pushed & a mixture of remote pushed commits / local only commits:

# example merging 4 commits

git checkout mybranch
git rebase -i mybranch~4 mybranch

# at the interactive screen
# choose fixup for commit: 2 / 3 / 4

git push -u origin +mybranch

I also have some pull request notes which may be helpful.

importing jar libraries into android-studio

Updated answer for Android Studio 2

The easy and correct way to import a jar/aar into your project is to import it as a module.

New -> Module

Right click on the main project and New -> Module

Select Import .JAR/.AAR Package

Import .JAR/.AAR Package

Select the .JAR/.AAR file and put a module name

Select the .JAR/.AAR file

Add the module as a dependency

Add the module as a dependency

The requested resource does not support HTTP method 'GET'

just use this attribute

[System.Web.Http.HttpGet]

not need this line of code:

[System.Web.Http.AcceptVerbs("GET", "POST")]

The EXECUTE permission was denied on the object 'xxxxxxx', database 'zzzzzzz', schema 'dbo'

You don't have the right to execute it, although you have enough permissions to create it.

For more information, see GRANT Object Permissions (Transact-SQL)

Change first commit of project with Git?

If you want to modify only the first commit, you may try git rebase and amend the commit, which is similar to this post: How to modify a specified commit in git?

And if you want to modify all the commits which contain the raw email, filter-branch is the best choice. There is an example of how to change email address globally on the book Pro Git, and you may find this link useful http://git-scm.com/book/en/Git-Tools-Rewriting-History

Git push: "fatal 'origin' does not appear to be a git repository - fatal Could not read from remote repository."

This is the way I updated the master branch

This kind of error occurs commonly after deleting the initial code on your project

So, go ahead, first of all, verify the actual remote version, then remove the origin add the comment, and copy the repo URL into the project files.

$ git remote -v
$ git remote rm origin
$ git commit -m "your commit"
$ git remote add origin https://github.com/user/repo.git
$ git push -f origin master

href overrides ng-click in Angular.js

There are so many answers for this question here but it seems there is a bit of confusion about what's actually going on here.

Firstly, your premise

"href overrides ng-click in Angular.js"

is wrong. What is actually happening is that after your click, the click event is first handled by angular(defined by ng-click directive in angular 1.x and click in angular 2.x+) and then it continues to propagate(which eventually triggers the browser to navigate to the url defined with href attribute).(See this for more about event propagation in javascript)

If you want to avoid this, then you should cancel the event propagation using the The Event interface's preventDefault() method:

<a href="#" ng-click="$event.preventDefault();logout()" />

(This is pure javascript functionality and nothing to do with angular)

Now, this will already solve your problem but this is not the optimal solution. Angular, rightfully, promotes the MVC pattern. With this solution, your html template is mixed with the javascript logic. You should try to avoid this as much as possible and put your logic into your angular controller. So a better way would be

<a href="#" ng-click="logout($event)" />

And in your logout() method:

logout($event) {
   $event.preventDefault();
   ...
}

Now the click event will not reach the browser, so it will not try to load the link pointed by href. (However note that if the user right clicks on the link and directly opens the link, then there won't be a click event at all. Instead it will directly load the url pointed by the href attribute.)

Regarding the comments about visited link color in the browsers. Again this has nothing to do with angular, if your href="..." points to a visited url by your browser by default the link color will be different. This is controlled by CSS :visited Selector, you can modify your css to override this behaviour:

a {
   color:pink;
}

PS1:

Some answers suggest to use:

<a href .../>

href is an angular directive. When your template is processed by angular this will be converted to

<a href="" .../>

Those two ways are essentially the same.

Gradle - Error Could not find method implementation() for arguments [com.android.support:appcompat-v7:26.0.0]

So ridiculous, but I still wanna share my experience in case of that someone falls into the situation like me.

Please check if you changed: compileSdkVersion --> implementationSdkVersion by mistake

Android failed to load JS bundle

Check your wifi connection.

Another possibility could be you are either not connected to wifi, connected to the wrong network, or the ip address is wrong in your dev settings. For some reason, my android disconnected from the wifi and I started to get this error, unknowingly.

How can I clear console

For Linux/Unix and maybe some others but not for Windows before 10 TH2:

printf("\033c");

will reset terminal.

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

Here is a better and elegant solution for your problem statement.

int mynumbercheck = 1000;
// Your number to be checked
var myswitch = new Dictionary <Func<int,bool>, Action>
            { 
             { x => x < 10 ,    () => //Do this!...  },  
             { x => x < 100 ,    () => //Do this!...  },
             { x => x < 1000 ,    () => //Do this!...  },
             { x => x < 10000 ,   () => //Do this!... } ,
             { x => x < 100000 ,  () => //Do this!... },
             { x => x < 1000000 ,  () => //Do this!... } 
            };

Now to call our conditional switch

   myswitch.First(sw => sw.Key(mynumbercheck)).Value();

Alternate for Switch/ifElse

How to set shape's opacity?

use this code below as progress.xml:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@android:id/background">
        <shape>
            <corners android:radius="5dip" />
            <gradient
                    android:startColor="#ff9d9e9d"
                    android:centerColor="#ff5a5d5a"
                    android:centerY="0.75"
                    android:endColor="#ff747674"
                    android:angle="270"
            />
        </shape>
    </item>

    <item android:id="@android:id/secondaryProgress">
        <clip>
            <shape>
                <solid android:color="#00000000" />
            </shape>
        </clip>
    </item>

    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <solid android:color="#00000000" />
            </shape>
        </clip>
    </item>

</layer-list>

where:

  • "progress" is current progress before the thumb and "secondaryProgress" is the progress after thumb.
  • color="#00000000" is a perfect transparency
  • NOTE: the file above is from default android res and is for 2.3.7, it is available on android sources at: frameworks/base/core/res/res/drawable/progress_horizontal.xml. For newer versions you must find the default drawable file for the seekbar corresponding to your android version.

after that use it in the layout containing the xml:

<SeekBar
    android:id="@+id/myseekbar"
    ...
    android:progressDrawable="@drawable/progress"
    />

you can also customize the thumb by using a custom icon seek_thumb.png:

android:thumb="@drawable/seek_thumb"

I do not want to inherit the child opacity from the parent in CSS

It seems that display: block elements do not inherit opacity from display: inline parents.

Codepen example

Maybe because it's invalid markup and the browser is secretly separating them? Because source doesn't show that happening. Am I missing something?

Where does MAMP keep its php.ini?

After running the MAMP server, you have php info link in toolbar Once click, You will get all information about php enter image description here

How to style an asp.net menu with CSS

The thing to look at is what HTML is being spit out by the control. In this case it puts out a table to create the menu. The hover style is set on the TD and once you select a menu item the control posts back and adds the selected style to the A tag of the link within the TD.

So you have two different items that are being manipulated here. One is a TD element and another is an A element. So, you have to make your CSS work accordingly. If I add the below CSS to a page with the menu then I get the expected behavior of the background color changing in either case. You may be doing some different CSS manipulation that may or may not apply to those elements.

<style>
    .StaticHoverStyle
    {
        background: #000000;
    }

    .StaticSelectedStyle
    {
        background: blue;
    }
</style>

How do I ignore ampersands in a SQL script running from SQL Plus?

You can set the special character, which is looked for upon execution of a script, to another value by means of using the SET DEFINE <1_CHARACTER>

By default, the DEFINE function itself is on, and it is set to &

It can be turned off - as mentioned already - but it can be avoided as well by means of setting it to a different value. Be very aware of what sign you set it to. In the below example, I've chose the # character, but that choice is just an example.

SQL> select '&var_ampersand #var_hash' from dual;
Enter value for var_ampersand: a value

'AVALUE#VAR_HASH'
-----------------
a value #var_hash

SQL> set define #
SQL> r
  1* select '&var_ampersand #var_hash' from dual
Enter value for var_hash: another value

'&VAR_AMPERSANDANOTHERVALUE'
----------------------------
&var_ampersand another value

SQL>

Programmatically register a broadcast receiver

Create a broadcast receiver

[BroadcastReceiver(Enabled = true, Exported = false)]

public class BCReceiver : BroadcastReceiver
{

    BCReceiver receiver;

    public override void OnReceive(Context context, Intent intent)
    {
        //Do something here
    }
}

From your activity add this code:

LocalBroadcastManager.getInstance(ApplicationContext)
    .registerReceiver(receiver, filter);

Extract first and last row of a dataframe in pandas

You can also use head and tail:

In [29]: pd.concat([df.head(1), df.tail(1)])
Out[29]:
   a  b
0  1  a
3  4  d

Java swing application, close one window and open another when button is clicked

Here is an example:

enter image description here

enter image description here

StartupWindow.java

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;


public class StartupWindow extends JFrame implements ActionListener
{
    private JButton btn;

    public StartupWindow()
    {
        super("Simple GUI");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        btn = new JButton("Open the other JFrame!");
        btn.addActionListener(this);
        btn.setActionCommand("Open");
        add(btn);
        pack();

    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        String cmd = e.getActionCommand();

        if(cmd.equals("Open"))
        {
            dispose();
            new AnotherJFrame();
        }
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable(){

            @Override
            public void run()
            {
                new StartupWindow().setVisible(true);
            }

        });
    }
}

AnotherJFrame.java

import javax.swing.JFrame;
import javax.swing.JLabel;

public class AnotherJFrame extends JFrame
{
    public AnotherJFrame()
    {
        super("Another GUI");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        add(new JLabel("Empty JFrame"));
        pack();
        setVisible(true);
    }
}

Docker "ERROR: could not find an available, non-overlapping IPv4 address pool among the defaults to assign to the network"

I ran into this issue on a corporate development VM which wasn't running OpenVPN. Checking out etc/docker/daemon.json, I found

...
"default-address-pools": [
  {
    "base": "192.168.11.0/24",
    "size": 24
  }
],
...

Strangely, removing the default-address-pools field and then restarting docker with sudo systemctl restart docker fixed the issue for me. I'm assuming this let docker choose a more suitable default, but I don't know what the problem was with the chosen default.

Import Android volley to Android Studio

The "compile project(':volley')" line was giving me this error:

Error:Execution failed for task ':volley:processDebugResources'. > com.android.ide.common.process.ProcessException: Failed to execute aapt

It was caused because the compileSdk and buildTools versions of module volley were currently on"22" and "22.0.1" and I my project was working with newer ones ("24" and "24.0.1").

SOLUTION:

Open your build.gradle (Module:volley) file and change the version of "compileSdk" and "buildTools", for example I changed this:

android {
    compileSdkVersion 22
    buildToolsVersion = '22.0.1'
}

for this:

android {
    compileSdkVersion 24
    buildToolsVersion = '24.0.1'
}

You should no longer have this error, I hope it helps:)

What is the best way to use a HashMap in C++?

The standard library includes the ordered and the unordered map (std::map and std::unordered_map) containers. In an ordered map the elements are sorted by the key, insert and access is in O(log n). Usually the standard library internally uses red black trees for ordered maps. But this is just an implementation detail. In an unordered map insert and access is in O(1). It is just another name for a hashtable.

An example with (ordered) std::map:

#include <map>
#include <iostream>
#include <cassert>

int main(int argc, char **argv)
{
  std::map<std::string, int> m;
  m["hello"] = 23;
  // check if key is present
  if (m.find("world") != m.end())
    std::cout << "map contains key world!\n";
  // retrieve
  std::cout << m["hello"] << '\n';
  std::map<std::string, int>::iterator i = m.find("hello");
  assert(i != m.end());
  std::cout << "Key: " << i->first << " Value: " << i->second << '\n';
  return 0;
}

Output:

23
Key: hello Value: 23

If you need ordering in your container and are fine with the O(log n) runtime then just use std::map.

Otherwise, if you really need a hash-table (O(1) insert/access), check out std::unordered_map, which has a similar to std::map API (e.g. in the above example you just have to search and replace map with unordered_map).

The unordered_map container was introduced with the C++11 standard revision. Thus, depending on your compiler, you have to enable C++11 features (e.g. when using GCC 4.8 you have to add -std=c++11 to the CXXFLAGS).

Even before the C++11 release GCC supported unordered_map - in the namespace std::tr1. Thus, for old GCC compilers you can try to use it like this:

#include <tr1/unordered_map>

std::tr1::unordered_map<std::string, int> m;

It is also part of boost, i.e. you can use the corresponding boost-header for better portability.

How do I remove a substring from the end of a string in Python?

Here,i have a simplest code.

url=url.split(".")[0]

setHintTextColor() in EditText

You could call editText.invalidate() after you reset the hint color. That could resolve your issue. Actually the SDK update the color in the same way.

How do I copy the contents of one stream to another?

Easy and safe - make new stream from original source:

    MemoryStream source = new MemoryStream(byteArray);
    MemoryStream copy = new MemoryStream(byteArray);

How do I mock a service that returns promise in AngularJS Jasmine unit test?

describe('testing a method() on a service', function () {    

    var mock, service

    function init(){
         return angular.mock.inject(function ($injector,, _serviceUnderTest_) {
                mock = $injector.get('service_that_is_being_mocked');;                    
                service = __serviceUnderTest_;
            });
    }

    beforeEach(module('yourApp'));
    beforeEach(init());

    it('that has a then', function () {
       //arrange                   
        var spy= spyOn(mock, 'actionBeingCalled').and.callFake(function () {
            return {
                then: function (callback) {
                    return callback({'foo' : "bar"});
                }
            };
        });

        //act                
        var result = service.actionUnderTest(); // does cleverness

        //assert 
        expect(spy).toHaveBeenCalled();  
    });
});

Interface vs Base class

An inheritor of a base class should have an "is a" relationship. Interface represents An "implements a" relationship. So only use a base class when your inheritors will maintain the is a relationship.

How to resolve "Server Error in '/' Application" error?

It sounds like the admin has locked the "authentication" node of the web.config, which one can do in the global web.config pretty easily. Or, in a nutshell, this is working as designed.

How do I get git to default to ssh and not https for new repositories

You need to clone in ssh not in https.

For that you need to set your ssh keys. I have prepared this little script that automates this:

#!/usr/bin/env bash
email="$1"
hostname="$2"
hostalias="$hostname"
keypath="$HOME/.ssh/${hostname}_rsa"
ssh-keygen -t rsa -C $email -f $keypath
if [ $? -eq 0 ]; then
cat >> ~/.ssh/config <<EOF
Host $hostalias
        Hostname $hostname *.$hostname
        User git
    IdentitiesOnly yes
        IdentityFile $keypath
EOF
fi

and run it like

bash script.sh [email protected] github.com

Change your remote url

git remote set-url origin [email protected]:user/foo.git

Add content of ~/.ssh/github.com_rsa.pub to your ssh keys on github.com

Check connection

ssh -T [email protected]

delete all record from table in mysql

It’s because you tried to update a table without a WHERE that uses a KEY column.

The quick fix is to add SET SQL_SAFE_UPDATES=0; before your query :

SET SQL_SAFE_UPDATES=0; 

Or

close the safe update mode. Edit -> Preferences -> SQL Editor -> SQL Editor remove Forbid UPDATE and DELETE statements without a WHERE clause (safe updates) .

BTW you can use TRUNCATE TABLE tablename; to delete all the records .

How to call base.base.method()?

Why not simply cast the child class to a specific parent class and invoke the specific implementation then? This is a special case situation and a special case solution should be used. You will have to use the new keyword in the children methods though.

public class SuperBase
{
    public string Speak() { return "Blah in SuperBase"; }
}

public class Base : SuperBase
{
    public new string Speak() { return "Blah in Base"; }
}

public class Child : Base
{
    public new string Speak() { return "Blah in Child"; }
}

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        Child childObj = new Child();

        Console.WriteLine(childObj.Speak());

        // casting the child to parent first and then calling Speak()
        Console.WriteLine((childObj as Base).Speak()); 

        Console.WriteLine((childObj as SuperBase).Speak());
    }
}

Remove carriage return in Unix

If you're using an OS (like OS X) that doesn't have the dos2unix command but does have a Python interpreter (version 2.5+), this command is equivalent to the dos2unix command:

python -c "import sys; import fileinput; sys.stdout.writelines(line.replace('\r', '\n') for line in fileinput.input(mode='rU'))"

This handles both named files on the command line as well as pipes and redirects, just like dos2unix. If you add this line to your ~/.bashrc file (or equivalent profile file for other shells):

alias dos2unix="python -c \"import sys; import fileinput; sys.stdout.writelines(line.replace('\r', '\n') for line in fileinput.input(mode='rU'))\""

... the next time you log in (or run source ~/.bashrc in the current session) you will be able to use the dos2unix name on the command line in the same manner as in the other examples.

How to access full source of old commit in BitBucket?

Great answers from a couple of years ago. Now Bitbucket has made it easier.

Tag the Commit you want to download (as mentioned in answer by Rudy Matela).

Then head over to Downloads and click the "Tags" tab and you'll get multiple options for download.

Tag Downloads

How to sort a list of lists by a specific index of the inner list?

Sorting a Multidimensional Array execute here

arr=[[2,1],[1,2],[3,5],[4,5],[3,1],[5,2],[3,8],[1,9],[1,3]]



arr.sort(key=lambda x:x[0])
la=set([i[0] for i in Points])

for i in la:
    tempres=list()
    for j in arr:
        if j[0]==i:
            tempres.append(j[1])

    for j in sorted(tempres,reverse=True):
        print(i,j)

How do I get just the date when using MSSQL GetDate()?

SELECT CONVERT(DATETIME, CONVERT(varchar(10), GETDATE(), 101))