Programs & Examples On #Column width

Set the table column width constant regardless of the amount of text in its cells?

See: http://www.html5-tutorials.org/tables/changing-column-width/

After the table tag, use the col element. you don't need a closing tag.

For example, if you had three columns:

<table>
  <colgroup>
    <col style="width:40%">
    <col style="width:30%">
    <col style="width:30%">
  </colgroup>  
  <tbody>
    ...
  </tbody>
</table>

How do I expand the output display to see more columns of a pandas DataFrame?

You can set the output display to match your current terminal width:

pd.set_option('display.width', pd.util.terminal.get_terminal_size()[0])

how to increase sqlplus column output length?

What I use:

set long 50000
set linesize 130

col x format a80 word_wrapped;
select dbms_metadata.get_ddl('TABLESPACE','LM_THIN_DATA') x from dual;

Or am I missing something?

Handling Dialogs in WPF with MVVM

My current solution solves most of the issues you mentioned yet its completely abstracted from platform specific things and can be reused. Also i used no code-behind only binding with DelegateCommands that implement ICommand. Dialog is basically a View - a separate control that has its own ViewModel and it is shown from the ViewModel of the main screen but triggered from the UI via DelagateCommand binding.

See full Silverlight 4 solution here Modal dialogs with MVVM and Silverlight 4

Codeigniter LIKE with wildcard(%)

For Full like you can user :

$this->db->like('title',$query);

For %$query you can use

$this->db->like('title', $query, 'before');

and for $query% you can use

$this->db->like('title', $query, 'after');

Can't access Eclipse marketplace

Here's the solution,

If you are a constant proxy changer like me for various reasons (university, home , workplace and so on..) you are mostly likely to get this error due to improper configuration of connection settings in the eclipse IDE. all you have to do it play around with the current settings and get it to working state. Here's how,,

1. GO TO

Window-> Preferences -> General -> Network Connection.

2. Change the Settings

Active Provider-> Manual-> and check---> HTTP, HTTPS and SOCKS

If your active provider is already set to Manual, try restoring the default (native)


That's all, restart Eclipse and you are good to go!


Filtering DataGridView without changing datasource

//"Comment" Filter datagrid without changing dataset,Perfectly works.

            (dg.ItemsSource as ListCollectionView).Filter = (d) =>
            {
                DataRow myRow = ((System.Data.DataRowView)(d)).Row;
                if (myRow["FName"].ToString().ToUpper().Contains(searchText.ToString().ToUpper()) || myRow["LName"].ToString().ToUpper().Contains(searchText.ToString().ToUpper()))
                    return true; //if want to show in grid
                return false;    //if don't want to show in grid
            };         

How to check visibility of software keyboard in Android?

Reuben Scratton's new answer (calculate the HeightDiff int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight(); ) will not work in activity if you set the translucent status bar mode.

if you use translucent status bar , activityRootView.getHeight() will never change weather the soft keyboard is visible. it will always return the height of activity and status bar.

For example, Nexus 4, Android 5.0.1, set android:windowTranslucentStatus to true, it will return 1184 forever, even the ime have opend. If you set android:windowTranslucentStatus to false, it will return Height correctly, if ime invisible,it return 1134(not include the status bar)?close the ime, it will return 5xx maybe (depends on ime's height)

I don't know weather this is a bug, I've try on 4.4.4 and 5.0.1, the result is same.

So, up to now, the second most agreed answer, Kachi's solution will be the most safe way to calcute the height of ime. Here's a copy:

final View activityRootView = findViewById(R.id.activityRoot);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new        OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect r = new Rect();
//r will be populated with the coordinates of your view that area still visible.
activityRootView.getWindowVisibleDisplayFrame(r);

int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
if (heightDiff > 100) { // if more than 100 pixels, its probably a keyboard...
    ... do something here
    }
 }
}); 

figure of imshow() is too small

If you don't give an aspect argument to imshow, it will use the value for image.aspect in your matplotlibrc. The default for this value in a new matplotlibrc is equal. So imshow will plot your array with equal aspect ratio.

If you don't need an equal aspect you can set aspect to auto

imshow(random.rand(8, 90), interpolation='nearest', aspect='auto')

which gives the following figure

imshow-auto

If you want an equal aspect ratio you have to adapt your figsize according to the aspect

fig, ax = subplots(figsize=(18, 2))
ax.imshow(random.rand(8, 90), interpolation='nearest')
tight_layout()

which gives you:

imshow-equal

Is there a Google Keep API?

No there's not and developers still don't know why google doesn't pay attention to this request!

As you can see in this link it's one of the most popular issues with many stars in google code but still no response from google! You can also add stars to this issue, maybe google hears that!

TypeError: Cannot read property "0" from undefined

Check your array index to see if it's accessed out of bound.

Once I accessed categories[0]. Later I changed the array name from categories to category but forgot to change the access point--from categories[0] to category[0], thus I also get this error.

JavaScript does a poor debug message. In your case, I reckon probably the access gets out of bound.

Entity Framework and SQL Server View

Agree with @Tillito, however in most cases it will foul SQL optimizer and it will not use right indexes.

It may be obvious for somebody, but I burned hours solving performance issues using Tillito solution. Lets say you have the table:

 Create table OrderDetail
    (  
       Id int primary key,
       CustomerId int references Customer(Id),
       Amount decimal default(0)
    );
 Create index ix_customer on OrderDetail(CustomerId);

and your view is something like this

 Create view CustomerView
    As
      Select 
          IsNull(CustomerId, -1) as CustomerId, -- forcing EF to use it as key
          Sum(Amount) as Amount
      From OrderDetail
      Group by CustomerId

Sql optimizer will not use index ix_customer and it will perform table scan on primary index, but if instead of:

Group by CustomerId

you use

Group by IsNull(CustomerId, -1)

it will make MS SQL (at least 2008) include right index into plan.

If

How to find a number in a string using JavaScript?

Use a regular expression.

var r = /\d+/;
var s = "you can enter maximum 500 choices";
alert (s.match(r));

The expression \d+ means "one or more digits". Regular expressions by default are greedy meaning they'll grab as much as they can. Also, this:

var r = /\d+/;

is equivalent to:

var r = new RegExp("\d+");

See the details for the RegExp object.

The above will grab the first group of digits. You can loop through and find all matches too:

var r = /\d+/g;
var s = "you can enter 333 maximum 500 choices";
var m;
while ((m = r.exec(s)) != null) {
  alert(m[0]);
}

The g (global) flag is key for this loop to work.

How to run regasm.exe from command line other than Visual Studio command prompt?

By dragging and dropping the dll onto 'regasm' you can register it. You can open two 'Window Explorer' windows. One will contain the dll you wish to register. The 2nd window will be the location of the 'regasm' application. Scroll down in both windows so that you have a view of both the dll and 'regasm'. It helps to reduce the size of the two windows so they are side-by-side. Be sure to drag the dll over the 'regasm' that is labeled 'application'. There are several 'regasm' files but you only want the application.

Bash tool to get nth line from a file

With awk it is pretty fast:

awk 'NR == num_line' file

When this is true, the default behaviour of awk is performed: {print $0}.


Alternative versions

If your file happens to be huge, you'd better exit after reading the required line. This way you save CPU time See time comparison at the end of the answer.

awk 'NR == num_line {print; exit}' file

If you want to give the line number from a bash variable you can use:

awk 'NR == n' n=$num file
awk -v n=$num 'NR == n' file   # equivalent

See how much time is saved by using exit, specially if the line happens to be in the first part of the file:

# Let's create a 10M lines file
for ((i=0; i<100000; i++)); do echo "bla bla"; done > 100Klines
for ((i=0; i<100; i++)); do cat 100Klines; done > 10Mlines

$ time awk 'NR == 1234567 {print}' 10Mlines
bla bla

real    0m1.303s
user    0m1.246s
sys 0m0.042s
$ time awk 'NR == 1234567 {print; exit}' 10Mlines
bla bla

real    0m0.198s
user    0m0.178s
sys 0m0.013s

So the difference is 0.198s vs 1.303s, around 6x times faster.

Execute jQuery function after another function completes

Deferred promises are a nice way to chain together function execution neatly and easily. Whether AJAX or normal functions, they offer greater flexibility than callbacks, and I've found easier to grasp.

function Typer()
{
var dfd = $.Deferred();
    var srcText = 'EXAMPLE ';
    var i = 0;
    var result = srcText[i];

UPDATE :

////////////////////////////////

  var timer=    setInterval(function() {
                    if(i == srcText.length) {

    // clearInterval(this);


       clearInterval(timer);

////////////////////////////////


   dfd.resolve();
                        };
                        i++;
                        result += srcText[i].replace("\n", "<br />");
                        $("#message").html( result);
                },
                100);
              return dfd.promise();
            }

I've modified the play function so it returns a promise when the audio finishes playing, which might be useful to some. The third function fires when sound finishes playing.

   function playBGM()
    {
      var playsound = $.Deferred();
      $('#bgm')[0].play();
      $("#bgm").on("ended", function() {
         playsound.resolve();
      });
        return playsound.promise();
    }


    function thirdFunction() {
        alert('third function');
    }

Now call the whole thing with the following: (be sure to use Jquery 1.9.1 or above as I found that 1.7.2 executes all the functions at once, rather than waiting for each to resolve.)

Typer().then(playBGM).then(thirdFunction);  

Before today, I had no luck using deferred promises in this way, and finally have grasped it. Precisely timed, chained interface events occurring exactly when we want them to, including async events, has never been easy. For me at least, I now have it under control thanks largely to others asking questions here.

powershell mouse move does not prevent idle mode

The solution from the blog Prevent desktop lock or screensaver with PowerShell is working for me. Here is the relevant script, which simply sends a single period to the shell:

param($minutes = 60)

$myshell = New-Object -com "Wscript.Shell"

for ($i = 0; $i -lt $minutes; $i++) {
  Start-Sleep -Seconds 60
  $myshell.sendkeys(".")
}

and an alternative from the comments, which moves the mouse a single pixel:

$Pos = [System.Windows.Forms.Cursor]::Position
[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point((($Pos.X) + 1) , $Pos.Y)
$Pos = [System.Windows.Forms.Cursor]::Position
[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point((($Pos.X) - 1) , $Pos.Y)

How do you make Vim unhighlight what you searched for?

            *:noh* *:nohlsearch*
:noh[lsearch]       Stop the highlighting for the 'hlsearch' option.  It
            is automatically turned back on when using a search
            command, or setting the 'hlsearch' option.
            This command doesn't work in an autocommand, because
            the highlighting state is saved and restored when
            executing autocommands |autocmd-searchpat|.
            Same thing for when invoking a user function.

I found it just under :help #, which I keep hitting all the time, and which highlights all the words on the current page like the current one.

How to get highcharts dates in the x axis?

You write like this-:

xAxis: {
        type: 'datetime',
        dateTimeLabelFormats: {
           day: '%d %b %Y'    //ex- 01 Jan 2016
        }
}

also check for other datetime format

http://api.highcharts.com/highcharts#xAxis.dateTimeLabelFormats

How to do if-else in Thymeleaf?

Use th:switch as an if-else

<span th:switch="${isThisTrue}">
  <i th:case="true" class="fas fa-check green-text"></i>
  <i th:case="false" class="fas fa-times red-text"></i>
</span>

Use th:switch as a switch

<span th:switch="${fruit}">
  <i th:case="Apple" class="fas fa-check red-text"></i>
  <i th:case="Orange" class="fas fa-times orange-text"></i>
  <i th:case="*" class="fas fa-times yellow-text"></i>
</span>

How to do fade-in and fade-out with JavaScript and CSS

Here is a more efficient way of fading out an element:

function fade(element) {
    var op = 1;  // initial opacity
    var timer = setInterval(function () {
        if (op <= 0.1){
            clearInterval(timer);
            element.style.display = 'none';
        }
        element.style.opacity = op;
        element.style.filter = 'alpha(opacity=' + op * 100 + ")";
        op -= op * 0.1;
    }, 50);
}

you can do the reverse for fade in

setInterval or setTimeout should not get a string as argument

google the evils of eval to know why

And here is a more efficient way of fading in an element.

function unfade(element) {
    var op = 0.1;  // initial opacity
    element.style.display = 'block';
    var timer = setInterval(function () {
        if (op >= 1){
            clearInterval(timer);
        }
        element.style.opacity = op;
        element.style.filter = 'alpha(opacity=' + op * 100 + ")";
        op += op * 0.1;
    }, 10);
}

std::cin input with spaces?

THE C WAY

You can use gets function found in cstdio(stdio.h in c):

#include<cstdio>
int main(){

char name[256];
gets(name); // for input
puts(name);// for printing 
}

THE C++ WAY

gets is removed in c++11.

[Recommended]:You can use getline(cin,name) which is in string.h or cin.getline(name,256) which is in iostream itself.

#include<iostream>
#include<string>
using namespace std;
int main(){

char name1[256];
string name2;
cin.getline(name1,256); // for input
getline(cin,name2); // for input
cout<<name1<<"\n"<<name2;// for printing
}

How to Display Multiple Google Maps per page with API V3

Take a Look at this Bundle for Laravel that I Made Recently !


https://github.com/Maghrooni/googlemap

it helps you to create one or multiple maps in your page !

you can find the class on

src/googlemap.php

Pls Read the readme file first and don't forget to pass different ID if you want to have multiple Maps in one page

Modal width (increase)

If you use Sass,

according to the documentation you can customize your default values.

In your case, you can easily override the variable named $modal-lg in your _custom.scss file.

How to start a background process in Python?

I found this here:

On windows (win xp), the parent process will not finish until the longtask.py has finished its work. It is not what you want in CGI-script. The problem is not specific to Python, in PHP community the problems are the same.

The solution is to pass DETACHED_PROCESS Process Creation Flag to the underlying CreateProcess function in win API. If you happen to have installed pywin32 you can import the flag from the win32process module, otherwise you should define it yourself:

DETACHED_PROCESS = 0x00000008

pid = subprocess.Popen([sys.executable, "longtask.py"],
                       creationflags=DETACHED_PROCESS).pid

GET parameters in the URL with CodeIgniter

A little bit out of topic, but I was looking for a get function in CodeIgniter just to pass some variables between controllers and come across Flashdata.
see : http://codeigniter.com/user_guide/libraries/sessions.html
Flashdata allows you to create a quick session data that will only be available for the next server request, and are then automatically cleared.

How does one reorder columns in a data frame?

Maybe it's a coincidence that the column order you want happens to have column names in descending alphabetical order. Since that's the case you could just do:

df<-df[,order(colnames(df),decreasing=TRUE)]

That's what I use when I have large files with many columns.

How do I check if a string is valid JSON in Python?

You can try to do json.loads(), which will throw a ValueError if the string you pass can't be decoded as JSON.

In general, the "Pythonic" philosophy for this kind of situation is called EAFP, for Easier to Ask for Forgiveness than Permission.

How to round an average to 2 decimal places in PostgreSQL?

you can use the function below

 SELECT TRUNC(14.568,2);

the result will show :

14.56

you can also cast your variable to the desire type :

 SELECT TRUNC(YOUR_VAR::numeric,2)

Flutter: how to make a TextField with HintText but no Underline?

Here is a supplemental answer that shows some fuller code:

enter image description here

  Container(
    decoration: BoxDecoration(
      color: Colors.tealAccent,
      borderRadius:  BorderRadius.circular(32),
    ),
    child: TextField(
      decoration: InputDecoration(
        hintStyle: TextStyle(fontSize: 17),
        hintText: 'Search your trips',
        suffixIcon: Icon(Icons.search),
        border: InputBorder.none,
        contentPadding: EdgeInsets.all(20),
      ),
    ),
  ),

Notes:

  • The dark background (code not shown) is Colors.teal.
  • InputDecoration also has a filled and fillColor property, but I couldn't get them to have a corner radius, so I used a container instead.

The differences between initialize, define, declare a variable

Declaration

Declaration, generally, refers to the introduction of a new name in the program. For example, you can declare a new function by describing it's "signature":

void xyz();

or declare an incomplete type:

class klass;
struct ztruct;

and last but not least, to declare an object:

int x;

It is described, in the C++ standard, at §3.1/1 as:

A declaration (Clause 7) may introduce one or more names into a translation unit or redeclare names introduced by previous declarations.

Definition

A definition is a definition of a previously declared name (or it can be both definition and declaration). For example:

int x;
void xyz() {...}
class klass {...};
struct ztruct {...};
enum { x, y, z };

Specifically the C++ standard defines it, at §3.1/1, as:

A declaration is a definition unless it declares a function without specifying the function’s body (8.4), it contains the extern specifier (7.1.1) or a linkage-specification25 (7.5) and neither an initializer nor a function- body, it declares a static data member in a class definition (9.2, 9.4), it is a class name declaration (9.1), it is an opaque-enum-declaration (7.2), it is a template-parameter (14.1), it is a parameter-declaration (8.3.5) in a function declarator that is not the declarator of a function-definition, or it is a typedef declaration (7.1.3), an alias-declaration (7.1.3), a using-declaration (7.3.3), a static_assert-declaration (Clause 7), an attribute- declaration (Clause 7), an empty-declaration (Clause 7), or a using-directive (7.3.4).

Initialization

Initialization refers to the "assignment" of a value, at construction time. For a generic object of type T, it's often in the form:

T x = i;

but in C++ it can be:

T x(i);

or even:

T x {i};

with C++11.

Conclusion

So does it mean definition equals declaration plus initialization?

It depends. On what you are talking about. If you are talking about an object, for example:

int x;

This is a definition without initialization. The following, instead, is a definition with initialization:

int x = 0;

In certain context, it doesn't make sense to talk about "initialization", "definition" and "declaration". If you are talking about a function, for example, initialization does not mean much.

So, the answer is no: definition does not automatically mean declaration plus initialization.

How to check Django version

The most pythonic way I've seen to get the version of any package:

>>> import pkg_resources;
>>> pkg_resources.get_distribution('django').version
'1.8.4'

This ties directly into setup.py: https://github.com/django/django/blob/master/setup.py#L37

Also there is distutils to compare the version:

>>> from distutils.version import LooseVersion, StrictVersion
>>> LooseVersion("2.3.1") < LooseVersion("10.1.2")
True
>>> StrictVersion("2.3.1") < StrictVersion("10.1.2")
True
>>> StrictVersion("2.3.1") > StrictVersion("10.1.2")
False

As for getting the python version, I agree with James Bradbury:

>>> import sys
>>> sys.version
'3.4.3 (default, Jul 13 2015, 12:18:23) \n[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)]'

Tying it all together:

>>> StrictVersion((sys.version.split(' ')[0])) > StrictVersion('2.6')
True

How to draw a rounded Rectangle on HTML Canvas?

try to add this line , when you want to get rounded corners : ctx.lineCap = "round";

how to break the _.each function in underscore.js

You cannot break a forEach in underscore, as it emulates EcmaScript 5 native behaviour.

How to 'restart' an android application programmatically

Checkout intent properties like no history , clear back stack etc ... Intent.setFlags

Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);

Powershell command to hide user from exchange address lists

You can use the following script, just replace DOMAIN with the name of your domain. When executed it will prompt you for a userlogin then hide that user's account from the address lists.

$name=Read-Host "Enter login name of user to hide"
Set-Mailbox -Identity DOMAIN\$name -HiddenFromAddressListsEnabled $true

Brian.

PHP cURL error code 60

First you have to download the certificate from this link

https://curl.haxx.se/ca/cacert.pem

and put it in a location you want the name of downloadable file is : cacert.pem So in my case I will put it under C:\wamp64\bin\php\cacert.pem

Then you have to specify the location of the php.ini file

For example, I am using php 7 the php.ini file is located at : C:\wamp64\bin\php\php7.0.10\php.ini

So access to that file and uncommit this line ;openssl.cafile

also update it to be looks like this openssl.cafile="C:\wamp64\bin\php\cacert.pem"

Finally restart your apache server and that's all

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

As a generic answer, not specifically directed at this task: In many cases, you can significantly speed up any program by making improvements at a high level. Like calculating data once instead of multiple times, avoiding unnecessary work completely, using caches in the best way, and so on. These things are much easier to do in a high level language.

Writing assembler code, it is possible to improve on what an optimising compiler does, but it is hard work. And once it's done, your code is much harder to modify, so it is much more difficult to add algorithmic improvements. Sometimes the processor has functionality that you cannot use from a high level language, inline assembly is often useful in these cases and still lets you use a high level language.

In the Euler problems, most of the time you succeed by building something, finding why it is slow, building something better, finding why it is slow, and so on and so on. That is very, very hard using assembler. A better algorithm at half the possible speed will usually beat a worse algorithm at full speed, and getting the full speed in assembler isn't trivial.

How to change the timeout on a .NET WebClient object

For completeness, here's kisp's solution ported to VB (can't add code to a comment)

Namespace Utils

''' <summary>
''' Subclass of WebClient to provide access to the timeout property
''' </summary>
Public Class WebClient
    Inherits System.Net.WebClient

    Private _TimeoutMS As Integer = 0

    Public Sub New()
        MyBase.New()
    End Sub
    Public Sub New(ByVal TimeoutMS As Integer)
        MyBase.New()
        _TimeoutMS = TimeoutMS
    End Sub
    ''' <summary>
    ''' Set the web call timeout in Milliseconds
    ''' </summary>
    ''' <value></value>
    Public WriteOnly Property setTimeout() As Integer
        Set(ByVal value As Integer)
            _TimeoutMS = value
        End Set
    End Property


    Protected Overrides Function GetWebRequest(ByVal address As System.Uri) As System.Net.WebRequest
        Dim w As System.Net.WebRequest = MyBase.GetWebRequest(address)
        If _TimeoutMS <> 0 Then
            w.Timeout = _TimeoutMS
        End If
        Return w
    End Function

End Class

End Namespace

How to run cron job every 2 hours

Just do:

0 */2 * * *  /home/username/test.sh 

The 0 at the beginning means to run at the 0th minute. (If it were an *, the script would run every minute during every second hour.)

Don't forget, you can check syslog to see if it ever actually ran!

How do you pass a function as a parameter in C?

Functions can be "passed" as function pointers, as per ISO C11 6.7.6.3p8: "A declaration of a parameter as ‘‘function returning type’’ shall be adjusted to ‘‘pointer to function returning type’’, as in 6.3.2.1. ". For example, this:

void foo(int bar(int, int));

is equivalent to this:

void foo(int (*bar)(int, int));

How to remove specific substrings from a set of strings in Python?

Strings are immutable. string.replace (python 2.x) or str.replace (python 3.x) creates a new string. This is stated in the documentation:

Return a copy of string s with all occurrences of substring old replaced by new. ...

This means you have to re-allocate the set or re-populate it (re-allocating is easier with set comprehension):

new_set = {x.replace('.good', '').replace('.bad', '') for x in set1}

MIT vs GPL license

Can I include GPL licensed code in a MIT licensed product?

You can. GPL is free software as well as MIT is, both licenses do not restrict you to bring together the code where as "include" is always two-way.

In copyright for a combined work (that is two or more works form together a work), it does not make much of a difference if the one work is "larger" than the other or not.

So if you include GPL licensed code in a MIT licensed product you will at the same time include a MIT licensed product in GPL licensed code as well.

As a second opinion, the OSI listed the following criteria (in more detail) for both licenses (MIT and GPL):

  1. Free Redistribution
  2. Source Code
  3. Derived Works
  4. Integrity of The Author's Source Code
  5. No Discrimination Against Persons or Groups
  6. No Discrimination Against Fields of Endeavor
  7. Distribution of License
  8. License Must Not Be Specific to a Product
  9. License Must Not Restrict Other Software
  10. License Must Be Technology-Neutral

Both allow the creation of combined works, which is what you've been asking for.

If combining the two works is considered being a derivate, then this is not restricted as well by both licenses.

And both licenses do not restrict to distribute the software.

It seems to me that the chief difference between the MIT license and GPL is that the MIT doesn't require modifications be open sourced whereas the GPL does.

The GPL doesn't require you to release your modifications only because you made them. That's not precise.

You might mix this with distribiution of software under GPL which is not what you've asked about directly.

Is that correct - is the GPL is more restrictive than the MIT license?

This is how I understand it:

As far as distribution counts, you need to put the whole package under GPL. MIT code inside of the package will still be available under MIT whereas the GPL applies to the package as a whole if not limited by higher rights.

"Restrictive" or "more restrictive" / "less restrictive" depends a lot on the point of view. For a software-user the MIT might result in software that is more restricted than the one available under GPL even some call the GPL more restrictive nowadays. That user in specific will call the MIT more restrictive. It's just subjective to say so and different people will give you different answers to that.

As it's just subjective to talk about restrictions of different licenses, you should think about what you would like to achieve instead:

  • If you want to restrict the use of your modifications, then MIT is able to be more restrictive than the GPL for distribution and that might be what you're looking for.
  • In case you want to ensure that the freedom of your software does not get restricted that much by the users you distribute it to, then you might want to release under GPL instead of MIT.

As long as you're the author it's you who can decide.

So the most restrictive person ever is the author, regardless of which license anybody is opting for ;)

WARNING: sanitizing unsafe style value url

You have to wrap the entire url statement in the bypassSecurityTrustStyle:

<div class="header" *ngIf="image" [style.background-image]="image"></div>

And have

this.image = this.sanitization.bypassSecurityTrustStyle(`url(${element.image})`);

Otherwise it is not seen as a valid style property

Error:Execution failed for task ':ProjectName:mergeDebugResources'. > Crunching Cruncher *some file* failed, see logs

I was getting the same error and it worked for me. Hope it helps.

As Niklas said, you have to update to the latest Gradle version.


My way to solve the error:

  1. Open your Android Studio (AS) program.
  2. Go to your build.gradle file in your project.
  3. Change:

    dependencies {
        classpath 'com.android.tools.build:gradle:1.1.0'
    

    to:

    dependencies {
        classpath 'com.android.tools.build:gradle:1.1.3'
    
  4. Sync your Android project with Gradle: enter image description here

  5. Clean your project.

  6. Rebuild your project.
  7. Done!

If its still not working:

  1. Close your Android Studio program and open it again.
  2. Try compiling the code.
  3. Done!

If you need more help, read the issue on Google Code!

li:before{ content: "¦"; } How to Encode this Special Character as a Bullit in an Email Stationery?

You are facing a double-encoding issue.

¦ and &#8226; are absolutely equivalent to each other. Both refer to the Unicode character 'BULLET' (U+2022) and can exist side-by-side in HTML source code.

However, if that source-code is HTML-encoded again at some point, it will contain ¦ and &amp;#8226;. The former is rendered unchanged, the latter will come out as "&#8226;" on the screen.

This is correct behavior under these circumstances. You need to find the point where the superfluous second HTML-encoding occurs and get rid of it.

Converting year and month ("yyyy-mm" format) to a date?

Using anytime package:

library(anytime)

anydate("2009-01")
# [1] "2009-01-01"

Xcode 6 iPhone Simulator Application Support location

Here is the sh for last used simulator and application. Just run sh and copy printed text and paste and run command for show in finder.

#!/bin/zsh

lastUsedSimulatorAndApplication=`ls -td -- ~/Library/Developer/CoreSimulator/Devices/*/data/Containers/Data/Application/*/ | head -n1`

echo $lastUsedSimulatorAndApplication

How do I convert a javascript object array to a string array of the object attribute I want?

If your array of objects is items, you can do:

_x000D_
_x000D_
var items = [{_x000D_
  id: 1,_x000D_
  name: 'john'_x000D_
}, {_x000D_
  id: 2,_x000D_
  name: 'jane'_x000D_
}, {_x000D_
  id: 2000,_x000D_
  name: 'zack'_x000D_
}];_x000D_
_x000D_
var names = items.map(function(item) {_x000D_
  return item['name'];_x000D_
});_x000D_
_x000D_
console.log(names);_x000D_
console.log(items);
_x000D_
_x000D_
_x000D_

Documentation: map()

How to compile a static library in Linux?

See Creating a shared and static library with the gnu compiler [gcc]

gcc -c -o out.o out.c

-c means to create an intermediary object file, rather than an executable.

ar rcs libout.a out.o

This creates the static library. r means to insert with replacement, c means to create a new archive, and s means to write an index. As always, see the man page for more info.

How do I rewrite URLs in a proxy response in NGINX

You can use the following nginx configuration example:

upstream adminhost {
  server adminhostname:8080;
}

server {
  listen 80;

  location ~ ^/admin/(.*)$ {
    proxy_pass http://adminhost/$1$is_args$args;
    proxy_redirect off;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Host $server_name;
  }
}

What is the difference between C++ and Visual C++?

C++ is a general-purpose programming language. It is regarded as a middle-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell Labs as an enhancement to the C programming language and originally named "C with Classes". It was renamed to C++ in 1983.

C++ is widely used in the software industry. Some of its application domains include systems software, application software, device drivers, embedded software, high-performance server and client applications, and entertainment software such as video games. Several groups provide both free and proprietary C++ compiler software, including the GNU Project, Microsoft, Intel, Borland and others.


Microsoft Visual C++ (often abbreviated as MSVC or VC++) is an integrated development environment (IDE) product from Microsoft for the C, C++, and C++/CLI programming languages. MSVC is proprietary software; it was originally a standalone product but later became a part of Visual Studio and made available in both trialware and freeware forms. It features tools for developing and debugging C++ code, especially code written for Windows API, DirectX and .NET Framework.


So the main difference between them is that they are different things. The former is a programming language, while the latter is a commercial integrated development environment (IDE).

Vim: faster way to select blocks of text in visual mode

You can press vi} to select the block surrounded with {} brackets where your cursor is currently located.

It doesn't really matter where you are inside that block (just make sure you are in the outermost one). Also you can change { to anything that has a pair like ) or ].

Color a table row with style="color:#fff" for displaying in an email

you can easily do like this:-

    <table>
    <thead>
        <tr>
          <th bgcolor="#5D7B9D"><font color="#fff">Header 1</font></th>
          <th bgcolor="#5D7B9D"><font color="#fff">Header 2</font></th>
           <th bgcolor="#5D7B9D"><font color="#fff">Header 3</font></th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>blah blah</td>
            <td>blah blah</td>
            <td>blah blah</td>
        </tr>
    </tbody>
</table>

Demo:- http://jsfiddle.net/VWdxj/7/

Convert a dataframe to a vector (by rows)

You can try as.vector(t(test)). Please note that, if you want to do it by columns you should use unlist(test).

show distinct column values in pyspark dataframe: python

If you want to select ALL(columns) data as distinct frrom a DataFrame (df), then

df.select('*').distinct().show(10,truncate=False)

How to replace item in array?

var items = Array(523,3452,334,31,5346);

If you know the value then use,

items[items.indexOf(334)] = 1010;

If you want to know that value is present or not, then use,

var point = items.indexOf(334);

if (point !== -1) {
    items[point] = 1010;
}

If you know the place (position) then directly use,

items[--position] = 1010;

If you want replace few elements, and you know only starting position only means,

items.splice(2, 1, 1010, 1220);

for more about .splice

How to get request url in a jQuery $.get/ajax request

Since jQuery.get is just a shorthand for jQuery.ajax, another way would be to use the latter one's context option, as stated in the documentation:

The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.

So you would use

$.ajax('http://www.example.org', {
  dataType: 'xml',
  data: {'a':1,'b':2,'c':3},
  context: {
    url: 'http://www.example.org'
  }
}).done(function(xml) {alert(this.url});

Scroll RecyclerView to show selected item on top

If you want to scroll automatic without show scroll motion then you need to write following code:

mRecyclerView.getLayoutManager().scrollToPosition(position);

If you want to display scroll motion then you need to add following code. =>Step 1: You need to declare SmoothScroller.

RecyclerView.SmoothScroller smoothScroller = new
                LinearSmoothScroller(this.getApplicationContext()) {
                    @Override
                    protected int getVerticalSnapPreference() {
                        return LinearSmoothScroller.SNAP_TO_START;
                    }
                };

=>step 2: You need to add this code any event you want to perform scroll to specific position. =>First you need to set target position to SmoothScroller.

smoothScroller.setTargetPosition(position);

=>Then you need to set SmoothScroller to LayoutManager.

mRecyclerView.getLayoutManager().startSmoothScroll(smoothScroller);

Templated check for the existence of a class member function?

Here are some usage snippets: *The guts for all this are farther down

Check for member x in a given class. Could be var, func, class, union, or enum:

CREATE_MEMBER_CHECK(x);
bool has_x = has_member_x<class_to_check_for_x>::value;

Check for member function void x():

//Func signature MUST have T as template variable here... simpler this way :\
CREATE_MEMBER_FUNC_SIG_CHECK(x, void (T::*)(), void__x);
bool has_func_sig_void__x = has_member_func_void__x<class_to_check_for_x>::value;

Check for member variable x:

CREATE_MEMBER_VAR_CHECK(x);
bool has_var_x = has_member_var_x<class_to_check_for_x>::value;

Check for member class x:

CREATE_MEMBER_CLASS_CHECK(x);
bool has_class_x = has_member_class_x<class_to_check_for_x>::value;

Check for member union x:

CREATE_MEMBER_UNION_CHECK(x);
bool has_union_x = has_member_union_x<class_to_check_for_x>::value;

Check for member enum x:

CREATE_MEMBER_ENUM_CHECK(x);
bool has_enum_x = has_member_enum_x<class_to_check_for_x>::value;

Check for any member function x regardless of signature:

CREATE_MEMBER_CHECK(x);
CREATE_MEMBER_VAR_CHECK(x);
CREATE_MEMBER_CLASS_CHECK(x);
CREATE_MEMBER_UNION_CHECK(x);
CREATE_MEMBER_ENUM_CHECK(x);
CREATE_MEMBER_FUNC_CHECK(x);
bool has_any_func_x = has_member_func_x<class_to_check_for_x>::value;

OR

CREATE_MEMBER_CHECKS(x);  //Just stamps out the same macro calls as above.
bool has_any_func_x = has_member_func_x<class_to_check_for_x>::value;

Details and core:

/*
    - Multiple inheritance forces ambiguity of member names.
    - SFINAE is used to make aliases to member names.
    - Expression SFINAE is used in just one generic has_member that can accept
      any alias we pass it.
*/

//Variadic to force ambiguity of class members.  C++11 and up.
template <typename... Args> struct ambiguate : public Args... {};

//Non-variadic version of the line above.
//template <typename A, typename B> struct ambiguate : public A, public B {};

template<typename A, typename = void>
struct got_type : std::false_type {};

template<typename A>
struct got_type<A> : std::true_type {
    typedef A type;
};

template<typename T, T>
struct sig_check : std::true_type {};

template<typename Alias, typename AmbiguitySeed>
struct has_member {
    template<typename C> static char ((&f(decltype(&C::value))))[1];
    template<typename C> static char ((&f(...)))[2];

    //Make sure the member name is consistently spelled the same.
    static_assert(
        (sizeof(f<AmbiguitySeed>(0)) == 1)
        , "Member name specified in AmbiguitySeed is different from member name specified in Alias, or wrong Alias/AmbiguitySeed has been specified."
    );

    static bool const value = sizeof(f<Alias>(0)) == 2;
};

Macros (El Diablo!):

CREATE_MEMBER_CHECK:

//Check for any member with given name, whether var, func, class, union, enum.
#define CREATE_MEMBER_CHECK(member)                                         \
                                                                            \
template<typename T, typename = std::true_type>                             \
struct Alias_##member;                                                      \
                                                                            \
template<typename T>                                                        \
struct Alias_##member <                                                     \
    T, std::integral_constant<bool, got_type<decltype(&T::member)>::value>  \
> { static const decltype(&T::member) value; };                             \
                                                                            \
struct AmbiguitySeed_##member { char member; };                             \
                                                                            \
template<typename T>                                                        \
struct has_member_##member {                                                \
    static const bool value                                                 \
        = has_member<                                                       \
            Alias_##member<ambiguate<T, AmbiguitySeed_##member>>            \
            , Alias_##member<AmbiguitySeed_##member>                        \
        >::value                                                            \
    ;                                                                       \
}

CREATE_MEMBER_VAR_CHECK:

//Check for member variable with given name.
#define CREATE_MEMBER_VAR_CHECK(var_name)                                   \
                                                                            \
template<typename T, typename = std::true_type>                             \
struct has_member_var_##var_name : std::false_type {};                      \
                                                                            \
template<typename T>                                                        \
struct has_member_var_##var_name<                                           \
    T                                                                       \
    , std::integral_constant<                                               \
        bool                                                                \
        , !std::is_member_function_pointer<decltype(&T::var_name)>::value   \
    >                                                                       \
> : std::true_type {}

CREATE_MEMBER_FUNC_SIG_CHECK:

//Check for member function with given name AND signature.
#define CREATE_MEMBER_FUNC_SIG_CHECK(func_name, func_sig, templ_postfix)    \
                                                                            \
template<typename T, typename = std::true_type>                             \
struct has_member_func_##templ_postfix : std::false_type {};                \
                                                                            \
template<typename T>                                                        \
struct has_member_func_##templ_postfix<                                     \
    T, std::integral_constant<                                              \
        bool                                                                \
        , sig_check<func_sig, &T::func_name>::value                         \
    >                                                                       \
> : std::true_type {}

CREATE_MEMBER_CLASS_CHECK:

//Check for member class with given name.
#define CREATE_MEMBER_CLASS_CHECK(class_name)               \
                                                            \
template<typename T, typename = std::true_type>             \
struct has_member_class_##class_name : std::false_type {};  \
                                                            \
template<typename T>                                        \
struct has_member_class_##class_name<                       \
    T                                                       \
    , std::integral_constant<                               \
        bool                                                \
        , std::is_class<                                    \
            typename got_type<typename T::class_name>::type \
        >::value                                            \
    >                                                       \
> : std::true_type {}

CREATE_MEMBER_UNION_CHECK:

//Check for member union with given name.
#define CREATE_MEMBER_UNION_CHECK(union_name)               \
                                                            \
template<typename T, typename = std::true_type>             \
struct has_member_union_##union_name : std::false_type {};  \
                                                            \
template<typename T>                                        \
struct has_member_union_##union_name<                       \
    T                                                       \
    , std::integral_constant<                               \
        bool                                                \
        , std::is_union<                                    \
            typename got_type<typename T::union_name>::type \
        >::value                                            \
    >                                                       \
> : std::true_type {}

CREATE_MEMBER_ENUM_CHECK:

//Check for member enum with given name.
#define CREATE_MEMBER_ENUM_CHECK(enum_name)                 \
                                                            \
template<typename T, typename = std::true_type>             \
struct has_member_enum_##enum_name : std::false_type {};    \
                                                            \
template<typename T>                                        \
struct has_member_enum_##enum_name<                         \
    T                                                       \
    , std::integral_constant<                               \
        bool                                                \
        , std::is_enum<                                     \
            typename got_type<typename T::enum_name>::type  \
        >::value                                            \
    >                                                       \
> : std::true_type {}

CREATE_MEMBER_FUNC_CHECK:

//Check for function with given name, any signature.
#define CREATE_MEMBER_FUNC_CHECK(func)          \
template<typename T>                            \
struct has_member_func_##func {                 \
    static const bool value                     \
        = has_member_##func<T>::value           \
        && !has_member_var_##func<T>::value     \
        && !has_member_class_##func<T>::value   \
        && !has_member_union_##func<T>::value   \
        && !has_member_enum_##func<T>::value    \
    ;                                           \
}

CREATE_MEMBER_CHECKS:

//Create all the checks for one member.  Does NOT include func sig checks.
#define CREATE_MEMBER_CHECKS(member)    \
CREATE_MEMBER_CHECK(member);            \
CREATE_MEMBER_VAR_CHECK(member);        \
CREATE_MEMBER_CLASS_CHECK(member);      \
CREATE_MEMBER_UNION_CHECK(member);      \
CREATE_MEMBER_ENUM_CHECK(member);       \
CREATE_MEMBER_FUNC_CHECK(member)

How can I check if a string contains a character in C#?

The following should work:

var abc = "sAb";
bool exists = abc.IndexOf("ab", StringComparison.CurrentCultureIgnoreCase) > -1;

Is there a macro to conditionally copy rows to another worksheet?

If this is just a one-off exercise, as an easier alternative, you could apply filters to your source data, and then copy and paste the filtered rows into your new worksheet?

How to check which PHP extensions have been enabled/disabled in Ubuntu Linux 12.04 LTS?

Checking for installed php modules and packages

In addition to running

php -m

to get the list of installed php modules, you will probably find it helpful to get the list of the currently installed php packages in Ubuntu:

sudo dpkg --get-selections | grep -v deinstall | grep php

This is helpful since Ubuntu makes php modules available via packages.

You can then install the needed modules by selecting from the available Ubuntu php packages, which you can view by running:

sudo apt-cache search php | grep "^php5-"

Or, for Ubuntu 16.04 and higher:

sudo apt-cache search php | grep "^php7"

As you have mentioned, there is plenty of information available on the actual installation of the packages that you might require, so I won't go into detail about that here.

Related: Enabling / disabling installed php modules

It is possible that an installed module has been disabled. In that case, it won't show up when running php -m, but it will show up in the list of installed Ubuntu packages.

Modules can be enabled/disabled via the php5enmod tool (phpenmod on later distros) which is part of the php-common package.

Ubuntu 12.04:

Enabled modules are symlinked in /etc/php5/conf.d

Ubuntu 12.04: (with PHP 5.4+)

To enable an installed module:

php5enmod <modulename>

To disable an installed module:

php5dismod <modulename>

Ubuntu 16.04 (php7) and higher:

To enable an installed module:

phpenmod <modulename>

To disable an installed module:

phpdismod <modulename>

Reload Apache

Remember to reload Apache2 after enabling/disabling:

service apache2 reload

ORDER BY date and time BEFORE GROUP BY name in mysql

This is not the exact answer, but this might be helpful for the people looking to solve some problem with the approach of ordering row before group by in mysql.

I came to this thread, when I wanted to find the latest row(which is order by date desc but get the only one result for a particular column type, which is group by column name).

One other approach to solve such problem is to make use of aggregation.

So, we can let the query run as usual, which sorted asc and introduce new field as max(doc) as latest_doc, which will give the latest date, with grouped by the same column.

Suppose, you want to find the data of a particular column now and max aggregation cannot be done. In general, to finding the data of a particular column, you can make use of GROUP_CONCAT aggregator, with some unique separator which can't be present in that column, like GROUP_CONCAT(string SEPARATOR ' ') as new_column, and while you're accessing it, you can split/explode the new_column field.

Again, this might not sound to everyone. I did it, and liked it as well because I had written few functions and I couldn't run subqueries. I am working on codeigniter framework for php.

Not sure of the complexity as well, may be someone can put some light on that.

Regards :)

How can I use a reportviewer control in an asp.net mvc 3 razor view?

The following solution works only for single page reports. Refer to comments for more details.

ReportViewer is a server control and thus can not be used within a razor view. However you can add a ASPX view page, view user control or traditional web form that containing a ReportViewer into the application.

You will need to ensure that you have added the relevant handler into your web.config.

If you use a ASPX view page or view user control you will need to set AsyncRendering to false to get the report to display properly.

Update:

Added more sample code. Note there are no meaningful changes required in Global.asax.

Web.Config

Mine ended up as follows:

<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=152368
  -->

<configuration>
  <appSettings>
    <add key="webpages:Version" value="1.0.0.0"/>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
  </appSettings>

  <system.web>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
        <add assembly="Microsoft.ReportViewer.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
      </assemblies>
    </compilation>

    <authentication mode="Forms">
      <forms loginUrl="~/Account/LogOn" timeout="2880" />
    </authentication>

    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages"/>
      </namespaces>
    </pages>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules runAllManagedModulesForAllRequests="true"/>
    <handlers>
      <add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    </handlers>
  </system.webServer>

  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

Controller

The controller actions are very simple.

As a bonus the File() action returns the output of "TestReport.rdlc" as a PDF file.

using System.Web.Mvc;
using Microsoft.Reporting.WebForms;

...

public class PDFController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public FileResult File()
    {
        ReportViewer rv = new Microsoft.Reporting.WebForms.ReportViewer();
        rv.ProcessingMode = ProcessingMode.Local;
        rv.LocalReport.ReportPath = Server.MapPath("~/Reports/TestReport.rdlc");
        rv.LocalReport.Refresh();

        byte[] streamBytes = null;
        string mimeType = "";
        string encoding = "";
        string filenameExtension = "";
        string[] streamids = null;
        Warning[] warnings = null;

        streamBytes = rv.LocalReport.Render("PDF", null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings);

        return File(streamBytes, mimeType, "TestReport.pdf");
    }

    public ActionResult ASPXView()
    {
        return View();
    }

    public ActionResult ASPXUserControl()
    {
        return View();
    }
}

ASPXView.apsx

The ASPXView is as follows.

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<%@ Register Assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
    Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>

<!DOCTYPE html>

<html>
<head runat="server">
    <title>ASPXView</title>
</head>
<body>
    <div>
        <script runat="server">
            private void Page_Load(object sender, System.EventArgs e)
            {
                ReportViewer1.LocalReport.ReportPath = Server.MapPath("~/Reports/TestReport.rdlc");
                ReportViewer1.LocalReport.Refresh();
            }
        </script>
        <form id="Form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server">          
        </asp:ScriptManager>
        <rsweb:reportviewer id="ReportViewer1" runat="server" height="500" width="500" AsyncRendering="false"></rsweb:reportviewer>
        </form>        
    </div>
</body>
</html>

ViewUserControl1.ascx

The ASPX user control looks like:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%@ Register Assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
    Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>
<script runat="server">
  private void Page_Load(object sender, System.EventArgs e)
  {
      ReportViewer1.LocalReport.ReportPath = Server.MapPath("~/Reports/TestReport.rdlc");
      ReportViewer1.LocalReport.Refresh();
  }
</script>
<form id="Form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<rsweb:ReportViewer ID="ReportViewer1" runat="server" AsyncRendering="false"></rsweb:ReportViewer>
</form>

ASPXUserControl.cshtml

Razor view. Requires ViewUserControl1.ascx.

@{
    ViewBag.Title = "ASPXUserControl";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>ASPXUserControl</h2>
@Html.Partial("ViewUserControl1")

References

http://blogs.msdn.com/b/sajoshi/archive/2010/06/16/asp-net-mvc-handling-ssrs-reports-with-reportviewer-part-i.aspx

bind report to reportviewer in web mvc2

Comparing floating point number to zero

Like @Exceptyon pointed out, this function is 'relative' to the values you're comparing. The Epsilon * abs(x) measure will scale based on the value of x, so that you'll get a comparison result as accurately as epsilon, irrespective of the range of values in x or y.

If you're comparing zero(y) to another really small value(x), say 1e-8, abs(x-y) = 1e-8 will still be much larger than epsilon *abs(x) = 1e-13. So unless you're dealing with extremely small number that can't be represented in a double type, this function should do the job and will match zero only against +0 and -0.

The function seems perfectly valid for zero comparison. If you're planning to use it, I suggest you use it everywhere there're floats involved, and not have special cases for things like zero, just so that there's uniformity in the code.

ps: This is a neat function. Thanks for pointing to it.

jQuery: How to get the HTTP status code from within the $.ajax.error method?

You should create a map of actions using the statusCode setting:

$.ajax({
  statusCode: {
    400: function() {
      alert('400 status code! user error');
    },
    500: function() {
      alert('500 status code! server error');
    }
  }
});

Reference (Scroll to: 'statusCode')

EDIT (In response to comments)

If you need to take action based on the data returned in the response body (which seems odd to me), you will need to use error: instead of statusCode:

error:function (xhr, ajaxOptions, thrownError){
    switch (xhr.status) {
        case 404:
             // Take action, referencing xhr.responseText as needed.
    }
} 

`getchar()` gives the same output as the input string

There is an underlying buffer/stream that getchar() and friends read from. When you enter text, the text is stored in a buffer somewhere. getchar() can stream through it one character at a time. Each read returns the next character until it reaches the end of the buffer. The reason it's not asking you for subsequent characters is that it can fetch the next one from the buffer.

If you run your script and type directly into it, it will continue to prompt you for input until you press CTRL+D (end of file). If you call it like ./program < myInput where myInput is a text file with some data, it will get the EOF when it reaches the end of the input. EOF isn't a character that exists in the stream, but a sentinel value to indicate when the end of the input has been reached.

As an extra warning, I believe getchar() will also return EOF if it encounters an error, so you'll want to check ferror(). Example below (not tested, but you get the idea).

main() {
    int c;
    do {
        c = getchar();
        if (c == EOF && ferror()) {
            perror("getchar");
        }
        else {
            putchar(c);
        }
    }
    while(c != EOF);
}

apache ProxyPass: how to preserve original IP address

This has a more elegant explanation and more than one possible solutions. http://kasunh.wordpress.com/2011/10/11/preserving-remote-iphost-while-proxying/

The post describes how to use one popular and one lesser known Apache modules to preserve host/ip while in a setup involving proxying.

Use mod_rpaf module, install and enable it in the backend server and add following directives in the module’s configuration. RPAFenable On
RPAFsethostname On
RPAFproxy_ips 127.0.0.1

(2017 edit) Current location of mod_rpaf: https://github.com/gnif/mod_rpaf

Command for restarting all running docker containers?

Just run

docker restart $(docker ps -q)

Update

For Docker 1.13.1 use docker restart $(docker ps -a -q) as in answer lower.

height style property doesn't work in div elements

I'm told that it's bad practice to overuse it, but you can always add !important after your code to prioritize the css properties value.

.p{height:400px!important;}

How does the stack work in assembly language?

You confuse an abstract stack and the hardware implemented stack. The latter is already implemented.

How can I use a JavaScript variable as a PHP variable?

I had the same problem a few weeks ago like yours; but I invented a brilliant solution for exchanging variables between PHP and JavaScript. It worked for me well:

  1. Create a hidden form on a HTML page

  2. Create a Textbox or Textarea in that hidden form

  3. After all of your code written in the script, store the final value of your variable in that textbox

  4. Use $_REQUEST['textbox name'] line in your PHP to gain access to value of your JavaScript variable.

I hope this trick works for you.

Why doesn't list have safe "get" method like dictionary?

Probably because it just didn't make much sense for list semantics. However, you can easily create your own by subclassing.

class safelist(list):
    def get(self, index, default=None):
        try:
            return self.__getitem__(index)
        except IndexError:
            return default

def _test():
    l = safelist(range(10))
    print l.get(20, "oops")

if __name__ == "__main__":
    _test()

How to count the number of rows in excel with data?

These would both work as well, letting Excel define the last time it sees data

numofrows = destsheet.UsedRange.SpecialCells(xlLastCell).row

numofrows = destsheet.Cells.SpecialCells(xlLastCell).row

How do I specify "close existing connections" in sql script

According to the ALTER DATABASE SET documentation, there is still a possibility that after setting a database to SINGLE_USER mode you won't be able to access that database:

Before you set the database to SINGLE_USER, verify the AUTO_UPDATE_STATISTICS_ASYNC option is set to OFF. When set to ON, the background thread used to update statistics takes a connection against the database, and you will be unable to access the database in single-user mode.

So, a complete script to drop the database with existing connections may look like this:

DECLARE @dbId int
DECLARE @isStatAsyncOn bit
DECLARE @jobId int
DECLARE @sqlString nvarchar(500)

SELECT @dbId = database_id,
       @isStatAsyncOn = is_auto_update_stats_async_on
FROM sys.databases
WHERE name = 'db_name'

IF @isStatAsyncOn = 1
BEGIN
    ALTER DATABASE [db_name] SET  AUTO_UPDATE_STATISTICS_ASYNC OFF

    -- kill running jobs
    DECLARE jobsCursor CURSOR FOR
    SELECT job_id
    FROM sys.dm_exec_background_job_queue
    WHERE database_id = @dbId

    OPEN jobsCursor

    FETCH NEXT FROM jobsCursor INTO @jobId
    WHILE @@FETCH_STATUS = 0
    BEGIN
        set @sqlString = 'KILL STATS JOB ' + STR(@jobId)
        EXECUTE sp_executesql @sqlString
        FETCH NEXT FROM jobsCursor INTO @jobId
    END

    CLOSE jobsCursor
    DEALLOCATE jobsCursor
END

ALTER DATABASE [db_name] SET  SINGLE_USER WITH ROLLBACK IMMEDIATE

DROP DATABASE [db_name]

Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList?

In Java 8 you can use Files.write() method with two arguments: Path and List<String>, something like this:

List<String> clubNames = clubs.stream()
    .map(Club::getName)
    .collect(Collectors.toList())

try {
    Files.write(Paths.get(fileName), clubNames);
} catch (IOException e) {
    log.error("Unable to write out names", e);
}

How can I stream webcam video with C#?

I've used VideoCapX for our project. It will stream out as MMS/ASF stream which can be open by media player. You can then embed media player into your webpage.

If you won't need much control, or if you want to try out VideoCapX without writing a code, try U-Broadcast, they use VideoCapX behind the scene.

Oracle Not Equals Operator

They are the same (as is the third form, ^=).

Note, though, that they are still considered different from the point of view of the parser, that is a stored outline defined for a != won't match <> or ^=.

This is unlike PostgreSQL where the parser treats != and <> yet on parsing stage, so you cannot overload != and <> to be different operators.

Compiling dynamic HTML strings from database

Found in a google discussion group. Works for me.

var $injector = angular.injector(['ng', 'myApp']);
$injector.invoke(function($rootScope, $compile) {
  $compile(element)($rootScope);
});

What is the difference between concurrency and parallelism?

Concurrency is the generalized form of parallelism. For example parallel program can also be called concurrent but reverse is not true.

  1. Concurrent execution is possible on single processor (multiple threads, managed by scheduler or thread-pool)

  2. Parallel execution is not possible on single processor but on multiple processors. (One process per processor)

  3. Distributed computing is also a related topic and it can also be called concurrent computing but reverse is not true, like parallelism.

For details read this research paper Concepts of Concurrent Programming

Check if number is prime number

I'm trying to get some efficiency out of early exit when using Any()...

    public static bool IsPrime(long n)
    {
        if (n == 1) return false;
        if (n == 3) return true;

        //Even numbers are not primes
        if (n % 2 == 0) return false;

        return !Enumerable.Range(2, Convert.ToInt32(Math.Ceiling(Math.Sqrt(n))))
            .Any(x => n % x == 0);
    }

jQuery find element by data attribute value

You can also use .filter()

$('.slide-link').filter('[data-slide="0"]').addClass('active');

Docker expose all ports or range of ports from 7000 to 8000

Since Docker 1.5 you can now expose a range of ports to other linked containers using:

The Dockerfile EXPOSE command:

EXPOSE 7000-8000

or The Docker run command:

docker run --expose=7000-8000

Or instead you can publish a range of ports to the host machine via Docker run command:

docker run -p 7000-8000:7000-8000

What is the preferred Bash shebang?

I recommend using:

#!/bin/bash

It's not 100% portable (some systems place bash in a location other than /bin), but the fact that a lot of existing scripts use #!/bin/bash pressures various operating systems to make /bin/bash at least a symlink to the main location.

The alternative of:

#!/usr/bin/env bash

has been suggested -- but there's no guarantee that the env command is in /usr/bin (and I've used systems where it isn't). Furthermore, this form will use the first instance of bash in the current users $PATH, which might not be a suitable version of the bash shell.

(But /usr/bin/env should work on any reasonably modern system, either because env is in /usr/bin or because the system does something to make it work. The system I referred to above was SunOS 4, which I probably haven't used in about 25 years.)

If you need a script to run on a system that doesn't have /bin/bash, you can modify the script to point to the correct location (that's admittedly inconvenient).

I've discussed the tradeoffs in greater depth in my answer to this question.

A somewhat obscure update: One system I use, Termux, a desktop-Linux-like layer that runs under Android, doesn't have /bin/bash (bash is /data/data/com.termux/files/usr/bin/bash) -- but it has special handling to support #!/bin/bash.

How ViewBag in ASP.NET MVC works

It's a dynamic object, meaning you can add properties to it in the controller, and read them later in the view, because you are essentially creating the object as you do, a feature of the dynamic type. See this MSDN article on dynamics. See this article on it's usage in relation to MVC.

If you wanted to use this for web forms, add a dynamic property to a base page class like so:

public class BasePage : Page
{

    public dynamic ViewBagProperty
    {
        get;
        set;
    }
}

Have all of your pages inherit from this. You should be able to, in your ASP.NET markup, do:

<%= ViewBagProperty.X %>

That should work. If not, there are ways to work around it.

What is an optional value in Swift?

When i started to learn Swift it was very difficult to realize why optional.

Lets think in this way. Let consider a class Person which has two property name and company.

class Person: NSObject {
    
    var name : String //Person must have a value so its no marked as optional
    var companyName : String? ///Company is optional as a person can be unemployed that is nil value is possible
    
    init(name:String,company:String?) {
        
        self.name = name
        self.companyName = company
        
    }
}

Now lets create few objects of Person

var tom:Person = Person.init(name: "Tom", company: "Apple")//posible
var bob:Person = Person.init(name: "Bob", company:nil) // also Possible because company is marked as optional so we can give Nil

But we can not pass Nil to name

var personWithNoName:Person = Person.init(name: nil, company: nil)

Now Lets talk about why we use optional?. Lets consider a situation where we want to add Inc after company name like apple will be apple Inc. We need to append Inc after company name and print.

print(tom.companyName+" Inc") ///Error saying optional is not unwrapped.
print(tom.companyName!+" Inc") ///Error Gone..we have forcefully unwrap it which is wrong approach..Will look in Next line
print(bob.companyName!+" Inc") ///Crash!!!because bob has no company and nil can be unwrapped.

Now lets study why optional takes into place.

if let companyString:String = bob.companyName{///Compiler safely unwrap company if not nil.If nil,no unwrap.
    
    print(companyString+" Inc") //Will never executed and no crash!!!
}

Lets replace bob with tom

if let companyString:String = tom.companyName{///Compiler safely unwrap company if not nil.If nil,no unwrap.
    
    print(companyString+" Inc") //Will executed and no crash!!!
}

And Congratulation! we have properly deal with optional?

So the realization points are

  1. We will mark a variable as optional if its possible to be nil
  2. If we want to use this variable somewhere in code compiler will remind you that we need to check if we have proper deal with that variable if it contain nil.

Thank you...Happy Coding

Errno 13 Permission denied Python

If you have this problem in Windows 10, and you know you have premisions on folder (You could write before but it just started to print exception PermissionError recently).. You will need to install Windows updates... I hope someone will help this info.

Node.js heap out of memory

For other beginners like me, who didn't find any suitable solution for this error, check the node version installed (x32, x64, x86). I have a 64-bit CPU and I've installed x86 node version, which caused the CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory error.

What does the servlet <load-on-startup> value signify

--> (Absence of load-on-start-up) tag First of all when ever servlet is deployed in the server, It is the responsibility of the server to creates the servlet object. Eg: Suppose Servlet is deployed in the server ,(Servlet Object is not available in server) client sends the request to the servlet for the first time then server creates the servlet object with help of default constructor and immediately calls init() . From that when ever client sends the request only service method will get executed as object is already available

If load-on-start-up tag is used in deployment descriptor: At the time of deployment itself the server creates the servlet object for the servlets based on the positive value provided in between the tags. The Creation of objects for the servlet classes will follow from 0-128 0 number servlet will be created first and followed by other numbers.

If we provide same value for two servlets in web.xml then creation of objects will be done based on the position of classes in web.xml also varies from server to server.

If we provide negative value in between the load on start up tag then server wont create the servlet object.

Other Scenarios where server creates the object for servlet.

If we dont use load on start up tag in web.xml, then project is deployed when ever client sends the request for the first time server creates the object and server is responsible for calling its life cycle methods. Then if a .class is been modified in the server(tomcat). again client sends the request for modified servlet but in case of tomcat new object will not created and server make use of existing object unless restart of server takes place. But in class of web-logic when ever .class file is modified in the server with out restarting the server if it receives a request then server calls the destroy method on existing servlet and creates a new servlet object and calls init() for its initilization.

Converting milliseconds to minutes and seconds with Javascript

function millisToMinutesAndSeconds(millis) {
  var minutes = Math.floor(millis / 60000);
  var seconds = ((millis % 60000) / 1000).toFixed(0);
  return minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
}

millisToMinutesAndSeconds(298999); // "4:59"
millisToMinutesAndSeconds(60999);  // "1:01"

As User HelpingHand pointed in the comments the return statement should be

return (seconds == 60 ? (minutes+1) + ":00" : minutes + ":" + (seconds < 10 ? "0" : "") + seconds);

Update React component every second

So you were on the right track. Inside your componentDidMount() you could have finished the job by implementing setInterval() to trigger the change, but remember the way to update a components state is via setState(), so inside your componentDidMount() you could have done this:

componentDidMount() {
  setInterval(() => {
   this.setState({time: Date.now()})    
  }, 1000)
}

Also, you use Date.now() which works, with the componentDidMount() implementation I offered above, but you will get a long set of nasty numbers updating that is not human readable, but it is technically the time updating every second in milliseconds since January 1, 1970, but we want to make this time readable to how we humans read time, so in addition to learning and implementing setInterval you want to learn about new Date() and toLocaleTimeString() and you would implement it like so:

class TimeComponent extends Component {
  state = { time: new Date().toLocaleTimeString() };
}

componentDidMount() {
  setInterval(() => {
   this.setState({ time: new Date().toLocaleTimeString() })    
  }, 1000)
}

Notice I also removed the constructor() function, you do not necessarily need it, my refactor is 100% equivalent to initializing site with the constructor() function.

Sort an ArrayList based on an object field

You can use the Bean Comparator to sort on any property in your custom class.

How to fix 'Notice: Undefined index:' in PHP form action

Simply

if(isset($_POST['filename'])){
 $filename = $_POST['filename'];
 echo $filename;
}
else{
 echo "POST filename is not assigned";
}

Deep copy of a dict in python

I like and learned a lot from Lasse V. Karlsen. I modified it into the following example, which highlights pretty well the difference between shallow dictionary copies and deep copies:

    import copy

    my_dict = {'a': [1, 2, 3], 'b': [4, 5, 6]}
    my_copy = copy.copy(my_dict)
    my_deepcopy = copy.deepcopy(my_dict)

Now if you change

    my_dict['a'][2] = 7

and do

    print("my_copy a[2]: ",my_copy['a'][2],",whereas my_deepcopy a[2]: ", my_deepcopy['a'][2])

you get

    >> my_copy a[2]:  7 ,whereas my_deepcopy a[2]:  3

merge two object arrays with Angular 2 and TypeScript?

try this

 data => {
                this.results = [...this.results, ...data.results];
                this._next = data.next;
            }

Concatenating multiple text files into a single file in Bash

all of that is nasty....

ls | grep *.txt | while read file; do cat $file >> ./output.txt; done;

easy stuff.

Login with facebook android sdk app crash API 4

The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):

Mikhail,

The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.

Good luck with your implementation.

How do you easily create empty matrices javascript?

Here's one, no looping:

(Math.pow(10, 20)+'').replace((/0/g),'1').split('').map(parseFloat);

Fill the '20' for length, use the (optional) regexp for handy transforms and map to ensure datatype. I added a function to the Array prototype to easily pull the parameters of 'map' into your functions.. bit risky, some people strongly oppose touching native prototypes, but it does come in handy..

    Array.prototype.$args = function(idx) {
        idx || (idx = 0);
        return function() {
            return arguments.length > idx ? arguments[idx] : null;
        };
    };

// Keys
(Math.pow(10, 20)+'').replace((/0/g),'1').split('').map(this.$args(1));
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

// Matrix
(Math.pow(10, 9)+'').replace((/0/g),'1').split('').map(this.$args(1)).map(this.$args(2))

datetime dtypes in pandas read_csv

I tried using the dtypes=[datetime, ...] option, but

import pandas as pd
from datetime import datetime
headers = ['col1', 'col2', 'col3', 'col4'] 
dtypes = [datetime, datetime, str, float] 
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes)

I encountered the following error:

TypeError: data type not understood

The only change I had to make is to replace datetime with datetime.datetime

import pandas as pd
from datetime import datetime
headers = ['col1', 'col2', 'col3', 'col4'] 
dtypes = [datetime.datetime, datetime.datetime, str, float] 
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes)

Confirm deletion in modal / dialog using Twitter Bootstrap?

I found this useful and easy to use, plus it looks pretty: http://maxailloud.github.io/confirm-bootstrap/.

To use it, include the .js file in your page then run:

$('your-link-selector').confirmModal();

There are various options you can apply to it, to make it look better when doing it to confirm a delete, I use:

$('your-link-selector').confirmModal({
    confirmTitle: 'Please confirm',
    confirmMessage: 'Are you sure you want to delete this?',
    confirmStyle: 'danger',
    confirmOk: '<i class="icon-trash icon-white"></i> Delete',
    confirmCallback: function (target) {
         //perform the deletion here, or leave this option
         //out to just follow link..
    }
});

How to iterate over arguments in a Bash script

Use "$@" to represent all the arguments:

for var in "$@"
do
    echo "$var"
done

This will iterate over each argument and print it out on a separate line. $@ behaves like $* except that when quoted the arguments are broken up properly if there are spaces in them:

sh test.sh 1 2 '3 4'
1
2
3 4

How do I position a div at the bottom center of the screen

If you aren't comfortable with using negative margins, check this out.

div {
  position: fixed;
  left: 50%;
  bottom: 20px;
  transform: translate(-50%, -50%);
  margin: 0 auto;
}
<div>
  Your Text
</div>

Especially useful when you don't know the width of the div.


align="center" has no effect.

Since you have position:absolute, I would recommend positioning it 50% from the left and then subtracting half of its width from its left margin.

#manipulate {
    position:absolute;
    width:300px;
    height:300px;
    background:#063;
    bottom:0px;
    right:25%;
    left:50%;
    margin-left:-150px;
}

Linux c++ error: undefined reference to 'dlopen'

@Masci is correct, but in case you're using C (and the gcc compiler) take in account that this doesn't work:

gcc -ldl dlopentest.c

But this does:

gcc dlopentest.c -ldl

Took me a bit to figure out...

ASP.NET MVC passing an ID in an ActionLink to the controller

On MVC 5 is quite similar

@Html.ActionLink("LinkText", "ActionName", new { id = "id" })

How to get the Enum Index value in C#

Use simple casting:

int value = (int) enum.item;

Refer to enum (C# Reference)

Removing pip's cache?

On archlinux pip cache is located at ~/.cache/pip, I could solve my issue by removing the http folder inside it.

Cross field validation with Hibernate Validator (JSR 303)

You need to call it explicitly. In the example above, bradhouse has given you all the steps to write a custom constraint.

Add this code in your caller class.

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();

Set<ConstraintViolation<yourObjectClass>> constraintViolations = validator.validate(yourObject);

in the above case it would be

Set<ConstraintViolation<AccountCreateForm>> constraintViolations = validator.validate(objAccountCreateForm);

TypeError: no implicit conversion of Symbol into Integer

This error shows up when you are treating an array or string as a Hash. In this line myHash.each do |item| you are assigning item to a two-element array [key, value], so item[:symbol] throws an error.

How do I post form data with fetch api?

To quote MDN on FormData (emphasis mine):

The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data".

So when using FormData you are locking yourself into multipart/form-data. There is no way to send a FormData object as the body and not sending data in the multipart/form-data format.

If you want to send the data as application/x-www-form-urlencoded you will either have to specify the body as an URL-encoded string, or pass a URLSearchParams object. The latter unfortunately cannot be directly initialized from a form element. If you don’t want to iterate through your form elements yourself (which you could do using HTMLFormElement.elements), you could also create a URLSearchParams object from a FormData object:

const data = new URLSearchParams();
for (const pair of new FormData(formElement)) {
    data.append(pair[0], pair[1]);
}

fetch(url, {
    method: 'post',
    body: data,
})
.then(…);

Note that you do not need to specify a Content-Type header yourself.


As noted by monk-time in the comments, you can also create URLSearchParams and pass the FormData object directly, instead of appending the values in a loop:

const data = new URLSearchParams(new FormData(formElement));

This still has some experimental support in browsers though, so make sure to test this properly before you use it.

jQuery: Setting select list 'selected' based on text, failing strangely

We can do it by searching the text in options of dropdown list and then by setting selected attribute to true.

This code is run in every environment.

 $("#numbers option:contains(" + inputText + ")").attr('selected', 'selected');

Postgresql : syntax error at or near "-"

I have reproduced the issue in my system,

postgres=# alter user my-sys with password 'pass11';
ERROR:  syntax error at or near "-"
LINE 1: alter user my-sys with password 'pass11';
                       ^

Here is the issue,

psql is asking for input and you have given again the alter query see postgres-#That's why it's giving error at alter

postgres-# alter user "my-sys" with password 'pass11';
ERROR:  syntax error at or near "alter"
LINE 2: alter user "my-sys" with password 'pass11';
        ^

Solution is as simple as the error,

postgres=# alter user "my-sys" with password 'pass11';
ALTER ROLE

node.js - request - How to "emitter.setMaxListeners()"?

I use the code to increase the default limit globally: require('events').EventEmitter.prototype._maxListeners = 100;

Spring boot: Unable to start embedded Tomcat servlet container

For me, the problem was in XML migrations. I deleted all tables and sequences and it works on next bootRun

Why use multiple columns as primary keys (composite primary key)

Your understanding is correct.

You would do this in many cases. One example is in a relationship like OrderHeader and OrderDetail. The PK in OrderHeader might be OrderNumber. The PK in OrderDetail might be OrderNumber AND LineNumber. If it was either of those two, it would not be unique, but the combination of the two is guaranteed unique.

The alternative is to use a generated (non-intelligent) primary key, for example in this case OrderDetailId. But then you would not always see the relationship as easily. Some folks prefer one way; some prefer the other way.

How to insert an image in python

Install PIL(Python Image Library) :

then:

from PIL import Image
myImage = Image.open("your_image_here");
myImage.show();

jQuery $.cookie is not a function

add this cookie plugin for jquery.

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>

How can I fix "Design editor is unavailable until a successful build" error?

If you are in corporate setting where there is a proxy server, double check your proxy settings.

  1. Go File -> Settings
  2. Search for Proxy.
  3. Fill out as appropreate.
  4. Test connection.

If you think you fat-fingered the password, there is a Clear passwords button you can click to where you can re-enter your creds. HTH

How to concat string + i?

Let me add another solution:

>> N = 5;
>> f = cellstr(num2str((1:N)', 'f%d'))
f = 
    'f1'
    'f2'
    'f3'
    'f4'
    'f5'

If N is more than two digits long (>= 10), you will start getting extra spaces. Add a call to strtrim(f) to get rid of them.


As a bonus, there is an undocumented built-in function sprintfc which nicely returns a cell arrays of strings:

>> N = 10;
>> f = sprintfc('f%d', 1:N)
f = 
    'f1'    'f2'    'f3'    'f4'    'f5'    'f6'    'f7'    'f8'    'f9'    'f10'

Netbeans - Error: Could not find or load main class

try this it work out for me perfectly go to project and right click on your java file at the right corner, go to properties, go to run, go to browse, and then select Main class. now you can run your program again.

finding and replacing elements in a list

I know this is a very old question and there's a myriad of ways to do it. The simpler one I found is using numpy package.

import numpy

arr = numpy.asarray([1, 6, 1, 9, 8])
arr[ arr == 8 ] = 0 # change all occurrences of 8 by 0
print(arr)

detect key press in python?

More things can be done with keyboard module. You can install this module using pip install keyboard Here are some of the methods:


Method #1:

Using the function read_key():

import keyboard

while True:
    if keyboard.read_key() == "p":
        print("You pressed p")
        break

This is gonna break the loop as the key p is pressed.


Method #2:

Using function wait:

import keyboard

keyboard.wait("p")
print("You pressed p")

It will wait for you to press p and continue the code as it is pressed.


Method #3:

Using the function on_press_key:

import keyboard

keyboard.on_press_key("p", lambda _:print("You pressed p"))

It needs a callback function. I used _ because the keyboard function returns the keyboard event to that function.

Once executed, it will run the function when the key is pressed. You can stop all hooks by running this line:

keyboard.unhook_all()

Method #4:

This method is sort of already answered by user8167727 but I disagree with the code they made. It will be using the function is_pressed but in an other way:

import keyboard

while True:
    if keyboard.is_pressed("p"):
        print("You pressed p")
        break

It will break the loop as p is pressed.


Notes:

  • keyboard will read keypresses from the whole OS.
  • keyboard requires root on linux

How to set selected index JComboBox by value

Just call comboBox.updateUI() after doing comboBox.setSelectedItem or comboBox.setSelectedIndex or comboModel.setSelectedItem

Colors in JavaScript console

Try this:

var funcNames = ["log", "warn", "error"];
var colors = ['color:green', 'color:orange', 'color:red'];

for (var i = 0; i < funcNames.length; i++) {
    let funcName = funcNames[i];
    let color = colors[i];
    let oldFunc = console[funcName];
    console[funcName] = function () {
        var args = Array.prototype.slice.call(arguments);
        if (args.length) args = ['%c' + args[0]].concat(color, args.slice(1));
        oldFunc.apply(null, args);
    };
}

now they all are as you wanted:

console.log("Log is green.");
console.warn("Warn is orange.");
console.error("Error is red.");

note: formatting like console.log("The number = %d", 123); is not broken.

Regular Expressions- Match Anything

(.*?) matches anything - I've been using it for years.

Difference between "\n" and Environment.NewLine

Exact implementation of Environment.NewLine from the source code:

The implementation in .NET 4.6.1:

/*===================================NewLine====================================
**Action: A property which returns the appropriate newline string for the given
**        platform.
**Returns: \r\n on Win32.
**Arguments: None.
**Exceptions: None.
==============================================================================*/
public static String NewLine {
    get {
        Contract.Ensures(Contract.Result<String>() != null);
        return "\r\n";
    }
}

source


The implementation in .NET Core:

/*===================================NewLine====================================
**Action: A property which returns the appropriate newline string for the
**        given platform.
**Returns: \r\n on Win32.
**Arguments: None.
**Exceptions: None.
==============================================================================*/
public static String NewLine {
    get {
        Contract.Ensures(Contract.Result() != null);
#if !PLATFORM_UNIX
        return "\r\n";
#else
        return "\n";
#endif // !PLATFORM_UNIX
    }
}

source (in System.Private.CoreLib)

public static string NewLine => "\r\n";

source (in System.Runtime.Extensions)

Convert datetime to Unix timestamp and convert it back in python

If you want to convert a python datetime to seconds since epoch you should do it explicitly:

>>> import datetime
>>> datetime.datetime(2012, 04, 01, 0, 0).strftime('%s')
'1333234800'
>>> (datetime.datetime(2012, 04, 01, 0, 0) - datetime.datetime(1970, 1, 1)).total_seconds()
1333238400.0

In Python 3.3+ you can use timestamp() instead:

>>> import datetime
>>> datetime.datetime(2012, 4, 1, 0, 0).timestamp()
1333234800.0

How to access remote server with local phpMyAdmin client?

Method 1 ( for multiserver )

First , lets make a backup of original config.

sudo cp /etc/phpmyadmin/config.inc.php      ~/ 

Now in /usr/share/doc/phpmyadmin/examples/ you will see a file config.manyhosts.inc.php. Just copy in to /etc/phpmyadmin/ using command bellow:

sudo cp /usr/share/doc/phpmyadmin/examples/config.manyhosts.inc.php \
        /etc/phpmyadmin/config.inc.php

Edit the config.inc.php

sudo nano /etc/phpmyadmin/config.inc.php 

Search for :

$hosts = array (
    "foo.example.com",
    "bar.example.com",
    "baz.example.com",
    "quux.example.com",
);

And add your ip or hostname array save ( in nano CTRL+X press Y ) and exit . Done

Method 2 ( single server ) Edit the config.inc.php

sudo nano /etc/phpmyadmin/config.inc.php 

Search for :

/* Server parameters */
if (empty($dbserver)) $dbserver = 'localhost';
$cfg['Servers'][$i]['host'] = $dbserver;

if (!empty($dbport) || $dbserver != 'localhost') {
    $cfg['Servers'][$i]['connect_type'] = 'tcp';
    $cfg['Servers'][$i]['port'] = $dbport;
}

And replace with:

$cfg['Servers'][$i]['host'] = '192.168.1.100';
$cfg['Servers'][$i]['port'] = '3306';

Remeber to replace 192.168.1.100 with your own mysql ip server.

Sorry for my bad English ( google translate have the blame :D )

Find Item in ObservableCollection without using a loop

I Don't know what do you mean exactly, but technially speaking, this is not possible without a loop.

May be you mean using a LINQ, like for example:

list.Where(x=>x.Title == title)

It's worth mentioning that the iteration over is not skipped, but simply wrapped into the LINQ query.

Hope this helps.

EDIT

In other words if you really concerned about performance, keep coding the way you already doing. Otherwise choose LINQ for more concise and clear syntax.

Serializing list to JSON

Yes, but then what do you do about the django objects? simple json tends to choke on them.

If the objects are individual model objects (not querysets, e.g.), I have occasionally stored the model object type and the pk, like so:

seralized_dict = simplejson.dumps(my_dict, 
                     default=lambda a: "[%s,%s]" % (str(type(a)), a.pk)
                     )

to de-serialize, you can reconstruct the object referenced with model.objects.get(). This doesn't help if you are interested in the object details at the type the dict is stored, but it's effective if all you need to know is which object was involved.

error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

use only

base64.b64decode(a) 

instead of

base64.b64decode(a).decode('utf-8')

Should methods in a Java interface be declared with or without a public access modifier?

I would avoid to put modifiers that are applied by default. As pointed out, it can lead to inconsistency and confusion.

The worst I saw is an interface with methods declared abstract...

Log all queries in mysql

Quick way to enable MySQL General Query Log without restarting.

mysql> SET GLOBAL general_log = 'ON';
mysql> SET GLOBAL general_log_file = '/var/www/nanhe/log/all.log';

I have installed mysql through homebrew, mysql version : mysql Ver 14.14 Distrib 5.7.15, for osx10.11 (x86_64) using EditLine wrapper

javascript create empty array of a given size

Try using while loop, Array.prototype.push()

var myArray = [], X = 3;
while (myArray.length < X) {
  myArray.push("")
}

Alternatively, using Array.prototype.fill()

var myArray = Array(3).fill("");

Java: Unresolved compilation problem

(rewritten 2015-07-28)

The default behavior of Eclipse when compiling code with errors in it, is to generate byte code throwing the exception you see, allowing the program to be run. This is possible as Eclipse uses its own built-in compiler, instead of javac from the JDK which Apache Maven uses, and which fails the compilation completely for errors. If you use Eclipse on a Maven project which you are also working with using the command line mvn command, this may happen.

The cure is to fix the errors and recompile, before running again.

The setting is marked with a red box in this screendump:

Eclipse Preferences under OS X

Using colors with printf

#include <stdio.h>

//fonts color
#define FBLACK      "\033[30;"
#define FRED        "\033[31;"
#define FGREEN      "\033[32;"
#define FYELLOW     "\033[33;"
#define FBLUE       "\033[34;"
#define FPURPLE     "\033[35;"
#define D_FGREEN    "\033[6;"
#define FWHITE      "\033[7;"
#define FCYAN       "\x1b[36m"

//background color
#define BBLACK      "40m"
#define BRED        "41m"
#define BGREEN      "42m"
#define BYELLOW     "43m"
#define BBLUE       "44m"
#define BPURPLE     "45m"
#define D_BGREEN    "46m"
#define BWHITE      "47m"

//end color
#define NONE        "\033[0m"

int main(int argc, char *argv[])
{
    printf(D_FGREEN BBLUE"Change color!\n"NONE);

    return 0;
}

auto refresh for every 5 mins

Auto reload with target of your choice. In this case target is _self set to every 5 minutes.

300000 milliseconds = 300 seconds = 5 minutes

as 60000 milliseconds = 60 seconds = 1 minute.

This is how you do it:

<script type="text/javascript">
function load()
{
setTimeout("window.open('http://YourPage.com', '_self');", 300000);
}
</script>
<body onload="load()">

Or this if it is the same page to reload itself:

<script type="text/javascript">
function load()
{
setTimeout("window.open(self.location, '_self');", 300000);
}
</script>
<body onload="load()">

How to select option in drop down using Capybara

Unfortunately, the most popular answer did not work for me entirely. I had to add .select_option to end of the statement

select("option_name_here", from: "organizationSelect").select_option

without the select_option, no select was being performed

How to do a for loop in windows command line?

You might also consider adding ".

For example for %i in (*.wav) do opusenc "%~ni.wav" "%~ni.opus" is very good idea.

Gradle proxy configuration

For me, works adding this configuration in the gradle.properties file of the project, where the build.gradle file is:

systemProp.http.proxyHost=proxyURL
systemProp.http.proxyPort=proxyPort
systemProp.http.proxyUser=USER
systemProp.http.proxyPassword=PASSWORD
systemProp.https.proxyHost=proxyUrl 
systemProp.https.proxyPort=proxyPort
systemProp.https.proxyUser=USER
systemProp.https.proxyPassword=PASSWORD

Where : proxyUrl is the url of the proxy server (http://.....)

proxyPort is the port (usually 8080)

USER is my domain user

PASSWORD, my password

In this case, the proxy for http and https is the same

What is the App_Data folder used for in Visual Studio?

The main intention is for keeping your application's database file(s) in.

And no this will not be accessable from the web by default.

Netbeans - class does not have a main method

I had this issue as well (Error: Could not find or load main class test.Test). I'll explain this relatively basically since I know I would have appreciated someone doing that when I was looking for my answer.

When I right-clicked on the project (left hand side of the screen unless you got rid of the projects tab) and went to properties and then run, the main class had the projectname.classname, which is what confused me. For example, I created a project "test" to test this out, and when I went to

(right-click) test or Source Packages -> properties -> run -> main class

had Test.test in that field, which is what the problem was. the class is test, not Test.test, so I clicked browse to its right, and the only thing in the list to select from was test, and when I selected that and tried rerunning it, it finally worked.

Additionally, I found that when you create a new project in Netbeans, one of the things it originally gives you (in my case of the project named test) is package test;. If you are having this problem, then like me, you probably originally got rid of that line seeing it as just another line of code you didn't need. That line of code is what enabled your main class which in my case was Test.test to find the main class *test from that.

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

We can do a nested loop to visit all the elements of elements in your list:

 for (Gun g: gunList) {
   System.out.print(g.toString() + "\n   "); 
   for(Bullet b : g.getBullet() {
      System.out.print(g);    
   }
   System.out.println(); 
 }

Another Repeated column in mapping for entity error

Take care to provide only 1 setter and getter for any attribute. The best way to approach is to write down the definition of all the attributes then use eclipse generate setter and getter utility rather than doing it manually. The option comes on right click-> source -> Generate Getter and Setter.

SQL Query for Student mark functionality

 select max(m.mark)  as maxMarkObtained,su.Subname from Student s 
  inner join Marks m on s.Stid=m.Stid inner join [Subject] su on
  su.Subid=m.Subid group by su.Subname

I have execute it , this should work.

How to compare two strings are equal in value, what is the best method?

You should use some form of the String#equals(Object) method. However, there is some subtlety in how you should do it:

If you have a string literal then you should use it like this:

"Hello".equals(someString);

This is because the string literal "Hello" can never be null, so you will never run into a NullPointerException.

If you have a string and another object then you should use:

myString.equals(myObject);

You can make sure you are actually getting string equality by doing this. For all you know, myObject could be of a class that always returns true in its equals method!

Start with the object less likely to be null because this:

String foo = null;
String bar = "hello";
foo.equals(bar);

will throw a NullPointerException, but this:

String foo = null;
String bar = "hello";
bar.equals(foo);

will not. String#equals(Object) will correctly handle the case when its parameter is null, so you only need to worry about the object you are dereferencing--the first object.

cd into directory without having permission

You've got several options:

  • Use a different user account, one with execute permissions on that directory.
  • Change the permissions on the directory to allow your user account execute permissions.
    • Either use chmod(1) to change the permissions or
    • Use the setfacl(1) command to add an access control list entry for your user account. (This also requires mounting the filesystem with the acl option; see mount(8) and fstab(5) for details on the mount parameter.)

It's impossible to suggest the correct approach without knowing more about the problem; why are the directory permissions set the way they are? Why do you need access to that directory?

How to embed a PDF?

This works perfectly and this is official html5.

<object data="https://link-to-pdf"></object>

python and sys.argv

BTW you can pass the error message directly to sys.exit:

if len(sys.argv) < 2:
    sys.exit('Usage: %s database-name' % sys.argv[0])

if not os.path.exists(sys.argv[1]):
    sys.exit('ERROR: Database %s was not found!' % sys.argv[1])

How to split a file into equal parts, without breaking individual lines?

A simple solution for a simple question:

split -n l/5 your_file.txt

no need for scripting here.

From the man file, CHUNKS may be:

l/N     split into N files without splitting lines

Update

Not all unix dist include this flag. For example, it will not work in OSX. To use it, you can consider replacing the Mac OS X utilities with GNU core utilities.

What is the difference between x86 and x64

The difference is that Java binaries compiled as x86 (32-bit) or x64 (64-bit) applications respectively.

On a 64-bit Windows you can use either version, since x86 will run in WOW64 mode. On a 32-bit Windows you should use only x86 obviously.

For a Linux you should select appropriate type x86 for 32-bit OS, and x64 for 64-bit OS.

CSS '>' selector; what is it?

> selects immediate children

For example, if you have nested divs like such:

<div class='outer'>
    <div class="middle">
        <div class="inner">...</div>
    </div>
    <div class="middle">
        <div class="inner">...</div>
    </div>
</div>

and you declare a css rule in your stylesheet like such:

.outer > div {
    ...
}

your rules will apply only to those divs that have a class of "middle" since those divs are direct descendants (immediate children) of elements with class "outer" (unless, of course, you declare other, more specific rules overriding these rules). See fiddle.

_x000D_
_x000D_
div {_x000D_
  border: 1px solid black;_x000D_
  padding: 10px;_x000D_
}_x000D_
.outer > div {_x000D_
  border: 1px solid orange;_x000D_
}
_x000D_
<div class='outer'>_x000D_
  div.outer - This is the parent._x000D_
  <div class="middle">_x000D_
    div.middle - This is an immediate child of "outer". This will receive the orange border._x000D_
    <div class="inner">div.inner - This is an immediate child of "middle". This will not receive the orange border.</div>_x000D_
  </div>_x000D_
  <div class="middle">_x000D_
    div.middle - This is an immediate child of "outer". This will receive the orange border._x000D_
    <div class="inner">div.inner - This is an immediate child of "middle". This will not receive the orange border.</div>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<p>Without Words</p>_x000D_
_x000D_
<div class='outer'>_x000D_
  <div class="middle">_x000D_
    <div class="inner">...</div>_x000D_
  </div>_x000D_
  <div class="middle">_x000D_
    <div class="inner">...</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Side note

If you, instead, had a space between selectors instead of >, your rules would apply to both of the nested divs. The space is much more commonly used and defines a "descendant selector", which means it looks for any matching element down the tree rather than just immediate children as the > does.

NOTE: The > selector is not supported by IE6. It does work in all other current browsers though, including IE7 and IE8.

If you're looking into less-well-used CSS selectors, you may also want to look at +, ~, and [attr] selectors, all of which can be very useful.

This page has a full list of all available selectors, along with details of their support in various browsers (its mainly IE that has problems), and good examples of their usage.

Finding the last index of an array

With C# 8:

int[] array = { 1, 3, 5 };
var lastItem = array[^1]; // 5

How to install pandas from pip on windows cmd?

If you are a windows user:
make sure you added the script(dir) path to environment variables
C:\Python34\Scripts
for more how to set path vist

How to split the screen with two equal LinearLayouts?

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout
            android:orientation="vertical"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            tools:context=".MainActivity">
            <TextView
                android:layout_marginTop="16dp"
                android:textSize="18sp"
                android:textStyle="bold"
                android:padding="4dp"
                android:textColor="#EA80FC"
                android:fontFamily="sans-serif-medium"
                android:text="@string/team_a"
                android:gravity="center_horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <TextView
                android:id="@+id/team_a_score"
                android:text="@string/_0"
                android:textSize="56sp"
                android:padding="4dp"
                android:gravity="center_horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <TextView
                android:id="@+id/team_a_fouls"
                android:text="@string/fouls"
                android:padding="4dp"
                android:textSize="26sp"
                android:gravity="center_horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <Button
                android:text="@string/_1_points"
                android:layout_width="match_parent"
                android:onClick="addOnePointTeamA"
                android:textColor="#fff"
                android:layout_margin="6dp"
                android:layout_height="wrap_content" />
            <Button
                android:text="@string/_2_points"
                android:textColor="#fff"
                android:onClick="addTwoPointTeamA"
                android:layout_width="match_parent"
                android:layout_margin="6dp"
                android:layout_height="wrap_content" />
            <Button
                android:text="@string/_3_points"
                android:textColor="#fff"
                android:onClick="addThreePointTeamA"
                android:layout_margin="6dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <Button
                android:text="@string/_1_point_foul"
                android:textColor="#fff"
                android:layout_width="match_parent"
                android:onClick="addOnePointFoulTeamA"
                android:layout_margin="6dp"
                android:layout_height="wrap_content" />
        </LinearLayout>
        <LinearLayout
            android:orientation="vertical"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            tools:context=".MainActivity">
            <TextView
                android:text="@string/team_b"
                android:textColor="#EA80FC"
                android:textStyle="bold"
                android:padding="4dp"
                android:layout_marginTop="16dp"
                android:fontFamily="sans-serif-medium"
                android:textSize="18sp"
                android:gravity="center_horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <TextView
                android:id="@+id/team_b_score"
                android:text="0"
                android:padding="4dp"
                android:textSize="56sp"
                android:gravity="center_horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <TextView
                android:id="@+id/team_b_fouls"
                android:text="Fouls"
                android:padding="4dp"
                android:textSize="26sp"
                android:gravity="center_horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <Button
                android:text="@string/_1_points"
                android:textColor="#fff"
                android:fontFamily="sans-serif-medium"
                android:layout_width="match_parent"
                android:onClick="addOnePointTeamB"
                android:layout_margin="6dp"
                android:layout_height="wrap_content" />
            <Button
                android:text="@string/_2_points"
                android:layout_margin="6dp"
                android:fontFamily="sans-serif-medium"
                android:textColor="#fff"
                android:onClick="addTwoPointTeamB"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <Button
                android:text="@string/_3_points"
                android:fontFamily="sans-serif-medium"
                android:textColor="#fff"
                android:onClick="addThreePointTeamB"
                android:layout_margin="6dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <Button
                android:text="@string/_1_point_foul"
                android:textColor="#fff"
                android:onClick="addOnePointFoulTeamB"
                android:layout_width="match_parent"
                android:layout_margin="6dp"
                android:layout_height="wrap_content" />


        </LinearLayout>
    </LinearLayout>
    <Button
        android:text="@string/reset"
        android:layout_marginBottom="25dp"
        android:onClick="resetScore"
        android:textColor="#fff"
        android:fontFamily="sans-serif-medium"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

How can I disable an <option> in a <select> based on its value in JavaScript?

For some reason other answers are unnecessarily complex, it's easy to do it in one line in pure JavaScript:

Array.prototype.find.call(selectElement.options, o => o.value === optionValue).disabled = true;

or

selectElement.querySelector('option[value="'+optionValue.replace(/["\\]/g, '\\$&')+'"]').disabled = true;

The performance depends on the number of the options (the more the options, the slower the first one) and whether you can omit the escaping (the replace call) from the second one. Also the first one uses Array.find and arrow functions that are not available in IE11.

Min width in window resizing

You can set min-width property of CSS for body tag. Since this property is not supported by IE6, you can write like:

body{
   min-width:1000px;        /* Suppose you want minimum width of 1000px */
   width: auto !important;  /* Firefox will set width as auto */
   width:1000px;            /* As IE6 ignores !important it will set width as 1000px; */
}

Or:

body{
   min-width:1000px; // Suppose you want minimum width of 1000px
   _width: expression( document.body.clientWidth > 1000 ? "1000px" : "auto" ); /* sets max-width for IE6 */
}

Java and HTTPS url connection without downloading certificate

If you are using any Payment Gateway to hit any url just to send a message, then i used a webview by following it : How can load https url without use of ssl in android webview

and make a webview in your activity with visibility gone. What you need to do : just load that webview.. like this:

 webViewForSms.setWebViewClient(new SSLTolerentWebViewClient());
                webViewForSms.loadUrl(" https://bulksms.com/" +
                        "?username=test&password=test@123&messageType=text&mobile="+
                        mobileEditText.getText().toString()+"&senderId=ATZEHC&message=Your%20OTP%20for%20A2Z%20registration%20is%20124");

Easy.

You will get this: SSLTolerentWebViewClient from this link: How can load https url without use of ssl in android webview

Android: I am unable to have ViewPager WRAP_CONTENT

When using static content inside the viewpager and you wish no fancy animation you may use the following view pager

public class HeightWrappingViewPager extends ViewPager {

  public HeightWrappingViewPager(Context context) {
    super(context);
  }

  public HeightWrappingViewPager(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)   {
      super.onMeasure(widthMeasureSpec, heightMeasureSpec);
      View firstChild = getChildAt(0);
      firstChild.measure(widthMeasureSpec, heightMeasureSpec);
      super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(firstChild.getMeasuredHeight(), MeasureSpec.EXACTLY));
  }
}

How to make html table vertically scrollable

Why don't you place your table in a div?

<div style="height:100px;overflow:auto;">

 ... Your code goes here ...

</div>

Draw radius around a point in Google map

It seems that the most common method of achieving this is to draw a GPolygon with enough points to simulate a circle. The example you referenced uses this method. This page has a good example - look for the function drawCircle in the source code.

Private pages for a private Github repo

This is finally possible for GitHub Enterprise Cloud customers: Access control for GitHub Pages.

To enable access control on Pages, navigate to your repository settings, and click the dropdown menu to toggle between public and private visibility for your site.

enter image description here

How to get the PID of a process by giving the process name in Mac OS X ?

You can try this

pid=$(ps -o pid=,comm= | grep -m1 $procname | cut -d' ' -f1)

MySQL ERROR 1045 (28000): Access denied for user 'bill'@'localhost' (using password: YES)

The percent sign means all ip's so localhost is superfluous ... There is no need of the second record with the localhost .

Actually there is, 'localhost' is special in mysql, it means a connection over a unix socket (or named pipes on windows I believe) as opposed to a TCP/IP socket. using % as the host does not include 'localhost'

MySQL user accounts have two components: a user name and a host name. The user name identifies the user, and the host name specifies what hosts that user can connect from. The user name and host name are combined to create a user account:

'<user_name>'@'<host_name>' You can specify a specific IP address or address range for host name, or use the percent character ("%") to enable that user to log in from any host.

Note that user accounts are defined by both the user name and the host name. For example, 'root'@'%' is a different user account than 'root'@'localhost'.

How to generate a range of numbers between two numbers?

I know I'm 4 years too late, but I stumbled upon yet another alternative answer to this problem. The issue for speed isn't just pre-filtering, but also preventing sorting. It's possible to force the join-order to execute in a manner that the Cartesian product actually counts up as a result of the join. Using slartidan's answer as a jump-off point:

    WITH x AS (SELECT n FROM (VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) v(n))
SELECT ones.n + 10*tens.n + 100*hundreds.n + 1000*thousands.n
FROM x ones,     x tens,      x hundreds,       x thousands
ORDER BY 1

If we know the range we want, we can specify it via @Upper and @Lower. By combining the join hint REMOTE along with TOP, we can calculate only the subset of values we want with nothing wasted.

WITH x AS (SELECT n FROM (VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) v(n))
SELECT TOP (1+@Upper-@Lower) @Lower + ones.n + 10*tens.n + 100*hundreds.n + 1000*thousands.n
FROM x thousands
INNER REMOTE JOIN x hundreds on 1=1
INNER REMOTE JOIN x tens on 1=1
INNER REMOTE JOIN x ones on 1=1

The join hint REMOTE forces the optimizer to compare on the right side of the join first. By specifying each join as REMOTE from most to least significant value, the join itself will count upwards by one correctly. No need to filter with a WHERE, or sort with an ORDER BY.

If you want to increase the range, you can continue to add additional joins with progressively higher orders of magnitude, so long as they're ordered from most to least significant in the FROM clause.

Note that this is a query specific to SQL Server 2008 or higher.

Error in finding last used cell in Excel with VBA

For the last 3+ years these are the functions that I am using for finding last row and last column per defined column(for row) and row(for column):

Last Column:

Function lastCol(Optional wsName As String, Optional rowToCheck As Long = 1) As Long

    Dim ws  As Worksheet

    If wsName = vbNullString Then
        Set ws = ActiveSheet
    Else
        Set ws = Worksheets(wsName)
    End If

    lastCol = ws.Cells(rowToCheck, ws.Columns.Count).End(xlToLeft).Column

End Function

Last Row:

Function lastRow(Optional wsName As String, Optional columnToCheck As Long = 1) As Long

    Dim ws As Worksheet

    If wsName = vbNullString Then
        Set ws = ActiveSheet
    Else
        Set ws = Worksheets(wsName)
    End If

    lastRow = ws.Cells(ws.Rows.Count, columnToCheck).End(xlUp).Row

End Function

For the case of the OP, this is the way to get the last row in column E:

Debug.Print lastRow(columnToCheck:=Range("E4:E48").Column)

Last Row, counting empty rows with data:

Here we may use the well-known Excel formulas, which give us the last row of a worksheet in Excel, without involving VBA - =IFERROR(LOOKUP(2,1/(NOT(ISBLANK(A:A))),ROW(A:A)),0)

In order to put this in VBA and not to write anything in Excel, using the parameters for the latter functions, something like this could be in mind:

Public Function LastRowWithHidden(Optional wsName As String, Optional columnToCheck As Long = 1) As Long

    Dim ws As Worksheet

    If wsName = vbNullString Then
        Set ws = ActiveSheet
    Else
        Set ws = Worksheets(wsName)
    End If

    Dim letters As String
    letters = ColLettersGenerator(columnToCheck)
    LastRowWithHidden = ws.Evaluate("=IFERROR(LOOKUP(2,1/(NOT(ISBLANK(" & letters & "))),ROW(" & letters & " )),0)")

End Function

Function ColLettersGenerator(col As Long) As String

    Dim result As Variant
    result = Split(Cells(1, col).Address(True, False), "$")
    ColLettersGenerator = result(0) & ":" & result(0)

End Function

Python 3 turn range to a list

Python 3:

my_list = [*range(1001)]

How to use placeholder as default value in select2 framework

$("#e2").select2({
   placeholder: "Select a State",
   allowClear: true
});
$("#e2_2").select2({
   placeholder: "Select a State"
});

The placeholder can be declared via a data-placeholder attribute attached to the select, or via the placeholder configuration element as seen in the example code.

When placeholder is used for a non-multi-value select box, it requires that you include an empty tag as your first option.

Optionally, a clear button (visible once a selection is made) is available to reset the select box back to the placeholder value.

https://select2.org/placeholders

How to clear gradle cache?

there seems to be incorrect info posted here. some people report on how to clear the Android builder cache (with task cleanBuildCache) but do not seem to realize that said cache is independent of Gradle's build cache, AFAIK.

my understanding is that Android's cache predates (and inspired) Gradle's, but i could be wrong. whether the Android builder will be/was updated to use Gradle's cache and retire its own, i do not know.

EDIT: the Android builder cache is obsolete and has been eliminated. the Android Gradle plugin now uses Gradle's build cache instead. to control this cache you must now interact with Gradle's generic cache infrastructure.

TIP: search for Gradle's cache help online without mentioning the keyword 'android' to get help for the currently relevant cache.

EDIT 2: due to tir38's question in a comment below, i am testing using an Android Gradle plugin v3.4.2 project. the gradle cache is enabled by org.gradle.caching=true in gradle.properties. i do a couple of clean build and the second time most tasks show FROM-CACHE as their status, showing that the cache is working.

surprisingly, i have a cleanBuildCache gradle task and a <user-home>/.android/build-cache/3.4.2/ directory, both hinting the existence of an Android builder cache.

i execute cleanBuildCache and the 3.4.2/ directory is gone. next i do another clean build:

  • nothing changed: most tasks show FROM-CACHE as their status and the build completed at cache-enabled speeds.
  • the 3.4.2/ directory is recreated.
  • the 3.4.2/ directory is empty (save for 2 hidden, zero length marker files).

conclusions:

  1. caching of all normal Android builder tasks is handled by Gradle.
  2. executing cleanBuildCache does not clear or affect the build cache in any way.
  3. there is still an Android builder cache there. this could be vestigial code that the Android build team forgot to remove, or it could actually cache something strange that for whatever reason has not or cannot be ported to using the Gradle cache. (the 'cannot' option being highly improvable, IMHO.)

next, i disable the Gradle cache by removing org.gradle.caching=true from gradle.properties and i try a couple of clean build:

  • the builds are slow.
  • all tasks show their status as being executed and not cached or up to date.
  • the 3.4.2/ directory continues to be empty.

more conclusions:

  1. there is no Android builder cache fallback for when the Gradle cache fails to hit.
  2. the Android builder cache, at least for common tasks, has indeed been eliminated as i stated before.
  3. the relevant android doc contains outdated info. in particular the cache is not enabled by default as stated there, and the Gradle cache has to be enabled manually.

EDIT 3: user tir38 confirmed that the Android builder cache is obsolete and has been eliminated with this find. tir38 also created this issue. thanks!

How to sort rows of HTML table that are called from MySQL

//this is a php file

<html>
<head>
<style>
a:link {color:green;}
a:visited {color:purple;}
A:active {color: red;}
A:hover {color: red;}
table
{
    width:50%;
    height:50%;
}
table,th,td
{
    border:1px solid black;
}
th,td
{
    text-align:center;  
    background-color:yellow;
}
th
{
    background-color:green;
    color:white;    
}
</style>
<script type="text/javascript">
function working(str)
{
if (str=="")
  {
  document.getElementById("tump").innerHTML="";
  return;
  } 
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("tump").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getsort.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body bgcolor="pink">
<form method="post">
<select name="sortitems" onchange="working(this.value)">
<option value="">Select</option>
<option value="Id">Id</option>
<option value="Name">Name</option>
<option value="Email">Email</option>
<option value="Password">Password</option>
</select>
<?php 
$connect=mysql_connect("localhost","root","");
$db=mysql_select_db("test1",$connect);
$sql=mysql_query("select * from mine");
echo "<center><br><br><br><br><table id='tump' border='1'>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Password</th>
</tr>";
echo "<tr>";
while ($row=mysql_fetch_array($sql))
{?>
<td><?php echo "$row[Id]";?></td>
<td><?php echo "$row[Name]";?></td>
<td><?php echo "$row[Email]";?></td>
<td><?php echo "$row[Password]";?></td>
<?php echo "</tr>";
}
echo "</table></center>";?>
</form>
<br>
<div id="tump"></div>
</body>
</html>
------------------------------------------------------------------------
that is another php file

<html>
<body bgcolor="pink">
<head>
<style>
a:link {color:green;}
a:visited {color:purple;}
A:active {color: red;}
A:hover {color: red;}
table
{
    width:50%;
    height:50%;
}
table,th,td
{
    border:1px solid black;
}
th,td
{
    text-align:center;  
    background-color:yellow;
}
th
{
    background-color:green;
    color:white;    
}
</style>
</head>
<?php
$q=$_GET['q'];
$connect=mysql_connect("localhost","root","");
$db=mysql_select_db("test1",$connect);
$sql=mysql_query("select * from mine order by $q");
echo "<table id='tump' border='1'>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Password</th>
</tr>";
echo "<tr>";
while ($row=mysql_fetch_array($sql))
{?>
<td><?php echo "$row[Id]";?></td>
<td><?php echo "$row[Name]";?></td>
<td><?php echo "$row[Email]";?></td>
<td><?php echo "$row[Password]";?></td>
<?php echo "</tr>";
}
echo "</table>";?>
</body>
</html>



that will sort the table using ajax

Can I use return value of INSERT...RETURNING in another INSERT?

DO $$
DECLARE tableId integer;
BEGIN
  INSERT INTO Table1 (name) VALUES ('a_title') RETURNING id INTO tableId;
  INSERT INTO Table2 (val) VALUES (tableId);
END $$;

Tested with psql (10.3, server 9.6.8)

How to close IPython Notebook properly?

I am copy pasting from the Jupyter/IPython Notebook Quick Start Guide Documentation, released on Feb 13, 2018. http://jupyter-notebook-beginner-guide.readthedocs.io/en/latest/execute.html

1.3.3 Close a notebook: kernel shut down When a notebook is opened, its “computational engine” (called the kernel) is automatically started. Closing the notebook browser tab, will not shut down the kernel, instead the kernel will keep running until is explicitly shut down. To shut down a kernel, go to the associated notebook and click on menu File -> Close and Halt. Alternatively, the Notebook Dashboard has a tab named Running that shows all the running notebooks (i.e. kernels) and allows shutting them down (by clicking on a Shutdown button).

Summary: First close and halt the notebooks running.

1.3.2 Shut down the Jupyter Notebook App Closing the browser (or the tab) will not close the Jupyter Notebook App. To completely shut it down you need to close the associated terminal. In more detail, the Jupyter Notebook App is a server that appears in your browser at a default address (http://localhost:8888). Closing the browser will not shut down the server. You can reopen the previous address and the Jupyter Notebook App will be redisplayed. You can run many copies of the Jupyter Notebook App and they will show up at a similar address (only the number after “:”, which is the port, will increment for each new copy). Since with a single Jupyter Notebook App you can already open many notebooks, we do not recommend running multiple copies of Jupyter Notebook App.

Summary: Second, quit the terminal from which you fired Jupyter.

What are the differences among grep, awk & sed?

Short definition:

grep: search for specific terms in a file

#usage
$ grep This file.txt
Every line containing "This"
Every line containing "This"
Every line containing "This"
Every line containing "This"

$ cat file.txt
Every line containing "This"
Every line containing "This"
Every line containing "That"
Every line containing "This"
Every line containing "This"

Now awk and sed are completly different than grep. awk and sed are text processors. Not only do they have the ability to find what you are looking for in text, they have the ability to remove, add and modify the text as well (and much more).

awk is mostly used for data extraction and reporting. sed is a stream editor
Each one of them has its own functionality and specialties.

Example
Sed

$ sed -i 's/cat/dog/' file.txt
# this will replace any occurrence of the characters 'cat' by 'dog'

Awk

$ awk '{print $2}' file.txt
# this will print the second column of file.txt

Basic awk usage:
Compute sum/average/max/min/etc. what ever you may need.

$ cat file.txt
A 10
B 20
C 60
$ awk 'BEGIN {sum=0; count=0; OFS="\t"} {sum+=$2; count++} END {print "Average:", sum/count}' file.txt
Average:    30

I recommend that you read this book: Sed & Awk: 2nd Ed.

It will help you become a proficient sed/awk user on any unix-like environment.

Swift Modal View Controller with transparent background

You can do it like this:

In your main view controller:

func showModal() {
    let modalViewController = ModalViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    presentViewController(modalViewController, animated: true, completion: nil)
}

In your modal view controller:

class ModalViewController: UIViewController {
    override func viewDidLoad() {
        view.backgroundColor = UIColor.clearColor()
        view.opaque = false
    }
}

If you are working with a storyboard:

Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values:

  • Background = Clear Color
  • Drawing = Uncheck the Opaque checkbox
  • Presentation = Over Current Context

As Crashalot pointed out in his comment: Make sure the segue only uses Default for both Presentation and Transition. Using Current Context for Presentation makes the modal turn black instead of remaining transparent.

Unable to auto-detect email address

git config --global user.email "put your email address here" # user.email will still be there  
git config --global user.name "put your github username here" # user.name will still be there

Note: it might prompt you to enter your git username and password. This works fine for me.

How to get the first and last date of the current year?

Try this:

DATE_FORMAT(NOW(),'01/01/%Y')
DATE_FORMAT(NOW(),'31/12/%Y')

WPF Add a Border to a TextBlock

A TextBlock does not actually inherit from Control so it does not have properties that you would generally associate with a Control. Your best bet for adding a border in a style is to replace the TextBlock with a Label

See this link for more on the differences between a TextBlock and other Controls

How to delete all rows from all tables in a SQL Server database?

In my recent project my task was to clean an entire database by using sql statement and each table having many constraints like Primary Key and Foreign Key. There are more than 1000 tables in database so its not possible to write a delete query on each and ever table.

By using a stored procedure named sp_MSForEachTable which allows us to easily process some code against each and every table in a single database. It means that it is used to process a single T-SQL command or a different T-SQL commands against every table in the database.

So follow the below steps to truncate all tables in a SQL Server Database:

Step 1- Disable all constraints on the database by using below sql query :

EXEC sys.sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'

Step 2- Execute a Delete or truncate operation on each table of the database by using below sql command :

EXEC sys.sp_msforeachtable 'DELETE FROM ?'

Step 3- Enable all constraints on the database by using below sql statement:

EXEC sys.sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'

Asp.net Hyperlink control equivalent to <a href="#"></a>

Just write <a href="#"></a>.

If that's what you want, you don't need a server-side control.

How to pass datetime from c# to sql correctly?

I had many issues involving C# and SqlServer. I ended up doing the following:

  1. On SQL Server I use the DateTime column type
  2. On c# I use the .ToString("yyyy-MM-dd HH:mm:ss") method

Also make sure that all your machines run on the same timezone.

Regarding the different result sets you get, your first example is "July First" while the second is "4th of July" ...

Also, the second example can be also interpreted as "April 7th", it depends on your server localization configuration (my solution doesn't suffer from this issue).

EDIT: hh was replaced with HH, as it doesn't seem to capture the correct hour on systems with AM/PM as opposed to systems with 24h clock. See the comments below.

Select data from "show tables" MySQL query

I don't understand why you want to use SELECT * FROM as part of the statement.

12.5.5.30. SHOW TABLES Syntax

Check if a number is int or float

absolute = abs(x)
rounded = round(absolute)
if absolute - rounded == 0:
  print 'Integer number'
else:
  print 'notInteger number'

How can I generate a list or array of sequential integers in Java?

You can use the Interval class from Eclipse Collections.

List<Integer> range = Interval.oneTo(10);
range.forEach(System.out::print);  // prints 12345678910

The Interval class is lazy, so doesn't store all of the values.

LazyIterable<Integer> range = Interval.oneTo(10);
System.out.println(range.makeString(",")); // prints 1,2,3,4,5,6,7,8,9,10

Your method would be able to be implemented as follows:

public List<Integer> makeSequence(int begin, int end) {
    return Interval.fromTo(begin, end);
}

If you would like to avoid boxing ints as Integers, but would still like a list structure as a result, then you can use IntList with IntInterval from Eclipse Collections.

public IntList makeSequence(int begin, int end) {
    return IntInterval.fromTo(begin, end);
}

IntList has the methods sum(), min(), minIfEmpty(), max(), maxIfEmpty(), average() and median() available on the interface.

Update for clarity: 11/27/2017

An Interval is a List<Integer>, but it is lazy and immutable. It is extremely useful for generating test data, especially if you deal a lot with collections. If you want you can easily copy an interval to a List, Set or Bag as follows:

Interval integers = Interval.oneTo(10);
Set<Integer> set = integers.toSet();
List<Integer> list = integers.toList();
Bag<Integer> bag = integers.toBag();

An IntInterval is an ImmutableIntList which extends IntList. It also has converter methods.

IntInterval ints = IntInterval.oneTo(10);
IntSet set = ints.toSet();
IntList list = ints.toList();
IntBag bag = ints.toBag();

An Interval and an IntInterval do not have the same equals contract.

Update for Eclipse Collections 9.0

You can now create primitive collections from primitive streams. There are withAll and ofAll methods depending on your preference. If you are curious, I explain why we have both here. These methods exist for mutable and immutable Int/Long/Double Lists, Sets, Bags and Stacks.

Assert.assertEquals(
        IntInterval.oneTo(10),
        IntLists.mutable.withAll(IntStream.rangeClosed(1, 10)));

Assert.assertEquals(
        IntInterval.oneTo(10),
        IntLists.immutable.withAll(IntStream.rangeClosed(1, 10)));

Note: I am a committer for Eclipse Collections

Default values in a C Struct

While macros and/or functions (as already suggested) will work (and might have other positive effects (i.e. debug hooks)), they are more complex than needed. The simplest and possibly most elegant solution is to just define a constant that you use for variable initialisation:

const struct foo FOO_DONT_CARE = { // or maybe FOO_DEFAULT or something
    dont_care, dont_care, dont_care, dont_care
};
...
struct foo bar = FOO_DONT_CARE;
bar.id = 42;
bar.current_route = new_route;
update(&bar);

This code has virtually no mental overhead of understanding the indirection, and it is very clear which fields in bar you set explicitly while (safely) ignoring those you do not set.

Angularjs - ng-cloak/ng-show elements blink

In addition to other answers, if you find the flash of template code to still be occuring it is likely you have your scripts at the bottom of the page and that means that the ng-cloak directive straight up will not work. You can either move your scripts to the head or create a CSS rule.

The docs say "For the best result, the angular.js script must be loaded in the head section of the html document; alternatively, the css rule above must be included in the external stylesheet of the application."

Now, it doesn't have to be an external stylesheet but just in a element in the head.

<style type="text/css">
  .ng-cloak {
    display: none !important;
  }
</style>

source: https://docs.angularjs.org/api/ng/directive/ngCloak

How do you display a Toast from a background thread on Android?

I made this approach based on mjaggard answer:

public static void toastAnywhere(final String text) {
    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(new Runnable() {
        public void run() {
            Toast.makeText(SuperApplication.getInstance().getApplicationContext(), text, 
                    Toast.LENGTH_LONG).show();
        }
    });
}

Worked well for me.

How to remove close button on the jQuery UI dialog?

As shown on the official page and suggested by David:

Create a style:

.no-close .ui-dialog-titlebar-close {
    display: none;
}

Then, you can simply add the no-close class to any dialog in order to hide it's close button:

$( "#dialog" ).dialog({
    dialogClass: "no-close",
    buttons: [{
        text: "OK",
        click: function() {
            $( this ).dialog( "close" );
        }
    }]
});

Make the current Git branch a master branch

From what I understand, you can branch the current branch into an existing branch. In essence, this will overwrite master with whatever you have in the current branch:

git branch -f master HEAD

Once you've done that, you can normally push your local master branch, possibly requiring the force parameter here as well:

git push -f origin master

No merges, no long commands. Simply branch and push— but, yes, this will rewrite history of the master branch, so if you work in a team you have got to know what you're doing.




Alternatively, I found that you can push any branch to the any remote branch, so:

# This will force push the current branch to the remote master
git push -f origin HEAD:master

# Switch current branch to master
git checkout master

# Reset the local master branch to what's on the remote
git reset --hard origin/master

Can a class member function template be virtual?

C++ doesn't allow virtual template member functions right now. The most likely reason is the complexity of implementing it. Rajendra gives good reason why it can't be done right now but it could be possible with reasonable changes of the standard. Especially working out how many instantiations of a templated function actually exist and building up the vtable seems difficult if you consider the place of the virtual function call. Standards people just have a lot of other things to do right now and C++1x is a lot of work for the compiler writers as well.

When would you need a templated member function? I once came across such a situation where I tried to refactor a hierarchy with a pure virtual base class. It was a poor style for implementing different strategies. I wanted to change the argument of one of the virtual functions to a numeric type and instead of overloading the member function and override every overload in all sub-classes I tried to use virtual template functions (and had to find out they don't exist.)

Why do people hate SQL cursors so much?

The "overhead" with cursors is merely part of the API. Cursors are how parts of the RDBMS work under the hood. Often CREATE TABLE and INSERT have SELECT statements, and the implementation is the obvious internal cursor implementation.

Using higher-level "set-based operators" bundles the cursor results into a single result set, meaning less API back-and-forth.

Cursors predate modern languages that provide first-class collections. Old C, COBOL, Fortran, etc., had to process rows one at a time because there was no notion of "collection" that could be used widely. Java, C#, Python, etc., have first-class list structures to contain result sets.

The Slow Issue

In some circles, the relational joins are a mystery, and folks will write nested cursors rather than a simple join. I've seen truly epic nested loop operations written out as lots and lots of cursors. Defeating an RDBMS optimization. And running really slowly.

Simple SQL rewrites to replace nested cursor loops with joins and a single, flat cursor loop can make programs run in 100th the time. [They thought I was the god of optimization. All I did was replace nested loops with joins. Still used cursors.]

This confusion often leads to an indictment of cursors. However, it isn't the cursor, it's the misuse of the cursor that's the problem.

The Size Issue

For really epic result sets (i.e., dumping a table to a file), cursors are essential. The set-based operations can't materialize really large result sets as a single collection in memory.

Alternatives

I try to use an ORM layer as much as possible. But that has two purposes. First, the cursors are managed by the ORM component. Second, the SQL is separated from the application into a configuration file. It's not that the cursors are bad. It's that coding all those opens, closes and fetches is not value-add programming.

Print very long string completely in pandas dataframe

Use pd.set_option('display.max_colwidth', None) for automatic linebreaks and multi-line cells.

This is a great resource on how to use jupyters display with pandas to the fullest.


Edited: Used to be pd.set_option('display.max_colwidth', -1).

S3 Static Website Hosting Route All Paths to Index.html

Just to put the extremely simple answer. Just use the hash location strategy for the router if you are hosting on S3.

export const AppRoutingModule: ModuleWithProviders = RouterModule.forRoot(routes, { useHash: true, scrollPositionRestoration: 'enabled' });

Using strtok with a std::string

#include <iostream>
#include <string>
#include <sstream>
int main(){
    std::string myText("some-text-to-tokenize");
    std::istringstream iss(myText);
    std::string token;
    while (std::getline(iss, token, '-'))
    {
        std::cout << token << std::endl;
    }
    return 0;
}

Or, as mentioned, use boost for more flexibility.

Why do you use typedef when declaring an enum in C++?

It's a C heritage, in C, if you do :

enum TokenType
{
    blah1   = 0x00000000,
    blah2   = 0X01000000,
    blah3   = 0X02000000
};

you'll have to use it doing something like :

enum TokenType foo;

But if you do this :

typedef enum e_TokenType
{
    blah1   = 0x00000000,
    blah2   = 0X01000000,
    blah3   = 0X02000000
} TokenType;

You'll be able to declare :

TokenType foo;

But in C++, you can use only the former definition and use it as if it were in a C typedef.

Any way to clear python's IDLE window?

Create a function as such...

def clear():
    os.system('clear')

and then when you get to the bottom of the Python IDLE you can just use

clear()

:)

submit a form in a new tab

I have a [submit] and a [preview] button, I want the preview to show the print view of the submitted form data, without persisting it to database. Therefore I want [preview] to open in a new tab, and submit to submit the data in the same window/tab.

<button type="submit" id="liquidacion_save"          name="liquidacion[save]"          onclick="$('form').attr('target', '');"      >Save</button></div>    <div>
<button type="submit" id="liquidacion_Previsualizar" name="liquidacion[Previsualizar]" onclick="$('form').attr('target', '_blank');">Preview</button></div>