Programs & Examples On #Editortemplates

Html attributes for EditorFor() in ASP.NET MVC

Why not just use

@Html.DisplayFor(model => model.Control.PeriodType)

OS X Terminal shortcut: Jump to beginning/end of line

As setup in the terminal using vi:

The Home button on a Macbook Pro keyboard: Fn + Left Arrow.

The End button on a Macbook Pro keyboard: Fn + Right Arrow.

Delete files in subfolder using batch script

Moved from the closed topic

del /s d:\test\archive*.txt

This should get you all of your text files

Alternatively,

I modified a script I already wrote to look for certain files to move them, this one should go and find files and delete them. It allows you to just choose to which folder by a selection screen.

Please test this on your system before using it though.

@echo off
Title DeleteFilesInSubfolderList
color 0A
SETLOCAL ENABLEDELAYEDEXPANSION

REM ---------------------------
REM   *** EDIT VARIABLES BELOW ***
REM ---------------------------

set targetFolder=
REM targetFolder is the location you want to delete from    
REM ---------------------------
REM  *** DO NOT EDIT BELOW ***
REM ---------------------------

IF NOT DEFINED targetFolder echo.Please type in the full BASE Symform Offline Folder (I.E. U:\targetFolder)
IF NOT DEFINED targetFolder set /p targetFolder=:
cls
echo.Listing folders for: %targetFolder%\^*
echo.-------------------------------
set Index=1
for /d %%D in (%targetFolder%\*) do (
  set "Subfolders[!Index!]=%%D"
  set /a Index+=1
)
set /a UBound=Index-1
for /l %%i in (1,1,%UBound%) do echo. %%i. !Subfolders[%%i]!

:choiceloop
echo.-------------------------------
set /p Choice=Search for ERRORS in: 
if "%Choice%"=="" goto chioceloop
if %Choice% LSS 1 goto choiceloop
if %Choice% GTR %UBound% goto choiceloop
set Subfolder=!Subfolders[%Choice%]!
goto start

:start
TITLE Delete Text Files - %Subfolder%
IF NOT EXIST %ERRPATH% goto notExist
IF EXIST %ERRPATH% echo.%ERRPATH% Exists - Beginning to test-delete files...
echo.Searching for .txt files...
pushd %ERRPATH%
for /r %%a in (*.txt) do (
echo "%%a" "%Subfolder%\%%~nxa"
)
popd
echo.
echo.
verIFy >nul
echo.Execute^?
choice /C:YNX /N /M "(Y)Yes or (N)No:"
IF '%ERRORLEVEL%'=='1' set question1=Y
IF '%ERRORLEVEL%'=='2' set question1=N
IF /I '%question1%'=='Y' goto execute
IF /I '%question1%'=='N' goto end

:execute
echo.%ERRPATH% Exists - Beginning to delete files...
echo.Searching for .txt files...
pushd %ERRPATH%
for /r %%a in (*.txt) do (
del "%%a" "%Subfolder%\%%~nxa"
)
popd
goto end

:end
echo.
echo.
echo.Finished deleting files from %subfolder%
pause
goto choiceloop
ENDLOCAL
exit


REM Created by Trevor Giannetti
REM An unpublished work
REM (October 2012)

If you change the

set targetFolder= 

to the folder you want you won't get prompted for the folder. *Remember when putting the base path in, the format does not include a '\' on the end. e.g. d:\test c:\temp

Hope this helps

iPhone app could not be installed at this time

clear your cache and cookies in Safari, make sure your device is in provisioning profile and provisioning profile is installed on the device.

If everything mentioned above didn't help, try to create a new build with higher build number and try to distribute your app again

Convert date to YYYYMM format

SELECT CONVERT(nvarchar(6), GETDATE(), 112)

NSURLErrorDomain error codes description

I was unable to find name of an error for given code when developing in Swift. For that reason I paste minus codes for NSURLErrorDomain taken from NSURLError.h

/*!
    @enum NSURL-related Error Codes
    @abstract Constants used by NSError to indicate errors in the NSURL domain
*/
NS_ENUM(NSInteger)
{
    NSURLErrorUnknown =             -1,
    NSURLErrorCancelled =           -999,
    NSURLErrorBadURL =              -1000,
    NSURLErrorTimedOut =            -1001,
    NSURLErrorUnsupportedURL =          -1002,
    NSURLErrorCannotFindHost =          -1003,
    NSURLErrorCannotConnectToHost =         -1004,
    NSURLErrorNetworkConnectionLost =       -1005,
    NSURLErrorDNSLookupFailed =         -1006,
    NSURLErrorHTTPTooManyRedirects =        -1007,
    NSURLErrorResourceUnavailable =         -1008,
    NSURLErrorNotConnectedToInternet =      -1009,
    NSURLErrorRedirectToNonExistentLocation =   -1010,
    NSURLErrorBadServerResponse =       -1011,
    NSURLErrorUserCancelledAuthentication =     -1012,
    NSURLErrorUserAuthenticationRequired =  -1013,
    NSURLErrorZeroByteResource =        -1014,
    NSURLErrorCannotDecodeRawData =             -1015,
    NSURLErrorCannotDecodeContentData =         -1016,
    NSURLErrorCannotParseResponse =             -1017,
    NSURLErrorAppTransportSecurityRequiresSecureConnection NS_ENUM_AVAILABLE(10_11, 9_0) = -1022,
    NSURLErrorFileDoesNotExist =        -1100,
    NSURLErrorFileIsDirectory =         -1101,
    NSURLErrorNoPermissionsToReadFile =     -1102,
    NSURLErrorDataLengthExceedsMaximum NS_ENUM_AVAILABLE(10_5, 2_0) =   -1103,

    // SSL errors
    NSURLErrorSecureConnectionFailed =      -1200,
    NSURLErrorServerCertificateHasBadDate =     -1201,
    NSURLErrorServerCertificateUntrusted =  -1202,
    NSURLErrorServerCertificateHasUnknownRoot = -1203,
    NSURLErrorServerCertificateNotYetValid =    -1204,
    NSURLErrorClientCertificateRejected =   -1205,
    NSURLErrorClientCertificateRequired =   -1206,
    NSURLErrorCannotLoadFromNetwork =       -2000,

    // Download and file I/O errors
    NSURLErrorCannotCreateFile =        -3000,
    NSURLErrorCannotOpenFile =          -3001,
    NSURLErrorCannotCloseFile =         -3002,
    NSURLErrorCannotWriteToFile =       -3003,
    NSURLErrorCannotRemoveFile =        -3004,
    NSURLErrorCannotMoveFile =          -3005,
    NSURLErrorDownloadDecodingFailedMidStream = -3006,
    NSURLErrorDownloadDecodingFailedToComplete =-3007,

    NSURLErrorInternationalRoamingOff NS_ENUM_AVAILABLE(10_7, 3_0) =         -1018,
    NSURLErrorCallIsActive NS_ENUM_AVAILABLE(10_7, 3_0) =                    -1019,
    NSURLErrorDataNotAllowed NS_ENUM_AVAILABLE(10_7, 3_0) =                  -1020,
    NSURLErrorRequestBodyStreamExhausted NS_ENUM_AVAILABLE(10_7, 3_0) =      -1021,

    NSURLErrorBackgroundSessionRequiresSharedContainer NS_ENUM_AVAILABLE(10_10, 8_0) = -995,
    NSURLErrorBackgroundSessionInUseByAnotherProcess NS_ENUM_AVAILABLE(10_10, 8_0) = -996,
    NSURLErrorBackgroundSessionWasDisconnected NS_ENUM_AVAILABLE(10_10, 8_0)= -997,
};

Make cross-domain ajax JSONP request with jQuery

Concept explained

Are you trying do a cross-domain AJAX call? Meaning, your service is not hosted in your same web application path? Your web-service must support method injection in order to do JSONP.

Your code seems fine and it should work if your web services and your web application hosted in the same domain.

When you do a $.ajax with dataType: 'jsonp' meaning that jQuery is actually adding a new parameter to the query URL.

For instance, if your URL is http://10.211.2.219:8080/SampleWebService/sample.do then jQuery will add ?callback={some_random_dynamically_generated_method}.

This method is more kind of a proxy actually attached in window object. This is nothing specific but does look something like this:

window.some_random_dynamically_generated_method = function(actualJsonpData) {
    //here actually has reference to the success function mentioned with $.ajax
    //so it just calls the success method like this: 
    successCallback(actualJsonData);
}

Summary

Your client code seems just fine. However, you have to modify your server-code to wrap your JSON data with a function name that passed with query string. i.e.

If you have reqested with query string

?callback=my_callback_method

then, your server must response data wrapped like this:

my_callback_method({your json serialized data});

How to uncheck checkbox using jQuery Uniform library

Just do this:

$('#checkbox').prop('checked',true).uniform('refresh');

Search a whole table in mySQL for a string

In addition to pattern matching with 'like' keyword. You can also perform search by using fulltext feature as below;

SELECT * FROM clients WHERE MATCH (shipping_name, billing_name, email) AGAINST ('mary')

Permission denied (publickey,gssapi-keyex,gssapi-with-mic)

I had the same problem and for some reason The sshKeys was not syncing up with my user on the instance.

I created another user by adding --ssh_user=anotheruser to gcutil command.

The gcutil looked like this

gcutil --service_version="v1" --project="project"  --ssh_user=anotheruser ssh  --zone="us-central1-a" "inst1"

JQuery How to extract value from href tag?

The first thing that comes to my mind is a one-liner regex:

var pageNum = $("#specificLink").attr("href").match(/page=([0-9]+)/)[1];

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in

use global scope on your $con and put it inside your getPosts() function like so.

function getPosts() {
global $con;
$query = mysqli_query($con,"SELECT * FROM Blog");
while($row = mysqli_fetch_array($query))
    {
        echo "<div class=\"blogsnippet\">";
        echo "<h4>" . $row['Title'] . "</h4>" . $row['SubHeading'];
        echo "</div>";
    }
}

How do I post button value to PHP?

As Josh has stated above, you want to give each one the same name (letter, button, etc.) and all of them work. Then you want to surround all of these with a form tag:

<form name="myLetters" action="yourScript.php" method="POST">
<!-- Enter your values here with the following syntax: -->
<input type="radio" name="letter" value="A" /> A
<!-- Then add a submit value & close your form -->
<input type="submit" name="submit" value="Choose Letter!" />
</form>

Then, in the PHP script "yourScript.php" as defined by the action attribute, you can use:

$_POST['letter']

To get the value chosen.

GIT clone repo across local file system in windows

Not sure if it was because of my git version (1.7.2) or what, but the approaches listed above using machine name and IP options were not working for me. An additional detail that may/may not be important is that the repo was a bare repo that I had initialized and pushed to from a different machine.

I was trying to clone project1 as advised above with commands like:

$ git clone file:////<IP_ADDRESS>/home/user/git/project1
Cloning into project1...
fatal: '//<IP_ADDRESS>/home/user/git/project1' does not appear to be a git repository
fatal: The remote end hung up unexpectedly

and

$ git clone file:////<MACHINE_NAME>/home/user/git/project1
Cloning into project1...
fatal: '//<MACHINE_NAME>/home/user/git/project1' does not appear to be a git repository
fatal: The remote end hung up unexpectedly

What did work for me was something simpler:

$ git clone ../git/project1
Cloning into project1...
done.

Note - even though the repo being cloned from was bare, this did produce a 'normal' clone with all the actual code/image/resource files that I was hoping for (as opposed to the internals of the git repo).

Where is the itoa function in Linux?

You can use this program instead of sprintf.

void itochar(int x, char *buffer, int radix);

int main()
{
    char buffer[10];
    itochar(725, buffer, 10);
    printf ("\n %s \n", buffer);
    return 0;
}

void itochar(int x, char *buffer, int radix)
{
    int i = 0 , n,s;
    n = s;
    while (n > 0)
    {
        s = n%radix;
        n = n/radix;
        buffer[i++] = '0' + s;
    }
    buffer[i] = '\0';
    strrev(buffer);
}

How can I change the default Mysql connection timeout when connecting through python?

MAX_EXECUTION_TIME is also an important parameter for long running queries.Will work for MySQL 5.7 or later.

Check the current value

SELECT @@GLOBAL.MAX_EXECUTION_TIME, @@SESSION.MAX_EXECUTION_TIME;

Then set it according to your needs.

SET SESSION MAX_EXECUTION_TIME=2000;
SET GLOBAL MAX_EXECUTION_TIME=2000;

Sorting by date & time in descending order?

SELECT id, name, form_id, DATE(updated_at) as date
FROM wp_frm_items
WHERE user_id = 11 && form_id=9
ORDER BY date ASC

"DESC" stands for descending but you need ascending order ("ASC").

Cocoa: What's the difference between the frame and the bounds?

The frame is the rectangle that defines the UIView with respect to its superview.

The bounds rect is the range of values that define that NSView's coordinate system.

i.e. anything in this rectangle will actually display in the UIView.

Difference between .keystore file and .jks file

You are confused on this.

A keystore is a container of certificates, private keys etc.

There are specifications of what should be the format of this keystore and the predominant is the #PKCS12

JKS is Java's keystore implementation. There is also BKS etc.

These are all keystore types.

So to answer your question:

difference between .keystore files and .jks files

There is none. JKS are keystore files. There is difference though between keystore types. E.g. JKS vs #PKCS12

Change onclick action with a Javascript function

What might be easier, is to have two buttons and show/hide them in your functions. (ie. display:none|block;) Each button could then have it's own onclick with whatever code you need.

So, at first button1 would be display:block and button2 would be display:none. Then when you click button1 it would switch button2 to be display:block and button1 to be display:none.

Text file in VBA: Open/Find Replace/SaveAs/Close File

This code will open and read lines of complete text file That variable "ReadedData" Holds the text line in memory

Open "C:\satheesh\myfile\Hello.txt" For Input As #1

do until EOF(1)   

       Input #1, ReadedData
loop**

Triggering change detection manually in Angular

Try one of these:

  • ApplicationRef.tick() - similar to AngularJS's $rootScope.$digest() -- i.e., check the full component tree
  • NgZone.run(callback) - similar to $rootScope.$apply(callback) -- i.e., evaluate the callback function inside the Angular zone. I think, but I'm not sure, that this ends up checking the full component tree after executing the callback function.
  • ChangeDetectorRef.detectChanges() - similar to $scope.$digest() -- i.e., check only this component and its children

You can inject ApplicationRef, NgZone, or ChangeDetectorRef into your component.

Determining if Swift dictionary contains key and obtaining any of its values

Looks like you got what you need from @matt, but if you want a quick way to get a value for a key, or just the first value if that key doesn’t exist:

extension Dictionary {
    func keyedOrFirstValue(key: Key) -> Value? {
        // if key not found, replace the nil with 
        // the first element of the values collection
        return self[key] ?? first(self.values)
        // note, this is still an optional (because the
        // dictionary could be empty)
    }
}

let d = ["one":"red", "two":"blue"]

d.keyedOrFirstValue("one")  // {Some "red"}
d.keyedOrFirstValue("two")  // {Some "blue"}
d.keyedOrFirstValue("three")  // {Some "red”}

Note, no guarantees what you'll actually get as the first value, it just happens in this case to return “red”.

Check if SQL Connection is Open or Closed

Here is what I'm using:

if (mySQLConnection.State != ConnectionState.Open)
{
    mySQLConnection.Close();
    mySQLConnection.Open();
}

The reason I'm not simply using:

if (mySQLConnection.State == ConnectionState.Closed)
{
    mySQLConnection.Open();
}

Is because the ConnectionState can also be:

Broken, Connnecting, Executing, Fetching

In addition to

Open, Closed

Additionally Microsoft states that Closing, and then Re-opening the connection "will refresh the value of State." See here http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.state(v=vs.110).aspx

Error in strings.xml file in Android

post your complete string. Though, my guess is there is an apostrophe (') character in your string. replace it with (\') and it will fix the issue. for example,

//strings.xml
<string name="terms">
Hey Mr. Android, are you stuck?  Here, I\'ll clear a path for you.  
</string>

Ref:

http://www.mrexcel.com/forum/showthread.php?t=195353

https://code.google.com/archive/p/replicaisland/issues/48

How do I output an ISO 8601 formatted string in JavaScript?

See the last example on page https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference:Global_Objects:Date:

/* Use a function for the exact format desired... */
function ISODateString(d) {
    function pad(n) {return n<10 ? '0'+n : n}
    return d.getUTCFullYear()+'-'
         + pad(d.getUTCMonth()+1)+'-'
         + pad(d.getUTCDate())+'T'
         + pad(d.getUTCHours())+':'
         + pad(d.getUTCMinutes())+':'
         + pad(d.getUTCSeconds())+'Z'
}

var d = new Date();
console.log(ISODateString(d)); // Prints something like 2009-09-28T19:03:12Z

How do I fix a merge conflict due to removal of a file in a branch?

The conflict message:

CONFLICT (delete/modify): res/layout/dialog_item.xml deleted in dialog and modified in HEAD

means that res/layout/dialog_item.xml was deleted in the 'dialog' branch you are merging, but was modified in HEAD (in the branch you are merging to).

So you have to decide whether

  • remove file using "git rm res/layout/dialog_item.xml"

or

  • accept version from HEAD (perhaps after editing it) with "git add res/layout/dialog_item.xml"

Then you finalize merge with "git commit".

Note that git will warn you that you are creating a merge commit, in the (rare) case where it is something you don't want. Probably remains from the days where said case was less rare.

SQL how to make null values come last when sorting ascending

Thanks RedFilter for providing excellent solution to the bugging issue of sorting nullable datetime field.

I am using SQL Server database for my project.

Changing the datetime null value to '1' does solves the problem of sorting for datetime datatype column. However if we have column with other than datetime datatype then it fails to handle.

To handle a varchar column sort, I tried using 'ZZZZZZZ' as I knew the column does not have values beginning with 'Z'. It worked as expected.

On the same lines, I used max values +1 for int and other data types to get the sort as expected. This also gave me the results as were required.

However, it would always be ideal to get something easier in the database engine itself that could do something like:

Order by Col1 Asc Nulls Last, Col2 Asc Nulls First 

As mentioned in the answer provided by a_horse_with_no_name.

What is the difference between String and string in C#?

String stands for System.String and it is a .NET Framework type. string is an alias in the C# language for System.String. Both of them are compiled to System.String in IL (Intermediate Language), so there is no difference. Choose what you like and use that. If you code in C#, I'd prefer string as it's a C# type alias and well-known by C# programmers.

I can say the same about (int, System.Int32) etc..

Show current assembly instruction in GDB

There is a simple solution that consists in using stepi, which in turns moves forward by 1 asm instruction and shows the surrounding asm code.

Custom height Bootstrap's navbar

your markup was a bit messed up. Here's the styles you need and proper html

CSS:

.navbar-brand,
.navbar-nav li a {
    line-height: 150px;
    height: 150px;
    padding-top: 0;
}

HTML:

<nav class="navbar navbar-default">
    <div class="navbar-header">
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>

        <a class="navbar-brand" href="#"><img src="img/logo.png" /></a>
    </div>

    <div class="collapse navbar-collapse">
        <ul class="nav navbar-nav">
            <li><a href="">Portfolio</a></li>
            <li><a href="">Blog</a></li>
            <li><a href="">Contact</a></li>
        </ul>
    </div>
</nav>

Or check out the fiddle at: http://jsfiddle.net/TP5V8/1/

Try-catch block in Jenkins pipeline script

This answer worked for me:

pipeline {
  agent any
  stages {
    stage("Run unit tests"){
      steps {
        script {
          try {
            sh  '''
              # Run unit tests without capturing stdout or logs, generates cobetura reports
              cd ./python
              nosetests3 --with-xcoverage --nocapture --with-xunit --nologcapture --cover-package=application
              cd ..
              '''
          } finally {
            junit 'nosetests.xml'
          }
        }
      }
    }
    stage ('Speak') {
      steps{
        echo "Hello, CONDITIONAL"
      }
    }
  }
}

How to get an object's properties in JavaScript / jQuery?

You can look up an object's keys and values by either invoking JavaScript's native for in loop:

var obj = {
    foo:    'bar',
    base:   'ball'
};

for(var key in obj) {
    alert('key: ' + key + '\n' + 'value: ' + obj[key]);
}

or using jQuery's .each() method:

$.each(obj, function(key, element) {
    alert('key: ' + key + '\n' + 'value: ' + element);
});

With the exception of six primitive types, everything in ECMA-/JavaScript is an object. Arrays; functions; everything is an object. Even most of those primitives are actually also objects with a limited selection of methods. They are cast into objects under the hood, when required. To know the base class name, you may invoke the Object.prototype.toString method on an object, like this:

alert(Object.prototype.toString.call([]));

The above will output [object Array].

There are several other class names, like [object Object], [object Function], [object Date], [object String], [object Number], [object Array], and [object Regex].

How to pass "Null" (a real surname!) to a SOAP web service in ActionScript 3

It's a kludge, but assuming there's a minimum length for SEARCHSTRING, for example 2 characters, substring the SEARCHSTRING parameter at the second character and pass it as two parameters instead: SEARCHSTRING1 ("Nu") and SEARCHSTRING2 ("ll"). Concatenate them back together when executing the query to the database.

Get fragment (value after hash '#') from a URL in php

I've been searching for a workaround for this for a bit - and the only thing I have found is to use URL rewrites to read the "anchor". I found in the apache docs here http://httpd.apache.org/docs/2.2/rewrite/advanced.html the following...

By default, redirecting to an HTML anchor doesn't work, because mod_rewrite escapes the # character, turning it into %23. This, in turn, breaks the redirection.

Solution: Use the [NE] flag on the RewriteRule. NE stands for No Escape.

Discussion: This technique will of course also work with other special characters that mod_rewrite, by default, URL-encodes.

It may have other caveats and what not ... but I think that at least doing something with the # on the server is possible.

How can I set a website image that will show as preview on Facebook?

Note also that if you have wordpress just scroll down to the bottom of the webpage when in edit mode, and select "featured image" (bottom right side of screen).

How do I see the extensions loaded by PHP?

Run command. You will get installed extentions:

php -r "print_r(get_loaded_extensions());"

Or run this command to get all module install and uninstall with version

dpkg -l | grep php5

basic authorization command for curl

curl -D- -X GET -H "Authorization: Basic ZnJlZDpmcmVk" -H "Content-Type: application/json" http://localhost:7990/rest/api/1.0/projects

--note

base46 encode =ZnJlZDpmcmVk

How to pass objects to functions in C++?

The following are the ways to pass a arguments/parameters to function in C++.

1. by value.

// passing parameters by value . . .

void foo(int x) 
{
    x = 6;  
}

2. by reference.

// passing parameters by reference . . .

void foo(const int &x) // x is a const reference
{
    x = 6;  
}

// passing parameters by const reference . . .

void foo(const int &x) // x is a const reference
{
    x = 6;  // compile error: a const reference cannot have its value changed!
}

3. by object.

class abc
{
    display()
    {
        cout<<"Class abc";
    }
}


// pass object by value
void show(abc S)
{
    cout<<S.display();
}

// pass object by reference
void show(abc& S)
{
    cout<<S.display();
}

Should I learn C before learning C++?

I think learning C first is a good idea.

There's a reason comp sci courses still use C.

In my opinion its to avoid all the "crowding" of the subject matter the obligation to require OOP carries.

I think that procedural programming is the most natural way to first learn programming. I think that's true because at the end of the day its what you have: lines of code executing one after the other.

Many texts today are pushing an "objects first" approach and start talking about cars and gearshifts before they introduce arrays.

Do AJAX requests retain PHP Session info?

put your session() auth in all server side pages accepting an ajax request:

if(require_once("auth.php")) {

//run json code

}

// do nothing otherwise

that's about the only way I've ever done it.

How can I get a list of all classes within current module in Python?

If you want to have all the classes, that belong to the current module, you could use this :

import sys, inspect
def print_classes():
    is_class_member = lambda member: inspect.isclass(member) and member.__module__ == __name__
    clsmembers = inspect.getmembers(sys.modules[__name__], is_class_member)

If you use Nadia's answer and you were importing other classes on your module, that classes will be being imported too.

So that's why member.__module__ == __name__ is being added to the predicate used on is_class_member. This statement checks that the class really belongs to the module.

A predicate is a function (callable), that returns a boolean value.

How do I change the number of open files limit in Linux?

If you are using Linux and you got the permission error, you will need to raise the allowed limit in the /etc/limits.conf or /etc/security/limits.conf file (where the file is located depends on your specific Linux distribution).

For example to allow anyone on the machine to raise their number of open files up to 10000 add the line to the limits.conf file.

* hard nofile 10000

Then logout and relogin to your system and you should be able to do:

ulimit -n 10000

without a permission error.

How to write PNG image to string with the PIL?

With modern (as of mid-2017 Python 3.5 and Pillow 4.0):

StringIO no longer seems to work as it used to. The BytesIO class is the proper way to handle this. Pillow's save function expects a string as the first argument, and surprisingly doesn't see StringIO as such. The following is similar to older StringIO solutions, but with BytesIO in its place.

from io import BytesIO
from PIL import Image

image = Image.open("a_file.png")
faux_file = BytesIO()
image.save(faux_file, 'png')

How to convert binary string value to decimal

  int base2(String bits) {
    int ans = 0;
    for (int i = bits.length() - 1, f = 1; i >= 0; i--) {
      ans += f * (bits.charAt(i) - '0');
      f <<= 1;
    }
    return ans;
  }

run a python script in terminal without the python command

There are three parts:

  1. Add a 'shebang' at the top of your script which tells how to execute your script
  2. Give the script 'run' permissions.
  3. Make the script in your PATH so you can run it from anywhere.

Adding a shebang

You need to add a shebang at the top of your script so the shell knows which interpreter to use when parsing your script. It is generally:

#!path/to/interpretter

To find the path to your python interpretter on your machine you can run the command:

which python

This will search your PATH to find the location of your python executable. It should come back with a absolute path which you can then use to form your shebang. Make sure your shebang is at the top of your python script:

#!/usr/bin/python

Run Permissions

You have to mark your script with run permissions so that your shell knows you want to actually execute it when you try to use it as a command. To do this you can run this command:

chmod +x myscript.py

Add the script to your path

The PATH environment variable is an ordered list of directories that your shell will search when looking for a command you are trying to run. So if you want your python script to be a command you can run from anywhere then it needs to be in your PATH. You can see the contents of your path running the command:

echo $PATH

This will print out a long line of text, where each directory is seperated by a semicolon. Whenever you are wondering where the actual location of an executable that you are running from your PATH, you can find it by running the command:

which <commandname>

Now you have two options: Add your script to a directory already in your PATH, or add a new directory to your PATH. I usually create a directory in my user home directory and then add it the PATH. To add things to your path you can run the command:

export PATH=/my/directory/with/pythonscript:$PATH

Now you should be able to run your python script as a command anywhere. BUT! if you close the shell window and open a new one, the new one won't remember the change you just made to your PATH. So if you want this change to be saved then you need to add that command at the bottom of your .bashrc or .bash_profile

How can I detect if this dictionary key exists in C#?

You can use ContainsKey:

if (dict.ContainsKey(key)) { ... }

or TryGetValue:

dict.TryGetValue(key, out value);

Update: according to a comment the actual class here is not an IDictionary but a PhysicalAddressDictionary, so the methods are Contains and TryGetValue but they work in the same way.

Example usage:

PhysicalAddressEntry entry;
PhysicalAddressKey key = c.PhysicalAddresses[PhysicalAddressKey.Home].Street;
if (c.PhysicalAddresses.TryGetValue(key, out entry))
{
    row["HomeStreet"] = entry;
}

Update 2: here is the working code (compiled by question asker)

PhysicalAddressEntry entry;
PhysicalAddressKey key = PhysicalAddressKey.Home;
if (c.PhysicalAddresses.TryGetValue(key, out entry))
{
    if (entry.Street != null)
    {
        row["HomeStreet"] = entry.Street.ToString();
    }
}

...with the inner conditional repeated as necessary for each key required. The TryGetValue is only done once per PhysicalAddressKey (Home, Work, etc).

Reading e-mails from Outlook with Python through MAPI

I had the same issue. Combining various approaches from the internet (and above) come up with the following approach (checkEmails.py)

class CheckMailer:

        def __init__(self, filename="LOG1.txt", mailbox="Mailbox - Another User Mailbox", folderindex=3):
            self.f = FileWriter(filename)
            self.outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI").Folders(mailbox)
            self.inbox = self.outlook.Folders(folderindex)


        def check(self):                
        #===============================================================================
        # for i in xrange(1,100):                           #Uncomment this section if index 3 does not work for you
        #     try:
        #         self.inbox = self.outlook.Folders(i)     # "6" refers to the index of inbox for Default User Mailbox
        #         print "%i %s" % (i,self.inbox)            # "3" refers to the index of inbox for Another user's mailbox
        #     except:
        #         print "%i does not work"%i
        #===============================================================================

                self.f.pl(time.strftime("%H:%M:%S"))
                tot = 0                
                messages = self.inbox.Items
                message = messages.GetFirst()
                while message:
                    self.f.pl (message.Subject)
                    message = messages.GetNext()
                    tot += 1
                self.f.pl("Total Messages found: %i" % tot)
                self.f.pl("-" * 80)
                self.f.flush()

if __name__ == "__main__":
    mail = CheckMailer()
    for i in xrange(320):  # this is 10.6 hours approximately
            mail.check()
            time.sleep(120.00)

For concistency I include also the code for the FileWriter class (found in FileWrapper.py). I needed this because trying to pipe UTF8 to a file in windows did not work.

class FileWriter(object):
    '''
    convenient file wrapper for writing to files
    '''


    def __init__(self, filename):
        '''
        Constructor
        '''
        self.file = open(filename, "w")

    def pl(self, a_string):
        str_uni = a_string.encode('utf-8')
        self.file.write(str_uni)
        self.file.write("\n")

    def flush(self):
        self.file.flush()

Opacity of div's background without affecting contained element in IE 8?

The opacity style affects the whole element and everything within it. The correct answer to this is to use an rgba background colour instead.

The CSS is fairly simple:

.myelement {
    background: rgba(200, 54, 54, 0.5);
}

...where the first three numbers are the red, green and blue values for your background colour, and the fourth is the 'alpha' channel value, which works the same way as the opacity value.

See this page for more info: http://css-tricks.com/rgba-browser-support/

The down-side, is that this doesn't work in IE8 or lower. The page I linked above also lists a few other browsers it doesn't work in, but they're all very old by now; all browsers in current use except IE6/7/8 will work with rgba colours.

The good news is that you can force IE to work with this as well, using a hack called CSS3Pie. CSS3Pie adds a number of modern CSS3 features to older versions of IE, including rgba background colours.

To use CSS3Pie for backgrounds, you need to add a specific -pie-background declaration to your CSS, as well as the PIE behavior style, so your stylesheet would end up looking like this:

.myelement {
    background: rgba(200, 54, 54, 0.5);
    -pie-background:  rgba(200, 54, 54, 0.5);
    behavior: url(PIE.htc);
}

Hope that helps.

[EDIT]

For what it's worth, as others have mentioned, you can use IE's filter style, with the gradient keyword. The CSS3Pie solution does actually use this same technique behind the scenes, but removes the need for you to mess around directly with IE's filters, so your stylesheets are much cleaner. (it also adds a whole bunch of other nice features too, but that's not relevant to this discussion)

Check if an element contains a class in JavaScript?

To check if an element contains a class, you use the contains() method of the classList property of the element:*

element.classList.contains(className);

*Suppose you have the following element:

<div class="secondary info">Item</div>*

To check if the element contains the secondary class, you use the following code:

 const div = document.querySelector('div');
 div.classList.contains('secondary'); // true

The following returns false because the element doesn’t have the class error:

 const div = document.querySelector('div');
 div.classList.contains('error'); // false

Jquery post, response in new window

I did it with an ajax post and then returned using a data url:

$(document).ready(function () {
    var exportClick = function () {
        $.ajax({
           url: "/api/test.php",
           type: "POST",
           dataType: "text",
           data: {
              action: "getCSV",
              filter: "name = 'smith'",
           },
           success: function(data) {
              var w = window.open('data:text/csv;charset=utf-8,' + encodeURIComponent(data));
              w.focus();
           },
           error: function () {
              alert('Problem getting data');
           },
        });
    }
});

CodeIgniter PHP Model Access "Unable to locate the model you have specified"

I resolve this with this way:

  1. I rename file do Page_model.php
  2. Class name to Page_model extends...
  3. I call on autoload: $autoload['model'] = array('Page_model'=>'page');

Works fine.. I hope help.

How to change UINavigationBar background color from the AppDelegate

You can set UINavigation Background color by using this code in any view controller

self.navigationController.navigationBar.backgroundColor = [UIColor colorWithRed:10.0f/255.0f green:30.0f/255.0f blue:200.0f/255.0f alpha:1.0f];

Disabling of EditText in Android

Simply:

editText.setEnabled(false);

Running Python on Windows for Node.js dependencies

Why not downloading the python installer here ? It make the work for you when you check the path installation

SQL SELECT multi-columns INTO multi-variable

SELECT @var = col1,
       @var2 = col2
FROM   Table

Here is some interesting information about SET / SELECT

  • SET is the ANSI standard for variable assignment, SELECT is not.
  • SET can only assign one variable at a time, SELECT can make multiple assignments at once.
  • If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
  • When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from it's previous value)
  • As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.

The controller for path was not found or does not implement IController

One other cause of this error: Accidental use of Html.Action in a Layout file where Html.ActionLink may have been intended. If the view referenced by the Html.Action uses the same Layout file you effectively have created an endless loop. (The layout view loads the referenced view as partial view which then loads the layout view which loads the referenced view...) If you set a breakpoint in the Layout file and single step through the Htlm.Action you will sometimes get a more helpful message about excessive stack size.

How to Convert JSON object to Custom C# object?

Performance-wise, I found the ServiceStack's serializer a bit faster than then others. It's JsonSerializer class in ServiceStack.Text namespace.

https://github.com/ServiceStack/ServiceStack.Text

ServiceStack is available through NuGet package: https://www.nuget.org/packages/ServiceStack/

Best practice for instantiating a new Android Fragment

setArguments() is useless. It only brings a mess.

public class MyFragment extends Fragment {

    public String mTitle;
    public String mInitialTitle;

    public static MyFragment newInstance(String param1) {
        MyFragment f = new MyFragment();
        f.mInitialTitle = param1;
        f.mTitle = param1;
        return f;
    }

    @Override
    public void onSaveInstanceState(Bundle state) {
        state.putString("mInitialTitle", mInitialTitle);
        state.putString("mTitle", mTitle);
        super.onSaveInstanceState(state);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state) {
        if (state != null) {
            mInitialTitle = state.getString("mInitialTitle");
            mTitle = state.getString("mTitle");
        } 
        ...
    }
}

JNI and Gradle in Android Studio

Gradle Build Tools 2.2.0+ - The closest the NDK has ever come to being called 'magic'

In trying to avoid experimental and frankly fed up with the NDK and all its hackery I am happy that 2.2.x of the Gradle Build Tools came out and now it just works. The key is the externalNativeBuild and pointing ndkBuild path argument at an Android.mk or change ndkBuild to cmake and point the path argument at a CMakeLists.txt build script.

android {
    compileSdkVersion 19
    buildToolsVersion "25.0.2"

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 19

        ndk {
            abiFilters 'armeabi', 'armeabi-v7a', 'x86'
        }

        externalNativeBuild {
            cmake {
                cppFlags '-std=c++11'
                arguments '-DANDROID_TOOLCHAIN=clang',
                        '-DANDROID_PLATFORM=android-19',
                        '-DANDROID_STL=gnustl_static',
                        '-DANDROID_ARM_NEON=TRUE',
                        '-DANDROID_CPP_FEATURES=exceptions rtti'
            }
        }
    }

    externalNativeBuild {
        cmake {
             path 'src/main/jni/CMakeLists.txt'
        }
        //ndkBuild {
        //   path 'src/main/jni/Android.mk'
        //}
    }
}

For much more detail check Google's page on adding native code.

After this is setup correctly you can ./gradlew installDebug and off you go. You will also need to be aware that the NDK is moving to clang since gcc is now deprecated in the Android NDK.

Android Studio Clean and Build Integration - DEPRECATED

The other answers do point out the correct way to prevent the automatic creation of Android.mk files, but they fail to go the extra step of integrating better with Android Studio. I have added the ability to actually clean and build from source without needing to go to the command-line. Your local.properties file will need to have ndk.dir=/path/to/ndk

apply plugin: 'com.android.application'

android {
    compileSdkVersion 14
    buildToolsVersion "20.0.0"

    defaultConfig {
        applicationId "com.example.application"
        minSdkVersion 14
        targetSdkVersion 14

        ndk {
            moduleName "YourModuleName"
        }
    }

    sourceSets.main {
        jni.srcDirs = [] // This prevents the auto generation of Android.mk
        jniLibs.srcDir 'src/main/libs' // This is not necessary unless you have precompiled libraries in your project.
    }

    task buildNative(type: Exec, description: 'Compile JNI source via NDK') {
        def ndkDir = android.ndkDirectory
        commandLine "$ndkDir/ndk-build",
                '-C', file('src/main/jni').absolutePath, // Change src/main/jni the relative path to your jni source
                '-j', Runtime.runtime.availableProcessors(),
                'all',
                'NDK_DEBUG=1'
    }

    task cleanNative(type: Exec, description: 'Clean JNI object files') {
        def ndkDir = android.ndkDirectory
        commandLine "$ndkDir/ndk-build",
                '-C', file('src/main/jni').absolutePath, // Change src/main/jni the relative path to your jni source
                'clean'
    }

    clean.dependsOn 'cleanNative'

    tasks.withType(JavaCompile) {
        compileTask -> compileTask.dependsOn buildNative
    }
}

dependencies {
    compile 'com.android.support:support-v4:20.0.0'
}

The src/main/jni directory assumes a standard layout of the project. It should be the relative from this build.gradle file location to the jni directory.

Gradle - for those having issues

Also check this Stack Overflow answer.

It is really important that your gradle version and general setup are correct. If you have an older project I highly recommend creating a new one with the latest Android Studio and see what Google considers the standard project. Also, use gradlew. This protects the developer from a gradle version mismatch. Finally, the gradle plugin must be configured correctly.

And you ask what is the latest version of the gradle plugin? Check the tools page and edit the version accordingly.

Final product - /build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

// Running 'gradle wrapper' will generate gradlew - Getting gradle wrapper working and using it will save you a lot of pain.
task wrapper(type: Wrapper) {
    gradleVersion = '2.2'
}

// Look Google doesn't use Maven Central, they use jcenter now.
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.2.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

Make sure gradle wrapper generates the gradlew file and gradle/wrapper subdirectory. This is a big gotcha.

ndkDirectory

This has come up a number of times, but android.ndkDirectory is the correct way to get the folder after 1.1. Migrating Gradle Projects to version 1.0.0. If you're using an experimental or ancient version of the plugin your mileage may vary.

Get WooCommerce product categories from WordPress

<?php

  $taxonomy     = 'product_cat';
  $orderby      = 'name';  
  $show_count   = 0;      // 1 for yes, 0 for no
  $pad_counts   = 0;      // 1 for yes, 0 for no
  $hierarchical = 1;      // 1 for yes, 0 for no  
  $title        = '';  
  $empty        = 0;

  $args = array(
         'taxonomy'     => $taxonomy,
         'orderby'      => $orderby,
         'show_count'   => $show_count,
         'pad_counts'   => $pad_counts,
         'hierarchical' => $hierarchical,
         'title_li'     => $title,
         'hide_empty'   => $empty
  );
 $all_categories = get_categories( $args );
 foreach ($all_categories as $cat) {
    if($cat->category_parent == 0) {
        $category_id = $cat->term_id;       
        echo '<br /><a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .'</a>';

        $args2 = array(
                'taxonomy'     => $taxonomy,
                'child_of'     => 0,
                'parent'       => $category_id,
                'orderby'      => $orderby,
                'show_count'   => $show_count,
                'pad_counts'   => $pad_counts,
                'hierarchical' => $hierarchical,
                'title_li'     => $title,
                'hide_empty'   => $empty
        );
        $sub_cats = get_categories( $args2 );
        if($sub_cats) {
            foreach($sub_cats as $sub_category) {
                echo  $sub_category->name ;
            }   
        }
    }       
}
?>

This will list all the top level categories and subcategories under them hierarchically. do not use the inner query if you just want to display the top level categories. Style it as you like.

How to export a Hive table into a CSV file?

INSERT OVERWRITE LOCAL DIRECTORY '/home/lvermeer/temp' ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' select * from table; 

is the correct answer.

If the number of records is really big, based on the number of files generated

the following command would give only partial result.

hive -e 'select * from some_table' > /home/yourfile.csv

Imshow: extent and aspect

From plt.imshow() official guide, we know that aspect controls the aspect ratio of the axes. Well in my words, the aspect is exactly the ratio of x unit and y unit. Most of the time we want to keep it as 1 since we do not want to distort out figures unintentionally. However, there is indeed cases that we need to specify aspect a value other than 1. The questioner provided a good example that x and y axis may have different physical units. Let's assume that x is in km and y in m. Hence for a 10x10 data, the extent should be [0,10km,0,10m] = [0, 10000m, 0, 10m]. In such case, if we continue to use the default aspect=1, the quality of the figure is really bad. We can hence specify aspect = 1000 to optimize our figure. The following codes illustrate this method.

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
rng=np.random.RandomState(0)
data=rng.randn(10,10)
plt.imshow(data, origin = 'lower',  extent = [0, 10000, 0, 10], aspect = 1000)

enter image description here

Nevertheless, I think there is an alternative that can meet the questioner's demand. We can just set the extent as [0,10,0,10] and add additional xy axis labels to denote the units. Codes as follows.

plt.imshow(data, origin = 'lower',  extent = [0, 10, 0, 10])
plt.xlabel('km')
plt.ylabel('m')

enter image description here

To make a correct figure, we should always bear in mind that x_max-x_min = x_res * data.shape[1] and y_max - y_min = y_res * data.shape[0], where extent = [x_min, x_max, y_min, y_max]. By default, aspect = 1, meaning that the unit pixel is square. This default behavior also works fine for x_res and y_res that have different values. Extending the previous example, let's assume that x_res is 1.5 while y_res is 1. Hence extent should equal to [0,15,0,10]. Using the default aspect, we can have rectangular color pixels, whereas the unit pixel is still square!

plt.imshow(data, origin = 'lower',  extent = [0, 15, 0, 10])
# Or we have similar x_max and y_max but different data.shape, leading to different color pixel res.
data=rng.randn(10,5)
plt.imshow(data, origin = 'lower',  extent = [0, 5, 0, 5])

enter image description here enter image description here

The aspect of color pixel is x_res / y_res. setting its aspect to the aspect of unit pixel (i.e. aspect = x_res / y_res = ((x_max - x_min) / data.shape[1]) / ((y_max - y_min) / data.shape[0])) would always give square color pixel. We can change aspect = 1.5 so that x-axis unit is 1.5 times y-axis unit, leading to a square color pixel and square whole figure but rectangular pixel unit. Apparently, it is not normally accepted.

data=rng.randn(10,10)
plt.imshow(data, origin = 'lower',  extent = [0, 15, 0, 10], aspect = 1.5)

enter image description here

The most undesired case is that set aspect an arbitrary value, like 1.2, which will lead to neither square unit pixels nor square color pixels.

plt.imshow(data, origin = 'lower',  extent = [0, 15, 0, 10], aspect = 1.2)

enter image description here

Long story short, it is always enough to set the correct extent and let the matplotlib do the remaining things for us (even though x_res!=y_res)! Change aspect only when it is a must.

How do I make WRAP_CONTENT work on a RecyclerView

Put the recyclerview in any other layout (Relative layout is preferable). Then change recyclerview's height/width as match parent to that layout and set the parent layout's height/width as wrap content.

Source: This comment.

Get value of Span Text

The accepted answer is close... but no cigar!

Use textContent instead of innerHTML if you strictly want a string to be returned to you.

innerHTML can have the side effect of giving you a node element if there's other dom elements in there. textContent will guard against this possibility.

Angular JS - angular.forEach - How to get key of the object?

The first parameter to the iterator in forEach is the value and second is the key of the object.

angular.forEach(objectToIterate, function(value, key) {
    /* do something for all key: value pairs */
});

In your example, the outer forEach is actually:

angular.forEach($scope.filters, function(filterObj , filterKey)

count (non-blank) lines-of-code in bash

'wc' counts lines, words, chars, so to count all lines (including blank ones) use:

wc *.py

To filter out the blank lines, you can use grep:

grep -v '^\s*$' *.py | wc

'-v' tells grep to output all lines except those that match '^' is the start of a line '\s*' is zero or more whitespace characters '$' is the end of a line *.py is my example for all the files you wish to count (all python files in current dir) pipe output to wc. Off you go.

I'm answering my own (genuine) question. Couldn't find an stackoverflow entry that covered this.

Provide an image for WhatsApp link sharing

I've been trying to do this myself as well and I've added all the right meta tags :

<meta property="og:image" itemprop="image" content="image_url" />
<meta property="og:image:url" itemprop="image" content="image_url" />
<meta property="og:image:type" content="image/png" />

but yet could not see the image when sharing my link within WhatsApp.

I've discovered that WhatsApp also does some kind of caching of the image and the url info, dont know for how long.

To check that I've inserted the correct tags, I just tried different url, for example : http://domain.com instead of http://www.domain.com .

hopefully this helps to someone else.

How to keep the header static, always on top while scrolling?

I personally needed a table with both the left and top headers visible at all times. Inspired by several articles, I think I have a good solution that you may find helpful. This version does not have the wrapping problem that other soltions have with floating divs or flexible/auto sizing of columns and rows.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script language="javascript" type="text/javascript" src="/Scripts/jquery-1.7.2.min.js"></script>
    <script language="javascript" type="text/javascript">
        // Handler for scrolling events
        function scrollFixedHeaderTable() {
            var outerPanel = $("#_outerPanel");
            var cloneLeft = $("#_cloneLeft");
            var cloneTop = $("#_cloneTop");
            cloneLeft.css({ 'margin-top': -outerPanel.scrollTop() });
            cloneTop.css({ 'margin-left': -outerPanel.scrollLeft() });
        }

        function initFixedHeaderTable() {
            var outerPanel = $("#_outerPanel");
            var innerPanel = $("#_innerPanel");
            var clonePanel = $("#_clonePanel");
            var table = $("#_table");
            // We will clone the table 2 times: For the top rowq and the left column. 
            var cloneLeft = $("#_cloneLeft");
            var cloneTop = $("#_cloneTop");
            var cloneTop = $("#_cloneTopLeft");
            // Time to create the table clones
            cloneLeft = table.clone();
            cloneTop = table.clone();
            cloneTopLeft = table.clone();
            cloneLeft.attr('id', '_cloneLeft');
            cloneTop.attr('id', '_cloneTop');
            cloneTopLeft.attr('id', '_cloneTopLeft');
            cloneLeft.css({
                position: 'fixed',
                'pointer-events': 'none',
                top: outerPanel.offset().top,
                'z-index': 1 // keep lower than top-left below
            });
            cloneTop.css({
                position: 'fixed',
                'pointer-events': 'none',
                top: outerPanel.offset().top,
                'z-index': 1 // keep lower than top-left below
            });
            cloneTopLeft.css({
                position: 'fixed',
                'pointer-events': 'none',
                top: outerPanel.offset().top,
                'z-index': 2 // higher z-index than the left and top to make the top-left header cell logical
            });
            // Add the controls to the control-tree
            clonePanel.append(cloneLeft);
            clonePanel.append(cloneTop);
            clonePanel.append(cloneTopLeft);
            // Keep all hidden: We will make the individual header cells visible in a moment
            cloneLeft.css({ visibility: 'hidden' });
            cloneTop.css({ visibility: 'hidden' });
            cloneTopLeft.css({ visibility: 'hidden' });
            // Make the lef column header cells visible in the left clone
            $("#_cloneLeft td._hdr.__row").css({
                visibility: 'visible',
            });
            // Make the top row header cells visible in the top clone
            $("#_cloneTop td._hdr.__col").css({
                visibility: 'visible',
            });
            // Make the top-left cell visible in the top-left clone
            $("#_cloneTopLeft td._hdr.__col.__row").css({
                visibility: 'visible',
            });
            // Clipping. First get the inner width/height by measuring it (normal innerWidth did not work for me)
            var helperDiv = $('<div style="positions: absolute; top: 0; right: 0; bottom: 0; left: 0; height: 100%;"></div>');
            outerPanel.append(helperDiv);
            var innerWidth = helperDiv.width();
            var innerHeight = helperDiv.height();
            helperDiv.remove(); // because we dont need it anymore, do we?
            // Make sure all the panels are clipped, or the clones will extend beyond them
            outerPanel.css({ clip: 'rect(0px,' + String(outerPanel.width()) + 'px,' + String(outerPanel.height()) + 'px,0px)' });
            // Clone panel clipping to prevent the clones from covering the outerPanel's scrollbars (this is why we use a separate div for this)
            clonePanel.css({ clip: 'rect(0px,' + String(innerWidth) + 'px,' + String(innerHeight) + 'px,0px)'   });
            // Subscribe the scrolling of the outer panel to our own handler function to move the clones as needed.
            $("#_outerPanel").scroll(scrollFixedHeaderTable);
        }


        $(document).ready(function () {
            initFixedHeaderTable();
        });

    </script>
    <style type="text/css">
        * {
            clip: rect font-family: Arial;
            font-size: 16px;
            margin: 0;
            padding: 0;
        }

        #_outerPanel {
            margin: 0px;
            padding: 0px;
            position: absolute;
            left: 50px;
            top: 50px;
            right: 50px;
            bottom: 50px;
            overflow: auto;
            z-index: 1000;
        }

        #_innerPanel {
            overflow: visible;
            position: absolute;
        }

        #_clonePanel {
            overflow: visible;
            position: fixed;
        }

        table {
        }

        td {
            white-space: nowrap;
            border-right: 1px solid #000;
            border-bottom: 1px solid #000;
            padding: 2px 2px 2px 2px;
        }

        td._hdr {
            color: Blue;
            font-weight: bold;
        }
        td._hdr.__row {
            background-color: #eee;
            border-left: 1px solid #000;
        }
        td._hdr.__col {
            background-color: #ddd;
            border-top: 1px solid #000;
        }
    </style>
</head>
<body>
    <div id="_outerPanel">
        <div id="_innerPanel">
            <div id="_clonePanel"></div>
            <table id="_table" border="0" cellpadding="0" cellspacing="0">
                <thead id="_topHeader" style="background-color: White;">
                    <tr class="row">
                        <td class="_hdr __col __row">
                            &nbsp;
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                    </tr>
                </thead>
                <tbody>
                    <tr class="row">
                        <td class="_hdr __row">
                            MY HEADER COLUMN:
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                    </tr>
                    <tr class="row">
                        <td class="_hdr __row">
                            MY HEADER COLUMN:
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
        <div id="_bottomAnchor">
        </div>
    </div>
</body>
</html>

CSS to make table 100% of max-width

Use this :

<div style="width:700px; background:#F2F2F2">
    <table style="width:100%;padding: 25px; margin: 0 auto; font-family:'Open Sans', 'Helvetica', 'Arial';">
        <tr align="center" style="margin: 0; padding: 0;">
            <td>
                <table style="width:100%;border-style:solid; border-width:2px; border-color: #c3d2d9;" cellspacing="0">
                    <tr style="background-color: white;">
                        <td style=" padding: 10px 15px 10px 15px; color: #000000;">
                            <p>Some content here</p>
                            <span style="font-weight: bold;">My Signature</span><br/>
                            My Title<br/>
                            My Company<br/>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</div>

Efficiently getting all divisors of a given number

//DIVISORS IN TIME COMPLEXITY sqrt(n)

#include<bits/stdc++.h>
using namespace std;

#define ll long long

int main()
{
    ll int n;
    cin >> n;

    for(ll i = 2;  i <= sqrt(n); i++)
    {
        if (n%i==0)
        {
            if (n/i!=i)
                cout << i << endl << n/i<< endl;
            else
                cout << i << endl;
        }
    }
}

What is the difference between .NET Core and .NET Standard Class Library project types?

Another way of explaining the difference could be with real world examples, as most of us mere mortals will use existing tools and frameworks (Xamarin, Unity, etc.) to do the job.

So, with .NET Framework you have all the .NET tools to work with, but you can only target Windows applications (UWP, Windows Forms, ASP.NET, etc.). Since .NET Framework is closed source there isn't much to do about it.

With .NET Core you have fewer tools, but you can target the main desktop platforms (Windows, Linux, and Mac). This is specially useful in ASP.NET Core applications, since you can now host ASP.NET on Linux (cheaper hosting prices). Now, since .NET Core was open sourced, it's technically possible to develop libraries for other platforms. But since there aren't frameworks that support it, I don't think that's a good idea.

With .NET Standard you have even fewer tools, but you can target all/most platforms. You can target mobile thanks to Xamarin, and you can even target game consoles thanks to Mono/Unity. It's also possible to target web clients with the UNO platform and Blazor (although both are kind of experimental right now).

In a real-world application you may need to use all of them. For example, I developed a point of sale application that had the following architecture:

Shared both server and slient:

  • A .NET Standard library that handles the models of my application.
  • A .NET Standard library that handles the validation of data sent by the clients.

Since it's a .NET Standard library, it can be used in any other project (client and server).

Also a nice advantage of having the validation on a .NET standard library since I can be sure the same validation is applied on the server and the client. Server is mandatory, while client is optional and useful to reduce traffic.

Server side (Web API):

  • A .NET Standard (could be .NET Core as well) library that handles all the database connections.

  • A .NET Core project that handles the Rest API and makes use of the database library.

As this is developed in .NET Core, I can host the application on a Linux server.

Client side (MVVM with WPF + Xamarin.Forms Android/iOS):

  • A .NET Standard library that handles the client API connection.

  • A .NET Standard library that handles the ViewModels logic. It is used in all the views.

  • A .NET Framework WPF application that handles the WPF views for a windows application. WPF applications can be .NET core now, although they only work on Windows currently. AvaloniaUI is a good alternative for making desktop GUI applications for other desktop platforms.

  • A .NET Standard library that handles Xamarin forms views.

  • A Xamarin Android and Xamarin iOS project.

So you can see that there's a big advantage here on the client side of the application, since I can reuse both .NET Standard libraries (client API and ViewModels) and just make views with no logic for the WPF, Xamarin and iOS applications.

Get all object attributes in Python?

Use the built-in function dir().

How to copy to clipboard in Vim?

Shift+Ctrl+C if you are in graphical mode of Linux, but first you need to select what you need to copy.

enter image description here

Git cli: get user info from username

While its true that git commits don't have a specific field called "username", a git repo does have users, and the users do have names. ;) If what you want is the github username, then knittl's answer is right. But since your question asked about git cli and not github, here's how you get a git user's email address using the command line:

To see a list of all users in a git repo using the git cli:

git log --format="%an %ae" | sort | uniq

To search for a specific user by name, e.g., "John":

git log --format="%an %ae" | sort | uniq | grep -i john

fatal: bad default revision 'HEAD'

just do an initial commit and the error will go away:

git commit -m "initial commit"

Git for Windows: .bashrc or equivalent configuration files for Git Bash shell

for gitbash in windows10 look out for the config file in

/.gitconfig file

Error: "an object reference is required for the non-static field, method or property..."

Change your signatures to private static bool siprimo(long a) and private static long volteado(long a) and see where that gets you.

How do I specify different layouts for portrait and landscape orientations?

I think the easiest way in the latest Android versions is by going to Design mode of an XML (not Text).

Then from the menu, select option - Create Landscape Variation. This will create a landscape xml without any hassle in a few seconds. The latest Android Studio version allows you to create a landscape view right away.

enter image description here

I hope this works for you.

How to change the time format (12/24 hours) of an <input>?

Even though you see the time in HH:MM AM/PM format, on the backend it still works in 24 hour format, you can try using some basic javascript to see that.

Linking a qtDesigner .ui file to python/pyqt?

(November 2020) This worked for me (UBUNTU 20.04):

pyuic5 /home/someuser/Documents/untitled.ui > /home/someuser/Documents/untitled.py

Difference between string and text in rails?

String translates to "Varchar" in your database, while text translates to "text". A varchar can contain far less items, a text can be of (almost) any length.

For an in-depth analysis with good references check http://www.pythian.com/news/7129/text-vs-varchar/

Edit: Some database engines can load varchar in one go, but store text (and blob) outside of the table. A SELECT name, amount FROM products could, be a lot slower when using text for name than when you use varchar. And since Rails, by default loads records with SELECT * FROM... your text-columns will be loaded. This will probably never be a real problem in your or my app, though (Premature optimization is ...). But knowing that text is not always "free" is good to know.

Highcharts - redraw() vs. new Highcharts.chart

@RobinL as mentioned in previous comments, you can use chart.series[n].setData(). First you need to make sure you’ve assigned a chart instance to the chart variable, that way it adopts all the properties and methods you need to access and manipulate the chart.

I’ve also used the second parameter of setData() and had it false, to prevent automatic rendering of the chart. This was because I have multiple data series, so I’ll rather update each of them, with render=false, and then running chart.redraw(). This multiplied performance (I’m having 10,000-100,000 data points and refreshing the data set every 50 milliseconds).

What's the difference between a word and byte?

The terms of BYTE and WORD are relative to the size of the processor that is being referred to. The most common processors are/were 8 bit, 16 bit, 32 bit or 64 bit. These are the WORD lengths of the processor. Actually half of a WORD is a BYTE, whatever the numerical length is. Ready for this, half of a BYTE is a NIBBLE.

How do you see the entire command history in interactive Python?

With python 3 interpreter the history is written to
~/.python_history

How do I detect a page refresh using jquery?

All the code is client side, I hope you fine this helpful:

First thing there are 3 functions we will use:

    function setCookie(c_name, value, exdays) {
            var exdate = new Date();
            exdate.setDate(exdate.getDate() + exdays);
            var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
            document.cookie = c_name + "=" + c_value;
        }

    function getCookie(c_name) {
        var i, x, y, ARRcookies = document.cookie.split(";");
        for (i = 0; i < ARRcookies.length; i++) {
            x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
            y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
            x = x.replace(/^\s+|\s+$/g, "");
            if (x == c_name) {
                return unescape(y);
            }
        }
    }

    function DeleteCookie(name) {
            document.cookie = name + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
        }

Now we will start with the page load:

$(window).load(function () {
 //if IsRefresh cookie exists
 var IsRefresh = getCookie("IsRefresh");
 if (IsRefresh != null && IsRefresh != "") {
    //cookie exists then you refreshed this page(F5, reload button or right click and reload)
    //SOME CODE
    DeleteCookie("IsRefresh");
 }
 else {
    //cookie doesnt exists then you landed on this page
    //SOME CODE
    setCookie("IsRefresh", "true", 1);
 }
})

Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'

It could be that the corresponding Gradle version was not downloaded properly.

You could delete the broken file at

rm -rf .gradle/wrapper/dists/

and restart studio.

or try

File -> Settings -> Gradle -> Check Offline Work

and download the file from the official site and extract to the destination location

.gradle/wrapper/dists/

Make $JAVA_HOME easily changable in Ubuntu

Put the environment variables into the global /etc/environment file:

...
export JAVA_HOME=/usr/lib/jvm/java-1.5.0-sun
...

Execute "source /etc/environment" in every shell where you want the variables to be updated:

$ source /etc/environment

Check that it works:

$ echo $JAVA_HOME
$ /usr/lib/jvm/java-1.5.0-sun

Great, no logout needed.

If you want to set JAVA_HOME environment variable in only the terminal, set it in ~/.bashrc file.

Hidden features of Windows batch files

Output a blank line:

echo.

Calculate the mean by group

There are many ways to do this in R. Specifically, by, aggregate, split, and plyr, cast, tapply, data.table, dplyr, and so forth.

Broadly speaking, these problems are of the form split-apply-combine. Hadley Wickham has written a beautiful article that will give you deeper insight into the whole category of problems, and it is well worth reading. His plyr package implements the strategy for general data structures, and dplyr is a newer implementation performance tuned for data frames. They allow for solving problems of the same form but of even greater complexity than this one. They are well worth learning as a general tool for solving data manipulation problems.

Performance is an issue on very large datasets, and for that it is hard to beat solutions based on data.table. If you only deal with medium-sized datasets or smaller, however, taking the time to learn data.table is likely not worth the effort. dplyr can also be fast, so it is a good choice if you want to speed things up, but don't quite need the scalability of data.table.

Many of the other solutions below do not require any additional packages. Some of them are even fairly fast on medium-large datasets. Their primary disadvantage is either one of metaphor or of flexibility. By metaphor I mean that it is a tool designed for something else being coerced to solve this particular type of problem in a 'clever' way. By flexibility I mean they lack the ability to solve as wide a range of similar problems or to easily produce tidy output.


Examples

base functions

tapply:

tapply(df$speed, df$dive, mean)
#     dive1     dive2 
# 0.5419921 0.5103974

aggregate:

aggregate takes in data.frames, outputs data.frames, and uses a formula interface.

aggregate( speed ~ dive, df, mean )
#    dive     speed
# 1 dive1 0.5790946
# 2 dive2 0.4864489

by:

In its most user-friendly form, it takes in vectors and applies a function to them. However, its output is not in a very manipulable form.:

res.by <- by(df$speed, df$dive, mean)
res.by
# df$dive: dive1
# [1] 0.5790946
# ---------------------------------------
# df$dive: dive2
# [1] 0.4864489

To get around this, for simple uses of by the as.data.frame method in the taRifx library works:

library(taRifx)
as.data.frame(res.by)
#    IDX1     value
# 1 dive1 0.6736807
# 2 dive2 0.4051447

split:

As the name suggests, it performs only the "split" part of the split-apply-combine strategy. To make the rest work, I'll write a small function that uses sapply for apply-combine. sapply automatically simplifies the result as much as possible. In our case, that means a vector rather than a data.frame, since we've got only 1 dimension of results.

splitmean <- function(df) {
  s <- split( df, df$dive)
  sapply( s, function(x) mean(x$speed) )
}
splitmean(df)
#     dive1     dive2 
# 0.5790946 0.4864489 

External packages

data.table:

library(data.table)
setDT(df)[ , .(mean_speed = mean(speed)), by = dive]
#    dive mean_speed
# 1: dive1  0.5419921
# 2: dive2  0.5103974

dplyr:

library(dplyr)
group_by(df, dive) %>% summarize(m = mean(speed))

plyr (the pre-cursor of dplyr)

Here's what the official page has to say about plyr:

It’s already possible to do this with base R functions (like split and the apply family of functions), but plyr makes it all a bit easier with:

  • totally consistent names, arguments and outputs
  • convenient parallelisation through the foreach package
  • input from and output to data.frames, matrices and lists
  • progress bars to keep track of long running operations
  • built-in error recovery, and informative error messages
  • labels that are maintained across all transformations

In other words, if you learn one tool for split-apply-combine manipulation it should be plyr.

library(plyr)
res.plyr <- ddply( df, .(dive), function(x) mean(x$speed) )
res.plyr
#    dive        V1
# 1 dive1 0.5790946
# 2 dive2 0.4864489

reshape2:

The reshape2 library is not designed with split-apply-combine as its primary focus. Instead, it uses a two-part melt/cast strategy to perform a wide variety of data reshaping tasks. However, since it allows an aggregation function it can be used for this problem. It would not be my first choice for split-apply-combine operations, but its reshaping capabilities are powerful and thus you should learn this package as well.

library(reshape2)
dcast( melt(df), variable ~ dive, mean)
# Using dive as id variables
#   variable     dive1     dive2
# 1    speed 0.5790946 0.4864489

Benchmarks

10 rows, 2 groups

library(microbenchmark)
m1 <- microbenchmark(
  by( df$speed, df$dive, mean),
  aggregate( speed ~ dive, df, mean ),
  splitmean(df),
  ddply( df, .(dive), function(x) mean(x$speed) ),
  dcast( melt(df), variable ~ dive, mean),
  dt[, mean(speed), by = dive],
  summarize( group_by(df, dive), m = mean(speed) ),
  summarize( group_by(dt, dive), m = mean(speed) )
)

> print(m1, signif = 3)
Unit: microseconds
                                           expr  min   lq   mean median   uq  max neval      cld
                    by(df$speed, df$dive, mean)  302  325  343.9    342  362  396   100  b      
              aggregate(speed ~ dive, df, mean)  904  966 1012.1   1020 1060 1130   100     e   
                                  splitmean(df)  191  206  249.9    220  232 1670   100 a       
  ddply(df, .(dive), function(x) mean(x$speed)) 1220 1310 1358.1   1340 1380 2740   100      f  
         dcast(melt(df), variable ~ dive, mean) 2150 2330 2440.7   2430 2490 4010   100        h
                   dt[, mean(speed), by = dive]  599  629  667.1    659  704  771   100   c     
 summarize(group_by(df, dive), m = mean(speed))  663  710  774.6    744  782 2140   100    d    
 summarize(group_by(dt, dive), m = mean(speed)) 1860 1960 2051.0   2020 2090 3430   100       g 

autoplot(m1)

benchmark 10 rows

As usual, data.table has a little more overhead so comes in about average for small datasets. These are microseconds, though, so the differences are trivial. Any of the approaches works fine here, and you should choose based on:

  • What you're already familiar with or want to be familiar with (plyr is always worth learning for its flexibility; data.table is worth learning if you plan to analyze huge datasets; by and aggregate and split are all base R functions and thus universally available)
  • What output it returns (numeric, data.frame, or data.table -- the latter of which inherits from data.frame)

10 million rows, 10 groups

But what if we have a big dataset? Let's try 10^7 rows split over ten groups.

df <- data.frame(dive=factor(sample(letters[1:10],10^7,replace=TRUE)),speed=runif(10^7))
dt <- data.table(df)
setkey(dt,dive)

m2 <- microbenchmark(
  by( df$speed, df$dive, mean),
  aggregate( speed ~ dive, df, mean ),
  splitmean(df),
  ddply( df, .(dive), function(x) mean(x$speed) ),
  dcast( melt(df), variable ~ dive, mean),
  dt[,mean(speed),by=dive],
  times=2
)

> print(m2, signif = 3)
Unit: milliseconds
                                           expr   min    lq    mean median    uq   max neval      cld
                    by(df$speed, df$dive, mean)   720   770   799.1    791   816   958   100    d    
              aggregate(speed ~ dive, df, mean) 10900 11000 11027.0  11000 11100 11300   100        h
                                  splitmean(df)   974  1040  1074.1   1060  1100  1280   100     e   
  ddply(df, .(dive), function(x) mean(x$speed))  1050  1080  1110.4   1100  1130  1260   100      f  
         dcast(melt(df), variable ~ dive, mean)  2360  2450  2492.8   2490  2520  2620   100       g 
                   dt[, mean(speed), by = dive]   119   120   126.2    120   122   212   100 a       
 summarize(group_by(df, dive), m = mean(speed))   517   521   531.0    522   532   620   100   c     
 summarize(group_by(dt, dive), m = mean(speed))   154   155   174.0    156   189   321   100  b      

autoplot(m2)

benchmark 1e7 rows, 10 groups

Then data.table or dplyr using operating on data.tables is clearly the way to go. Certain approaches (aggregate and dcast) are beginning to look very slow.

10 million rows, 1,000 groups

If you have more groups, the difference becomes more pronounced. With 1,000 groups and the same 10^7 rows:

df <- data.frame(dive=factor(sample(seq(1000),10^7,replace=TRUE)),speed=runif(10^7))
dt <- data.table(df)
setkey(dt,dive)

# then run the same microbenchmark as above
print(m3, signif = 3)
Unit: milliseconds
                                           expr   min    lq    mean median    uq   max neval    cld
                    by(df$speed, df$dive, mean)   776   791   816.2    810   828   925   100  b    
              aggregate(speed ~ dive, df, mean) 11200 11400 11460.2  11400 11500 12000   100      f
                                  splitmean(df)  5940  6450  7562.4   7470  8370 11200   100     e 
  ddply(df, .(dive), function(x) mean(x$speed))  1220  1250  1279.1   1280  1300  1440   100   c   
         dcast(melt(df), variable ~ dive, mean)  2110  2190  2267.8   2250  2290  2750   100    d  
                   dt[, mean(speed), by = dive]   110   111   113.5    111   113   143   100 a     
 summarize(group_by(df, dive), m = mean(speed))   625   630   637.1    633   644   701   100  b    
 summarize(group_by(dt, dive), m = mean(speed))   129   130   137.3    131   142   213   100 a     

autoplot(m3)

enter image description here

So data.table continues scaling well, and dplyr operating on a data.table also works well, with dplyr on data.frame close to an order of magnitude slower. The split/sapply strategy seems to scale poorly in the number of groups (meaning the split() is likely slow and the sapply is fast). by continues to be relatively efficient--at 5 seconds, it's definitely noticeable to the user but for a dataset this large still not unreasonable. Still, if you're routinely working with datasets of this size, data.table is clearly the way to go - 100% data.table for the best performance or dplyr with dplyr using data.table as a viable alternative.

How do I plot list of tuples in Python?

You could also use zip

import matplotlib.pyplot as plt

l = [(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),
     (2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),
     (4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]

x, y = zip(*l)

plt.plot(x, y)

HTML - Alert Box when loading page

For making alert just put below javascript code in footer.

<script> 
 $(document).ready(function(){
    alert('Hi');
 });
</script>

You need to also load jquery min file. Please insert this script in header.

<script type='text/javascript' src='https://code.jquery.com/jquery-1.12.0.min.js'></script>

Python dictionary: Get list of values for list of keys

Try this:

mydict = {'one': 1, 'two': 2, 'three': 3}
mykeys = ['three', 'one'] # if there are many keys, use a set

[mydict[k] for k in mykeys]
=> [3, 1]

Fix GitLab error: "you are not allowed to push code to protected branches on this project"?

I have encountered this error on "an empty branch" on my local gitlab server. Some people mentioned that "you can not push for the first time on an empty branch". I tried to create a simple README file on the gitlab via my browser. Then everything fixed amazingly and the problem sorted out!! I mention that I was the master and the branch was not protected.

In LaTeX, how can one add a header/footer in the document class Letter?

With regard to Brent.Longborough's answer (appering only on page 2 onward), perhaps you need to set the \thispagestyle{} after \begin{document}. I wonder if the letter class is setting the first page style to empty.

What does `ValueError: cannot reindex from a duplicate axis` mean?

I wasted couple of hours on the same issue. In my case, I had to reset_index() of a dataframe before using apply function. Before merging, or looking up from another indexed dataset, you need to reset the index as 1 dataset can have only 1 Index.

Install an apk file from command prompt?

You're likely here because you want to build it too!

Build

gradlew

(On Windows gradlew.bat)

Then Install

adb install -r exampleApp.apk

(The -r makes it replace the existing copy, add an -s if installing on an emulator)

Bonus

I set up an alias in my ~/.bash_profile

alias bi="gradlew && adb install -r exampleApp.apk"

(Short for Build and Install)

'react-scripts' is not recognized as an internal or external command

  1. I uninstalled my Node.js and showed hidden files.

  2. Then, I went to C:\Users\yourpcname\AppData\Roaming\ and deleted the npm and npm-cache folders.

  3. Finally, I installed a new version of Node.js.

Watching variables in SSIS during debug

I believe you can only add variables to the Watch window while the debugger is stopped on a breakpoint. If you set a breakpoint on a step, you should be able to enter variables into the Watch window when the breakpoint is hit. You can select the first empty row in the Watch window and enter the variable name (you may or may not get some Intellisense there, I can't remember how well that works.)

Email address validation using ASP.NET MVC data type attributes

I use MVC 3. An example of email address property in one of my classes is:

[Display(Name = "Email address")]
[Required(ErrorMessage = "The email address is required")]
[Email(ErrorMessage = "The email address is not valid")]
public string Email { get; set; }

Remove the Required if the input is optional. No need for regular expressions although I have one which covers all of the options within an email address up to RFC 2822 level (it's very long).

Spring RestTemplate timeout

I had a similar scenario, but was also required to set a Proxy. The simplest way I could see to do this was to extend the SimpleClientHttpRequestFactory for the ease of setting the proxy (different proxies for non-prod vs prod). This should still work even if you don't require the proxy though. Then in my extended class I override the openConnection(URL url, Proxy proxy) method, using the same as the source, but just setting the timeouts before returning.

@Override
protected HttpURLConnection openConnection(URL url, Proxy proxy) throws IOException {
    URLConnection urlConnection = proxy != null ? url.openConnection(proxy) : url.openConnection();
    Assert.isInstanceOf(HttpURLConnection.class, urlConnection);
    urlConnection.setConnectTimeout(5000);
    urlConnection.setReadTimeout(5000);
    return (HttpURLConnection) urlConnection;
}

How can I refresh a page with jQuery?

I found

window.location.href = "";

or

window.location.href = null;

also makes a page refresh.

This makes it very much easier to reload the page removing any hash. This is very nice when I am using AngularJS in the iOS simulator, so that I don't have to rerun the app.

NoClassDefFoundError - Eclipse and Android

John O'Connor is right with the issue. The problem stays with installing ADT 17 and above. Found this link for fixing the error:

http://android.foxykeep.com/dev/how-to-fix-the-classdefnotfounderror-with-adt-17

Evenly space multiple views within a container view

With labels this works fine at least:

@"H:|-15-[first(==second)]-[second(==third)]-[third(==first)]-15-|

If the first has the same width as the second, and second the third, and third the first, then they will all get the same width... You can do it both horizontally (H) and vertically (V).

How to add elements to a list in R (loop)

You should not add to your list using c inside the loop, because that can result in very very slow code. Basically when you do c(l, new_element), the whole contents of the list are copied. Instead of that, you need to access the elements of the list by index. If you know how long your list is going to be, it's best to initialise it to this size using l <- vector("list", N). If you don't you can initialise it to have length equal to some large number (e.g if you have an upper bound on the number of iterations) and then just pick the non-NULL elements after the loop has finished. Anyway, the basic point is that you should have an index to keep track of the list element and add using that eg

i <- 1
while(...) {
    l[[i]] <- new_element
    i <- i + 1
}

For more info have a look at Patrick Burns' The R Inferno (Chapter 2).

angularjs: allows only numbers to be typed into a text box

Based on djsiz solution, wrapped in directive. NOTE: it will not handle digit numbers, but it can be easily updated

angular
        .module("app")
        .directive("mwInputRestrict", [
            function () {
                return {
                    restrict: "A",
                    link: function (scope, element, attrs) {
                        element.on("keypress", function (event) {
                            if (attrs.mwInputRestrict === "onlynumbers") {
                                // allow only digits to be entered, or backspace and delete keys to be pressed
                                return (event.charCode >= 48 && event.charCode <= 57) ||
                                       (event.keyCode === 8 || event.keyCode === 46);
                            }
                            return true;
                        });
                    }
                }
            }
        ]);

HTML

 <input type="text"
        class="form-control"
        id="inputHeight"
        name="inputHeight"
        placeholder="Height"
        mw-input-restrict="onlynumbers"
        ng-model="ctbtVm.dto.height">

How to get package name from anywhere?

Just import Android.app,then you can use: <br/>Application.getProcessName()<br/>

Get the current Application Process Name without context, view, or activity.

Eclipse fonts and background color

On Windows or Mac, you can find this setting under the General ? Editors ? Text Editors menu.

Print commit message of a given commit in git

I started to use

git show-branch --no-name <hash>

It seems to be faster than

git show -s --format=%s <hash>

Both give the same result

I actually wrote a small tool to see the status of all my repos. You can find it on github.

enter image description here

what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean?

Generally, EXC_BAD_INSTRUCTION means that there was an assertion failure in your code. A wild guess, your Screen.text is not an integer. Double check its type.

PHP - remove <img> tag from string

Sean it works fine i've just used this code

$content = preg_replace("/<img[^>]+\>/i", " ", $content); 
echo $content;

//the result it's only the plain text. It works!!!

Make elasticsearch only return certain fields?

In Elasticsearch 5.x the above mentioned approach is deprecated. You can use the _source approach, but but in certain situations it can make sense to store a field. For instance, if you have a document with a title, a date, and a very large content field, you may want to retrieve just the title and the date without having to extract those fields from a large _source field:

In this case, you'd use:

{  
   "size": $INT_NUM_OF_DOCS_TO_RETURN,
   "stored_fields":[  
      "doc.headline",
      "doc.text",
      "doc.timestamp_utc"
   ],
   "query":{  
      "bool":{  
         "must":{  
            "term":{  
               "doc.topic":"news_on_things"
            }
         },
         "filter":{  
            "range":{  
               "doc.timestamp_utc":{  
                  "gte":1451606400000,
                  "lt":1483228800000,
                  "format":"epoch_millis"
               }
            }
         }
      }
   },
   "aggs":{  

   }
}

See the documentation on how to index stored fields. Always happy for an Upvote!

Get year, month or day from numpy datetime64

Use dates.tolist() to convert to native datetime objects, then simply access year. Example:

>>> dates = np.array(['2010-10-17', '2011-05-13', '2012-01-15'], dtype='datetime64')
>>> [x.year for x in dates.tolist()]
[2010, 2011, 2012]

This is basically the same idea exposed in https://stackoverflow.com/a/35281829/2192272, but using simpler syntax.

Tested with python 3.6 / numpy 1.18.

Adding a column after another column within SQL

In a Firebird database the AFTER myOtherColumn does not work but you can try re-positioning the column using:

ALTER TABLE name ALTER column POSITION new_position

I guess it may work in other cases as well.

How do I get the AM/PM value from a DateTime?

Here is an easier way you can write the time format (hh:mm:ss tt) and display them separately if you wish.

string time = DateTime.Now.Hour.ToString("00") + ":" + DateTime.Now.Minute.ToString("00") + ":" + DateTime.Now.Second.ToString("00") + DateTime.Now.ToString(" tt");

or just simply:

 DateTime.Now.ToString("hh:mm:ss tt")

self referential struct definition?

Another convenient method is to pre-typedef the structure with,structure tag as:

//declare new type 'Node', as same as struct tag
typedef struct Node Node;
//struct with structure tag 'Node'
struct Node
{
int data;
//pointer to structure with custom type as same as struct tag
Node *nextNode;
};
//another pointer of custom type 'Node', same as struct tag
Node *node;

How to detect if URL has changed after hash in JavaScript

this solution worked for me:

var oldURL = "";
var currentURL = window.location.href;
function checkURLchange(currentURL){
    if(currentURL != oldURL){
        alert("url changed!");
        oldURL = currentURL;
    }

    oldURL = window.location.href;
    setTimeout(function() {
        checkURLchange(window.location.href);
    }, 1000);
}

checkURLchange();

Application Installation Failed in Android Studio

In my own case, it was because my phone was out of space. For people that are facing this problem right now, if Clean Project + Build APKs does not work, check the available space on your phone or emulator.

I hope this helps.. Merry coding!

Python subprocess/Popen with a modified environment

In certain circumstances you may want to only pass down the environment variables your subprocess needs, but I think you've got the right idea in general (that's how I do it too).

How do I check if an array includes a value in JavaScript?

In Addition to what others said, if you don't have a reference of the object which you want to search in the array, then you can do something like this.

let array = [1, 2, 3, 4, {"key": "value"}];

array.some((element) => JSON.stringify(element) === JSON.stringify({"key": "value"})) // true

array.some((element) => JSON.stringify(element) === JSON.stringify({})) // true

Array.some returns true if any element matches the given condition and returns false if none of the elements matches the given condition.

What does the "$" sign mean in jQuery or JavaScript?

The jQuery syntax is tailor made for selecting HTML elements and perform some action on the element(s).

Basic syntax is: $(selector).action()

A dollar sign to define jQuery A (selector) to "query (or find)" HTML elements A jQuery action() to be performed on the element(s)

More on this

Indentation Error in Python

In Notepad++

View --->Show Symbols --->Show White Spaces and Tabs(select)

replace all tabs with spaces.

How to remove last n characters from a string in Bash?

In this case you could use basename assuming you have the same suffix on the files you want to remove.

Example:

basename -s .rtf "some string.rtf"

This will return "some string"

If you don't know the suffix, and want it to remove everything after and including the last dot:

f=file.whateverthisis
basename "${f%.*}"

outputs "file"

% means chop, . is what you are chopping, * is wildcard

Wavy shape with css

I think this is the right way to make a shape like you want. By using the SVG possibilities, and an container to keep the shape responsive.

_x000D_
_x000D_
svg {_x000D_
  display: inline-block;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
}_x000D_
.container {_x000D_
  display: inline-block;_x000D_
  position: relative;_x000D_
  width: 100%;_x000D_
  padding-bottom: 100%;_x000D_
  vertical-align: middle;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
  <svg viewBox="0 0 500 500" preserveAspectRatio="xMinYMin meet">_x000D_
    <path d="M0,100 C150,200 350,0 500,100 L500,00 L0,0 Z" style="stroke: none; fill:red;"></path>_x000D_
  </svg>_x000D_
</div>
_x000D_
_x000D_
_x000D_

what is the multicast doing on 224.0.0.251?

If you don't have avahi installed then it's probably cups.

How to extract a substring using regex

you can use this i use while loop to store all matches substring in the array if you use

if (matcher.find()) { System.out.println(matcher.group(1)); }

you will get on matches substring so you can use this to get all matches substring

Matcher m = Pattern.compile("[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+").matcher(text);
   // Matcher  mat = pattern.matcher(text);
    ArrayList<String>matchesEmail = new ArrayList<>();
        while (m.find()){
            String s = m.group();
            if(!matchesEmail.contains(s))
                matchesEmail.add(s);
        }

    Log.d(TAG, "emails: "+matchesEmail);

How to apply style classes to td classes?

If I remember well, some CSS properties you apply to table are not inherited as expected. So you should indeed apply the style directly to td,tr and th elements.

If you need to add styling to each column, use the <col> element in your table.

See an example here: http://jsfiddle.net/GlauberRocha/xkuRA/2/

NB: You can't have a margin in a td. Use padding instead.

hexadecimal string to byte array in python

There is a built-in function in bytearray that does what you intend.

bytearray.fromhex("de ad be ef 00")

It returns a bytearray and it reads hex strings with or without space separator.

Return back to MainActivity from another activity

This usually works as well :)

navigateUpTo(new Intent(getBaseContext(), MainActivity.class));

What does the variable $this mean in PHP?

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

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

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

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

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

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

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

OUTPUT: I am IRON MAN

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

How do you import a large MS SQL .sql file?

I had exactly the same issue and had been struggling for a while then finally found the solution which is to set -a parameter to the sqlcmd in order to change its default packet size:

sqlcmd -S [servername] -d [databasename] -i [scriptfilename] -a 32767

iOS change navigation bar title font and color

My Swift code for change Navigation Bar title:

let attributes = [NSFontAttributeName : UIFont(name: "Roboto-Medium", size: 16)!, NSForegroundColorAttributeName : UIColor.whiteColor()]
self.navigationController.navigationBar.titleTextAttributes = attributes

And if you want to change background font too then I have this in my AppDelegate:

let attributes = [NSFontAttributeName : UIFont(name: "Roboto-Medium", size: 16)!, NSForegroundColorAttributeName : UIColor.whiteColor()]
UIBarButtonItem.appearance().setTitleTextAttributes(attributes, forState: UIControlState.Normal)

What is the correct SQL type to store a .Net Timespan with values > 24:00:00?

Thanks for the advice. As there is no equivalent in SQL server. I simply created a 2nd field which converted the TimeSpan to ticks and stored that in the DB. I then prevented storing the TimeSpan

public Int64 ValidityPeriodTicks { get; set; }

[NotMapped]
public TimeSpan ValidityPeriod
{
    get { return TimeSpan.FromTicks(ValidityPeriodTicks); }
    set { ValidityPeriodTicks = value.Ticks; }
}

LDAP server which is my base dn

The base dn is dc=example,dc=com.

I don't know about openca, but I will try this answer since you got very little traffic so far.

A base dn is the point from where a server will search for users. So I would try to simply use admin as a login name.

If openca behaves like most ldap aware applications, this is what is going to happen :

  1. An ldap search for the user admin will be done by the server starting at the base dn (dc=example,dc=com).
  2. When the user is found, the full dn (cn=admin,dc=example,dc=com) will be used to bind with the supplied password.
  3. The ldap server will hash the password and compare with the stored hash value. If it matches, you're in.

Getting step 1 right is the hardest part, but mostly because we don't get to do it often. Things you have to look out for in your configuraiton file are :

  • The dn your application will use to bind to the ldap server. This happens at application startup, before any user comes to authenticate. You will have to supply a full dn, maybe something like cn=admin,dc=example,dc=com.
  • The authentication method. It is usually a "simple bind".
  • The user search filter. Look at the attribute named objectClass for your admin user. It will be either inetOrgPerson or user. There will be others like top, you can ignore them. In your openca configuration, there should be a string like (objectClass=inetOrgPerson). Whatever it is, make sure it matches your admin user's object Class. You can specify two object class with this search filter (|(objectClass=inetOrgPerson)(objectClass=user)).

Download an LDAP Browser, such as Apache's Directory Studio. Connect using your application's credentials, so you will see what your application sees.

How can I close a browser window without receiving the "Do you want to close this window" prompt?

In the body tag:

<body onload="window.open('', '_self', '');">

To close the window:

<a href="javascript:window.close();">

Tested on Safari 4.0.5, FF for Mac 3.6, IE 8.0, and FF for Windows 3.5

How do I add all new files to SVN

svn status | grep "^\?" | awk '{ printf("\""); for (f=2; f <= NF; f++) { printf("%s", $f); if (f<NF) printf(" "); } printf("\"\n");}' | xargs svn add

This was based on markb's answer... and a little hunting on the internet. It looks ugly, but it seems to work for me on OS X (including files with spaces).

How to get these two divs side-by-side?

Using the style

.child_div_1 {
    float:left
}

Show constraints on tables command

Try doing:

SHOW TABLE STATUS FROM credentialing1;

The foreign key constraints are listed in the Comment column of the output.

Is it possible to CONTINUE a loop from an exception?

In the construct you have provided, you don't need a CONTINUE. Once the exception is handled, the statement after the END is performed, assuming your EXCEPTION block doesn't terminate the procedure. In other words, it will continue on to the next iteration of the user_rec loop.

You also need to SELECT INTO a variable inside your BEGIN block:

SELECT attr INTO v_attr FROM attribute_table...

Obviously you must declare v_attr as well...

Can you find all classes in a package using reflection?

Based on @Staale's answer, and in an attempt not to rely on third party libraries, I would implement the File System approach by inspecting first package physical location with:

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
...
Class<?>[] foundClasses = new Class<?>[0];
final ArrayList<Class<?>> foundClassesDyn = new ArrayList<Class<?>>();

new java.io.File(
    klass.getResource(
        "/" + curPackage.replace( "." , "/")
    ).getFile()
).listFiles(
    new java.io.FileFilter() {
        public boolean accept(java.io.File file) {
            final String classExtension = ".class";

            if ( file.isFile()
                && file.getName().endsWith(classExtension)
                // avoid inner classes
                && ! file.getName().contains("$") )
            {
                try {
                    String className = file.getName();
                    className = className.substring(0, className.length() - classExtension.length());
                    foundClassesDyn.add( Class.forName( curPackage + "." + className ) );
                } catch (ClassNotFoundException e) {
                    e.printStackTrace(System.out);
                }
            }

            return false;
        }
    }
);

foundClasses = foundClassesDyn.toArray(foundClasses);

How to make Bootstrap 4 cards the same height in card-columns?

Another useful approach is Card Grids:

_x000D_
_x000D_
<div class="row row-cols-1 row-cols-md-2">_x000D_
  <div class="col mb-4">_x000D_
    <div class="card">_x000D_
      <img src="..." class="card-img-top" alt="...">_x000D_
      <div class="card-body">_x000D_
        <h5 class="card-title">Card title</h5>_x000D_
        <p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="col mb-4">_x000D_
    <div class="card">_x000D_
      <img src="..." class="card-img-top" alt="...">_x000D_
      <div class="card-body">_x000D_
        <h5 class="card-title">Card title</h5>_x000D_
        <p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="col mb-4">_x000D_
    <div class="card">_x000D_
      <img src="..." class="card-img-top" alt="...">_x000D_
      <div class="card-body">_x000D_
        <h5 class="card-title">Card title</h5>_x000D_
        <p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content.</p>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="col mb-4">_x000D_
    <div class="card">_x000D_
      <img src="..." class="card-img-top" alt="...">_x000D_
      <div class="card-body">_x000D_
        <h5 class="card-title">Card title</h5>_x000D_
        <p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to split a data frame?

subset() is also useful:

subset(DATAFRAME, COLUMNNAME == "")

For a survey package, maybe the survey package is pertinent?

http://faculty.washington.edu/tlumley/survey/

How to change sa password in SQL Server 2008 express?

If you want to change your 'sa' password with SQL Server Management Studio, here are the steps:

  1. Login using Windows Authentication and ".\SQLExpress" as Server Name
  2. Change server authentication mode - Right click on root, choose Properties, from Security tab select "SQL Server and Windows Authentication mode", click OK Change server authentication mode

  3. Set sa password - Navigate to Security > Logins > sa, right click on it, choose Properties, from General tab set the Password (don't close the window) Set sa password

  4. Grant permission - Go to Status tab, make sure the Grant and Enabled radiobuttons are chosen, click OK Grant permission

  5. Restart SQLEXPRESS service from your local services (Window+R > services.msc)

Installing jQuery?

jQuery is just a JavaScript library (simply put, a JavaScript file). All you have to do is put it into your website directory and reference it in your HTML to use it.

For example, in the head tag of your webpage

<script type="text/javascript" src="../Js/jquery.js"></script>

You can download the current jQuery release from Downloading jQuery.

The difference between Classes, Objects, and Instances

Class

  • It has logical existence, i.e. no memory space is allocated when it is created.

  • It is a set of objects.

  • A class may be regarded as a blueprint to create objects.

    • It is created using class keyword

    • A class defines the methods and data members that will be possessed by Objects.


Object

  • It has physical existence, i.e. memory space is allocated when it is created.

  • It is an instance of a class.

  • An object is a unique entity which contains data members and member functions together in OOP language.

    • It is created using new keyword

    • An object specifies the implementations of the methods and the values that will be possessed by the data members in the class.

Select 2 columns in one and combine them

(SELECT column1 as column FROM table )
UNION 
(SELECT column2 as column FROM table )

Good Linux (Ubuntu) SVN client

kdesvn is probably the best you'll find.

Last I checked it may hook in with konqueror, but its been a while, I've moved on to git :)

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

The fact the character is a < make me think you have a PHP error, have you tried echoing all errors.

Since I don't have your database, I'm going through your code trying to find errors, so far, I've updated your JS file

$("#register-form").submit(function (event) {

    var entrance = $(this).find('input[name="IsValid"]').val();
    var password = $(this).find('input[name="objPassword"]').val();
    var namesurname = $(this).find('input[name="objNameSurname"]').val();
    var email = $(this).find('input[name="objEmail"]').val();
    var gsm = $(this).find('input[name="objGsm"]').val();
    var adres = $(this).find('input[name="objAddress"]').val();
    var termsOk = $(this).find('input[name="objAcceptTerms"]').val();

    var formURL = $(this).attr("action");


    if (request) {
        request.abort(); // cancel if any process on pending
    }

    var postData = {
        "objAskGrant": entrance,
        "objPass": password,
        "objNameSurname": namesurname,
        "objEmail": email,
        "objGsm": parseInt(gsm),
        "objAdres": adres,
        "objTerms": termsOk
    };

    $.post(formURL,postData,function(data,status){
        console.log("Data: " + data + "\nStatus: " + status);
    });

    event.preventDefault();
});

PHP Edit:

 if (isset($_POST)) {

    $fValid = clear($_POST['objAskGrant']);
    $fTerms = clear($_POST['objTerms']);

    if ($fValid) {
        $fPass = clear($_POST['objPass']);
        $fNameSurname = clear($_POST['objNameSurname']);
        $fMail = clear($_POST['objEmail']);
        $fGsm = clear(int($_POST['objGsm']));
        $fAddress = clear($_POST['objAdres']);
        $UserIpAddress = "hidden";
        $UserCityLocation = "hidden";
        $UserCountry = "hidden";

        $DateTime = new DateTime();
        $result = $date->format('d-m-Y-H:i:s');
        $krr = explode('-', $result);
        $resultDateTime = implode("", $krr);

        $data = array('error' => 'Yükleme Sirasinda Hata Olustu');

        $kayit = "INSERT INTO tbl_Records(UserNameSurname, UserMail, UserGsm, UserAddress, DateAdded, UserIp, UserCityLocation, UserCountry, IsChecked, GivenPasscode) VALUES ('$fNameSurname', '$fMail', '$fGsm', '$fAddress', '$resultDateTime', '$UserIpAddress', '$UserCityLocation', '$UserCountry', '$fTerms', '$fPass')";
        $retval = mysql_query( $kayit, $conn ); // Update with you connection details
            if ($retval) {
                $data = array('success' => 'Register Completed', 'postData' => $_POST);
            }

        } // valid ends
    }echo json_encode($data);

Is a Python list guaranteed to have its elements stay in the order they are inserted in?

I suppose one thing that may be concerning you is whether or not the entries could change, so that the 2 becomes a different number, for instance. You can put your mind at ease here, because in Python, integers are immutable, meaning they cannot change after they are created.

Not everything in Python is immutable, though. For example, lists are mutable---they can change after being created. So for example, if you had a list of lists

>>> a = [[1], [2], [3]]
>>> a[0].append(7)
>>> a
[[1, 7], [2], [3]]

Here, I changed the first entry of a (I added 7 to it). One could imagine shuffling things around, and getting unexpected things here if you are not careful (and indeed, this does happen to everyone when they start programming in Python in some way or another; just search this site for "modifying a list while looping through it" to see dozens of examples).

It's also worth pointing out that x = x + [a] and x.append(a) are not the same thing. The second one mutates x, and the first one creates a new list and assigns it to x. To see the difference, try setting y = x before adding anything to x and trying each one, and look at the difference the two make to y.

Replace None with NaN in pandas dataframe

The following line replaces None with NaN:

df['column'].replace('None', np.nan, inplace=True)

Rolling or sliding window iterator?

here is a one liner. I timed it and it's comprable to the performance of the top answer and gets progressively better with larger seq from 20% slower with len(seq) = 20 and 7% slower with len(seq) = 10000

zip(*[seq[i:(len(seq) - n - 1 + i)] for i in range(n)])

How to get a specific column value from a DataTable in c#

The table normally contains multiple rows. Use a loop and use row.Field<string>(0) to access the value of each row.

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>("File");
}

You can also access it via index:

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>(0);
}

If you expect only one row, you can also use the indexer of DataRowCollection:

string file = dt.Rows[0].Field<string>(0); 

Since this fails if the table is empty, use dt.Rows.Count to check if there is a row:

if(dt.Rows.Count > 0)
    file = dt.Rows[0].Field<string>(0);

Set ANDROID_HOME environment variable in mac

Open the terminal and type :

export ANDROID_HOME=/Applications/ADT/sdk

Add this to the PATH environment variable

export PATH=$PATH:$ANDROID_HOME/platform-tools

If the terminal doesn't locate the added path(s) from the .bash_profile, please run this command

source ~/.bash_profile

Hope it works to you!

How to set up Android emulator proxy settings

Having the AVD android emulator:

  1. Open the simulator ( "..\android-sdk\AVD Manager.exe")
  2. Go to Tools
  3. Go to Options
  4. On Proxy settings:

On the first field(HTTP Proxy Server) set only the IP address where is your proxy (XXX.XXX.XXX.XXX) on the second field set the port of your proxy (example: 8080)

Then, click Close on the window and start the emulator

---- Added ... Then the alex steps works on my case:

Click on Menu
Click on Settings
Click on Wireless & Networks
Go to Mobile Networks
Go to Access Point Names
Here you will Telkila Internet (or other name), click on it.
In the Edit access point section, input the "proxy" and "port"

How to slice an array in Bash

See the Parameter Expansion section in the Bash man page. A[@] returns the contents of the array, :1:2 takes a slice of length 2, starting at index 1.

A=( foo bar "a  b c" 42 )
B=("${A[@]:1:2}")
C=("${A[@]:1}")       # slice to the end of the array
echo "${B[@]}"        # bar a  b c
echo "${B[1]}"        # a  b c
echo "${C[@]}"        # bar a  b c 42
echo "${C[@]: -2:2}"  # a  b c 42 # The space before the - is necesssary

Note that the fact that "a b c" is one array element (and that it contains an extra space) is preserved.

How to use cURL in Java?

You can make use of java.net.URL and/or java.net.URLConnection.

URL url = new URL("https://stackoverflow.com");

try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"))) {
    for (String line; (line = reader.readLine()) != null;) {
        System.out.println(line);
    }
}

Also see the Oracle's simple tutorial on the subject. It's however a bit verbose. To end up with less verbose code, you may want to consider Apache HttpClient instead.

By the way: if your next question is "How to process HTML result?", then the answer is "Use a HTML parser. No, don't use regex for this.".

See also:

View content of H2 or HSQLDB in-memory database

For H2, you can start a web server within your code during a debugging session if you have a database connection object. You could add this line to your code, or as a 'watch expression' (dynamically):

org.h2.tools.Server.startWebServer(conn);

The server tool will start a web browser locally that allows you to access the database.

Binding a WPF ComboBox to a custom list

To bind the data to ComboBox

List<ComboData> ListData = new List<ComboData>();
ListData.Add(new ComboData { Id = "1", Value = "One" });
ListData.Add(new ComboData { Id = "2", Value = "Two" });
ListData.Add(new ComboData { Id = "3", Value = "Three" });
ListData.Add(new ComboData { Id = "4", Value = "Four" });
ListData.Add(new ComboData { Id = "5", Value = "Five" });

cbotest.ItemsSource = ListData;
cbotest.DisplayMemberPath = "Value";
cbotest.SelectedValuePath = "Id";

cbotest.SelectedValue = "2";

ComboData looks like:

public class ComboData
{ 
  public int Id { get; set; } 
  public string Value { get; set; } 
}

(note that Id and Value have to be properties, not class fields)

How can I wait for a thread to finish with .NET?

When I want the UI to be able to update its display while waiting for a task to complete, I use a while-loop that tests IsAlive on the thread:

    Thread t = new Thread(() => someMethod(parameters));
    t.Start();
    while (t.IsAlive)
    {
        Thread.Sleep(500);
        Application.DoEvents();
    }

HTML text-overflow ellipsis detection

Once upon a time I needed to do this, and the only cross-browser reliable solution I came across was hack job. I'm not the biggest fan of solutions like this, but it certainly produces the correct result time and time again.

The idea is that you clone the element, remove any bounding width, and test if the cloned element is wider than the original. If so, you know it's going to have been truncated.

For example, using jQuery:

var $element = $('#element-to-test');
var $c = $element
           .clone()
           .css({display: 'inline', width: 'auto', visibility: 'hidden'})
           .appendTo('body');

if( $c.width() > $element.width() ) {
    // text was truncated. 
    // do what you need to do
}

$c.remove();

I made a jsFiddle to demonstrate this, http://jsfiddle.net/cgzW8/2/

You could even create your own custom pseudo-selector for jQuery:

$.expr[':'].truncated = function(obj) {
  var $this = $(obj);
  var $c = $this
             .clone()
             .css({display: 'inline', width: 'auto', visibility: 'hidden'})
             .appendTo('body');

  var c_width = $c.width();
  $c.remove();

  if ( c_width > $this.width() )
    return true;
  else
    return false;
};

Then use it to find elements

$truncated_elements = $('.my-selector:truncated');

Demo: http://jsfiddle.net/cgzW8/293/

Hopefully this helps, hacky as it is.

UITableView - change section header color

You can do this if you want header with custom color:

[[UITableViewHeaderFooterView appearance] setTintColor:[UIColor redColor]];

This solution works great since iOS 6.0.

How to disable an input box using angular.js

<input type="text" input-disabled="editableInput" />
<button ng-click="editableInput = !editableInput">enable/disable</button>

app.controller("myController", function(){
  $scope.editableInput = false;
});

app.directive("inputDisabled", function(){
  return function(scope, element, attrs){
    scope.$watch(attrs.inputDisabled, function(val){
      if(val)
        element.removeAttr("disabled");
      else
        element.attr("disabled", "disabled");
    });
  }
});

Protect image download

There is no full-proof method to prevent your images being downloaded/stolen.

But, some solutions like: watermarking your images(from client side or server side), implement a background image, disable/prevent right clicks, slice images into small pieces and then present as a complete image to browser, you can also use flash to show images.

Personally, recommended methods are: Watermarking and flash. But it is a difficult and almost impossible mission to accomplish. As long as user is able to "see" that image, means they take "screenshot" to steal the image.

How to limit the maximum files chosen when using multiple file input

Use two <input type=file> elements instead, without the multiple attribute.

Cast a Double Variable to Decimal

Well this is an old question and I indeed made use of some of the answers shown here. Nevertheless, in my particular scenario it was possible that the double value that I wanted to convert to decimal was often bigger than decimal.MaxValue. So, instead of handling exceptions I wrote this extension method:

    public static decimal ToDecimal(this double @double) => 
        @double > (double) decimal.MaxValue ? decimal.MaxValue : (decimal) @double;

The above approach works if you do not want to bother handling overflow exceptions and if such a thing happen you want just to keep the max possible value(my case), but I am aware that for many other scenarios this would not be the expected behavior and may be the exception handling will be needed.

How can I bind to the change event of a textarea in jQuery?

bind is deprecated. Use on:

$("#textarea").on('change keyup paste', function() {
    // your code here
});

Note: The code above will fire multiple times, once for each matching trigger-type. To handle that, do something like this:

var oldVal = "";
$("#textarea").on("change keyup paste", function() {
    var currentVal = $(this).val();
    if(currentVal == oldVal) {
        return; //check to prevent multiple simultaneous triggers
    }

    oldVal = currentVal;
    //action to be performed on textarea changed
    alert("changed!");
});

jsFiddle Demo

How to set an environment variable from a Gradle build?

If you are using an IDE, go to run, edit configurations, gradle, select gradle task and update the environment variables. See the picture below.

enter image description here

Alternatively, if you are executing gradle commands using terminal, just type 'export KEY=VALUE', and your job is done.

python: creating list from string

Try this:

b = [ entry.split(',') for entry in a ]
b = [ b[i] if i % 3 == 0 else int(b[i]) for i in xrange(0, len(b)) ]

How to give credentials in a batch script that copies files to a network location?

Try using the net use command in your script to map the share first, because you can provide it credentials. Then, your copy command should use those credentials.

net use \\<network-location>\<some-share> password /USER:username

Don't leave a trailing \ at the end of the

T-SQL split string based on delimiter

May be this will help you.

SELECT SUBSTRING(myColumn, 1, CASE CHARINDEX('/', myColumn)
            WHEN 0
                THEN LEN(myColumn)
            ELSE CHARINDEX('/', myColumn) - 1
            END) AS FirstName
    ,SUBSTRING(myColumn, CASE CHARINDEX('/', myColumn)
            WHEN 0
                THEN LEN(myColumn) + 1
            ELSE CHARINDEX('/', myColumn) + 1
            END, 1000) AS LastName
FROM MyTable

Copy folder structure (without files) from one location to another

The following solution worked well for me in various environments:

sourceDir="some/directory"
targetDir="any/other/directory"

find "$sourceDir" -type d | sed -e "s?$sourceDir?$targetDir?" | xargs mkdir -p

Android layout replacing a view with another view on run time

You could replace any view at any time.

int optionId = someExpression ? R.layout.option1 : R.layout.option2;

View C = findViewById(R.id.C);
ViewGroup parent = (ViewGroup) C.getParent();
int index = parent.indexOfChild(C);
parent.removeView(C);
C = getLayoutInflater().inflate(optionId, parent, false);
parent.addView(C, index);

If you don't want to replace already existing View, but choose between option1/option2 at initialization time, then you could do this easier: set android:id for parent layout and then:

ViewGroup parent = (ViewGroup) findViewById(R.id.parent);
View C = getLayoutInflater().inflate(optionId, parent, false);
parent.addView(C, index);

You will have to set "index" to proper value depending on views structure. You could also use a ViewStub: add your C view as ViewStub and then:

ViewStub C = (ViewStub) findViewById(R.id.C);
C.setLayoutResource(optionId);
C.inflate();

That way you won't have to worry about above "index" value if you will want to restructure your XML layout.

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

Hello sorry for the delay! Here is the best and the most efficiency answer that you are looking for:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MyPatternReplace {

public String replaceWithPattern(String str,String replace){

    Pattern ptn = Pattern.compile("\\s+");
    Matcher mtch = ptn.matcher(str);
    return mtch.replaceAll(replace);
}

public static void main(String a[]){
    String str = "My    name    is  kingkon.  ";
    MyPatternReplace mpr = new MyPatternReplace();
    System.out.println(mpr.replaceWithPattern(str, " "));
}

So your output of this example will be: My name is kingkon.

However this method will remove also the "\n" that your string may has. So if you do not want that just use this simple method:

while (str.contains("  ")){  //2 spaces
str = str.replace("  ", " "); //(2 spaces, 1 space) 
}

And if you want to strip the leading and trailing spaces too just add:

str = str.trim();

How to install latest version of Node using Brew

After installation/upgrading node via brew I ran into this issue exactly: the node command worked but not the npm command.

I used these commands to fix it.

brew uninstall node
brew update
brew upgrade
brew cleanup
brew install node
sudo chown -R $(whoami) /usr/local
brew link --overwrite node
brew postinstall node

I pieced together this solution after trial and error using...

How can I remove a style added with .css() function?

This will remove complete tag :

  $("body").removeAttr("style");

Playing .mp3 and .wav in Java?

It's been a while since I used it, but JavaLayer is great for MP3 playback

$(document).ready(function(){ Uncaught ReferenceError: $ is not defined

Put this code in the <head></head> tags:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>

Regex to replace everything except numbers and a decimal point

Use this:

document.getElementById(target).value = newVal.replace(/[^0-9.]/g, '');

How do I pass parameters into a PHP script through a webpage?

Presumably you're passing the arguments in on the command line as follows:

php /path/to/wwwpublic/path/to/script.php arg1 arg2

... and then accessing them in the script thusly:

<?php
// $argv[0] is '/path/to/wwwpublic/path/to/script.php'
$argument1 = $argv[1];
$argument2 = $argv[2];
?>

What you need to be doing when passing arguments through HTTP (accessing the script over the web) is using the query string and access them through the $_GET superglobal:

Go to http://yourdomain.com/path/to/script.php?argument1=arg1&argument2=arg2

... and access:

<?php
$argument1 = $_GET['argument1'];
$argument2 = $_GET['argument2'];
?>

If you want the script to run regardless of where you call it from (command line or from the browser) you'll want something like the following:

EDIT: as pointed out by Cthulhu in the comments, the most direct way to test which environment you're executing in is to use the PHP_SAPI constant. I've updated the code accordingly:

<?php
if (PHP_SAPI === 'cli') {
    $argument1 = $argv[1];
    $argument2 = $argv[2];
}
else {
    $argument1 = $_GET['argument1'];
    $argument2 = $_GET['argument2'];
}
?>

SQL Server Text type vs. varchar data type

If you're using SQL Server 2005 or later, use varchar(MAX). The text datatype is deprecated and should not be used for new development work. From the docs:

Important

ntext , text, and image data types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.

How to generate components in a specific folder with Angular CLI?

Go to project folder in command prompt or in Project Terminal.

Run cmd : ng g c componentname

enter image description here

How do I turn off Unicode in a VC++ project?

For whatever reason, I noticed that setting to unicode for "All Configurations" did not actually apply to all configurations.

Picture: Setting Configuragion In IDE

To confirm this, I would open the .vcxproj and confirm the correct token is in all 4 locations. In this photo, I am using unicode. So the string I am looking for is "Unicode". For you, you likely want it to say "MultiByte".

Picture: Confirming changes in configuration file

How to round a Double to the nearest Int in swift?

You can also extend FloatingPoint in Swift 3 as follow:

extension FloatingPoint {
    func rounded(to n: Int) -> Self {
        let n = Self(n)
        return (self / n).rounded() * n

    }
}

324.0.rounded(to: 5)   // 325

How to set image width to be 100% and height to be auto in react native?

use aspectRatio property in style

Aspect ratio control the size of the undefined dimension of a node. Aspect ratio is a non-standard property only available in react native and not CSS.

  • On a node with a set width/height aspect ratio control the size of the unset dimension
  • On a node with a set flex basis aspect ratio controls the size of the node in the cross axis if unset
  • On a node with a measure function aspect ratio works as though the measure function measures the flex basis
  • On a node with flex grow/shrink aspect ratio controls the size of the node in the cross axis if unset
  • Aspect ratio takes min/max dimensions into account

docs: https://reactnative.dev/docs/layout-props#aspectratio

try like this:

import {Image, Dimensions} from 'react-native';

var width = Dimensions.get('window').width; 

<Image
    source={{
        uri: '<IMAGE_URI>'
    }}
    style={{
        width: width * .2,  //its same to '20%' of device width
        aspectRatio: 1, // <-- this
        resizeMode: 'contain', //optional
    }}
/>

Change column type in pandas

When I've only needed to specify specific columns, and I want to be explicit, I've used (per DOCS LOCATION):

dataframe = dataframe.astype({'col_name_1':'int','col_name_2':'float64', etc. ...})

So, using the original question, but providing column names to it ...

a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']]
df = pd.DataFrame(a, columns=['col_name_1', 'col_name_2', 'col_name_3'])
df = df.astype({'col_name_2':'float64', 'col_name_3':'float64'})

Adding a custom header to HTTP request using angular.js

And what's the answer from the server? It should reply a 204 and then really send the GET you are requesting.

In the OPTIONS the client is checking if the server allows CORS requests. If it gives you something different than a 204 then you should configure your server to send the correct Allow-Origin headers.

The way you are adding headers is the right way to do it.

SQL query to select distinct row with minimum value

This will work

select * from table 
where (id,point) IN (select id,min(point) from table group by id);

Import Certificate to Trusted Root but not to Personal [Command Line]

If there are multiple certificates in a pfx file (key + corresponding certificate and a CA certificate) then this command worked well for me:

certutil -importpfx c:\somepfx.pfx this works but still a password is needed to be typed in manually for private key. Including -p and "password" cause error too many arguments for certutil on XP

How to print to console using swift playground?

You may still have trouble displaying the output in the Assistant Editor. Rather than wrapping the string in println(), simply output the string. For example:

for index in 1...5 {
    "The number is \(index)"
}

Will write (5 times) in the playground area. This will allow you to display it in the Assistant Editor (via the little circle on the far right edge).

However, if you were to println("The number is \(index)") you wouldn't be able to visualize it in the Assistant Editor.

Execute external program

This is not right. Here's how you should use Runtime.exec(). You might also try its more modern cousin, ProcessBuilder:

Java Runtime.getRuntime().exec() alternatives

Blur or dim background when Android PopupWindow active

For me, something like Abdelhak Mouaamou's answer works, tested on API level 16 and 27.

Instead of using popupWindow.getContentView().getParent() and casting the result to View (which crashes on API level 16 cause there it returns a ViewRootImpl object which isn't an instance of View) I just use .getRootView() which returns a view already, so no casting required there.

Hope it helps someone :)

complete working example scrambled together from other stackoverflow posts, just copy-paste it, e.g., in the onClick listener of a button:

// inflate the layout of the popup window
LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
if(inflater == null) {
    return;
}
//View popupView = inflater.inflate(R.layout.my_popup_layout, null); // this version gives a warning cause it doesn't like null as argument for the viewRoot, c.f. https://stackoverflow.com/questions/24832497 and https://stackoverflow.com/questions/26404951
View popupView = View.inflate(MyParentActivity.this, R.layout.my_popup_layout, null);

// create the popup window
final PopupWindow popupWindow = new PopupWindow(popupView,
        LinearLayout.LayoutParams.WRAP_CONTENT,
        LinearLayout.LayoutParams.WRAP_CONTENT,
        true // lets taps outside the popup also dismiss it
        );

// do something with the stuff in your popup layout, e.g.:
//((TextView)popupView.findViewById(R.id.textview_popup_helloworld))
//      .setText("hello stackoverflow");

// dismiss the popup window when touched
popupView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            popupWindow.dismiss();
            return true;
        }
});

// show the popup window
// which view you pass in doesn't matter, it is only used for the window token
popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
//popupWindow.setOutsideTouchable(false); // doesn't seem to change anything for me

View container = popupWindow.getContentView().getRootView();
if(container != null) {
    WindowManager wm = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
    WindowManager.LayoutParams p = (WindowManager.LayoutParams)container.getLayoutParams();
    p.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;
    p.dimAmount = 0.3f;
    if(wm != null) {
        wm.updateViewLayout(container, p);
    }
}

Show pop-ups the most elegant way

  • Create a 'popup' directive and apply it to the container of the popup content
  • In the directive, wrap the content in a absolute position div along with the mask div below it.
  • It is OK to move the 2 divs in the DOM tree as needed from within the directive. Any UI code is OK in the directives, including the code to position the popup in center of screen.
  • Create and bind a boolean flag to controller. This flag will control visibility.
  • Create scope variables that bond to OK / Cancel functions etc.

Editing to add a high level example (non functional)

<div id='popup1-content' popup='showPopup1'>
  ....
  ....
</div>


<div id='popup2-content' popup='showPopup2'>
  ....
  ....
</div>



.directive('popup', function() {
  var p = {
      link : function(scope, iElement, iAttrs){
           //code to wrap the div (iElement) with a abs pos div (parentDiv)
          // code to add a mask layer div behind 
          // if the parent is already there, then skip adding it again.
         //use jquery ui to make it dragable etc.
          scope.watch(showPopup, function(newVal, oldVal){
               if(newVal === true){
                   $(parentDiv).show();
                 } 
              else{
                 $(parentDiv).hide();
                }
          });
      }


   }
  return p;
});

How to compare two JSON have the same properties without order?

In VueJs function you can use this as well... A working solution using recursion. Base credits Samadhan Sakhale

     check_objects(obj1, obj2) {
            try {
                var flag = true;

                if (Object.keys(obj1).length == Object.keys(obj2).length) {
                    for (let key in obj1) {

                        if(typeof (obj1[key]) != typeof (obj2[key]))
                        {
                            return false;
                        }

                        if (obj1[key] == obj2[key]) {
                            continue;
                        }

                        else if(typeof (obj1[key]) == typeof (new Object()))
                        {
                            if(!this.check_objects(obj1[key], obj2[key])) {
                                return false;
                            }
                        }
                        else {
                            return false;
                        }
                    }
                }
                else {
                    return false
                }
            }
            catch {

                return false;
            }

            return flag;
        },

How do you migrate an IIS 7 site to another server?

I'd say export your server config in IIS manager:

  1. In IIS manager, click the Server node
  2. Go to Shared Configuration under "Management"
  3. Click “Export Configuration”. (You can use a password if you are sending them across the internet, if you are just gonna move them via a USB key then don't sweat it.)
  4. Move these files to your new server

    administration.config
    applicationHost.config
    configEncKey.key 
    
  5. On the new server, go back to the “Shared Configuration” section and check “Enable shared configuration.” Enter the location in physical path to these files and apply them.

  6. It should prompt for the encryption password(if you set it) and reset IIS.

BAM! Go have a beer!

How do I convert hh:mm:ss.000 to milliseconds in Excel?

Let's say that your time value is in cell A1 then in A2 you can put:

=A1*1000*60*60*24

or simply:

=A1*86400000

What I am doing is taking the decimal value of the time and multiply it by 1000 (milliseconds) and 60 (seconds) and 60 (minutes) and 24 (hours).

You will then need to format cell A2 as General for it to be in milliseconds format.

If your time is a text value then use:

=TIMEVALUE(A1)*86400000

UPDATE

Per @dandfra's comment this solution may not work in the Italian version of Excel.

How do I move focus to next input with jQuery?

Could you post some of your HTML as an example?

In the mean-time, try this:

$('#myInput').result(function(){
    $(this).next('input').focus();
})

That's untested, so it'll probably need some tweaking.

How can I style an Android Switch?

It's an awesome detailed reply by Janusz. But just for the sake of people who are coming to this page for answers, the easier way is at http://android-holo-colors.com/ (dead link) linked from Android Asset Studio

A good description of all the tools are at AndroidOnRocks.com (site offline now)

However, I highly recommend everybody to read the reply from Janusz as it will make understanding clearer. Use the tool to do stuffs real quick

What does this error mean: "error: expected specifier-qualifier-list before 'type_name'"?

The compiler doesn't know that spe_context_ptr_t is a type. Check that the appropriate typedef is in scope when this code is compiled. You may have forgotten to include the appropriate header file.

Indexes of all occurrences of character in a string

    String input = "GATATATGCG";
    String substring = "G";
    String temp = input;
    String indexOF ="";
    int tempIntex=1;

    while(temp.indexOf(substring) != -1)
    {
        int index = temp.indexOf(substring);
        indexOF +=(index+tempIntex)+" ";
        tempIntex+=(index+1);
        temp = temp.substring(index + 1);
    }
    Log.e("indexOf ","" + indexOF);