Programs & Examples On #Dynamic cast

dynamic_cast and static_cast in C++

No, not easily. The compiler assigns a unique identity to every class, that information is referenced by every object instance, and that is what gets inspected at runtime to determine if a dynamic cast is legal. You could create a standard base class with this information and operators to do the runtime inspection on that base class, then any derived class would inform the base class of its place in the class hierarchy and any instances of those classes would be runtime-castable via your operations.

edit

Here's an implementation that demonstrates one technique. I'm not claiming the compiler uses anything like this, but I think it demonstrates the concepts:

class SafeCastableBase
{
public:
    typedef long TypeID;
    static TypeID s_nextTypeID;
    static TypeID GetNextTypeID()
    {
        return s_nextTypeID++;
    }
    static TypeID GetTypeID()
    {
        return 0;
    }
    virtual bool CanCastTo(TypeID id)
    {
        if (GetTypeID() != id) { return false; }
        return true;
    }
    template <class Target>
    static Target *SafeCast(SafeCastableBase *pSource)
    {
        if (pSource->CanCastTo(Target::GetTypeID()))
        {
            return (Target*)pSource;
        }
        return NULL;
    }
};
SafeCastableBase::TypeID SafeCastableBase::s_nextTypeID = 1;

class TypeIDInitializer
{
public:
    TypeIDInitializer(SafeCastableBase::TypeID *pTypeID)
    {
        *pTypeID = SafeCastableBase::GetNextTypeID();
    }
};

class ChildCastable : public SafeCastableBase
{
public:
    static TypeID s_typeID;
    static TypeID GetTypeID()
    {
        return s_typeID;
    }
    virtual bool CanCastTo(TypeID id)
    {
        if (GetTypeID() != id) { return SafeCastableBase::CanCastTo(id); }
        return true;
    }
};
SafeCastableBase::TypeID ChildCastable::s_typeID;

TypeIDInitializer ChildCastableInitializer(&ChildCastable::s_typeID);

class PeerChildCastable : public SafeCastableBase
{
public:
    static TypeID s_typeID;
    static TypeID GetTypeID()
    {
        return s_typeID;
    }
    virtual bool CanCastTo(TypeID id)
    {
        if (GetTypeID() != id) { return SafeCastableBase::CanCastTo(id); }
        return true;
    }
};
SafeCastableBase::TypeID PeerChildCastable::s_typeID;

TypeIDInitializer PeerChildCastableInitializer(&PeerChildCastable::s_typeID);

int _tmain(int argc, _TCHAR* argv[])
{
    ChildCastable *pChild = new ChildCastable();
    SafeCastableBase *pBase = new SafeCastableBase();
    PeerChildCastable *pPeerChild = new PeerChildCastable();
    ChildCastable *pSameChild = SafeCastableBase::SafeCast<ChildCastable>(pChild);
    SafeCastableBase *pBaseToChild = SafeCastableBase::SafeCast<SafeCastableBase>(pChild);
    ChildCastable *pNullDownCast = SafeCastableBase::SafeCast<ChildCastable>(pBase);
    SafeCastableBase *pBaseToPeerChild = SafeCastableBase::SafeCast<SafeCastableBase>(pPeerChild);
    ChildCastable *pNullCrossCast = SafeCastableBase::SafeCast<ChildCastable>(pPeerChild);
    return 0;
}

java: How can I do dynamic casting of a variable from one type to another?

Don't do this. Just have a properly parameterized constructor instead. The set and types of the connection parameters are fixed anyway, so there is no point in doing this all dynamically.

MySQL user DB does not have password columns - Installing MySQL on OSX

In MySQL 5.7, the password field in mysql.user table field was removed, now the field name is 'authentication_string'.

First choose the database:

mysql>use mysql;

And then show the tables:

mysql>show tables;

You will find the user table, now let's see its fields:

mysql> describe user;
+------------------------+-----------------------------------+------+-----+-----------------------+-------+
| Field                  | Type                              | Null | Key | Default               | Extra |
+------------------------+-----------------------------------+------+-----+-----------------------+-------+
| Host                   | char(60)                          | NO   | PRI |                       |       |
| User                   | char(16)                          | NO   | PRI |                       |       |
| Select_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Insert_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Update_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Delete_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Create_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Drop_priv              | enum('N','Y')                     | NO   |     | N                     |       |
| Reload_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Shutdown_priv          | enum('N','Y')                     | NO   |     | N                     |       |
| Process_priv           | enum('N','Y')                     | NO   |     | N                     |       |
| File_priv              | enum('N','Y')                     | NO   |     | N                     |       |
| Grant_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| References_priv        | enum('N','Y')                     | NO   |     | N                     |       |
| Index_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| Alter_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| Show_db_priv           | enum('N','Y')                     | NO   |     | N                     |       |
| Super_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| Create_tmp_table_priv  | enum('N','Y')                     | NO   |     | N                     |       |
| Lock_tables_priv       | enum('N','Y')                     | NO   |     | N                     |       |
| Execute_priv           | enum('N','Y')                     | NO   |     | N                     |       |
| Repl_slave_priv        | enum('N','Y')                     | NO   |     | N                     |       |
| Repl_client_priv       | enum('N','Y')                     | NO   |     | N                     |       |
| Create_view_priv       | enum('N','Y')                     | NO   |     | N                     |       |
| Show_view_priv         | enum('N','Y')                     | NO   |     | N                     |       |
| Create_routine_priv    | enum('N','Y')                     | NO   |     | N                     |       |
| Alter_routine_priv     | enum('N','Y')                     | NO   |     | N                     |       |
| Create_user_priv       | enum('N','Y')                     | NO   |     | N                     |       |
| Event_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| Trigger_priv           | enum('N','Y')                     | NO   |     | N                     |       |
| Create_tablespace_priv | enum('N','Y')                     | NO   |     | N                     |       |
| ssl_type               | enum('','ANY','X509','SPECIFIED') | NO   |     |                       |       |
| ssl_cipher             | blob                              | NO   |     | NULL                  |       |
| x509_issuer            | blob                              | NO   |     | NULL                  |       |
| x509_subject           | blob                              | NO   |     | NULL                  |       |
| max_questions          | int(11) unsigned                  | NO   |     | 0                     |       |
| max_updates            | int(11) unsigned                  | NO   |     | 0                     |       |
| max_connections        | int(11) unsigned                  | NO   |     | 0                     |       |
| max_user_connections   | int(11) unsigned                  | NO   |     | 0                     |       |
| plugin                 | char(64)                          | NO   |     | mysql_native_password |       |
| authentication_string  | text                              | YES  |     | NULL                  |       |
| password_expired       | enum('N','Y')                     | NO   |     | N                     |       |
| password_last_changed  | timestamp                         | YES  |     | NULL                  |       |
| password_lifetime      | smallint(5) unsigned              | YES  |     | NULL                  |       |
| account_locked         | enum('N','Y')                     | NO   |     | N                     |       |
+------------------------+-----------------------------------+------+-----+-----------------------+-------+
45 rows in set (0.00 sec)

Surprise!There is no field named 'password', the password field is named ' authentication_string'. So, just do this:

update user set authentication_string=password('1111') where user='root';

Now, everything will be ok.

Compared to MySQL 5.6, the changes are quite extensive: What’s New in MySQL 5.7

transform object to array with lodash

2017 update: Object.values, lodash values and toArray do it. And to preserve keys map and spread operator play nice:

_x000D_
_x000D_
// import { toArray, map } from 'lodash'_x000D_
const map = _.map_x000D_
_x000D_
const input = {_x000D_
  key: {_x000D_
    value: 'value'_x000D_
  }_x000D_
}_x000D_
_x000D_
const output = map(input, (value, key) => ({_x000D_
  key,_x000D_
  ...value_x000D_
}))_x000D_
_x000D_
console.log(output)_x000D_
// >> [{key: 'key', value: 'value'}])
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
_x000D_
_x000D_
_x000D_

jquery append div inside div with id and manipulate

var e = $('<div style="display:block; id="myid" float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
$("#box").html(e);

PHP - Copy image to my server direct from URL

$url="http://www.google.co.in/intl/en_com/images/srpr/logo1w.png";
$contents=file_get_contents($url);
$save_path="/path/to/the/dir/and/image.jpg";
file_put_contents($save_path,$contents);

you must have allow_url_fopen set to on

Is it possible to get a history of queries made in postgres

If The question is the see the history of queries executed in the Command line. Answer is

As per Postgresql 9.3, Try \? in your command line, you will find all possible commands, in that search for history,

  \s [FILE]              display history or save it to file

in your command line, try \s. This will list the history of queries, you have executed in the current session. you can also save to the file, as shown below.

hms=# \s /tmp/save_queries.sql
Wrote history to file ".//tmp/save_queries.sql".
hms=# 

Set a thin border using .css() in javascript

Maybe just "border-width" instead of "border-weight"? There is no "border-weight" and this property is just ignored and default width is used instead.

Count the number of occurrences of a string in a VARCHAR field?

SELECT 
id,
jsondata,    
ROUND (   
    (
        LENGTH(jsondata)
        - LENGTH( REPLACE ( jsondata, "sonal", "") ) 
    ) / LENGTH("sonal")        
)
+
ROUND (   
    (
        LENGTH(jsondata)
        - LENGTH( REPLACE ( jsondata, "khunt", "") ) 
    ) / LENGTH("khunt")        
)
AS count1    FROM test ORDER BY count1 DESC LIMIT 0, 2

Thanks Yannis, your solution worked for me and here I'm sharing same solution for multiple keywords with order and limit.

CSS: how to position element in lower right?

Lets say your HTML looks something like this:

<div class="box">
    <!-- stuff -->
    <p class="bet_time">Bet 5 days ago</p>
</div>

Then, with CSS, you can make that text appear in the bottom right like so:

.box {
    position:relative;
}
.bet_time {
    position:absolute;
    bottom:0;
    right:0;
}

The way this works is that absolutely positioned elements are always positioned with respect to the first relatively positioned parent element, or the window. Because we set the box's position to relative, .bet_time positions its right edge to the right edge of .box and its bottom edge to the bottom edge of .box

When should we use mutex and when should we use semaphore

It is very important to understand that a mutex is not a semaphore with count 1!

This is the reason there are things like binary semaphores (which are really semaphores with count 1).

The difference between a Mutex and a Binary-Semaphore is the principle of ownership:

A mutex is acquired by a task and therefore must also be released by the same task. This makes it possible to fix several problems with binary semaphores (Accidential release, recursive deadlock and priority inversion).

Caveat: I wrote "makes it possible", if and how these problems are fixed is up to the OS implementation.

Because the mutex is has to be released by the same task it is not very good for synchronization of tasks. But if combined with condition variables you get very powerful building blocks for building all kinds of ipc primitives.

So my recommendation is: if you got cleanly implemented mutexes and condition variables (like with POSIX pthreads) use these.

Use semaphores only if they fit exactly to the problem you are trying to solve, don't try to build other primitives (e.g. rw-locks out of semaphores, use mutexes and condition variables for these)

There is a lot of misunderstanding mutexes and semaphores. The best explanation I found so far is in this 3-Part article:

Mutex vs. Semaphores – Part 1: Semaphores

Mutex vs. Semaphores – Part 2: The Mutex

Mutex vs. Semaphores – Part 3 (final part): Mutual Exclusion Problems

How to do a join in linq to sql with method syntax?

To add on to the other answers here, if you would like to create a new object of a third different type with a where clause (e.g. one that is not your Entity Framework object) you can do this:

public IEnumerable<ThirdNonEntityClass> demoMethod(IEnumerable<int> property1Values)
{
    using(var entityFrameworkObjectContext = new EntityFrameworkObjectContext )
    {
        var result = entityFrameworkObjectContext.SomeClass
            .Join(entityFrameworkObjectContext.SomeOtherClass,
                sc => sc.property1,
                soc => soc.property2,
                (sc, soc) => new {sc, soc})
            .Where(s => propertyValues.Any(pvals => pvals == es.sc.property1)
            .Select(s => new ThirdNonEntityClass 
            {
                dataValue1 = s.sc.dataValueA,
                dataValue2 = s.soc.dataValueB
            })
            .ToList();
    }

    return result;

}    

Pay special attention to the intermediate object that is created in the Where and Select clauses.

Note that here we also look for any joined objects that have a property1 that matches one of the ones in the input list.

I know this is a bit more complex than what the original asker was looking for, but hopefully it will help someone.

insert data into database using servlet and jsp in eclipse

Same problem fetch main problem in PreparedStatement use simple statement then you successfully insert record same use below.

String  st2="insert into 
user(gender,name,address,telephone,fax,email,
     destination,sdate,edate,Participant,hcategory,
     Culture,Nature,People,Cities,Beaches,Festivals,username,password) 
values('"+gender+"','"+name+"','"+address+"','"+phone+"','"+fax+"',
       '"+email+"','"+desti+"','"+sdate+"','"+edate+"','"+parti+"',
       '"+hotel+"','"+chk1+"','"+chk2+"','"+chk3+"','"+chk4+"',
       '"+chk5+"','"+chk6+"','"+user+"','"+password+"')";


int i=stm.executeUpdate(st2);

How to get a value from a cell of a dataframe?

df_gdp.columns

Index([u'Country', u'Country Code', u'Indicator Name', u'Indicator Code', u'1960', u'1961', u'1962', u'1963', u'1964', u'1965', u'1966', u'1967', u'1968', u'1969', u'1970', u'1971', u'1972', u'1973', u'1974', u'1975', u'1976', u'1977', u'1978', u'1979', u'1980', u'1981', u'1982', u'1983', u'1984', u'1985', u'1986', u'1987', u'1988', u'1989', u'1990', u'1991', u'1992', u'1993', u'1994', u'1995', u'1996', u'1997', u'1998', u'1999', u'2000', u'2001', u'2002', u'2003', u'2004', u'2005', u'2006', u'2007', u'2008', u'2009', u'2010', u'2011', u'2012', u'2013', u'2014', u'2015', u'2016'], dtype='object')

df_gdp[df_gdp["Country Code"] == "USA"]["1996"].values[0]

8100000000000.0

Gradle version 2.2 is required. Current version is 2.10

Based on https://developer.android.com/studio/releases/gradle-plugin.html ...

The following table lists which version of Gradle is required for each version of the Android plugin for Gradle. For the best performance, you should use the latest possible version of both Gradle and the Android plugin.

So, the Plugin version with Required Gradle version should be match.

enter image description here

How to sort a Pandas DataFrame by index?

Dataframes have a sort_index method which returns a copy by default. Pass inplace=True to operate in place.

import pandas as pd
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df.sort_index(inplace=True)
print(df.to_string())

Gives me:

     A
1    4
29   2
100  1
150  5
234  3

How to get the directory of the currently running file?

Gustavo Niemeyer's answer is great. But in Windows, runtime proc is mostly in another dir, like this:

"C:\Users\XXX\AppData\Local\Temp"

If you use relative file path, like "/config/api.yaml", this will use your project path where your code exists.

How to set the UITableView Section title programmatically (iPhone/iPad)?

titleForHeaderInSection is a delegate method of UITableView so to apply header text of section write as follows,

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
              return @"Hello World";
}

Split string by single spaces

You can even develop your own split function (I know, little old-fashioned):

size_t split(const std::string &txt, std::vector<std::string> &strs, char ch)
{
    size_t pos = txt.find( ch );
    size_t initialPos = 0;
    strs.clear();

    // Decompose statement
    while( pos != std::string::npos ) {
        strs.push_back( txt.substr( initialPos, pos - initialPos ) );
        initialPos = pos + 1;

        pos = txt.find( ch, initialPos );
    }

    // Add the last one
    strs.push_back( txt.substr( initialPos, std::min( pos, txt.size() ) - initialPos + 1 ) );

    return strs.size();
}

Then you just need to invoke it with a vector<string> as argument:

int main()
{
    std::vector<std::string> v;

    split( "This  is a  test", v, ' ' );
    dump( cout, v );

    return 0;
}

Find the code for splitting a string in IDEone.

Hope this helps.

JSON post to Spring Controller

see here

The consumable media types of the mapped request, narrowing the primary mapping.

the producer is used to narrow the primary mapping, you send request should specify the exact header to match it.

Does Django scale?

Here's a list of some relatively high-profile things built in Django:

  1. The Guardian's "Investigate your MP's expenses" app

  2. Politifact.com (here's a Blog post talking about the (positive) experience. Site won a Pulitzer.

  3. NY Times' Represent app

  4. EveryBlock

  5. Peter Harkins, one of the programmers over at WaPo, lists all the stuff they’ve built with Django on his blog

  6. It's a little old, but someone from the LA Times gave a basic overview of why they went with Django.

  7. The Onion's AV Club was recently moved from (I think Drupal) to Django.

I imagine a number of these these sites probably gets well over 100k+ hits per day. Django can certainly do 100k hits/day and more. But YMMV in getting your particular site there depending on what you're building.

There are caching options at the Django level (for example caching querysets and views in memcached can work wonders) and beyond (upstream caches like Squid). Database Server specifications will also be a factor (and usually the place to splurge), as is how well you've tuned it. Don't assume, for example, that Django's going set up indexes properly. Don't assume that the default PostgreSQL or MySQL configuration is the right one.

Furthermore, you always have the option of having multiple application servers running Django if that is the slow point, with a software or hardware load balancer in front.

Finally, are you serving static content on the same server as Django? Are you using Apache or something like nginx or lighttpd? Can you afford to use a CDN for static content? These are things to think about, but it's all very speculative. 100k hits/day isn't the only variable: how much do you want to spend? How much expertise do you have managing all these components? How much time do you have to pull it all together?

how to bind img src in angular 2 in ngFor?

I hope i am understanding your question correctly, as the above comment says you need to provide more information.

In order to bind it to your view you would use property binding which is using [property]="value". Hope this helps.

<div *ngFor="let student of students">  
 {{student.id}}
 {{student.name}}

 <img [src]="student.image">

</div>  

Operation is not valid due to the current state of the object, when I select a dropdown list

I know an answer has already been accepted for this problem but someone asked in the comments if there was a solution that could be done outside the web.config. I had a ListView producing the exact same error and setting EnableViewState to false resolved this problem for me.

Reportviewer tool missing in visual studio 2017 RC

Download Microsoft Rdlc Report Designer for Visual Studio from this link. https://marketplace.visualstudio.com/items?itemName=ProBITools.MicrosoftRdlcReportDesignerforVisualStudio-18001

Microsoft explain the steps in details:

https://docs.microsoft.com/en-us/sql/reporting-services/application-integration/integrating-reporting-services-using-reportviewer-controls-get-started?view=sql-server-2017

The following steps summarizes the above article.

Adding the Report Viewer control to a new web project:

  1. Create a new ASP.NET Empty Web Site or open an existing ASP.NET project.

  2. Install the Report Viewer control NuGet package via the NuGet package manager console. From Visual Studio -> Tools -> NuGet Package Manager -> Package Manager Console

    Install-Package Microsoft.ReportingServices.ReportViewerControl.WebForms
    
  3. Add a new .aspx page to the project and register the Report Viewer control assembly for use within the page.

    <%@ Register assembly="Microsoft.ReportViewer.WebForms, Version=15.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" namespace="Microsoft.Reporting.WebForms" tagprefix="rsweb" %>
    
  4. Add a ScriptManagerControl to the page.

  5. Add the Report Viewer control to the page. The snippet below can be updated to reference a report hosted on a remote report server.

     <rsweb:ReportViewer ID="ReportViewer1" runat="server" ProcessingMode="Remote">
     <ServerReport ReportPath="" ReportServerUrl="" /></rsweb:ReportViewer>
    

The final page should look like the following.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Sample" %>

<%@ Register assembly="Microsoft.ReportViewer.WebForms, Version=15.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" namespace="Microsoft.Reporting.WebForms" tagprefix="rsweb" %>

<!DOCTYPE html>

<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="X-UA-Compatible" content="IE=edge" /> 
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager runat="server"></asp:ScriptManager>        
       <rsweb:ReportViewer ID="ReportViewer1" runat="server" ProcessingMode="Remote">
           <ServerReport ReportServerUrl="https://AContosoDepartment/ReportServer" ReportPath="/LatestSales" />
    </rsweb:ReportViewer>
    </form>
</body>

PHP add elements to multidimensional array with array_push

if you want to add the data in the increment order inside your associative array you can do this:

$newdata =  array (
      'wpseo_title' => 'test',
      'wpseo_desc' => 'test',
      'wpseo_metakey' => 'test'
    );

// for recipe

$md_array["recipe_type"][] = $newdata;

//for cuisine

 $md_array["cuisine"][] = $newdata;

this will get added to the recipe or cuisine depending on what was the last index.

Array push is usually used in the array when you have sequential index: $arr[0] , $ar[1].. you cannot use it in associative array directly. But since your sub array is had this kind of index you can still use it like this

array_push($md_array["cuisine"],$newdata);

html 5 audio tag width

You also can set the width of a audio tag by JavaScript:

audio = document.getElementById('audio-id');
audio.style.width = '200px';

Find a row in dataGridView based on column and value

The above answers only work if AllowUserToAddRows is set to false. If that property is set to true, then you will get a NullReferenceException when the loop or Linq query tries to negotiate the new row. I've modified the two accepted answers above to handle AllowUserToAddRows = true.

Loop answer:

String searchValue = "somestring";
int rowIndex = -1;
foreach(DataGridViewRow row in DataGridView1.Rows)
{
    if (row.Cells["SystemId"].Value != null) // Need to check for null if new row is exposed
    {
        if(row.Cells["SystemId"].Value.ToString().Equals(searchValue))
        {
            rowIndex = row.Index;
            break;
        }
    }
}

LINQ answer:

int rowIndex = -1;

bool tempAllowUserToAddRows = dgv.AllowUserToAddRows;

dgv.AllowUserToAddRows = false; // Turn off or .Value below will throw null exception

    DataGridViewRow row = dgv.Rows
        .Cast<DataGridViewRow>()
        .Where(r => r.Cells["SystemId"].Value.ToString().Equals(searchValue))
        .First();

    rowIndex = row.Index;

dgv.AllowUserToAddRows = tempAllowUserToAddRows;

How to play a notification sound on websites?

As of 2016, the following will suffice (you don't even need to embed):

let src = 'https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_700KB.mp3';
let audio = new Audio(src);
audio.play();

See more here.

How to 'foreach' a column in a DataTable using C#?

You can check this out. Use foreach loop over a DataColumn provided with your DataTable.

 foreach(DataColumn column in dtTable.Columns)
 {
     // do here whatever you want to...
 }

New line in JavaScript alert box

As of ECMAScript 2015 you can use back-ticks (` `) to enclose Template Literals for multi-line strings like this:

_x000D_
_x000D_
alert(`Line1_x000D_
Line2`);
_x000D_
_x000D_
_x000D_

Outputs:

Line1
Line2

Google Chrome: This setting is enforced by your administrator

Any one on windows 10 Pro , this is for you guys --

  1. Open CMD in administrator mode .
  2. Paste below code-

    RD /S /Q "%WinDir%\System32\GroupPolicyUsers" 
    RD /S /Q "%WinDir%\System32\GroupPolicy" 
    gpupdate /force
    
  3. After few seconds you will see this -

    User Policy update has completed successfully.
    Computer Policy update has completed successfully.
    
  4. Now you can change your search engine to whatever you want.

Thank you

How to select records without duplicate on just one field in SQL?

select Country_id,country_title from(
   select Country_id,country_title,row_number() over (partition by country_title 
   order by Country_id  ) rn from country)a
   where rn=1;

Ruby objects and JSON serialization (without Rails)

require 'json'
{"foo" => "bar"}.to_json
# => "{\"foo\":\"bar\"}"

Display UIViewController as Popup in iPhone

You can do this in Interface Builder.

  • For the view you wish to present modally set its outermost view background to transparent
  • Control + click and drag from the host view controller to the modal view controller
  • Select present modally
  • Click on the newly created segue and in the Attribute Inspector (on the right) set "Presentation" to "Over Current Context"

"Least Astonishment" and the Mutable Default Argument

This "bug" gave me a lot of overtime work hours! But I'm beginning to see a potential use of it (but I would have liked it to be at the execution time, still)

I'm gonna give you what I see as a useful example.

def example(errors=[]):
    # statements
    # Something went wrong
    mistake = True
    if mistake:
        tryToFixIt(errors)
        # Didn't work.. let's try again
        tryToFixItAnotherway(errors)
        # This time it worked
    return errors

def tryToFixIt(err):
    err.append('Attempt to fix it')

def tryToFixItAnotherway(err):
    err.append('Attempt to fix it by another way')

def main():
    for item in range(2):
        errors = example()
    print '\n'.join(errors)

main()

prints the following

Attempt to fix it
Attempt to fix it by another way
Attempt to fix it
Attempt to fix it by another way

What are the undocumented features and limitations of the Windows FINDSTR command?

findstr sometimes hangs unexpectedly when searching large files.

I haven't confirmed the exact conditions or boundary sizes. I suspect any file larger 2GB may be at risk.

I have had mixed experiences with this, so it is more than just file size. This looks like it may be a variation on FINDSTR hangs on XP and Windows 7 if redirected input does not end with LF, but as demonstrated this particular problem manifests when input is not redirected.

The following command line session (Windows 7) demonstrates how findstr can hang when searching a 3GB file.

C:\Data\Temp\2014-04>echo 1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890> T100B.txt

C:\Data\Temp\2014-04>for /L %i in (1,1,10) do @type T100B.txt >> T1KB.txt

C:\Data\Temp\2014-04>for /L %i in (1,1,1000) do @type T1KB.txt >> T1MB.txt

C:\Data\Temp\2014-04>for /L %i in (1,1,1000) do @type T1MB.txt >> T1GB.txt

C:\Data\Temp\2014-04>echo find this line>> T1GB.txt

C:\Data\Temp\2014-04>copy T1GB.txt + T1GB.txt + T1GB.txt T3GB.txt
T1GB.txt
T1GB.txt
T1GB.txt
        1 file(s) copied.

C:\Data\Temp\2014-04>dir
 Volume in drive C has no label.
 Volume Serial Number is D2B2-FFDF

 Directory of C:\Data\Temp\2014-04

2014/04/08  04:28 PM    <DIR>          .
2014/04/08  04:28 PM    <DIR>          ..
2014/04/08  04:22 PM               102 T100B.txt
2014/04/08  04:28 PM     1 020 000 016 T1GB.txt
2014/04/08  04:23 PM             1 020 T1KB.txt
2014/04/08  04:23 PM         1 020 000 T1MB.txt
2014/04/08  04:29 PM     3 060 000 049 T3GB.txt
               5 File(s)  4 081 021 187 bytes
               2 Dir(s)  51 881 050 112 bytes free
C:\Data\Temp\2014-04>rem Findstr on the 1GB file does not hang

C:\Data\Temp\2014-04>findstr "this" T1GB.txt
find this line

C:\Data\Temp\2014-04>rem On the 3GB file, findstr hangs and must be aborted... even though it clearly reaches end of file

C:\Data\Temp\2014-04>findstr "this" T3GB.txt
find this line
find this line
find this line
^C
C:\Data\Temp\2014-04>

Note, I've verified in a hex editor that all lines are terminated with CRLF. The only anomaly is that the file is terminated with 0x1A due to the way copy works. Note however, that this anomaly doesn't cause a problem on "small" files.

With additional testing I have confirmed the following:

  • Using copy with the /b option for binary files prevents the addition of the 0x1A character, and findstr doesn't hang on the 3GB file.
  • Terminating the 3GB file with a different character also causes a findstr to hang.
  • The 0x1A character doesn't cause any problems on a "small" file. (Similarly for other terminating characters.)
  • Adding CRLF after 0x1A resolves the problem. (LF by itself would probably suffice.)
  • Using type to pipe the file into findstr works without hanging. (This might be due to a side effect of either type or | that inserts an additional End Of Line.)
  • Use redirected input < also causes findstr to hang. But this is expected; as explained in dbenham's post: "redirected input must end in LF".

What is the purpose of the "final" keyword in C++11 for functions?

Final cannot be applied to non-virtual functions.

error: only virtual member functions can be marked 'final'

It wouldn't be very meaningful to be able to mark a non-virtual method as 'final'. Given

struct A { void foo(); };
struct B : public A { void foo(); };
A * a = new B;
a -> foo(); // this will call A :: foo anyway, regardless of whether there is a B::foo

a->foo() will always call A::foo.

But, if A::foo was virtual, then B::foo would override it. This might be undesirable, and hence it would make sense to make the virtual function final.

The question is though, why allow final on virtual functions. If you have a deep hierarchy:

struct A            { virtual void foo(); };
struct B : public A { virtual void foo(); };
struct C : public B { virtual void foo() final; };
struct D : public C { /* cannot override foo */ };

Then the final puts a 'floor' on how much overriding can be done. Other classes can extend A and B and override their foo, but it a class extends C then it is not allowed.

So it probably doesn't make sense to make the 'top-level' foo final, but it might make sense lower down.

(I think though, there is room to extend the words final and override to non-virtual members. They would have a different meaning though.)

How to send list of file in a folder to a txt file in Linux

you can just use

ls > filenames.txt

(usually, start a shell by using "Terminal", or "shell", or "Bash".) You may need to use cd to go to that folder first, or you can ls ~/docs > filenames.txt

Unfortunately MyApp has stopped. How can I solve this?

Also running this command in terminal can help find the problem:

gradlew build > log.txt 2>details.txt

then you should go to gradlew file location in read two above log files.

OpenCV Error: (-215)size.width>0 && size.height>0 in function imshow

This Error can also occur if you slice a negative point and pass it to the array. So check if you did

SQL: How to get the count of each distinct value in a column?

SELECT
  category,
  COUNT(*) AS `num`
FROM
  posts
GROUP BY
  category

How to write to the Output window in Visual Studio?

Useful tip - if you use __FILE__ and __LINE__ then format your debug as:

"file(line): Your output here"

then when you click on that line in the output window Visual Studio will jump directly to that line of code. An example:

#include <Windows.h>
#include <iostream>
#include <sstream>

void DBOut(const char *file, const int line, const WCHAR *s)
{
    std::wostringstream os_;
    os_ << file << "(" << line << "): ";
    os_ << s;
    OutputDebugStringW(os_.str().c_str());
}

#define DBOUT(s)       DBOut(__FILE__, __LINE__, s)

I wrote a blog post about this so I always knew where I could look it up: https://windowscecleaner.blogspot.co.nz/2013/04/debug-output-tricks-for-visual-studio.html

How to print the data in byte array as characters?

How about Arrays.toString(byteArray)?

Here's some compilable code:

byte[] byteArray = new byte[] { -1, -128, 1, 127 };
System.out.println(Arrays.toString(byteArray));

Output:

[-1, -128, 1, 127]

Why re-invent the wheel...

How to convert string to datetime format in pandas python?

Use to_datetime, there is no need for a format string the parser is man/woman enough to handle it:

In [51]:
pd.to_datetime(df['I_DATE'])

Out[51]:
0   2012-03-28 14:15:00
1   2012-03-28 14:17:28
2   2012-03-28 14:50:50
Name: I_DATE, dtype: datetime64[ns]

To access the date/day/time component use the dt accessor:

In [54]:
df['I_DATE'].dt.date

Out[54]:
0    2012-03-28
1    2012-03-28
2    2012-03-28
dtype: object

In [56]:    
df['I_DATE'].dt.time

Out[56]:
0    14:15:00
1    14:17:28
2    14:50:50
dtype: object

You can use strings to filter as an example:

In [59]:
df = pd.DataFrame({'date':pd.date_range(start = dt.datetime(2015,1,1), end = dt.datetime.now())})
df[(df['date'] > '2015-02-04') & (df['date'] < '2015-02-10')]

Out[59]:
         date
35 2015-02-05
36 2015-02-06
37 2015-02-07
38 2015-02-08
39 2015-02-09

How to set shape's opacity?

In general you just have to define a slightly transparent color when creating the shape.

You can achieve that by setting the colors alpha channel.

#FF000000 will get you a solid black whereas #00000000 will get you a 100% transparent black (well it isn't black anymore obviously).

The color scheme is like this #AARRGGBB there A stands for alpha channel, R stands for red, G for green and B for blue.

The same thing applies if you set the color in Java. There it will only look like 0xFF000000.

UPDATE

In your case you'd have to add a solid node. Like below.

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/shape_my">
    <stroke android:width="4dp" android:color="#636161" />
    <padding android:left="20dp"
        android:top="20dp"
        android:right="20dp"
        android:bottom="20dp" />
    <corners android:radius="24dp" />
    <solid android:color="#88000000" />
</shape>

The color here is a half transparent black.

git pull error :error: remote ref is at but expected

I know this is old, but I have my own fix. Because I'm using source tree, this error happens because someone create a new branch. The source tree is confused about this. After I press "Refresh" button beside the "remote branch to pull" combobox, it seems that sourcetree has updated the branch list, and now I can pull successfully.

Do I need Content-Type: application/octet-stream for file download?

No.

The content-type should be whatever it is known to be, if you know it. application/octet-stream is defined as "arbitrary binary data" in RFC 2046, and there's a definite overlap here of it being appropriate for entities whose sole intended purpose is to be saved to disk, and from that point on be outside of anything "webby". Or to look at it from another direction; the only thing one can safely do with application/octet-stream is to save it to file and hope someone else knows what it's for.

You can combine the use of Content-Disposition with other content-types, such as image/png or even text/html to indicate you want saving rather than display. It used to be the case that some browsers would ignore it in the case of text/html but I think this was some long time ago at this point (and I'm going to bed soon so I'm not going to start testing a whole bunch of browsers right now; maybe later).

RFC 2616 also mentions the possibility of extension tokens, and these days most browsers recognise inline to mean you do want the entity displayed if possible (that is, if it's a type the browser knows how to display, otherwise it's got no choice in the matter). This is of course the default behaviour anyway, but it means that you can include the filename part of the header, which browsers will use (perhaps with some adjustment so file-extensions match local system norms for the content-type in question, perhaps not) as the suggestion if the user tries to save.

Hence:

Content-Type: application/octet-stream
Content-Disposition: attachment; filename="picture.png"

Means "I don't know what the hell this is. Please save it as a file, preferably named picture.png".

Content-Type: image/png
Content-Disposition: attachment; filename="picture.png"

Means "This is a PNG image. Please save it as a file, preferably named picture.png".

Content-Type: image/png
Content-Disposition: inline; filename="picture.png"

Means "This is a PNG image. Please display it unless you don't know how to display PNG images. Otherwise, or if the user chooses to save it, we recommend the name picture.png for the file you save it as".

Of those browsers that recognise inline some would always use it, while others would use it if the user had selected "save link as" but not if they'd selected "save" while viewing (or at least IE used to be like that, it may have changed some years ago).

how to open a url in python

import webbrowser  
webbrowser.open(url, new=0, autoraise=True)

Display url using the default browser. If new is 0, the url is opened in the same browser window if possible. If new is 1, a new browser window is opened if possible. If new is 2, a new browser page (“tab”) is opened if possible. If autoraise is True, the window is raised

webbrowser.open_new(url)

Open url in a new window of the default browser

webbrowser.open_new_tab(url)

Open url in a new page (“tab”) of the default browser

Add space between HTML elements only using CSS

Or, instead of setting margin and than overriding it, you can just set it properly right away with the following combo:

span:not(:first-of-type) {
    margin-left:  5px;
}

span:not(:last-of-type) {
    margin-right: 5px;
}

Reading data from XML

Alternatively, you can use XPathNavigator:

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XPathNavigator navigator = doc.CreateNavigator();

string books = GetStringValues("Books: ", navigator, "//Book/Title");
string authors = GetStringValues("Authors: ", navigator, "//Book/Author");

..

/// <summary>
/// Gets the string values.
/// </summary>
/// <param name="description">The description.</param>
/// <param name="navigator">The navigator.</param>
/// <param name="xpath">The xpath.</param>
/// <returns></returns>
private static string GetStringValues(string description,
                                      XPathNavigator navigator, string xpath) {
    StringBuilder sb = new StringBuilder();
    sb.Append(description);
    XPathNodeIterator bookNodesIterator = navigator.Select(xpath);
    while (bookNodesIterator.MoveNext())
       sb.Append(string.Format("{0} ", bookNodesIterator.Current.Value));
    return sb.ToString();
}

Load a WPF BitmapImage from a System.Drawing.Bitmap

The easiest thing is if you can make the WPF bitmap from a file directly.

Otherwise you will have to use System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap.

event.preventDefault() vs. return false

This is not, as you've titled it, a "JavaScript" question; it is a question regarding the design of jQuery.

jQuery and the previously linked citation from John Resig (in karim79's message) seem to be the source misunderstanding of how event handlers in general work.

Fact: An event handler that returns false prevents the default action for that event. It does not stop the event propagation. Event handlers have always worked this way, since the old days of Netscape Navigator.

The documentation from MDN explains how return false in an event handler works

What happens in jQuery is not the same as what happens with event handlers. DOM event listeners and MSIE "attached" events are a different matter altogether.

For further reading, see attachEvent on MSDN and the W3C DOM 2 Events documentation.

How do you make an element "flash" in jQuery

How about a really simple answer?

$('selector').fadeTo('fast',0).fadeTo('fast',1).fadeTo('fast',0).fadeTo('fast',1)

Blinks twice...that's all folks!

Sorting Values of Set

If you sort the strings "12", "15" and "5" then "5" comes last because "5" > "1". i.e. the natural ordering of Strings doesn't work the way you expect.

If you want to store strings in your list but sort them numerically then you will need to use a comparator that handles this. e.g.

Collections.sort(list, new Comparator<String>() {
    public int compare(String o1, String o2) {
        Integer i1 = Integer.parseInt(o1);
        Integer i2 = Integer.parseInt(o2);
        return (i1 > i2 ? -1 : (i1 == i2 ? 0 : 1));
    }
});

Also, I think you are getting slightly mixed up between Collection types. A HashSet and a HashMap are different things.

If Browser is Internet Explorer: run an alternative script instead

Note that you can also determine in pure js in what browser you script is beeing executed through : window.navigator.userAgent

However, that's not a recommended way as it's configurable in the browser settings. More info available there: https://developer.mozilla.org/fr/docs/DOM/window.navigator.userAgent

Failed to start mongod.service: Unit mongod.service not found

It worked for me on ubuntu 20.04: In my case, mongod.service file was locked so it was giving me the same error. To resolve the issue:- Step 1: Use following command to check if the mongod.service is present there

cd /usr/bin/systemd/system
ls

Step 2: If the file is present there then Run the following command to unlock the file mongod.service

sudo chmod 777 /usr/bin/systemd/system/mongod.service -R

Step 3: Now run the following commands:

sudo systemctl daemon-reload
sudo systemctl start mongod
sudo systemctl enable mongod

How do I create a HTTP Client Request with a cookie?

This answer is deprecated, please see @ankitjaininfo's answer below for a more modern solution


Here's how I think you make a POST request with data and a cookie using just the node http library. This example is posting JSON, set your content-type and content-length accordingly if you post different data.

// NB:- node's http client API has changed since this was written
// this code is for 0.4.x
// for 0.6.5+ see http://nodejs.org/docs/v0.6.5/api/http.html#http.request

var http = require('http');

var data = JSON.stringify({ 'important': 'data' });
var cookie = 'something=anything'

var client = http.createClient(80, 'www.example.com');

var headers = {
    'Host': 'www.example.com',
    'Cookie': cookie,
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(data,'utf8')
};

var request = client.request('POST', '/', headers);

// listening to the response is optional, I suppose
request.on('response', function(response) {
  response.on('data', function(chunk) {
    // do what you do
  });
  response.on('end', function() {
    // do what you do
  });
});
// you'd also want to listen for errors in production

request.write(data);

request.end();

What you send in the Cookie value should really depend on what you received from the server. Wikipedia's write-up of this stuff is pretty good: http://en.wikipedia.org/wiki/HTTP_cookie#Cookie_attributes

How to check whether a pandas DataFrame is empty?

1) If a DataFrame has got Nan and Non Null values and you want to find whether the DataFrame
is empty or not then try this code.
2) when this situation can happen? 
This situation happens when a single function is used to plot more than one DataFrame 
which are passed as parameter.In such a situation the function try to plot the data even 
when a DataFrame is empty and thus plot an empty figure!.
It will make sense if simply display 'DataFrame has no data' message.
3) why? 
if a DataFrame is empty(i.e. contain no data at all.Mind you DataFrame with Nan values 
is considered non empty) then it is desirable not to plot but put out a message :
Suppose we have two DataFrames df1 and df2.
The function myfunc takes any DataFrame(df1 and df2 in this case) and print a message 
if a DataFrame is empty(instead of plotting):
df1                     df2
col1 col2           col1 col2 
Nan   2              Nan  Nan 
2     Nan            Nan  Nan  

and the function:

def myfunc(df):
  if (df.count().sum())>0: ##count the total number of non Nan values.Equal to 0 if DataFrame is empty
     print('not empty')
     df.plot(kind='barh')
  else:
     display a message instead of plotting if it is empty
     print('empty')

When to favor ng-if vs. ng-show/ng-hide?

See here for a CodePen that demonstrates the difference in how ng-if/ng-show work, DOM-wise.

@markovuksanovic has answered the question well. But I'd come at it from another perspective: I'd always use ng-if and get those elements out of DOM, unless:

  1. you for some reason need the data-bindings and $watch-es on your elements to remain active while they're invisible. Forms might be a good case for this, if you want to be able to check validity on inputs that aren't currently visible, in order to determine whether the whole form is valid.
  2. You're using some really elaborate stateful logic with conditional event handlers, as mentioned above. That said, if you find yourself manually attaching and detaching handlers, such that you're losing important state when you use ng-if, ask yourself whether that state would be better represented in a data model, and the handlers applied conditionally by directives whenever the element is rendered. Put another way, the presence/absence of handlers is a form of state data. Get that data out of the DOM, and into a model. The presence/absence of the handlers should be determined by the data, and thus easy to recreate.

Angular is written really well. It's fast, considering what it does. But what it does is a whole bunch of magic that makes hard things (like 2-way data-binding) look trivially easy. Making all those things look easy entails some performance overhead. You might be shocked to realize how many hundreds or thousands of times a setter function gets evaluated during the $digest cycle on a hunk of DOM that nobody's even looking at. And then you realize you've got dozens or hundreds of invisible elements all doing the same thing...

Desktops may indeed be powerful enough to render most JS execution-speed issues moot. But if you're developing for mobile, using ng-if whenever humanly possible should be a no-brainer. JS speed still matters on mobile processors. Using ng-if is a very easy way to get potentially-significant optimization at very, very low cost.

good example of Javadoc

If you install a JDK and choose to install sources too, the src.zip contains the source of ALL the public Java classes. Most of these have pretty good javadoc.

What is "pom" packaging in maven?

POM(Project Object Model) is nothing but the automation script for building the project,we can write the automation script in XML, the building script files are named diffrenetly in different Automation tools

like we call build.xml in ANT,pom.xml in MAVEN

MAVEN can packages jars,wars, ears and POM which new thing to all of us

if you want check WHAT IS POM.XML

Android: alternate layout xml for landscape mode

The layouts in /res/layout are applied to both portrait and landscape, unless you specify otherwise. Let’s assume we have /res/layout/home.xml for our homepage and we want it to look differently in the 2 layout types.

  1. create folder /res/layout-land (here you will keep your landscape adjusted layouts)
  2. copy home.xml there
  3. make necessary changes to it

Source

command/usr/bin/codesign failed with exit code 1- code sign error

I had the same error on January 2018 with xcode 8.2.1

Before I try to open xcode I couldn't because the system was updating. I tried sometime later and it let me working on it, and then I got the same error.

I followed most of the solutions described in this article but they didn't work for me.

Then I remembered the message about the system updating and I tried to reboot the machine.

And that did the magic. It worked for me.

How can you run a command in bash over and over until success?

If anyone looking to have retry limit:

max_retry=5
counter=0
until $command
do
   sleep 1
   [[ counter -eq $max_retry ]] && echo "Failed!" && exit 1
   echo "Trying again. Try #$counter"
   ((counter++))
done

Datatable date sorting dd/mm/yyyy issue

use this snippet!

$(document).ready(function() {
 $.fn.dataTable.moment = function ( format, locale ) {
    var types = $.fn.dataTable.ext.type;

    // Add type detection
    types.detect.unshift( function ( d ) {
        return moment( d, format, locale, true ).isValid() ?
            'moment-'+format :
            null;
    } );

    // Add sorting method - use an integer for the sorting
    types.order[ 'moment-'+format+'-pre' ] = function ( d ) {
        return moment( d, format, locale, true ).unix();
    };
};

$.fn.dataTable.moment('DD/MM/YYYY');

$('#example').DataTable();
});

the moment js works well for all date and time formats, add this snipper before you initialize the datatable like i've done earlier.

Also remember to load the http://momentjs.com/

The transaction log for the database is full

Try this:

If possible restart the services MSSQLSERVER and SQLSERVERAGENT.

Import CSV file into SQL Server

Import the file into Excel by first opening excel, then going to DATA, import from TXT File, choose the csv extension which will preserve 0 prefixed values, and save that column as TEXT because excel will drop the leading 0 otherwise (DO NOT double click to open with Excel if you have numeric data in a field starting with a 0 [zero]). Then just save out as a Tab Delimited Text file. When you are importing into excel you get an option to save as GENERAL, TEXT, etc.. choose TEXT so that quotes in the middle of a string in a field like YourCompany,LLC are preserved also...

BULK INSERT dbo.YourTableName
FROM 'C:\Users\Steve\Downloads\yourfiletoIMPORT.txt'
WITH (
FirstRow = 2, (if skipping a header row)
FIELDTERMINATOR = '\t',
ROWTERMINATOR   = '\n'
)

I wish I could use the FORMAT and Fieldquote functionality but that does not appear to be supported in my version of SSMS

Warning: The method assertEquals from the type Assert is deprecated

When I use Junit4, import junit.framework.Assert; import junit.framework.TestCase; the warning info is :The type of Assert is deprecated

when import like this: import org.junit.Assert; import org.junit.Test; the warning has disappeared

possible duplicate of differences between 2 JUnit Assert classes

How to send email to multiple recipients using python smtplib?

This really works, I spent a lot of time trying multiple variants.

import smtplib
from email.mime.text import MIMEText

s = smtplib.SMTP('smtp.uk.xensource.com')
s.set_debuglevel(1)
msg = MIMEText("""body""")
sender = '[email protected]'
recipients = ['[email protected]', '[email protected]']
msg['Subject'] = "subject line"
msg['From'] = sender
msg['To'] = ", ".join(recipients)
s.sendmail(sender, recipients, msg.as_string())

Spring CrudRepository findByInventoryIds(List<Long> inventoryIdList) - equivalent to IN clause

For any method in a Spring CrudRepository you should be able to specify the @Query yourself. Something like this should work:

@Query( "select o from MyObject o where inventoryId in :ids" )
List<MyObject> findByInventoryIds(@Param("ids") List<Long> inventoryIdList);

How to trim a list in Python

To trim a list in place without creating copies of it, use del:

>>> t = [1, 2, 3, 4, 5]
>>> # delete elements starting from index 4 to the end
>>> del t[4:]
>>> t
[1, 2, 3, 4]
>>> # delete elements starting from index 5 to the end
>>> # but the list has only 4 elements -- no error
>>> del t[5:]
>>> t
[1, 2, 3, 4]
>>> 

How can I disable notices and warnings in PHP within the .htaccess file?

Use:

ini_set('display_errors','off');

It is working fine in WordPress' config.php.

When should I use "this" in a class?

Unless you have overlapping variable names, its really just for clarity when you're reading the code.

npm ERR! Error: EPERM: operation not permitted, rename

For me i just closed the Code editor (VS Code) and then run the same command. And that solves the issue for me.

Does it matter what extension is used for SQLite database files?

SQLite doesn't define any particular extension for this, it's your own choice. Personally, I name them with the .sqlite extension, just so there isn't any ambiguity when I'm looking at my files later.

How to disable scrolling the document body?

I know this is an ancient question, but I just thought that I'd weigh in.

I'm using disableScroll. Simple and it works like in a dream.

I have had some trouble disabling scroll on body, but allowing it on child elements (like a modal or a sidebar). It looks like that something can be done using disableScroll.on([element], [options]);, but I haven't gotten that to work just yet.


The reason that this is prefered compared to overflow: hidden; on body is that the overflow-hidden can get nasty, since some things might add overflow: hidden; like this:

... This is good for preloaders and such, since that is rendered before the CSS is finished loading.

But it gives problems, when an open navigation should add a class to the body-tag (like <body class="body__nav-open">). And then it turns into one big tug-of-war with overflow: hidden; !important and all kinds of crap.

How to get only the date value from a Windows Forms DateTimePicker control?

Datum = DateTime.Parse(DateTimePicker1.Value.ToString("dd/MM/yyyy"))

How to find integer array size in java

There is no method call size() with array. you can use array.length

Retrieve list of tasks in a queue in Celery

If you don't use prioritized tasks, this is actually pretty simple if you're using Redis. To get the task counts:

redis-cli -h HOST -p PORT -n DATABASE_NUMBER llen QUEUE_NAME

But, prioritized tasks use a different key in redis, so the full picture is slightly more complicated. The full picture is that you need to query redis for every priority of task. In python (and from the Flower project), this looks like:

PRIORITY_SEP = '\x06\x16'
DEFAULT_PRIORITY_STEPS = [0, 3, 6, 9]


def make_queue_name_for_pri(queue, pri):
    """Make a queue name for redis

    Celery uses PRIORITY_SEP to separate different priorities of tasks into
    different queues in Redis. Each queue-priority combination becomes a key in
    redis with names like:

     - batch1\x06\x163 <-- P3 queue named batch1

    There's more information about this in Github, but it doesn't look like it 
    will change any time soon:

      - https://github.com/celery/kombu/issues/422

    In that ticket the code below, from the Flower project, is referenced:

      - https://github.com/mher/flower/blob/master/flower/utils/broker.py#L135

    :param queue: The name of the queue to make a name for.
    :param pri: The priority to make a name with.
    :return: A name for the queue-priority pair.
    """
    if pri not in DEFAULT_PRIORITY_STEPS:
        raise ValueError('Priority not in priority steps')
    return '{0}{1}{2}'.format(*((queue, PRIORITY_SEP, pri) if pri else
                                (queue, '', '')))


def get_queue_length(queue_name='celery'):
    """Get the number of tasks in a celery queue.

    :param queue_name: The name of the queue you want to inspect.
    :return: the number of items in the queue.
    """
    priority_names = [make_queue_name_for_pri(queue_name, pri) for pri in
                      DEFAULT_PRIORITY_STEPS]
    r = redis.StrictRedis(
        host=settings.REDIS_HOST,
        port=settings.REDIS_PORT,
        db=settings.REDIS_DATABASES['CELERY'],
    )
    return sum([r.llen(x) for x in priority_names])

If you want to get an actual task, you can use something like:

redis-cli -h HOST -p PORT -n DATABASE_NUMBER lrange QUEUE_NAME 0 -1

From there you'll have to deserialize the returned list. In my case I was able to accomplish this with something like:

r = redis.StrictRedis(
    host=settings.REDIS_HOST,
    port=settings.REDIS_PORT,
    db=settings.REDIS_DATABASES['CELERY'],
)
l = r.lrange('celery', 0, -1)
pickle.loads(base64.decodestring(json.loads(l[0])['body']))

Just be warned that deserialization can take a moment, and you'll need to adjust the commands above to work with various priorities.

A project with an Output Type of Class Library cannot be started directly

The project you've downloaded is a class library, not an executable assembly. This means you need to import that library into your own project instead of trying to run it directly.

What is a method group in C#?

You can cast a method group into a delegate.

The delegate signature selects 1 method out of the group.

This example picks the ToString() overload which takes a string parameter:

Func<string,string> fn = 123.ToString;
Console.WriteLine(fn("00000000"));

This example picks the ToString() overload which takes no parameters:

Func<string> fn = 123.ToString;
Console.WriteLine(fn());

How to check for changes on remote (origin) Git repository

I just use

git remote update
git status

The latter then reports how many commits behind my local is (if any).

Then

git pull origin master

to bring my local up to date :)

What is the difference between char, nchar, varchar, and nvarchar in SQL Server?

nchar and char pretty much operate in exactly the same way as each other, as do nvarchar and varchar. The only difference between them is that nchar/nvarchar store Unicode characters (essential if you require the use of extended character sets) whilst varchar does not.

Because Unicode characters require more storage, nchar/nvarchar fields take up twice as much space (so for example in earlier versions of SQL Server the maximum size of an nvarchar field is 4000).

This question is a duplicate of this one.

ReferenceError: variable is not defined

Variables are available only in the scope you defined them. If you define a variable inside a function, you won't be able to access it outside of it.

Define variable with var outside the function (and of course before it) and then assign 10 to it inside function:

var value;
$(function() {
  value = "10";
});
console.log(value); // 10

Note that you shouldn't omit the first line in this code (var value;), because otherwise you are assigning value to undefined variable. This is bad coding practice and will not work in strict mode. Defining a variable (var variable;) and assigning value to a variable (variable = value;) are two different things. You can't assign value to variable that you haven't defined.

It might be irrelevant here, but $(function() {}) is a shortcut for $(document).ready(function() {}), which executes a function as soon as document is loaded. If you want to execute something immediately, you don't need it, otherwise beware that if you run it before DOM has loaded, value will be undefined until it has loaded, so console.log(value); placed right after $(function() {}) will return undefined. In other words, it would execute in following order:

var value;
console.log(value);
value = "10";

See also:

Remove CSS from a Div using JQuery

Set the default value, for example:

$(this).css("height", "auto");

or in the case of other CSS features

$(this).css("height", "inherit");

Maven home (M2_HOME) not being picked up by IntelliJ IDEA

If M2_HOME is configured to point to the Maven home directory then:

  1. Go to File -> Settings
  2. Search for Maven
  3. Select Runner
  4. Insert in the field VM Options the following string:

    Dmaven.multiModuleProjectDirectory=$M2_HOME
    

Click Apply and OK

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

Python 3.3 and later now uses the 2010 compiler. To best way to solve the issue is to just install Visual C++ Express 2010 for free.

Now comes the harder part for 64 bit users and to be honest I just moved to 32 bit but 2010 express doesn't come with a 64 bit compiler (you get a new error, ValueError: ['path'] ) so you have to install Microsoft SDK 7.1 and follow the directions here to get the 64 bit compiler working with python: Python PIP has issues with path for MS Visual Studio 2010 Express for 64-bit install on Windows 7

It may just be easier for you to use the 32 bit version for now. In addition to getting the compiler working, you can bypass the need to compile many modules by getting the binary wheel file from this locaiton http://www.lfd.uci.edu/~gohlke/pythonlibs/

Just download the .whl file you need, shift + right click the download folder and select "open command window here" and run

pip install module-name.whl 

I used that method on 64 bit 3.4.3 before I broke down and decided to just get a working compiler for pip compiles modules from source by default, which is why the binary wheel files work and having pip build from source doesn't.

People getting this (vcvarsall.bat) error on Python 2.7 can instead install "Microsoft Visual C++ Compiler for Python 2.7"

HTML-encoding lost when attribute read from input field

Here's a non-jQuery version that is considerably faster than both the jQuery .html() version and the .replace() version. This preserves all whitespace, but like the jQuery version, doesn't handle quotes.

function htmlEncode( html ) {
    return document.createElement( 'a' ).appendChild( 
        document.createTextNode( html ) ).parentNode.innerHTML;
};

Speed: http://jsperf.com/htmlencoderegex/17

speed test

Demo: jsFiddle

Output:

output

Script:

function htmlEncode( html ) {
    return document.createElement( 'a' ).appendChild( 
        document.createTextNode( html ) ).parentNode.innerHTML;
};

function htmlDecode( html ) {
    var a = document.createElement( 'a' ); a.innerHTML = html;
    return a.textContent;
};

document.getElementById( 'text' ).value = htmlEncode( document.getElementById( 'hidden' ).value );

//sanity check
var html = '<div>   &amp; hello</div>';
document.getElementById( 'same' ).textContent = 
      'html === htmlDecode( htmlEncode( html ) ): ' 
    + ( html === htmlDecode( htmlEncode( html ) ) );

HTML:

<input id="hidden" type="hidden" value="chalk    &amp; cheese" />
<input id="text" value="" />
<div id="same"></div>

How to insert a newline in front of a pattern?

sed -e 's/regexp/\0\n/g'

\0 is the null, so your expression is replaced with null (nothing) and then...
\n is the new line

On some flavors of Unix doesn't work, but I think it's the solution to your problem.

echo "Hello" | sed -e 's/Hello/\0\ntmow/g'
Hello
tmow

Rails params explained?

As others have pointed out, params values can come from the query string of a GET request, or the form data of a POST request, but there's also a third place they can come from: The path of the URL.

As you might know, Rails uses something called routes to direct requests to their corresponding controller actions. These routes may contain segments that are extracted from the URL and put into params. For example, if you have a route like this:

match 'products/:id', ...

Then a request to a URL like http://example.com/products/42 will set params[:id] to 42.

Run Command Prompt Commands

Though technically this doesn't directly answer question posed, it does answer the question of how to do what the original poster wanted to do: combine files. If anything, this is a post to help newbies understand what Instance Hunter and Konstantin are talking about.

This is the method I use to combine files (in this case a jpg and a zip). Note that I create a buffer that gets filled with the content of the zip file (in small chunks rather than in one big read operation), and then the buffer gets written to the back of the jpg file until the end of the zip file is reached:

private void CombineFiles(string jpgFileName, string zipFileName)
{
    using (Stream original = new FileStream(jpgFileName, FileMode.Append))
    {
        using (Stream extra = new FileStream(zipFileName, FileMode.Open, FileAccess.Read))
        {
            var buffer = new byte[32 * 1024];

            int blockSize;
            while ((blockSize = extra.Read(buffer, 0, buffer.Length)) > 0)
            {
                original.Write(buffer, 0, blockSize);
            }
        }
    }
}

Call another rest api from my server in Spring-Boot

Modern Spring 5+ answer using WebClient instead of RestTemplate.

Configure WebClient for a specific web-service or resource as a bean (additional properties can be configured).

@Bean
public WebClient localApiClient() {
    return WebClient.create("http://localhost:8080/api/v3");
}

Inject and use the bean from your service(s).

@Service
public class UserService {

    private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(3);

    private final WebClient localApiClient;

    @Autowired
    public UserService(WebClient localApiClient) {
        this.localApiClient = localApiClient;
    }

    public User getUser(long id) {
        return localApiClient
                .get()
                .uri("/users/" + id)
                .retrieve()
                .bodyToMono(User.class)
                .block(REQUEST_TIMEOUT);
    }

}

OVER_QUERY_LIMIT in Google Maps API v3: How do I pause/delay in Javascript to slow it down?

Nothing like these two lines appears in Mike Williams' tutorial:

    wait = true;
    setTimeout("wait = true", 2000);

Here's a Version 3 port:

http://acleach.me.uk/gmaps/v3/plotaddresses.htm

The relevant bit of code is

  // ====== Geocoding ======
  function getAddress(search, next) {
    geo.geocode({address:search}, function (results,status)
      { 
        // If that was successful
        if (status == google.maps.GeocoderStatus.OK) {
          // Lets assume that the first marker is the one we want
          var p = results[0].geometry.location;
          var lat=p.lat();
          var lng=p.lng();
          // Output the data
            var msg = 'address="' + search + '" lat=' +lat+ ' lng=' +lng+ '(delay='+delay+'ms)<br>';
            document.getElementById("messages").innerHTML += msg;
          // Create a marker
          createMarker(search,lat,lng);
        }
        // ====== Decode the error status ======
        else {
          // === if we were sending the requests to fast, try this one again and increase the delay
          if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
            nextAddress--;
            delay++;
          } else {
            var reason="Code "+status;
            var msg = 'address="' + search + '" error=' +reason+ '(delay='+delay+'ms)<br>';
            document.getElementById("messages").innerHTML += msg;
          }   
        }
        next();
      }
    );
  }

How to concatenate two strings to build a complete path

#!/usr/bin/env bash

mvFiles() {
    local -a files=( file1 file2 ... ) \
             subDirs=( subDir1 subDir2 ) \
             subDirs=( "${subDirs[@]/#/$baseDir/}" )

    mkdir -p "${subDirs[@]}" || return 1

    local x
    for x in "${subDirs[@]}"; do
        cp "${files[@]}" "$x"
    done
}



main() {
    local baseDir
    [[ -t 1 ]] && echo 'Enter a path:'
    read -re baseDir
    mvFiles "$baseDir"
}

main "$@"

Scala check if element is present in a list

this should work also with different predicate

myFunction(strings.find( _ == mystring ).isDefined)

Maven Jacoco Configuration - Exclude classes/packages from report not working

https://github.com/jacoco/jacoco/issues/34

These are the different notations for classes we have:

  • VM Name: java/util/Map$Entry
  • Java Name: java.util.Map$Entry File
  • Name: java/util/Map$Entry.class

Agent Parameters, Ant tasks and Maven prepare-agent goal

  • includes: Java Name (VM Name also works)
  • excludes: Java Name (VM Name also works)
  • exclclassloader: Java Name

These specifications allow wildcards * and ?, where * wildcards any number of characters, even multiple nested folders.

Maven report goal

  • includes: File Name
  • excludes: File Name

These specs allow Ant Filespec like wildcards *, ** and ?, where * wildcards parts of a single path element only.

Convert string to integer type in Go?

If you control the input data, you can use the mini version

package main

import (
    "testing"
    "strconv"
)

func Atoi (s string) int {
    var (
        n uint64
        i int
        v byte
    )   
    for ; i < len(s); i++ {
        d := s[i]
        if '0' <= d && d <= '9' {
            v = d - '0'
        } else if 'a' <= d && d <= 'z' {
            v = d - 'a' + 10
        } else if 'A' <= d && d <= 'Z' {
            v = d - 'A' + 10
        } else {
            n = 0; break        
        }
        n *= uint64(10) 
        n += uint64(v)
    }
    return int(n)
}

func BenchmarkAtoi(b *testing.B) {
    for i := 0; i < b.N; i++ {
        in := Atoi("9999")
        _ = in
    }   
}

func BenchmarkStrconvAtoi(b *testing.B) {
    for i := 0; i < b.N; i++ {
        in, _ := strconv.Atoi("9999")
        _ = in
    }   
}

the fastest option (write your check if necessary). Result :

Path>go test -bench=. atoi_test.go
goos: windows
goarch: amd64
BenchmarkAtoi-2                 100000000               14.6 ns/op
BenchmarkStrconvAtoi-2          30000000                51.2 ns/op
PASS
ok      path     3.293s

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)

Python : Trying to POST form using requests

I was having problems here (i.e. sending form-data whilst uploading a file) until I used the following:

files = {'file': (filename, open(filepath, 'rb'), 'text/xml'),
         'Content-Disposition': 'form-data; name="file"; filename="' + filename + '"',
         'Content-Type': 'text/xml'}

That's the input that ended up working for me. In Chrome Dev Tools -> Network tab, I clicked the request I was interested in. In the Headers tab, there's a Form Data section, and it showed both the Content-Disposition and the Content-Type headers being set there.

I did NOT need to set headers in the actual requests.post() command for this to succeed (including them actually caused it to fail)

How to restore the dump into your running mongodb

I have been through a lot of trouble so I came up with my own solution, I created this script, just set the path inside script and db name and run it, it will do the trick

#!/bin/bash

FILES= #absolute or relative path to dump directory
DB=`db` #db name
for file in $FILES
do

    name=$(basename $file)
    collection="${name%.*}"
    echo `mongoimport --db "$DB" --file "$name" --collection "$collection"`

done

How to send a POST request using volley with string body?

You can refer to the following code (of course you can customize to get more details of the network response):

try {
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    String URL = "http://...";
    JSONObject jsonBody = new JSONObject();
    jsonBody.put("Title", "Android Volley Demo");
    jsonBody.put("Author", "BNK");
    final String requestBody = jsonBody.toString();

    StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.i("VOLLEY", response);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("VOLLEY", error.toString());
        }
    }) {
        @Override
        public String getBodyContentType() {
            return "application/json; charset=utf-8";
        }

        @Override
        public byte[] getBody() throws AuthFailureError {
            try {
                return requestBody == null ? null : requestBody.getBytes("utf-8");
            } catch (UnsupportedEncodingException uee) {
                VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
                return null;
            }
        }

        @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            String responseString = "";
            if (response != null) {
                responseString = String.valueOf(response.statusCode);
                // can get more details such as response.headers
            }
            return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
        }
    };

    requestQueue.add(stringRequest);
} catch (JSONException e) {
    e.printStackTrace();
}

Where does VBA Debug.Print log to?

Debug.Print outputs to the "Immediate" window.

Debug.Print outputs to the Immediate window

Also, you can simply type ? and then a statement directly into the immediate window (and then press Enter) and have the output appear right below, like this:

simply type ? and then a statement directly into the immediate window

This can be very handy to quickly output the property of an object...

? myWidget.name

...to set the property of an object...

myWidget.name = "thingy"

...or to even execute a function or line of code, while in debugging mode:

Sheet1.MyFunction()

What is Domain Driven Design?

I do not want to repeat others' answers, so, in short I explain some common misunderstanding

  • Practical resource: PATTERNS, PRINCIPLES, AND PRACTICES OF DOMAIN-DRIVEN DESIGN by Scott Millett
  • It is a methodology for complicated business systems. It takes all the technical matters out when communicating with business experts
  • It provides an extensive understanding of (simplified and distilled model of) business across the whole dev team.
  • it keeps business model in sync with code model by using ubiquitous language (the language understood by the whole dev team, business experts, business analysts, ...), which is used for communication within the dev team or dev with other teams
  • It has nothing to do with Project Management. Although it can be perfectly used in project management methods like Agile.
  • You should avoid using it all across your project

    DDD stresses the need to focus the most effort on the core subdomain. The core subdomain is the area of your product that will be the difference between it being a success and it being a failure. It’s the product’s unique selling point, the reason it is being built rather than bought.

    Basically, it is because it takes too much time and effort. So, it is suggested to break down the whole domain into subdomain and just apply it in those with high business value. (ex not in generic subdomain like email, ...)

  • It is not object oriented programming. It is mostly problem solving approach and (sometimes) you do not need to use OO patterns (such as Gang of Four) in your domain models. Simply because it can not be understood by Business Experts (they do not know much about Factory, Decorator, ...). There are even some patterns in DDD (such as The Transaction Script, Table Module) which are not 100% in line with OO concepts.

Oracle pl-sql escape character (for a " ' ")

Here is a way to easily escape & char in oracle DB

set escape '\\'

and within query write like

'ERRORS &\\\ PERFORMANCE';

Using Intent in an Android application to show another activity

you can use the context of the view that did the calling. Example:

Button orderButton = (Button)findViewById(R.id.order);

orderButton.setOnClickListener(new View.OnClickListener() {

  @Override
  public void onClick(View view) {
    Intent intent = new Intent(/*FirstActivity.this*/ view.getContext(), OrderScreen.class);
    startActivity(intent);
  }

});

OWIN Security - How to Implement OAuth2 Refresh Tokens

Just implemented my OWIN Service with Bearer (called access_token in the following) and Refresh Tokens. My insight into this is that you can use different flows. So it depends on the flow you want to use how you set your access_token and refresh_token expiration times.

I will describe two flows A and B in the follwing (I suggest what you want to have is flow B):

A) expiration time of access_token and refresh_token are the same as it is per default 1200 seconds or 20 minutes. This flow needs your client first to send client_id and client_secret with login data to get an access_token, refresh_token and expiration_time. With the refresh_token it is now possible to get a new access_token for 20 minutes (or whatever you set the AccessTokenExpireTimeSpan in the OAuthAuthorizationServerOptions to). For the reason that the expiration time of access_token and refresh_token are the same, your client is responsible to get a new access_token before the expiration time! E.g. your client could send a refresh POST call to your token endpoint with the body (remark: you should use https in production)

grant_type=refresh_token&client_id=xxxxxx&refresh_token=xxxxxxxx-xxxx-xxxx-xxxx-xxxxx

to get a new token after e.g. 19 minutes to prevent the tokens from expiration.

B) in this flow you want to have a short term expiration for your access_token and a long term expiration for your refresh_token. Lets assume for test purpose you set the access_token to expire in 10 seconds (AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(10)) and the refresh_token to 5 Minutes. Now it comes to the interesting part setting the expiration time of refresh_token: You do this in your createAsync function in SimpleRefreshTokenProvider class like this:

var guid = Guid.NewGuid().ToString();


        //copy properties and set the desired lifetime of refresh token
        var refreshTokenProperties = new AuthenticationProperties(context.Ticket.Properties.Dictionary)
        {
            IssuedUtc = context.Ticket.Properties.IssuedUtc,
            ExpiresUtc = DateTime.UtcNow.AddMinutes(5) //SET DATETIME to 5 Minutes
            //ExpiresUtc = DateTime.UtcNow.AddMonths(3) 
        };
        /*CREATE A NEW TICKET WITH EXPIRATION TIME OF 5 MINUTES 
         *INCLUDING THE VALUES OF THE CONTEXT TICKET: SO ALL WE 
         *DO HERE IS TO ADD THE PROPERTIES IssuedUtc and 
         *ExpiredUtc to the TICKET*/
        var refreshTokenTicket = new AuthenticationTicket(context.Ticket.Identity, refreshTokenProperties);

        //saving the new refreshTokenTicket to a local var of Type ConcurrentDictionary<string,AuthenticationTicket>
        // consider storing only the hash of the handle
        RefreshTokens.TryAdd(guid, refreshTokenTicket);            
        context.SetToken(guid);

Now your client is able to send a POST call with a refresh_token to your token endpoint when the access_token is expired. The body part of the call may look like this: grant_type=refresh_token&client_id=xxxxxx&refresh_token=xxxxxxxx-xxxx-xxxx-xxxx-xx

One important thing is that you may want to use this code not only in your CreateAsync function but also in your Create function. So you should consider to use your own function (e.g. called CreateTokenInternal) for the above code. Here you can find implementations of different flows including refresh_token flow(but without setting the expiration time of the refresh_token)

Here is one sample implementation of IAuthenticationTokenProvider on github (with setting the expiration time of the refresh_token)

I am sorry that I can't help out with further materials than the OAuth Specs and the Microsoft API Documentation. I would post the links here but my reputation doesn't let me post more than 2 links....

I hope this may help some others to spare time when trying to implement OAuth2.0 with refresh_token expiration time different to access_token expiration time. I couldn't find an example implementation on the web (except the one of thinktecture linked above) and it took me some hours of investigation until it worked for me.

New info: In my case I have two different possibilities to receive tokens. One is to receive a valid access_token. There I have to send a POST call with a String body in format application/x-www-form-urlencoded with the following data

client_id=YOURCLIENTID&grant_type=password&username=YOURUSERNAME&password=YOURPASSWORD

Second is if access_token is not valid anymore we can try the refresh_token by sending a POST call with a String body in format application/x-www-form-urlencoded with the following data grant_type=refresh_token&client_id=YOURCLIENTID&refresh_token=YOURREFRESHTOKENGUID

checking for typeof error in JS

Or use this for different types of errors

function isError(val) {
  return (!!val && typeof val === 'object')
    && ((Object.prototype.toString.call(val) === '[object Error]')
      || (typeof val.message === 'string' && typeof val.name === 'string'))
}

How to print an exception in Python 3?

Although if you want a code that is compatible with both python2 and python3 you can use this:

import logging
try:
    1/0
except Exception as e:
    if hasattr(e, 'message'):
        logging.warning('python2')
        logging.error(e.message)
    else:
        logging.warning('python3')
        logging.error(e)

Base 64 encode and decode example code

If you are using Kotlin than use like this

For Encode

val password = "Here Your String"
val data = password.toByteArray(charset("UTF-8"))
val base64 = Base64.encodeToString(data, Base64.DEFAULT)

For Decode

val datasd = Base64.decode(base64, Base64.DEFAULT)
val text = String(datasd, charset("UTF-8"))

Create a List of primitive int?

Is there a way to create a list of primitive int or any primitives in java

No you can't. You can only create List of reference types, like Integer, String, or your custom type.

It seems I can do List myList = new ArrayList(); and add "int" into this list.

When you add int to this list, it is automatically boxed to Integer wrapper type. But it is a bad idea to use raw type lists, or for any generic type for that matter, in newer code.

I can add anything into this list.

Of course, that is the dis-advantage of using raw type. You can have Cat, Dog, Tiger, Dinosaur, all in one container.

Is my only option, creating an array of int and converting it into a list

In that case also, you will get a List<Integer> only. There is no way you can create List<int> or any primitives.

You shouldn't be bothered anyways. Even in List<Integer> you can add an int primitive types. It will be automatically boxed, as in below example:

List<Integer> list = new ArrayList<Integer>();
list.add(5);

Error message: "'chromedriver' executable needs to be available in the path"

On Ubuntu:

sudo apt install chromium-chromedriver

On Debian:

sudo apt install chromium-driver

On macOS install https://brew.sh/ then do

brew cask install chromedriver

Firing events on CSS class changes in jQuery

change() does not fire when a CSS class is added or removed or the definition changes. It fires in circumstances like when a select box value is selected or unselected.

I'm not sure if you mean if the CSS class definition is changed (which can be done programmatically but is tedious and not generally recommended) or if a class is added or removed to an element. There is no way to reliably capture this happening in either case.

You could of course create your own event for this but this can only be described as advisory. It won't capture code that isn't yours doing it.

Alternatively you could override/replace the addClass() (etc) methods in jQuery but this won't capture when it's done via vanilla Javascript (although I guess you could replace those methods too).

Using an image caption in Markdown Jekyll

You can try to use pandoc as your converter. Here's a jekyll plugin to implement this. Pandoc will be able to add a figure caption the same as your alt attribute automatically.

But you have to push the compiled site because github doesn't allow plugins in Github pages for security.

No resource identifier found for attribute '...' in package 'com.app....'

I just changed:

xmlns:app="http://schemas.android.com/apk/res-auto" 

to:

xmlns:app="http://schemas.android.com/apk/lib/com.app.chasebank"

and it stopped generating the errors, com.app.chasebank is the name of the package. It should work according to this Stack Overflow : No resource identifier found for attribute 'adSize' in package 'com.google.example' main.xml

How can I convert a string to boolean in JavaScript?

var falsy = /^(?:f(?:alse)?|no?|0+)$/i;
Boolean.parse = function(val) { 
    return !falsy.test(val) && !!val;
};

This returns false for every falsy value and true for every truthy value except for 'false', 'f', 'no', 'n', and '0' (case-insensitive).

// False
Boolean.parse(false);
Boolean.parse('false');
Boolean.parse('False');
Boolean.parse('FALSE');
Boolean.parse('f');
Boolean.parse('F');
Boolean.parse('no');
Boolean.parse('No');
Boolean.parse('NO');
Boolean.parse('n');
Boolean.parse('N');
Boolean.parse('0');
Boolean.parse('');
Boolean.parse(0);
Boolean.parse(null);
Boolean.parse(undefined);
Boolean.parse(NaN);
Boolean.parse();

//True
Boolean.parse(true);
Boolean.parse('true');
Boolean.parse('True');
Boolean.parse('t');
Boolean.parse('yes');
Boolean.parse('YES');
Boolean.parse('y');
Boolean.parse('1');
Boolean.parse('foo');
Boolean.parse({});
Boolean.parse(1);
Boolean.parse(-1);
Boolean.parse(new Date());

How can I mock the JavaScript window object using Jest?

can test it:

describe('TableItem Components', () => {
    let open_url = ""
    const { open } = window;
    beforeAll(() => {
        delete window.open;
        window.open = (url) => { open_url = url };
    });
    afterAll(() => {
        window.open = open;
    });
    test('string type', async () => {
        wrapper.vm.openNewTab('http://example.com')
        expect(open_url).toBe('http://example.com')
    })
})

Excel VBA Loop on columns

Just use the Cells function and loop thru columns. Cells(Row,Column)

How can I reorder a list?

One more thing which can be considered is the other interpretation as pointed out by darkless

Code in Python 2.7

Mainly:

  1. Reorder by value - Already solved by AJ above
  2. Reorder by index

    mylist = ['a', 'b', 'c', 'd', 'e']
    myorder = [3, 2, 0, 1, 4]
    
    mylist = sorted(zip(mylist, myorder), key=lambda x: x[1])
    print [item[0] for item in mylist]
    

This will print ['c', 'd', 'b', 'a', 'e']

Shortcut to create properties in Visual Studio?

I think Alt+R+F is the correct one for creating property from a variable declaration

angularjs ng-style: background-image isn't working

The syntax is changed for Angular 2 and above:

[ngStyle]="{'background-image': 'url(path)'}"

Running python script inside ipython

In python there is no difference between modules and scripts; You can execute both scripts and modules. The file must be on the pythonpath AFAIK because python must be able to find the file in question. If python is executed from a directory, then the directory is automatically added to the pythonpath.

Refer to What is the best way to call a Python script from another Python script? for more information about modules vs scripts

There is also a builtin function execfile(filename) that will do what you want

Setting max-height for table cell contents

Possibly not cross browser but I managed get this: http://jsfiddle.net/QexkH/

basically it requires a fixed height header and footer. and it absolute positions the table.

    table {
        width: 50%;
        height: 50%;
        border-spacing: 0;
        position:absolute;
    }
    td {
        border: 1px solid black;
    }
    #content {
        position:absolute;
        width:100%;
        left:0px;
        top:20px;
        bottom:20px;
        overflow: hidden;
    }

Inner Joining three tables

try this:

SELECT * FROM TableA
JOIN TableB ON TableA.primary_key = TableB.foreign_key 
JOIN TableB ON TableB.foreign_key = TableC.foreign_key

The Eclipse executable launcher was unable to locate its companion launcher jar windows

I got this error because on Windows the Zend Studio Icon in the Start Menu was still pointing at the previous version of Zend Studio. Once I changed the target to the new path, the error went away.

Parsing JSON from URL

GSON has a builder that takes a Reader object: fromJson(Reader json, Class classOfT).

This means you can create a Reader from a URL and then pass it to Gson to consume the stream and do the deserialisation.

Only three lines of relevant code.

import java.io.InputStreamReader;
import java.net.URL;
import java.util.Map;

import com.google.gson.Gson;

public class GsonFetchNetworkJson {

    public static void main(String[] ignored) throws Exception {

        URL url = new URL("https://httpbin.org/get?color=red&shape=oval");
        InputStreamReader reader = new InputStreamReader(url.openStream());
        MyDto dto = new Gson().fromJson(reader, MyDto.class);

        // using the deserialized object
        System.out.println(dto.headers);
        System.out.println(dto.args);
        System.out.println(dto.origin);
        System.out.println(dto.url);
    }

    private class MyDto {
        Map<String, String> headers;
        Map<String, String> args;
        String origin;
        String url;
    }
}

If you happen to get a 403 error code with an endpoint which otherwise works fine (e.g. with curl or other clients) then a possible cause could be that the endpoint expects a User-Agent header and by default Java URLConnection is not setting it. An easy fix is to add at the top of the file e.g. System.setProperty("http.agent", "Netscape 1.0");.

dyld: Library not loaded: /usr/local/lib/libpng16.16.dylib with anything php related

I got this problem after updating MAMP, and the custom $PATH I had set was wrong because of the new php version, so the wrong version of php was loaded first, and it was that version of php that triggered the error.

Updating the path in my .bash_profile fixed my issue.

Find value in an array

Using Array#select will give you an array of elements that meet the criteria. But if you're looking for a way of getting the element out of the array that meets your criteria, Enumerable#detect would be a better way to go:

array = [1,2,3]
found = array.select {|e| e == 3} #=> [3]
found = array.detect {|e| e == 3} #=> 3

Otherwise you'd have to do something awkward like:

found = array.select {|e| e == 3}.first

How to search for a part of a word with ElasticSearch

I think there's no need to change any mapping. Try to use query_string, it's perfect. All scenarios will work with default standard analyzer:

We have data:

{"_id" : "1","name" : "John Doeman","function" : "Janitor"}
{"_id" : "2","name" : "Jane Doewoman","function" : "Teacher"}

Scenario 1:

{"query": {
    "query_string" : {"default_field" : "name", "query" : "*Doe*"}
} }

Response:

{"_id" : "1","name" : "John Doeman","function" : "Janitor"}
{"_id" : "2","name" : "Jane Doewoman","function" : "Teacher"}

Scenario 2:

{"query": {
    "query_string" : {"default_field" : "name", "query" : "*Jan*"}
} }

Response:

{"_id" : "1","name" : "John Doeman","function" : "Janitor"}

Scenario 3:

{"query": {
    "query_string" : {"default_field" : "name", "query" : "*oh* *oe*"}
} }

Response:

{"_id" : "1","name" : "John Doeman","function" : "Janitor"}
{"_id" : "2","name" : "Jane Doewoman","function" : "Teacher"}

EDIT - Same implementation with spring data elastic search https://stackoverflow.com/a/43579948/2357869

One more explanation how query_string is better than others https://stackoverflow.com/a/43321606/2357869

Getting "Cannot call a class as a function" in my React Project

I experienced this when writing an import statement wrong while importing a function, rather than a class. If removeMaterial is a function in another module:

Right:

import { removeMaterial } from './ClaimForm';

Wrong:

import removeMaterial from './ClaimForm';

"No such file or directory" error when executing a binary

Well another possible cause of this can be simple line break at end of each line and shebang line If you have been coding in windows IDE its possible that windows has added its own line break at the end of each line and when you try to run it on linux the line break cause problems

Why emulator is very slow in Android Studio?

Android Development Tools (ADT) 9.0.0 (or later) has a feature that allows you to save state of the AVD (emulator), and you can start your emulator instantly. You have to enable this feature while creating a new AVD or you can just create it later by editing the AVD.

Also I have increased the Device RAM Size to 1024 which results in a very fast emulator.

Refer the given below screenshots for more information.

Creating a new AVD with the save snapshot feature.

enter image description here

Launching the emulator from the snapshot.

enter image description here

And for speeding up your emulator you can refer to Speed up your Android Emulator!:

How do you clear the console screen in C?

Windows:

system("cls");

Unix:

system("clear");

You could instead, insert newline chars until everything gets scrolled, take a look here.

With that, you achieve portability easily.

CSS "color" vs. "font-color"

The same way Boston came up with its street plan. They followed the cow paths already there, and built houses where the streets weren't, and after a while it was too much trouble to change.

How to install lxml on Ubuntu

Many answers here are rather old,
thanks to the pointer from @Simplans (https://stackoverflow.com/a/37759871/417747) and the home page...

What worked for me (Ubuntu bionic):

sudo apt-get install python3-lxml  

(+ sudo apt-get install libxml2-dev libxslt1-dev I installed before it, but not sure if that's the requirement still)

Escape string Python for MySQL

{!a} applies ascii() and hence escapes non-ASCII characters like quotes and even emoticons. Here is an example

cursor.execute("UPDATE skcript set author='{!a}',Count='{:d}' where url='{!s}'".format(authors),leng,url))

Python3 docs

Adding script tag to React/JSX

for multiple scripts, use this

var loadScript = function(src) {
  var tag = document.createElement('script');
  tag.async = false;
  tag.src = src;
  document.getElementsByTagName('body').appendChild(tag);
}
loadScript('//cdnjs.com/some/library.js')
loadScript('//cdnjs.com/some/other/library.js')

Merge trunk to branch in Subversion

Is there something that prevents you from merging all revisions on trunk since the last merge?

svn merge -rLastRevisionMergedFromTrunkToBranch:HEAD url/of/trunk path/to/branch/wc

should work just fine. At least if you want to merge all changes on trunk to your branch.

Removing duplicates in the lists

If you don't care about order and want something different than the pythonic ways suggested above (that is, it can be used in interviews) then :

def remove_dup(arr):
    size = len(arr)
    j = 0    # To store index of next unique element
    for i in range(0, size-1):
        # If current element is not equal
        # to next element then store that
        # current element
        if(arr[i] != arr[i+1]):
            arr[j] = arr[i]
            j+=1

    arr[j] = arr[size-1] # Store the last element as whether it is unique or repeated, it hasn't stored previously

    return arr[0:j+1]

if __name__ == '__main__':
    arr = [10, 10, 1, 1, 1, 3, 3, 4, 5, 6, 7, 8, 8, 9]
    print(remove_dup(sorted(arr)))

Time Complexity : O(n)

Auxiliary Space : O(n)

Reference: http://www.geeksforgeeks.org/remove-duplicates-sorted-array/

How can I exit from a javascript function?

you can use

return false; or return; within your condition.

function refreshGrid(entity) {
    var store = window.localStorage;
    var partitionKey;
    ....
    if(some_condition) {
      return false;
    }
}

How to send json data in the Http request using NSURLRequest

You can try this code for send json string

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ARRAY_CONTAIN_JSON_STRING options:NSJSONWritin*emphasized text*gPrettyPrinted error:NULL];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *WS_test = [NSString stringWithFormat:@"www.test.com?xyz.php&param=%@",jsonString];

How can I do a case insensitive string comparison?

Please use this for comparison:

string.Equals(a, b, StringComparison.CurrentCultureIgnoreCase);

Clear the cache in JavaScript

If you are using php can do:

 <script src="js/myscript.js?rev=<?php echo time();?>"
    type="text/javascript"></script>

How to output (to a log) a multi-level array in a format that is human-readable?

You should be able to use a var_dump() within a pre tag. Otherwise you could look into using a library like dump_r.php: https://github.com/leeoniya/dump_r.php

My solution is incorrect. OP was looking for a solution formatted with spaces to store in a log file.

A solution might be to use output buffering with var_dump, then str_replace() all the tabs with spaces to format it in the log file.

Remove 'b' character do in front of a string literal in Python 3

This should do the trick:

pw_bytes.decode("utf-8")

Could not find a version that satisfies the requirement tensorflow

Python version is not supported Uninstall python

https://www.python.org/downloads/release/python-362/

You should check and use the exact version in install page. https://www.tensorflow.org/install/install_windows

python 3.6.2 or python 3.5.2 solved this issue for me

Can a CSS class inherit one or more other classes?

Unfortunately, CSS does not provide 'inheritance' in the way that programming languages like C++, C# or Java do. You can't declare a CSS class an then extend it with another CSS class.

However, you can apply more than a single class to an tag in your markup ... in which case there is a sophisticated set of rules that determine which actual styles will get applied by the browser.

<span class="styleA styleB"> ... </span>

CSS will look for all the styles that can be applied based on what your markup, and combine the CSS styles from those multiple rules together.

Typically, the styles are merged, but when conflicts arise, the later declared style will generally win (unless the !important attribute is specified on one of the styles, in which case that wins). Also, styles applied directly to an HTML element take precedence over CSS class styles.

Sorting objects by property values

With ES6 arrow functions it will be like this:

//Let's say we have these cars
let cars = [ { brand: 'Porsche', top_speed: 260 },
  { brand: 'Benz', top_speed: 110 },
  { brand: 'Fiat', top_speed: 90 },
  { brand: 'Aston Martin', top_speed: 70 } ]

Array.prototype.sort() can accept a comparator function (here I used arrow notation, but ordinary functions work the same):

let sortedByBrand = [...cars].sort((first, second) => first.brand > second.brand)

// [ { brand: 'Aston Martin', top_speed: 70 },
//   { brand: 'Benz', top_speed: 110 },
//   { brand: 'Fiat', top_speed: 90 },
//   { brand: 'Porsche', top_speed: 260 } ]

The above approach copies the contents of cars array into a new one and sorts it alphabetically based on brand names. Similarly, you can pass a different function:

let sortedBySpeed =[...cars].sort((first, second) => first.top_speed > second.top_speed)

//[ { brand: 'Aston Martin', top_speed: 70 },
//  { brand: 'Fiat', top_speed: 90 },
//  { brand: 'Benz', top_speed: 110 },
//  { brand: 'Porsche', top_speed: 260 } ]

If you don't mind mutating the orginal array cars.sort(comparatorFunction) will do the trick.

How to sum the values of a JavaScript object?

A ramda one liner:

import {
 compose, 
 sum,
 values,
} from 'ramda'

export const sumValues = compose(sum, values);

Use: const summed = sumValues({ 'a': 1 , 'b': 2 , 'c':3 });

What is the best way to iterate over a dictionary?

As already pointed out on this answer, KeyValuePair<TKey, TValue> implements a Deconstruct method starting on .NET Core 2.0, .NET Standard 2.1 and .NET Framework 5.0 (preview).

With this, it's possible to iterate through a dictionary in a KeyValuePair agnostic way:

var dictionary = new Dictionary<int, string>();

// ...

foreach (var (key, value) in dictionary)
{
    // ...
}

HttpListener Access Denied

Unfortunately, for some reasons probably linked with HTTPS and certificates, the native .NET HttpListener requires admin privileges, and even for HTTP only protocol...

The good point

It is interesting to note that HTTP protocol is on top of TCP protocol, but launching a C# TCP listener doesn't require any admin privileges to run. In other words, it is conceptually possible to implement an HTTP server which do not requires admin privileges.

Alternative

Below, an example of project which doesn't require admin privileges: https://github.com/EmilianoElMariachi/ElMariachi.Http.Server

How do I install Python OpenCV through Conda?

Using Wheel files is an easier approach. If you cannot install Wheel files from the command prompt, you can use an executable pip file which exists in the <Anaconda path>/Scripts folder.

LINQ Joining in C# with multiple conditions

If you need not equal object condition use cross join sequences:

var query = from obj1 in set1
from obj2 in set2
where obj1.key1 == obj2.key2 && obj1.key3.contains(obj2.key5) [...conditions...]

Setting top and left CSS attributes

div.style yields an object (CSSStyleDeclaration). Since it's an object, you can alternatively use the following:

div.style["top"] = "200px";
div.style["left"] = "200px";

This is useful, for example, if you need to access a "variable" property:

div.style[prop] = "200px";

What's the advantage of a Java enum versus a class with public static final fields?

Main reason: Enums help you to write well-structured code where the semantic meaning of parameters is clear and strongly-typed at compile time - for all the reasons other answers have given.

Quid pro quo: in Java out of the box, an Enum's array of members is final. That's normally good as it helps value safety and testing, but in some situations it could be a drawback, for example if you are extending existing base code perhaps from a library. In contrast, if the same data is in a class with static fields you can easily add new instances of that class at runtime (you might also need to write code to add these to any Iterable you have for that class). But this behaviour of Enums can be changed: using reflection you can add new members at runtime or replace existing members, though this should probably only be done in specialised situations where there is no alternative: i.e. it's a hacky solution and may produce unexpected issues, see my answer on Can I add and remove elements of enumeration at runtime in Java.

How to set the text color of TextView in code?

From API 23 onward, getResources().getColor() is deprecated.

Use this instead:

textView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.color_black));

How to access parameters in a RESTful POST method

Your @POST method should be accepting a JSON object instead of a string. Jersey uses JAXB to support marshaling and unmarshaling JSON objects (see the jersey docs for details). Create a class like:

@XmlRootElement
public class MyJaxBean {
    @XmlElement public String param1;
    @XmlElement public String param2;
}

Then your @POST method would look like the following:

@POST @Consumes("application/json")
@Path("/create")
public void create(final MyJaxBean input) {
    System.out.println("param1 = " + input.param1);
    System.out.println("param2 = " + input.param2);
}

This method expects to receive JSON object as the body of the HTTP POST. JAX-RS passes the content body of the HTTP message as an unannotated parameter -- input in this case. The actual message would look something like:

POST /create HTTP/1.1
Content-Type: application/json
Content-Length: 35
Host: www.example.com

{"param1":"hello","param2":"world"}

Using JSON in this way is quite common for obvious reasons. However, if you are generating or consuming it in something other than JavaScript, then you do have to be careful to properly escape the data. In JAX-RS, you would use a MessageBodyReader and MessageBodyWriter to implement this. I believe that Jersey already has implementations for the required types (e.g., Java primitives and JAXB wrapped classes) as well as for JSON. JAX-RS supports a number of other methods for passing data. These don't require the creation of a new class since the data is passed using simple argument passing.


HTML <FORM>

The parameters would be annotated using @FormParam:

@POST
@Path("/create")
public void create(@FormParam("param1") String param1,
                   @FormParam("param2") String param2) {
    ...
}

The browser will encode the form using "application/x-www-form-urlencoded". The JAX-RS runtime will take care of decoding the body and passing it to the method. Here's what you should see on the wire:

POST /create HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 25

param1=hello&param2=world

The content is URL encoded in this case.

If you do not know the names of the FormParam's you can do the following:

@POST @Consumes("application/x-www-form-urlencoded")
@Path("/create")
public void create(final MultivaluedMap<String, String> formParams) {
    ...
}

HTTP Headers

You can using the @HeaderParam annotation if you want to pass parameters via HTTP headers:

@POST
@Path("/create")
public void create(@HeaderParam("param1") String param1,
                   @HeaderParam("param2") String param2) {
    ...
}

Here's what the HTTP message would look like. Note that this POST does not have a body.

POST /create HTTP/1.1
Content-Length: 0
Host: www.example.com
param1: hello
param2: world

I wouldn't use this method for generalized parameter passing. It is really handy if you need to access the value of a particular HTTP header though.


HTTP Query Parameters

This method is primarily used with HTTP GETs but it is equally applicable to POSTs. It uses the @QueryParam annotation.

@POST
@Path("/create")
public void create(@QueryParam("param1") String param1,
                   @QueryParam("param2") String param2) {
    ...
}

Like the previous technique, passing parameters via the query string does not require a message body. Here's the HTTP message:

POST /create?param1=hello&param2=world HTTP/1.1
Content-Length: 0
Host: www.example.com

You do have to be particularly careful to properly encode query parameters on the client side. Using query parameters can be problematic due to URL length restrictions enforced by some proxies as well as problems associated with encoding them.


HTTP Path Parameters

Path parameters are similar to query parameters except that they are embedded in the HTTP resource path. This method seems to be in favor today. There are impacts with respect to HTTP caching since the path is what really defines the HTTP resource. The code looks a little different than the others since the @Path annotation is modified and it uses @PathParam:

@POST
@Path("/create/{param1}/{param2}")
public void create(@PathParam("param1") String param1,
                   @PathParam("param2") String param2) {
    ...
}

The message is similar to the query parameter version except that the names of the parameters are not included anywhere in the message.

POST /create/hello/world HTTP/1.1
Content-Length: 0
Host: www.example.com

This method shares the same encoding woes that the query parameter version. Path segments are encoded differently so you do have to be careful there as well.


As you can see, there are pros and cons to each method. The choice is usually decided by your clients. If you are serving FORM-based HTML pages, then use @FormParam. If your clients are JavaScript+HTML5-based, then you will probably want to use JAXB-based serialization and JSON objects. The MessageBodyReader/Writer implementations should take care of the necessary escaping for you so that is one fewer thing that can go wrong. If your client is Java based but does not have a good XML processor (e.g., Android), then I would probably use FORM encoding since a content body is easier to generate and encode properly than URLs are. Hopefully this mini-wiki entry sheds some light on the various methods that JAX-RS supports.

Note: in the interest of full disclosure, I haven't actually used this feature of Jersey yet. We were tinkering with it since we have a number of JAXB+JAX-RS applications deployed and are moving into the mobile client space. JSON is a much better fit that XML on HTML5 or jQuery-based solutions.

What are the differences between git remote prune, git prune, git fetch --prune, etc

In the event that anyone would be interested. Here's a quick shell script that will remove all local branches that aren't tracked remotely. A word of caution: This will get rid of any branch that isn't tracked remotely regardless of whether it was merged or not.

If you guys see any issues with this please let me know and I'll fix it (etc. etc.)

Save it in a file called git-rm-ntb (call it whatever) on PATH and run:

git-rm-ntb <remote1:optional> <remote2:optional> ...

clean()
{
  REMOTES="$@";
  if [ -z "$REMOTES" ]; then
    REMOTES=$(git remote);
  fi
  REMOTES=$(echo "$REMOTES" | xargs -n1 echo)
  RBRANCHES=()
  while read REMOTE; do
    CURRBRANCHES=($(git ls-remote $REMOTE | awk '{print $2}' | grep 'refs/heads/' | sed 's:refs/heads/::'))
    RBRANCHES=("${CURRBRANCHES[@]}" "${RBRANCHES[@]}")
  done < <(echo "$REMOTES" )
  [[ $RBRANCHES ]] || exit
  LBRANCHES=($(git branch | sed 's:\*::' | awk '{print $1}'))
  for i in "${LBRANCHES[@]}"; do
    skip=
    for j in "${RBRANCHES[@]}"; do
      [[ $i == $j ]] && { skip=1; echo -e "\033[32m Keeping $i \033[0m"; break; }
    done
    [[ -n $skip ]] || { echo -e "\033[31m $(git branch -D $i) \033[0m"; }
  done
}

clean $@

Can I add extension methods to an existing static class?

No. Extension methods require an instance variable (value) for an object. You can however, write a static wrapper around the ConfigurationManager interface. If you implement the wrapper, you don't need an extension method since you can just add the method directly.

 public static class ConfigurationManagerWrapper
 {
      public static ConfigurationSection GetSection( string name )
      {
         return ConfigurationManager.GetSection( name );
      }

      .....

      public static ConfigurationSection GetWidgetSection()
      {
          return GetSection( "widgets" );
      }
 }

"element.dispatchEvent is not a function" js error caught in firebug of FF3.0

are you using jquery and prototype on the same page by any chance?

If so, use jquery noConflict mode, otherwise you are overwriting prototypes $ function.

noConflict mode is activated by doing the following:

<script src="jquery.js"></script>
<script>jQuery.noConflict();</script>

Note: by doing this, the dollar sign variable no longer represents the jQuery object. To keep from rewriting all your jQuery code, you can use this little trick to create a dollar sign scope for jQuery:

jQuery(function ($) {
    // The dollar sign will equal jQuery in this scope
});

// Out here, the dollar sign still equals Prototype

Uncaught TypeError: data.push is not a function

Also make sure that the name of the variable is not some kind of a language keyword. For instance, the following produces the same type of error:

var history = [];
history.push("what a mess");

replacing it for:

var history123 = [];
history123.push("pray for a better language");

works as expected.

How to read data from a zip file without having to unzip the entire file

DotNetZip is your friend here.

As easy as:

using (ZipFile zip = ZipFile.Read(ExistingZipFile))
{
  ZipEntry e = zip["MyReport.doc"];
  e.Extract(OutputStream);
}

(you can also extract to a file or other destinations).

Reading the zip file's table of contents is as easy as:

using (ZipFile zip = ZipFile.Read(ExistingZipFile))
{
  foreach (ZipEntry e in zip)
  {
    if (header)
    {
      System.Console.WriteLine("Zipfile: {0}", zip.Name);
      if ((zip.Comment != null) && (zip.Comment != "")) 
        System.Console.WriteLine("Comment: {0}", zip.Comment);
      System.Console.WriteLine("\n{1,-22} {2,8}  {3,5}   {4,8}  {5,3} {0}",
                               "Filename", "Modified", "Size", "Ratio", "Packed", "pw?");
      System.Console.WriteLine(new System.String('-', 72));
      header = false;
    }
    System.Console.WriteLine("{1,-22} {2,8} {3,5:F0}%   {4,8}  {5,3} {0}",
                             e.FileName,
                             e.LastModified.ToString("yyyy-MM-dd HH:mm:ss"),
                             e.UncompressedSize,
                             e.CompressionRatio,
                             e.CompressedSize,
                             (e.UsesEncryption) ? "Y" : "N");

  }
}

Edited To Note: DotNetZip used to live at Codeplex. Codeplex has been shut down. The old archive is still available at Codeplex. It looks like the code has migrated to Github:


Https to http redirect using htaccess

RewriteEngine On
RewriteCond %{SERVER_PORT} 443
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Android simple alert dialog

You can easily make your own 'AlertView' and use it everywhere.

alertView("You really want this?");

Implement it once:

private void alertView( String message ) {
 AlertDialog.Builder dialog = new AlertDialog.Builder(context);
 dialog.setTitle( "Hello" )
       .setIcon(R.drawable.ic_launcher)
       .setMessage(message)
//     .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
//      public void onClick(DialogInterface dialoginterface, int i) {
//          dialoginterface.cancel();   
//          }})
      .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialoginterface, int i) {   
        }               
        }).show();
 }

How to document Python code using Doxygen

This is documented on the doxygen website, but to summarize here:

You can use doxygen to document your Python code. You can either use the Python documentation string syntax:

"""@package docstring
Documentation for this module.

More details.
"""

def func():
    """Documentation for a function.

    More details.
    """
    pass

In which case the comments will be extracted by doxygen, but you won't be able to use any of the special doxygen commands.

Or you can (similar to C-style languages under doxygen) double up the comment marker (#) on the first line before the member:

## @package pyexample
#  Documentation for this module.
#
#  More details.

## Documentation for a function.
#
#  More details.
def func():
    pass

In that case, you can use the special doxygen commands. There's no particular Python output mode, but you can apparently improve the results by setting OPTMIZE_OUTPUT_JAVA to YES.

Honestly, I'm a little surprised at the difference - it seems like once doxygen can detect the comments in ## blocks or """ blocks, most of the work would be done and you'd be able to use the special commands in either case. Maybe they expect people using """ to adhere to more Pythonic documentation practices and that would interfere with the special doxygen commands?

Determine on iPhone if user has enabled push notifications

UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
if (types & UIRemoteNotificationTypeAlert)
    // blah blah blah
{
    NSLog(@"Notification Enabled");
}
else
{
    NSLog(@"Notification not enabled");
}

Here we get the UIRemoteNotificationType from UIApplication. It represents the state of push notification of this app in the setting, than you can check on its type easily

How to get ip address of a server on Centos 7 in bash

You can run simple commands like

curl ifconfig.co

curl ifconfig.me

wget -qO - icanhazip.com

Jquery: How to check if the element has certain css class/style

Question is asking for two different things:

  1. An element has certain class
  2. An element has certain style.

Second question has been already answered. For the first one, I would do it this way:

if($("#someElement").is(".test")){
    // Has class test assigned, eventually combined with other classes
}
else{
    // Does not have it
}

How can I create my own comparator for a map?

Since C++11, you can also use a lambda expression instead of defining a comparator struct:

auto comp = [](const string& a, const string& b) { return a.length() < b.length(); };
map<string, string, decltype(comp)> my_map(comp);

my_map["1"]      = "a";
my_map["three"]  = "b";
my_map["two"]    = "c";
my_map["fouuur"] = "d";

for(auto const &kv : my_map)
    cout << kv.first << endl;

Output:

1
two
three
fouuur

I'd like to repeat the final note of Georg's answer: When comparing by length you can only have one string of each length in the map as a key.

Code on Ideone

How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags?

That is an HTTP header. You would configure your webserver or webapp to send this header ideally. Perhaps in htaccess or PHP.

Alternatively you might be able to use

<head>...<meta http-equiv="Access-Control-Allow-Origin" content="*">...</head>

I do not know if that would work. Not all HTTP headers can be configured directly in the HTML.

This works as an alternative to many HTTP headers, but see @EricLaw's comment below. This particular header is different.

Caveat

This answer is strictly about how to set headers. I do not know anything about allowing cross domain requests.

About HTTP Headers

Every request and response has headers. The browser sends this to the webserver

GET /index.htm HTTP/1.1

Then the headers

Host: www.example.com
User-Agent: (Browser/OS name and version information)
.. Additional headers indicating supported compression types and content types and other info

Then the server sends a response

Content-type: text/html
Content-length: (number of bytes in file (optional))
Date: (server clock)
Server: (Webserver name and version information)

Additional headers can be configured for example Cache-Control, it all depends on your language (PHP, CGI, Java, htaccess) and webserver (Apache, etc).

How to call Stored Procedure in a View?

Easiest solution that I might have found is to create a table from the data you get from the SP. Then create a view from that:

Insert this at the last step when selecting data from the SP. SELECT * into table1 FROM #Temp

create view vw_view1 as select * from table1

Change the background color in a twitter bootstrap modal?

When modal appears, it will trigger event show.bs.modal before appearing. I tried at Safari 13.1.2 on MacOS 10.15.6. When show.bs.modal event triggered, the .modal-backgrop is not inserted into body yet.

So, I give up to addClass, and removeClass to .modal-backdrop dynamically.

After viewing a lot articles on the Internet, I found a code snippet. It addClass and removeClass to the body, which is the parent of .modal-backdrop, when show.bs.modal and hide.bs.modal events triggered.

ps: I use Bootstrap 4.5.

CSS

// In order to addClass/removeClass on the `body`. The parent of `.modal-backdrop`
.no-modal-bg .modal-backdrop {
    background: none;
}

Javascript

$('#myModalId').on('show.bs.modal', function(e) {
     $('body').addClass('no-modal-bg');
}).on('hidden.bs.modal', function(e) {
     // 'hide.bs.modal' or 'hidden.bs.modal', depends on your needs.
     $('body').removeClass('no-modal-bg');
});

References

  1. The code snippet after google
  2. Bootstrap 4.5, modal, #events
  3. Bootstrap 4.5 documents

Python - List of unique dictionaries

There are a lot of answers here, so let me add another:

import json
from typing import List

def dedup_dicts(items: List[dict]):
    dedupped = [ json.loads(i) for i in set(json.dumps(item, sort_keys=True) for item in items)]
    return dedupped

items = [
    {'id': 1, 'name': 'john', 'age': 34},
    {'id': 1, 'name': 'john', 'age': 34},
    {'id': 2, 'name': 'hanna', 'age': 30},
]
dedup_dicts(items)

Is it possible to pass a flag to Gulp to have it run tasks in different ways?

If you've some strict (ordered!) arguments, then you can get them simply by checking process.argv.

var args = process.argv.slice(2);

if (args[0] === "--env" && args[1] === "production");

Execute it: gulp --env production

...however, I think that this is tooo strict and not bulletproof! So, I fiddled a bit around... and ended up with this utility function:

function getArg(key) {
  var index = process.argv.indexOf(key);
  var next = process.argv[index + 1];
  return (index < 0) ? null : (!next || next[0] === "-") ? true : next;
}

It eats an argument-name and will search for this in process.argv. If nothing was found it spits out null. Otherwise if their is no next argument or the next argument is a command and not a value (we differ with a dash) true gets returned. (That's because the key exist, but there's just no value). If all the cases before will fail, the next argument-value is what we get.

> gulp watch --foo --bar 1337 -boom "Foo isn't equal to bar."

getArg("--foo") // => true
getArg("--bar") // => "1337"
getArg("-boom") // => "Foo isn't equal to bar."
getArg("--404") // => null

Ok, enough for now... Here's a simple example using gulp:

var gulp = require("gulp");
var sass = require("gulp-sass");
var rename = require("gulp-rename");

var env = getArg("--env");

gulp.task("styles", function () {
  return gulp.src("./index.scss")
  .pipe(sass({
    style: env === "production" ? "compressed" : "nested"
  }))
  .pipe(rename({
    extname: env === "production" ? ".min.css" : ".css"
  }))
  .pipe(gulp.dest("./build"));
});

Run it gulp --env production

JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?

Many thanks to David Walsh, here is a vanilla version of underscore debounce.

Code:

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

Simple usage:

var myEfficientFn = debounce(function() {
    // All the taxing stuff you do
}, 250);

$(window).on('resize', myEfficientFn);

Ref: http://davidwalsh.name/javascript-debounce-function

Ternary operator in AngularJS templates

Update: Angular 1.1.5 added a ternary operator, so now we can simply write

<li ng-class="$first ? 'firstRow' : 'nonFirstRow'">

If you are using an earlier version of Angular, your two choices are:

  1. (condition && result_if_true || !condition && result_if_false)
  2. {true: 'result_if_true', false: 'result_if_false'}[condition]

item 2. above creates an object with two properties. The array syntax is used to select either the property with name true or the property with name false, and return the associated value.

E.g.,

<li class="{{{true: 'myClass1 myClass2', false: ''}[$first]}}">...</li>
 or
<li ng-class="{true: 'myClass1 myClass2', false: ''}[$first]">...</li>

$first is set to true inside an ng-repeat for the first element, so the above would apply class 'myClass1' and 'myClass2' only the first time through the loop.

With ng-class there is an easier way though: ng-class takes an expression that must evaluate to one of the following:

  1. a string of space-delimited class names
  2. an array of class names
  3. a map/object of class names to boolean values.

An example of 1) was given above. Here is an example of 3, which I think reads much better:

 <li ng-class="{myClass: $first, anotherClass: $index == 2}">...</li>

The first time through an ng-repeat loop, class myClass is added. The 3rd time through ($index starts at 0), class anotherClass is added.

ng-style takes an expression that must evaluate to a map/object of CSS style names to CSS values. E.g.,

 <li ng-style="{true: {color: 'red'}, false: {}}[$first]">...</li>

What is the canonical way to check for errors using the CUDA runtime API?

Probably the best way to check for errors in runtime API code is to define an assert style handler function and wrapper macro like this:

#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort=true)
{
   if (code != cudaSuccess) 
   {
      fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line);
      if (abort) exit(code);
   }
}

You can then wrap each API call with the gpuErrchk macro, which will process the return status of the API call it wraps, for example:

gpuErrchk( cudaMalloc(&a_d, size*sizeof(int)) );

If there is an error in a call, a textual message describing the error and the file and line in your code where the error occurred will be emitted to stderr and the application will exit. You could conceivably modify gpuAssert to raise an exception rather than call exit() in a more sophisticated application if it were required.

A second related question is how to check for errors in kernel launches, which can't be directly wrapped in a macro call like standard runtime API calls. For kernels, something like this:

kernel<<<1,1>>>(a);
gpuErrchk( cudaPeekAtLastError() );
gpuErrchk( cudaDeviceSynchronize() );

will firstly check for invalid launch argument, then force the host to wait until the kernel stops and checks for an execution error. The synchronisation can be eliminated if you have a subsequent blocking API call like this:

kernel<<<1,1>>>(a_d);
gpuErrchk( cudaPeekAtLastError() );
gpuErrchk( cudaMemcpy(a_h, a_d, size * sizeof(int), cudaMemcpyDeviceToHost) );

in which case the cudaMemcpy call can return either errors which occurred during the kernel execution or those from the memory copy itself. This can be confusing for the beginner, and I would recommend using explicit synchronisation after a kernel launch during debugging to make it easier to understand where problems might be arising.

Note that when using CUDA Dynamic Parallelism, a very similar methodology can and should be applied to any usage of the CUDA runtime API in device kernels, as well as after any device kernel launches:

#include <assert.h>
#define cdpErrchk(ans) { cdpAssert((ans), __FILE__, __LINE__); }
__device__ void cdpAssert(cudaError_t code, const char *file, int line, bool abort=true)
{
   if (code != cudaSuccess)
   {
      printf("GPU kernel assert: %s %s %d\n", cudaGetErrorString(code), file, line);
      if (abort) assert(0);
   }
}

3 column layout HTML/CSS

.container{
height:100px;
width:500px;
border:2px dotted #F00;
border-left:none;
border-right:none;
text-align:center;
}
.container div{
display: inline-block;
border-left: 2px dotted #ccc;
vertical-align: middle;
line-height: 100px;
} 
 .column-left{ float: left; width: 32%;  height:100px;}
.column-right{ float: right; width: 32%;  height:100px; border-right: 2px dotted #ccc;}
.column-center{ display: inline-block; width: 33%; height:100px;}

 <div class="container">
   <div class="column-left">Column left</div>
   <div class="column-center">Column center</div>
   <div class="column-right">Column right</div>
</div> 

See this link http://jsfiddle.net/bipin_kumar/XD8RW/2/

Get loop count inside a Python FOR loop

Try using itertools.count([n])

How do I tell matplotlib that I am done with a plot?

You can use figure to create a new plot, for example, or use close after the first plot.

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

json.loads() takes a JSON encoded string, not a filename. You want to use json.load() (no s) instead and pass in an open file object:

with open('/Users/JoshuaHawley/clean1.txt') as jsonfile:
    data = json.load(jsonfile)

The open() command produces a file object that json.load() can then read from, to produce the decoded Python object for you. The with statement ensures that the file is closed again when done.

The alternative is to read the data yourself and then pass it into json.loads().

UILabel with text of two different colors

Having a UIWebView or more than one UILabel could be considered overkill for this situation.

My suggestion would be to use TTTAttributedLabel which is a drop-in replacement for UILabel that supports NSAttributedString. This means you can very easily apply differents styles to different ranges in a string.

The view 'Index' or its master was not found.

If You can get this error even with all the correct MapRoutes in your area registration and all other basic configurations are fine.

This is the situation:

I have used below mentioned code from Jquery file to post back data and then load a view from controller action method.

$.post("/Customers/ReturnRetailOnlySales", {petKey: '<%: Model.PetKey %>'}); 

Above jQuery code I didn't mentioned success callback function. What was happened there is after finishing a post back scenario on action method, without routing to my expected view it came back to Jquery side and gave view not found error as above.

Then I gave a solution like below and its working without any problem.

 $.post("/Customers/ReturnRetailOnlySales", {petKey: '<%: Model.PetKey %>'},
      function (data) {
 var url = Sys.Url.route('PetDetail', { action: "ReturnRetailOnlySalesItems", controller: "Customers",petKey: '<%: Model.PetKey %>'});
 window.location = url;});   

Note: I sent my request inside the success callback function to my expected views action method.Then view engine found a relevant area's view file and load correctly.

How do I consume the JSON POST data in an Express application

@Daniel Thompson mentions that he had forgotten to add {"Content-Type": "application/json"} in the request. He was able to change the request, however, changing requests is not always possible (we are working on the server here).

In my case I needed to force content-type: text/plain to be parsed as json.

If you cannot change the content-type of the request, try using the following code:

app.use(express.json({type: '*/*'}));

Instead of using express.json() globally, I prefer to apply it only where needed, for instance in a POST request:

app.post('/mypost', express.json({type: '*/*'}), (req, res) => {
  // echo json
  res.json(req.body);
});

How to detect Safari, Chrome, IE, Firefox and Opera browser?

Here is my customized solution.

        const inBrowser = typeof window !== 'undefined'
        const UA = inBrowser && window.navigator.userAgent.toLowerCase()
        const isIE =
          UA && /; msie|trident/i.test(UA) && !/ucbrowser/i.test(UA).test(UA)
        const isEdge = UA && /edg/i.test(UA)
        const isAndroid = UA && UA.indexOf('android') > 0
        const isIOS = UA && /iphone|ipad|ipod|ios/i.test(UA)
        const isChrome =
          UA &&
          /chrome|crios/i.test(UA) &&
          !/opr|opera|chromium|edg|ucbrowser|googlebot/i.test(UA)
        const isGoogleBot = UA && /googlebot/i.test(UA)
        const isChromium = UA && /chromium/i.test(UA)
        const isUcBrowser = UA && /ucbrowser/i.test(UA)
        const isSafari =
          UA &&
          /safari/i.test(UA) &&
          !/chromium|edg|ucbrowser|chrome|crios|opr|opera|fxios|firefox/i.test(UA)
        const isFirefox = UA && /firefox|fxios/i.test(UA) && !/seamonkey/i.test(UA)
        const isOpera = UA && /opr|opera/i.test(UA)
        const isMobile =
          /\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(UA) ||
          /\b(Android|Windows Phone|iPad|iPod)\b/i.test(UA)
        const isSamsung = UA && /samsungbrowser/i.test(UA)
        const isIPad = UA && /ipad/.test(UA)
        const isIPhone = UA && /iphone/.test(UA)
        const isIPod = UA && /ipod/.test(UA)
    
        console.log({
          UA,
          isAndroid,
          isChrome,
          isChromium,
          isEdge,
          isFirefox,
          isGoogleBot,
          isIE,
          isMobile,
          isIOS,
          isIPad,
          isIPhone,
          isIPod,
          isOpera,
          isSafari,
          isSamsung,
          isUcBrowser,
        }
      }

Bad operand type for unary +: 'str'

The code works for me. (after adding missing except clause / import statements)

Did you put \ in the original code?

urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/' \
              + stock + '/chartdata;type=quote;range=5d/csv'

If you omit it, it could be a cause of the exception:

>>> stock = 'GOOG'
>>> urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/'
>>> + stock + '/chartdata;type=quote;range=5d/csv'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary +: 'str'

BTW, string(e) should be str(e).

Setting environment variables for accessing in PHP when using Apache

Unbelievable, but on httpd 2.2 on centos 6.4 this works.

Export env vars in /etc/sysconfig/httpd

export mydocroot=/var/www/html

Then simply do this...

<VirtualHost *:80>
  DocumentRoot ${mydocroot}
</VirtualHost>

Then finally....

service httpd restart;

How to get full width in body element

You should set body and html to position:fixed;, and then set right:, left:, top:, and bottom: to 0;. That way, even if content overflows it will not extend past the limits of the viewport.

For example:

<html>
<body>
    <div id="wrapper"></div>
</body>
</html>

CSS:

html, body, {
    position:fixed;
    top:0;
    bottom:0;
    left:0;
    right:0;
}

JS Fiddle Example

Caveat: Using this method, if the user makes their window smaller, content will be cut off.

Hide all warnings in ipython

For jupyter lab this should work (@Alasja)

from IPython.display import HTML
HTML('''<script>
var code_show_err = false; 
var code_toggle_err = function() {
 var stderrNodes = document.querySelectorAll('[data-mime-type="application/vnd.jupyter.stderr"]')
 var stderr = Array.from(stderrNodes)
 if (code_show_err){
     stderr.forEach(ele => ele.style.display = 'block');
 } else {
     stderr.forEach(ele => ele.style.display = 'none');
 }
 code_show_err = !code_show_err
} 
document.addEventListener('DOMContentLoaded', code_toggle_err);
</script>
To toggle on/off output_stderr, click <a onclick="javascript:code_toggle_err()">here</a>.''')

Run .php file in Windows Command Prompt (cmd)

If running Windows 10:

  1. Open the start menu
  2. Type path
  3. Click Edit the system environment variables (usually, it's the top search result) and continue on step 6 below.

If on older Windows:

  1. Show Desktop.

  2. Right Click My Computer shortcut in the desktop.

  3. Click Properties.

  4. You should see a section of control Panel - Control Panel\System and Security\System.

  5. Click Advanced System Settings on the Left menu.

  6. Click Enviornment Variables towards the bottom of the System Properties window.

  7. Select PATH in the user variables list.

  8. Append your PHP Path (C:\myfolder\php) to your PATH variable, separated from the already existing string by a semi colon.

  9. Click OK

  10. Open your "cmd"

  11. Type PATH, press enter

  12. Make sure that you see your PHP folder among the list.

That should work.

Note: Make sure that your PHP folder has the php.exe. It should have the file type CLI. If you do not have the php.exe, go ahead and check the installation guidelines at - http://www.php.net/manual/en/install.windows.manual.php - and download the installation file from there.

Node.js ES6 classes with require

The ES6 way of require is import. You can export your class and import it somewhere else using import { ClassName } from 'path/to/ClassName'syntax.

import fs from 'fs';
export default class Animal {

  constructor(name){
    this.name = name ;
  }

  print(){
    console.log('Name is :'+ this.name);
  }
}

import Animal from 'path/to/Animal.js';

Why use the params keyword?

Another example

public IEnumerable<string> Tokenize(params string[] words)
{
  ...
}

var items = Tokenize(product.Name, product.FullName, product.Xyz)

How to convert Varchar to Int in sql server 2008?

That is how you would do it, is it throwing an error? Are you sure the value you are trying to convert is convertible? For obvious reasons you cannot convert abc123 to an int.

UPDATE

Based on your comments I would remove any spaces that are in the values you are trying to convert.

Mockito: Trying to spy on method is calling the original method

One way to make sure a method from a class is not called is to override the method with a dummy.

    WebFormCreatorActivity activity = spy(new WebFormCreatorActivity(clientFactory) {//spy(new WebFormCreatorActivity(clientFactory));
            @Override
            public void select(TreeItem i) {
                log.debug("SELECT");
            };
        });

Android findViewById() in Custom View

Change your Method as following and check it will work

private void initViews() {
    inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    inflater.inflate(R.layout.id_number_edit_text_custom, this, true);
    View view = (View) inflater.inflate(R.layout.main, null);
    editText = (EditText) view.findViewById(R.id.id_number_custom);
    loadButton = (ImageButton) view.findViewById(R.id.load_data_button);
    loadButton.setVisibility(RelativeLayout.INVISIBLE);
    loadData();
} 

Checkout old commit and make it a new commit

The other answers so far create new commits that undo what is in older commits. It is possible to go back and "change history" as it were, but this can be a bit dangerous. You should only do this if the commit you're changing has not been pushed to other repositories.

The command you're looking for is git rebase --interactive

If you want to change HEAD~3, the command you want to issue is git rebase --interactive HEAD~4. This will open a text editor and allow you to specify which commits you want to change.

Practice on a different repository before you try this with something important. The man pages should give you all the rest of the information you need.

urllib2 and json

To read json response use json.loads(). Here is the sample.

import json
import urllib
import urllib2

post_params = {
    'foo' : bar
}

params = urllib.urlencode(post_params)
response = urllib2.urlopen(url, params)
json_response = json.loads(response.read())

Apache HttpClient 4.0.3 - how do I set cookie with sessionID for POST request?

I did it by passing the cookie through the HttpContext:

HttpContext localContext = new BasicHttpContext();

localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

response = client.execute(httppost, localContext);

Open link in new tab or window

set the target attribute of your <a> element to "_tab"

EDIT: It works, however W3Schools says there is no such target attribute: http://www.w3schools.com/tags/att_a_target.asp

EDIT2: From what I've figured out from the comments. setting target to _blank will take you to a new tab or window (depending on your browser settings). Typing anything except one of the ones below will create a new tab group (I'm not sure how these work):

_blank  Opens the linked document in a new window or tab
_self   Opens the linked document in the same frame as it was clicked (this is default)
_parent Opens the linked document in the parent frame
_top    Opens the linked document in the full body of the window
framename   Opens the linked document in a named frame

How to make responsive table

Basically

A responsive table is simply a 100% width table.

You can just set up your table with this CSS:

.table { width: 100%; }

Demo here

You can use media queries to show/hide/manipulate columns according to the screens dimensions by adding a class (or targeting using nth-child, etc):

@media screen and (max-width: 320px) {
    .hide { display: none; }
}

HTML

<td class="hide">Not important</td>

More advanced solutions

If you have a table with a lot of data and you would like to make it readable on small screen devices there are many other solutions:

AttributeError: Can only use .dt accessor with datetimelike values

First you need to define the format of date column.

df['Date'] = pd.to_datetime(df.Date, format='%Y-%m-%d %H:%M:%S')

For your case base format can be set to;

df['Date'] = pd.to_datetime(df.Date, format='%Y-%m-%d')

After that you can set/change your desired output as follows;

df['Date'] = df['Date'].dt.strftime('%Y-%m-%d')