Programs & Examples On #Layoutsubviews

layoutSubviews is a method that is called automatically during view size changes. It can be used by a custom view to perform additional manual changes above and beyond any autoresizing behaviours

When is layoutSubviews called?

A rather obscure, yet potentially important case when layoutSubviews never gets called is:

import UIKit

class View: UIView {

    override class var layerClass: AnyClass { return Layer.self }

    class Layer: CALayer {
        override func layoutSublayers() {
            // if we don't call super.layoutSublayers()...
            print(type(of: self), #function)
        }
    }

    override func layoutSubviews() {
        // ... this method never gets called by the OS!
        print(type(of: self), #function)
    }
}

let view = View(frame: CGRect(x: 0, y: 0, width: 100, height: 100))

What is the difference between tree depth and height?

height and depth of a tree is equal...

but height and depth of a node is not equal because...

the height is calculated by traversing from the given node to the deepest possible leaf.

depth is calculated from traversal from root to the given node.....

ResultSet exception - before start of result set

Basically you are positioning the cursor before the first row and then requesting data. You need to move the cursor to the first row.

 result.next();
 String foundType = result.getString(1);

It is common to do this in an if statement or loop.

if(result.next()){
   foundType = result.getString(1);
}

"ImportError: no module named 'requests'" after installing with pip

Run in command prompt.

pip list

Check what version you have installed on your system if you have an old version.

Try to uninstall the package...

pip uninstall requests

Try after to install it:

pip install requests

You can also test if pip does not do the job.

easy_install requests

Interface or an Abstract Class: which one to use?

Best practice is to use an interface to specify the contract and an abstract class as just one implementation thereof. That abstract class can fill in a lot of the boilerplate so you can create an implementation by just overriding what you need to or want to without forcing you to use a particular implementation.

CSS3 Transition not working

HTML:

<div class="foo">
    /* whatever is required */
</div>

CSS:

.foo {
    top: 0;
    transition: top ease 0.5s;
}

.foo:hover{
    top: -10px;
}

This is just a basic transition to ease the div tag up by 10px when it is hovered on. The transition property's values can be edited along with the class.hover properties to determine how the transition works.

How can I uninstall an application using PowerShell?

For Most of my programs the scripts in this Post did the job. But I had to face a legacy program that I couldn't remove using msiexec.exe or Win32_Product class. (from some reason I got exit 0 but the program was still there)

My solution was to use Win32_Process class:

with the help from nickdnk this command is to get the uninstall exe file path:

64bit:

[array]$unInstallPathReg= gci "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" | foreach { gp $_.PSPath } | ? { $_ -match $programName } | select UninstallString

32bit:

 [array]$unInstallPathReg= gci "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall" | foreach { gp $_.PSPath } | ? { $_ -match $programName } | select UninstallString

you will have to clean the the result string:

$uninstallPath = $unInstallPathReg[0].UninstallString
$uninstallPath = $uninstallPath -Replace "msiexec.exe","" -Replace "/I","" -Replace "/X",""
$uninstallPath = $uninstallPath .Trim()

now when you have the relevant program uninstall exe file path you can use this command:

$uninstallResult = (Get-WMIObject -List -Verbose | Where-Object {$_.Name -eq "Win32_Process"}).InvokeMethod("Create","$unInstallPath")

$uninstallResult - will have the exit code. 0 is success

the above commands can also run remotely - I did it using invoke command but I believe that adding the argument -computername can work

Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused

In my case the error was due to missing /data/db folder which the mongodb uses to store your data. Please type this command $sudo mongod in your terminal. If the error message is something like :

missing data/db folder error

Simply create the folder and you are good to go.

Having both a Created and Last Updated timestamp columns in MySQL 4.0

My web host is stuck on version 5.1 of mysql so anyone like me that doesn't have the option of upgrading can follow these directions:

http://joegornick.com/2009/12/30/mysql-created-and-modified-date-fields/

What happens to C# Dictionary<int, int> lookup if the key does not exist?

The Dictionary throws a KeyNotFound exception in the event that the dictionary does not contain your key.

As suggested, ContainsKey is the appropriate precaution. TryGetValue is also effective.

This allows the dictionary to store a value of null more effectively. Without it behaving this way, checking for a null result from the [] operator would indicate either a null value OR the non-existance of the input key which is no good.

How to detect scroll direction

I managed to figure it out in the end, so if anyone is looking for the answer:

 //Firefox
 $('#elem').bind('DOMMouseScroll', function(e){
     if(e.originalEvent.detail > 0) {
         //scroll down
         console.log('Down');
     }else {
         //scroll up
         console.log('Up');
     }

     //prevent page fom scrolling
     return false;
 });

 //IE, Opera, Safari
 $('#elem').bind('mousewheel', function(e){
     if(e.originalEvent.wheelDelta < 0) {
         //scroll down
         console.log('Down');
     }else {
         //scroll up
         console.log('Up');
     }

     //prevent page fom scrolling
     return false;
 });

How to remove non-alphanumeric characters?

If you need to support other languages, instead of the typical A-Z, you can use the following:

preg_replace('/[^\p{L}\p{N} ]+/', '', $string);
  • [^\p{L}\p{N} ] defines a negated (It will match a character that is not defined) character class of:
    • \p{L}: a letter from any language.
    • \p{N}: a numeric character in any script.
    • : a space character.
  • + greedily matches the character class between 1 and unlimited times.

This will preserve letters and numbers from other languages and scripts as well as A-Z:

preg_replace('/[^\p{L}\p{N} ]+/', '', 'hello-world'); // helloworld
preg_replace('/[^\p{L}\p{N} ]+/', '', 'abc@~#123-+=öäå'); // abc123öäå
preg_replace('/[^\p{L}\p{N} ]+/', '', '????!@£$%^&*()'); // ????

Note: This is a very old, but still relevant question. I am answering purely to provide supplementary information that may be useful to future visitors.

How to generate the whole database script in MySQL Workbench?

Q#1: I would guess that it's somewhere on your MySQL server? Q#2: Yes, this is possible. You have to establish a connection via Server Administration. There you can clone any table or the entire database.

This tutorial might be useful.

EDIT

Since the provided link is no longer active, here's a SO answer outlining the process of creating a DB backup in Workbench.

memcpy() vs memmove()

The difference between memcpy and memmove is that

  1. in memmove, the source memory of specified size is copied into buffer and then moved to destination. So if the memory is overlapping, there are no side effects.

  2. in case of memcpy(), there is no extra buffer taken for source memory. The copying is done directly on the memory so that when there is memory overlap, we get unexpected results.

These can be observed by the following code:

//include string.h, stdio.h, stdlib.h
int main(){
  char a[]="hare rama hare rama";

  char b[]="hare rama hare rama";

  memmove(a+5,a,20);
  puts(a);

  memcpy(b+5,b,20);
  puts(b);
}

Output is:

hare hare rama hare rama
hare hare hare hare hare hare rama hare rama

Copying text to the clipboard using Java

This works for me and is quite simple:

Import these:

import java.awt.datatransfer.StringSelection;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;

And then put this snippet of code wherever you'd like to alter the clipboard:

String myString = "This text will be copied into clipboard";
StringSelection stringSelection = new StringSelection(myString);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);

"Port 4200 is already in use" when running the ng serve command

In my case none of the above mentioned worked.

UBUNTU 18.04 VERSION

Below command worked.

sudo kill -9 $(lsof -i tcp:4200 -t)

Converting String to "Character" array in Java

Use this:

String str = "testString";
char[] charArray = str.toCharArray();
Character[] charObjectArray = ArrayUtils.toObject(charArray);

Dataframe to Excel sheet

Or you can do like this:

your_df.to_excel( r'C:\Users\full_path\excel_name.xlsx',
                  sheet_name= 'your_sheet_name'
                )

How to replace a hash key with another key

hash[:new_key] = hash.delete :old_key

Adding onClick event dynamically using jQuery

Try below approach,

$('#bfCaptchaEntry').on('click', myfunction);

or in case jQuery is not an absolute necessaity then try below,

document.getElementById('bfCaptchaEntry').onclick = myfunction;

However the above method has few drawbacks as it set onclick as a property rather than being registered as handler...

Read more on this post https://stackoverflow.com/a/6348597/297641

jQuery: go to URL with target="_blank"

Use,

var url = $(this).attr('href');
window.open(url, '_blank');

Update:the href is better off being retrieved with prop since it will return the full url and it's slightly faster.

var url = $(this).prop('href');

SQL Server 100% CPU Utilization - One database shows high CPU usage than others

According to this article on sqlserverstudymaterial;

Remember that "%Privileged time" is not based on 100%.It is based on number of processors.If you see 200 for sqlserver.exe and the system has 8 CPU then CPU consumed by sqlserver.exe is 200 out of 800 (only 25%).

If "% Privileged Time" value is more than 30% then it's generally caused by faulty drivers or anti-virus software. In such situations make sure the BIOS and filter drives are up to date and then try disabling the anti-virus software temporarily to see the change.

If "% User Time" is high then there is something consuming of SQL Server. There are several known patterns which can be caused high CPU for processes running in SQL Server including

What does the ELIFECYCLE Node.js error mean?

at process._tickCallback (internal/process/next_tick.js:10
4:9)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] sample: `node src/server/dat
a/seed-db.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] sample script.
npm ERR! This is probably not a problem with npm. There is lik
ely additional logging output above.

npm ERR! A complete log of this run can be found in:

I have the same issue here is how I got solved finally! the error: my error from the terminal when i run npm run sample after correcting my database connection username and password I was using mlab for my database and under the file .env i forget to properly put the user name and password. When I correct that I works.

> [email protected] sample /Users/mohammedr.kemal/Downl
oads/Ex_Files_ANGULAR_API_AUTH/Exercise Files/Ch01/01_04/start
> node src/server/data/seed-db.js

connected to mongodb...
connected to mongodb...
2 records inserted.
closing connection...
done.
12 records inserted.
closing connection...
done.

So it might be good to look any data connection we made in our code if we have.

How can I get form data with JavaScript/jQuery?

Here is a working JavaScript only implementation which correctly handles checkboxes, radio buttons, and sliders (probably other input types as well, but I've only tested these).

function setOrPush(target, val) {
    var result = val;
    if (target) {
        result = [target];
        result.push(val);
    }
    return result;
}

function getFormResults(formElement) {
    var formElements = formElement.elements;
    var formParams = {};
    var i = 0;
    var elem = null;
    for (i = 0; i < formElements.length; i += 1) {
        elem = formElements[i];
        switch (elem.type) {
            case 'submit':
                break;
            case 'radio':
                if (elem.checked) {
                    formParams[elem.name] = elem.value;
                }
                break;
            case 'checkbox':
                if (elem.checked) {
                    formParams[elem.name] = setOrPush(formParams[elem.name], elem.value);
                }
                break;
            default:
                formParams[elem.name] = setOrPush(formParams[elem.name], elem.value);
        }
    }
    return formParams;
}

Working example:

_x000D_
_x000D_
    function setOrPush(target, val) {_x000D_
      var result = val;_x000D_
      if (target) {_x000D_
        result = [target];_x000D_
        result.push(val);_x000D_
      }_x000D_
      return result;_x000D_
    }_x000D_
_x000D_
    function getFormResults(formElement) {_x000D_
      var formElements = formElement.elements;_x000D_
      var formParams = {};_x000D_
      var i = 0;_x000D_
      var elem = null;_x000D_
      for (i = 0; i < formElements.length; i += 1) {_x000D_
        elem = formElements[i];_x000D_
        switch (elem.type) {_x000D_
          case 'submit':_x000D_
            break;_x000D_
          case 'radio':_x000D_
            if (elem.checked) {_x000D_
              formParams[elem.name] = elem.value;_x000D_
            }_x000D_
            break;_x000D_
          case 'checkbox':_x000D_
            if (elem.checked) {_x000D_
              formParams[elem.name] = setOrPush(formParams[elem.name], elem.value);_x000D_
            }_x000D_
            break;_x000D_
          default:_x000D_
            formParams[elem.name] = setOrPush(formParams[elem.name], elem.value);_x000D_
        }_x000D_
      }_x000D_
      return formParams;_x000D_
    }_x000D_
_x000D_
    //_x000D_
    // Boilerplate for running the snippet/form_x000D_
    //_x000D_
_x000D_
    function ok() {_x000D_
      var params = getFormResults(document.getElementById('main_form'));_x000D_
      document.getElementById('results_wrapper').innerHTML = JSON.stringify(params, null, ' ');_x000D_
    }_x000D_
_x000D_
    (function() {_x000D_
      var main_form = document.getElementById('main_form');_x000D_
      main_form.addEventListener('submit', function(event) {_x000D_
        event.preventDefault();_x000D_
        ok();_x000D_
      }, false);_x000D_
    })();
_x000D_
<form id="main_form">_x000D_
  <div id="questions_wrapper">_x000D_
    <p>what is a?</p>_x000D_
    <div>_x000D_
      <input type="radio" required="" name="q_0" value="a" id="a_0">_x000D_
      <label for="a_0">a</label>_x000D_
      <input type="radio" required="" name="q_0" value="b" id="a_1">_x000D_
      <label for="a_1">b</label>_x000D_
      <input type="radio" required="" name="q_0" value="c" id="a_2">_x000D_
      <label for="a_2">c</label>_x000D_
      <input type="radio" required="" name="q_0" value="d" id="a_3">_x000D_
      <label for="a_3">d</label>_x000D_
    </div>_x000D_
    <div class="question range">_x000D_
      <label for="a_13">A?</label>_x000D_
      <input type="range" required="" name="q_3" id="a_13" min="0" max="10" step="1" list="q_3_dl">_x000D_
      <datalist id="q_3_dl">_x000D_
        <option value="0"></option>_x000D_
        <option value="1"></option>_x000D_
        <option value="2"></option>_x000D_
        <option value="3"></option>_x000D_
        <option value="4"></option>_x000D_
        <option value="5"></option>_x000D_
        <option value="6"></option>_x000D_
        <option value="7"></option>_x000D_
        <option value="8"></option>_x000D_
        <option value="9"></option>_x000D_
        <option value="10"></option>_x000D_
      </datalist>_x000D_
    </div>_x000D_
    <p>A and/or B?</p>_x000D_
    <div>_x000D_
      <input type="checkbox" name="q_4" value="A" id="a_14">_x000D_
      <label for="a_14">A</label>_x000D_
      <input type="checkbox" name="q_4" value="B" id="a_15">_x000D_
      <label for="a_15">B</label>_x000D_
    </div>_x000D_
  </div>_x000D_
  <button id="btn" type="submit">OK</button>_x000D_
</form>_x000D_
<div id="results_wrapper"></div>
_x000D_
_x000D_
_x000D_

edit:

If you're looking for a more complete implementation, then take a look at this section of the project I made this for. I'll update this question eventually with the complete solution I came up with, but maybe this will be helpful to someone.

printing a value of a variable in postgresql

You can raise a notice in Postgres as follows:

raise notice 'Value: %', deletedContactId;

Read here

How do I use Bash on Windows from the Visual Studio Code integrated terminal?

For scoop users:

"terminal.integrated.shell.windows": "C:\\Users\\[YOUR-NAME]\\scoop\\apps\\git\\current\\usr\\bin\\bash.exe",
"terminal.integrated.shellArgs.windows": [
  "-l",
  "-i"
],

Deleting a pointer in C++

There is a rule in C++, for every new there is a delete.

  1. Why won't the first case work? Seems the most straightforward use to use and delete a pointer? The error says the memory wasn't allocated but 'cout' returned an address.

new is never called. So the address that cout prints is the address of the memory location of myVar, or the value assigned to myPointer in this case. By writing:

myPointer = &myVar;

you say:

myPointer = The address of where the data in myVar is stored

  1. On the second example the error is not being triggered but doing a cout of the value of myPointer still returns a memory address?

It returns an address that points to a memory location that has been deleted. Because first you create the pointer and assign its value to myPointer, second you delete it, third you print it. So unless you assign another value to myPointer, the deleted address will remain.

  1. Does #3 really work? Seems to work to me, the pointer is no longer storing an address, is this the proper way to delete a pointer?

NULL equals 0, you delete 0, so you delete nothing. And it's logic that it prints 0 because you did:

myPointer = NULL;

which equals:

myPointer = 0;

Parse strings to double with comma and point

Make two static cultures, one for comma and one for point.

    var commaCulture = new CultureInfo("en")
    {
        NumberFormat =
        {
            NumberDecimalSeparator = ","
        }
    };

    var pointCulture = new CultureInfo("en")
    {
        NumberFormat =
        {
            NumberDecimalSeparator = "."
        }
    };

Then use each one respectively, depending on the input (using a function):

    public double ConvertToDouble(string input)
    {
        input = input.Trim();

        if (input == "0") {
            return 0;
        }

        if (input.Contains(",") && input.Split(',').Length == 2)
        {
            return Convert.ToDouble(input, commaCulture);
        }

        if (input.Contains(".") && input.Split('.').Length == 2)
        {
            return Convert.ToDouble(input, pointCulture);
        }

        throw new Exception("Invalid input!");
    }

Then loop through your arrays

    var strings = new List<string> {"0,12", "0.122", "1,23", "00,0", "0.00", "12.5000", "0.002", "0,001"};
    var doubles = new List<double>();

    foreach (var value in strings) {
        doubles.Add(ConvertToDouble(value));
    }

This should work even though the host environment and culture changes.

C++ Convert string (or char*) to wstring (or wchar_t*)

This variant of it is my favourite in real life. It converts the input, if it is valid UTF-8, to the respective wstring. If the input is corrupted, the wstring is constructed out of the single bytes. This is extremely helpful if you cannot really be sure about the quality of your input data.

std::wstring convert(const std::string& input)
{
    try
    {
        std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
        return converter.from_bytes(input);
    }
    catch(std::range_error& e)
    {
        size_t length = input.length();
        std::wstring result;
        result.reserve(length);
        for(size_t i = 0; i < length; i++)
        {
            result.push_back(input[i] & 0xFF);
        }
        return result;
    }
}

How to define Gradle's home in IDEA?

This is instruction for MAC only. I had the same problem. I solved it by configuring $GRADLE_HOME in .bash_profile. Here's how you do it:

  • Open .bash_profile (usually it's located in the user’s home directory).
  • Add the following lines to update $PATH variable: export GRADLE_HOME=/usr/local/opt/gradle/libexec export PATH=$GRADLE_HOME/bin:$PATH
  • Save it.
  • Apply your changes by running source .bash_profile

I wrote my own article with instruction in a case if somebody will encounter the same problem.

How do I explicitly specify a Model's table-name mapping in Rails?

class Countries < ActiveRecord::Base
    self.table_name = "cc"
end

In Rails 3.x this is the way to specify the table name.

Amazon Interview Question: Design an OO parking lot

public class ParkingLot 
{
    Vector<ParkingSpace> vacantParkingSpaces = null;
    Vector<ParkingSpace> fullParkingSpaces = null;

    int parkingSpaceCount = 0;

    boolean isFull;
    boolean isEmpty;

    ParkingSpace findNearestVacant(ParkingType type)
    {
        Iterator<ParkingSpace> itr = vacantParkingSpaces.iterator();

        while(itr.hasNext())
        {
            ParkingSpace parkingSpace = itr.next();

            if(parkingSpace.parkingType == type)
            {
                return parkingSpace;
            }
        }
        return null;
    }

    void parkVehicle(ParkingType type, Vehicle vehicle)
    {
        if(!isFull())
        {
            ParkingSpace parkingSpace = findNearestVacant(type);

            if(parkingSpace != null)
            {
                parkingSpace.vehicle = vehicle;
                parkingSpace.isVacant = false;

                vacantParkingSpaces.remove(parkingSpace);
                fullParkingSpaces.add(parkingSpace);

                if(fullParkingSpaces.size() == parkingSpaceCount)
                    isFull = true;

                isEmpty = false;
            }
        }
    }

    void releaseVehicle(Vehicle vehicle)
    {
        if(!isEmpty())
        {
            Iterator<ParkingSpace> itr = fullParkingSpaces.iterator();

            while(itr.hasNext())
            {
                ParkingSpace parkingSpace = itr.next();

                if(parkingSpace.vehicle.equals(vehicle))
                {
                    fullParkingSpaces.remove(parkingSpace);
                    vacantParkingSpaces.add(parkingSpace);

                    parkingSpace.isVacant = true;
                    parkingSpace.vehicle = null;

                    if(vacantParkingSpaces.size() == parkingSpaceCount)
                        isEmpty = true;

                    isFull = false;
                }
            }
        }
    }

    boolean isFull()
    {
        return isFull;
    }

    boolean isEmpty()
    {
        return isEmpty;
    }
}

public class ParkingSpace 
{
    boolean isVacant;
    Vehicle vehicle;
    ParkingType parkingType;
    int distance;
}

public class Vehicle 
{
    int num;
}

public enum ParkingType
{
    REGULAR,
    HANDICAPPED,
    COMPACT,
    MAX_PARKING_TYPE,
}

Switch php versions on commandline ubuntu 16.04

Type given command in your terminal..

For disable the selected PHP version...

    • sudo a2dismod php5
    • sudo service apache2 restart
  1. For enable other PHP version....

    • sudo a2enmod php5.6
    • sudo service apache2 restart

It will upgrade Php version, same thing reverse if you want version downgrade, you can see it by PHP_INFO();

Get User Selected Range

This depends on what you mean by "get the range of selection". If you mean getting the range address (like "A1:B1") then use the Address property of Selection object - as Michael stated Selection object is much like a Range object, so most properties and methods works on it.

Sub test()
    Dim myString As String
    myString = Selection.Address
End Sub

Scroll to bottom of div?

You can try the code below:

function scrollToBottom (id) {
   var div = document.getElementById(id);
   div.scrollTop = div.scrollHeight - div.clientHeight;
}

To perform a smooth scroll with JQuery:

function scrollSmoothToBottom (id) {
   var div = document.getElementById(id);
   $('#' + id).animate({
      scrollTop: div.scrollHeight - div.clientHeight
   }, 500);
}

See the example on JSFiddle

Here's why this works:

enter image description here

Ref: scrollTop, scrollHeight, clientHeight

Textarea to resize based on content length

You may also try contenteditable attribute onto a normal p or div. Not really a textarea but it will auto-resize without script.

_x000D_
_x000D_
.divtext {
    border: ridge 2px;
    padding: 5px;
    width: 20em;
    min-height: 5em;
    overflow: auto;
}
_x000D_
<div class="divtext" contentEditable>Hello World</div>
_x000D_
_x000D_
_x000D_

Difference between Ctrl+Shift+F and Ctrl+I in Eclipse

Reformat affects the whole source code and may rebreak your lines, while Correct Indentation only affects the whitespace at the beginning of the lines.

Echo a blank (empty) line to the console from a Windows batch file

There is often the tip to use 'echo.'

But that is slow, and it could fail with an error message, as cmd.exe will search first for a file named 'echo' (without extension) and only when the file doesn't exists it outputs an empty line.

You could use echo(. This is approximately 20 times faster, and it works always. The only drawback could be that it looks odd.

More about the different ECHO:/\ variants is at DOS tips: ECHO. FAILS to give text or blank line.

AngularJS $watch window resize inside directive

// Following is angular 2.0 directive for window re size that adjust scroll bar for give element as per your tag

---- angular 2.0 window resize directive.
import { Directive, ElementRef} from 'angular2/core';

@Directive({
       selector: '[resize]',
       host: { '(window:resize)': 'onResize()' } // Window resize listener
})

export class AutoResize {

element: ElementRef; // Element that associated to attribute.
$window: any;
       constructor(_element: ElementRef) {

         this.element = _element;
         // Get instance of DOM window.
         this.$window = angular.element(window);

         this.onResize();

    }

    // Adjust height of element.
    onResize() {
         $(this.element.nativeElement).css('height', (this.$window.height() - 163) + 'px');
   }
}

Javascript / Chrome - How to copy an object from the webkit inspector as code

Add this to your console and execute

copy(JSON.stringify(foo));

This copies your JSON to clipboard

Writing file to web server - ASP.NET

protected void TestSubmit_ServerClick(object sender, EventArgs e)
{
  using (StreamWriter _testData = new StreamWriter(Server.MapPath("~/data.txt"), true))
 {
  _testData.WriteLine(TextBox1.Text); // Write the file.
 }         
}

Server.MapPath takes a virtual path and returns an absolute one. "~" is used to resolve to the application root.

Getting reference to child component in parent component

You may actually go with ViewChild API...

parent.ts

<button (click)="clicked()">click</button>

export class App {
  @ViewChild(Child) vc:Child;
  constructor() {
    this.name = 'Angular2'
  }

  func(e) {
    console.log(e)

  }
  clicked(){
   this.vc.getName();
  }
}

child.ts

export class Child implements OnInit{

  onInitialized = new EventEmitter<Child>();
  ...  
  ...
  getName()
  {
     console.log('called by vc')
     console.log(this.name);
  }
}

How to upsert (update or insert) in SQL Server 2005

Here is a useful article by Michael J. Swart on the matter, which covers different patterns and antipatterns for implementing UPSERT in SQL Server:
https://michaeljswart.com/2017/07/sql-server-upsert-patterns-and-antipatterns/

It addresses associated concurrency issues (primary key violations, deadlocks) - all of the answers provided here yet are considered antipatterns in the article (except for the @Bridge solution using triggers, which is not covered there).

Here is an extract from the article with the solution preferred by the author:

Inside a serializable transaction with lock hints:

CREATE PROCEDURE s_AccountDetails_Upsert ( @Email nvarchar(4000), @Etc nvarchar(max) )
AS 
  SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
  BEGIN TRAN

    IF EXISTS ( SELECT * FROM dbo.AccountDetails WITH (UPDLOCK) WHERE Email = @Email )

      UPDATE dbo.AccountDetails
         SET Etc = @Etc
       WHERE Email = @Email;

    ELSE 

      INSERT dbo.AccountDetails ( Email, Etc )
      VALUES ( @Email, @Etc );

  COMMIT

There is also related question with answers here on stackoverflow: Insert Update stored proc on SQL Server

MySQL SELECT DISTINCT multiple columns

This will give DISTINCT values across all the columns:

SELECT DISTINCT value
FROM (
    SELECT DISTINCT a AS value FROM my_table
    UNION SELECT DISTINCT b AS value FROM my_table
    UNION SELECT DISTINCT c AS value FROM my_table
) AS derived

The simplest possible JavaScript countdown timer?

If you want a real timer you need to use the date object.

Calculate the difference.

Format your string.

window.onload=function(){
      var start=Date.now(),r=document.getElementById('r');
      (function f(){
      var diff=Date.now()-start,ns=(((3e5-diff)/1e3)>>0),m=(ns/60)>>0,s=ns-m*60;
      r.textContent="Registration closes in "+m+':'+((''+s).length>1?'':'0')+s;
      if(diff>3e5){
         start=Date.now()
      }
      setTimeout(f,1e3);
      })();
}

Example

Jsfiddle

not so precise timer

var time=5*60,r=document.getElementById('r'),tmp=time;

setInterval(function(){
    var c=tmp--,m=(c/60)>>0,s=(c-m*60)+'';
    r.textContent='Registration closes in '+m+':'+(s.length>1?'':'0')+s
    tmp!=0||(tmp=time);
},1000);

JsFiddle

Pointer vs. Reference

Consider C#'s out keyword. The compiler requires the caller of a method to apply the out keyword to any out args, even though it knows already if they are. This is intended to enhance readability. Although with modern IDEs I'm inclined to think that this is a job for syntax (or semantic) highlighting.

How to set max_connections in MySQL Programmatically

You can set max connections using:

set global max_connections = '1 < your number > 100000';

This will set your number of mysql connection unti (Requires SUPER privileges).

HTML meta tag for content language

Html5 also recommend to use <html lang="es-ES"> The small letter lang tag only specifies: language code The large letter specifies: country code

This is really useful for ie.Chrome, when the browser is proposing to translate web content(ie google translate)

How to replace all occurrences of a character in string?

I thought I'd toss in the boost solution as well:

#include <boost/algorithm/string/replace.hpp>

// in place
std::string in_place = "blah#blah";
boost::replace_all(in_place, "#", "@");

// copy
const std::string input = "blah#blah";
std::string output = boost::replace_all_copy(input, "#", "@");

Going to a specific line number using Less in Unix

To open at a specific line straight from the command line, use:

less +320123 filename

If you want to see the line numbers too:

less +320123 -N filename

You can also choose to display a specific line of the file at a specific line of the terminal, for when you need a few lines of context. For example, this will open the file with line 320123 on the 10th line of the terminal:

less +320123 -j 10 filename

CSS Div stretch 100% page height

_x000D_
_x000D_
 _x000D_
           document.body.onload = function () {_x000D_
                var textcontrol = document.getElementById("page");_x000D_
                textcontrol.style.height = (window.innerHeight) + 'px';_x000D_
            }
_x000D_
<html>_x000D_
<head><title></title></head>_x000D_
<body>_x000D_
_x000D_
<div id="page" style="background:green;">_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Abstraction VS Information Hiding VS Encapsulation

Go to the source! Grady Booch says (in Object Oriented Analysis and Design, page 49, second edition):

Abstraction and encapsulation are complementary concepts: abstraction focuses on the observable behavior of an object... encapsulation focuses upon the implementation that gives rise to this behavior... encapsulation is most often achieved through information hiding, which is the process of hiding all of the secrets of object that do not contribute to its essential characteristics.

In other words: abstraction = the object externally; encapsulation (achieved through information hiding) = the object internally,

Example: In the .NET Framework, the System.Text.StringBuilder class provides an abstraction over a string buffer. This buffer abstraction lets you work with the buffer without regard for its implementation. Thus, you're able to append strings to the buffer without regard for how the StringBuilder internally keeps track of things such the pointer to the buffer and managing memory when the buffer gets full (which it does with encapsulation via information hiding).

rp

Set default format of datetimepicker as dd-MM-yyyy

Try this,

string Date = datePicker1.SelectedDate.Value.ToString("dd-MMM-yyyy");

It worked for me the output format will be '02-May-2016'

How do I prevent the padding property from changing width or height in CSS?

just change your div width to 160px if you have a padding of 20px it adds 40px extra to the width of your div so you need to subtract 40px from the width in order to keep your div looking normal and not distorted with extra width on it and your text all messed up.

When to use std::size_t?

When using size_t be careful with the following expression

size_t i = containner.find("mytoken");
size_t x = 99;
if (i-x>-1 && i+x < containner.size()) {
    cout << containner[i-x] << " " << containner[i+x] << endl;
}

You will get false in the if expression regardless of what value you have for x. It took me several days to realize this (the code is so simple that I did not do unit test), although it only take a few minutes to figure the source of the problem. Not sure it is better to do a cast or use zero.

if ((int)(i-x) > -1 or (i-x) >= 0)

Both ways should work. Here is my test run

size_t i = 5;
cerr << "i-7=" << i-7 << " (int)(i-7)=" << (int)(i-7) << endl;

The output: i-7=18446744073709551614 (int)(i-7)=-2

I would like other's comments.

bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml. Do you need to install a parser library?

I encountered the same issue. I found the reason is that I had a slightly-outdated python six package.

>>> import html5lib
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/site-packages/html5lib/__init__.py", line 16, in <module>
    from .html5parser import HTMLParser, parse, parseFragment
  File "/usr/local/lib/python2.7/site-packages/html5lib/html5parser.py", line 2, in <module>
    from six import with_metaclass, viewkeys, PY3
ImportError: cannot import name viewkeys

Upgrading your six package will solve the issue:

sudo pip install six=1.10.0

PyCharm shows unresolved references error for valid code

If you want to ignore only some "unresolved reference" errors, you can also tell it PyCharm explicitly by placing this in front of your class/method/function:

# noinspection PyUnresolvedReferences

How can I dynamically switch web service addresses in .NET without a recompile?

When you generate a web reference and click on the web reference in the Solution Explorer. In the properties pane you should see something like this:

Web Reference Properties

Changing the value to dynamic will put an entry in your app.config.

Here is the CodePlex article that has more information.

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

The following adds elements to a list in a loop.

l<-c()
i=1

while(i<100) {

    b<-i
    l<-c(l,b)
    i=i+1
}

How do I insert values into a Map<K, V>?

The two errors you have in your code are very different.

The first problem is that you're initializing and populating your Map in the body of the class without a statement. You can either have a static Map and a static {//TODO manipulate Map} statement in the body of the class, or initialize and populate the Map in a method or in the class' constructor.

The second problem is that you cannot treat a Map syntactically like an array, so the statement data["John"] = "Taxi Driver"; should be replaced by data.put("John", "Taxi Driver"). If you already have a "John" key in your HashMap, its value will be replaced with "Taxi Driver".

Call function with setInterval in jQuery?

First of all: Yes you can mix jQuery with common JS :)

Best way to build up an intervall call of a function is to use setTimeout methode:

For example, if you have a function called test() and want to repeat it all 5 seconds, you could build it up like this:

function test(){
    console.log('test called');
    setTimeout(test, 5000);
}

Finally you have to trigger the function once:

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

This document ready function is called automatically, after all html is loaded.

Handle Button click inside a row in RecyclerView

Just wanted to add another solution if you already have a recycler touch listener and want to handle all of the touch events in it rather than dealing with the button touch event separately in the view holder. The key thing this adapted version of the class does is return the button view in the onItemClick() callback when it's tapped, as opposed to the item container. You can then test for the view being a button, and carry out a different action. Note, long tapping on the button is interpreted as a long tap on the whole row still.

public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener
{
    public static interface OnItemClickListener
    {
        public void onItemClick(View view, int position);
        public void onItemLongClick(View view, int position);
    }

    private OnItemClickListener mListener;
    private GestureDetector mGestureDetector;

    public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener)
    {
        mListener = listener;

        mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener()
        {
            @Override
            public boolean onSingleTapUp(MotionEvent e)
            {
                // Important: x and y are translated coordinates here
                final ViewGroup childViewGroup = (ViewGroup) recyclerView.findChildViewUnder(e.getX(), e.getY());

                if (childViewGroup != null && mListener != null) {
                    final List<View> viewHierarchy = new ArrayList<View>();
                    // Important: x and y are raw screen coordinates here
                    getViewHierarchyUnderChild(childViewGroup, e.getRawX(), e.getRawY(), viewHierarchy);

                    View touchedView = childViewGroup;
                    if (viewHierarchy.size() > 0) {
                        touchedView = viewHierarchy.get(0);
                    }
                    mListener.onItemClick(touchedView, recyclerView.getChildPosition(childViewGroup));
                    return true;
                }

                return false;
            }

            @Override
            public void onLongPress(MotionEvent e)
            {
                View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());

                if(childView != null && mListener != null)
                {
                    mListener.onItemLongClick(childView, recyclerView.getChildPosition(childView));
                }
            }
        });
    }

    public void getViewHierarchyUnderChild(ViewGroup root, float x, float y, List<View> viewHierarchy) {
        int[] location = new int[2];
        final int childCount = root.getChildCount();

        for (int i = 0; i < childCount; ++i) {
            final View child = root.getChildAt(i);
            child.getLocationOnScreen(location);
            final int childLeft = location[0], childRight = childLeft + child.getWidth();
            final int childTop = location[1], childBottom = childTop + child.getHeight();

            if (child.isShown() && x >= childLeft && x <= childRight && y >= childTop && y <= childBottom) {
                viewHierarchy.add(0, child);
            }
            if (child instanceof ViewGroup) {
                getViewHierarchyUnderChild((ViewGroup) child, x, y, viewHierarchy);
            }
        }
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e)
    {
        mGestureDetector.onTouchEvent(e);

        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView view, MotionEvent motionEvent){}

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }
}

Then using it from activity / fragment:

recyclerView.addOnItemTouchListener(createItemClickListener(recyclerView));

    public RecyclerItemClickListener createItemClickListener(final RecyclerView recyclerView) {
        return new RecyclerItemClickListener (context, recyclerView, new RecyclerItemClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (view instanceof AppCompatButton) {
                    // ... tapped on the button, so go do something
                } else {
                    // ... tapped on the item container (row), so do something different
                }
            }

            @Override
            public void onItemLongClick(View view, int position) {
            }
        });
    }

the getSource() and getActionCommand()

Assuming you are talking about the ActionEvent class, then there is a big difference between the two methods.

getActionCommand() gives you a String representing the action command. The value is component specific; for a JButton you have the option to set the value with setActionCommand(String command) but for a JTextField if you don't set this, it will automatically give you the value of the text field. According to the javadoc this is for compatability with java.awt.TextField.

getSource() is specified by the EventObject class that ActionEvent is a child of (via java.awt.AWTEvent). This gives you a reference to the object that the event came from.

Edit:

Here is a example. There are two fields, one has an action command explicitly set, the other doesn't. Type some text into each then press enter.

public class Events implements ActionListener {

  private static JFrame frame; 

  public static void main(String[] args) {

    frame = new JFrame("JTextField events");
    frame.getContentPane().setLayout(new FlowLayout());

    JTextField field1 = new JTextField(10);
    field1.addActionListener(new Events());
    frame.getContentPane().add(new JLabel("Field with no action command set"));
    frame.getContentPane().add(field1);

    JTextField field2 = new JTextField(10);
    field2.addActionListener(new Events());
    field2.setActionCommand("my action command");
    frame.getContentPane().add(new JLabel("Field with an action command set"));
    frame.getContentPane().add(field2);


    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(220, 150);
    frame.setResizable(false);
    frame.setVisible(true);
  }

  @Override
  public void actionPerformed(ActionEvent evt) {
    String cmd = evt.getActionCommand();
    JOptionPane.showMessageDialog(frame, "Command: " + cmd);
  }

}

Detecting Browser Autofill

Just in case someone is looking for a solution (just as I was today), to listen to a browser autofill change, here's a custom jquery method that I've built, just to simplify the proccess when adding a change listener to an input:

    $.fn.allchange = function (callback) {
        var me = this;
        var last = "";
        var infunc = function () {
            var text = $(me).val();
            if (text != last) {
                last = text;
                callback();
            }
            setTimeout(infunc, 100);
        }
        setTimeout(infunc, 100);
    };

You can call it like this:

$("#myInput").allchange(function () {
    alert("change!");
});

How to trim a string in SQL Server before 2017?

SELECT LTRIM(RTRIM(Replace(Replace(Replace(name,'   ',' '),CHAR(13), ' '),char(10), ' ')))
from author

Replace all particular values in a data frame

We can use data.table to get it quickly. First create df without factors,

df <- data.frame(list(A=c("","xyz","jkl"), B=c(12,"",100)), stringsAsFactors=F)

Now you can use

setDT(df)
for (jj in 1:ncol(df)) set(df, i = which(df[[jj]]==""), j = jj, v = NA)

and you can convert it back to a data.frame

setDF(df)

If you only want to use data.frame and keep factors it's more difficult, you need to work with

levels(df$value)[levels(df$value)==""] <- NA

where value is the name of every column. You need to insert it in a loop.

IIS Config Error - This configuration section cannot be used at this path

Click on your project properties, go to the web section, from the Servers section, change from IIS express to Local IIS, it will create a virtual directory for you

JavaScript Extending Class

I can propose one variant, just have read in book, it seems the simplest:

function Parent() { 
  this.name = 'default name';
};

function Child() {
  this.address = '11 street';
};

Child.prototype = new Parent();      // child class inherits from Parent
Child.prototype.constructor = Child; // constructor alignment

var a = new Child(); 

console.log(a.name);                // "default name" trying to reach property of inherited class

How do I SET the GOPATH environment variable on Ubuntu? What file must I edit?

GOPATH should be set to a newly created empty directory. This is the go "workspace", where it downloads packages, et cetera. I use ~/.go.

For example:

mkdir ~/.go
echo "GOPATH=$HOME/.go" >> ~/.bashrc
echo "export GOPATH" >> ~/.bashrc
echo "PATH=\$PATH:\$GOPATH/bin # Add GOPATH/bin to PATH for scripting" >> ~/.bashrc
source ~/.bashrc

source: http://www.larry-price.com/blog/2013/12/15/setting-up-a-go-environment-in-ubuntu-12-dot-04/

Compile a DLL in C/C++, then call it from another program

The thing to watch out for when writing C++ dlls is name mangling. If you want interoperability between C and C++, you'd be better off by exporting non-mangled C-style functions from within the dll.

You have two options to use a dll

  • Either use a lib file to link the symbols -- compile time dynamic linking
  • Use LoadLibrary() or some suitable function to load the library, retrieve a function pointer (GetProcAddress) and call it -- runtime dynamic linking

Exporting classes will not work if you follow the second method though.

Bash or KornShell (ksh)?

I'm a korn-shell veteran, so know that I speak from that perspective.

However, I have been comfortable with Bourne shell, ksh88, and ksh93, and for the most I know which features are supported in which. (I should skip ksh88 here, as it's not widely distributed anymore.)

For interactive use, take whatever fits your need. Experiment. I like being able to use the same shell for interactive use and for programming.

I went from ksh88 on SVR2 to tcsh, to ksh88sun (which added significant internationalisation support) and ksh93. I tried bash, and hated it because it flattened my history. Then I discovered shopt -s lithist and all was well. (The lithist option assures that newlines are preserved in your command history.)

For shell programming, I'd seriously recommend ksh93 if you want a consistent programming language, good POSIX conformance, and good performance, as many common unix commands can be available as builtin functions.

If you want portability use at least both. And make sure you have a good test suite.

There are many subtle differences between shells. Consider for example reading from a pipe:

b=42 && echo one two three four |
    read a b junk && echo $b

This will produce different results in different shells. The korn-shell runs pipelines from back to front; the last element in the pipeline runs in the current process. Bash did not support this useful behaviour until v4.x, and even then, it's not the default.

Another example illustrating consistency: The echo command itself, which was made obsolete by the split between BSD and SYSV unix, and each introduced their own convention for not printing newlines (and other behaviour). The result of this can still be seen in many 'configure' scripts.

Ksh took a radical approach to that - and introduced the print command, which actually supports both methods (the -n option from BSD, and the trailing \c special character from SYSV)

However, for serious systems programming I'd recommend something other than a shell, like python, perl. Or take it a step further, and use a platform like puppet - which allows you to watch and correct the state of whole clusters of systems, with good auditing.

Shell programming is like swimming in uncharted waters, or worse.

Programming in any language requires familiarity with its syntax, its interfaces and behaviour. Shell programming isn't any different.

Generic XSLT Search and Replace template

Here's one way in XSLT 2

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;','''')"/>   </xsl:template> </xsl:stylesheet> 

Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:variable name="apos">'</xsl:variable>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;',$apos)"/>   </xsl:template> </xsl:stylesheet> 

Force browser to download image files on click

I managed to get this working in Chrome and Firefox too by appending a link to the to document.

var link = document.createElement('a');
link.href = 'images.jpg';
link.download = 'Download.jpg';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);

Binding multiple events to a listener (without JQuery)?

One way how to do it:

_x000D_
_x000D_
const troll = document.getElementById('troll');_x000D_
_x000D_
['mousedown', 'mouseup'].forEach(type => {_x000D_
 if (type === 'mousedown') {_x000D_
  troll.addEventListener(type, () => console.log('Mouse is down'));_x000D_
 }_x000D_
        else if (type === 'mouseup') {_x000D_
                troll.addEventListener(type, () => console.log('Mouse is up'));_x000D_
        }_x000D_
});
_x000D_
img {_x000D_
  width: 100px;_x000D_
  cursor: pointer;_x000D_
}
_x000D_
<div id="troll">_x000D_
  <img src="http://images.mmorpg.com/features/7909/images/Troll.png" alt="Troll">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Ruby: How to iterate over a range, but in set increments?

You can use Numeric#step.

0.step(30,5) do |num|
  puts "number is #{num}"
end
# >> number is 0
# >> number is 5
# >> number is 10
# >> number is 15
# >> number is 20
# >> number is 25
# >> number is 30

How do I programmatically get the GUID of an application in .NET 2.0

There wasn't any luck here with the other answers, but I managed to work it out with this nice one-liner:

((GuidAttribute)(AppDomain.CurrentDomain.DomainManager.EntryAssembly).GetCustomAttributes(typeof(GuidAttribute), true)[0]).Value

How can I debug my JavaScript code?

Visual Studio 2008 has some very good JavaScript debugging tools. You can drop a breakpoint in your client side JavaScript code and step through it using the exact same tools as you would the server side code. There is no need to attach to a process or do anything tricky to enable it.

Javascript - removing undefined fields from an object

Another Javascript Solution

for(var i=0,keys = Object.keys(obj),len=keys.length;i<len;i++){ 
  if(typeof obj[keys[i]] === 'undefined'){
    delete obj[keys[i]];
  }
}

No additional hasOwnProperty check is required as Object.keys does not look up the prototype chain and returns only the properties of obj.

DEMO

How do I make a JAR from a .java file?

Ok this is the solution I would have liked to find, instead here I write it:

First create the directory structure corresponding to the package defined for the .java file, if it is my.super.application create the directory "my" and inside it "super" and inside it the .java file "App.java"

then from command line:

   javac -cp /path/to/lib1.jar:/path/to/lib2.jar path/to/my/super/App.java

Notice the above will include multiple libraries, if under windows use "," to separate multiple files otherwise under GNU/Linux use ":" To create a jar file

   jar -cvfe App.jar App my/app/

the above will create the application with its corresponding Manifest indicating the App as the main class.

Including the required libraries inside the jar file is not possible using java or jar command line parameters.

You can instead:

  1. manually extract libraries to the root folder of the jar file
  2. use an IDE such as Netbeans and insert a rule inside post-jar section of nbproject/build-impl.xml to extract the libraries inside the jar. See below.
<target name="-post-jar">
        <!-- Empty placeholder for easier customization. -->
        <!-- You can override this target in the ../build.xml file. -->
  <jar jarfile="${dist.jar}" update="true">  
            <zipfileset src="${dist.jar}" includes="**/*.class" />  
            <zipfileset src="${file.reference.iText-1.0.8.jar}" includes="**/*"/>
      <zipfileset src="${file.reference.itextpdf-3.2.1.jar}" includes="**/*"/>
  </jar>
    </target>

the file.reference names are found inside project.properties file after you added the libraries to the Netbeans IDE.

NGINX to reverse proxy websockets AND enable SSL (wss://)?

for .net core 2.0 Nginx with SSL

location / {
    # redirect all HTTP traffic to localhost:8080
    proxy_pass http://localhost:8080;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    # WebSocket support
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $http_connection;
}

This worked for me

How to convert Blob to String and String to Blob in java

try this (a2 is BLOB col)

PreparedStatement ps1 = conn.prepareStatement("update t1 set a2=? where id=1");
Blob blob = conn.createBlob();
blob.setBytes(1, str.getBytes());
ps1.setBlob(1, blob);
ps1.executeUpdate();

it may work even without BLOB, driver will transform types automatically:

   ps1.setBytes(1, str.getBytes);
   ps1.setString(1, str);

Besides if you work with text CLOB seems to be a more natural col type

HTML/JavaScript: Simple form validation on submit

I use this really simple small JavaScript library to validate a complete form in one single line of code:

 jsFormValidator.App.create().Validator.applyRules('Login');

Check here: jsFormValidator

The benefit of this tool is that you just write a JSON object which describe your validation rules. There isn't any need to put in a line like:

 <input type=text name="username" data-validate placeholder="Username">

data-validate is injected in all the input fields of your form, but when using jsFormValidator, you don't require this heavy syntax and the validation will be applied to your form in one shot, without the need to touch your HTML code.

Bash if statement with multiple conditions throws an error

Use -a (for and) and -o (for or) operations.

tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html

Update

Actually you could still use && and || with the -eq operation. So your script would be like this:

my_error_flag=1
my_error_flag_o=1
if [ $my_error_flag -eq 1 ] ||  [ $my_error_flag_o -eq 2 ] || ([ $my_error_flag -eq 1 ] && [ $my_error_flag_o -eq 2 ]); then
      echo "$my_error_flag"
else
    echo "no flag"
fi

Although in your case you can discard the last two expressions and just stick with one or operation like this:

my_error_flag=1
my_error_flag_o=1
if [ $my_error_flag -eq 1 ] ||  [ $my_error_flag_o -eq 2 ]; then
      echo "$my_error_flag"
else
    echo "no flag"
fi

CSS: image link, change on hover

That could be done with <a> only:

#twitterbird {
 display: block; /* 'convert' <a> to <div> */
 margin-bottom: 10px;
 background-position: center top;
 background-repeat: no-repeat;
 width: 160px;
 height: 160px;
 background-image: url('twitterbird.png');
}
#twitterbird:hover {
 background-image: url('twitterbird_hover.png');
}

Set the absolute position of a view

A more cleaner and dynamic way without hardcoding any pixel values in the code.

I wanted to position a dialog (which I inflate on the fly) exactly below a clicked button.

and solved it this way :

    // get the yoffset of the position where your View has to be placed 
    final int yoffset = < calculate the position of the view >

    // position using top margin
    if(myView.getLayoutParams() instanceof MarginLayoutParams) {
        ((MarginLayoutParams) myView.getLayoutParams()).topMargin = yOffset;
    }

However you have to make sure the parent layout of myView is an instance of RelativeLayout.

more complete code :

    // identify the button
    final Button clickedButton = <... code to find the button here ...>

    // inflate the dialog - the following style preserves xml layout params
    final View floatingDialog = 
        this.getLayoutInflater().inflate(R.layout.floating_dialog,
            this.floatingDialogContainer, false);

    this.floatingDialogContainer.addView(floatingDialog);

    // get the buttons position
    final int[] buttonPos = new int[2];
    clickedButton.getLocationOnScreen(buttonPos);        
    final int yOffset =  buttonPos[1] + clickedButton.getHeight();

    // position using top margin
    if(floatingDialog.getLayoutParams() instanceof MarginLayoutParams) {
        ((MarginLayoutParams) floatingDialog.getLayoutParams()).topMargin = yOffset;
    }

This way you can still expect the target view to adjust to any layout parameters set using layout XML files, instead of hardcoding those pixels/dps in your Java code.

Stopword removal with NLTK

@alvas has a good answer. But again it depends on the nature of the task, for example in your application you want to consider all conjunction e.g. and, or, but, if, while and all determiner e.g. the, a, some, most, every, no as stop words considering all others parts of speech as legitimate, then you might want to look into this solution which use Part-of-Speech Tagset to discard words, Check table 5.1:

import nltk

STOP_TYPES = ['DET', 'CNJ']

text = "some data here "
tokens = nltk.pos_tag(nltk.word_tokenize(text))
good_words = [w for w, wtype in tokens if wtype not in STOP_TYPES]

python pandas extract year from datetime: df['year'] = df['date'].year is not working

What worked for me was upgrading pandas to latest version:

From Command Line do:

conda update pandas

How to make link not change color after visited?

Something like this should work:

a, a:visited { 
    color:red; text-decoration:none; 
    }

How to hide status bar in Android

Use theme "Theme.NoTitleBar.Fullscreen" and try setting "android:windowSoftInputMode=adjustResize" for the activity in AndroidManifest.xml. You can find details here.

What is the best way to programmatically detect porn images?

Detecting porn images is still a definite AI task which is very much theoretical yet.

Harvest collective power and human intelligence by adding a button/link "Report spam/abuse". Or employ several moderators to do this job.

P.S. Really surprised how many people ask questions assuming software and algorithms are all-mighty without even thinking whether what they want could be done. Are they representatives of that new breed of programmers who have no understanding of hardware, low-level programming and all that "magic behind"?

P.S. #2. I also remember that periodically it happens that some situation when people themselves cannot decide whether a picture is porn or art is taken to the court. Even after the court rules, chances are half of the people will consider the decision wrong. The last stupid situation of the kind was quite recently when a Wikipedia page got banned in UK because of a CD cover image that features some nakedness.

<input type="file"> limit selectable files by extensions

NOTE: This answer is from 2011. It was a really good answer back then, but as of 2015, native HTML properties are supported by most browsers, so there's (usually) no need to implement such custom logic in JS. See Edi's answer and the docs.


Before the file is uploaded, you can check the file's extension using Javascript, and prevent the form being submitted if it doesn't match. The name of the file to be uploaded is stored in the "value" field of the form element.

Here's a simple example that only allows files that end in ".gif" to be uploaded:

<script type="text/javascript">
    function checkFile() {
        var fileElement = document.getElementById("uploadFile");
        var fileExtension = "";
        if (fileElement.value.lastIndexOf(".") > 0) {
            fileExtension = fileElement.value.substring(fileElement.value.lastIndexOf(".") + 1, fileElement.value.length);
        }
        if (fileExtension.toLowerCase() == "gif") {
            return true;
        }
        else {
            alert("You must select a GIF file for upload");
            return false;
        }
    }
</script>

<form action="upload.aspx" enctype="multipart/form-data" onsubmit="return checkFile();">
    <input name="uploadFile" id="uploadFile" type="file" />

    <input type="submit" />
</form>

However, this method is not foolproof. Sean Haddy is correct that you always want to check on the server side, because users can defeat your Javascript checking by turning off javascript, or editing your code after it arrives in their browser. Definitely check server-side in addition to the client-side check. Also I recommend checking for size server-side too, so that users don't crash your server with a 2 GB file (there's no way that I know of to check file size on the client side without using Flash or a Java applet or something).

However, checking client side before hand using the method I've given here is still useful, because it can prevent mistakes and is a minor deterrent to non-serious mischief.

How to copy a row and insert in same table with a autoincrement field in MySQL?

IMO, the best seems to use sql statements only to copy that row, while at the same time only referencing the columns you must and want to change.

CREATE TEMPORARY TABLE temp_table ENGINE=MEMORY

SELECT * FROM your_table WHERE id=1;
UPDATE temp_table SET id=0; /* Update other values at will. */

INSERT INTO your_table SELECT * FROM temp_table;
DROP TABLE temp_table;

See also av8n.com - How to Clone an SQL Record

Benefits:

  • The SQL statements 2 mention only the fields that need to be changed during the cloning process. They do not know about – or care about – other fields. The other fields just go along for the ride, unchanged. This makes the SQL statements easier to write, easier to read, easier to maintain, and more extensible.
  • Only ordinary MySQL statements are used. No other tools or programming languages are required.
  • A fully-correct record is inserted in your_table in one atomic operation.

How to create query parameters in Javascript?

I have improved the function of shog9`s to handle array values

function encodeQueryData(data) {
    const ret = [];
    for (let d in data) {
        if (typeof data[d] === 'object' || typeof data[d] === 'array') {
            for (let arrD in data[d]) {
                ret.push(`${encodeURIComponent(d)}[]=${encodeURIComponent(data[d][arrD])}`)
            }
        } else if (typeof data[d] === 'null' || typeof data[d] === 'undefined') {
            ret.push(encodeURIComponent(d))
        } else {
            ret.push(`${encodeURIComponent(d)}=${encodeURIComponent(data[d])}`)
        }

    }
    return ret.join('&');
}

Example

let data = {
  user: 'Mark'
  fruits: ['apple', 'banana']
}

encodeQueryData(data) // user=Mark&fruits[]=apple&fruits[]=banana

How do you produce a .d.ts "typings" definition file from an existing JavaScript library?

The best way to deal with this (if a declaration file is not available on DefinitelyTyped) is to write declarations only for the things you use rather than the entire library. This reduces the work a lot - and additionally the compiler is there to help out by complaining about missing methods.

ASP.NET MVC 404 Error Handling

Yet another solution.

Add ErrorControllers or static page to with 404 error information.

Modify your web.config (in case of controller).

<system.web>
    <customErrors mode="On" >
       <error statusCode="404" redirect="~/Errors/Error404" />
    </customErrors>
</system.web>

Or in case of static page

<system.web>
    <customErrors mode="On" >
        <error statusCode="404" redirect="~/Static404.html" />
    </customErrors>
</system.web>

This will handle both missed routes and missed actions.

C++ Pass A String

print(string ("Yo!"));

You need to make a (temporary) std::string object out of it.

What does !important mean in CSS?

!important is a part of CSS1.

Browsers supporting it: IE5.5+, Firefox 1+, Safari 3+, Chrome 1+.

It means, something like:

Use me, if there is nothing important else around!

Cant say it better.

'DataFrame' object has no attribute 'sort'

Pandas Sorting 101

sort has been replaced in v0.20 by DataFrame.sort_values and DataFrame.sort_index. Aside from this, we also have argsort.

Here are some common use cases in sorting, and how to solve them using the sorting functions in the current API. First, the setup.

# Setup
np.random.seed(0)
df = pd.DataFrame({'A': list('accab'), 'B': np.random.choice(10, 5)})    
df                                                                                                                                        
   A  B
0  a  7
1  c  9
2  c  3
3  a  5
4  b  2

Sort by Single Column

For example, to sort df by column "A", use sort_values with a single column name:

df.sort_values(by='A')

   A  B
0  a  7
3  a  5
4  b  2
1  c  9
2  c  3

If you need a fresh RangeIndex, use DataFrame.reset_index.

Sort by Multiple Columns

For example, to sort by both col "A" and "B" in df, you can pass a list to sort_values:

df.sort_values(by=['A', 'B'])

   A  B
3  a  5
0  a  7
4  b  2
2  c  3
1  c  9

Sort By DataFrame Index

df2 = df.sample(frac=1)
df2

   A  B
1  c  9
0  a  7
2  c  3
3  a  5
4  b  2

You can do this using sort_index:

df2.sort_index()

   A  B
0  a  7
1  c  9
2  c  3
3  a  5
4  b  2

df.equals(df2)                                                                                                                            
# False
df.equals(df2.sort_index())                                                                                                               
# True

Here are some comparable methods with their performance:

%timeit df2.sort_index()                                                                                                                  
%timeit df2.iloc[df2.index.argsort()]                                                                                                     
%timeit df2.reindex(np.sort(df2.index))                                                                                                   

605 µs ± 13.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
610 µs ± 24.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
581 µs ± 7.63 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Sort by List of Indices

For example,

idx = df2.index.argsort()
idx
# array([0, 7, 2, 3, 9, 4, 5, 6, 8, 1])

This "sorting" problem is actually a simple indexing problem. Just passing integer labels to iloc will do.

df.iloc[idx]

   A  B
1  c  9
0  a  7
2  c  3
3  a  5
4  b  2

How does the "final" keyword in Java work? (I can still modify an object.)

"A final variable can only be assigned once"

*Reflection* - "wowo wait, hold my beer".


Freeze of final fields happen in two scenarios:

  • End of constructor.
  • When reflection sets the field's value. (as many times as it wants to)

Let's break the law

public class HoldMyBeer 
{
    final int notSoFinal;
    
    public HoldMyBeer()
    {
       notSoFinal = 1;
    }

    static void holdIt(HoldMyBeer beer, int yetAnotherFinalValue) throws Exception
    {
       Class<HoldMyBeer> cl = HoldMyBeer.class;
       Field field = cl.getDeclaredField("notSoFinal");
       field.setAccessible(true);
       field.set(beer, yetAnotherFinalValue);
    }

    public static void main(String[] args) throws Exception 
    {
       HoldMyBeer beer = new HoldMyBeer();
       System.out.println(beer.notSoFinal);
       holdIt(beer, 50);
       System.out.println(beer.notSoFinal);
       holdIt(beer, 100);
       System.out.println(beer.notSoFinal);
       holdIt(beer, 666);
       System.out.println(beer.notSoFinal);
       holdIt(beer, 8888);
       System.out.println(beer.notSoFinal);
    }    
}

Output:

1
50
100
666
8888

The "final" field has been assigned 5 different "final" values (note the quotes). And it could keep being assigned different values over and over...

Why? Because reflection is like Chuck Norris, and if it wants to change the value of an initialized final field, it does. Some say he himself is the one that pushes the new values into the stack :

Code:
   7: astore_1
  11: aload_1
  12: getfield                
  18: aload_1
  19: bipush        50        //wait what
  27: aload_1
  28: getfield                
  34: aload_1
  35: bipush        100       //come on...
  43: aload_1
  44: getfield                
  50: aload_1
  51: sipush        666      //...you were supposed to be final...
  60: aload_1
  61: getfield                
  67: aload_1
  68: sipush        8888     //ok i'm out whatever dude
  77: aload_1
  78: getfield                

How to access the content of an iframe with jQuery?

You have to use the contents() method:

$("#myiframe").contents().find("#myContent")

Source: http://simple.procoding.net/2008/03/21/how-to-access-iframe-in-jquery/

API Doc: https://api.jquery.com/contents/

Numpy - Replace a number with NaN

A[A==NDV]=numpy.nan

A==NDV will produce a boolean array that can be used as an index for A

Find substring in the string in TWIG

Just searched for the docs, and found this:

Containment Operator: The in operator performs containment test. It returns true if the left operand is contained in the right:

{# returns true #}

{{ 1 in [1, 2, 3] }}

{{ 'cd' in 'abcde' }}

Add Legend to Seaborn point plot

I would suggest not to use seaborn pointplot for plotting. This makes things unnecessarily complicated.
Instead use matplotlib plot_date. This allows to set labels to the plots and have them automatically put into a legend with ax.legend().

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np

date = pd.date_range("2017-03", freq="M", periods=15)
count = np.random.rand(15,4)
df1 = pd.DataFrame({"date":date, "count" : count[:,0]})
df2 = pd.DataFrame({"date":date, "count" : count[:,1]+0.7})
df3 = pd.DataFrame({"date":date, "count" : count[:,2]+2})

f, ax = plt.subplots(1, 1)
x_col='date'
y_col = 'count'

ax.plot_date(df1.date, df1["count"], color="blue", label="A", linestyle="-")
ax.plot_date(df2.date, df2["count"], color="red", label="B", linestyle="-")
ax.plot_date(df3.date, df3["count"], color="green", label="C", linestyle="-")

ax.legend()

plt.gcf().autofmt_xdate()
plt.show()

enter image description here


In case one is still interested in obtaining the legend for pointplots, here a way to go:

sns.pointplot(ax=ax,x=x_col,y=y_col,data=df1,color='blue')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df2,color='green')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df3,color='red')

ax.legend(handles=ax.lines[::len(df1)+1], labels=["A","B","C"])

ax.set_xticklabels([t.get_text().split("T")[0] for t in ax.get_xticklabels()])
plt.gcf().autofmt_xdate()

plt.show()

Is there a stopwatch in Java?

You can find a convenient one here:

https://github.com/varra4u/utils4j/blob/master/src/main/java/com/varra/util/StopWatch.java

Usage:

final StopWatch timer = new StopWatch();
System.out.println("Timer: " + timer);
System.out.println("ElapsedTime: " + timer.getElapsedTime());

Using jquery to get all checked checkboxes with a certain class name

$('.theClass:checkbox:checked') will give you all the checked checkboxes with the class theClass.

Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '='

The default collation for stored procedure parameters is utf8_general_ci and you can't mix collations, so you have four options:

Option 1: add COLLATE to your input variable:

SET @rUsername = ‘aname’ COLLATE utf8_unicode_ci; -- COLLATE added
CALL updateProductUsers(@rUsername, @rProductID, @rPerm);

Option 2: add COLLATE to the WHERE clause:

CREATE PROCEDURE updateProductUsers(
    IN rUsername VARCHAR(24),
    IN rProductID INT UNSIGNED,
    IN rPerm VARCHAR(16))
BEGIN
    UPDATE productUsers
        INNER JOIN users
        ON productUsers.userID = users.userID
        SET productUsers.permission = rPerm
        WHERE users.username = rUsername COLLATE utf8_unicode_ci -- COLLATE added
        AND productUsers.productID = rProductID;
END

Option 3: add it to the IN parameter definition:

CREATE PROCEDURE updateProductUsers(
    IN rUsername VARCHAR(24) COLLATE utf8_unicode_ci, -- COLLATE added
    IN rProductID INT UNSIGNED,
    IN rPerm VARCHAR(16))
BEGIN
    UPDATE productUsers
        INNER JOIN users
        ON productUsers.userID = users.userID
        SET productUsers.permission = rPerm
        WHERE users.username = rUsername
        AND productUsers.productID = rProductID;
END

Option 4: alter the field itself:

ALTER TABLE users CHARACTER SET utf8 COLLATE utf8_general_ci;

Unless you need to sort data in Unicode order, I would suggest altering all your tables to use utf8_general_ci collation, as it requires no code changes, and will speed sorts up slightly.

UPDATE: utf8mb4/utf8mb4_unicode_ci is now the preferred character set/collation method. utf8_general_ci is advised against, as the performance improvement is negligible. See https://stackoverflow.com/a/766996/1432614

How to format a floating number to fixed width in Python

See Python 3.x format string syntax:

IDLE 3.5.1   
numbers = ['23.23', '.1233', '1', '4.223', '9887.2']

for x in numbers:  
    print('{0: >#016.4f}'. format(float(x)))  

     23.2300
      0.1233
      1.0000
      4.2230
   9887.2000

How to show full column content in a Spark Dataframe?

Try this in scala:

df.show(df.count.toInt, false)

The show method accepts an integer and a Boolean value but df.count returns Long...so type casting is required

Iterating over all the keys of a map

This is also an option

 for key, element := range myMap{
    fmt.Println("Key:", key, "Element:", element)
 }

Where can I find a list of escape characters required for my JSON ajax return type?

As explained in the section 9 of the official ECMA specification (http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf) in JSON, the following chars have to be escaped:

  • U+0022 (", the quotation mark)
  • U+005C (\, the backslash or reverse solidus)
  • U+0000 to U+001F (the ASCII control characters)

In addition, in order to safely embed JSON in HTML, the following chars have to be also escaped:

  • U+002F (/)
  • U+0027 (')
  • U+003C (<)
  • U+003E (>)
  • U+0026 (&)
  • U+0085 (Next Line)
  • U+2028 (Line Separator)
  • U+2029 (Paragraph Separator)

Some of the above characters can be escaped with the following short escape sequences defined in the standard:

  • \" represents the quotation mark character (U+0022).
  • \\ represents the reverse solidus character (U+005C).
  • \/ represents the solidus character (U+002F).
  • \b represents the backspace character (U+0008).
  • \f represents the form feed character (U+000C).
  • \n represents the line feed character (U+000A).
  • \r represents the carriage return character (U+000D).
  • \t represents the character tabulation character (U+0009).

The other characters which need to be escaped will use the \uXXXX notation, that is \u followed by the four hexadecimal digits that encode the code point.

The \uXXXX can be also used instead of the short escape sequence, or to optionally escape any other character from the Basic Multilingual Plane (BMP).

Writing BMP image in pure c/c++ without other libraries

I edited ralf's htp code so that it would compile (on gcc, running ubuntu 16.04 lts). It was just a matter of initializing the variables.

    int w = 100; /* Put here what ever width you want */
    int h = 100; /* Put here what ever height you want */
    int red[w][h]; 
    int green[w][h];
    int blue[w][h];


    FILE *f;
    unsigned char *img = NULL;
    int filesize = 54 + 3*w*h;  //w is your image width, h is image height, both int
    if( img )
            free( img );
    img = (unsigned char *)malloc(3*w*h);
    memset(img,0,sizeof(img));
    int x;
    int y;
    int r;
    int g;
    int b;

    for(int i=0; i<w; i++)
    {
            for(int j=0; j<h; j++)
            {
                    x=i; y=(h-1)-j;
                    r = red[i][j]*255;
                    g = green[i][j]*255;
                    b = blue[i][j]*255;
                    if (r > 255) r=255;
                    if (g > 255) g=255;
                    if (b > 255) b=255;
                    img[(x+y*w)*3+2] = (unsigned char)(r);
                    img[(x+y*w)*3+1] = (unsigned char)(g);
                    img[(x+y*w)*3+0] = (unsigned char)(b);
            }
    }

    unsigned char bmpfileheader[14] = {'B','M', 0,0,0,0, 0,0, 0,0, 54,0,0,0};
    unsigned char bmpinfoheader[40] = {40,0,0,0, 0,0,0,0, 0,0,0,0, 1,0, 24,0};
    unsigned char bmppad[3] = {0,0,0};

    bmpfileheader[ 2] = (unsigned char)(filesize    );
    bmpfileheader[ 3] = (unsigned char)(filesize>> 8);
    bmpfileheader[ 4] = (unsigned char)(filesize>>16);
    bmpfileheader[ 5] = (unsigned char)(filesize>>24);

    bmpinfoheader[ 4] = (unsigned char)(       w    );
    bmpinfoheader[ 5] = (unsigned char)(       w>> 8);
    bmpinfoheader[ 6] = (unsigned char)(       w>>16);
    bmpinfoheader[ 7] = (unsigned char)(       w>>24);
    bmpinfoheader[ 8] = (unsigned char)(       h    );
    bmpinfoheader[ 9] = (unsigned char)(       h>> 8);
    bmpinfoheader[10] = (unsigned char)(       h>>16);
    bmpinfoheader[11] = (unsigned char)(       h>>24);

    f = fopen("img.bmp","wb");
    fwrite(bmpfileheader,1,14,f);
    fwrite(bmpinfoheader,1,40,f);
    for(int i=0; i<h; i++)
    {
            fwrite(img+(w*(h-i-1)*3),3,w,f);
            fwrite(bmppad,1,(4-(w*3)%4)%4,f);
    }
    fclose(f);

Flutter: RenderBox was not laid out

The problem is that you are placing the ListView inside a Column/Row. The text in the exception gives a good explanation of the error.

To avoid the error you need to provide a size to the ListView inside.

I propose you this code that uses an Expanded to inform the horizontal size (maximum available) and the SizedBox (Could be a Container) for the height:

    new Row(
      children: <Widget>[
        Expanded(
          child: SizedBox(
            height: 200.0,
            child: new ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: products.length,
              itemBuilder: (BuildContext ctxt, int index) {
                return new Text(products[index]);
              },
            ),
          ),
        ),
        new IconButton(
          icon: Icon(Icons.remove_circle),
          onPressed: () {},
        ),
      ],
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
    )

,

Button inside of anchor link works in Firefox but not in Internet Explorer?

You cannot have a button inside an a tag. You can do some javascript to make it work however.

ASP.NET jQuery Ajax Calling Code-Behind Method

This hasn't solved my problem too, so I changed the parameters slightly.
This code worked for me:

var dataValue = "{ name: 'person', isGoing: 'true', returnAddress: 'returnEmail' }";

$.ajax({
    type: "POST",
    url: "Default.aspx/OnSubmit",
    data: dataValue,
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
    },
    success: function (result) {
        alert("We returned: " + result.d);
    }
});

MySQL - UPDATE multiple rows with different values in one query

You can use a CASE statement to handle multiple if/then scenarios:

UPDATE table_to_update 
SET  cod_user= CASE WHEN user_rol = 'student' THEN '622057'
                   WHEN user_rol = 'assistant' THEN '2913659'
                   WHEN user_rol = 'admin' THEN '6160230'
               END
    ,date = '12082014'
WHERE user_rol IN ('student','assistant','admin')
  AND cod_office = '17389551';

Process.start: how to get the output?

When you create your Process object set StartInfo appropriately:

var proc = new Process 
{
    StartInfo = new ProcessStartInfo
    {
        FileName = "program.exe",
        Arguments = "command line arguments to your executable",
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    }
};

then start the process and read from it:

proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
    string line = proc.StandardOutput.ReadLine();
    // do something with line
}

You can use int.Parse() or int.TryParse() to convert the strings to numeric values. You may have to do some string manipulation first if there are invalid numeric characters in the strings you read.

How can I declare optional function parameters in JavaScript?

With ES6: This is now part of the language:

function myFunc(a, b = 0) {
   // function body
}

Please keep in mind that ES6 checks the values against undefined and not against truthy-ness (so only real undefined values get the default value - falsy values like null will not default).


With ES5:

function myFunc(a,b) {
  b = b || 0;

  // b will be set either to b or to 0.
}

This works as long as all values you explicitly pass in are truthy. Values that are not truthy as per MiniGod's comment: null, undefined, 0, false, ''

It's pretty common to see JavaScript libraries to do a bunch of checks on optional inputs before the function actually starts.

extract column value based on another column pandas dataframe

You can try query, which is less typing:

df.query('B==3')['A']

Empty ArrayList equals null

If you want to check whether the array contains items with null values, use this:

private boolean isListOfNulls(ArrayList<String> stringList){
    for (String s: stringList)
        if( s != null) return false;
    return true;
}

You could replace <String> with the corresponding type for your ArrayList

MySQL Removing Some Foreign keys

step1: show create table vendor_locations;

step2: ALTER TABLE vendor_locations drop foreign key vendor_locations_ibfk_1;

it worked for me.

How to align title at center of ActionBar in default theme(Theme.Holo.Light)

Java code: write this in onCreate()
getSupportActionBar().setDisplayShowCustomEnabled(true); getSupportActionBar().setCustomView(R.layout.action_bar);

and for you custom view, simply use FrameLayout, east peasy!
android.support.v7.widget.Toolbar is another option

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left|center_vertical"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/app_name"
        android:textColor="@color/black"
        android:id="@+id/textView" />
</FrameLayout>

How to modify a specified commit?

Completely non-interactive command(1)

I just thought I'd share an alias that I'm using for this. It's based on non-interactive interactive rebase. To add it to your git, run this command (explanation given below):

git config --global alias.amend-to '!f() { SHA=`git rev-parse "$1"`; git commit --fixup "$SHA" && GIT_SEQUENCE_EDITOR=true git rebase --interactive --autosquash "$SHA^"; }; f'

Or, a version that can also handle unstaged files (by stashing and then un-stashing them):

git config --global alias.amend-to '!f() { SHA=`git rev-parse "$1"`; git stash -k && git commit --fixup "$SHA" && GIT_SEQUENCE_EDITOR=true git rebase --interactive --autosquash "$SHA^" && git stash pop; }; f'

The biggest advantage of this command is the fact that it's no-vim.


(1)given that there are no conflicts during rebase, of course

Usage

git amend-to <REV> # e.g.
git amend-to HEAD~1
git amend-to aaaa1111

The name amend-to seems appropriate IMHO. Compare the flow with --amend:

git add . && git commit --amend --no-edit
# vs
git add . && git amend-to <REV>

Explanation

  • git config --global alias.<NAME> '!<COMMAND>' - creates a global git alias named <NAME> that will execute non-git command <COMMAND>
  • f() { <BODY> }; f - an "anonymous" bash function.
  • SHA=`git rev-parse "$1"`; - converts the argument to git revision, and assigns the result to variable SHA
  • git commit --fixup "$SHA" - fixup-commit for SHA. See git-commit docs
  • GIT_SEQUENCE_EDITOR=true git rebase --interactive --autosquash "$SHA^"
    • git rebase --interactive "$SHA^" part has been covered by other answers.
    • --autosquash is what's used in conjunction with git commit --fixup, see git-rebase docs for more info
    • GIT_SEQUENCE_EDITOR=true is what makes the whole thing non-interactive. This hack I learned from this blog post.

nil detection in Go

You can also check like struct_var == (struct{}). This does not allow you to compare to nil but it does check if it is initialized or not. Be careful while using this method. If your struct can have zero values for all of its fields you won't have great time.

package main

import "fmt"

type A struct {
    Name string
}

func main() {
    a := A{"Hello"}
    var b A

    if a == (A{}) {
        fmt.Println("A is empty") // Does not print
    } 

    if b == (A{}) {
        fmt.Println("B is empty") // Prints
    } 
}

http://play.golang.org/p/RXcE06chxE

How do I perform HTML decoding/encoding using Python/Django?

I found a fine function at: http://snippets.dzone.com/posts/show/4569

def decodeHtmlentities(string):
    import re
    entity_re = re.compile("&(#?)(\d{1,5}|\w{1,8});")

    def substitute_entity(match):
        from htmlentitydefs import name2codepoint as n2cp
        ent = match.group(2)
        if match.group(1) == "#":
            return unichr(int(ent))
        else:
            cp = n2cp.get(ent)

            if cp:
                return unichr(cp)
            else:
                return match.group()

    return entity_re.subn(substitute_entity, string)[0]

Statically rotate font-awesome icons

In case someone else stumbles upon this question and wants it here is the SASS mixin I use.

@mixin rotate($deg: 90){
    $sDeg: #{$deg}deg;

    -webkit-transform: rotate($sDeg);
    -moz-transform: rotate($sDeg);
    -ms-transform: rotate($sDeg);
    -o-transform: rotate($sDeg);
    transform: rotate($sDeg);
}

ASP.NET MVC 3 Razor - Adding class to EditorFor

There isn't any EditorFor override that lets you pass in an anonymous object whose properties would somehow get added as attributes on some tag, especially for the built-in editor templates. You would need to write your own custom editor template and pass the value you want as additional viewdata.

How to return part of string before a certain character?

Another method could be to split the string by ":" and then pop off the end. var newString = string.split(":").pop();

Angular (4, 5, 6, 7) - Simple example of slide in out animation on ngIf

The most upvoted answer is not implementing a real slide in/out (or down/up), as:

  1. It's not doing a soft transition on the height attribute. At time zero the element already has the 100% of its height producing a sudden glitch on the elements below it.
  2. When sliding out/up, the element does a translateY(-100%) and then suddenly disappears, causing another glitch on the elements below it.

You can implement a slide in and slide out like so:

my-component.ts

import { animate, style, transition, trigger } from '@angular/animations';

@Component({
  ...
  animations: [
    trigger('slideDownUp', [
      transition(':enter', [style({ height: 0 }), animate(500)]),
      transition(':leave', [animate(500, style({ height: 0 }))]),
    ]),
  ],
})

my-component.html

<div @slideDownUp *ngIf="isShowing" class="box">
  I am the content of the div!
</div>

my-component.scss

.box {
  overflow: hidden;
}

ORA-01652 Unable to extend temp segment by in tablespace

Create a new datafile by running the following command:

alter tablespace TABLE_SPACE_NAME add datafile 'D:\oracle\Oradata\TEMP04.dbf'            
   size 2000M autoextend on;

Declaring variables in Excel Cells

You can name cells. This is done by clicking the Name Box (that thing next to the formula bar which says "A1" for example) and typing a name, such as, "myvar". Now you can use that name instead of the cell reference:

= myvar*25

Android: How to use webcam in emulator?

Follow the below steps in Eclipse.

  1. Goto -> AVD Manager
  2. Create/Edit the AVD.
  3. Hardware > New:
  4. Configures camera facing back
  5. Click on the property value and choose = "webcam0".
  6. Once done all the above the webcam should be connected. If it doesnt then you need to check your WebCam drivers.

Check here for more information : How to use web camera in android emulator to capture a live image?

enter image description here

ESRI : Failed to parse source map

I had the same problem because .htaccess has incorrect settings:

RewriteEngine on
RewriteRule !.(js|gif|jpg|png|css)$ index.php


I solved this by modifying the file:

RewriteEngine on
RewriteRule !.(js|gif|jpg|png|css|eot|svg|ttf|woff|woff2|map)$ index.php

Alert after page load

There are three ways.
The first is to put the script tag on the bottom of the page:

<body>
<!--Body content-->
<script type="text/javascript">
alert('<%: TempData["Resultat"]%>');
</script>
</body>

The second way is to create an onload event:

<head>
<script type="text/javascript">
window.onload = function(){//window.addEventListener('load',function(){...}); (for Netscape) and window.attachEvent('onload',function(){...}); (for IE and Opera) also work
    alert('<%: TempData["Resultat"]%>');
}
</script>
</head>

It will execute a function when the window loads.
Finally, the third way is to create a readystatechange event and check the current document.readystate:

<head>
<script type="text/javascript">
document.onreadystatechange = function(){//window.addEventListener('readystatechange',function(){...}); (for Netscape) and window.attachEvent('onreadystatechange',function(){...}); (for IE and Opera) also work
    if(document.readyState=='loaded' || document.readyState=='complete')
        alert('<%: TempData["Resultat"]%>');
}
</script>
</head>

Node.js for() loop returning the same values at each loop

I would suggest doing this in a more functional style :P

function CreateMessageboard(BoardMessages) {
  var htmlMessageboardString = BoardMessages
   .map(function(BoardMessage) {
     return MessageToHTMLString(BoardMessage);
   })
   .join('');
}

Try this

Replace words in a string - Ruby

If you're dealing with natural language text and need to replace a word, not just part of a string, you have to add a pinch of regular expressions to your gsub as a plain text substitution can lead to disastrous results:

'mislocated cat, vindicating'.gsub('cat', 'dog')
=> "mislodoged dog, vindidoging"

Regular expressions have word boundaries, such as \b which matches start or end of a word. Thus,

'mislocated cat, vindicating'.gsub(/\bcat\b/, 'dog')
=> "mislocated dog, vindicating"

In Ruby, unlike some other languages like Javascript, word boundaries are UTF-8-compatible, so you can use it for languages with non-Latin or extended Latin alphabets:

'???? ? ??????, ??? ??????'.gsub(/\b????\b/, '?????')
=> "????? ? ??????, ??? ??????"

How to fix committing to the wrong Git branch?

To elaborate on this answer, in case you have multiple commits to move from, e.g. develop to new_branch:

git checkout develop # You're probably there already
git reflog # Find LAST_GOOD, FIRST_NEW, LAST_NEW hashes
git checkout new_branch
git cherry-pick FIRST_NEW^..LAST_NEW # ^.. includes FIRST_NEW
git reflog # Confirm that your commits are safely home in their new branch!
git checkout develop
git reset --hard LAST_GOOD # develop is now back where it started

Is there a program to decompile Delphi?

Languages like Delphi, C and C++ Compile to processor-native machine code, and the output executables have little or no metadata in them. This is in contrast with Java or .Net, which compile to object-oriented platform-independent bytecode, which retains the names of methods, method parameters, classes and namespaces, and other metadata.

So there is a lot less useful decompiling that can be done on Delphi or C code. However, Delphi typically has embedded form data for any form in the project (generated by the $R *.dfm line), and it also has metadata on all published properties, so a Delphi-specific tool would be able to extract this information.

ViewDidAppear is not called when opening app from background

Just have your view controller register for the UIApplicationWillEnterForegroundNotification notification and react accordingly.

HTML5 required attribute seems not working

Try putting it inside a form tag and closing the input tag:

<form>
  <input type = "text" class = "txtPost" placeholder = "Post a question?" required />
  <button class = "btnPost btnBlue">Post</button>
</form>

Run react-native on android emulator

I had similar issue running emulator from android studio everytime, or on a physical device. Instead, you can quickly run android emulator from command line,

android avd

Once the emulator is running, you can check with adb devices if the emulator shows up. Then you can simply use react-native run-android to run the app on the emulator.

Make sure you've platform tools installed to be able to use adb. Or you can use

brew install android-platform-tools

What is recursion and when should I use it?

Recursion is technique of defining a function, a set or an algorithm in terms of itself.

For example

n! = n(n-1)(n-2)(n-3)...........*3*2*1

Now it can be defined recursively as:-

n! = n(n-1)!   for n>=1

In programming terms, when a function or method calls itself repeatedly, until some specific condition gets satisfied, this process is called Recursion. But there must be a terminating condition and function or method must no enter into an infinite loop.

Unable to create Android Virtual Device

I had the same problem while creating AVD with 4.2.2 images, I resolved it by doing the following :

  1. Check if there exist a "default" folder in adt-bundle-windows-x86_64-20131030\sdk\system-images\android-17.

  2. If it exists then move the contents(downloaded system images) of the "default" folder to adt-bundle-windows-x86_64-20131030\sdk\system-images\android-17.

Hope this helps.

Multiple contexts with the same path error running web service in Eclipse using Tomcat

Try to delete the existing tomcat server in the server console. If you don't have the console then you can go to "Show view ->server", delete the server by right clicking on it, then add a new server.

Error when trying vagrant up

The first and most important step before starting a Vagrant is, check which all boxes are present in your system. Use this command for getting the list of boxes available.

vagrant box list

Then move to further process that is, selecting a particular box

vagrant init ubuntu/trusty64 (I have selected ubuntu/trusty64)

then,

vagrant up

Thanks

Update Item to Revision vs Revert to Revision

Update your working copy to the selected revision. Useful if you want to have your working copy reflect a time in the past, or if there have been further commits to the repository and you want to update your working copy one step at a time. It is best to update a whole directory in your working copy, not just one file, otherwise your working copy could be inconsistent. This is used to test a specific rev purpose, if your test has done, you can use this command to test another rev or use SVN Update to get HEAD

If you want to undo an earlier change permanently, use Revert to this revision instead.

-- from TSVN help doc

If you Update your working copy to an earlier rev, this is only affect your own working copy, after you do some change, and want to commit, you will fail,TSVN will alert you to update your WC to latest revision first If you Revert to a rev, you can commit to repository.everyone will back to the rev after they do an update.

How to disable Django's CSRF validation?

If you just need some views not to use CSRF, you can use @csrf_exempt:

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def my_view(request):
    return HttpResponse('Hello world')

You can find more examples and other scenarios in the Django documentation:

document.body.appendChild(i)

You could try

document.getElementsByTagName('body')[0].appendChild(i);

Now that won't do you any good if the code is running in the <head>, and running before the <body> has even been seen by the browser. If you don't want to mess with "onload" handlers, try moving your <script> block to the very end of the document instead of the <head>.

Adding files to a GitHub repository

Open github app. Then, add the Folder of files into the github repo file onto your computer (You WILL need to copy the repo onto your computer. Most repo files are located in the following directory: C:\Users\USERNAME\Documents\GitHub\REPONAME) Then, in the github app, check our your repo. You can easily commit from there.

How to get response as String using retrofit without using GSON or any other library in android

** Update ** A scalars converter has been added to retrofit that allows for a String response with less ceremony than my original answer below.

Example interface --

public interface GitHubService {
    @GET("/users/{user}")
    Call<String> listRepos(@Path("user") String user);
}

Add the ScalarsConverterFactory to your retrofit builder. Note: If using ScalarsConverterFactory and another factory, add the scalars factory first.

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(ScalarsConverterFactory.create())
    // add other factories here, if needed.
    .build();

You will also need to include the scalars converter in your gradle file --

implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'

--- Original Answer (still works, just more code) ---

I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject land. I suspect your specific problem might be better solved using a custom gson TypeAdapter or a retrofit Converter if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -

First, if you are using Retrofit 2, you should start using the Call API. Instead of sending an object to convert as the type parameter, use ResponseBody from okhttp --

public interface GitHubService {
    @GET("/users/{user}")
    Call<ResponseBody> listRepos(@Path("user") String user);
}

then you can create and execute your call --

GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Response<ResponseBody> response) {
        try {
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(Throwable t) {
        e.printStackTrace();
    }
});

Note The code above calls string() on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream() instead. See the ResponseBody docs.

Setting "checked" for a checkbox with jQuery

If you are using .prop('checked', true|false) and don’t have changed checkbox, you need to add trigger('click') like this:

// Check
$('#checkboxF1').prop( "checked", true).trigger('click');


// Uncheck
$('#checkboxF1').prop( "checked", false).trigger('click');

Is it possible to return empty in react render function?

Yes you can return an empty value from a React render method.

You can return any of the following: false, null, undefined, or true

According to the docs:

false, null, undefined, and true are valid children. They simply don’t render.

You could write

return null; or
return false; or
return true; or
return <div>{undefined}</div>; 

However return null is the most preferred as it signifies that nothing is returned

How to save the output of a console.log(object) to a file?

In case you have an object logged:

  • Right click on the object in console and click Store as a global variable
  • the output will be something like temp1
  • type in console copy(temp1)
  • paste to your favorite text editor

How to add /usr/local/bin in $PATH on Mac

In MAC OS Catalina, this are the steps that worked for me, all the above solutions did help but didn't solve my problem.

  1. check node --version, still the old one in use.
  2. cd ~/
  3. atom .bash_profile
  4. Remove the $PATH pointing to old node version, in my case it was /usr/local/bin/node/@node8
  5. Add & save this to $PATH instead "export PATH=$PATH:/usr/local/git/bin:/usr/local/bin"
  6. Close all applications using node (terminal, simulator, browser expo etc)
  7. restart terminal and check node --version

Git pushing to remote branch

Simply push this branch to a different branch name

 git push -u origin localBranch:remoteBranch

Retrieve a Fragment from a ViewPager

In Fragment

public int getArgument(){
   return mPage;
{
public void update(){

}

In FragmentActivity

List<Fragment> fragments = getSupportFragmentManager().getFragments();
for(Fragment f:fragments){
    if((f instanceof PageFragment)&&(!f.isDetached())){
          PageFragment pf = (PageFragment)f;   
          if(pf.getArgument()==pager.getCurrentItem())pf.update();
    }
}

C# how to use enum with switch

Since C# 8.0 introduced a new switch expression for enums you can do it even more elegant:

public double Calculate(int left, int right, Operator op) =>
            op switch 
        {
            Operator.PLUS => left + right,
            Operator.MINUS => left - right,
            Operator.MULTIPLY => left * right,
            Operator.DIVIDE => left / right,
            _    =>  0
        }

Ref. https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8

Convert double to string

a = 0.000006;
b = 6;
c = a/b;

textbox.Text = c.ToString("0.000000");

As you requested:

textbox.Text = c.ToString("0.######");

This will only display out to the 6th decimal place if there are 6 decimals to display.

Save matplotlib file to a directory

If the directory you wish to save to is a sub-directory of your working directory, simply specify the relative path before your file name:

    fig.savefig('Sub Directory/graph.png')

If you wish to use an absolute path, import the os module:

    import os
    my_path = os.path.abspath(__file__) # Figures out the absolute path for you in case your working directory moves around.
    ...
    fig.savefig(my_path + '/Sub Directory/graph.png')

If you don't want to worry about the leading slash in front of the sub-directory name, you can join paths intelligently as follows:

    import os
    my_path = os.path.abspath(__file__) # Figures out the absolute path for you in case your working directory moves around.
    my_file = 'graph.png'
    ...
    fig.savefig(os.path.join(my_path, my_file))        

Count the number of commits on a Git branch

How about git log --pretty=oneline | wc -l

That should count all the commits from the perspective of your current branch.

java.sql.SQLException: - ORA-01000: maximum open cursors exceeded

This problem mainly happens when you are using connection pooling because when you close connection that connection go back to the connection pool and all cursor associated with that connection never get closed as the connection to database is still open. So one alternative is to decrease the idle connection time of connections in pool, so may whenever connection sits idle in connection for say 10 sec , connection to database will get closed and new connection created to put in pool.

Node.js fs.readdir recursive directory search

Check out the final-fs library. It provides a readdirRecursive function:

ffs.readdirRecursive(dirPath, true, 'my/initial/path')
    .then(function (files) {
        // in the `files` variable you've got all the files
    })
    .otherwise(function (err) {
        // something went wrong
    });

Multiple conditions in an IF statement in Excel VBA

In VBA we can not use if jj = 5 or 6 then we must use if jj = 5 or jj = 6 then

maybe this:

If inputWks.Range("d9") > 0 And (inputWks.Range("d11") = "Restricted_Expenditure" Or inputWks.Range("d11") = "Unrestricted_Expenditure") Then

What is and how to fix System.TypeInitializationException error?

i. Please check the InnerException property of the TypeInitializationException

ii. Also, this may occur due to mismatch between the runtime versions of the assemblies. Please verify the runtime versions of the main assembly (calling application) and the referred assembly

Val and Var in Kotlin

Both, val and var can be used for declaring variables (local and class properties).

Local variables:

  1. val declares read-only variables that can only be assigned once, but cannot be reassigned.

Example:

val readonlyString = “hello”
readonlyString = “c u” // Not allowed for `val`
  1. var declares reassignable variables as you know them from Java (the keyword will be introduced in Java 10, “local variable type inference”).

Example:

var reasignableString = “hello”
reasignableString = “c u” // OK

It is always preferable to use val. Try to avoid var as often as possible!

Class properties:

Both keywords are also used in order to define properties inside classes. As an example, have a look at the following data class:

data class Person (val name: String, var age: Int)

The Person contains two fields, one of which is readonly (name). The age, on the other hand, may be reassigned after class instantiation, via the provided setter. Note that name won’t have a corresponding setter method.

Why does Java's hashCode() in String use 31 as a multiplier?

Bloch doesn't quite go into this, but the rationale I've always heard/believed is that this is basic algebra. Hashes boil down to multiplication and modulus operations, which means that you never want to use numbers with common factors if you can help it. In other words, relatively prime numbers provide an even distribution of answers.

The numbers that make up using a hash are typically:

  • modulus of the data type you put it into (2^32 or 2^64)
  • modulus of the bucket count in your hashtable (varies. In java used to be prime, now 2^n)
  • multiply or shift by a magic number in your mixing function
  • The input value

You really only get to control a couple of these values, so a little extra care is due.

How to specify Memory & CPU limit in docker compose version 3

deploy:
  resources:
    limits:
      cpus: '0.001'
      memory: 50M
    reservations:
      cpus: '0.0001'
      memory: 20M

More: https://docs.docker.com/compose/compose-file/compose-file-v3/#resources

In you specific case:

version: "3"
services:
  node:
    image: USER/Your-Pre-Built-Image
    environment:
      - VIRTUAL_HOST=localhost
    volumes:
      - logs:/app/out/
    command: ["npm","start"]
    cap_drop:
      - NET_ADMIN
      - SYS_ADMIN
    deploy:
      resources:
        limits:
          cpus: '0.001'
          memory: 50M
        reservations:
          cpus: '0.0001'
          memory: 20M

volumes:
  - logs

networks:
  default:
    driver: overlay

Note:

  • Expose is not necessary, it will be exposed per default on your stack network.
  • Images have to be pre-built. Build within v3 is not possible
  • "Restart" is also deprecated. You can use restart under deploy with on-failure action
  • You can use a standalone one node "swarm", v3 most improvements (if not all) are for swarm

Also Note: Networks in Swarm mode do not bridge. If you would like to connect internally only, you have to attach to the network. You can 1) specify an external network within an other compose file, or have to create the network with --attachable parameter (docker network create -d overlay My-Network --attachable) Otherwise you have to publish the port like this:

ports:
  - 80:80

SQL Server query to find all current database names

This forum suggests also:

SELECT CATALOG_NAME AS DataBaseName
FROM INFORMATION_SCHEMA.SCHEMATA

Draw a line in a div

If the div has some content inside, this will be the best practice to have a line over or under the div and maintaining the content spacing with the div

.div_line_bottom{
 border-bottom: 1px solid #ff0000;
 padding-bottom:20px;
}

.div_line_top{
border-top: 1px solid #ff0000;
padding-top:20px;
}

How to convert date into this 'yyyy-MM-dd' format in angular 2

A simple solution would be to just write

this.date = new Date().toLocaleDateString();

date .toLocaleDateString() time .toLocaleTimeString() both .toLocaleString()

Hope this helps.

Warning :-Presenting view controllers on detached view controllers is discouraged

Make sure you have a root view controller to start with. You can set it in didFinishLaunchingWithOptions.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    [window setRootViewController:viewController];
}

Command to get latest Git commit hash from a branch

Use git ls-remote git://github.com/<user>/<project>.git. For example, my trac-backlog project gives:

:: git ls-remote git://github.com/jszakmeister/trac-backlog.git
5d6a3c973c254378738bdbc85d72f14aefa316a0    HEAD
4652257768acef90b9af560295b02d0ac6e7702c    refs/heads/0.1.x
35af07bc99c7527b84e11a8632bfb396823326f3    refs/heads/0.2.x
5d6a3c973c254378738bdbc85d72f14aefa316a0    refs/heads/master
520dcebff52506682d6822ade0188d4622eb41d1    refs/pull/11/head
6b2c1ed650a7ff693ecd8ab1cb5c124ba32866a2    refs/pull/11/merge
51088b60d66b68a565080eb56dbbc5f8c97c1400    refs/pull/12/head
127c468826c0c77e26a5da4d40ae3a61e00c0726    refs/pull/12/merge
2401b5537224fe4176f2a134ee93005a6263cf24    refs/pull/15/head
8aa9aedc0e3a0d43ddfeaf0b971d0ae3a23d57b3    refs/pull/15/merge
d96aed93c94f97d328fc57588e61a7ec52a05c69    refs/pull/7/head
f7c1e8dabdbeca9f9060de24da4560abc76e77cd    refs/pull/7/merge
aa8a935f084a6e1c66aa939b47b9a5567c4e25f5    refs/pull/8/head
cd258b82cc499d84165ea8d7a23faa46f0f2f125    refs/pull/8/merge
c10a73a8b0c1809fcb3a1f49bdc1a6487927483d    refs/tags/0.1.0
a39dad9a1268f7df256ba78f1166308563544af1    refs/tags/0.2.0
2d559cf785816afd69c3cb768413c4f6ca574708    refs/tags/0.2.1
434170523d5f8aad05dc5cf86c2a326908cf3f57    refs/tags/0.2.2
d2dfe40cb78ddc66e6865dcd2e76d6bc2291d44c    refs/tags/0.3.0
9db35263a15dcdfbc19ed0a1f7a9e29a40507070    refs/tags/0.3.0^{}

Just grep for the one you need and cut it out:

:: git ls-remote git://github.com/jszakmeister/trac-backlog.git | \
   grep refs/heads/master | cut -f 1
5d6a3c973c254378738bdbc85d72f14aefa316a0

Or, you can specify which refs you want on the command line and avoid the grep with:

:: git ls-remote git://github.com/jszakmeister/trac-backlog.git refs/heads/master | \
   cut -f 1
5d6a3c973c254378738bdbc85d72f14aefa316a0

Note: it doesn't have to be the git:// URL. It could be https:// or [email protected]: too.

Originally, this was geared towards finding out the latest commit of a remote branch (not just from your last fetch, but the actual latest commit in the branch on the remote repository). If you need the commit hash for something locally, the best answer is:

git rev-parse branch-name

It's fast, easy, and a single command. If you want the commit hash for the current branch, you can look at HEAD:

git rev-parse HEAD

Spark: Add column to dataframe conditionally

Try withColumn with the function when as follows:

val sqlContext = new SQLContext(sc)
import sqlContext.implicits._ // for `toDF` and $""
import org.apache.spark.sql.functions._ // for `when`

val df = sc.parallelize(Seq((4, "blah", 2), (2, "", 3), (56, "foo", 3), (100, null, 5)))
    .toDF("A", "B", "C")

val newDf = df.withColumn("D", when($"B".isNull or $"B" === "", 0).otherwise(1))

newDf.show() shows

+---+----+---+---+
|  A|   B|  C|  D|
+---+----+---+---+
|  4|blah|  2|  1|
|  2|    |  3|  0|
| 56| foo|  3|  1|
|100|null|  5|  0|
+---+----+---+---+

I added the (100, null, 5) row for testing the isNull case.

I tried this code with Spark 1.6.0 but as commented in the code of when, it works on the versions after 1.4.0.

How to place a div below another div?

what about changing the position: relative on your #content #text div to position: absolute

#content #text {
   position:absolute;
   width:950px;
   height:215px;
   color:red;
}

http://jsfiddle.net/CaZY7/12/

then you can use the css properties left and top to position within the #content div

Maven: How to rename the war file for the project?

You can follow the below step to modify the .war file name if you are using maven project.

Open pom.xml file of your maven project and go to the tag <build></build>,

  1. In that give your desired name between this tag : <finalName></finalName>.

    ex. : <finalName>krutik</finalName>

    After deploying this .war you will be able to access url with:
    http://localhost:8080/krutik/

  2. If you want to access the url with slash '/' then you will have to specify then name as below:

    e.x. : <finalName>krutik#maheta</finalName>

    After deploying this .war you will be able to access url with:
    http://localhost:8080/krutik/maheta

HTML character codes for this ? or this ?

There are several correct ways to display a down-pointing and upward-pointing triangle.

Method 1 : use decimal HTML entity

HTML :

&#9650;
&#9660;

Method 2 : use hexidecimal HTML entity

HTML :

&#x25B2;
&#x25BC;

Method 3 : use character directly

HTML :

?
?

Method 4 : use CSS

HTML :

<span class='icon-up'></span>
<span class='icon-down'></span>

CSS :

.icon-up:before {
    content: "\25B2";
}

.icon-down:before {
    content: "\25BC";
}

Each of these three methods should have the same output. For other symbols, the same three options exist. Some even have a fourth option, allowing you to use a string based reference (eg. &hearts; to display ?).

You can use a reference website like Unicode-table.com to find which icons are supported in UNICODE and which codes they correspond with. For example, you find the values for the down-pointing triangle at http://unicode-table.com/en/25BC/.

Note that these methods are sufficient only for icons that are available by default in every browser. For symbols like ?,?,?,?,?,? or ?, this is far less likely to be the case. While it is possible to provide cross-browser support for other UNICODE symbols, the procedure is a bit more complicated.

If you want to know how to add support for less common UNICODE characters, see Create webfont with Unicode Supplementary Multilingual Plane symbols for more info on how to do this.


Background images

A totally different strategy is the use of background-images instead of fonts. For optimal performance, it's best to embed the image in your CSS file by base-encoding it, as mentioned by eg. @weasel5i2 and @Obsidian. I would recommend the use of SVG rather than GIF, however, is that's better both for performance and for the sharpness of your symbols.

This following code is the base64 for and SVG version of the enter image description here icon :

/* size: 0.9kb */
url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48IURPQ1RZUEUgc3ZnIFBVQkxJQyAiLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4iICJodHRwOi8vd3d3LnczLm9yZy9HcmFwaGljcy9TVkcvMS4xL0RURC9zdmcxMS5kdGQiPjxzdmcgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB3aWR0aD0iMTYiIGhlaWdodD0iMjgiIHZpZXdCb3g9IjAgMCAxNiAyOCI+PGcgaWQ9Imljb21vb24taWdub3JlIj48L2c+PHBhdGggZD0iTTE2IDE3cTAgMC40MDYtMC4yOTcgMC43MDNsLTcgN3EtMC4yOTcgMC4yOTctMC43MDMgMC4yOTd0LTAuNzAzLTAuMjk3bC03LTdxLTAuMjk3LTAuMjk3LTAuMjk3LTAuNzAzdDAuMjk3LTAuNzAzIDAuNzAzLTAuMjk3aDE0cTAuNDA2IDAgMC43MDMgMC4yOTd0MC4yOTcgMC43MDN6TTE2IDExcTAgMC40MDYtMC4yOTcgMC43MDN0LTAuNzAzIDAuMjk3aC0xNHEtMC40MDYgMC0wLjcwMy0wLjI5N3QtMC4yOTctMC43MDMgMC4yOTctMC43MDNsNy03cTAuMjk3LTAuMjk3IDAuNzAzLTAuMjk3dDAuNzAzIDAuMjk3bDcgN3EwLjI5NyAwLjI5NyAwLjI5NyAwLjcwM3oiIGZpbGw9IiMwMDAwMDAiPjwvcGF0aD48L3N2Zz4=

When to use background-images or fonts

For many use cases, SVG-based background images and icon fonts are largely equivalent with regards to performance and flexibility. To decide which to pick, consider the following differences:

SVG images

  • They can have multiple colors
  • They can embed their own CSS and/or be styled by the HTML document
  • They can be loaded as a seperate file, embedded in CSS AND embedded in HTML
  • Each symbol is represented by XML code or base64 code. You cannot use the character directly within your code editor or use an HTML entity
  • Multiple uses of the same symbol implies duplication of the symbol when XML code is embedded in the HTML. Duplication is not required when embedding the file in the CSS or loading it as a seperate file
  • You can not use color, font-size, line-height, background-color or other font related styling rules to change the display of your icon, but you can reference different components of the icon as shapes individually.
  • You need some knowledge of SVG and/or base64 encoding
  • Limited or no support in old versions of IE

Icon fonts

  • An icon can have but one fill color, one background color, etc.
  • An icon can be embedded in CSS or HTML. In HTML, you can use the character directly or use an HTML entity to represent it.
  • Some symbols can be displayed without the use of a webfont. Most symbols cannot.
  • Multiple uses of the same symbol implies duplication of the symbol when your character embedded in the HTML. Duplication is not required when embedding the file in the CSS.
  • You can use color, font-size, line-height, background-color or other font related styling rules to change the display of your icon
  • You need no special technical knowledge
  • Support in all major browsers, including old versions of IE

Personally, I would recommend the use of background-images only when you need multiple colors and those color can't be achieved by means of color, background-color and other color-related CSS rules for fonts.

The main benefit of using SVG images is that you can give different components of a symbol their own styling. If you embed your SVG XML code in the HTML document, this is very similar to styling the HTML. This would, however, result in a web page that uses both HTML tags and SVG tags, which could significantly reduce the readability of a webpage. It also adds extra bloat if the symbol is repeated across multiple pages and you need to consider that old versions of IE have no or limited support for SVG.

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

Enable Multidex through build.gradle of your app module

multiDexEnabled true

Same as below -

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

Then follow below steps -

  1. From the Build menu -> press the Clean Project button.
  2. When task completed, press the Rebuild Project button from the Build menu.
  3. From menu File -> Invalidate cashes / Restart

compile is now deprecated so it's better to use implementation or api

Imported a csv-dataset to R but the values becomes factors

None of these answers mention the colClasses argument which is another way to specify the variable classes in read.csv.

 stuckey <- read.csv("C:/kalle/R/stuckey.csv", colClasses = "numeric") # all variables to numeric

or you can specify which columns to convert:

stuckey <- read.csv("C:/kalle/R/stuckey.csv", colClasses = c("PTS" = "numeric", "MP" = "numeric") # specific columns to numeric

Note that if a variable can't be converted to numeric then it will be converted to factor as default which makes it more difficult to convert to number. Therefore, it can be advisable just to read all variables in as 'character' colClasses = "character" and then convert the specific columns to numeric once the csv is read in:

stuckey <- read.csv("C:/kalle/R/stuckey.csv", colClasses = "character")
point <- as.numeric(stuckey$PTS)
time <- as.numeric(stuckey$MP)

What method in the String class returns only the first N characters?

Whenever I have to do string manipulations in C#, I miss the good old Left and Right functions from Visual Basic, which are much simpler to use than Substring.

So in most of my C# projects, I create extension methods for them:

public static class StringExtensions
{
    public static string Left(this string str, int length)
    {
        return str.Substring(0, Math.Min(length, str.Length));
    }

    public static string Right(this string str, int length)
    {
        return str.Substring(str.Length - Math.Min(length, str.Length));
    }
}

Note:
The Math.Min part is there because Substring throws an ArgumentOutOfRangeException when the input string's length is smaller than the requested length, as already mentioned in some comments under previous answers.

Usage:

string longString = "Long String";

// returns "Long";
string left1 = longString.Left(4);

// returns "Long String";
string left2 = longString.Left(100);

Random color generator

Use this:

// RGBA()
function getRandomRGBA() {
    function numbers() {
        var x = Math.floor(Math.random() * 256);
        return x;
    }

    alpha = 1.0;
    return (
        "rgba(" +
        numbers() +
        ", " +
        numbers() +
        ", " +
        numbers() +
        ", " +
        alpha.toFixed(1) +
        ")"
    );
}

tar: file changed as we read it

Simply using an outer directory for the output, solved the problem for me.

sudo tar czf ./../31OCT18.tar.gz ./

Changing a specific column name in pandas DataFrame

Another option would be to simply copy & drop the column:

df = pd.DataFrame(d)
df['new_name'] = df['two']
df = df.drop('two', axis=1)
df.head()

After that you get the result:

    one three   new_name
0   1   a       9
1   2   b       8
2   3   c       7
3   4   d       6
4   5   e       5

Angular 2: How to call a function after get a response from subscribe http.post

You can do this be using a new Subject too:

Typescript:

let subject = new Subject();

get_categories(...) {
   this.http.post(...).subscribe( 
      (response) => {
         this.total = response.json();
         subject.next();
      }
   ); 

   return subject; // can be subscribed as well 
}

get_categories(...).subscribe(
   (response) => {
     // ...
   }
);

Make one div visible and another invisible

I don't think that you really want an iframe, do you?

Unless you're doing something weird, you should be getting your results back as JSON or (in the worst case) XML, right?

For your white box / extra space issue, try

style="display: none;"

instead of

style="visibility: hidden;"

How to build a DataTable from a DataGridView?

one of best solution enjoyed it ;)

  public DataTable GetContentAsDataTable(bool IgnoreHideColumns=false)
        {
            try
            {
                if (dgv.ColumnCount == 0) return null;
                DataTable dtSource = new DataTable();
                foreach (DataGridViewColumn col in dgv.Columns)
                {
                    if (IgnoreHideColumns & !col.Visible) continue;
                    if (col.Name == string.Empty) continue;
                    dtSource.Columns.Add(col.Name, col.ValueType);
                    dtSource.Columns[col.Name].Caption = col.HeaderText;
                }
                if (dtSource.Columns.Count == 0) return null;
                foreach (DataGridViewRow row in dgv.Rows)
                {
                    DataRow drNewRow = dtSource.NewRow();
                    foreach (DataColumn  col in dtSource .Columns)
                    {
                        drNewRow[col.ColumnName] = row.Cells[col.ColumnName].Value;
                    }
                    dtSource.Rows.Add(drNewRow);
                }
                return dtSource;
            }
            catch { return null; }
        }

How to automatically update an application without ClickOnce?

The most common way would be to put a simple text file (XML/JSON would be better) on your webserver with the last build version. The application will then download this file, check the version and start the updater. A typical file would look like this:

Application Update File (A unique string that will let your application recognize the file type)

version: 1.0.0 (Latest Assembly Version)

download: http://yourserver.com/... (A link to the download version)

redirect: http://yournewserver.com/... (I used this field in case of a change in the server address.)

This would let the client know that they need to be looking at a new address.

You can also add other important details.

git clone error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 10054

All these tips did not work for me, what worked was cloning over ssh rather that http

Code for Greatest Common Divisor in Python

using recursion,

def gcd(a,b):
    return a if not b else gcd(b, a%b)

using while,

def gcd(a,b):
  while b:
    a,b = b, a%b
  return a

using lambda,

gcd = lambda a,b : a if not b else gcd(b, a%b)

>>> gcd(10,20)
>>> 10

Iptables setting multiple multiports in one rule

enable_boxi_poorten

}

enable_boxi_poorten() {
SRV="boxi_poorten"
boxi_ports="427 5666 6001 6002 6003 6004 6005 6400 6410 8080 9321 15191 16447 17284 17723 17736 21306 25146 26632 27657 27683 28925 41583 45637 47648 49633 52551 53166 56392 56599 56911 59115 59898 60163 63512 6352 25834"


case "$1" in
  "LOCAL")
         for port in $boxi_ports; do $IPT -A tcp_inbound -p TCP -s $LOC_SUB --dport $port -j ACCEPT -m comment --comment "boxi specifieke poorten";done
     # multiports gaat maar tot 15 maximaal :((
     # daarom maar for loop maken
     # $IPT -A tcp_inbound -p TCP -s $LOC_SUB -m state --state NEW -m multiport --dports $MULTIPORTS -j ACCEPT -m comment --comment "boxi specifieke poorten"
     echo "${GREEN}Allowing $SRV for local hosts.....${NORMAL}"
    ;;
  "WEB")
     for port in $boxi_ports; do $IPT -A tcp_inbound -p TCP -s 0/0 --dport $port -j ACCEPT -m comment --comment "boxi specifieke poorten";done
     echo "${RED}Allowing $SRV for all hosts.....${NORMAL}"
    ;;
  *)
     for port in $boxi_ports; do $IPT -A tcp_inbound -p TCP -s $LOC_SUB --dport $port -j ACCEPT -m comment --comment "boxi specifieke poorten";done
     echo "${GREEN}Allowing $SRV for local hosts.....${NORMAL}"
    ;;
 esac

}

What is the difference between association, aggregation and composition?

For two objects, Foo and Bar the relationships can be defined

Association - I have a relationship with an object. Foo uses Bar

public class Foo { 
    void Baz(Bar bar) {
    } 
};

Composition - I own an object and I am responsible for its lifetime. When Foo dies, so does Bar

public class Foo {
    private Bar bar = new Bar(); 
}

Aggregation - I have an object which I've borrowed from someone else. When Foo dies, Bar may live on.

public class Foo { 
    private Bar bar; 
    Foo(Bar bar) { 
       this.bar = bar; 
    }
}

Eclipse add Tomcat 7 blank server name

In Eclipse Neon.3 Release (4.6.3) on Ubuntu 17.04 with Tomcat 8.0 the problem persists. What helped me was the combination of deleting the prefs files:

rm ~/workspace/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.jst.server.tomcat.core.prefs    
rm ~/workspace/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.wst.server.core.prefs

and linking to catalina.policy (somewhat differently than how @michael-brooks suggested for his configuration):

sudo ln -s /var/lib/tomcat8/policy/catalina.policy conf/catalina.policy

The type or namespace name 'Objects' does not exist in the namespace 'System.Data'

Upgraded from EF5 to EF6 nuget a while back and kept encountering this issue. I'd temp fix it by updating the generated code to reference System.Data.Entity.Core.Objects, but after generation it would be changed back again (as expected since its generated).

This solved the problem for good:

http://msdn.microsoft.com/en-us/data/upgradeef6

If you have any models created with the EF Designer, you will need to update the code generation templates to generate EF6 compatible code. Note: There are currently only EF 6.x DbContext Generator templates available for Visual Studio 2012 and 2013.

  1. Delete existing code-generation templates. These files will typically be named <edmx_file_name>.tt and <edmx_file_name>.Context.tt and be nested under your edmx file in Solution Explorer. You can select the templates in Solution Explorer and press the Del key to delete them.
    Note: In Web Site projects the templates will not be nested under your edmx file, but listed alongside it in Solution Explorer.
    Note: In VB.NET projects you will need to enable 'Show All Files' to be able to see the nested template files.
  2. Add the appropriate EF 6.x code generation template. Open your model in the EF Designer, right-click on the design surface and select Add Code Generation Item...
    • If you are using the DbContext API (recommended) then EF 6.x DbContext Generator will be available under the Data tab.
      Note: If you are using Visual Studio 2012, you will need to install the EF 6 Tools to have this template. See Get Entity Framework for details.
    • If you are using the ObjectContext API then you will need to select the Online tab and search for EF 6.x EntityObject Generator.
  3. If you applied any customizations to the code generation templates you will need to re-apply them to the updated templates.

How to quickly drop a user with existing privileges

I faced the same problem and now found a way to solve it. First you have to delete the database of the user that you wish to drop. Then the user can be easily deleted.

I created an user named "msf" and struggled a while to delete the user and recreate it. I followed the below steps and Got succeeded.

1) Drop the database

dropdb msf

2) drop the user

dropuser msf

Now I got the user successfully dropped.

How do I upload a file to an SFTP server in C# (.NET)?

Maybe you can script/control winscp?

Update: winscp now has a .NET library available as a nuget package that supports SFTP, SCP, and FTPS

Is it possible to select the last n items with nth-child?

This will select the last two iems of a list:

_x000D_
_x000D_
li:nth-last-child(-n+2) {color:red;}
_x000D_
<ul>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
</ul>
_x000D_
_x000D_
_x000D_

REST - HTTP Post Multipart with JSON

If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes. You set request header Content-Type: multipart/form-data; boundary=HereGoes. Then this should be a valid request body:

--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json

{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64

<...JPEG content in base64...>
--HereGoes--

JQuery, select first row of table

This is a better solution, using:

$("table tr:first-child").has('img')

How to get the response of XMLHttpRequest?

You can get it by XMLHttpRequest.responseText in XMLHttpRequest.onreadystatechange when XMLHttpRequest.readyState equals to XMLHttpRequest.DONE.

Here's an example (not compatible with IE6/7).

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        alert(xhr.responseText);
    }
}
xhr.open('GET', 'http://example.com', true);
xhr.send(null);

For better crossbrowser compatibility, not only with IE6/7, but also to cover some browser-specific memory leaks or bugs, and also for less verbosity with firing ajaxical requests, you could use jQuery.

$.get('http://example.com', function(responseText) {
    alert(responseText);
});

Note that you've to take the Same origin policy for JavaScript into account when not running at localhost. You may want to consider to create a proxy script at your domain.

In Python, can I call the main() of an imported module?

It depends. If the main code is protected by an if as in:

if __name__ == '__main__':
    ...main code...

then no, you can't make Python execute that because you can't influence the automatic variable __name__.

But when all the code is in a function, then might be able to. Try

import myModule

myModule.main()

This works even when the module protects itself with a __all__.

from myModule import * might not make main visible to you, so you really need to import the module itself.