Programs & Examples On #Federated table

Docker official registry (Docker Hub) URL

The registry path for official images (without a slash in the name) is library/<image>. Try this instead:

docker pull registry.hub.docker.com/library/busybox

Pandas percentage of total with groupby

df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3,
               'office_id': list(range(1, 7)) * 2,
               'sales': [np.random.randint(100000, 999999)
                         for _ in range(12)]})

grouped = df.groupby(['state', 'office_id'])
100*grouped.sum()/df[["state","sales"]].groupby('state').sum()

Returns:

sales
state   office_id   
AZ  2   54.587910
    4   33.009225
    6   12.402865
CA  1   32.046582
    3   44.937684
    5   23.015735
CO  1   21.099989
    3   31.848658
    5   47.051353
WA  2   43.882790
    4   10.265275
    6   45.851935

How can I write text on a HTML5 canvas element?

It is really easy to write text on a canvas. It was not clear if you want someone to enter text in the HTML page and then have that text appear on the canvas, or if you were going to use JavaScript to write the information to the screen.

The following code will write some text in different fonts and formats to your canvas. You can modify this as you wish to test other aspects of writing onto a canvas.

 <canvas id="YourCanvasNameHere" width="500" height="500">Canvas not supported</canvas>

 var c = document.getElementById('YourCanvasNameHere');
 var context = c.getContext('2d'); //returns drawing functions to allow the user to draw on the canvas with graphic tools. 

You can either place the canvas ID tag in the HTML and then reference the name or you can create the canvas in the JavaScript code. I think that for the most part I see the <canvas> tag in the HTML code and on occasion see it created dynamically in the JavaScript code itself.

Code:

  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');

  context.font = 'bold 10pt Calibri';
  context.fillText('Hello World!', 150, 100);
  context.font = 'italic 40pt Times Roman';
  context.fillStyle = 'blue';
  context.fillText('Hello World!', 200, 150);
  context.font = '60pt Calibri';
  context.lineWidth = 4;
  context.strokeStyle = 'blue';
  context.strokeText('Hello World!', 70, 70);

Get spinner selected items text?

TextView textView = (TextView) spinActSubTask.getSelectedView().findViewById(R.id.tvProduct);

String subItem = textView.getText().toString();

The SELECT permission was denied on the object 'Users', database 'XXX', schema 'dbo'

May be your Plesk panel or other panel subscription has been expired....please check subscription End.

How to hide .php extension in .htaccess

I've used this:

RewriteEngine On

# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ http://example.com/folder/$1 [R=301,L]

# Redirect external .php requests to extensionless URL
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(.+)\.php$ http://example.com/folder/$1 [R=301,L]

# Resolve .php file for extensionless PHP URLs
RewriteRule ^([^/.]+)$ $1.php [L]

See also: this question

How to get a Static property with Reflection

Just wanted to clarify this for myself, while using the new reflection API based on TypeInfo - where BindingFlags is not available reliably (depending on target framework).

In the 'new' reflection, to get the static properties for a type (not including base class(es)) you have to do something like:

IEnumerable<PropertyInfo> props = 
  type.GetTypeInfo().DeclaredProperties.Where(p => 
    (p.GetMethod != null && p.GetMethod.IsStatic) ||
    (p.SetMethod != null && p.SetMethod.IsStatic));

Caters for both read-only or write-only properties (despite write-only being a terrible idea).

The DeclaredProperties member, too doesn't distinguish between properties with public/private accessors - so to filter around visibility, you then need to do it based on the accessor you need to use. E.g - assuming the above call has returned, you could do:

var publicStaticReadable = props.Where(p => p.GetMethod != null && p.GetMethod.IsPublic);

There are some shortcut methods available - but ultimately we're all going to be writing a lot more extension methods around the TypeInfo query methods/properties in the future. Also, the new API forces us to think about exactly what we think of as a 'private' or 'public' property from now on - because we must filter ourselves based on individual accessors.

How to make parent wait for all child processes to finish?

Use waitpid() like this:

pid_t childPid;  // the child process that the execution will soon run inside of. 
childPid = fork();

if(childPid == 0)  // fork succeeded 
{   
   // Do something   
   exit(0); 
}

else if(childPid < 0)  // fork failed 
{    
   // log the error
}

else  // Main (parent) process after fork succeeds 
{    
    int returnStatus;    
    waitpid(childPid, &returnStatus, 0);  // Parent process waits here for child to terminate.

    if (returnStatus == 0)  // Verify child process terminated without error.  
    {
       printf("The child process terminated normally.");    
    }

    if (returnStatus == 1)      
    {
       printf("The child process terminated with an error!.");    
    }
}

Set up Python simpleHTTPserver on Windows

From Stack Overflow question What is the Python 3 equivalent of "python -m SimpleHTTPServer":

The following works for me:

python -m http.server [<portNo>]

Because I am using Python 3 the module SimpleHTTPServer has been replaced by http.server, at least in Windows.

How to open Android Device Monitor in latest Android Studio 3.1

To get it to work I had to switch to Java 8 from Java 10 (In my system PATH variable) then go to C:\Users\Alex\AppData\Local\Android\Sdk\tools\lib\monitor-x86_64 and run monitor.exe.

How to format strings using printf() to get equal length in the output

Start with the use of tabs - the \t character modifier. It will advance to a fixed location (columns, terminal lingo).

However, it doesn't help if there are differences of more than the column width (4 characters, if I recall correctly).

To fix that, write your "OK/NOK" stuff using a fixed number of tabs (5? 6?, try it). Then return (\r) without new-lining, and write your message.

Enable binary mode while restoring a Database from an SQL dump

I know the original posters question was solved, but I came here via Google, and the various answers eventually led me to discovering that my SQL was dumped with a different default charset than the one used to import it. I got the same error as the original question, but as our dump was piped into another MySQL client, we couldn't go the route of opening it with another tool and saving it differently.

For us, the solution turned out to be the --default-character-set=utf8mb4 option, to be used both on the call of mysqldump as well as the call to import it via mysql. Of course, the value of the parameter may differ for others facing the same problem, it's just important to keep it the same, as the servers (or the tools) default setting might be any charset.

Call to undefined function App\Http\Controllers\ [ function name ]

If they are in the same controller class, it would be:

foreach ( $characters as $character) {
    $num += $this->getFactorial($index) * $index;
    $index ++;
}

Otherwise you need to create a new instance of the class, and call the method, ie:

$controller = new MyController();
foreach ( $characters as $character) {
    $num += $controller->getFactorial($index) * $index;
    $index ++;
}

Crystal Reports for VS2012 - VS2013 - VS2015 - VS2017 - VS2019

There is also someone who managed to modify CR for VS.NET 2010 to install on 2012, using MS ORCA in this thread: http://scn.sap.com/thread/3235515 . I couldn't get it to work myself, though.

Object Library Not Registered When Adding Windows Common Controls 6.0

You Just execute the following commands in your command prompt,

For 32 bit machine,

cd C:\Windows\System32
regsvr32 mscomctl.ocx
regtlib msdatsrc.tlb

For 64 bit machine,

cd C:\Windows\SysWOW64
regsvr32 mscomctl.ocx
regtlib msdatsrc.tlb

How to jquery alert confirm box "yes" & "no"

This plugin can help you,

craftpip/jquery-confirm

Its easy to setup and has great set of features.

$.confirm({
    title: 'Confirm!',
    content: 'Simple confirm!',
    buttons: {
        confirm: function () {
            $.alert('Confirmed!');
        },
        cancel: function () {
            $.alert('Canceled!');
        },
        somethingElse: {
            text: 'Something else',
            btnClass: 'btn-blue',
            keys: ['enter', 'shift'], // trigger when enter or shift is pressed
            action: function(){
                $.alert('Something else?');
            }
        }
    }
});

Other than this you can also load your content from a remote url.

$.confirm({
    content: 'url:hugedata.html' // location of your hugedata.html.
});

UPDATE multiple tables in MySQL using LEFT JOIN

Table A 
+--------+-----------+
| A-num  | text      | 
|    1   |           |
|    2   |           |
|    3   |           |
|    4   |           |
|    5   |           |
+--------+-----------+

Table B
+------+------+--------------+
| B-num|  date        |  A-num | 
|  22  |  01.08.2003  |     2  |
|  23  |  02.08.2003  |     2  | 
|  24  |  03.08.2003  |     1  |
|  25  |  04.08.2003  |     4  |
|  26  |  05.03.2003  |     4  |

I will update field text in table A with

UPDATE `Table A`,`Table B`
SET `Table A`.`text`=concat_ws('',`Table A`.`text`,`Table B`.`B-num`," from                                           
",`Table B`.`date`,'/')
WHERE `Table A`.`A-num` = `Table B`.`A-num`

and come to this result:

Table A 
+--------+------------------------+
| A-num  | text                   | 
|    1   |  24 from 03 08 2003 /  |
|    2   |  22 from 01 08 2003 /  |       
|    3   |                        |
|    4   |  25 from 04 08 2003 /  |
|    5   |                        |
--------+-------------------------+

where only one field from Table B is accepted, but I will come to this result:

Table A 
+--------+--------------------------------------------+
| A-num  | text                                       | 
|    1   |  24 from 03 08 2003                        |
|    2   |  22 from 01 08 2003 / 23 from 02 08 2003 / |       
|    3   |                                            |
|    4   |  25 from 04 08 2003 / 26 from 05 03 2003 / |
|    5   |                                            |
+--------+--------------------------------------------+

UnicodeDecodeError: 'utf8' codec can't decode byte 0xa5 in position 0: invalid start byte

On read csv, I added an encoding method:

import pandas as pd
dataset = pd.read_csv('sample_data.csv', header= 0,
                        encoding= 'unicode_escape')

UITableView - scroll to the top

Swift 3

tableView.setContentOffset(CGPoint.zero, animated: true)

if tableView.setContentOffset don't work.

Use:

tableView.beginUpdates()
tableView.setContentOffset(CGPoint.zero, animated: true)
tableView.endUpdates()

How to lock orientation of one view controller to portrait mode only in Swift

Create new extension with

import UIKit

extension UINavigationController {
    override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
}

extension UITabBarController {
    override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
}

How to have multiple colors in a Windows batch file?

Yes, it is possible with cmdcolor:

echo \033[32mhi \033[92mworld

hi will be dark green, and world - light green.

What is causing ImportError: No module named pkg_resources after upgrade of Python on os X?

In my case, package python-pygments was missed. You can fix it by command:

sudo apt-get install python-pygments

If there is problem with pandoc. You should install pandoc and pandoc-citeproc.

sudo apt-get install pandoc pandoc-citeproc

How to get input from user at runtime

you can try this too And it will work:

DECLARE
  a NUMBER;
  b NUMBER;
BEGIN
  a :=: a; --this will take input from user
  b :=: b;
  DBMS_OUTPUT.PUT_LINE('a = '|| a);
  DBMS_OUTPUT.PUT_LINE('b = '|| b);
END;

Disabling right click on images using jquery

The better way of doing this without jQuery:

const images = document.getElementsByTagName('img');
for (let i = 0; i < images.length; i++) {
    images[i].addEventListener('contextmenu', event => event.preventDefault());
}

ConnectionTimeout versus SocketTimeout

A connection timeout is the maximum amount of time that the program is willing to wait to setup a connection to another process. You aren't getting or posting any application data at this point, just establishing the connection, itself.

A socket timeout is the timeout when waiting for individual packets. It's a common misconception that a socket timeout is the timeout to receive the full response. So if you have a socket timeout of 1 second, and a response comprised of 3 IP packets, where each response packet takes 0.9 seconds to arrive, for a total response time of 2.7 seconds, then there will be no timeout.

How do I alter the precision of a decimal column in Sql Server?

ALTER TABLE Testing ALTER COLUMN TestDec decimal(16,1)

Just put decimal(precision, scale), replacing the precision and scale with your desired values.

I haven't done any testing with this with data in the table, but if you alter the precision, you would be subject to losing data if the new precision is lower.

Access restriction: The type 'Application' is not API (restriction on required library rt.jar)

I had a little different problem. In Project - Properties - Libraries - JRE library, I had the wrong JRE lib version. Remove and set the actual one, and voila - all Access restriction... warnings are away.

How to downgrade the installed version of 'pip' on windows?

If downgrading from pip version 10 because of PyCharm manage.py or other python errors:

python -m pip install pip==9.0.1

How do I remove all null and empty string values from an object?

Enhancement to Alexis King's code to run without Jquery and removal of empty arrays and array of empty objects (With no properties) recursively.

var sjonObj = {
"executionMode": "SEQUENTIAL",
"coreTEEVersion": "3.3.1.4_RC8",
"testSuiteId": "yyy",
"testSuiteFormatVersion": "1.0.0.0",
"testStatus": "IDLE",
"reportPath": "",
"startTime": 0,
"durationBetweenTestCases": 20,
"endTime": 0,
"lastExecutedTestCaseId": 0,
"repeatCount": 0,
"retryCount": 0,
"fixedTimeSyncSupported": false,
"totalRepeatCount": 0,
"totalRetryCount": 0,
"summaryReportRequired": "true",
"postConditionExecution": "ON_SUCCESS",
"testCaseList": [{
        "executionMode": "SEQUENTIAL",
        "commandList": [{
            "sample1": "",
            "sample2": ""
        }],
        "testCaseList": [

        ],
        "testStatus": "IDLE",
        "boundTimeDurationForExecution": 0,
        "startTime": 0,
        "endTime": 0,
        "label": null,
        "repeatCount": 0,
        "retryCount": 0,
        "totalRepeatCount": 0,
        "totalRetryCount": 0,
        "testCaseId": "a",
        "summaryReportRequired": "false",
        "postConditionExecution": "ON_SUCCESS"
    },
    {
        "executionMode": "SEQUENTIAL",
        "commandList": [

        ],
        "testCaseList": [{
            "executionMode": "SEQUENTIAL",
            "commandList": [{
                "commandParameters": {
                    "serverAddress": "www.ggp.com",
                    "echoRequestCount": "",
                    "sendPacketSize": "",
                    "interval": "",
                    "ttl": "",
                    "addFullDataInReport": "True",
                    "maxRTT": "",
                    "failOnTargetHostUnreachable": "True",
                    "failOnTargetHostUnreachableCount": "",
                    "initialDelay": "",
                    "commandTimeout": "",
                    "testDuration": ""
                },
                "commandName": "Ping",
                "testStatus": "IDLE",
                "label": "",
                "reportFileName": "tc_2-tc_1-cmd_1_Ping",
                "endTime": 0,
                "startTime": 0,
                "repeatCount": 0,
                "retryCount": 0,
                "totalRepeatCount": 0,
                "totalRetryCount": 0,
                "postConditionExecution": "ON_SUCCESS",
                "detailReportRequired": "true",
                "summaryReportRequired": "true"
            }],
            "testCaseList": [

            ],
            "testStatus": "IDLE",
            "boundTimeDurationForExecution": 0,
            "startTime": 0,
            "endTime": 0,
            "label": null,
            "repeatCount": 0,
            "retryCount": 0,
            "totalRepeatCount": 0,
            "totalRetryCount": 0,
            "testCaseId": "dd",
            "summaryReportRequired": "false",
            "postConditionExecution": "ON_SUCCESS"
        }],
        "testStatus": "IDLE",
        "boundTimeDurationForExecution": 0,
        "startTime": 0,
        "endTime": 0,
        "label": null,
        "repeatCount": 0,
        "retryCount": 0,
        "totalRepeatCount": 0,
        "totalRetryCount": 0,
        "testCaseId": "b",
        "summaryReportRequired": "false",
        "postConditionExecution": "ON_SUCCESS"
    }
]};
function filter(obj) {
  for(let key in obj){
    if (obj[key] === "" || obj[key] === null){
        delete obj[key];
    } else if (Object.prototype.toString.call(obj[key]) === '[object Object]') {
            filter(obj[key]);
    } else if (Array.isArray(obj[key])) {
        if(obj[key].length == 0){
            delete obj[key];
        }else{
            for(let _key in obj[key]){
                filter(obj[key][_key]);
            }
            obj[key] = obj[key].filter(value => Object.keys(value).length !== 0);
            if(obj[key].length == 0){
                delete obj[key];
            }
        }
    }   
}};

filter(sjonObj);
console.log(JSON.stringify(sjonObj, null, 3));

How do I make a self extract and running installer

It's simple with open source 7zip SFX-Packager - easy way to just "Drag & drop" folders onto it, and it creates a portable/self-extracting package.

How to get an Instagram Access Token

By using https://www.hurl.it/ i was able to see this: { "code": 400, "error_type": "OAuthException", "error_message": "Matching code was not found or was already used." }

so: you have to get new code for every request.

How to execute a .sql script from bash

You simply need to start mysql and feed it with the content of db.sql:

mysql -u user -p < db.sql

Python speed testing - Time Difference - milliseconds

Arrow: Better dates & times for Python

import arrow
start_time = arrow.utcnow()
end_time = arrow.utcnow()
(end_time - start_time).total_seconds()  # senconds
(end_time - start_time).total_seconds() * 1000  # milliseconds

Set Page Title using PHP

You parse the field from the database as usual.

Then let's say you put it in a variable called $title, you just

<html>
<head>
<title>Ultan.me - <?php echo htmlspecialchars($title);?></title>
</head>

EDIT:

I see your problem. You have to set $title BEFORE using it. That is, you should query the database before <title>...

How can I split this comma-delimited string in Python?

How about a list?

mystring.split(",")

It might help if you could explain what kind of info we are looking at. Maybe some background info also?

EDIT:

I had a thought you might want the info in groups of two?

then try:

re.split(r"\d*,\d*", mystring)

and also if you want them into tuples

[(pair[0], pair[1]) for match in re.split(r"\d*,\d*", mystring) for pair in match.split(",")]

in a more readable form:

mylist = []
for match in re.split(r"\d*,\d*", mystring):
    for pair in match.split(",")
        mylist.append((pair[0], pair[1]))

Set maxlength in Html Textarea

If you are using HTML 5, you need to specify that in your DOCTYPE declaration.

For a valid HTML 5 document, it should start with:

<!DOCTYPE html>

Before HTML 5, the textarea element did not have a maxlength attribute.

You can see this in the DTD/spec:

<!ELEMENT TEXTAREA - - (#PCDATA)       -- multi-line text field -->
<!ATTLIST TEXTAREA
  %attrs;                              -- %coreattrs, %i18n, %events --
  name        CDATA          #IMPLIED
  rows        NUMBER         #REQUIRED
  cols        NUMBER         #REQUIRED
  disabled    (disabled)     #IMPLIED  -- unavailable in this context --
  readonly    (readonly)     #IMPLIED
  tabindex    NUMBER         #IMPLIED  -- position in tabbing order --
  accesskey   %Character;    #IMPLIED  -- accessibility key character --
  onfocus     %Script;       #IMPLIED  -- the element got the focus --
  onblur      %Script;       #IMPLIED  -- the element lost the focus --
  onselect    %Script;       #IMPLIED  -- some text was selected --
  onchange    %Script;       #IMPLIED  -- the element value was changed --
  %reserved;                           -- reserved for possible future use --
  >

In order to limit the number of characters typed into a textarea, you will need to use javascript with the onChange event. You can then count the number of characters and disallow further typing.

Here is an in-depth discussion on text input and how to use server and client side scripting to limit the size.

Here is another sample.

Do I need to convert .CER to .CRT for Apache SSL certificates? If so, how?

I assume that you have a .cer file containing PKCS#7-encoded certificate data and you want to convert it to PEM-encoded certificate data (typically a .crt or .pem file). For instance, a .cer file containing PKCS#7-encoded data looks like this:

-----BEGIN PKCS7-----
MIIW4gYJKoZIhvcNAQcCoIIW0zCCFs8CAQExADALBgkqhkiG9w0BBwGggha1MIIH
...
POI9n9cd2cNgQ4xYDiKWL2KjLB+6rQXvqzJ4h6BUcxm1XAX5Uj5tLUUL9wqT6u0G
+bKhADEA
-----END PKCS7-----

PEM certificate data looks like this:

-----BEGIN CERTIFICATE-----
MIIHNjCCBh6gAwIBAgIQAlBxtqKazsxUSR9QdWWxaDANBgkqhkiG9w0BAQUFADBm
...
nv72c/OV4nlyrvBLPoaS5JFUJvFUG8RfAEY=
-----END CERTIFICATE-----

There is an OpenSSL command that will convert .cer files (with PKCS#7 data) to the PEM data you may be expecting to encounter (the BEGIN CERTIFICATE block in the example above). You can coerce PKCS#7 data into PEM format by this command on a file we'll call certfile.cer:

openssl pkcs7 -text -in certfile.cer -print_certs -outform PEM -out certfile.pem

Note that a .cer or .pem file might contain one or more certificates (possibly the entire certificate chain).

java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries. spark Eclipse on windows 7

Here is a good explanation of your problem with the solution.

  1. Download winutils.exe from http://public-repo-1.hortonworks.com/hdp-win-alpha/winutils.exe.
  2. SetUp your HADOOP_HOME environment variable on the OS level or programmatically:

    System.setProperty("hadoop.home.dir", "full path to the folder with winutils");

  3. Enjoy

Omitting the second expression when using the if-else shorthand

Tiny addition to this very old thread..

If your'e evaluating an expression inside a for/while loop with a ternary operator, and want to continue or break as a result - you're gonna have a problem because both continue&break aren't expressions, they're statements without any value.

This will produce Uncaught SyntaxError: Unexpected token continue

 for (const item of myArray) {
      item.value ? break : continue;
 }

If you really want a one-liner that returns a statement, you can use this instead:

  for (const item of myArray) {
      if (item.value) break; else continue;
  }
  • P.S - This code might raise some eyebrows. Just saying.. :)

How to make <label> and <input> appear on the same line on an HTML form?

Another option is to place a table inside the form. (see below) I know tables are frowned upon by some people but I think they work nicely when it comes to responsive form layouts.

<FORM METHOD="POST" ACTION="http://www.cs.tut.fi/cgi-bin/run/~jkorpela/echo.cgi">
<TABLE BORDER="1">
  <TR>
    <TD>Your name</TD>
    <TD>
      <INPUT TYPE="TEXT" NAME="name" SIZE="20">
    </TD>
  </TR>
  <TR>
    <TD>Your E-mail address</TD>
    <TD><INPUT TYPE="TEXT" NAME="email" SIZE="25"></TD>
  </TR>
</TABLE>
<P><INPUT TYPE="SUBMIT" VALUE="Submit" NAME="B1"></P>
</FORM>

Android getting value from selected radiobutton

int genid=gender.getCheckedRadioButtonId();
RadioButton radioButton = (RadioButton) findViewById(genid);
String gender=radioButton.getText().toString();

Hope this works. You can convert your output to string in the above manner. gender.getCheckedRadioButtonId(); - gender is the id of RadioGroup.

How do I set log4j level on the command line?

With Log4j2, this can be achieved using the following utility method added to your code.

private static void setLogLevel() {
  if (Boolean.getBoolean("log4j.debug")) {
    Configurator.setLevel(System.getProperty("log4j.logger"), Level.DEBUG);
  }
}

You need these imports

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.config.Configurator;

Now invoke the setLogLevel method in your main() or whereever appropriate and pass command line params -Dlog4j.logger=com.mypackage.Thingie and -Dlog4j.debug=true.

Get child node index

ES—Shorter

[...element.parentNode.children].indexOf(element);

The spread Operator is a shortcut for that

Handling back button in Android Navigation Component

So, I created an interface

public interface OnBackPressedListener {
    void onBackPressed();
}

And implemented it by all fragments that need to handle back button. In main activity I overrided onBackPressed() method:

@Override
public void onBackPressed() {
    final Fragment currentFragment = mNavHostFragment.getChildFragmentManager().getFragments().get(0);
    final NavController controller = Navigation.findNavController(this, R.id.nav_host_fragment);
    if (currentFragment instanceof OnBackPressedListener)
        ((OnBackPressedListener) currentFragment).onBackPressed();
    else if (!controller.popBackStack())
        finish();

}

So, If the top fragment of my Navigation host implements OnBackPressedListener interface, I call its onBackPressed() method, elsewhere I simply pop back stack and close application if the back stack is empty.

Get first key in a (possibly) associative array?

2019 Update

Starting from PHP 7.3, there is a new built in function called array_key_first() which will retrieve the first key from the given array without resetting the internal pointer. Check out the documentation for more info.


You can use reset and key:

reset($array);
$first_key = key($array);

It's essentially the same as your initial code, but with a little less overhead, and it's more obvious what is happening.

Just remember to call reset, or you may get any of the keys in the array. You can also use end instead of reset to get the last key.

If you wanted the key to get the first value, reset actually returns it:

$first_value = reset($array);

There is one special case to watch out for though (so check the length of the array first):

$arr1 = array(false);
$arr2 = array();
var_dump(reset($arr1) === reset($arr2)); // bool(true)

How to re-sign the ipa file?

Check iResign for an easy tool on how to do this!

[edit] after some fudling around, I found a solution to keychain-aware resigning. You can check it out at https://gist.github.com/Weptun/5406993

How can I open Java .class files in a human-readable way?

cpuguru, if your applet has been compiled with javac 1.3 (or less), your best option is to use Jad.

Unfortunately, the last JDK supported by JAD 1.5.8 (Apr 14, 2001) is JDK 1.3.

If your applet has been compiled with a more recent compiler, you could try JD-GUI : this decompiler is under development, nevertheless, it generates correct Java sources, most of time, for classes compiled with the JDKs 1.4, 1.5 or 1.6.

DarenW, thank you for your post. JD-GUI is not the best decompiler yet ... but I'm working on :)

Making a Sass mixin with optional arguments

Super simple way

Just add a default value of none to $inset - so

@mixin box-shadow($top, $left, $blur, $color, $inset: none) { ....

Now when no $inset is passed nothing will be displayed.

How do I negate a condition in PowerShell?

You almost had it with Not. It should be:

if (-Not (Test-Path C:\Code)) {
    write "it doesn't exist!"
} 

You can also use !: if (!(Test-Path C:\Code)){}

Just for fun, you could also use bitwise exclusive or, though it's not the most readable/understandable method.

if ((test-path C:\code) -bxor 1) {write "it doesn't exist!"}

Use space as a delimiter with cut command

You can't do it easily with cut if the data has for example multiple spaces. I have found it useful to normalize input for easier processing. One trick is to use sed for normalization as below.

echo -e "foor\t \t bar" | sed 's:\s\+:\t:g' | cut -f2  #bar

How to initialize const member variable in a class?

In C++ you cannot initialize any variables directly while the declaration. For this we've to use the concept of constructors.
See this example:-

#include <iostream>

using namespace std;

class A
{
    public:
  const int x;  
  
  A():x(0) //initializing the value of x to 0
  {
      //constructor
  }
};

int main()
{
    A a; //creating object
   cout << "Value of x:- " <<a.x<<endl; 
   
   return 0;
}

Hope it would help you!

How to pass an array to a function in VBA?

Your function worked for me after changing its declaration to this ...

Function processArr(Arr As Variant) As String

You could also consider a ParamArray like this ...

Function processArr(ParamArray Arr() As Variant) As String
    'Dim N As Variant
    Dim N As Long
    Dim finalStr As String
    For N = LBound(Arr) To UBound(Arr)
        finalStr = finalStr & Arr(N)
    Next N
    processArr = finalStr
End Function

And then call the function like this ...

processArr("foo", "bar")

Attach to a processes output for viewing

How would I 'attach' a console/terminal-view to an applications output so I can see what it may be saying?

About this question, I know it is possible to catch the output, even when you didn't launch sceen command before launching the processus.

While I never tried it, I've found an interesting article which explains how to do using GDB (and without restarting your process).

redirecting-output-from-a-running-process

Basically:

  1. Check the open files list for your process, thanks to /proc/xxx/fd
  2. Attach your process with GDB
  3. While it is paused, close the file you are interested in, calling close() function (you can any function of your process in GDB. I suspect you need debug symbols in your process..)
  4. Open the a new file calling the create() or open() function. (Have a look in comments at the end, you'll see people suggest to use dup2() to ensure the same handle will be in use)
  5. Detach the process and let in run.

By the way, if you are running a linux OS on i386 box, comments are talking about a better tool to redirect output to a new console : 'retty' . If so, consider its use.

Subset data.frame by date

Well, it's clearly not a number since it has dashes in it. The error message and the two comments tell you that it is a factor but the commentators are apparently waiting and letting the message sink in. Dirk is suggesting that you do this:

 EPL2011_12$Date2 <- as.Date( as.character(EPL2011_12$Date), "%d-%m-%y")

After that you can do this:

 EPL2011_12FirstHalf <- subset(EPL2011_12, Date2 > as.Date("2012-01-13") )

R date functions assume the format is either "YYYY-MM-DD" or "YYYY/MM/DD". You do need to compare like classes: date to date, or character to character.

How to update record using Entity Framework 6?

Try It....

UpdateModel(book);

var book = new Model.Book
{
    BookNumber =  _book.BookNumber,
    BookName = _book.BookName,
    BookTitle = _book.BookTitle,
};
using (var db = new MyContextDB())
{
    var result = db.Books.SingleOrDefault(b => b.BookNumber == bookNumber);
    if (result != null)
    {
        try
        {
            UpdateModel(book);
            db.Books.Attach(book);
            db.Entry(book).State = EntityState.Modified;
            db.SaveChanges();
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}

Disable scrolling in webview?

This should be the complete answer. As suggested by @GDanger . Extend WebView to override the scroll methods and embed the custom webview within layout xml.

public class ScrollDisabledWebView extends WebView {

    private boolean scrollEnabled = false;

    public ScrollDisabledWebView(Context context) {
        super(context);
        initView(context);
    }

    public ScrollDisabledWebView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        initView(context);
    }
    // this is important. Otherwise it throws Binary Inflate Exception.
    private void initView(Context context) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

    @Override
    protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY,
                                   int scrollRangeX, int scrollRangeY, int maxOverScrollX,
                                   int maxOverScrollY, boolean isTouchEvent) {
        if (scrollEnabled) {
            return super.overScrollBy(deltaX, deltaY, scrollX, scrollY,
                    scrollRangeX, scrollRangeY, maxOverScrollX, maxOverScrollY, isTouchEvent);
        }
        return false;
    }

    @Override
    public void scrollTo(int x, int y) {
        if (scrollEnabled) {
            super.scrollTo(x, y);
        }
    }

    @Override
    public void computeScroll() {
        if (scrollEnabled) {
            super.computeScroll();
        }
    }
}

And then embed in layout file as follows

<com.sample.apps.ScrollDisabledWebView
    android:id="@+id/webView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true"
    tools:context="com.sample.apps.HomeActivity"/>

Then in the Activity, use some additional methods for disabling scrollbars too.

ScrollDisabledWebView webView = (ScrollDisabledWebView) findViewById(R.id.webView);
webView.setVerticalScrollBarEnabled(false);
webView.setHorizontalScrollBarEnabled(false);

What is the path that Django uses for locating and loading templates?

In django 3.1, go to setting of your project and import os

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "templates")],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Sorting Characters Of A C++ String

std::sort(str.begin(), str.end());

See here

SQlite - Android - Foreign key syntax

Since I cannot comment, adding this note in addition to @jethro answer.

I found out that you also need to do the FOREIGN KEY line as the last part of create the table statement, otherwise you will get a syntax error when installing your app. What I mean is, you cannot do something like this:

private static final String TASK_TABLE_CREATE = "create table "
    + TASK_TABLE + " (" + TASK_ID
    + " integer primary key autoincrement, " + TASK_TITLE
    + " text not null, " + TASK_NOTES + " text not null, "
+ TASK_CAT + " integer,"
+ " FOREIGN KEY ("+TASK_CAT+") REFERENCES "+CAT_TABLE+" ("+CAT_ID+"), "
+ TASK_DATE_TIME + " text not null);";

Where I put the TASK_DATE_TIME after the foreign key line.

Replace last occurrence of character in string

_x000D_
_x000D_
var someString = "(/n{})+++(/n{})---(/n{})$$$";_x000D_
var toRemove = "(/n{})"; // should find & remove last occurrence _x000D_
_x000D_
function removeLast(s, r){_x000D_
  s = s.split(r)_x000D_
  return s.slice(0,-1).join(r) + s.pop()_x000D_
}_x000D_
_x000D_
console.log(_x000D_
  removeLast(someString, toRemove)_x000D_
)
_x000D_
_x000D_
_x000D_

Breakdown:

s = s.split(toRemove)         // ["", "+++", "---", "$$$"]
s.slice(0,-1)                 //  ["", "+++", "---"]   
s.slice(0,-1).join(toRemove)  // "})()+++})()---"
s.pop()                       //  "$$$"   

How to set background color in jquery

How about this:

$(this).css('background-color', '#FFFFFF');

Related post: Add background color and border to table row on hover using jquery

How to install Python MySQLdb module using pip?

I had problems installing the 64-bit version of MySQLdb on Windows via Pip (problem compiling sources) [32bit version installed ok]. Managed to install the compiled MySQLdb from the .whl file available from http://www.lfd.uci.edu/~gohlke/pythonlibs/

The .whl file can then be installed via pip as document in https://pip.pypa.io/en/latest/user_guide/#installing-from-wheels

For example if you save in C:/ the you can install via

pip install c:/MySQL_python-1.2.5-cp27-none-win_amd64.whl

Follow-up: if you have a 64bit version of Python installed, then you want to install the 64-bit AMD version of MySQLdb from the link above [i.e. even if you have a Intel processor]. If you instead try and install the 32-bit version, I think you get the unsupported wheel error in comments below.

How do I get the computer name in .NET

System.Environment.MachineName

Or, if you are using Winforms, you can use System.Windows.Forms.SystemInformation.ComputerName, which returns exactly the same value as System.Environment.MachineName.

What is the standard way to add N seconds to datetime.time in Python?

Try adding a datetime.datetime to a datetime.timedelta. If you only want the time portion, you can call the time() method on the resultant datetime.datetime object to get it.

How to check if a user is logged in (how to properly use user.is_authenticated)?

If you want to check for authenticated users in your template then:

{% if user.is_authenticated %}
    <p>Authenticated user</p>
{% else %}
    <!-- Do something which you want to do with unauthenticated user -->
{% endif %}

GridView - Show headers on empty data source

You can use HeaderTemplate property to setup the head programatically or use ListView instead if you are using .NET 3.5.

Personally, I prefer ListView over GridView and DetailsView if possible, it gives you more control over your html.

Python coding standards/best practices

I follow the Python Idioms and Efficiency guidelines, by Rob Knight. I think they are exactly the same as PEP 8, but are more synthetic and based on examples.

If you are using wxPython you might also want to check Style Guide for wxPython code, by Chris Barker, as well.

Quick Sort Vs Merge Sort

Quicksort is in place. You need very little extra memory. Which is extremely important.

Good choice of median makes it even more efficient but even a bad choice of median quarantees Theta(nlogn).

How to save an activity state using save instance state?

My colleague wrote an article explaining application state on Android devices including explanations on activity lifecycle and state information, how to store state information, and saving to state Bundle and SharedPreferences and take a look at here.

The article covers three approaches:

Store local variable/UI control data for application lifetime (i.e. temporarily) using an instance state bundle

[Code sample – Store state in state bundle]
@Override
public void onSaveInstanceState(Bundle savedInstanceState)
{
  // Store UI state to the savedInstanceState.
  // This bundle will be passed to onCreate on next call.  EditText txtName = (EditText)findViewById(R.id.txtName);
  String strName = txtName.getText().toString();

  EditText txtEmail = (EditText)findViewById(R.id.txtEmail);
  String strEmail = txtEmail.getText().toString();

  CheckBox chkTandC = (CheckBox)findViewById(R.id.chkTandC);
  boolean blnTandC = chkTandC.isChecked();

  savedInstanceState.putString(“Name”, strName);
  savedInstanceState.putString(“Email”, strEmail);
  savedInstanceState.putBoolean(“TandC”, blnTandC);

  super.onSaveInstanceState(savedInstanceState);
}

Store local variable/UI control data between application instances (i.e. permanently) using shared preferences

[Code sample – store state in SharedPreferences]
@Override
protected void onPause()
{
  super.onPause();

  // Store values between instances here
  SharedPreferences preferences = getPreferences(MODE_PRIVATE);
  SharedPreferences.Editor editor = preferences.edit();  // Put the values from the UI
  EditText txtName = (EditText)findViewById(R.id.txtName);
  String strName = txtName.getText().toString();

  EditText txtEmail = (EditText)findViewById(R.id.txtEmail);
  String strEmail = txtEmail.getText().toString();

  CheckBox chkTandC = (CheckBox)findViewById(R.id.chkTandC);
  boolean blnTandC = chkTandC.isChecked();

  editor.putString(“Name”, strName); // value to store
  editor.putString(“Email”, strEmail); // value to store
  editor.putBoolean(“TandC”, blnTandC); // value to store
  // Commit to storage
  editor.commit();
}

Keeping object instances alive in memory between activities within application lifetime using a retained non-configuration instance

[Code sample – store object instance]
private cMyClassType moInstanceOfAClass; // Store the instance of an object
@Override
public Object onRetainNonConfigurationInstance()
{
  if (moInstanceOfAClass != null) // Check that the object exists
      return(moInstanceOfAClass);
  return super.onRetainNonConfigurationInstance();
}

Simplest Way to Test ODBC on WIndows

For ad hoc queries, the ODBC Test utility is pretty handy. Its design and interface is more oriented toward testing various parts of the ODBC API. But it works quite nicely for running queries and showing the output. It is part of the Microsoft Data Access Components.

To run a query, you can click the connect button (or use ctrl-F), choose a data source, type a query, then ctrl-E to execute it and ctrl-R to display the results (e.g., if it is a SELECT or something that returns a cursor).

How to select a node of treeview programmatically in c#?

private void btn_CollapseAllAndExpandFirstLevelUnderRoot(object sender, EventArgs e)

{
    //this example collapses everything, then expands the first level under the root node.

    tv_myTreeView.CollapseAll();
    TreeNode tn =  tv_myTreeView.Nodes[0];
    tn.Expand();
}

How do I set default value of select box in angularjs

if you don't even want to initialize ng-model to a static value and each value is DB driven, it can be done in the following way. Angular compares the evaluated value and populates the drop down.

Here below modelData.unitId is retrieved from DB and is compared to the list of unit id which is a separate list from db-

_x000D_
_x000D_
 <select id="uomList" ng-init="modelData.unitId"_x000D_
                         ng-model="modelData.unitId" ng-options="unitOfMeasurement.id as unitOfMeasurement.unitName for unitOfMeasurement in unitOfMeasurements">
_x000D_
_x000D_
_x000D_

How to disable margin-collapsing?

I know that this is a very old post but just wanted to say that using flexbox on a parent element would disable margin collapsing for its child elements.

How to get the second column from command output?

You don't need awk for that. Using read in Bash shell should be enough, e.g.

some_command | while read c1 c2; do echo $c2; done

or:

while read c1 c2; do echo $c2; done < in.txt

How do I get the App version and build number using Swift?

Bundle+Extensions.swift

import Foundation

extension Bundle {
    var versionNumber: String? {
        return infoDictionary?["CFBundleShortVersionString"] as? String
    }

    var buildNumber: String? {
        return infoDictionary?["CFBundleVersion"] as? String
    }

    var bundleName: String? {
        return infoDictionary?["CFBundleName"] as? String
    }
}

Usage:

someLabel.text = Bundle.main.versionNumber

Dropdownlist width in IE

The hedgerwow link (the YUI animation work-around) in the first best answer is broken, I guess the domain got expired. I copied the code before it got expired, so you can find it here (owner of code can let me know if I am breaching any copyrights by uploading it again)

http://ciitronian.com/blog/programming/yui-button-mimicking-native-select-dropdown-avoid-width-problem/

On the same blog post I wrote about making an exact same SELECT element like the normal one using YUI Button menu. Have a look and let me know if this helps!

How do I add a ToolTip to a control?

I did it this way: Just add the event to any control, set the control's tag, and add a conditional to handle the tooltip for the appropriate control/tag.

private void Info_MouseHover(object sender, EventArgs e)
{
    Control senderObject = sender as Control;
    string hoveredControl = senderObject.Tag.ToString();

    // only instantiate a tooltip if the control's tag contains data
    if (hoveredControl != "")
    {
        ToolTip info = new ToolTip
        {
            AutomaticDelay = 500
        };

        string tooltipMessage = string.Empty;

        // add all conditionals here to modify message based on the tag 
        // of the hovered control
        if (hoveredControl == "save button")
        {
            tooltipMessage = "This button will save stuff.";
        }

        info.SetToolTip(senderObject, tooltipMessage);
    }
}

How to split() a delimited string to a List<String>

Include using namespace System.Linq

List<string> stringList = line.Split(',').ToList();

you can make use of it with ease for iterating through each item.

foreach(string str in stringList)
{

}

String.Split() returns an array, hence convert it to a list using ToList()

What is the Angular equivalent to an AngularJS $watch?

If you want to make it 2 way binding, you can use [(yourVar)], but you have to implement yourVarChange event and call it everytime your variable change.

Something like this to track the hero change

@Output() heroChange = new EventEmitter();

and then when your hero get changed, call this.heroChange.emit(this.hero);

the [(hero)] binding will do the rest for you

see example here:

http://plnkr.co/edit/efOGIJ0POh1XQeRZctSx?p=preview

No process is on the other end of the pipe (SQL Server 2012)

Please check this also enter image description here Also check in configuration TCP/IP,Names PipeLine and shared memory enabled

How to obtain the number of CPUs/cores in Linux from the command line?

cat /proc/cpuinfo | grep processor

This worked fine. When I tried the first answer I got 3 CPU's as the output. I know that I have 4 CPUs on the system so I just did a grep for processor and the output looked like this:

[root@theservername ~]# cat /proc/cpuinfo | grep processor
processor       : 0
processor       : 1
processor       : 2
processor       : 3

Localhost : 404 not found

I had the same problem and here is how it worked for me :

1) Open XAMPP control panel.

2)On the right top corner go to config > Service and Port setting and change the port (I did 81 from 80).

3)Open config in Apache just right(next) to Apache admin Option and click on that and select first one (httpd.conf) it will open in the notepad.

4) There you find port listen 80 and replace it with 81 in all place and save the file.

5) Now restart Apache and MYSql

6) Now type following in Browser : http://localhost:81/phpmyadmin/

I hope this works.

PHP - count specific array values

$array = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");
$counts = array_count_values($array);
echo $counts['Ben'];

Create text file and fill it using bash

Your question is a a bit vague. This is a shell command that does what I think you want to do:

echo >> name_of_file

Javascript Image Resize

You don't have to do it with Javascript. You can just create a CSS class and apply it to your tag.

.preview_image{
        width: 300px;
    height: auto;
    border: 0px;
}

Compiled vs. Interpreted Languages

Short (un-precise) definition:

Compiled language: Entire program is translated to machine code at once, then the machine code is run by the CPU.

Interpreted language: Program is read line-by-line and as soon as a line is read the machine instructions for that line are executed by the CPU.

But really, few languages these days are purely compiled or purely interpreted, it often is a mix. For a more detailed description with pictures, see this thread:

What is the difference between compilation and interpretation?

Or my later blog post:

https://orangejuiceliberationfront.com/the-difference-between-compiler-and-interpreter/

How do I make a new line in swift

You can do this

textView.text = "Name: \(string1) \n" + "Phone Number: \(string2)"

The output will be

Name: output of string1 Phone Number: output of string2

Set timeout for ajax (jQuery)

Here's some examples that demonstrate setting and detecting timeouts in jQuery's old and new paradigmes.

Live Demo

Promise with jQuery 1.8+

Promise.resolve(
  $.ajax({
    url: '/getData',
    timeout:3000 //3 second timeout
  })
).then(function(){
  //do something
}).catch(function(e) {
  if(e.statusText == 'timeout')
  {     
    alert('Native Promise: Failed from timeout'); 
    //do something. Try again perhaps?
  }
});

jQuery 1.8+

$.ajax({
    url: '/getData',
    timeout:3000 //3 second timeout
}).done(function(){
    //do something
}).fail(function(jqXHR, textStatus){
    if(textStatus === 'timeout')
    {     
        alert('Failed from timeout'); 
        //do something. Try again perhaps?
    }
});?

jQuery <= 1.7.2

$.ajax({
    url: '/getData',
    error: function(jqXHR, textStatus){
        if(textStatus === 'timeout')
        {     
             alert('Failed from timeout');         
            //do something. Try again perhaps?
        }
    },
    success: function(){
        //do something
    },
    timeout:3000 //3 second timeout
});

Notice that the textStatus param (or jqXHR.statusText) will let you know what the error was. This may be useful if you want to know that the failure was caused by a timeout.

error(jqXHR, textStatus, errorThrown)

A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and JSONP requests.

src: http://api.jquery.com/jQuery.ajax/

How do I pull files from remote without overwriting local files?

You can stash your local changes first, then pull, then pop the stash.

git stash
git pull origin master
git stash pop

Anything that overrides changes from remote will have conflicts which you will have to manually resolve.

Best ways to teach a beginner to program?

My personal experience started back in elementary using Logo Writer (which in a way has evolved into Scratch), granted I was a little kid and computers where not as awesome as they are nowadays, but for the time being it took me places I hadn't been before... I think that's how I got hooked in the business... I could say that it was these first impressions based on such simplicity and coolness that made the goods that stick into my head for life. That's how basics in teaching programming should be taught... a simple process that yearns magic.

Back to my first CS 101, I started with notions of what an algorithm was by building a Tequila Sunrise (a step by step process that could be repeated at any time with the right ingredients, that will result in the same output), from there we move on to basic math functions using Scheme (like EHaskins was saying... start small and then build up), and from there to notions of loops, Boolean logic, structures and then building into concepts of objects and some simulation executions...

One of the good things about this approach is that language was not a goal but just a tool in the process of learning the concepts and basics of programming (just like operators, functions and else are in mathematics).

IMHO learning the basics of programming and creating a foundation is probably the best thing you could teach your brother, once the goal is covered then u can move on into a more general use language like python and teach them higher concepts like architecture and design patterns (make them natural in the process so he will get use to good practices from early stages and will see them as part of the process)... we are far from reinventing the warm water, but we always have to start by creating fire.

From there on the sky is the limit!

Installing Tomcat 7 as Service on Windows Server 2008

There are a lot of answers here, but many overlook a few points. I ran into the same issue and it was likely due to a combination of being a complete neophyte when it comes to tomcat. Even more I am rather new to web servers in general. I consider myself somewhat proficient user of windows, but I guess not proficient enough. In particular I don't work with services too much.

I did not have a startup.bat or any bat files. I only downloaded the 32-bit/64-bit Windows Service Installer. The bin that is created for that download is small - only 4 files. My colleagues were surprised that I did not have a catalina.bat etc... and I was too. Only the below four files in the bin. And no %CATALINA_HOME% or %TOMCAT_HOME% etc...

bootstrap.jar
tomcat-juli.jar
Tomcat7.exe
Tomcat7w.exe

With this setup I had some frustrations as setting parameters is done via the gui widget - very helpful I might add.

So nearly all the answers I have perused were not immediately applicable as many said, "go to bin and issue the startup.bat file" I am a neophyte but not so much to not be able to look into the bin and start such a file it is existed!

For my simple purposes (again remember that I am a neophyte at tomcat and even web servers) all I wanted to do was to be able to startup and shutdown the tomcat server from a cmd prompt window. Nothing too heavy duty. I am embarrassed to say how simple it is. It is probably evident to anyone with a shred of experience with services and such.

To Start server: <Tomcat Root>/bin>Tomcat7.exe start
To Stop server: <Tomcat Root>/bin>Tomcat7.exe stop

Found here - http://crunchify.com/how-to-start-stop-apache-tomcat-server-via-command-line-setup-as-windows-service/

I did not realize there was a separate download the 64-bit Windows zip file that has a tomcat server and all the standard array of cmd line tomcat management tools. This zip file has all the common startup/shutdown scripts, batch files for windows, including catalina.bat/.sh etc... Then all the above answers make sense and are rather trivial.

Remember I am a neophyte when it comes to tomcat and web servers. It appears these two downloads are somewhat mutually exclusive in the sense that if I download and install the 32-bit/64-bit Windows Service Installer version and the 64-bit Windows zip file the startup.bat file in the 64-bit Windows zip file version will not run or interact with the 32-bit/64-bit Windows Service Installer tomcat instance. But I am not sure about this point.

How to send password securely over HTTP?

Using HTTP with SSL will make your life much easier and you can rest at ease very smart people (smarter than me at least!) have scrutinized this method of confidential communication for years.

How to enable CORS in ASP.net Core WebAPI

Because you have a very simple CORS policy (Allow all requests from XXX domain), you don't need to make it so complicated. Try doing the following first (A very basic implementation of CORS).

If you haven't already, install the CORS nuget package.

Install-Package Microsoft.AspNetCore.Cors

In the ConfigureServices method of your startup.cs, add the CORS services.

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(); // Make sure you call this previous to AddMvc
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

Then in your Configure method of your startup.cs, add the following :

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    // Make sure you call this before calling app.UseMvc()
    app.UseCors(
        options => options.WithOrigins("http://example.com").AllowAnyMethod()
    );

    app.UseMvc();
}

Now give it a go. Policies are for when you want different policies for different actions (e.g. different hosts or different headers). For your simple example you really don't need it. Start with this simple example and tweak as you need to from there.

Further reading : http://dotnetcoretutorials.com/2017/01/03/enabling-cors-asp-net-core/

Shrinking navigation bar when scrolling down (bootstrap3)

Sticky navbar:

To make a sticky nav you need to add the class navbar-fixed-top to your nav

Official documentation:
http://getbootstrap.com/components/#navbar-fixed-top

Official example:
http://getbootstrap.com/examples/navbar-fixed-top/

A simple example code:

<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
  <div class="container">
    ...
  </div>
</nav>

with related jsfiddle: http://jsfiddle.net/ur7t8/

Resize the navbar:

If you want the nav bar to resize while you scroll the page you can give a look to this example: http://www.bootply.com/109943

JS

$(window).scroll(function() {
  if ($(document).scrollTop() > 50) {
    $('nav').addClass('shrink');
  } else {
    $('nav').removeClass('shrink');
  }
});

CSS

nav.navbar.shrink {
  min-height: 35px;
}

Animation:

To add an animation while you scroll, all you need to do is set a transition on the nav

CSS

nav.navbar{
  background-color:#ccc;
   // Animation
   -webkit-transition: all 0.4s ease;
   transition: all 0.4s ease;
}

I made a jsfiddle with the full example code: http://jsfiddle.net/Filo/m7yww8oa/

"The page has expired due to inactivity" - Laravel 5.5

I encountered the same issue on Linux-mint but then realized that the htdocs folder had no full permissions. So I changed the permissions of all the subdirectories in the htdocs folder by doing: sudo chown -c -R $USER:$USER /opt/lampp/htdocs/*

Get width/height of SVG element

From Firefox 33 onwards you can call getBoundingClientRect() and it will work normally, i.e. in the question above it will return 300 x 100.

Firefox 33 will be released on 14th October 2014 but the fix is already in Firefox nightlies if you want to try it out.

CSS: Fix row height

I haven't tried it but if you put a div in your table cell set so that it will have scrollbars if needed, then you could insert in there, with a fixed height on the div and it should keep your table row to a fixed height.

Rounding BigDecimal to *always* have two decimal places

value = value.setScale(2, RoundingMode.CEILING)

Add borders to cells in POI generated Excel File

If you're using the org.apache.poi.ss.usermodel (not HSSF or XSSF) you can use:

style.setBorderBottom(BorderStyle.THIN);
style.setBorderTop(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);

all the border styles are here at the apache documentation

Procedure expects parameter which was not supplied

It is necessary to tell that a Stored Proc is being called:

comm.CommandType = CommandType.StoredProcedure;

sql use statement with variable

I case that someone need a solution for this, this is one:

if you use a dynamic USE statement all your query need to be dynamic, because it need to be everything in the same context.

You can try with SYNONYM, is basically an ALIAS to a specific Table, this SYNONYM is inserted into the sys.synonyms table so you have access to it from any context

Look this static statement:

CREATE SYNONYM MASTER_SCHEMACOLUMNS FOR Master.INFORMATION_SCHEMA.COLUMNS
SELECT * FROM MASTER_SCHEMACOLUMNS

Now dynamic:

DECLARE @SQL VARCHAR(200)
DECLARE @CATALOG VARCHAR(200) = 'Master'

IF EXISTS(SELECT * FROM  sys.synonyms s WHERE s.name = 'CURRENT_SCHEMACOLUMNS')
BEGIN
DROP SYNONYM CURRENT_SCHEMACOLUMNS
END

SELECT @SQL = 'CREATE SYNONYM CURRENT_SCHEMACOLUMNS FOR '+ @CATALOG +'.INFORMATION_SCHEMA.COLUMNS';
EXEC sp_sqlexec @SQL

--Your not dynamic Code
SELECT * FROM CURRENT_SCHEMACOLUMNS

Now just change the value of @CATALOG and you will be able to list the same table but from different catalog.

Difference between a class and a module

The first answer is good and gives some structural answers, but another approach is to think about what you're doing. Modules are about providing methods that you can use across multiple classes - think about them as "libraries" (as you would see in a Rails app). Classes are about objects; modules are about functions.

For example, authentication and authorization systems are good examples of modules. Authentication systems work across multiple app-level classes (users are authenticated, sessions manage authentication, lots of other classes will act differently based on the auth state), so authentication systems act as shared APIs.

You might also use a module when you have shared methods across multiple apps (again, the library model is good here).

How to convert a Datetime string to a current culture datetime string

This works for me,

DateTimeFormatInfo usDtfi = new CultureInfo("en-US", false).DateTimeFormat;
DateTimeFormatInfo ukDtfi = new CultureInfo("en-GB", false).DateTimeFormat;
string result = Convert.ToDateTime("26/09/2015",ukDtfi).ToString(usDtfi.ShortDatePattern);

Java decimal formatting using String.format?

java.text.NumberFormat is probably what you want.

How to fix the Eclipse executable launcher was unable to locate its companion shared library for windows 7?

Had similar issue, which was a result of update. Please make sure that names of libraries mentioned in eclipse.ini and the actual names of these files on your disk match exactly.

-startup
plugins\org.eclipse.equinox.launcher_1.0.100.v20080509-1800.jar

--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.1.R36x_v20100810

Here is the post that I used to fix this issue on my system http://codewithgeeks.blogspot.in/2013/11/fixing-eclipse-executable-launcher-was.html

List all liquibase sql types

Well, since liquibase is open source there's always the source code which you could check.

Some of the data type classes seem to have a method toDatabaseDataType() which should give you information about what type works (is used) on a specific data base.

Bootstrap modal appearing under background

Having

transform:translate3d(0, 0, 0);

On any ancestor element can cause this as well. Tested on bootstrap 4.6.0.

How to create and download a csv file from php script?

I don't have enough reputation to reply to @complex857 solution. It works great, but I had to add ; at the end of the Content-Disposition header. Without it the browser adds two dashes at the end of the filename (e.g. instead of "export.csv" the file gets saved as "export.csv--"). Probably it tries to sanitize \r\n at the end of the header line.

Correct line should look like this:

header('Content-Disposition: attachment;filename="'.$filename.'";');

In case when CSV has UTF-8 chars in it, you have to change the encoding to UTF-8 by changing the Content-Type line:

header('Content-Type: application/csv; charset=UTF-8');

Also, I find it more elegant to use rewind() instead of fseek():

rewind($f);

Thanks for your solution!

Escape double quote character in XML

Others have answered in terms of how to handle the specific escaping in this case.

A broader answer is not to try to do it yourself. Use an XML API - there are plenty available for just about every modern programming platform in existence.

XML APIs will handle things like this for you automatically, making it a lot harder to go wrong. Unless you're writing an XML API yourself, you should rarely need to worry about the details like this.

Difference between HashMap and Map in Java..?

Map is an interface in Java. And HashMap is an implementation of that interface (i.e. provides all of the methods specified in the interface).

Regular expression for decimal number

As I tussled with this, TryParse in 3.5 does have NumberStyles: The following code should also do the trick without Regex to ignore thousands seperator.

double.TryParse(length, NumberStyles.AllowDecimalPoint,CultureInfo.CurrentUICulture, out lengthD))

Not relevant to the original question asked but confirming that TryParse() indeed is a good option.

Heroku deployment error H10 (App crashed)

I solved this problem by pushing to Git:

git add .
git commit -am "some text"
git push

then push to Heroku:

git push heroku

then rake db:migrate on Heroku:

heroku run rake db:migrate

What's an object file in C?

Object files are codes that are dependent on functions, symbols, and text to run the program. Just like old telex machines, which required teletyping to send signals to other telex machine.

In the same way processor's require binary code to run, object files are like binary code but not linked. Linking creates additional files so that the user does not have to have compile the C language themselves. Users can directly open the exe file once the object file is linked with some compiler like c language , or vb etc.

Visual Studio popup: "the operation could not be completed"

For me, this issue was being caused by conflicting <site> configurations in the following file.

C:\Users\smunro\Documents\IISExpress\config\applicationhost.config

I edited this file to remove all of the site elements within the following element. You might want to be a little more selective and try to identify the site that is causing the conflict and remove just that.

<configuration><system.applicationHost><sites>

Note that I left the <siteDefaults>, <applicationDefaults> and <virtualDirectoryDefaults> elements there.

When I reloaded the project, a new <site> element was created automatically.

How to sort an ArrayList in Java

Implement Comparable interface to Fruit.

public class Fruit implements Comparable<Fruit> {

It implements the method

@Override
    public int compareTo(Fruit fruit) {
        //write code here for compare name
    }

Then do call sort method

Collections.sort(fruitList);

EXCEL VBA, inserting blank row and shifting cells

If you want to just shift everything down you can use:

Rows(1).Insert shift:=xlShiftDown

Similarly to shift everything over:

Columns(1).Insert shift:=xlShiftRight

remove borders around html input

your code is look like this jsfiddle.net/NTkGZ/

try

border:none;

Prompt for user input in PowerShell

Using parameter binding is definitely the way to go here. Not only is it very quick to write (just add [Parameter(Mandatory=$true)] above your mandatory parameters), but it's also the only option that you won't hate yourself for later.

More below:

[Console]::ReadLine is explicitly forbidden by the FxCop rules for PowerShell. Why? Because it only works in PowerShell.exe, not PowerShell ISE, PowerGUI, etc.

Read-Host is, quite simply, bad form. Read-Host uncontrollably stops the script to prompt the user, which means that you can never have another script that includes the script that uses Read-Host.

You're trying to ask for parameters.

You should use the [Parameter(Mandatory=$true)] attribute, and correct typing, to ask for the parameters.

If you use this on a [SecureString], it will prompt for a password field. If you use this on a Credential type, ([Management.Automation.PSCredential]), the credentials dialog will pop up, if the parameter isn't there. A string will just become a plain old text box. If you add a HelpMessage to the parameter attribute (that is, [Parameter(Mandatory = $true, HelpMessage = 'New User Credentials')]) then it will become help text for the prompt.

Can someone explain the dollar sign in Javascript?

Dollar sign is used in ecmascript 2015-2016 as 'template literals'. Example:

var a = 5;
var b = 10;
console.log(`Sum is equal: ${a + b}`); // 'Sum is equlat: 15'

Here working example: https://es6console.com/j3lg8xeo/ Notice this sign " ` ",its not normal quotes.

U can also meet $ while working with library jQuery.

$ sign in Regular Expressions means end of line.

Where is Python language used?

Your categorization is not correct:

php, asp and ColdFusion are mostly used for websites, that is correct, but .net is definetly much more than asp you can build desktop applications, too (Paint.NET). I don't know about ColdFusion, but PHP can also be used to write desktop applications.

On the other hand C,C++ are not really often used for web programming, But it can be used for web programming (cgit). Java is definetly a language to develop web applications (spring and much more).

Python is a scripting language like PHP, Perl, Ruby and so much more. It can be used for web programming (django, Zope, Google App Engine, and much more). But it also can be used for desktop applications (Blender 3D, or even for games pygame).

Python can also be translated into binary code like java.

Using sed, how do you print the first 'N' characters of a line?

don't have to use grep either

an example:

sed -n '/searchwords/{s/^\(.\{12\}\).*/\1/g;p}' file

Python socket.error: [Errno 111] Connection refused

The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND command on another connection, but it apparently was "not opening [it] up in sync with the client side".

Well, the main reason would be there was no synchronisation whatsoever. Calling:

cs.send("SEND " + FILE)
cs.close()

would just place the data into a OS buffer; close would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep after close might mitigate the problem, but this is not synchronisation.

The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK, or better PORT 36250 to indicate where to connect). This would make sure the server is already listening.

The other thing is you must check the return values of send to make sure how many bytes was taken from your buffer. Or use sendall.

(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)

How do I write a RGB color value in JavaScript?

ES6 (template literal) helper functions:

function rgba(r, g, b, a=1){
    return `rgba(${r}, ${g}, ${b}, ${a})`
}
function rgb(r, g, b){
    return `rgb(${r}, ${g}, ${b})`
}

SHA512 vs. Blowfish and Bcrypt

It should suffice to say whether bcrypt or SHA-512 (in the context of an appropriate algorithm like PBKDF2) is good enough. And the answer is yes, either algorithm is secure enough that a breach will occur through an implementation flaw, not cryptanalysis.

If you insist on knowing which is "better", SHA-512 has had in-depth reviews by NIST and others. It's good, but flaws have been recognized that, while not exploitable now, have led to the the SHA-3 competition for new hash algorithms. Also, keep in mind that the study of hash algorithms is "newer" than that of ciphers, and cryptographers are still learning about them.

Even though bcrypt as a whole hasn't had as much scrutiny as Blowfish itself, I believe that being based on a cipher with a well-understood structure gives it some inherent security that hash-based authentication lacks. Also, it is easier to use common GPUs as a tool for attacking SHA-2–based hashes; because of its memory requirements, optimizing bcrypt requires more specialized hardware like FPGA with some on-board RAM.


Note: bcrypt is an algorithm that uses Blowfish internally. It is not an encryption algorithm itself. It is used to irreversibly obscure passwords, just as hash functions are used to do a "one-way hash".

Cryptographic hash algorithms are designed to be impossible to reverse. In other words, given only the output of a hash function, it should take "forever" to find a message that will produce the same hash output. In fact, it should be computationally infeasible to find any two messages that produce the same hash value. Unlike a cipher, hash functions aren't parameterized with a key; the same input will always produce the same output.

If someone provides a password that hashes to the value stored in the password table, they are authenticated. In particular, because of the irreversibility of the hash function, it's assumed that the user isn't an attacker that got hold of the hash and reversed it to find a working password.

Now consider bcrypt. It uses Blowfish to encrypt a magic string, using a key "derived" from the password. Later, when a user enters a password, the key is derived again, and if the ciphertext produced by encrypting with that key matches the stored ciphertext, the user is authenticated. The ciphertext is stored in the "password" table, but the derived key is never stored.

In order to break the cryptography here, an attacker would have to recover the key from the ciphertext. This is called a "known-plaintext" attack, since the attack knows the magic string that has been encrypted, but not the key used. Blowfish has been studied extensively, and no attacks are yet known that would allow an attacker to find the key with a single known plaintext.

So, just like irreversible algorithms based cryptographic digests, bcrypt produces an irreversible output, from a password, salt, and cost factor. Its strength lies in Blowfish's resistance to known plaintext attacks, which is analogous to a "first pre-image attack" on a digest algorithm. Since it can be used in place of a hash algorithm to protect passwords, bcrypt is confusingly referred to as a "hash" algorithm itself.

Assuming that rainbow tables have been thwarted by proper use of salt, any truly irreversible function reduces the attacker to trial-and-error. And the rate that the attacker can make trials is determined by the speed of that irreversible "hash" algorithm. If a single iteration of a hash function is used, an attacker can make millions of trials per second using equipment that costs on the order of $1000, testing all passwords up to 8 characters long in a few months.

If however, the digest output is "fed back" thousands of times, it will take hundreds of years to test the same set of passwords on that hardware. Bcrypt achieves the same "key strengthening" effect by iterating inside its key derivation routine, and a proper hash-based method like PBKDF2 does the same thing; in this respect, the two methods are similar.

So, my recommendation of bcrypt stems from the assumptions 1) that a Blowfish has had a similar level of scrutiny as the SHA-2 family of hash functions, and 2) that cryptanalytic methods for ciphers are better developed than those for hash functions.

$.widget is not a function

I got this error recently by introducing an old plugin to wordpress. It loaded an older version of jquery, which happened to be placed before the jquery mouse file. There was no jquery widget file loaded with the second version, which caused the error.

No error for using the extra jquery library -- that's a problem especially if a silent fail might have happened, causing a not so silent fail later on.

A potential way around it for wordpress might be to be explicit about the dependencies that way the jquery mouse would follow the widget which would follow the correct core leaving the other jquery to be loaded afterwards. Still might cause a production error later if you don't catch that and change the default function for jquery for the second version in all the files associated with it.

Can't escape the backslash with regex?

you can use ? at the end to skip one "\"

regex("\\\\?")

CSS: Responsive way to center a fluid div (without px width) while limiting the maximum width?

From Chris Coyier's article on centering percentage width elements:

Instead of using negative margins, you use negative translate() transforms.

.center {
  position: absolute;
  left: 50%;
  top: 50%;

  /*
  Nope =(
  margin-left: -25%;
  margin-top: -25%;
  */

  /* 
  Yep!
  */
  transform: translate(-50%, -50%);

  /*
  Not even necessary really. 
  e.g. Height could be left out!
  */
  width: 40%;
  height: 50%;
}

Codepen

When to use IList and when to use List

I don't think there are hard and fast rules for this type of thing, but I usually go by the guideline of using the lightest possible way until absolutely necessary.

For example, let's say you have a Person class and a Group class. A Group instance has many people, so a List here would make sense. When I declare the list object in Group I will use an IList<Person> and instantiate it as a List.

public class Group {
  private IList<Person> people;

  public Group() {
    this.people = new List<Person>();
  }
}

And, if you don't even need everything in IList you can always use IEnumerable too. With modern compilers and processors, I don't think there is really any speed difference, so this is more just a matter of style.

jQuery UI dialog positioning

As an alternative, you could use the jQuery UI Position utility e.g.

$(".mytext").mouseover(function() {
    var target = $(this);
    $("#dialog").dialog("widget").position({
       my: 'left',
       at: 'right',
       of: target
    });
}

What is the use of DesiredCapabilities in Selenium WebDriver?

When you run selenium WebDriver, the WebDriver opens a remote server in your computer's local host. Now, this server, called the Selenium Server, is used to interpret your code into actions to run or "drive" the instance of a real browser known as either chromebrowser, ie broser, ff browser, etc.

So, the Selenium Server can interact with different browser properties and hence it has many "capabilities".

Now what capabilities do you desire? Consider a scenario where you are validating if files have been downloaded properly in your app but, however, you do not have a desktop automation tool. In the case where you click the download link and a desktop pop up shows up to ask where to save and/or if you want to download. Your next route to bypass that would be to suppress that pop up. How? Desired Capabilities.

There are other such examples. In summary, Selenium Server can do a lot, use Desired Capabilities to tailor it to your need.

PowerShell: Create Local User Account

As of PowerShell 5.1 there cmdlet New-LocalUser which could create local user account.

Example of usage:

Create a user account

New-LocalUser -Name "User02" -Description "Description of this account." -NoPassword

or Create a user account that has a password

$Password = Read-Host -AsSecureString
New-LocalUser "User03" -Password $Password -FullName "Third User" -Description "Description of this account."

or Create a user account that is connected to a Microsoft account

New-LocalUser -Name "MicrosoftAccount\usr [email protected]" -Description "Description of this account." 

Firebase (FCM) how to get token

FirebaseInstanceId.getInstance().getInstanceId() deprecated. Now get user FCM token

 FirebaseMessaging.getInstance().getToken()
            .addOnCompleteListener(new OnCompleteListener<String>() {
                @Override
                public void onComplete(@NonNull Task<String> task) {
                    if (!task.isSuccessful()) {
                        System.out.println("--------------------------");
                        System.out.println(" " + task.getException());
                        System.out.println("--------------------------");
                        return;
                    }

                    // Get new FCM registration token
                    String token = task.getResult();

                    // Log 
                    String msg = "GET TOKEN " + token;
                    System.out.println("--------------------------");
                    System.out.println(" " + msg);
                    System.out.println("--------------------------");

                }
            });

Volatile boolean vs AtomicBoolean

Remember the IDIOM -

READ - MODIFY- WRITE this you can't achieve with volatile

The object 'DF__*' is dependent on column '*' - Changing int to double

MS SQL Studio take care of when you delete the column but if you need to Delete Constraint Programmatically here is simple solution

Here’s a code snippet that’ll drop a column with a default constraint:

DECLARE @ConstraintName nvarchar(200)
SELECT @ConstraintName = Name FROM SYS.DEFAULT_CONSTRAINTS WHERE PARENT_OBJECT_ID = OBJECT_ID('__TableName__') AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns WHERE NAME = N'__ColumnName__' AND object_id = OBJECT_ID(N'__TableName__'))
IF @ConstraintName IS NOT NULL
EXEC('ALTER TABLE __TableName__ DROP CONSTRAINT ' + @ConstraintName)
IF EXISTS (SELECT * FROM syscolumns WHERE id=object_id('__TableName__') AND name='__ColumnName__')
EXEC('ALTER TABLE __TableName__ DROP COLUMN __ColumnName__')

Just replace TableName and ColumnName with the appropriate values. You can safely run this even if the column has already been dropped.

Bonus: Here’s the code to drop foreign keys and other types of constraints.

IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where TABLE_NAME = '__TableName__' AND COLUMN_NAME = '__ColumnName__')
BEGIN
SELECT @ConstraintName = CONSTRAINT_NAME FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where TABLE_NAME = '__TableName__' AND COLUMN_NAME = '__ColumnName__'
EXEC('ALTER TABLE __TableName__ DROP CONSTRAINT ' + @ConstraintName)
END

Blog

Google Chrome forcing download of "f.txt" file

This issue appears to be causing ongoing consternation, so I will attempt to give a clearer answer than the previously posted answers, which only contain partial hints as to what's happening.

  • Some time around the summer of 2014, IT Security Engineer Michele Spagnuolo (apparently employed at Google Zurich) developed a proof-of-concept exploit and supporting tool called Rosetta Flash that demonstrated a way for hackers to run malicious Flash SWF files from a remote domain in a manner which tricks browsers into thinking it came from the same domain the user was currently browsing. This allows bypassing of the "same-origin policy" and can permit hackers a variety of exploits. You can read the details here: https://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
    • Known affected browsers: Chrome, IE
    • Possibly unaffected browsers: Firefox
  • Adobe has released at least 5 different fixes over the past year while trying to comprehensively fix this vulnerability, but various major websites also introduced their own fixes earlier on in order to prevent mass vulnerability to their userbases. Among the sites to do so: Google, Youtube, Facebook, Github, and others. One component of the ad-hoc mitigation implemented by these website owners was to force the HTTP Header Content-Disposition: attachment; filename=f.txt on the returns from JSONP endpoints. This has the annoyance of causing the browser to automatically download a file called f.txt that you didn't request—but it is far better than your browser automatically running a possibly malicious Flash file.
  • In conclusion, the websites you were visiting when this file spontaneously downloaded are not bad or malicious, but some domain serving content on their pages (usually ads) had content with this exploit inside it. Note that this issue will be random and intermittent in nature because even visiting the same pages consecutively will often produce different ad content. For example, the advertisement domain ad.doubleclick.net probably serves out hundreds of thousands of different ads and only a small percentage likely contain malicious content. This is why various users online are confused thinking they fixed the issue or somehow affected it by uninstalling this program or running that scan, when in fact it is all unrelated. The f.txt download just means you were protected from a recent potential attack with this exploit and you should have no reason to believe you were compromised in any way.
  • The only way I'm aware that you could stop this f.txt file from being downloaded again in the future would be to block the most common domains that appear to be serving this exploit. I've put a short list below of some of the ones implicated in various posts. If you wanted to block these domains from touching your computer, you could add them to your firewall or alternatively you could use the HOSTS file technique described in the second section of this link: http://www.chromefans.org/chrome-tutorial/how-to-block-a-website-in-google-chrome.htm
  • Short list of domains you could block (by no means a comprehensive list). Most of these are highly associated with adware and malware:
    • ad.doubleclick.net
    • adclick.g.doubleclick.net
    • secure-us.imrworldwide.com
    • d.turn.com
    • ad.turn.com
    • secure.insightexpressai.com
    • core.insightexpressai.com

Column name or number of supplied values does not match table definition

The computed columns make the problem. Do not use SELECT *. You must specify each fields after SELECT except computed fields

jQuery '.each' and attaching '.click' event

No need to use .each. click already binds to all div occurrences.

$('div').click(function(e) {
    ..    
});

See Demo

Note: use hard binding such as .click to make sure dynamically loaded elements don't get bound.

How do I show a "Loading . . . please wait" message in Winforms for a long loading form?

I looked at most the solutions posted, but came across a different one that I prefer. It's simple, doesn't use threads, and works for what I want it to.

http://weblogs.asp.net/kennykerr/archive/2004/11/26/where-is-form-s-loaded-event.aspx

I added to the solution in the article and moved the code into a base class that all my forms inherit from. Now I just call one function: ShowWaitForm() during the frm_load() event of any form that needs a wait dialogue box while the form is loading. Here's the code:

public class MyFormBase : System.Windows.Forms.Form
{
    private MyWaitForm _waitForm;

    protected void ShowWaitForm(string message)
    {
        // don't display more than one wait form at a time
        if (_waitForm != null && !_waitForm.IsDisposed) 
        {
            return;
        }

        _waitForm = new MyWaitForm();
        _waitForm.SetMessage(message); // "Loading data. Please wait..."
        _waitForm.TopMost = true;
        _waitForm.StartPosition = FormStartPosition.CenterScreen;
        _waitForm.Show();
        _waitForm.Refresh();

        // force the wait window to display for at least 700ms so it doesn't just flash on the screen
        System.Threading.Thread.Sleep(700);         
        Application.Idle += OnLoaded;
    }

    private void OnLoaded(object sender, EventArgs e)
    {
        Application.Idle -= OnLoaded;
        _waitForm.Close();
    }
}

MyWaitForm is the name of a form you create to look like a wait dialogue. I added a SetMessage() function to customize the text on the wait form.

Create a new file in git bash

Yes, it is. Just create files in the windows explorer and git automatically detects these files as currently untracked. Then add it with the command you already mentioned.

git add does not create any files. See also http://gitref.org/basic/#add

Github probably creates the file with touch and adds the file for tracking automatically. You can do this on the bash as well.

Ruby String to Date Conversion

You can try https://rubygems.org/gems/dates_from_string:

Find date in structure:

text = "get car from repair 2015-02-02 23:00:10"
dates_from_string = DatesFromString.new
dates_from_string.find_date(text)

=> ["2015-02-02 23:00:10"]

How can I convert my Java program to an .exe file?

We're using Install4J to build installers for windows or unix environments.

It's easily customizable up to the point where you want to write scripts for special actions that cannot be done with standard dialogues. But even though we're setting up windows services with it, we're only using standard components.

  • installer + launcher
  • windows or unix
  • scriptable in Java
  • ant task
  • lots of customizable standard panels and actions
  • optionally includes or downloads a JRE
  • can also launch windows services
  • multiple languages

I think Launch4J is from the same company (just the launcher - no installer).

PS: sadly i'm not getting paid for this endorsement. I just like that tool.

In Visual Studio C++, what are the memory allocation representations?

There's actually quite a bit of useful information added to debug allocations. This table is more complete:

http://www.nobugs.org/developer/win32/debug_crt_heap.html#table

Address  Offset After HeapAlloc() After malloc() During free() After HeapFree() Comments
0x00320FD8  -40    0x01090009    0x01090009     0x01090009    0x0109005A     Win32 heap info
0x00320FDC  -36    0x01090009    0x00180700     0x01090009    0x00180400     Win32 heap info
0x00320FE0  -32    0xBAADF00D    0x00320798     0xDDDDDDDD    0x00320448     Ptr to next CRT heap block (allocated earlier in time)
0x00320FE4  -28    0xBAADF00D    0x00000000     0xDDDDDDDD    0x00320448     Ptr to prev CRT heap block (allocated later in time)
0x00320FE8  -24    0xBAADF00D    0x00000000     0xDDDDDDDD    0xFEEEFEEE     Filename of malloc() call
0x00320FEC  -20    0xBAADF00D    0x00000000     0xDDDDDDDD    0xFEEEFEEE     Line number of malloc() call
0x00320FF0  -16    0xBAADF00D    0x00000008     0xDDDDDDDD    0xFEEEFEEE     Number of bytes to malloc()
0x00320FF4  -12    0xBAADF00D    0x00000001     0xDDDDDDDD    0xFEEEFEEE     Type (0=Freed, 1=Normal, 2=CRT use, etc)
0x00320FF8  -8     0xBAADF00D    0x00000031     0xDDDDDDDD    0xFEEEFEEE     Request #, increases from 0
0x00320FFC  -4     0xBAADF00D    0xFDFDFDFD     0xDDDDDDDD    0xFEEEFEEE     No mans land
0x00321000  +0     0xBAADF00D    0xCDCDCDCD     0xDDDDDDDD    0xFEEEFEEE     The 8 bytes you wanted
0x00321004  +4     0xBAADF00D    0xCDCDCDCD     0xDDDDDDDD    0xFEEEFEEE     The 8 bytes you wanted
0x00321008  +8     0xBAADF00D    0xFDFDFDFD     0xDDDDDDDD    0xFEEEFEEE     No mans land
0x0032100C  +12    0xBAADF00D    0xBAADF00D     0xDDDDDDDD    0xFEEEFEEE     Win32 heap allocations are rounded up to 16 bytes
0x00321010  +16    0xABABABAB    0xABABABAB     0xABABABAB    0xFEEEFEEE     Win32 heap bookkeeping
0x00321014  +20    0xABABABAB    0xABABABAB     0xABABABAB    0xFEEEFEEE     Win32 heap bookkeeping
0x00321018  +24    0x00000010    0x00000010     0x00000010    0xFEEEFEEE     Win32 heap bookkeeping
0x0032101C  +28    0x00000000    0x00000000     0x00000000    0xFEEEFEEE     Win32 heap bookkeeping
0x00321020  +32    0x00090051    0x00090051     0x00090051    0xFEEEFEEE     Win32 heap bookkeeping
0x00321024  +36    0xFEEE0400    0xFEEE0400     0xFEEE0400    0xFEEEFEEE     Win32 heap bookkeeping
0x00321028  +40    0x00320400    0x00320400     0x00320400    0xFEEEFEEE     Win32 heap bookkeeping
0x0032102C  +44    0x00320400    0x00320400     0x00320400    0xFEEEFEEE     Win32 heap bookkeeping

How to call Stored Procedure in a View?

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

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

create view vw_view1 as select * from table1

How to find tags with only certain attributes - BeautifulSoup

The easiest way to do this is with the new CSS style select method:

soup = BeautifulSoup(html)
results = soup.select('td[valign="top"]')

How to include jQuery in ASP.Net project?

if you build an MVC project, its included by default. otherwise, what Nick said.

How to add image in Flutter

  1. Create images folder in root level of your project.

    enter image description here

    enter image description here

  2. Drop your image in this folder, it should look like

    enter image description here

  3. Go to your pubspec.yaml file, add assets header and pay close attention to all the spaces.

    flutter:
    
      uses-material-design: true
    
      # add this
      assets:
        - images/profile.jpg
    
  4. Tap on Packages get at the top right corner of the IDE.

    enter image description here

  5. Now you can use your image anywhere using

    Image.asset("images/profile.jpg")
    

'heroku' does not appear to be a git repository

I got the same error and it turned out I was in the wrong directory. It's a simple mistake to make so double check that you are in the root and then run heroku create and heroku git push master again. Of course you must have done git init, as mentioned in StickMaNX answer above, already before the heroku steps.

Copying a local file from Windows to a remote server using scp

Drive letter can be used in the source like

scp /c/path/to/file.txt user@server:/dir1/file.txt

Delete last char of string

string strgroupids = string.Empty;

groupIds.ForEach(g =>
{
    strgroupids = strgroupids + g.ToString() + ",";
});

strgroupids = strgroupids.Substring(0, strgroupids.Length - 1);

Note that the use of ForEach here is normally considered "wrong" (read for example http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx)

Using some LINQ:

string strgroupids = groupIds.Aggregate(string.Empty, (p, q) => p + q + ',');
strgroupids = strgroupids.Substring(0, str1.Length - 1);

Without end-substringing:

string strgroupids = groupIds.Aggregate(string.Empty, (p, q) => (p != string.Empty ? p + "," + q : q.ToString()));

What are NDF Files?

Secondary data files are optional, are user-defined, and store user data. Secondary files can be used to spread data across multiple disks by putting each file on a different disk drive. Additionally, if a database exceeds the maximum size for a single Windows file, you can use secondary data files so the database can continue to grow.

Source: MSDN: Understanding Files and Filegroups

The recommended file name extension for secondary data files is .ndf, but this is not enforced.

Convert cells(1,1) into "A1" and vice versa

The Address property of a cell can get this for you:

MsgBox Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)

returns A1.

The other way around can be done with the Row and Column property of Range:

MsgBox Range("A1").Row & ", " & Range("A1").Column

returns 1,1.

What does \u003C mean?

It is a unicode char \u003C = <

Constantly print Subprocess output while process is running

In Python >= 3.5 using subprocess.run works for me:

import subprocess

cmd = 'echo foo; sleep 1; echo foo; sleep 2; echo foo'
subprocess.run(cmd, shell=True)

(getting the output during execution also works without shell=True) https://docs.python.org/3/library/subprocess.html#subprocess.run

R dates "origin" must be supplied

I suspect you meant:

axis.Date(1, as.Date(sites$date, origin = "1970-01-01"))

as the 'x' argument to as.Date() has to be of type Date.

As an aside, this would have appropriate as a follow-up or edit of your previous question.

How to select first and last TD in a row?

You could use the :first-child and :last-child pseudo-selectors:

tr td:first-child,
tr td:last-child {
    /* styles */
}

This should work in all major browsers, but IE7 has some problems when elements are added dynamically (and it won't work in IE6).

How to get the current directory in a C program?

Have you had a look at getcwd()?

#include <unistd.h>
char *getcwd(char *buf, size_t size);

Simple example:

#include <unistd.h>
#include <stdio.h>
#include <limits.h>

int main() {
   char cwd[PATH_MAX];
   if (getcwd(cwd, sizeof(cwd)) != NULL) {
       printf("Current working dir: %s\n", cwd);
   } else {
       perror("getcwd() error");
       return 1;
   }
   return 0;
}

How to select the first element of a set with JSTL?

Work for arrays and lists only, not for set.

Determine Pixel Length of String in Javascript/jQuery?

If you use Snap.svg, the following works:

var tPaper = Snap(300, 300);
var tLabelText = tPaper.text(100, 100, "label text");
var tWidth = tLabelText.getBBox().width;  // the width of the text in pixels.
tLabelText.attr({ x : 150 - (tWidth/2)});   // now it's centered in x

Java String array: is there a size of method?

Yes, .length (property-like, not a method):

String[] array = new String[10];
int size = array.length;

How to listen to route changes in react router v4?

You should to use history v4 lib.

Example from there

history.listen((location, action) => {
  console.log(`The current URL is ${location.pathname}${location.search}${location.hash}`)
  console.log(`The last navigation action was ${action}`)
})

How to run a javascript function during a mouseover on a div

 <div onmouseover='alert("welcome")' id="sub1 sub2 sub3">some text</div>

Or something like this

Java Try and Catch IOException Problem

Your countLines(String filename) method throws IOException.

You can't use it in a member declaration. You'll need to perform the operation in a main(String[] args) method.

Your main(String[] args) method will get the IOException thrown to it by countLines and it will need to handle or declare it.

Try this to just throw the IOException from main

public class MyClass {
  private int lineCount;
  public static void main(String[] args) throws IOException {
    lineCount = LineCounter.countLines(sFileName);
  }
}

or this to handle it and wrap it in an unchecked IllegalArgumentException:

public class MyClass {
  private int lineCount;
  private String sFileName  = "myfile";
  public static void main(String[] args) throws IOException {
    try {
      lineCount = LineCounter.countLines(sFileName);
     } catch (IOException e) {
       throw new IllegalArgumentException("Unable to load " + sFileName, e);
     }
  }
}

how to change text box value with jQuery?

Try this jsfiddle:

$(function() {
  $('#cd').click(function () {
    $('#dsf').val('Changed Value');
  });
});

Default string initialization: NULL or Empty?

I think there's no reason not to use null for an unassigned (or at this place in a program flow not occurring) value. If you want to distinguish, there's ==null. If you just want to check for a certain value and don't care whether it's null or something different, String.Equals("XXX",MyStringVar) does just fine.

Setting TIME_WAIT TCP

A TCP connection is specified by the tuple (source IP, source port, destination IP, destination port).

The reason why there is a TIME_WAIT state following session shutdown is because there may still be live packets out in the network on their way to you (or from you which may solicit a response of some sort). If you were to re-create that same tuple and one of those packets showed up, it would be treated as a valid packet for your connection (and probably cause an error due to sequencing).

So the TIME_WAIT time is generally set to double the packets maximum age. This value is the maximum age your packets will be allowed to get to before the network discards them.

That guarantees that, before you're allowed to create a connection with the same tuple, all the packets belonging to previous incarnations of that tuple will be dead.

That generally dictates the minimum value you should use. The maximum packet age is dictated by network properties, an example being that satellite lifetimes are higher than LAN lifetimes since the packets have much further to go.

Selecting data from two different servers in SQL Server

You can do it using Linked Server.

Typically linked servers are configured to enable the Database Engine to execute a Transact-SQL statement that includes tables in another instance of SQL Server, or another database product such as Oracle. Many types OLE DB data sources can be configured as linked servers, including Microsoft Access and Excel.

Linked servers offer the following advantages:

  • The ability to access data from outside of SQL Server.
  • The ability to issue distributed queries, updates, commands, and transactions on heterogeneous data sources across the enterprise.
  • The ability to address diverse data sources similarly.

Read more about Linked Servers.

Follow these steps to create a Linked Server:

  1. Server Objects -> Linked Servers -> New Linked Server

  2. Provide Remote Server Name.

  3. Select Remote Server Type (SQL Server or Other).

  4. Select Security -> Be made using this security context and provide login and password of remote server.

  5. Click OK and you are done !!

Here is a simple tutorial for creating a linked server.

OR

You can add linked server using query.

Syntax:

sp_addlinkedserver [ @server= ] 'server' [ , [ @srvproduct= ] 'product_name' ] 
     [ , [ @provider= ] 'provider_name' ]
     [ , [ @datasrc= ] 'data_source' ] 
     [ , [ @location= ] 'location' ] 
     [ , [ @provstr= ] 'provider_string' ] 
     [ , [ @catalog= ] 'catalog' ] 

Read more about sp_addlinkedserver.

You have to create linked server only once. After creating linked server, we can query it as follows:

select * from LinkedServerName.DatabaseName.OwnerName.TableName

How to increase the vertical split window size in Vim

I am using the below commands for this:

set lines=50     " For increasing the height to 50 lines (vertical)
set columns=200  " For increasing the width to 200 columns (horizontal)

Is there a better way to refresh WebView?

This worked for me.

just put under onCreate metode

Button button = (Button) findViewById(R.id.reload_btn);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            web.loadUrl( "javascript:window.location.reload( true )" );             
        }
    });

This is the code that can reload a website in a webView

web.loadUrl( "javascript:window.location.reload( true )" );  

How to improve performance of ngRepeat over a huge dataset (angular.js)?

Sometimes what happened,you get the data from server (or back-end) in few ms (for example I'm I am assuming it 100ms) but it takes more time to display in our web page (let's say it is taking 900ms to display).

So, What is happening here is 800ms It is taking just to render web page.

What I have done in my web application is, I have used pagination (or you can use infinite scrolling also) to display list of data. Let's say I am showing 50 data/page.

So I will not load render all the data at once,only 50 data I am loading initially which takes only 50ms (I'm assuming here).

so total time here decreased from 900ms to 150ms, once user request next page then display next 50 data and so on.

Hope this will help you to improve the performance. All the best

What is a practical use for a closure in JavaScript?

JavaScript closures can be used to implement throttle and debounce functionality in your application.

Throttling

Throttling puts a limit on as a maximum number of times a function can be called over time. As in "execute this function at most once every 100 milliseconds."

Code:

const throttle = (func, limit) => {
  let isThrottling
  return function() {
    const args = arguments
    const context = this
    if (!isThrottling) {
      func.apply(context, args)
      isThrottling = true
      setTimeout(() => isThrottling = false, limit)
    }
  }
}

Debouncing

Debouncing puts a limit on a function not be called again until a certain amount of time has passed without it being called. As in "execute this function only if 100 milliseconds have passed without it being called."

Code:

const debounce = (func, delay) => {
  let debouncing
  return function() {
    const context = this
    const args = arguments
    clearTimeout(debouncing)
    debouncing = setTimeout(() => func.apply(context, args), delay)
  }
}

As you can see closures helped in implementing two beautiful features which every web application should have to provide smooth UI experience functionality.

How to connect wireless network adapter to VMWare workstation?

Workstation doesn't have a wireless NIC type, so direct wireless hardware access is out. If you just want to access through the extant host wireless connection, bridging is your answer.

I think the only way to get a wireless NIC dedicated to the VM would be using a USB wireless NIC as a USB-passthrough device on the VM. When you have Workstation running and a USB device plugged in, it should give you an option to change whether that device is connected to the host or to the VM.

Laravel Eloquent update just if changes have been made

You're already doing it!

save() will check if something in the model has changed. If it hasn't it won't run a db query.

Here's the relevant part of code in Illuminate\Database\Eloquent\Model@performUpdate:

protected function performUpdate(Builder $query, array $options = [])
{
    $dirty = $this->getDirty();

    if (count($dirty) > 0)
    {
        // runs update query
    }

    return true;
}

The getDirty() method simply compares the current attributes with a copy saved in original when the model is created. This is done in the syncOriginal() method:

public function __construct(array $attributes = array())
{
    $this->bootIfNotBooted();

    $this->syncOriginal();

    $this->fill($attributes);
}

public function syncOriginal()
{
    $this->original = $this->attributes;

    return $this;
}

If you want to check if the model is dirty just call isDirty():

if($product->isDirty()){
    // changes have been made
}

Or if you want to check a certain attribute:

if($product->isDirty('price')){
    // price has changed
}

Enable SQL Server Broker taking too long

Enabling SQL Server Service Broker requires a database lock. Stop the SQL Server Agent and then execute the following:

USE master ;
GO

ALTER DATABASE [MyDatabase] SET ENABLE_BROKER ;
GO

Change [MyDatabase] with the name of your database in question and then start SQL Server Agent.

If you want to see all the databases that have Service Broker enabled or disabled, then query sys.databases, for instance:

SELECT
    name, database_id, is_broker_enabled
FROM sys.databases

How to enable bulk permission in SQL Server

SQL Server may also return this error if the service account does not have permission to read the file being imported. Ensure that the service account has read access to the file location. For example:

icacls D:\ImportFiles /Grant "NT Service\MSSQLServer":(OI)(CI)R

How to pass form input value to php function

you must have read about function call . here i give you example of it.

<?php
 funtion pr($n)
{
echo $n;
 }
?>
<form action="<?php $f=$_POST['input'];pr($f);?>" method="POST">
<input name=input type=text></input>
</form>

Is there a TRY CATCH command in Bash

You can do:

#!/bin/bash
if <command> ; then # TRY
    <do-whatever-you-want>
else # CATCH
    echo 'Exception'
    <do-whatever-you-want>
fi

How does bitshifting work in Java?

These examples cover the three types of shifts applied to both a positive and a negative number:

// Signed left shift on 626348975
00100101010101010101001110101111 is   626348975
01001010101010101010011101011110 is  1252697950 after << 1
10010101010101010100111010111100 is -1789571396 after << 2
00101010101010101001110101111000 is   715824504 after << 3

// Signed left shift on -552270512
11011111000101010000010101010000 is  -552270512
10111110001010100000101010100000 is -1104541024 after << 1
01111100010101000001010101000000 is  2085885248 after << 2
11111000101010000010101010000000 is  -123196800 after << 3


// Signed right shift on 626348975
00100101010101010101001110101111 is   626348975
00010010101010101010100111010111 is   313174487 after >> 1
00001001010101010101010011101011 is   156587243 after >> 2
00000100101010101010101001110101 is    78293621 after >> 3

// Signed right shift on -552270512
11011111000101010000010101010000 is  -552270512
11101111100010101000001010101000 is  -276135256 after >> 1
11110111110001010100000101010100 is  -138067628 after >> 2
11111011111000101010000010101010 is   -69033814 after >> 3


// Unsigned right shift on 626348975
00100101010101010101001110101111 is   626348975
00010010101010101010100111010111 is   313174487 after >>> 1
00001001010101010101010011101011 is   156587243 after >>> 2
00000100101010101010101001110101 is    78293621 after >>> 3

// Unsigned right shift on -552270512
11011111000101010000010101010000 is  -552270512
01101111100010101000001010101000 is  1871348392 after >>> 1
00110111110001010100000101010100 is   935674196 after >>> 2
00011011111000101010000010101010 is   467837098 after >>> 3

org.hibernate.NonUniqueResultException: query did not return a unique result: 2?

First you must test the query list size; here a example:

long count;
if (query.list().size() > 0)
    count=(long) criteria.list().get(0);   
else
    count=0;            
return count;

What does SQL clause "GROUP BY 1" mean?

It means to group by the first column regardless of what it's called. You can do the same with ORDER BY.

Save file/open file dialog box, using Swing & Netbeans GUI editor

I have created a sample UI which shows the save and open file dialog. Click on save button to open save dialog and click on open button to open file dialog.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class FileChooserEx {
    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                new FileChooserEx().createUI();
            }
        };

        EventQueue.invokeLater(r);
    }

    private void createUI() {
        JFrame frame = new JFrame();
        frame.setLayout(new BorderLayout());

        JButton saveBtn = new JButton("Save");
        JButton openBtn = new JButton("Open");

        saveBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                JFileChooser saveFile = new JFileChooser();
                saveFile.showSaveDialog(null);
            }
        });

        openBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                JFileChooser openFile = new JFileChooser();
                openFile.showOpenDialog(null);
            }
        });

        frame.add(new JLabel("File Chooser"), BorderLayout.NORTH);
        frame.add(saveBtn, BorderLayout.CENTER);
        frame.add(openBtn, BorderLayout.SOUTH);
        frame.setTitle("File Chooser");
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

SQL - Create view from multiple tables

Union is not what you want. You want to use joins to create single rows. It's a little unclear what constitutes a unique row in your tables and how they really relate to each other and it's also unclear if one table will have rows for every country in every year. But I think this will work:

CREATE VIEW V AS (

  SELECT i.country,i.year,p.pop,f.food,i.income FROM
    INCOME i
  LEFT JOIN 
    POP p 
  ON
    i.country=p.country
  LEFT JOIN
    Food f
  ON 
    i.country=f.country
  WHERE 
    i.year=p.year
  AND
    i.year=f.year
);

The left (outer) join will return rows from the first table even if there are no matches in the second. I've written this assuming you would have a row for every country for every year in the income table. If you don't things get a bit hairy as MySQL does not have built in support for FULL OUTER JOINs last I checked. There are ways to simulate it, and they would involve unions. This article goes into some depth on the subject: http://www.xaprb.com/blog/2006/05/26/how-to-write-full-outer-join-in-mysql/

Is the order of elements in a JSON list preserved?

The order of elements in an array ([]) is maintained. The order of elements (name:value pairs) in an "object" ({}) is not, and it's usual for them to be "jumbled", if not by the JSON formatter/parser itself then by the language-specific objects (Dictionary, NSDictionary, Hashtable, etc) that are used as an internal representation.

How can I get the file name from request.FILES?

request.FILES['filename'].name

From the request documentation.

If you don't know the key, you can iterate over the files:

for filename, file in request.FILES.iteritems():
    name = request.FILES[filename].name

Check if String / Record exists in DataTable

I think that if your "item_manuf_id" is the primary key of the DataTable you could use the Find method ...

string s = "stringValue";
DataRow foundRow = dtPs.Rows.Find(s);
if(foundRow != null) {
 //You have it ...
 }

Repeat string to certain length

i use this:

def extend_string(s, l):
    return (s*l)[:l]

Is there a way to word-wrap long words in a div?

Most of the previous answer didn't work for me in Firefox 38.0.5. This did...

<div style='padding: 3px; width: 130px; word-break: break-all; word-wrap: break-word;'>
    // Content goes here
</div>

Documentation:

What does it mean to write to stdout in C?

stdout is the standard output stream in UNIX. See http://www.gnu.org/software/libc/manual/html_node/Standard-Streams.html#Standard-Streams. When running in a terminal, you will see data written to stdout in the terminal and you can redirect it as you choose.

Replace Default Null Values Returned From Left Outer Join

In case of MySQL or SQLite the correct keyword is IFNULL (not ISNULL).

 SELECT iar.Description, 
      IFNULL(iai.Quantity,0) as Quantity, 
      IFNULL(iai.Quantity * rpl.RegularPrice,0) as 'Retail', 
      iar.Compliance 
    FROM InventoryAdjustmentReason iar
    LEFT OUTER JOIN InventoryAdjustmentItem iai  on (iar.Id = iai.InventoryAdjustmentReasonId)
    LEFT OUTER JOIN Item i on (i.Id = iai.ItemId)
    LEFT OUTER JOIN ReportPriceLookup rpl on (rpl.SkuNumber = i.SkuNo)
WHERE iar.StoreUse = 'yes'

MAX() and MAX() OVER PARTITION BY produces error 3504 in Teradata Query

Logically OLAP functions are calculated after GROUP BY/HAVING, so you can only access columns in GROUP BY or columns with an aggregate function. Following looks strange, but is Standard SQL:

SELECT employee_number,
       MAX(MAX(course_completion_date)) 
           OVER (PARTITION BY course_code) AS max_course_date,
       MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code

And as Teradata allows re-using an alias this also works:

SELECT employee_number,
       MAX(max_date) 
           OVER (PARTITION BY course_code) AS max_course_date,
       MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code

Script to get the HTTP status code of a list of urls?

Due to https://mywiki.wooledge.org/BashPitfalls#Non-atomic_writes_with_xargs_-P (output from parallel jobs in xargs risks being mixed), I would use GNU Parallel instead of xargs to parallelize:

cat url.lst |
  parallel -P0 -q curl -o /dev/null --silent --head --write-out '%{url_effective}: %{http_code}\n' > outfile

In this particular case it may be safe to use xargs because the output is so short, so the problem with using xargs is rather that if someone later changes the code to do something bigger, it will no longer be safe. Or if someone reads this question and thinks he can replace curl with something else, then that may also not be safe.

Capture Video of Android's Screen

Android 4.3 has a new MediaCodec API that can be used to record from a surface. See: http://developer.android.com/about/versions/android-4.3.html (scroll down to the section "Video encoding from a Surface")

How to search a list of tuples in Python

Supposing the list may be long and the numbers may repeat, consider using the SortedList type from the Python sortedcontainers module. The SortedList type will automatically maintain the tuples in order by number and allow for fast searching.

For example:

from sortedcontainers import SortedList
sl = SortedList([(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")])

# Get the index of 53:

index = sl.bisect((53,))

# With the index, get the tuple:

tup = sl[index]

This will work a lot faster than the list comprehension suggestion by doing a binary search. The dictionary suggestion will be faster still but won't work if there could be duplicate numbers with different strings.

If there are duplicate numbers with different strings then you need to take one more step:

end = sl.bisect((53 + 1,))

results = sl[index:end]

By bisecting for 54, we will find the end index for our slice. This will be significantly faster on long lists as compared with the accepted answer.

HTML 5 Favicon - Support?

The answers provided (at the time of this post) are link only answers so I thought I would summarize the links into an answer and what I will be using.

When working to create Cross Browser Favicons (including touch icons) there are several things to consider.

The first (of course) is Internet Explorer. IE does not support PNG favicons until version 11. So our first line is a conditional comment for favicons in IE 9 and below:

<!--[if IE]><link rel="shortcut icon" href="path/to/favicon.ico"><![endif]-->

To cover the uses of the icon create it at 32x32 pixels. Notice the rel="shortcut icon" for IE to recognize the icon it needs the word shortcut which is not standard. Also we wrap the .ico favicon in a IE conditional comment because Chrome and Safari will use the .ico file if it is present, despite other options available, not what we would like.

The above covers IE up to IE 9. IE 11 accepts PNG favicons, however, IE 10 does not. Also IE 10 does not read conditional comments thus IE 10 won't show a favicon. With IE 11 and Edge available I don't see IE 10 in widespread use, so I ignore this browser.

For the rest of the browsers we are going to use the standard way to cite a favicon:

<link rel="icon" href="path/to/favicon.png">

This icon should be 196x196 pixels in size to cover all devices that may use this icon.

To cover touch icons on mobile devices we are going to use Apple's proprietary way to cite a touch icon:

<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">

Using rel="apple-touch-icon-precomposed" will not apply the reflective shine when bookmarked on iOS. To have iOS apply the shine use rel="apple-touch-icon". This icon should be sized to 180x180 pixels as that is the current size recommend by Apple for the latest iPhones and iPads. I have read Blackberry will also use rel="apple-touch-icon-precomposed".

As a note: Chrome for Android states:

The apple-touch-* are deprecated, and will be supported only for a short time. (Written as of beta for m31 of Chrome).

Custom Tiles for IE 11+ on Windows 8.1+

IE 11+ on Windows 8.1+ does offer a way to create pinned tiles for your site.

Microsoft recommends creating a few tiles at the following size:

Small: 128 x 128

Medium: 270 x 270

Wide: 558 x 270

Large: 558 x 558

These should be transparent images as we will define a color background next.

Once these images are created you should create an xml file called browserconfig.xml with the following code:

<?xml version="1.0" encoding="utf-8"?>
<browserconfig>
  <msapplication>
    <tile>
      <square70x70logo src="images/smalltile.png"/>
      <square150x150logo src="images/mediumtile.png"/>
      <wide310x150logo src="images/widetile.png"/>
      <square310x310logo src="images/largetile.png"/>
      <TileColor>#009900</TileColor>
    </tile>
  </msapplication>
</browserconfig>

Save this xml file in the root of your site. When a site is pinned IE will look for this file. If you want to name the xml file something different or have it in a different location add this meta tag to the head:

<meta name="msapplication-config" content="path-to-browserconfig/custom-name.xml" />

For additional information on IE 11+ custom tiles and using the XML file visit Microsoft's website.

Putting it all together:

To put it all together the above code would look like this:

<!-- For IE 9 and below. ICO should be 32x32 pixels in size -->
<!--[if IE]><link rel="shortcut icon" href="path/to/favicon.ico"><![endif]-->

<!-- Touch Icons - iOS and Android 2.1+ 180x180 pixels in size. --> 
<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">

<!-- Firefox, Chrome, Safari, IE 11+ and Opera. 196x196 pixels in size. -->
<link rel="icon" href="path/to/favicon.png">

Windows Phone Live Tiles

If a user is using a Windows Phone they can pin a website to the start screen of their phone. Unfortunately, when they do this it displays a screenshot of your phone, not a favicon (not even the MS specific code referenced above). To make a "Live Tile" for Windows Phone Users for your website one must use the following code:

Here are detailed instructions from Microsoft but here is a synopsis:

Step 1

Create a square image for your website, to support hi-res screens create it at 768x768 pixels in size.

Step 2

Add a hidden overlay of this image. Here is example code from Microsoft:

<div id="TileOverlay" onclick="ToggleTileOverlay()" style='background-color: Highlight; height: 100%; width: 100%; top: 0px; left: 0px; position: fixed; color: black; visibility: hidden'>
  <img src="customtile.png" width="320" height="320" />
  <div style='margin-top: 40px'>
     Add text/graphic asking user to pin to start using the menu...
  </div>
</div>

Step 3

You then can add thew following line to add a pin to start link:

<a href="javascript:ToggleTileOverlay()">Pin this site to your start screen</a>

Microsoft recommends that you detect windows phone and only show that link to those users since it won't work for other users.

Step 4

Next you add some JS to toggle the overlay visibility

<script>
function ToggleTileOverlay() {
 var newVisibility =     (document.getElementById('TileOverlay').style.visibility == 'visible') ? 'hidden' : 'visible';
 document.getElementById('TileOverlay').style.visibility =    newVisibility;
}
</script>

Note on Sizes

I am using one size as every browser will scale down the image as necessary. I could add more HTML to specify multiple sizes if desired for those with a lower bandwidth but I am already compressing the PNG files heavily using TinyPNG and I find this unnecessary for my purposes. Also, according to philippe_b's answer Chrome and Firefox have bugs that cause the browser to load all sizes of icons. Using one large icon may be better than multiple smaller ones because of this.

Further Reading

For those who would like more details see the links below:

How to remove a build from itunes connect?

Choose the build

The answer is that you Mouse over the icon for your build and at the end of the line you'll see a little colored minus in a circle. This removes the build and you can now click on the + sign and choose a new build for submitting.

It is an unbelievably complicated web page with tricks and gizmos to do the thing you want. I'm sure Steve never saw this page or tried to use it.

Surely it's better practice to design the screen so that you can see the options all the time, not to have the screen change depending on whether you have an app in review or not!

Why can't DateTime.Parse parse UTC date

or use the AdjustToUniversal DateTimeStyle in a call to

DateTime.ParseExact(String, String[], IFormatProvider, DateTimeStyles)

Convert PDF to image with high resolution

I have used pdf2image. A simple python library that works like charm.

First install poppler on non linux machine. You can just download the zip. Unzip in Program Files and add bin to Machine Path.

After that you can use pdf2image in python class like this:

from pdf2image import convert_from_path, convert_from_bytes
images_from_path = convert_from_path(
   inputfile,
   output_folder=outputpath,
   grayscale=True, fmt='jpeg')

I am not good with python but was able to make exe of it. Later you may use the exe with file input and output parameter. I have used it in C# and things are working fine.

Image quality is good. OCR works fine.

How to add to an NSDictionary

Update version

Objective-C

Create:

NSDictionary *dictionary = @{@"myKey1": @7, @"myKey2": @5}; 

Change:

NSMutableDictionary *mutableDictionary = [dictionary mutableCopy];     //Make the dictionary mutable to change/add
mutableDictionary[@"myKey3"] = @3;

The short-hand syntax is called Objective-C Literals.

Swift

Create:

var dictionary = ["myKey1": 7, "myKey2": 5]

Change:

dictionary["myKey3"] = 3

log4net vs. Nlog

Well .. I used Enterprise library for database logging tasks and now I switched to NLog due to performance bottleneck.

some comparison info :

http://pauliusraila.blogspot.com/2010/10/solving-database-logging-bottlenecks.html