Programs & Examples On #Redirect

A response by a webserver, that asks the user agent to not show the response body, but instead request a different resource.

How to redirect user's browser URL to a different page in Nodejs?

OP: "I would love if there were a way to do it where I didn't have to know the host address..."

response.writeHead(301, {
  Location: "http" + (request.socket.encrypted ? "s" : "") + "://" + 
    request.headers.host + newRoom
});
response.end();

Prevent redirect after form is submitted

I found this page 10 years (!) after the original post, and needed the answer as vanilla js instead of AJAX. I figured it out with the help of @gargAman's answer.

Use an appropriate selector to assign your button to a variable, e.g.

document.getElementById('myButton')

then

myButton.addEventListener('click', function(e) {
    e.preventDefault();
    // do cool stuff
});

I should note that my html looks like this (specifically, I am not using type="Submit" in my button and action="" in my form:

  <form method="POST" action="" id="myForm">
    <!-- form fields -->
    <button id="myButton" class="btn-submit">Submit</button>
  </form>

How to redirect back to form with input - Laravel 5

this will work definately !!!

  $v = Validator::make($request->all(),[
  'name' => ['Required','alpha']
  ]);

   if($v->passes()){
     print_r($request->name);
   }
   else{
     //this will return the errors & to check put "dd($errors);" in your blade(view)
     return back()->withErrors($v)->withInput();
   }

Python Requests library redirect new url

I think requests.head instead of requests.get will be more safe to call when handling url redirect,check the github issue here:

r = requests.head(url, allow_redirects=True)
print(r.url)

PHP page redirect

The header() function does this:

header("Location: user.php");

Laravel 5.4 redirection to custom url after login

you can add method in LoginController add line use App\User; on Top, after this add method, it is work for me wkwkwkwkw , but you must add {{ csrf_field() }} on view admin and user

protected function authenticated(Request $request, $user){

$user=User::where('email',$request->input('email'))->pluck('jabatan');
$c=" ".$user." ";
$a=strcmp($c,' ["admin"] ');

if ($a==0) {
    return redirect('admin');

}else{
    return redirect('user');

}}

Page redirect with successful Ajax request

I suppose you could attack this in two ways;

1) insert window.location = 'http://www.yourdomain.com into the success function.

2) Use a further ajax call an inject this into an element on your page, further info on which you can find in the jQuery docs at http://api.jquery.com/jQuery.get/

Nodejs - Redirect url

You have to use the following code:

response.writeHead(302 , {
           'Location' : '/view/index.html' // This is your url which you want
        });
response.end();

How to redirect to action from JavaScript method?

To redirect:

function DeleteJob() {
    if (confirm("Do you really want to delete selected job/s?"))
        window.location.href = "your/url";
    else
        return false;
}

Redirect from an HTML page

I use a script which redirects the user from index.html to relative url of Login Page

<html>
  <head>
    <title>index.html</title>
  </head>
  <body onload="document.getElementById('lnkhome').click();">
    <a href="/Pages/Login.aspx" id="lnkhome">Go to Login Page<a>
  </body>
</html>

HTTP redirect: 301 (permanent) vs. 302 (temporary)

Status 301 means that the resource (page) is moved permanently to a new location. The client/browser should not attempt to request the original location but use the new location from now on.

Status 302 means that the resource is temporarily located somewhere else, and the client/browser should continue requesting the original url.

javascript window.location in new tab

window.open('https://support.wwf.org.uk', '_blank');

The second parameter is what makes it open in a new window. Don't forget to read Jakob Nielsen's informative article :)

Rerouting stdin and stdout from C

freopen("/my/newstdin", "r", stdin);
freopen("/my/newstdout", "w", stdout);
freopen("/my/newstderr", "w", stderr);

... do your stuff

freopen("/dev/stdin", "r", stdin);
...
...

This peaks the needle on my round-peg-square-hole-o-meter, what are you trying to accomplish?

Edit:

Remember that stdin, stdout and stderr are file descriptors 0, 1 and 2 for every newly created process. freopen() should keep the same fd's, just assign new streams to them.

So, a good way to ensure that this is actually doing what you want it to do would be:

printf("Stdout is descriptor %d\n", fileno(stdout));
freopen("/tmp/newstdout", "w", stdout);
printf("Stdout is now /tmp/newstdout and hopefully still fd %d\n",
   fileno(stdout));
freopen("/dev/stdout", "w", stdout);
printf("Now we put it back, hopefully its still fd %d\n",
   fileno(stdout));

I believe this is the expected behavior of freopen(), as you can see, you're still only using three file descriptors (and associated streams).

This would override any shell redirection, as there would be nothing for the shell to redirect. However, its probably going to break pipes. You might want to be sure to set up a handler for SIGPIPE, in case your program finds itself on the blocking end of a pipe (not FIFO, pipe).

So, ./your_program --stdout /tmp/stdout.txt --stderr /tmp/stderr.txt should be easily accomplished with freopen() and keeping the same actual file descriptors. What I don't understand is why you'd need to put them back once changing them? Surely, if someone passed either option, they would want it to persist until the program terminated?

Redirect From Action Filter Attribute

I am using MVC4, I used following approach to redirect a custom html screen upon authorization breach.

Extend AuthorizeAttribute say CutomAuthorizer override the OnAuthorization and HandleUnauthorizedRequest

Register the CustomAuthorizer in the RegisterGlobalFilters.

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{

    filters.Add(new CustomAuthorizer());
}

upon identifying the unAuthorized access call HandleUnauthorizedRequestand redirect to the concerned controller action as shown below.


public class CustomAuthorizer : AuthorizeAttribute
{

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        bool isAuthorized = IsAuthorized(filterContext); // check authorization
        base.OnAuthorization(filterContext);
        if (!isAuthorized && !filterContext.ActionDescriptor.ActionName.Equals("Unauthorized", StringComparison.InvariantCultureIgnoreCase)
            && !filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.Equals("LogOn", StringComparison.InvariantCultureIgnoreCase))
        {

            HandleUnauthorizedRequest(filterContext);

        }
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result =
       new RedirectToRouteResult(
           new RouteValueDictionary{{ "controller", "LogOn" },
                                          { "action", "Unauthorized" }

                                         });

    }
}

PHP Session timeout

    session_cache_expire( 20 );
    session_start(); // NEVER FORGET TO START THE SESSION!!!
    $inactive = 1200; //20 minutes *60
    if(isset($_SESSION['start']) ) {
$session_life = time() - $_SESSION['start'];
if($session_life > $inactive){
    header("Location: user_logout.php");
}
    }
    $_SESSION['start'] = time();

    if($_SESSION['valid_user'] != true){
    header('Location: ../....php');
    }else{  

source: http://www.daniweb.com/web-development/php/threads/124500

Redirecting to URL in Flask

its pretty easy if u just want to redirect to a url without any status codes or anything like that u can simple say

from flask import Flask, redirect

app = Flask(__name__)

@app.route('/')
def redirect_to_link():
    # return redirect method, NOTE: replace google.com with the link u want
    return redirect('https://google.com')

here is the link to the Flask Docs for more explanation

Printing Batch file results to a text file

For Print Result to text file

we can follow

echo "test data" > test.txt

This will create test.txt file and written "test data"

If you want to append then

echo "test data" >> test.txt

How to redirect in a servlet filter?

If you also want to keep hash and get parameter, you can do something like this (fill redirectMap at filter init):

String uri = request.getRequestURI();

String[] uriParts = uri.split("[#?]");
String path = uriParts[0];
String rest = uri.substring(uriParts[0].length());

if(redirectMap.containsKey(path)) {
    response.sendRedirect(redirectMap.get(path) + rest);
} else {
    chain.doFilter(request, response);
}

How to redirect to an external URL in Angular2?

In your component.ts

import { Component } from '@angular/core';

@Component({
  ...
})
export class AppComponent {
  ...
  goToSpecificUrl(url): void {
    window.location.href=url;
  }

  gotoGoogle() : void {
    window.location.href='https://www.google.com';
  }
}

In your component.html

<button type="button" (click)="goToSpecificUrl('http://stackoverflow.com/')">Open URL</button>
<button type="button" (click)="gotoGoogle()">Open Google</button>

<li *ngFor="item of itemList" (click)="goToSpecificUrl(item.link)"> // (click) don't enable pointer when we hover so we should enable it by using css like: **cursor: pointer;**

PHP Redirect to another page after form submit

If your redirect is in PHP, nothing should be echoed to the user before the redirect instruction.

See header for more info.

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP

Otherwise, you can use Javascript to redirect the user.

Just use

window.location = "http://www.google.com/"

Use .htaccess to redirect HTTP to HTTPs

None if this worked for me. First of all I had to look at my provider to see how they activate SSL in .htaccess my provider gives

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteCond %{HTTP:HTTPS} !on
   RewriteRule (.*) https://%{SERVER_NAME}/$1 [QSA,L,R=301]
</IfModule>

But what took me days of research is I had to add to wp-config.php the following lines as my provided site is behind a proxy :

/**
 * Force le SSL
 */
define('FORCE_SSL_ADMIN', true);
if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false) $_SERVER['HTTPS']='on';

GET URL parameter in PHP

I was getting nothing for any $_GET["..."] (e.g print_r($_GET) gave an empty array) yet $_SERVER['REQUEST_URI'] showed stuff should be there. In the end it turned out that I was only getting to the web page because my .htaccess was redirecting it there (my 404 handler was the same .php file, and I had made a typo in the browser when testing).

Simply changing the name meant the same php code worked once the 404 redirection wasn't kicking in!

So there are ways $_GET can return nothing even though the php code may be correct.

yii2 redirect in controller action does not work?

try by this

if(!Yii::$app->request->getIsPost()) 
{
  Yii::$app->response->redirect(array('user/index','id'=>302));
    exit(0);
}

redirect COPY of stdout to log file from within bash script itself

Can't say I'm comfortable with any of the solutions based on exec. I prefer to use tee directly, so I make the script call itself with tee when requested:

# my script: 

check_tee_output()
{
    # copy (append) stdout and stderr to log file if TEE is unset or true
    if [[ -z $TEE || "$TEE" == true ]]; then 
        echo '-------------------------------------------' >> log.txt
        echo '***' $(date) $0 $@ >> log.txt
        TEE=false $0 $@ 2>&1 | tee --append log.txt
        exit $?
    fi 
}

check_tee_output $@

rest of my script

This allows you to do this:

your_script.sh args           # tee 
TEE=true your_script.sh args  # tee 
TEE=false your_script.sh args # don't tee
export TEE=false
your_script.sh args           # tee

You can customize this, e.g. make tee=false the default instead, make TEE hold the log file instead, etc. I guess this solution is similar to jbarlow's, but simpler, maybe mine has limitations that I have not come across yet.

RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()

The main important difference between the forward() and sendRedirect() method is that in case of forward(), redirect happens at server end and not visible to client, but in case of sendRedirect(), redirection happens at client end and it's visible to client.

enter image description here

Writing outputs to log file and console

I wanted to display logs on stdout and log file along with the timestamp. None of the above answers worked for me. I made use of process substitution and exec command and came up with the following code. Sample logs:

2017-06-21 11:16:41+05:30 Fetching information about files in the directory...

Add following lines at the top of your script:

LOG_FILE=script.log
exec > >(while read -r line; do printf '%s %s\n' "$(date --rfc-3339=seconds)" "$line" | tee -a $LOG_FILE; done)
exec 2> >(while read -r line; do printf '%s %s\n' "$(date --rfc-3339=seconds)" "$line" | tee -a $LOG_FILE; done >&2)

Hope this helps somebody!

Redirect to new Page in AngularJS using $location

It might help you!

AngularJs Code-sample

var app = angular.module('urlApp', []);
app.controller('urlCtrl', function ($scope, $log, $window) {
    $scope.ClickMeToRedirect = function () {
        var url = "http://" + $window.location.host + "/Account/Login";
        $log.log(url);
        $window.location.href = url;
    };
});

HTML Code-sample

<div ng-app="urlApp">
    <div ng-controller="urlCtrl">
        Redirect to <a href="#" ng-click="ClickMeToRedirect()">Click Me!</a>
    </div>
</div>

jquery: change the URL address without redirecting?

You cannot really change the whole URL in the location bar without redirecting (think of the security issues!).

However you can change the hash part (whats after the #) and read that: location.hash

ps. prevent the default onclick redirect of a link by something like:

$("#link").bind("click",function(e){
  doRedirectFunction();
  e.preventDefault();
})

aspx page to redirect to a new page

You could also do this is plain in html with a meta tag:

<html>
<head>
  <meta http-equiv="refresh" content="0;url=new.aspx" />
</head>
<body>
</body>
</html>

ASP.NET MVC 3 - redirect to another action

return RedirectToAction("ActionName", "ControllerName");

Redirect HTTP to HTTPS on default virtual host without ServerName

This is the complete way to omit unneeded redirects, too ;)

These rules are intended to be used in .htaccess files, as a RewriteRule in a *:80 VirtualHost entry needs no Conditions.

RewriteEngine on
RewriteCond %{HTTPS} off [OR] 
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R=301,L]

Eplanations:

RewriteEngine on

==> enable the engine at all

RewriteCond %{HTTPS} off [OR]

==> match on non-https connections, or (not setting [OR] would cause an implicit AND !)

RewriteCond %{HTTP:X-Forwarded-Proto} !https

==> match on forwarded connections (proxy, loadbalancer, etc.) without https

RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R=301,L]

==> if one of both Conditions match, do the rewrite of the whole URL, sending a 301 to have this 'learned' by the client (some do, some don't) and the L for the last rule.

Redirecting unauthorized controller in ASP.NET MVC

You should build your own Authorize-filter attribute.

Here's mine to study ;)

Public Class RequiresRoleAttribute : Inherits ActionFilterAttribute
    Private _role As String

    Public Property Role() As String
        Get
            Return Me._role
        End Get
        Set(ByVal value As String)
            Me._role = value
        End Set
    End Property

    Public Overrides Sub OnActionExecuting(ByVal filterContext As System.Web.Mvc.ActionExecutingContext)
        If Not String.IsNullOrEmpty(Me.Role) Then
            If Not filterContext.HttpContext.User.Identity.IsAuthenticated Then
                Dim redirectOnSuccess As String = filterContext.HttpContext.Request.Url.AbsolutePath
                Dim redirectUrl As String = String.Format("?ReturnUrl={0}", redirectOnSuccess)
                Dim loginUrl As String = FormsAuthentication.LoginUrl + redirectUrl

                filterContext.HttpContext.Response.Redirect(loginUrl, True)
            Else
                Dim hasAccess As Boolean = filterContext.HttpContext.User.IsInRole(Me.Role)
                If Not hasAccess Then
                    Throw New UnauthorizedAccessException("You don't have access to this page. Only " & Me.Role & " can view this page.")
                End If
            End If
        Else
            Throw New InvalidOperationException("No Role Specified")
        End If

    End Sub
End Class

Google Apps Script to open a URL

Google Apps Script will not open automatically web pages, but it could be used to display a message with links, buttons that the user could click on them to open the desired web pages or even to use the Window object and methods like addEventListener() to open URLs.

It's worth to note that UiApp is now deprecated. From Class UiApp - Google Apps Script - Google Developers

Deprecated. The UI service was deprecated on December 11, 2014. To create user interfaces, use the HTML service instead.

The example in the HTML Service linked page is pretty simple,

Code.gs

// Use this code for Google Docs, Forms, or new Sheets.
function onOpen() {
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
      .createMenu('Dialog')
      .addItem('Open', 'openDialog')
      .addToUi();
}

function openDialog() {
  var html = HtmlService.createHtmlOutputFromFile('index')
      .setSandboxMode(HtmlService.SandboxMode.IFRAME);
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
      .showModalDialog(html, 'Dialog title');
}

A customized version of index.html to show two hyperlinks

<a href='http://stackoverflow.com' target='_blank'>Stack Overflow</a>
<br/>
<a href='http://meta.stackoverflow.com/' target='_blank'>Meta Stack Overflow</a>

How to redirect to the same page in PHP

Another elegant one is

header("Location: http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
exit;

Insert variable into Header Location PHP

<?php
$variable1 = "foo";
$variable2 = "bar";


header('Location: http://linkhere.com?fieldname1=$variable1&fieldname2=$variable2&fieldname3=$variable3);

?>

This works without any quotations.

How to redirect to another page in node.js

@Nazar Medeiros - Your solution uses passport with Express. I am not using passport, just express-jwt. I might be doing something wrong, but when a user logs in, the token needs to return to the client side. From what I have found so far, this means we have to return a json with the token and therefor cannot call redirect. Is there something I am missing there?

To get around this, I simply return the token, store it in my cookies and then make a ajax GET request (with the valid token). When that ajax call returns I replace the body's html with the returned HTML. This is probably not the right way to do it, but I can't find a better way. Here is my JQuery JavaScript code.

function loginUser(){
  $.post("/users/login", {
    username: $( '#login_input_username' ).val(),
   password: $( '#login_input_password' ).val()
 }).done(function(res){
    document.cookie = "token = " + res.token;
    redirectToHome();
  })
}

function redirectToHome(){
  var settings = {
    "async": true,
    "crossDomain": true,
    "url": "/home",
    "type": "GET",
    "headers": {
      "authorization": "Bearer " + getCookie('token'),
      "cache-control": "no-cache"
    }
  }

  $.ajax(settings).done(function (response) {
    $('body').replaceWith(response);
  });
}

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

Change URL and redirect using jQuery

tell you the true, I still don't get what you need, but

window.location(url);

should be

window.location = url;

a search on window.location reference will tell you that.

http to https through .htaccess

To redirect http://example.com or http://www.example.com to https://www.example.com in a simple way, you can use the following Rule in htaccess :

RewriteEngine on

RewriteCond %{HTTPS} off
RewriteCond www.%{HTTP_HOST} ^(?:www\.)?(www\..+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [NE,L,R]

[Tested]

%{REQUEST_SCHEME} variable is available since apache 2.4 , this variable contains the value of requested scheme (http or https), on apache 2.4 you can use the following rule :

RewriteEngine on


RewriteCond %{REQUEST_SCHEME} ^http$
RewriteCond %{HTTP_HOST} ^(www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [NE,L,R]

How to redirect the output of print to a TXT file

Building on previous answers, I think it's a perfect use case for doing it (simple) context manager style:

import sys

class StdoutRedirection:
    """Standard output redirection context manager"""

    def __init__(self, path):
        self._path = path

    def __enter__(self):
        sys.stdout = open(self._path, mode="w")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        sys.stdout.close()
        sys.stdout = sys.__stdout__

and then:

with StdoutRedirection("path/to/file"):
    print("Hello world")

Also it would be really easy to add some functionality to StdoutRedirection class (e.g. a method that lets you change the path)

apache ProxyPass: how to preserve original IP address

If you are using Apache reverse proxy for serving an app running on a localhost port you must add a location to your vhost.

<Location />            
   ProxyPass http://localhost:1339/ retry=0
   ProxyPassReverse http://localhost:1339/
   ProxyPreserveHost On
   ProxyErrorOverride Off
</Location>

To get the IP address have following options

console.log(">>>", req.ip);// this works fine for me returned a valid ip address 
console.log(">>>", req.headers['x-forwarded-for'] );// returned a valid IP address 
console.log(">>>", req.headers['X-Real-IP'] ); // did not work returned undefined 
console.log(">>>", req.connection.remoteAddress );// returned the loopback IP address 

So either use req.ip or req.headers['x-forwarded-for']

How to set a cookie for another domain

Probaly you can use Iframe for this. Facebook probably uses this technique. You can read more on this here. Stackoverflow uses similar technique, but with HTML5 local storage, more on this on their blog

How do I navigate to another page when PHP script is done?

if ($done)
{
    header("Location: /url/to/the/other/page");
    exit;
}

Redirect website after certain amount of time

Place the following HTML redirect code between the and tags of your HTML code.

<meta HTTP-EQUIV="REFRESH" content="3; url=http://www.yourdomain.com/index.html">

The above HTML redirect code will redirect your visitors to another web page instantly. The content="3; may be changed to the number of seconds you want the browser to wait before redirecting. 4, 5, 8, 10 or 15 seconds, etc.

How can I find where I will be redirected using cURL?

The chosen answer here is decent but its case sensitive, doesn't protect against relative location: headers (which some sites do) or pages that might actually have the phrase Location: in their content... (which zillow currently does).

A bit sloppy, but a couple quick edits to make this a bit smarter are:

function getOriginalURL($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $result = curl_exec($ch);
    $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    // if it's not a redirection (3XX), move along
    if ($httpStatus < 300 || $httpStatus >= 400)
        return $url;

    // look for a location: header to find the target URL
    if(preg_match('/location: (.*)/i', $result, $r)) {
        $location = trim($r[1]);

        // if the location is a relative URL, attempt to make it absolute
        if (preg_match('/^\/(.*)/', $location)) {
            $urlParts = parse_url($url);
            if ($urlParts['scheme'])
                $baseURL = $urlParts['scheme'].'://';

            if ($urlParts['host'])
                $baseURL .= $urlParts['host'];

            if ($urlParts['port'])
                $baseURL .= ':'.$urlParts['port'];

            return $baseURL.$location;
        }

        return $location;
    }
    return $url;
}

Note that this still only goes 1 redirection deep. To go deeper, you actually need to get the content and follow the redirects.

Redirecting to previous page after login? PHP

You should first get user refer page in a variable using $_SERVER['HTTP_REFERER']; in your login page.

LIKE:

<?php 
    session_start();
    $refPage = $_SERVER['HTTP_REFERER']; 
?>

And now when the user clicks to Login then change header location to user refer page

LIKE:

<?php 
if(isset($_POST[login])){
    session_start();
    header('location:' . $refPage);
}
?>

And in this time you should first check that user refers page empty or not because your user can visit direct your login page then your $refPage variable will be empty so after Click to Login page stays here

LIKE:

<?php
if(isset($_POST[login])){
    session_start();
    $refPage = $_SERVER['HTTP_REFERER'];  // get reffer page url
    if(empty($refPage)){ 
        header('location: yourredirectpage'); // if ref page is empty then set default redirect page.
    }else{
        header('location:' . $refPage); // or if ref page in not empty then redirect page to reffer page
    }
}
?>


Or you can use input type hidden where you can set value $_SERVER['HTTP_REFERER'];

LIKE:

<input type="hidden" name="refPage" value="<?php echo $_SERVER['HTTP_REFERER']; ?>">

And when a user clicks to Login then you can get the refPage value and redirect the previous page. And you should also check empty refer page. Because your user can visit direct your login page.


Thank you.

React-Router External link

I had luck with this:

  <Route
    path="/example"
    component={() => {
    global.window && (global.window.location.href = 'https://example.com');
    return null;
    }}
/>

How to redirect stderr to null in cmd.exe

Your DOS command 2> nul

Read page Using command redirection operators. Besides the "2>" construct mentioned by Tanuki Software, it lists some other useful combinations.

How can I create an error 404 in PHP?

In the Drupal or Wordpress CMS (and likely others), if you are trying to make some custom php code appear not to exist (unless some condition is met), the following works well by making the CMS's 404 handler take over:

<?php
  if(condition){
    do stuff;
  } else {
    include('index.php');
  }
?>

redirect to current page in ASP.Net

Why Server.Transfer? Response.Redirect(Request.RawUrl) would get you what you need.

Spring MVC Controller redirect using URL parameters instead of in response

Hey you can just do one simple thing instead of using model to send parameter use HttpServletRequest object and do this

HttpServletRequest request;
request.setAttribute("param", "value")

now your parametrs will not be shown in your url header hope it works :)

Nginx no-www to www and www to no-www

You may find out you want to use the same config for more domains.

Following snippet removes www before any domain:

if ($host ~* ^www\.(.*)$) {
    rewrite / $scheme://$1 permanent;
}

How do I redirect with JavaScript?

window.location.replace('http://sidanmor.com');

It's better than using window.location.href = 'http://sidanmor.com';

Using replace() is better because it does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco.

If you want to simulate someone clicking on a link, use window.location.href

If you want to simulate an HTTP redirect, use window.location.replace

For example:

// similar behavior as an HTTP redirect
window.location.replace("http://sidanmor.com");

// similar behavior as clicking on a link
window.location.href = "http://sidanmor.com";

Taken from here: How to redirect to another page in jQuery?

Redirecting 404 error with .htaccess via 301 for SEO etc

I came up with the solution and posted it on my blog

http://web.archive.org/web/20130310123646/http://onlinemarketingexperts.com.au/2013/01/how-to-permanently-redirect-301-all-404-missing-pages-in-htaccess/

here is the htaccess code also

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . / [L,R=301]

but I posted other solutions on my blog too, it depends what you need really

PHP header(Location: ...): Force URL change in address bar

I got a solution for you, Why dont you rather use Explode if your url is something like

Url-> website.com/test/blog.php

$StringExplo=explode("/",$_SERVER['REQUEST_URI']);
$HeadTo=$StringExplo[0]."/Index.php";
Header("Location: ".$HeadTo);

Redirect after Login on WordPress

You can also use the customized link as:

https://example.com/wp-login.php?redirect_to=https://example.com/news.php

S3 Static Website Hosting Route All Paths to Index.html

since the problem is still there I though I throw in another solution. My case was that I wanted to auto deploy all pull requests to s3 for testing before merge making them accessible on [mydomain]/pull-requests/[pr number]/
(ex. www.example.com/pull-requests/822/)

To the best of my knowledge non of s3 rules scenarios would allow to have multiple projects in one bucket using html5 routing so while above most voted suggestion works for a project in root folder, it doesn't for multiple projects in own subfolders.

So I pointed my domain to my server where following nginx config did the job

location /pull-requests/ {
    try_files $uri @get_files;
}
location @get_files {
    rewrite ^\/pull-requests\/(.*) /$1 break;
    proxy_pass http://<your-amazon-bucket-url>;
    proxy_intercept_errors on;
    recursive_error_pages on;
    error_page 404 = @get_routes;
}

location @get_routes {
    rewrite ^\/(\w+)\/(.+) /$1/ break;
    proxy_pass http://<your-amazon-bucket-url>;
    proxy_intercept_errors on;
    recursive_error_pages on;
    error_page 404 = @not_found;
}

location @not_found {
    return 404;
}

it tries to get the file and if not found assumes it is html5 route and tries that. If you have a 404 angular page for not found routes you will never get to @not_found and get you angular 404 page returned instead of not found files, which could be fixed with some if rule in @get_routes or something.

I have to say I don't feel too comfortable in area of nginx config and using regex for that matter, I got this working with some trial and error so while this works I am sure there is room for improvement and please do share your thoughts.

Note: remove s3 redirection rules if you had them in S3 config.

and btw works in Safari

Django return redirect() with parameters

Firstly, your URL definition does not accept any parameters at all. If you want parameters to be passed from the URL into the view, you need to define them in the urlconf.

Secondly, it's not at all clear what you are expecting to happen to the cleaned_data dictionary. Don't forget you can't redirect to a POST - this is a limitation of HTTP, not Django - so your cleaned_data either needs to be a URL parameter (horrible) or, slightly better, a series of GET parameters - so the URL would be in the form:

/link/mybackend/?field1=value1&field2=value2&field3=value3

and so on. In this case, field1, field2 and field3 are not included in the URLconf definition - they are available in the view via request.GET.

So your urlconf would be:

url(r'^link/(?P<backend>\w+?)/$', my_function)

and the view would look like:

def my_function(request, backend):
   data = request.GET

and the reverse would be (after importing urllib):

return "%s?%s" % (redirect('my_function', args=(backend,)),
                  urllib.urlencode(form.cleaned_data))

Edited after comment

The whole point of using redirect and reverse, as you have been doing, is that you go to the URL - it returns an Http code that causes the browser to redirect to the new URL, and call that.

If you simply want to call the view from within your code, just do it directly - no need to use reverse at all.

That said, if all you want to do is store the data, then just put it in the session:

request.session['temp_data'] = form.cleaned_data

How do I redirect to another webpage?

Use:

function redirect(a) {
    location = a
}

And call it with: redirect([url]);

There's no need for the href after location, as it is implied.

Back to previous page with header( "Location: " ); in PHP

Just try this in Javascript:

 $previous = "javascript:history.go(-1)";

Or you can try it in PHP:

if(isset($_SERVER['HTTP_REFERER'])) {
    $previous = $_SERVER['HTTP_REFERER'];
}

What's the difference between a 302 and a 307 redirect?

The difference concerns redirecting POST, PUT and DELETE requests and what the expectations of the server are for the user agent behavior (RFC 2616):

Note: RFC 1945 and RFC 2068 specify that the client is not allowed to change the method on the redirected request. However, most existing user agent implementations treat 302 as if it were a 303 response, performing a GET on the Location field-value regardless of the original request method. The status codes 303 and 307 have been added for servers that wish to make unambiguously clear which kind of reaction is expected of the client.

Also, read Wikipedia article on the 30x redirection codes.

ASP.NET MVC: What is the correct way to redirect to pages/actions in MVC?

RedirectToAction("actionName", "controllerName");

It has other overloads as well, please check up!

Also, If you are new and you are not using T4MVC, then I would recommend you to use it!

It gives you intellisence for actions,Controllers,views etc (no more magic strings)

Spring Security redirect to previous page after successful login

I found Utku Özdemir's solution works to some extent, but kind of defeats the purpose of the saved request since the session attribute will take precedence over it. This means that redirects to secure pages will not work as intended - after login you will be sent to the page you were on instead of the redirect target. So as an alternative you could use a modified version of SavedRequestAwareAuthenticationSuccessHandler instead of extending it. This will allow you to have better control over when to use the session attribute.

Here is an example:

private static class MyCustomLoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private RequestCache requestCache = new HttpSessionRequestCache();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws ServletException, IOException {
        SavedRequest savedRequest = requestCache.getRequest(request, response);

        if (savedRequest == null) {
            HttpSession session = request.getSession();
            if (session != null) {
                String redirectUrl = (String) session.getAttribute("url_prior_login");
                if (redirectUrl != null) {
                    session.removeAttribute("url_prior_login");
                    getRedirectStrategy().sendRedirect(request, response, redirectUrl);
                } else {
                    super.onAuthenticationSuccess(request, response, authentication);
                }
            } else {
                super.onAuthenticationSuccess(request, response, authentication);
            }

            return;
        }

        String targetUrlParameter = getTargetUrlParameter();
        if (isAlwaysUseDefaultTargetUrl()
                || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
            requestCache.removeRequest(request, response);
            super.onAuthenticationSuccess(request, response, authentication);

            return;
        }

        clearAuthenticationAttributes(request);

        // Use the DefaultSavedRequest URL
        String targetUrl = savedRequest.getRedirectUrl();
        logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
        getRedirectStrategy().sendRedirect(request, response, targetUrl);
    }
}

Also, you don't want to save the referrer when authentication has failed, since the referrer will then be the login page itself. So check for the error param manually or provide a separate RequestMapping like below.

@RequestMapping(value = "/login", params = "error")
public String loginError() {
    // Don't save referrer here!
}

IIS7 URL Redirection from root to sub directory

You need to download this from Microsoft: http://www.microsoft.com/en-us/download/details.aspx?id=7435.

The tool is called "Microsoft URL Rewrite Module 2.0 for IIS 7" and is described as follows by Microsoft: "URL Rewrite Module 2.0 provides a rule-based rewriting mechanism for changing requested URL’s before they get processed by web server and for modifying response content before it gets served to HTTP clients"

Rewrite URL after redirecting 404 error htaccess

Try this in your .htaccess:

.htaccess

ErrorDocument 404 http://example.com/404/
ErrorDocument 500 http://example.com/500/
# or map them to one error document:
# ErrorDocument 404 /pages/errors/error_redirect.php
# ErrorDocument 500 /pages/errors/error_redirect.php

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} ^/404/$
RewriteRule ^(.*)$ /pages/errors/404.php [L]

RewriteCond %{REQUEST_URI} ^/500/$
RewriteRule ^(.*)$ /pages/errors/500.php [L]

# or map them to one error document:
#RewriteCond %{REQUEST_URI} ^/404/$ [OR]
#RewriteCond %{REQUEST_URI} ^/500/$
#RewriteRule ^(.*)$ /pages/errors/error_redirect.php [L]

The ErrorDocument redirects all 404s to a specific URL, all 500s to another url (replace with your domain).

The Rewrite rules map that URL to your actual 404.php script. The RewriteCond regular expressions can be made more generic if you want, but I think you have to explicitly define all ErrorDocument codes you want to override.

Local Redirect:

Change .htaccess ErrorDocument to a file that exists (must exist, or you'll get an error):

ErrorDocument 404 /pages/errors/404_redirect.php

404_redirect.php

<?php
   header('Location: /404/');
   exit;
?>

Redirect based on error number

Looks like you'll need to specify an ErrorDocument line in .htaccess for every error you want to redirect (see: Apache ErrorDocument and Apache Custom Error). The .htaccess example above has multiple examples in it. You can use the following as the generic redirect script to replace 404_redirect.php above.

error_redirect.php

<?php
   $error_url = $_SERVER["REDIRECT_STATUS"] . '/';
   $error_path = $error_url . '.php';

   if ( ! file_exists($error_path)) {
      // this is the default error if a specific error page is not found
      $error_url = '404/';
   }

   header('Location: ' . $error_url);
   exit;
?>

Can I redirect the stdout in python into some sort of string buffer?

from cStringIO import StringIO # Python3 use: from io import StringIO
import sys

old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()

# blah blah lots of code ...

sys.stdout = old_stdout

# examine mystdout.getvalue()

How to manage a redirect request after a jQuery Ajax call

Use the low-level $.ajax() call:

$.ajax({
  url: "/yourservlet",
  data: { },
  complete: function(xmlHttp) {
    // xmlHttp is a XMLHttpRquest object
    alert(xmlHttp.status);
  }
});

Try this for a redirect:

if (xmlHttp.code != 200) {
  top.location.href = '/some/other/page';
}

How to redirect to previous page in Ruby On Rails?

Why does redirect_to(:back) not work for you, why is it a no go?

redirect_to(:back) works like a charm for me. It's just a short cut for redirect_to(request.env['HTTP_REFERER'])

http://apidock.com/rails/ActionController/Base/redirect_to (pre Rails 3) or http://apidock.com/rails/ActionController/Redirecting/redirect_to (Rails 3)

Please note that redirect_to(:back) is being deprecated in Rails 5. You can use

redirect_back(fallback_location: 'something') instead (see http://blog.bigbinary.com/2016/02/29/rails-5-improves-redirect_to_back-with-redirect-back.html)

Redirect with CodeIgniter

Here is .htacess file that hide index file

#RewriteEngine on
#RewriteCond $1 !^(index\.php|images|robots\.txt)
#RewriteRule ^(.*)$ /index.php/$1 [L]

<IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteBase /

        # Removes index.php from ExpressionEngine URLs
        RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
        RewriteCond %{REQUEST_URI} !/system/.* [NC]
        RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]

        # Directs all EE web requests through the site index file
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

Apache redirect to another port

This is working in ISPConfig too. In website list get inside a domain, click to Options tab, add these lines: ;

ProxyPass / http://localhost:8181/
ProxyPassReverse / http://localhost:8181/

Then go to website and wolaa :) This is working HTTPS protocol too.

How to redirect Valgrind's output to a file?

In addition to the other answers (particularly by Lekakis), some string replacements can also be used in the option --log-file= as elaborated in the Valgrind's user manual.

Four replacements were available at the time of writing:

  • %p: Prints the current process ID
    • valgrind --log-file="myFile-%p.dat" <application-name>
  • %n: Prints file sequence number unique for the current process
    • valgrind --log-file="myFile-%p-%n.dat" <application-name>
  • %q{ENV}: Prints contents of the environment variable ENV
    • valgrind --log-file="myFile-%q{HOME}.dat" <application-name>
  • %%: Prints %
    • valgrind --log-file="myFile-%%.dat" <application-name>

How to redirect a url in NGINX

First make sure you have installed Nginx with the HTTP rewrite module. To install this we need to have pcre-library

How to install pcre library

If the above mentioned are done or if you already have them, then just add the below code in your nginx server block

  if ($host !~* ^www\.) {
    rewrite ^(.*)$ http://www.$host$1 permanent;
  }

To remove www from every request you can use

  if ($host = 'www.your_domain.com' ) {
   rewrite  ^/(.*)$  http://your_domain.com/$1  permanent;
  }

so your server block will look like

  server {
            listen       80;
            server_name  test.com;
            if ($host !~* ^www\.) {
                    rewrite ^(.*)$ http://www.$host$1 permanent;
            }
            client_max_body_size   10M;
            client_body_buffer_size   128k;

            root       /home/test/test/public;
            passenger_enabled on;
            rails_env production;

            error_page   500 502 503 504  /50x.html;
            location = /50x.html {
                    root   html;
            }
    }

htaccess redirect to https://www

I used the below code from this website, it works great https://www.freecodecamp.org/news/how-to-redirect-http-to-https-using-htaccess/

_x000D_
_x000D_
RewriteEngine On_x000D_
RewriteCond %{SERVER_PORT} 80_x000D_
RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R,L]
_x000D_
_x000D_
_x000D_

Hope it helps

Using $window or $location to Redirect in AngularJS

I believe the way to do this is $location.url('/RouteTo/Login');

Edit for Clarity

Say my route for my login view was /Login, I would say $location.url('/Login') to navigate to that route.

For locations outside of the Angular app (i.e. no route defined), plain old JavaScript will serve:

window.location = "http://www.my-domain.com/login"

Open another page in php

<?php
    header("Location: index.html");
?>

Just make sure nothing is actually written to the page prior to this code, or it won't work.

Redirecting to a relative URL in JavaScript

<a href="..">no JS needed</a>

.. means parent directory.

.htaccess redirect www to non-www with SSL/HTTPS

RewriteEngine On

RewriteCond %{HTTP_HOST} ^www\.(.*)
RewriteRule ^.*$ https://%1/$1 [R=301,L]

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

This worked for me after much trial and error. Part one is from the user above and will capture www.xxx.yyy and send to https://xxx.yyy

Part 2 looks at entered URL and checks if HTTPS, if not, it sends to HTTPS

Done in this order, it follows logic and no error occurs.

HERE is my FULL version in side htaccess with WordPress:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)
RewriteRule ^.*$ https://%1/$1 [R=301,L]

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]


# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

response.sendRedirect() from Servlet to JSP does not seem to work

You can use this:

response.sendRedirect(String.format("%s%s", request.getContextPath(), "/views/equipment/createEquipment.jsp"));

The last part is your path in your web-app

Redirecting a page using Javascript, like PHP's Header->Location

You application of js and php in totally invalid.

You have to understand a fact that JS runs on clientside, once the page loads it does not care, whether the page was a php page or jsp or asp. It executes of DOM and is related to it only.

However you can do something like this

var newLocation = "<?php echo $newlocation; ?>";
window.location = newLocation;

You see, by the time the script is loaded, the above code renders into different form, something like this

var newLocation = "your/redirecting/page.php";
window.location = newLocation;

Like above, there are many possibilities of php and js fusions and one you are doing is not one of them.

How to store standard error in a variable

In zsh:

{ . ./useless.sh > /dev/tty } 2>&1 | read ERROR
$ echo $ERROR
( your message )

In the shell, what does " 2>&1 " mean?

That construct sends the standard error stream (stderr) to the current location of standard output (stdout) - this currency issue appears to have been neglected by the other answers.

You can redirect any output handle to another by using this method but it's most often used to channel stdout and stderr streams into a single stream for processing.

Some examples are:

# Look for ERROR string in both stdout and stderr.
foo 2>&1 | grep ERROR

# Run the less pager without stderr screwing up the output.
foo 2>&1 | less

# Send stdout/err to file (with append) and terminal.
foo 2>&1 |tee /dev/tty >>outfile

# Send stderr to normal location and stdout to file.
foo >outfile1 2>&1 >outfile2

Note that that last one will not direct stderr to outfile2 - it redirects it to what stdout was when the argument was encountered (outfile1) and then redirects stdout to outfile2.

This allows some pretty sophisticated trickery.

How to send redirect to JSP page in Servlet

Please use the below code and let me know

try{

            Class.forName("com.mysql.jdbc.Driver").newInstance();
            con = DriverManager.getConnection(c, "root", "MyNewPass");
            System.out.println("connection done");


            PreparedStatement ps=con.prepareStatement(q);
            System.out.println(q);
            rs=ps.executeQuery();
            System.out.println("done2");
            while (rs.next()) {
               System.out.println(rs.getString(1));
               System.out.println(rs.getString(2));

            }

         response.sendRedirect("myfolder/welcome.jsp"); // wherever you wanna redirect this page.

        }
            catch (Exception e) {
                // TODO: handle exception
                System.out.println("Failed");
            }

myfolder/welcome.jsp is the relative path of your jsp page. So, change it as per your jsp page path.

Redirect using AngularJS

Don't forget to inject $location into controller.

Get final URL after curl is redirected

I'm not sure how to do it with curl, but libwww-perl installs the GET alias.

$ GET -S -d -e http://google.com
GET http://google.com --> 301 Moved Permanently
GET http://www.google.com/ --> 302 Found
GET http://www.google.ca/ --> 200 OK
Cache-Control: private, max-age=0
Connection: close
Date: Sat, 19 Jun 2010 04:11:01 GMT
Server: gws
Content-Type: text/html; charset=ISO-8859-1
Expires: -1
Client-Date: Sat, 19 Jun 2010 04:11:01 GMT
Client-Peer: 74.125.155.105:80
Client-Response-Num: 1
Set-Cookie: PREF=ID=a1925ca9f8af11b9:TM=1276920661:LM=1276920661:S=ULFrHqOiFDDzDVFB; expires=Mon, 18-Jun-2012 04:11:01 GMT; path=/; domain=.google.ca
Title: Google
X-XSS-Protection: 1; mode=block

Python + Django page redirect

If you want to redirect a whole subfolder, the url argument in RedirectView is actually interpolated, so you can do something like this in urls.py:

from django.conf.urls.defaults import url
from django.views.generic import RedirectView

urlpatterns = [
    url(r'^old/(?P<path>.*)$', RedirectView.as_view(url='/new_path/%(path)s')),
]

The ?P<path> you capture will be fed into RedirectView. This captured variable will then be replaced in the url argument you gave, giving us /new_path/yay/mypath if your original path was /old/yay/mypath.

You can also do ….as_view(url='…', query_string=True) if you want to copy the query string over as well.

PHP session lost after redirect

If you are using session_set_cookie_params() you might want to check if you are passing the fourth param $secure as true. If you are, then you need to access the url using https.

The $secure param being true means the Session is only available within a secure request. This might affect you locally more than in stage or production environments.

Mentioning it because I just spent most of today trying to find this issue, and this is what solved it for me. I was just added to this project and no one mentioned that it required https.

So you can either use https locally, or you can set the $secure param to FALSE and then use http locally. Just be sure to set it back to true when you push your changes up.

Depending on your local server, you might have to edit DocumentRoot in the httpd-ssl.conf of the server so that your local url is served https.

window.location (JS) vs header() (PHP) for redirection

PHP redirects are better if you can as with the JavaScript one you're causing the client to load the page before the redirect, whereas with the PHP one it sends the proper header.

However the PHP shouldn't go in the <head>, it should go before any output is sent to the client, as to do otherwise will cause errors.

Using <meta> tags have the same issue as Javascript in causing the initial page to load before doing the redirect. Server-side redirects are almost always better, if you can use them.

jQuery and AJAX response header

 var geturl;
  geturl = $.ajax({
    type: "GET",
    url: 'http://....',
    success: function () {
      alert("done!"+ geturl.getAllResponseHeaders());
    }
  });

How to redirect all HTTP requests to HTTPS

If you are using Apache, mod_rewrite is the easiest solution, and has a lot of documentation online how to do that. For example: http://www.askapache.com/htaccess/http-https-rewriterule-redirect.html

Is there a way to follow redirects with command line cURL?

I had a similar problem. I am posting my solution here because I believe it might help one of the commenters.

For me, the obstacle was that the page required a login and then gave me a new URL through javascript. Here is what I had to do:

curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <URL>

Note that j_username and j_password is the name of the fields for my website's login form. You will have to open the source of the webpage to see what the 'name' of the username field and the 'name' of the password field is in your case. After that I go an html file with java script in which the new URL was embedded. After parsing this out just resubmit with the new URL:

curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <NEWURL>

.htaccess rewrite to redirect root URL to subdirectory

I think the main problems with the code you posted are:

  • the first line matches on a host beginning with strictly sample.com, so www.sample.com doesn't match.

  • the second line wants at least one character, followed by www.sample.com which also doesn't match (why did you escape the first w?)

  • none of the included rules redirect to the url you specified in your goal (plus, sample is misspelled as samle, but that's irrelevant).

For reference, here's the code you currently have:

Options +FollowSymlinks
RewriteEngine on

RewriteCond %{HTTP_HOST} ^sample.com$
RewriteRule (.*) http://www.sample.com/$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^(.+)\www.sample\.com$
RewriteRule ^/(.*)$ /samle/%1/$1 [L]

Redirect to Action by parameter mvc

Try this,

return RedirectToAction("ActionEventName", "Controller", new { ID = model.ID, SiteID = model.SiteID });

Here i mention you are pass multiple values or model also. That's why here i mention that.

apache redirect from non www to www

If using the above solution of two <VirtualHost *:80> blocks with different ServerNames...

<VirtualHost *:80>
    ServerName example.com
    Redirect permanent / http://www.example.com/
</VirtualHost>
<VirtualHost *:80>
    ServerName www.example.com
</VirtualHost>

... then you must set NameVirtualHost On as well.

If you don't do this, Apache doesn't allow itself to use the different ServerNames to distinguish the blocks, so you get this error message:

[warn] _default_ VirtualHost overlap on port 80, the first has precedence

...and either no redirection happens, or you have an infinite redirection loop, depending on which block you put first.

Redirect to external URI from ASP.NET MVC controller

If you're talking about ASP.NET MVC then you should have a controller method that returns the following:

return Redirect("http://www.google.com");

Otherwise we need more info on the error you're getting in the redirect. I'd step through to make sure the url isn't empty.

Page redirect after certain time PHP

You can try this:

header('Refresh: 10; URL=http://yoursite.com/page.php');

Where 10 is in seconds.

Command output redirect to file and terminal

Yes, if you redirect the output, it won't appear on the console. Use tee.

ls 2>&1 | tee /tmp/ls.txt

Send string to stdin

aliases can and can't process piped stdin...

Here we create 3 lines of output

$ echo -e "line 1\nline 2\nline 3"
line 1
line 2
line 3

We then pipe the output to stdin of the sed command to put them all on one line

$ echo -e "line 1\nline 2\nline 3" |  sed -e ":a;N;\$!ba ;s?\n? ?g"
line 1 line 2 line 3

If we define an alias of the same sed command

$ alias oline='sed -e ":a;N;\$!ba ;s?\n? ?g"'

We can pipe the output to the stdin of the alias and it behaves exactly the same

$ echo -e "line 1\nline 2\nline 3" |  oline
line 1 line 2 line 3

The problem arises when we try to define the alias as a function

$ alias oline='function _oline(){ sed -e ":a;N;\$!ba ;s?\n? ?g";}_oline'

Defining the alias as a funstion breaks the pipe

$ echo -e "line 1\nline 2\nline 3" |  oline
>

How do I redirect to the previous action in ASP.NET MVC?

try:

public ActionResult MyNextAction()
{
    return Redirect(Request.UrlReferrer.ToString());
}

alternatively, touching on what darin said, try this:

public ActionResult MyFirstAction()
{
    return RedirectToAction("MyNextAction",
        new { r = Request.Url.ToString() });
}

then:

public ActionResult MyNextAction()
{
    return Redirect(Request.QueryString["r"]);
}

JQuery Redirect to URL after specified time

I have made a simple demo that prompts for X number of seconds and redirects to set url. If you don't want to wait until the end of the count, just click on the counter to redirect with no time. Simple counter that will count down while pulsing time in the midle of the page. You can run it onclick or while some page is loaded.

LIVE DEMO ONLOAD

LIVE DEMO ONCLICK

I also made github repo for this: https://github.com/GlupiJas/redirect-counter-plugin

JS CODE EXAMPLE:

// FUNCTION CODE
function gjCountAndRedirect(secounds, url)
{

        $('#gj-counter-num').text(secounds);

        $('#gj-counter-box').show();

    var interval = setInterval(function()
    {

        secounds = secounds - 1;

        $('#gj-counter-num').text(secounds);

        if(secounds == 0)
        {

            clearInterval(interval);
            window.location = url;
            $('#gj-counter-box').hide();

        }

    }, 1000);

    $('#gj-counter-box').click(function() //comment it out -if you dont want to allo count skipping
    {
        clearInterval(interval);
        window.location = url;

    });
}

// USE EXAMPLE
$(document).ready(function() {
    //var
    var gjCountAndRedirectStatus = false; //prevent from seting multiple Interval

    //call
    $('h1').click(function(){
        if(gjCountAndRedirectStatus == false)
        {
            gjCountAndRedirect(10, document.URL);
            gjCountAndRedirectStatus = true;
        }
    });

});

How to pass model attributes from one Spring MVC controller to another controller?

Using just redirectAttributes.addFlashAttribute(...) -> "redirect:..." worked as well, didn't have to "reinsert" the model attribute.

Thanks, aborskiy!

How can I do an asc and desc sort using underscore.js?

Underscore Mixins

Extending on @emil_lundberg's answer, you can also write a "mixin" if you're using Underscore to make a custom function for sorting if it's a kind of sorting you might repeat in an application somewhere.

For example, maybe you have a controller or view sorting results with sort order of "ASC" or "DESC", and you want to toggle between that sort, you could do something like this:

Mixin.js

_.mixin({
    sortByOrder: function(stooges, prop, order) {
      if (String(order) === "desc") {
          return _.sortBy(stooges, prop).reverse();
      } else if (String(order) === "asc") {
          return _.sortBy(stooges, prop);
      } else {
          return stooges;
      }
    }
})

Usage Example

var sort_order = "asc";
var stooges = [
  {name: 'moe', age: 40}, 
  {name: 'larry', age: 50}, 
  {name: 'curly', age: 60},
  {name: 'July', age: 35},
  {name: 'mel', age: 38}
 ];

_.mixin({
    sortByOrder: function(stooges, prop, order) {
    if (String(order) === "desc") {
        return _.sortBy(stooges, prop).reverse();
    } else if (String(order) === "asc") {
        return _.sortBy(stooges, prop);
    } else {
        return stooges;
    }
  }
})


// find elements
var banner = $("#banner-message");
var sort_name_btn = $("button.sort-name");
var sort_age_btn = $("button.sort-age");

function showSortedResults(results, sort_order, prop) {
    banner.empty();
    banner.append("<p>Sorting: " + prop + ', ' + sort_order + "</p><hr>")
  _.each(results, function(r) {
    banner.append('<li>' + r.name + ' is '+ r.age + ' years old.</li>');
  }) 
}

// handle click and add class
sort_name_btn.on("click", function() {
  sort_order = (sort_order === "asc") ? "desc" : "asc"; 
    var sortedResults = _.sortByOrder(stooges, 'name', sort_order);
  showSortedResults(sortedResults, sort_order, 'name');
})

sort_age_btn.on('click', function() {
    sort_order = (sort_order === "asc") ? "desc" : "asc"; 
    var sortedResults = _.sortByOrder(stooges, 'age', sort_order);
  showSortedResults(sortedResults, sort_order, 'age');
})

Here's a JSFiddle demonstrating this: JSFiddle for SortBy Mixin

DateTime.TryParse issue with dates of yyyy-dd-MM format

You need to use the ParseExact method. This takes a string as its second argument that specifies the format the datetime is in, for example:

// Parse date and time with custom specifier.
dateString = "2011-29-01 12:00 am";
format = "yyyy-dd-MM h:mm tt";
try
{
   result = DateTime.ParseExact(dateString, format, provider);
   Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException)
{
   Console.WriteLine("{0} is not in the correct format.", dateString);
}

If the user can specify a format in the UI, then you need to translate that to a string you can pass into this method. You can do that by either allowing the user to enter the format string directly - though this means that the conversion is more likely to fail as they will enter an invalid format string - or having a combo box that presents them with the possible choices and you set up the format strings for these choices.

If it's likely that the input will be incorrect (user input for example) it would be better to use TryParseExact rather than use exceptions to handle the error case:

// Parse date and time with custom specifier.
dateString = "2011-29-01 12:00 am";
format = "yyyy-dd-MM h:mm tt";
DateTime result;
if (DateTime.TryParseExact(dateString, format, provider, DateTimeStyles.None, out result))
{
   Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
else
{
   Console.WriteLine("{0} is not in the correct format.", dateString);
}

A better alternative might be to not present the user with a choice of date formats, but use the overload that takes an array of formats:

// A list of possible American date formats - swap M and d for European formats
string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", 
                   "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", 
                   "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", 
                   "M/d/yyyy h:mm", "M/d/yyyy h:mm", 
                   "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm",
                   "MM/d/yyyy HH:mm:ss.ffffff" };
string dateString; // The string the date gets read into

try
{
    dateValue = DateTime.ParseExact(dateString, formats, 
                                    new CultureInfo("en-US"), 
                                    DateTimeStyles.None);
    Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
}
catch (FormatException)
{
    Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
}                                               

If you read the possible formats out of a configuration file or database then you can add to these as you encounter all the different ways people want to enter dates.

Why can't non-default arguments follow default arguments?

SyntaxError: non-default argument follows default argument

If you were to allow this, the default arguments would be rendered useless because you would never be able to use their default values, since the non-default arguments come after.

In Python 3 however, you may do the following:

def fun1(a="who is you", b="True", *, x, y):
    pass

which makes x and y keyword only so you can do this:

fun1(x=2, y=2)

This works because there is no longer any ambiguity. Note you still can't do fun1(2, 2) (that would set the default arguments).

Reading Email using Pop3 in C#

HigLabo.Mail is easy to use. Here is a sample usage:

using (Pop3Client cl = new Pop3Client()) 
{ 
    cl.UserName = "MyUserName"; 
    cl.Password = "MyPassword"; 
    cl.ServerName = "MyServer"; 
    cl.AuthenticateMode = Pop3AuthenticateMode.Pop; 
    cl.Ssl = false; 
    cl.Authenticate(); 
    ///Get first mail of my mailbox 
    Pop3Message mg = cl.GetMessage(1); 
    String MyText = mg.BodyText; 
    ///If the message have one attachment 
    Pop3Content ct = mg.Contents[0];         
    ///you can save it to local disk 
    ct.DecodeData("your file path"); 
} 

you can get it from https://github.com/higty/higlabo or Nuget [HigLabo]

PHP Accessing Parent Class Variable

With parent::$bb; you try to retrieve the static constant defined with the value of $bb.

Instead, do:

echo $this->bb;

Note: you don't need to call parent::_construct if B is the only class that calls it. Simply don't declare __construct in B class.

How to leave/exit/deactivate a Python virtualenv

Use:

$ deactivate 

If this doesn't work, try

$ source deactivate

Anyone who knows how Bash source works will think that's odd, but some wrappers/workflows around virtualenv implement it as a complement/counterpart to source activate. Your mileage may vary.

How to get the last N rows of a pandas DataFrame?

This is because of using integer indices (ix selects those by label over -3 rather than position, and this is by design: see integer indexing in pandas "gotchas"*).

*In newer versions of pandas prefer loc or iloc to remove the ambiguity of ix as position or label:

df.iloc[-3:]

see the docs.

As Wes points out, in this specific case you should just use tail!

Iterating on a file doesn't work the second time

Of course. That is normal and sane behaviour. Instead of closing and re-opening, you could rewind the file.

Resolving require paths with webpack

For future reference, webpack 2 removed everything but modules as a way to resolve paths. This means root will not work.

https://gist.github.com/sokra/27b24881210b56bbaff7#resolving-options

The example configuration starts with:

{
  modules: [path.resolve(__dirname, "app"), "node_modules"]
  // (was split into `root`, `modulesDirectories` and `fallback` in the old options)

When to use Comparable and Comparator

If you own the class better go with Comparable. Generally Comparator is used if you dont own the class but you have to use it a TreeSet or TreeMap because Comparator can be passed as a parameter in the conctructor of TreeSet or TreeMap. You can see how to use Comparator and Comparable in http://preciselyconcise.com/java/collections/g_comparator.php

Latex Multiple Linebreaks

\\\\

This works on pdfLatex. It creates 2 new lines for you.

What is the purpose of the "role" attribute in HTML?

As I understand it, roles were initially defined by XHTML but were deprecated. However, they are now defined by HTML 5, see here: https://www.w3.org/WAI/PF/aria/roles#abstract_roles_header

The purpose of the role attribute is to identify to parsing software the exact function of an element (and its children) as part of a web application. This is mostly as an accessibility thing for screen readers, but I can also see it as being useful for embedded browsers and screen scrapers. In order to be useful to the unusual HTML client, the attribute needs to be set to one of the roles from the spec I linked. If you make up your own, this 'future' functionality can't work - a comment would be better.

Practicalities here: http://www.accessibleculture.org/articles/2011/04/html5-aria-2011/

Is there a way to know your current username in mysql?

You can find the current user name with CURRENT_USER() function in MySQL.

for Ex: SELECT CURRENT_USER();

But CURRENT_USER() will not always return the logged in user. So in case you want to have the logged in user, then use SESSION_USER() instead.

how to change php version in htaccess in server

An addition to the current marked answer:

Place the addhandler inside the following scope, like so:

<IfModule mod_rewrite.c>

   AddHandler application/x-httpd-php71 .php
   RewriteEngine On

   ....

</IfModule>

How to add image for button in android?

Simply use ImageButton View and set image for it:`

 <ImageButton
    android:id="@+id/searchImageButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"
    android:src="@android:drawable/ic_menu_search" />

What is the Java ?: operator called and what does it do?

Actually it can take more than 3 arguments. For instance if we want to check wether a number is positive, negative or zero we can do this:

String m= num > 0 ? "is a POSITIVE NUMBER.": num < 0 ?"is a NEGATIVE NUMBER." :"IT's ZERO.";

which is better than using if, else if, else.

How to add multiple font files for the same font?

nowadays,2017-12-17. I don't find any description about Font-property-order‘s necessity in spec. And I test in chrome always works whatever the order is.

@font-face {
  font-family: 'Font Awesome 5 Free';
  font-weight: 900;
  src: url('#{$fa-font-path}/fa-solid-900.eot');
  src: url('#{$fa-font-path}/fa-solid-900.eot?#iefix') format('embedded-opentype'),
  url('#{$fa-font-path}/fa-solid-900.woff2') format('woff2'),
  url('#{$fa-font-path}/fa-solid-900.woff') format('woff'),
  url('#{$fa-font-path}/fa-solid-900.ttf') format('truetype'),
  url('#{$fa-font-path}/fa-solid-900.svg#fontawesome') format('svg');
}

@font-face {
  font-family: 'Font Awesome 5 Free';
  font-weight: 400;
  src: url('#{$fa-font-path}/fa-regular-400.eot');
  src: url('#{$fa-font-path}/fa-regular-400.eot?#iefix') format('embedded-opentype'),
  url('#{$fa-font-path}/fa-regular-400.woff2') format('woff2'),
  url('#{$fa-font-path}/fa-regular-400.woff') format('woff'),
  url('#{$fa-font-path}/fa-regular-400.ttf') format('truetype'),
  url('#{$fa-font-path}/fa-regular-400.svg#fontawesome') format('svg');
}

Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'

If you are using PHPMyAdmin You can be solved this issue by doing this:

CAUTION: Don't use this solution if you want to maintain existing records in your table.

Step 1: Select database export method to custom:

enter image description here

Step 2: Please make sure to check truncate table before insert in data creation options:

enter image description here

Now you are able to import this database successfully.

Task.Run with Parameter(s)?

Idea is to avoid using a Signal like above. Pumping int values into a struct prevents those values from changing (in the struct). I had the following Problem: loop var i would change before DoSomething(i) was called (i was incremented at end of loop before ()=> DoSomething(i,ii) was called). With the structs it doesn't happen anymore. Nasty bug to find: DoSomething(i, ii) looks great, but never sure if it gets called each time with a different value for i (or just a 100 times with i=100), hence -> struct

struct Job { public int P1; public int P2; }
…
for (int i = 0; i < 100; i++) {
    var job = new Job { P1 = i, P2 = i * i}; // structs immutable...
    Task.Run(() => DoSomething(job));
}

How to get a DOM Element from a JQuery Selector

If you need to interact directly with the DOM element, why not just use document.getElementById since, if you are trying to interact with a specific element you will probably know the id, as assuming that the classname is on only one element or some other option tends to be risky.

But, I tend to agree with the others, that in most cases you should learn to do what you need using what jQuery gives you, as it is very flexible.

UPDATE: Based on a comment: Here is a post with a nice explanation: http://www.mail-archive.com/[email protected]/msg04461.html

$(this).attr("checked") ? $(this).val() : 0

This will return the value if it's checked, or 0 if it's not.

$(this).val() is just reaching into the dom and getting the attribute "value" of the element, whether or not it's checked.

How to fix committing to the wrong Git branch?

For me, this was solved by reverting the commit I had pushed, then cherry-picking that commit to the other branch.

git checkout branch_that_had_the_commit_originally
git revert COMMIT-HASH
git checkout branch_that_was_supposed_to_have_the_commit
git cherry pick COMMIT-HASH

You can use git log to find the correct hash, and you can push these changes whenever you like!

Convert DataTable to IEnumerable<T>

Nothing wrong with that implementation. You might give the yield keyword a shot, see how you like it:

private IEnumerable<TankReading> ConvertToTankReadings(DataTable dataTable)
    {
        foreach (DataRow row in dataTable.Rows)
        {
            yield return new TankReading
                                  {
                                      TankReadingsID = Convert.ToInt32(row["TRReadingsID"]),
                                      TankID = Convert.ToInt32(row["TankID"]),
                                      ReadingDateTime = Convert.ToDateTime(row["ReadingDateTime"]),
                                      ReadingFeet = Convert.ToInt32(row["ReadingFeet"]),
                                      ReadingInches = Convert.ToInt32(row["ReadingInches"]),
                                      MaterialNumber = row["MaterialNumber"].ToString(),
                                      EnteredBy = row["EnteredBy"].ToString(),
                                      ReadingPounds = Convert.ToDecimal(row["ReadingPounds"]),
                                      MaterialID = Convert.ToInt32(row["MaterialID"]),
                                      Submitted = Convert.ToBoolean(row["Submitted"]),
                                  };
        }

    }

Also the AsEnumerable isn't necessary, as List<T> is already an IEnumerable<T>

Hibernate: hbm2ddl.auto=update in production?

Applications' schema may evolve in time; if you have several installations, which may be at different versions, you should have some way to ensure that your application, some kind of tool or script is capable of migrating schema and data from one version stepwise to any following one.

Having all your persistence in Hibernate mappings (or annotations) is a very good way for keeping schema evolution under control.

You should consider that schema evolution has several aspects to be considered:

  1. evolution of the database schema in adding more columns and tables

  2. dropping of old columns, tables and relations

  3. filling new columns with defaults

Hibernate tools are important in particular in case (like in my experience) you have different versions of the same application on many different kinds of databases.

Point 3 is very sensitive in case you are using Hibernate, as in case you introduce a new boolean valued property or numeric one, if Hibernate will find any null value in such columns, if will raise an exception.

So what I would do is: do indeed use the Hibernate tools capacity of schema update, but you must add alongside of it some data and schema maintenance callback, like for filling defaults, dropping no longer used columns, and similar. In this way you get the advantages (database independent schema update scripts and avoiding duplicated coding of the updates, in peristence and in scripts) but you also cover all the aspects of the operation.

So for example if a version update consists simply in adding a varchar valued property (hence column), which may default to null, with auto update you'll be done. Where more complexity is necessary, more work will be necessary.

This is assuming that the application when updated is capable of updating its schema (it can be done), which also means that it must have the user rights to do so on the schema. If the policy of the customer prevents this (likely Lizard Brain case), you will have to provide the database - specific scripts.

Regular expression for not allowing spaces in the input field

Use + plus sign (Match one or more of the previous items),

var regexp = /^\S+$/

How to set adaptive learning rate for GradientDescentOptimizer?

Tensorflow provides an op to automatically apply an exponential decay to a learning rate tensor: tf.train.exponential_decay. For an example of it in use, see this line in the MNIST convolutional model example. Then use @mrry's suggestion above to supply this variable as the learning_rate parameter to your optimizer of choice.

The key excerpt to look at is:

# Optimizer: set up a variable that's incremented once per batch and
# controls the learning rate decay.
batch = tf.Variable(0)

learning_rate = tf.train.exponential_decay(
  0.01,                # Base learning rate.
  batch * BATCH_SIZE,  # Current index into the dataset.
  train_size,          # Decay step.
  0.95,                # Decay rate.
  staircase=True)
# Use simple momentum for the optimization.
optimizer = tf.train.MomentumOptimizer(learning_rate,
                                     0.9).minimize(loss,
                                                   global_step=batch)

Note the global_step=batch parameter to minimize. That tells the optimizer to helpfully increment the 'batch' parameter for you every time it trains.

Dropping Unique constraint from MySQL table

while dropping unique key we use index

ALTER TABLE tbl
DROP INDEX  unique_address;

Batch - Echo or Variable Not Working

Try the following (note that there should not be a space between the VAR, =, and GREG).

SET VAR=GREG
ECHO %VAR%
PAUSE

How can I assign an ID to a view programmatically?

You can just use the View.setId(integer) for this. In the XML, even though you're setting a String id, this gets converted into an integer. Due to this, you can use any (positive) Integer for the Views you add programmatically.

According to View documentation

The identifier does not have to be unique in this view's hierarchy. The identifier should be a positive number.

So you can use any positive integer you like, but in this case there can be some views with equivalent id's. If you want to search for some view in hierarchy calling to setTag with some key objects may be handy.

Credits to this answer.

How do I remove the horizontal scrollbar in a div?

Removes the HORIZONTAL scrollbar while ALLOWING for scroll and NOTHING more.

&::-webkit-scrollbar:horizontal {
  height: 0;
  width: 0;
  display: none;
}

&::-webkit-scrollbar-thumb:horizontal {
  display: none;
}

How to pass command line argument to gnuplot?

@vagoberto's answer seems the best IMHO if you need positional arguments, and I have a small improvement to add.

vagoberto's suggestion:

#!/usr/local/bin/gnuplot --persist

THIRD=ARG3
print "script name        : ", ARG0
print "first argument     : ", ARG1
print "third argument     : ", THIRD 
print "number of arguments: ", ARGC 

which gets called by:

$ gnuplot -c script.gp one two three four five
script name        : script.gp
first argument     : one
third argument     : three
number of arguments: 5

for those lazy typers like myself, one could make the script executable (chmod 755 script.gp)

then use the following:

#!/usr/bin/env gnuplot -c

THIRD=ARG3
print "script name        : ", ARG0
print "first argument     : ", ARG1
print "third argument     : ", THIRD
print "number of arguments: ", ARGC

and execute it as:

$ ./imb.plot a b c d
script name        : ./imb.plot
first argument     : a
third argument     : c
number of arguments: 4

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

Why involve Notepad?

Sub ReplaceStringInFile()

Dim sBuf As String
Dim sTemp As String
Dim iFileNum As Integer
Dim sFileName As String

' Edit as needed
sFileName = "C:\Temp\test.txt"

iFileNum = FreeFile
Open sFileName For Input As iFileNum

Do Until EOF(iFileNum)
    Line Input #iFileNum, sBuf
    sTemp = sTemp & sBuf & vbCrLf
Loop
Close iFileNum

sTemp = Replace(sTemp, "THIS", "THAT")

iFileNum = FreeFile
Open sFileName For Output As iFileNum
Print #iFileNum, sTemp
Close iFileNum

End Sub

Bootstrap Alert Auto Close

Tiggers automatically and manually when needed

$(function () {
    TriggerAlertClose();
});

function TriggerAlertClose() {
    window.setTimeout(function () {
        $(".alert").fadeTo(1000, 0).slideUp(1000, function () {
            $(this).remove();
        });
    }, 5000);
}

How to split a string in Haskell?

Example in the ghci:

>  import qualified Text.Regex as R
>  R.splitRegex (R.mkRegex "x") "2x3x777"
>  ["2","3","777"]

How to check if an integer is within a range of numbers in PHP?

using a switch case

    switch ($num){

        case ($num>= $value1 && $num<= $value2): 
            echo "within range 1";
        break;
        case ($num>= $value3 && $num<= $value4): 
            echo "within range 2";
        break;
        .
        .
        .
        .
        .

        default: //default
            echo "within no range";
        break;
     }

C++ IDE for Macs

Xcode is free and good, which is lucky because it's pretty much the only option on the Mac.

How do I search a Perl array for a matching string?

For just a boolean match result or for a count of occurrences, you could use:

use 5.014; use strict; use warnings;
my @foo=('hello', 'world', 'foo', 'bar', 'hello world', 'HeLlo');
my $patterns=join(',',@foo);
for my $str (qw(quux world hello hEllO)) {
    my $count=map {m/^$str$/i} @foo;
    if ($count) {
        print "I found '$str' $count time(s) in '$patterns'\n";
    } else {
        print "I could not find '$str' in the pattern list\n"
    };
}

Output:

I could not find 'quux' in the pattern list
I found 'world' 1 time(s) in 'hello,world,foo,bar,hello world,HeLlo'
I found 'hello' 2 time(s) in 'hello,world,foo,bar,hello world,HeLlo'
I found 'hEllO' 2 time(s) in 'hello,world,foo,bar,hello world,HeLlo'

Does not require to use a module.
Of course it's less "expandable" and versatile as some code above.
I use this for interactive user answers to match against a predefined set of case unsensitive answers.

React: Expected an assignment or function call and instead saw an expression

You must return something

instead of this (this is not the right way)

const def = (props) => { <div></div> };

try

const def = (props) => ( <div></div> );

or use return statement

const def = (props) => { return  <div></div> };

Getting ORA-01031: insufficient privileges while querying a table instead of ORA-00942: table or view does not exist

for ORA-01031: insufficient privileges. Some of the more common causes are:

  1. You tried to change an Oracle username or password without having the appropriate privileges.
  2. You tried to perform an UPDATE to a table, but you only have SELECT access to the table.
  3. You tried to start up an Oracle database using CONNECT INTERNAL.
  4. You tried to install an Oracle database without having the appropriate privileges to the operating-system.

The option(s) to resolve this Oracle error are:

  1. You can have the Oracle DBA grant you the appropriate privileges that you are missing.
  2. You can have the Oracle DBA execute the operation for you.
  3. If you are having trouble starting up Oracle, you may need to add the Oracle user to the dba group.

For ORA-00942: table or view does not exist. You tried to execute a SQL statement that references a table or view that either does not exist, that you do not have access to, or that belongs to another schema and you didn't reference the table by the schema name.

If this error occurred because the table or view does not exist, you will need to create the table or view.

You can check to see if the table exists in Oracle by executing the following SQL statement:

select *
from all_objects
where object_type in ('TABLE','VIEW')
and object_name = 'OBJECT_NAME';

For example, if you are looking for a suppliers table, you would execute:

select *
from all_objects
where object_type in ('TABLE','VIEW')
and object_name = 'SUPPLIERS';

OPTION #2

If this error occurred because you do not have access to the table or view, you will need to have the owner of the table/view, or a DBA grant you the appropriate privileges to this object.

OPTION #3

If this error occurred because the table/view belongs to another schema and you didn't reference the table by the schema name, you will need to rewrite your SQL to include the schema name.

For example, you may have executed the following SQL statement:

select *
from suppliers;

But the suppliers table is not owned by you, but rather, it is owned by a schema called app, you could fix your SQL as follows:

select *
from app.suppliers;

If you do not know what schema the suppliers table/view belongs to, you can execute the following SQL to find out:

select owner
from all_objects
where object_type in ('TABLE','VIEW')
and object_name = 'SUPPLIERS';

This will return the schema name who owns the suppliers table.

PHP not displaying errors even though display_errors = On

When running PHP on windows with ISS there are some configuration settings in ISS that need to be set to prevent generic default pages from being shown.

1) Double click on FastCGISettings, click on PHP then Edit. Set StandardErrorMode to ReturnStdErrLn500.

StandardErrorMode

2) Go the the site, double click on the Error Pages, click on the 500 status, click Edit Feature Settings, Change Error Responses to Detailed Errors, click ok

Change Error Responses to Detailed Errors

Unit Testing: DateTime.Now

One clean way to do this is to inject VirtualTime. It allows you to control time. First install VirtualTime

Install-Package VirtualTime

That allows to, for example, make time that moves 5 times faster on all calls to DateTime.Now or UtcNow

var DateTime = DateTime.Now.ToVirtualTime(5);

To make time move slower , eg 5 times slower do

var DateTime = DateTime.Now.ToVirtualTime(0.5);

To make time stand still do

var DateTime = DateTime.Now.ToVirtualTime(0);

Moving backwards in time is not tested yet

Here are a sample test:

[TestMethod]
public void it_should_make_time_move_faster()
{
    int speedOfTimePerMs = 1000;
    int timeToPassMs = 3000;
    int expectedElapsedVirtualTime = speedOfTimePerMs * timeToPassMs;
    DateTime whenTimeStarts = DateTime.Now;
    ITime time = whenTimeStarts.ToVirtualTime(speedOfTimePerMs);
    Thread.Sleep(timeToPassMs);
    DateTime expectedTime = DateTime.Now.AddMilliseconds(expectedElapsedVirtualTime - timeToPassMs);
    DateTime virtualTime = time.Now;

    Assert.IsTrue(TestHelper.AreEqualWithinMarginOfError(expectedTime, virtualTime, MarginOfErrorMs));
}

You can check out more tests here:

https://github.com/VirtualTime/VirtualTime/blob/master/VirtualTimeLib.Tests/when_virtual_time_is_used.cs

What DateTime.Now.ToVirtualTime extension gives you is an instance of ITime which you pass to a method / class that depends on ITime. some DateTime.Now.ToVirtualTime is setup in the DI container of your choice

Here is another example injecting into a class contrustor

public class AlarmClock
{
    private ITime DateTime;
    public AlarmClock(ITime dateTime, int numberOfHours)
    {
        DateTime = dateTime;
        SetTime = DateTime.UtcNow.AddHours(numberOfHours);
        Task.Run(() =>
        {
            while (!IsAlarmOn)
            {
                IsAlarmOn = (SetTime - DateTime.UtcNow).TotalMilliseconds < 0;
            }
        });
    }
    public DateTime SetTime { get; set; }
    public bool IsAlarmOn { get; set; }
}

[TestMethod]
public void it_can_be_injected_as_a_dependency()
{
    //virtual time has to be 1000*3.75 faster to get to an hour 
    //in 1000 ms real time
    var dateTime = DateTime.Now.ToVirtualTime(1000 * 3.75);
    var numberOfHoursBeforeAlarmSounds = 1;
    var alarmClock = new AlarmClock(dateTime, numberOfHoursBeforeAlarmSounds);
    Assert.IsFalse(alarmClock.IsAlarmOn);
    System.Threading.Thread.Sleep(1000);
    Assert.IsTrue(alarmClock.IsAlarmOn);
}

node.js: read a text file into an array. (Each line an item in the array.)

js:

var array = fs.readFileSync('file.txt', 'utf8').split('\n');

ts:

var array = fs.readFileSync('file.txt', 'utf8').toString().split('\n');

"unable to locate adb" using Android Studio

(I am using Android Studio 3.0.1)

  1. I downloaded "SDK Platform-Tools" from https://developer.android.com/studio/releases/platform-tools
  2. Copied 'adb.exe' to C:\Users\user\AppData\Local\Android\Sdk\platform-tools.
  3. Then I got no errors when running the app.
  4. I also added C:\Users\user\AppData\Local\Android\Sdk\platform-tools\adb.exe to the exception list of my anti-virus tool

Copy/Paste from Excel to a web page

Digging this up, in case anyone comes across it in the future. I used the above code as intended, but then ran into an issue displaying the table after it had been submitted to a database. It's much easier once you've stored the data to use PHP to replace the new lines and tabs in your query. You may perform the replace upon submission, $_POST[request] would be the name of your textarea:

$postrequest = trim($_POST[request]);
$dirty = array("\n", "\t");
$clean = array('</tr><tr><td>', '</td><td>');
$request = str_replace($dirty, $clean, $postrequest);

Now just insert $request into your database, and it will be stored as an HTML table.

Invoke a second script with arguments from a script

Much simpler actually:

Method 1:

Invoke-Expression $scriptPath $argumentList

Method 2:

& $scriptPath $argumentList

Method 3:

$scriptPath $argumentList

If you have spaces in your scriptPath, don't forget to escape them `"$scriptPath`"

LDAP Authentication using Java

// this class will authenticate LDAP UserName or Email

// simply call LdapAuth.authenticateUserAndGetInfo (username,password);

//Note: Configure ldapURI ,requiredAttributes ,ADSearchPaths,accountSuffex 

import java.util.*;

import javax.naming.*;

import java.util.regex.*;

import javax.naming.directory.*;

import javax.naming.ldap.InitialLdapContext;

import javax.naming.ldap.LdapContext;

public class LdapAuth {


private final static String ldapURI = "ldap://20.200.200.200:389/DC=corp,DC=local";

private final static String contextFactory = "com.sun.jndi.ldap.LdapCtxFactory";

private  static String[] requiredAttributes = {"cn","givenName","sn","displayName","userPrincipalName","sAMAccountName","objectSid","userAccountControl"};


// see you active directory user OU's hirarchy 

private  static String[] ADSearchPaths = 

{ 

    "OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=In-House,OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=Torbram Users,OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=Migrated Users,OU=TES-Users"

};


private static String accountSuffex = "@corp.local"; // this will be used if user name is just provided


private static void authenticateUserAndGetInfo (String user, String password) throws Exception {

    try {


        Hashtable<String,String> env = new Hashtable <String,String>();

        env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);

        env.put(Context.PROVIDER_URL, ldapURI);     

        env.put(Context.SECURITY_AUTHENTICATION, "simple");

        env.put(Context.SECURITY_PRINCIPAL, user);

        env.put(Context.SECURITY_CREDENTIALS, password);

        DirContext ctx = new InitialDirContext(env);

        String filter = "(sAMAccountName="+user+")";  // default for search filter username

        if(user.contains("@"))  // if user name is a email then
        {
            //String parts[] = user.split("\\@");
            //use different filter for email
            filter = "(userPrincipalName="+user+")";
        }

        SearchControls ctrl = new SearchControls();
        ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
        ctrl.setReturningAttributes(requiredAttributes);

        NamingEnumeration userInfo = null;


        Integer i = 0;
        do
        {
            userInfo = ctx.search(ADSearchPaths[i], filter, ctrl);
            i++;

        } while(!userInfo.hasMore() && i < ADSearchPaths.length );

        if (userInfo.hasMore()) {

            SearchResult UserDetails = (SearchResult) userInfo.next();
            Attributes userAttr = UserDetails.getAttributes();System.out.println("adEmail = "+userAttr.get("userPrincipalName").get(0).toString());

            System.out.println("adFirstName = "+userAttr.get("givenName").get(0).toString());

            System.out.println("adLastName = "+userAttr.get("sn").get(0).toString());

            System.out.println("name = "+userAttr.get("cn").get(0).toString());

            System.out.println("AdFullName = "+userAttr.get("cn").get(0).toString());

        }

        userInfo.close();

    }
    catch (javax.naming.AuthenticationException e) {

    }
}   
}

How do I capture all of my compiler's output to a file?

Try make 2> file. Compiler warnings come out on the standard error stream, not the standard output stream. If my suggestion doesn't work, check your shell manual for how to divert standard error.

Intellij idea subversion checkout error: `Cannot run program "svn"`

Basically, what IntelliJ needs is svn.exe. You will need to install Subversion for Windows. It automatically adds svn.exe to PATH environment variable. After installing, please restart IntelliJ.

Note - Tortoise SVN doesn't install svn.exe, at least I couldn't find it in my TortoiseSVN bin directory.

Creating a mock HttpServletRequest out of a url string?

for those looking for a way to mock POST HttpServletRequest with Json payload, the below is in Kotlin, but the key take away here is the DelegatingServetInputStream when you want to mock the request.getInputStream from the HttpServletRequest

@Mock
private lateinit var request: HttpServletRequest

@Mock
private lateinit var response: HttpServletResponse

@Mock
private lateinit var chain: FilterChain

@InjectMocks
private lateinit var filter: ValidationFilter


@Test
fun `continue filter chain with valid json payload`() {
    val payload = """{
      "firstName":"aB",
      "middleName":"asdadsa",
      "lastName":"asdsada",
      "dob":null,
      "gender":"male"
    }""".trimMargin()

    whenever(request.requestURL).
        thenReturn(StringBuffer("/profile/personal-details"))
    whenever(request.method).
        thenReturn("PUT")
    whenever(request.inputStream).
        thenReturn(DelegatingServletInputStream(ByteArrayInputStream(payload.toByteArray())))

    filter.doFilter(request, response, chain)

    verify(chain).doFilter(request, response)
}

How to check what user php is running as?

If available you can probe the current user account with posix_geteuid and then get the user name with posix_getpwuid.

$username = posix_getpwuid(posix_geteuid())['name'];

If you are running in safe mode however (which is often the case when exec is disabled), then it's unlikely that your PHP process is running under anything but the default www-data or apache account.

Find the number of employees in each department - SQL Oracle

SELECT d.DEPTNO
    , d.dname
    , COUNT(e.ename) AS count
FROM   emp e
      INNER JOIN dept d ON e.DEPTNO = d.deptno
GROUP BY d.deptno
      , d.dname;

web.xml is missing and <failOnMissingWebXml> is set to true

I had the same problem, even though I had 'src/main/webapp/WEB-INF/' folder with correct web.xml.

The problem disappeared after I recreated (maven->eclipse) configuration with Maven build.. I executed mvn eclipse:clean eclipse:eclipse

And then I used Maven -> Update Project to add (eclipse->maven) plugin specific options.

java.net.ConnectException: localhost/127.0.0.1:8080 - Connection refused

in android

Replace: String webServiceUrl = "http://localhost:8080/Service1.asmx"

With : String webServiceUrl = "http://10.0.2.2:8080/Service1.asmx"

Good luck!

twitter bootstrap autocomplete dropdown / combobox with Knockoutjs

Does the basic HTML5 datalist work? It's clean and you don't have to play around with the messy third party code. W3SCHOOL tutorial

The MDN Documentation is very eloquent and features examples.

What is the easiest way to push an element to the beginning of the array?

You can use insert:

a = [1,2,3]
a.insert(0,'x')
=> ['x',1,2,3]

Where the first argument is the index to insert at and the second is the value.

Iterate over a Javascript associative array in sorted order

_x000D_
_x000D_
var a = new Array();_x000D_
a['b'] = 1;_x000D_
a['z'] = 1;_x000D_
a['a'] = 1;_x000D_
_x000D_
_x000D_
var keys=Object.keys(a).sort();_x000D_
for(var i=0,key=keys[0];i<keys.length;key=keys[++i]){_x000D_
  document.write(key+' : '+a[key]+'<br>');_x000D_
}
_x000D_
_x000D_
_x000D_

How to import multiple csv files in a single load?

Using Spark 2.0+, we can load multiple CSV files from different directories using df = spark.read.csv(['directory_1','directory_2','directory_3'.....], header=True). For more information, refer the documentation here

How to set Apache Spark Executor memory

You need to increase the driver memory.On mac(i.e when running on local master), the default driver-memory is 1024M). By default, thus 380Mb is allotted to the executor.

Screenshot

Upon increasing [--driver-memory 2G], executor memory got increased to ~950Mb. enter image description here

gnuplot plotting multiple line graphs

Whatever your separator is in your ls.dat, you can specify it to gnuplot:

set datafile separator "\t"

How do I remove packages installed with Python's easy_install?

To uninstall an .egg you need to rm -rf the egg (it might be a directory) and remove the matching line from site-packages/easy-install.pth

JavaScript: Global variables after Ajax requests

It seems that your problem is simply a concurrency issue. The post function takes a callback argument to tell you when the post has been finished. You cannot make the alert in global scope like this and expect that the post has already been finished. You have to move it to the callback function.

jQuery: how do I animate a div rotation?

If you're designing for an iOS device or just webkit, you can do it with no JS whatsoever:

CSS:

@-webkit-keyframes spin {  
from {  
    -webkit-transform: rotate(0deg);  
}  
to {  
    -webkit-transform: rotate(360deg);  
    } 
}

.wheel {
    width:40px;
    height:40px;
    background:url(wheel.png);
    -webkit-animation-name: spin; 
    -webkit-animation-iteration-count: infinite; 
    -webkit-animation-timing-function: linear;
    -webkit-animation-duration: 3s; 
}

This would trigger the animation on load. If you wanted to trigger it on hover, it might look like this:

.wheel {
    width:40px;
    height:40px;
    background:url(wheel.png);
}

.wheel:hover {
    -webkit-animation-name: spin; 
    -webkit-animation-iteration-count: infinite; 
    -webkit-animation-timing-function: ease-in-out;
    -webkit-animation-duration: 3s; 
}

Spark: subtract two DataFrames

According to the api docs, doing:

dataFrame1.except(dataFrame2)

will return a new DataFrame containing rows in dataFrame1 but not in dataframe2.

What does O(log n) mean exactly?

What's logb(n)?

It is the number of times you can cut a log of length n repeatedly into b equal parts before reaching a section of size 1.

How to install pandas from pip on windows cmd?

Assuming you are using Windows OS.

All you need to add the pip.exe path to the Environment Variables (Path).

Generally, you can find it under ..Python\Scripts folder.

For me it is, C:\Program Files\Python36\Scripts\

How do I select a random value from an enumeration?

Call Enum.GetValues; this returns an array that represents all possible values for your enum. Pick a random item from this array. Cast that item back to the original enum type.

How to select rows that have current day's timestamp?

How many ways can we skin this cat? Here is yet another variant.

SELECT * FROM table WHERE DATE(FROM_UNIXTIME(timestamp)) = '2015-11-18';

Can git undo a checkout of unstaged files

Technically yes. But only on certain instances. If for example you have the code page up and you hit git checkout, and you realize that you accidently checked out the wrong page or something. Go to the page and click undo. (for me, command + z), and it will go back to exactly where you were before you hit the good old git checkout.

This will not work if your page has been closed, and then you hit git checkout. It only works if the actual code page is open

JavaScript style.display="none" or jQuery .hide() is more efficient?

Talking about efficiency:

document.getElementById( 'elemtId' ).style.display = 'none';

What jQuery does with its .show() and .hide() methods is, that it remembers the last state of an element. That can come in handy sometimes, but since you asked about efficiency that doesn't matter here.

Removing single-quote from a string in php

You could also be more restrictive in removing disallowed characters. The following regex would remove all characters that are not letters, digits or underscores:

$FileName = preg_replace('/[^\w]/', '', $UserInput);

You might want to do this to ensure maximum compatibility for filenames across different operating systems.

Update a column value, replacing part of a string

Try using the REPLACE function:

mysql> SELECT REPLACE('www.mysql.com', 'w', 'Ww');
        -> 'WwWwWw.mysql.com'

Note that it is case sensitive.

"document.getElementByClass is not a function"

I tried

Document.getElementsByClassName('option0')

Which resulted in the error: Uncaught TypeError: Document.getElementsByClass is not a function

After that I tried:

document.getElementsByClassName('option0')

And it works!

Returning data from Axios API

The issue is that the original axiosTest() function isn't returning the promise. Here's an extended explanation for clarity:

function axiosTest() {
    // create a promise for the axios request
    const promise = axios.get(url)

    // using .then, create a new promise which extracts the data
    const dataPromise = promise.then((response) => response.data)

    // return it
    return dataPromise
}

// now we can use that data from the outside!
axiosTest()
    .then(data => {
        response.json({ message: 'Request received!', data })
    })
    .catch(err => console.log(err))

The function can be written more succinctly:

function axiosTest() {
    return axios.get(url).then(response => response.data)
}

Or with async/await:

async function axiosTest() {
    const response = await axios.get(url)
    return response.data
}

Send form data with jquery ajax json

here is a simple one

here is my test.php for testing only

<?php

// this is just a test
//send back to the ajax request the request

echo json_encode($_POST);

here is my index.html

<!DOCTYPE html>
<html>

<head>

</head>
<body>

<form id="form" action="" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input id="submit" type="button" name="submit" value="submit">
</form>




<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        // click on button submit
        $("#submit").on('click', function(){
            // send ajax
            $.ajax({
                url: 'test.php', // url where to submit the request
                type : "POST", // type of action POST || GET
                dataType : 'json', // data type
                data : $("#form").serialize(), // post data || get data
                success : function(result) {
                    // you can see the result from the console
                    // tab of the developer tools
                    console.log(result);
                },
                error: function(xhr, resp, text) {
                    console.log(xhr, resp, text);
                }
            })
        });
    });

</script>
</body>
</html>

Both file are place in the same directory

What is the purpose of the word 'self'?

In the __init__ method, self refers to the newly created object; in other class methods, it refers to the instance whose method was called.

self, as a name, is just a convention, call it as you want ! but when using it, for example to delete the object, you have to use the same name: __del__(var), where var was used in the __init__(var,[...])

You should take a look at cls too, to have the bigger picture. This post could be helpful.

How to reverse apply a stash?

This is long over due, but if i interpret the problem correctly i have found a simple solution, note, this is an explanation in my own terminology:

git stash [save] will save away current changes and set your current branch to the "clean state"

git stash list gives something like: stash@{0}: On develop: saved testing-stuff

git apply stash@{0} will set current branch as before stash [save]

git checkout . Will set current branch as after stash [save]

The code that is saved in the stash is not lost, it can be found by git apply stash@{0} again.

Anywhay, this worked for me!

Convert a list of objects to an array of one of the object's properties

For everyone who is stuck with .NET 2.0, like me, try the following way (applicable to the example in the OP):

ConfigItemList.ConvertAll<string>(delegate (ConfigItemType ci) 
{ 
   return ci.Name; 
}).ToArray();

where ConfigItemList is your list variable.

How to set zoom level in google map

For zooming your map two level then just add this small code of line map.setZoom(map.getZoom() + 2);

How to Add a Dotted Underline Beneath HTML Text

Without CSS, you basically are stuck with using an image tag. Basically make an image of the text and add the underline. That basically means your page is useless to a screen reader.

With CSS, it is simple.

HTML:

<u class="dotted">I like cheese</u>

CSS:

u.dotted{
  border-bottom: 1px dashed #999;
  text-decoration: none; 
}

Running Example

Example page

<!DOCTYPE HTML>
<html>
<head>
    <style>
        u.dotted{
          border-bottom: 1px dashed #999;
          text-decoration: none; 
        }
    </style>
</head>
<body>
    <u class="dotted">I like cheese</u>
</body>
</html>

Release generating .pdb files, why?

Because without the PDB files, it would be impossible to debug a "Release" build by anything other than address-level debugging. Optimizations really do a number on your code, making it very difficult to find the culprit if something goes wrong (say, an exception is thrown). Even setting breakpoints is extremely difficult, because lines of source code cannot be matched up one-to-one with (or even in the same order as) the generated assembly code. PDB files help you and the debugger out, making post-mortem debugging significantly easier.

You make the point that if your software is ready for release, you should have done all your debugging by then. While that's certainly true, there are a couple of important points to keep in mind:

  1. You should also test and debug your application (before you release it) using the "Release" build. That's because turning optimizations on (they are disabled by default under the "Debug" configuration) can sometimes cause subtle bugs to appear that you wouldn't otherwise catch. When you're doing this debugging, you'll want the PDB symbols.

  2. Customers frequently report edge cases and bugs that only crop up under "ideal" conditions. These are things that are almost impossible to reproduce in the lab because they rely on some whacky configuration of that user's machine. If they're particularly helpful customers, they'll report the exception that was thrown and provide you with a stack trace. Or they'll even let you borrow their machine to debug your software remotely. In either of those cases, you'll want the PDB files to assist you.

  3. Profiling should always be done on "Release" builds with optimizations enabled. And once again, the PDB files come in handy, because they allow the assembly instructions being profiled to be mapped back to the source code that you actually wrote.

You can't go back and generate the PDB files after the compile.* If you don't create them during the build, you've lost your opportunity. It doesn't hurt anything to create them. If you don't want to distribute them, you can simply omit them from your binaries. But if you later decide you want them, you're out of luck. Better to always generate them and archive a copy, just in case you ever need them.

If you really want to turn them off, that's always an option. In your project's Properties window, set the "Debug Info" option to "none" for any configuration you want to change.

Do note, however, that the "Debug" and "Release" configurations do by default use different settings for emitting debug information. You will want to keep this setting. The "Debug Info" option is set to "full" for a Debug build, which means that in addition to a PDB file, debugging symbol information is embedded into the assembly. You also get symbols that support cool features like edit-and-continue. In Release mode, the "pdb-only" option is selected, which, like it sounds, includes only the PDB file, without affecting the content of the assembly. So it's not quite as simple as the mere presence or absence of PDB files in your /bin directory. But assuming you use the "pdb-only" option, the PDB file's presence will in no way affect the run-time performance of your code.

* As Marc Sherman points out in a comment, as long as your source code has not changed (or you can retrieve the original code from a version-control system), you can rebuild it and generate a matching PDB file. At least, usually. This works well most of the time, but the compiler is not guaranteed to generate identical binaries each time you compile the same code, so there may be subtle differences. Worse, if you have made any upgrades to your toolchain in the meantime (like applying a service pack for Visual Studio), the PDBs are even less likely to match. To guarantee the reliable generation of ex postfacto PDB files, you would need to archive not only the source code in your version-control system, but also the binaries for your entire build toolchain to ensure that you could precisely recreate the configuration of your build environment. It goes without saying that it is much easier to simply create and archive the PDB files.

How to get files in a relative path in C#

Write it like this:

string[] files = Directory.GetFiles(@".\Archive", "*.zip");

. is for relative to the folder where you started your exe, and @ to allow \ in the name.

When using filters, you pass it as a second parameter. You can also add a third parameter to specify if you want to search recursively for the pattern.

In order to get the folder where your .exe actually resides, use:

var executingPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

how to loop through rows columns in excel VBA Macro

I'd recommend the Range object's AutoFill method for this:

rngSource.AutoFill Destination:=rngDest

Specify the Source range that contains the values or formulas you want to fill down, and the Destination range as the whole range that you want the cells filled to. The Destination range must include the Source range. You can fill across as well as down.

It works exactly the same way as it would if you manually "dragged" the cells at the corner with the mouse; absolute and relative formulas work as expected.

Here's an example:

'Set some example values'
Range("A1").Value = "1"
Range("B1").Formula = "=NOW()"
Range("C1").Formula = "=B1+A1"

'AutoFill the values / formulas to row 20'
Range("A1:C1").AutoFill Destination:=Range("A1:C20")

Hope this helps.

How to get the text of the selected value of a dropdown list?

$("#select_id").find("option:selected").text();

It is helpful if your control is on Server side. In .NET it looks like:

$('#<%= dropdownID.ClientID %>').find("option:selected").text();

Angular 2 ngfor first, last, index loop

By this you can get any index in *ngFor loop in ANGULAR ...

<ul>
  <li *ngFor="let object of myArray; let i = index; let first = first ;let last = last;">
    <div *ngIf="first">
       // write your code...
    </div>

    <div *ngIf="last">
       // write your code...
    </div>
  </li>
</ul>

We can use these alias in *ngFor

  • index : number : let i = index to get all index of object.
  • first : boolean : let first = first to get first index of object.
  • last : boolean : let last = last to get last index of object.
  • odd : boolean : let odd = odd to get odd index of object.
  • even : boolean : let even = even to get even index of object.

LIKE operator in LINQ

In native LINQ you may use combination of Contains/StartsWith/EndsWith or RegExp.

In LINQ2SQL use method SqlMethods.Like()

    from i in db.myTable
    where SqlMethods.Like(i.field, "tra%ata")
    select i

add Assembly: System.Data.Linq (in System.Data.Linq.dll) to use this feature.

Scala: join an iterable of strings

How about mkString ?

theStrings.mkString(",")

A variant exists in which you can specify a prefix and suffix too.

See here for an implementation using foldLeft, which is much more verbose, but perhaps worth looking at for education's sake.

If else on WHERE clause

You want to use coalesce():

where coalesce(email, email2) like '%[email protected]%'

If you want to handle empty strings ('') versus NULL, a case works:

where (case when email is NULL or email = '' then email2 else email end) like '%[email protected]%'

And, if you are worried about the string really being just spaces:

where (case when email is NULL or ltrim(email) = '' then email2 else email end) like '%[email protected]%'

As an aside, the sample if statement is really saying "If email starts with a number larger than 0". This is because the comparison is to 0, a number. MySQL implicitly tries to convert the string to a number. So, '[email protected]' would fail, because the string would convert as 0. As would '[email protected]'. But, '[email protected]' and '[email protected]' would succeed.

How can I extract a good quality JPEG image from a video file with ffmpeg?

Output the images in a lossless format such as PNG:

ffmpeg.exe -i 10fps.h264 -r 10 -f image2 10fps.h264_%03d.png

Edit/Update: Not quite sure why I originally gave a strange filename example (with a possibly made-up extension).

I have since found that -vsync 0 is simpler than -r 10 because it avoids needing to know the frame rate.

This is something like what I currently use:

mkdir stills
ffmpeg -i my-film.mp4 -vsync 0 -f image2 stills/my-film-%06d.png

To extract only the key frames (which are likely to be of higher quality post-edit):

ffmpeg -skip_frame nokey -i my-film.mp4 -vsync 0 -f image2 stills/my-film-%06d.png

Then use another program (where you can more precisely specify quality, subsampling and DCT method – e.g. GIMP) to convert the PNGs you want to JPEG.

It is possible to obtain slightly sharper images in JPEG format this way than is possible with -qmin 1 -q:v 1 and outputting as JPEG directly from ffmpeg.

How to get TimeZone from android mobile?

TimeZone tz = TimeZone.getDefault();
System.out.println("TimeZone   "+tz.getDisplayName(false, TimeZone.SHORT)+" Timezone id :: " +tz.getID());

Output:

TimeZone GMT+09:30 Timezone id :: Australia/Darwin

How to generate class diagram from project in Visual Studio 2013?

For creating real UML class diagrams:

In Visual Studio 2013 Ultimate you can do this without any external tools.

  • In the menu, click on Architecture, New Diagram Select UML Class Diagram
  • This will ask you to create a new Modeling Project if you don't have one already.

You will have a empty UMLClassDiagram.classdiagram.

  • Again, go to Architecture, Windows, Architecture Explorer.
  • A window will pop up with your namespaces, Choose Class View.
  • Then a list of sub-namespaces will appear, if any. Choose one, select the classes and drag them to the empty UMLClassDiagram1.classdiagram window.

Reference: Create UML Class Diagrams from Code

Java generics - ArrayList initialization

You can't assign a List<Number> to a reference of type List<Integer> because List<Number> allows types of numbers other than Integer. If you were allowed to do that, the following would be allowed:

List<Number> numbers = new ArrayList<Number>();
numbers.add(1.1); // add a double
List<Integer> ints = numbers;
Integer fail = ints.get(0); // ClassCastException!

The type List<Integer> is making a guarantee that anything it contains will be an Integer. That's why you're allowed to get an Integer out of it without casting. As you can see, if the compiler allowed a List of another type such as Number to be assigned to a List<Integer> that guarantee would be broken.

Assigning a List<Integer> to a reference of a type such as List<?> or List<? extends Number> is legal because the ? means "some unknown subtype of the given type" (where the type is Object in the case of just ? and Number in the case of ? extends Number).

Since ? indicates that you do not know what specific type of object the List will accept, it isn't legal to add anything but null to it. You are, however, allowed to retrieve any object from it, which is the purpose of using a ? extends X bounded wildcard type. Note that the opposite is true for a ? super X bounded wildcard type... a List<? super Integer> is "a list of some unknown type that is at least a supertype of Integer". While you don't know exactly what type of List it is (could be List<Integer>, List<Number>, List<Object>) you do know for sure that whatever it is, an Integer can be added to it.

Finally, new ArrayList<?>() isn't legal because when you're creating an instance of a paramterized class like ArrayList, you have to give a specific type parameter. You could really use whatever in your example (Object, Foo, it doesn't matter) since you'll never be able to add anything but null to it since you're assigning it directly to an ArrayList<?> reference.

Save internal file in my own internal folder in Android

First Way:

You didn't create the directory. Also, you are passing an absolute path to openFileOutput(), which is wrong.

Second way:

You created an empty file with the desired name, which then prevented you from creating the directory. Also, you are passing an absolute path to openFileOutput(), which is wrong.

Third way:

You didn't create the directory. Also, you are passing an absolute path to openFileOutput(), which is wrong.

Fourth Way:

You didn't create the directory. Also, you are passing an absolute path to openFileOutput(), which is wrong.

Fifth way:

You didn't create the directory. Also, you are passing an absolute path to openFileOutput(), which is wrong.

Correct way:

  1. Create a File for your desired directory (e.g., File path=new File(getFilesDir(),"myfolder");)
  2. Call mkdirs() on that File to create the directory if it does not exist
  3. Create a File for the output file (e.g., File mypath=new File(path,"myfile.txt");)
  4. Use standard Java I/O to write to that File (e.g., using new BufferedWriter(new FileWriter(mypath)))

Is there functionality to generate a random character in Java?

   Random randomGenerator = new Random();

   int i = randomGenerator.nextInt(256);
   System.out.println((char)i);

Should take care of what you want, assuming you consider '0,'1','2'.. as characters.

How can I make SQL case sensitive string comparison on MySQL?

To make use of an index before using the BINARY, you could do something like this if you have large tables.

SELECT
   *
FROM
   (SELECT * FROM `table` WHERE `column` = 'value') as firstresult
WHERE
   BINARY `column` = 'value'

The subquery would result in a really small case-insensitive subset of which you then select the only case-sensitive match.

WebDriver - wait for element using Java

This is how I do it in my code.

WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id<locator>));

or

wait.until(ExpectedConditions.elementToBeClickable(By.id<locator>));

to be precise.

See also:

PHP: How can I determine if a variable has a value that is between two distinct constant values?

If you just want to check the value is in Range, use this:

   MIN_VALUE = 1;
   MAX_VALUE = 100;
   $customValue = min(MAX_VALUE,max(MIN_VALUE,$customValue)));

How to pass ArrayList<CustomeObject> from one activity to another?

In First activity:

ArrayList<ContactBean> fileList = new ArrayList<ContactBean>();
Intent intent = new Intent(MainActivity.this, secondActivity.class);
intent.putExtra("FILES_TO_SEND", fileList);
startActivity(intent);

In receiver activity:

ArrayList<ContactBean> filelist =  (ArrayList<ContactBean>)getIntent().getSerializableExtra("FILES_TO_SEND");`

how do I insert a column at a specific column index in pandas?

If you want a single value for all rows:

df.insert(0,'name_of_column','')
df['name_of_column'] = value

Edit:

You can also:

df.insert(0,'name_of_column',value)

Getting 400 bad request error in Jquery Ajax POST

In case anyone else runs into this. I have a web site that was working fine on the desktop browser but I was getting 400 errors with Android devices.

It turned out to be the anti forgery token.

$.ajax({
        url: "/Cart/AddProduct/",
        data: {
            __RequestVerificationToken: $("[name='__RequestVerificationToken']").val(),
            productId: $(this).data("productcode")
        },

The problem was that the .Net controller wasn't set up correctly.

I needed to add the attributes to the controller:

    [AllowAnonymous]
    [IgnoreAntiforgeryToken]
    [DisableCors]
    [HttpPost]
    public async Task<JsonResult> AddProduct(int productId)
    {

The code needs review but for now at least I know what was causing it. 400 error not helpful at all.

PostgreSQL Exception Handling

To catch the error message and its code:

do $$       
begin

    create table yyy(a int);
    create table yyy(a int); -- this will cause an error

exception when others then 

    raise notice 'The transaction is in an uncommittable state. '
                 'Transaction was rolled back';

    raise notice '% %', SQLERRM, SQLSTATE;

end; $$ 
language 'plpgsql';

Haven't found the line number yet

UPDATE April, 16, 2019

As suggested by Diego Scaravaggi, for Postgres 9.2 and up, use GET STACKED DIAGNOSTICS:

do language plpgsql $$
declare
    v_state   TEXT;
    v_msg     TEXT;
    v_detail  TEXT;
    v_hint    TEXT;
    v_context TEXT;
begin

    create table yyy(a int);
    create table yyy(a int); -- this will cause an error

exception when others then 

    get stacked diagnostics
        v_state   = returned_sqlstate,
        v_msg     = message_text,
        v_detail  = pg_exception_detail,
        v_hint    = pg_exception_hint,
        v_context = pg_exception_context;

    raise notice E'Got exception:
        state  : %
        message: %
        detail : %
        hint   : %
        context: %', v_state, v_msg, v_detail, v_hint, v_context;

    raise notice E'Got exception:
        SQLSTATE: % 
        SQLERRM: %', SQLSTATE, SQLERRM;     

    raise notice '%', message_text; -- invalid. message_text is contextual to GET STACKED DIAGNOSTICS only

end; $$;

Result:

NOTICE:  Got exception:
        state  : 42P07
        message: relation "yyy" already exists
        detail : 
        hint   : 
        context: SQL statement "create table yyy(a int)"
PL/pgSQL function inline_code_block line 11 at SQL statement
NOTICE:  Got exception:
        SQLSTATE: 42P07 
        SQLERRM: relation "yyy" already exists

ERROR:  column "message_text" does not exist
LINE 1: SELECT message_text
               ^
QUERY:  SELECT message_text
CONTEXT:  PL/pgSQL function inline_code_block line 33 at RAISE
SQL state: 42703

Aside from GET STACKED DIAGNOSTICS is SQL standard-compliant, its diagnostics variables (e.g., message_text) are contextual to GSD only. So if you have a field named message_text in your table, there's no chance that GSD can interfere with your field's value.

Still no line number though.

Groovy: How to check if a string contains any element of an array?

def valid = pointAddress.findAll { a ->
    validPointTypes.any { a.contains(it) }
}

Should do it

How to present UIAlertController when not in a view controller?

iOS13 scene support (when using UIWindowScene)

import UIKit

private var windows: [String:UIWindow] = [:]

extension UIWindowScene {
    static var focused: UIWindowScene? {
        return UIApplication.shared.connectedScenes
            .first { $0.activationState == .foregroundActive && $0 is UIWindowScene } as? UIWindowScene
    }
}

class StyledAlertController: UIAlertController {

    var wid: String?

    func present(animated: Bool, completion: (() -> Void)?) {

        //let window = UIWindow(frame: UIScreen.main.bounds)
        guard let window = UIWindowScene.focused.map(UIWindow.init(windowScene:)) else {
            return
        }
        window.rootViewController = UIViewController()
        window.windowLevel = .alert + 1
        window.makeKeyAndVisible()
        window.rootViewController!.present(self, animated: animated, completion: completion)

        wid = UUID().uuidString
        windows[wid!] = window
    }

    open override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        if let wid = wid {
            windows[wid] = nil
        }

    }

}

How do I collapse a table row in Bootstrap?

I just came up with the same problem since we still use bootstrap 2.3.2.

My solution for this: http://jsfiddle.net/KnuU6/281/

css:

.myCollapse {
    display: none;
}
.myCollapse.in {
    display: block;
}

javascript:

 $("[data-toggle=myCollapse]").click(function( ev ) {
   ev.preventDefault();
   var target;
   if (this.hasAttribute('data-target')) {
 target = $(this.getAttribute('data-target'));
   } else {
 target = $(this.getAttribute('href'));
   };
   target.toggleClass("in");
 });

html:

<table>
  <tr><td><a href="#demo" data-toggle="myCollapse">Click me to toggle next row</a></td></tr>
  <tr class="collapse" id="#demo"><td>You can collapse and expand me.</td></tr>
</table>

Flex-box: Align last row to grid

If you know the width of spaces between elements in the row and the amount of elements in a row, this would work:

Example: 3 elements in a row, 10px gap between elements

div:last-child:nth-child(3n+2) {
  flex-grow: 1
  margin-left: 10px
}

Communicating between a fragment and an activity - best practices

I am using Intents to communicate actions back to the main activity. The main activity is listening to these by overriding onNewIntent(Intent intent). The main activity translates these actions to the corresponding fragments for example.

So you can do something like this:

public class MainActivity extends Activity  {

    public static final String INTENT_ACTION_SHOW_FOO = "show_foo";
    public static final String INTENT_ACTION_SHOW_BAR = "show_bar";


   @Override
   protected void onNewIntent(Intent intent) {
        routeIntent(intent);
   }

  private void routeIntent(Intent intent) {
       String action = intent.getAction();
       if (action != null) {               
            switch (action) {
            case INTENT_ACTION_SHOW_FOO:
                // for example show the corresponding fragment
                loadFragment(FooFragment);
                break;
            case INTENT_ACTION_SHOW_BAR:
                loadFragment(BarFragment);
                break;               
        }
    }
}

Then inside any fragment to show the foo fragment:

Intent intent = new Intent(context, MainActivity.class);
intent.setAction(INTENT_ACTION_SHOW_FOO);
// Prevent activity to be re-instantiated if it is already running.
// Instead, the onNewEvent() is triggered
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
getContext().startActivity(intent);

Ignore outliers in ggplot2 boxplot

One idea would be to winsorize the data in a two-pass procedure:

  1. run a first pass, learn what the bounds are, e.g. cut of at given percentile, or N standard deviation above the mean, or ...

  2. in a second pass, set the values beyond the given bound to the value of that bound

I should stress that this is an old-fashioned method which ought to be dominated by more modern robust techniques but you still come across it a lot.

Why does git perform fast-forward merges by default?

Let me expand a bit on a VonC's very comprehensive answer:


First, if I remember it correctly, the fact that Git by default doesn't create merge commits in the fast-forward case has come from considering single-branch "equal repositories", where mutual pull is used to sync those two repositories (a workflow you can find as first example in most user's documentation, including "The Git User's Manual" and "Version Control by Example"). In this case you don't use pull to merge fully realized branch, you use it to keep up with other work. You don't want to have ephemeral and unimportant fact when you happen to do a sync saved and stored in repository, saved for the future.

Note that usefulness of feature branches and of having multiple branches in single repository came only later, with more widespread usage of VCS with good merging support, and with trying various merge-based workflows. That is why for example Mercurial originally supported only one branch per repository (plus anonymous tips for tracking remote branches), as seen in older revisions of "Mercurial: The Definitive Guide".


Second, when following best practices of using feature branches, namely that feature branches should all start from stable version (usually from last release), to be able to cherry-pick and select which features to include by selecting which feature branches to merge, you are usually not in fast-forward situation... which makes this issue moot. You need to worry about creating a true merge and not fast-forward when merging a very first branch (assuming that you don't put single-commit changes directly on 'master'); all other later merges are of course in non fast-forward situation.

HTH

Using pickle.dump - TypeError: must be str, not bytes

Just had same issue. In Python 3, Binary modes 'wb', 'rb' must be specified whereas in Python 2x, they are not needed. When you follow tutorials that are based on Python 2x, that's why you are here.

import pickle

class MyUser(object):
    def __init__(self,name):
        self.name = name

user = MyUser('Peter')

print("Before serialization: ")
print(user.name)
print("------------")
serialized = pickle.dumps(user)
filename = 'serialized.native'

with open(filename,'wb') as file_object:
    file_object.write(serialized)

with open(filename,'rb') as file_object:
    raw_data = file_object.read()

deserialized = pickle.loads(raw_data)


print("Loading from serialized file: ")
user2 = deserialized
print(user2.name)
print("------------")

How to find server name of SQL Server Management Studio

As mentioned by @Khaneddy2013, the cmd SQLCMD -L returns no server name when I run. Bcz I only have installed the SSMS (local db and server were not installed). After tried installing SqlLocaLDB and SQLEXPR32_x86_ENU(32 bit OS) I was able to connect. And now the cmd window shows the server names too. enter image description here

Responsive dropdown navbar with angular-ui bootstrap (done in the correct angular kind of way)

You can do it using the "collapse" directive: http://jsfiddle.net/iscrow/Es4L3/ (check the two "Note" in the HTML).

        <!-- Note: set the initial collapsed state and change it when clicking -->
        <a ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed" class="btn btn-navbar">
           <span class="icon-bar"></span>
           <span class="icon-bar"></span>
           <span class="icon-bar"></span>
        </a>
        <a class="brand" href="#">Title</a>
           <!-- Note: use "collapse" here. The original "data-" settings are not needed anymore. -->
           <div collapse="navCollapsed" class="nav-collapse collapse navbar-responsive-collapse">
              <ul class="nav">

That is, you need to store the collapsed state in a variable, and changing the collapsed also by (simply) changing the value of that variable.


Release 0.14 added a uib- prefix to components:

https://github.com/angular-ui/bootstrap/wiki/Migration-guide-for-prefixes

Change: collapse to uib-collapse.

Add a column in a table in HIVE QL

You cannot add a column with a default value in Hive. You have the right syntax for adding the column ALTER TABLE test1 ADD COLUMNS (access_count1 int);, you just need to get rid of default sum(max_count). No changes to that files backing your table will happen as a result of adding the column. Hive handles the "missing" data by interpreting NULL as the value for every cell in that column.

So now your have the problem of needing to populate the column. Unfortunately in Hive you essentially need to rewrite the whole table, this time with the column populated. It may be easier to rerun your original query with the new column. Or you could add the column to the table you have now, then select all of its columns plus value for the new column.

You also have the option to always COALESCE the column to your desired default and leave it NULL for now. This option fails when you want NULL to have a meaning distinct from your desired default. It also requires you to depend on always remembering to COALESCE.

If you are very confident in your abilities to deal with the files backing Hive, you could also directly alter them to add your default. In general I would recommend against this because most of the time it will be slower and more dangerous. There might be some case where it makes sense though, so I've included this option for completeness.

Appending items to a list of lists in python

import csv
cols = [' V1', ' I1'] # define your columns here, check the spaces!
data = [[] for col in cols] # this creates a list of **different** lists, not a list of pointers to the same list like you did in [[]]*len(positions) 
with open('data.csv', 'r') as f:
    for rec in csv.DictReader(f):
        for l, col in zip(data, cols):
            l.append(float(rec[col]))
print data

# [[3.0, 3.0], [0.01, 0.01]]

Read a zipped file as a pandas DataFrame

https://www.kaggle.com/jboysen/quick-gz-pandas-tutorial

Please follow this link.

import pandas as pd
traffic_station_df = pd.read_csv('C:\\Folders\\Jupiter_Feed.txt.gz', compression='gzip',
                                 header=1, sep='\t', quotechar='"')

#traffic_station_df['Address'] = 'address'

#traffic_station_df.append(traffic_station_df)
print(traffic_station_df)

customize Android Facebook Login button

In order to have completely custom facebook login button without using com.facebook.widget.LoginButton.

According to facebook sdk 4.x,

There new concept of login as from facebook

LoginManager and AccessToken - These new classes perform Facebook Login

So, Now you can access Facebook authentication without Facebook login button as

layout.xml

    <Button
            android:id="@+id/btn_fb_login"
            .../>

MainActivity.java

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        FacebookSdk.sdkInitialize(this.getApplicationContext());

        callbackManager = CallbackManager.Factory.create();

        LoginManager.getInstance().registerCallback(callbackManager,
                new FacebookCallback<LoginResult>() {
                    @Override
                    public void onSuccess(LoginResult loginResult) {
                        Log.d("Success", "Login");

                    }

                    @Override
                    public void onCancel() {
                        Toast.makeText(MainActivity.this, "Login Cancel", Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onError(FacebookException exception) {
                        Toast.makeText(MainActivity.this, exception.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });

        setContentView(R.layout.activity_main);

        Button btn_fb_login = (Button)findViewById(R.id.btn_fb_login);

        btn_fb_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                  LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile", "user_friends"));
            }
        });

    }

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    callbackManager.onActivityResult(requestCode, resultCode, data); 
}

Close window automatically after printing dialog closes

I just want to write what I have done and what has worked for me (as nothing else I tried had worked).

I had the problem that IE would close the windows before the print dialog got up.

After a lot of trial and error og testing this is what I got to work:

var w = window.open();
w.document.write($('#data').html()); //only part of the page to print, using jquery
w.document.close(); //this seems to be the thing doing the trick
w.focus();
w.print();
w.close();

This seems to work in all browsers.

How to index into a dictionary?

Dictionaries are unordered in Python versions up to and including Python 3.6. If you do not care about the order of the entries and want to access the keys or values by index anyway, you can use d.keys()[i] and d.values()[i] or d.items()[i]. (Note that these methods create a list of all keys, values or items in Python 2.x. So if you need them more then once, store the list in a variable to improve performance.)

If you do care about the order of the entries, starting with Python 2.7 you can use collections.OrderedDict. Or use a list of pairs

l = [("blue", "5"), ("red", "6"), ("yellow", "8")]

if you don't need access by key. (Why are your numbers strings by the way?)

In Python 3.7, normal dictionaries are ordered, so you don't need to use OrderedDict anymore (but you still can – it's basically the same type). The CPython implementation of Python 3.6 already included that change, but since it's not part of the language specification, you can't rely on it in Python 3.6.

Jquery validation plugin - TypeError: $(...).validate is not a function

It looks like the JavaScript error your getting is probably being caused by

password: {
    required:true,
    rangelenght:[4.20]
},

As the [4.20] should be [4,20], which i'd guess is throwing off the validation code in additional-methods hence giving the type error's you posted.

Edit: As others have noted in the below comments rangelenght is also misspelled & jquery.validate.js library appears to be missing (assuming its not compiled in to one of your other assets)

Angular 2 - innerHTML styling

The recommended version by Günter Zöchbauer works fine, but I have an addition to make. In my case I had an unstyled html-element and I did not know how to style it. Therefore I designed a pipe to add styling to it.

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';


@Pipe({
    name: 'StyleClass'
})
export class StyleClassPipe implements PipeTransform {

    constructor(private sanitizer: DomSanitizer) { }
    transform(html: any, styleSelector: any, styleValue: any): SafeHtml {
        const style = ` style = "${styleSelector}: ${styleValue};"`;
        const indexPosition = html.indexOf('>');
        const newHtml = [html.slice(0, indexPosition), style, html.slice(indexPosition)].join('');
        return this.sanitizer.bypassSecurityTrustHtml(newHtml);
    }

}

Then you can add style to any html-element like this:

<span [innerhtml]="Variable | StyleClass: 'margin': '0'"> </span>

With:

Variable = '<p> Test </p>'

Where is the itoa function in Linux?

I have used _itoa(...) on RedHat 6 and GCC compiler. It works.

SyntaxError of Non-ASCII character

You should define source code encoding, add this to the top of your script:

# -*- coding: utf-8 -*-

The reason why it works differently in console and in the IDE is, likely, because of different default encodings set. You can check it by running:

import sys
print sys.getdefaultencoding()

Also see:

How to map to multiple elements with Java 8 streams?

To do this, I had to come up with an intermediate data structure:

class KeyDataPoint {
    String key;
    DateTime timestamp;
    Number data;
    // obvious constructor and getters
}

With this in place, the approach is to "flatten" each MultiDataPoint into a list of (timestamp, key, data) triples and stream together all such triples from the list of MultiDataPoint.

Then, we apply a groupingBy operation on the string key in order to gather the data for each key together. Note that a simple groupingBy would result in a map from each string key to a list of the corresponding KeyDataPoint triples. We don't want the triples; we want DataPoint instances, which are (timestamp, data) pairs. To do this we apply a "downstream" collector of the groupingBy which is a mapping operation that constructs a new DataPoint by getting the right values from the KeyDataPoint triple. The downstream collector of the mapping operation is simply toList which collects the DataPoint objects of the same group into a list.

Now we have a Map<String, List<DataPoint>> and we want to convert it to a collection of DataSet objects. We simply stream out the map entries and construct DataSet objects, collect them into a list, and return it.

The code ends up looking like this:

Collection<DataSet> convertMultiDataPointToDataSet(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .flatMap(mdp -> mdp.getData().entrySet().stream()
                           .map(e -> new KeyDataPoint(e.getKey(), mdp.getTimestamp(), e.getValue())))
        .collect(groupingBy(KeyDataPoint::getKey,
                    mapping(kdp -> new DataPoint(kdp.getTimestamp(), kdp.getData()), toList())))
        .entrySet().stream()
        .map(e -> new DataSet(e.getKey(), e.getValue()))
        .collect(toList());
}

I took some liberties with constructors and getters, but I think they should be obvious.

use Lodash to sort array of object by value

This method orderBy does not change the input array, you have to assign the result to your array :

var chars = this.state.characters;

chars = _.orderBy(chars, ['name'],['asc']); // Use Lodash to sort array by 'name'

 this.setState({characters: chars})

Way to insert text having ' (apostrophe) into a SQL table

INSERT INTO exampleTbl VALUES('he doesn''t work for me')

If you're adding a record through ASP.NET, you can use the SqlParameter object to pass in values so you don't have to worry about the apostrophe's that users enter in.

Getting and removing the first character of a string

substring is definitely best, but here's one strsplit alternative, since I haven't seen one yet.

> x <- 'hello stackoverflow'
> strsplit(x, '')[[1]][1]
## [1] "h"

or equivalently

> unlist(strsplit(x, ''))[1]
## [1] "h"

And you can paste the rest of the string back together.

> paste0(strsplit(x, '')[[1]][-1], collapse = '')
## [1] "ello stackoverflow"

Update and left outer join statements

Update t 
SET 
       t.Column1=100
FROM 
       myTableA t 
LEFT JOIN 
       myTableB t2 
ON 
       t2.ID=t.ID

Replace myTableA with your table name and replace Column1 with your column name.

After this simply LEFT JOIN to tableB. t in this case is just an alias for myTableA. t2 is an alias for your joined table, in my example that is myTableB. If you don't like using t or t2 use any alias name you prefer - it doesn't matter - I just happen to like using those.

Linux / Bash, using ps -o to get process by specific name?

Sometimes you need to grep the process by name - in that case:

ps aux | grep simple-scan

Example output:

simple-scan  1090  0.0  0.1   4248  1432 ?        S    Jun11   0:00

Returning an empty array

A different way to return an empty array is to use a constant as all empty arrays of a given type are the same.

private static final File[] NO_FILES = {};
private static File[] bar(){
    return NO_FILES;
}

"Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions" error

I had the same problem with something like

@foreach (var item in Model)
{
    @Html.DisplayFor(m => !item.IsIdle, "BoolIcon")
}

I solved this just by doing

@foreach (var item in Model)
{
    var active = !item.IsIdle;
    @Html.DisplayFor(m => active , "BoolIcon")
}

When you know the trick, it's simple.

The difference is that, in the first case, I passed a method as a parameter whereas in the second case, it's an expression.

Get string after character

echo "GenFiltEff=7.092200e-01" | cut -d "=" -f2 

Can I override and overload static methods in Java?

Definitely, we cannot override static methods in Java. Because JVM resolves correct overridden method based upon the object at run-time by using dynamic binding in Java.

However, the static method in Java is associated with Class rather than the object and resolved and bonded during compile time.

How to count the occurrence of certain item in an ndarray?

For generic entries:

x = np.array([11, 2, 3, 5, 3, 2, 16, 10, 10, 3, 11, 4, 5, 16, 3, 11, 4])
n = {i:len([j for j in np.where(x==i)[0]]) for i in set(x)}
ix = {i:[j for j in np.where(x==i)[0]] for i in set(x)}

Will output a count:

{2: 2, 3: 4, 4: 2, 5: 2, 10: 2, 11: 3, 16: 2}

And indices:

{2: [1, 5],
3: [2, 4, 9, 14],
4: [11, 16],
5: [3, 12],
10: [7, 8],
11: [0, 10, 15],
16: [6, 13]}

Modifying list while iterating

The general rule of thumb is that you don't modify a collection/array/list while iterating over it.

Use a secondary list to store the items you want to act upon and execute that logic in a loop after your initial loop.

Can I simultaneously declare and assign a variable in VBA?

There is no shorthand in VBA unfortunately, The closest you will get is a purely visual thing using the : continuation character if you want it on one line for readability;

Dim clientToTest As String:  clientToTest = clientsToTest(i)
Dim clientString As Variant: clientString = Split(clientToTest)

Hint (summary of other answers/comments): Works with objects too (Excel 2010):

Dim ws  As Worksheet: Set ws = ActiveWorkbook.Worksheets("Sheet1")
Dim ws2 As New Worksheet: ws2.Name = "test"

Logger slf4j advantages of formatting with {} instead of string concatenation

Short version: Yes it is faster, with less code!

String concatenation does a lot of work without knowing if it is needed or not (the traditional "is debugging enabled" test known from log4j), and should be avoided if possible, as the {} allows delaying the toString() call and string construction to after it has been decided if the event needs capturing or not. By having the logger format a single string the code becomes cleaner in my opinion.

You can provide any number of arguments. Note that if you use an old version of sljf4j and you have more than two arguments to {}, you must use the new Object[]{a,b,c,d} syntax to pass an array instead. See e.g. http://slf4j.org/apidocs/org/slf4j/Logger.html#debug(java.lang.String, java.lang.Object[]).

Regarding the speed: Ceki posted a benchmark a while back on one of the lists.

Check if two unordered lists are equal

if you do not want to use the collections library, you can always do something like this: given that a and b are your lists, the following returns the number of matching elements (it considers the order).

sum([1 for i,j in zip(a,b) if i==j])

Therefore,

len(a)==len(b) and len(a)==sum([1 for i,j in zip(a,b) if i==j])

will be True if both lists are the same, contain the same elements and in the same order. False otherwise.

So, you can define the compare function like the first response above,but without the collections library.

compare = lambda a,b: len(a)==len(b) and len(a)==sum([1 for i,j in zip(a,b) if i==j])

and

>>> compare([1,2,3], [1,2,3,3])
False
>>> compare([1,2,3], [1,2,3])
True
>>> compare([1,2,3], [1,2,4])
False

Remove duplicated rows

The data.table package also has unique and duplicated methods of it's own with some additional features.

Both the unique.data.table and the duplicated.data.table methods have an additional by argument which allows you to pass a character or integer vector of column names or their locations respectively

library(data.table)
DT <- data.table(id = c(1,1,1,2,2,2),
                 val = c(10,20,30,10,20,30))

unique(DT, by = "id")
#    id val
# 1:  1  10
# 2:  2  10

duplicated(DT, by = "id")
# [1] FALSE  TRUE  TRUE FALSE  TRUE  TRUE

Another important feature of these methods is a huge performance gain for larger data sets

library(microbenchmark)
library(data.table)
set.seed(123)
DF <- as.data.frame(matrix(sample(1e8, 1e5, replace = TRUE), ncol = 10))
DT <- copy(DF)
setDT(DT)

microbenchmark(unique(DF), unique(DT))
# Unit: microseconds
#       expr       min         lq      mean    median        uq       max neval cld
# unique(DF) 44708.230 48981.8445 53062.536 51573.276 52844.591 107032.18   100   b
# unique(DT)   746.855   776.6145  2201.657   864.932   919.489  55986.88   100  a 


microbenchmark(duplicated(DF), duplicated(DT))
# Unit: microseconds
#           expr       min         lq       mean     median        uq        max neval cld
# duplicated(DF) 43786.662 44418.8005 46684.0602 44925.0230 46802.398 109550.170   100   b
# duplicated(DT)   551.982   558.2215   851.0246   639.9795   663.658   5805.243   100  a 

How to use PHP OPCache?

OPcache replaces APC

Because OPcache is designed to replace the APC module, it is not possible to run them in parallel in PHP. This is fine for caching PHP opcode as neither affects how you write code.

However it means that if you are currently using APC to store other data (through the apc_store() function) you will not be able to do that if you decide to use OPCache.

You will need to use another library such as either APCu or Yac which both store data in shared PHP memory, or switch to use something like memcached, which stores data in memory in a separate process to PHP.

Also, OPcache has no equivalent of the upload progress meter present in APC. Instead you should use the Session Upload Progress.

Settings for OPcache

The documentation for OPcache can be found here with all of the configuration options listed here. The recommended settings are:

; Sets how much memory to use
opcache.memory_consumption=128

;Sets how much memory should be used by OPcache for storing internal strings 
;(e.g. classnames and the files they are contained in)
opcache.interned_strings_buffer=8

; The maximum number of files OPcache will cache
opcache.max_accelerated_files=4000

;How often (in seconds) to check file timestamps for changes to the shared
;memory storage allocation.
opcache.revalidate_freq=60

;If enabled, a fast shutdown sequence is used for the accelerated code
;The fast shutdown sequence doesn't free each allocated block, but lets
;the Zend Engine Memory Manager do the work.
opcache.fast_shutdown=1

;Enables the OPcache for the CLI version of PHP.
opcache.enable_cli=1

If you use any library or code that uses code annotations you must enable save comments:

opcache.save_comments=1

If disabled, all PHPDoc comments are dropped from the code to reduce the size of the optimized code. Disabling "Doc Comments" may break some existing applications and frameworks (e.g. Doctrine, ZF2, PHPUnit)

SQL Server: Get table primary key using sql query

Keep in mind that if you want to get exact primary field you need to put TABLE_NAME and TABLE_SCHEMA into the condition.

this solution should work:

select COLUMN_NAME from information_schema.KEY_COLUMN_USAGE 
where CONSTRAINT_NAME='PRIMARY' AND TABLE_NAME='TABLENAME' 
AND TABLE_SCHEMA='DATABASENAME'

Plotting power spectrum in python

Since FFT is symmetric over it's centre, half the values are just enough.

import numpy as np
import matplotlib.pyplot as plt

fs = 30.0
t = np.arange(0,10,1/fs)
x = np.cos(2*np.pi*10*t)

xF = np.fft.fft(x)
N = len(xF)
xF = xF[0:N/2]
fr = np.linspace(0,fs/2,N/2)

plt.ion()
plt.plot(fr,abs(xF)**2)

Free Barcode API for .NET

There is a "3 of 9" control on CodeProject: Barcode .NET Control

Get spinner selected items text?

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

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

How does the @property decorator work in Python?

The best explanation can be found here: Python @Property Explained – How to Use and When? (Full Examples) by Selva Prabhakaran | Posted on November 5, 2018

It helped me understand WHY not only HOW.

https://www.machinelearningplus.com/python/python-property/

Installing jQuery?

Install JQuery with only JavaScript. This is not a very good solution if you are developing a website but it's great if you want JQuery in the JavaScript console of a random website that does not use JQuery already.

function loadScript(url, callback)
{
    // adding the script tag to the head as suggested before
   var head = document.getElementsByTagName('head')[0];
   var script = document.createElement('script');
   script.type = 'text/javascript';
   script.src = url;

   // then bind the event to the callback function 
   // there are several events for cross browser compatibility
   script.onreadystatechange = callback;
   script.onload = callback;

   // fire the loading
   head.appendChild(script);
}
loadScript("http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js")

loadScript function thanks to e-satis's answer to Include JavaScript file inside JavaScript file?

Print execution time of a shell command

If I'm starting a long-running process like a copy or hash and I want to know later how long it took, I just do this:

$ date; sha1sum reallybigfile.txt; date

Which will result in the following output:

Tue Jun  2 21:16:03 PDT 2015
5089a8e475cc41b2672982f690e5221469390bc0  reallybigfile.txt
Tue Jun  2 21:33:54 PDT 2015

Granted, as implemented here it isn't very precise and doesn't calculate the elapsed time. But it's dirt simple and sometimes all you need.

How to find the kafka version in linux

You can use for Debian/Ubuntu:

dpkg -l|grep kafka

Expected result should to be like:

ii  confluent-kafka-2.11                   0.11.0.1-1                                 all          publish-subscribe messaging rethought as a distributed commit log
ii  confluent-kafka-connect-elasticsearch  3.3.1-1                                    all          Kafka Connect connector for copying data between Kafka and Elasticsearch
ii  confluent-kafka-connect-hdfs           3.3.1-1                                    all          Kafka Connect connector for copying data between Kafka and Hadoop HDFS
ii  confluent-kafka-connect-jdbc           3.3.1-1                                    all          Kafka Connect connector for JDBC-compatible databases
ii  confluent-kafka-connect-replicator     3.3.1-1                                    all          Kafka Connect connector for replicating topics between Kafka clusters
ii  confluent-kafka-connect-s3             3.3.1-1                                    all          Kafka Connect S3 connector for copying data between Kafka and
ii  confluent-kafka-connect-storage-common 3.3.1-1                                    all          Kafka Connect Storage Common contains packages used by storage
ii  confluent-kafka-rest                   3.3.1-1                                    all          A REST proxy for Kafka

ByRef argument type mismatch in Excel VBA

Something is wrong with that string try like this:

Worksheets(data_sheet).Range("C2").Value = ProcessString(CStr(last_name))

Golang read request body

I could use the GetBody from Request package.

Look this comment in source code from request.go in net/http:

GetBody defines an optional func to return a new copy of Body. It is used for client requests when a redirect requires reading the body more than once. Use of GetBody still requires setting Body. For server requests it is unused."

GetBody func() (io.ReadCloser, error)

This way you can get the body request without make it empty.

Sample:

getBody := request.GetBody
copyBody, err := getBody()
if err != nil {
    // Do something return err
}
http.DefaultClient.Do(request)

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

Given the Django use case, there are two answers to this. Here is its django.utils.html.escape function, for reference:

def escape(html):
    """Returns the given HTML with ampersands, quotes and carets encoded."""
    return mark_safe(force_unicode(html).replace('&', '&amp;').replace('<', '&l
t;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;'))

To reverse this, the Cheetah function described in Jake's answer should work, but is missing the single-quote. This version includes an updated tuple, with the order of replacement reversed to avoid symmetric problems:

def html_decode(s):
    """
    Returns the ASCII decoded version of the given HTML string. This does
    NOT remove normal HTML tags like <p>.
    """
    htmlCodes = (
            ("'", '&#39;'),
            ('"', '&quot;'),
            ('>', '&gt;'),
            ('<', '&lt;'),
            ('&', '&amp;')
        )
    for code in htmlCodes:
        s = s.replace(code[1], code[0])
    return s

unescaped = html_decode(my_string)

This, however, is not a general solution; it is only appropriate for strings encoded with django.utils.html.escape. More generally, it is a good idea to stick with the standard library:

# Python 2.x:
import HTMLParser
html_parser = HTMLParser.HTMLParser()
unescaped = html_parser.unescape(my_string)

# Python 3.x:
import html.parser
html_parser = html.parser.HTMLParser()
unescaped = html_parser.unescape(my_string)

# >= Python 3.5:
from html import unescape
unescaped = unescape(my_string)

As a suggestion: it may make more sense to store the HTML unescaped in your database. It'd be worth looking into getting unescaped results back from BeautifulSoup if possible, and avoiding this process altogether.

With Django, escaping only occurs during template rendering; so to prevent escaping you just tell the templating engine not to escape your string. To do that, use one of these options in your template:

{{ context_var|safe }}
{% autoescape off %}
    {{ context_var }}
{% endautoescape %}

bootstrap datepicker change date event doesnt fire up when manually editing dates or clearing date

The new version has changed.. for the latest version use the code below:

$('#UpToDate').datetimepicker({
        format:'MMMM DD, YYYY',
        maxDate:moment(),
        defaultDate:moment()            
    }).on('dp.change',function(e){
        console.log(e);
    });

How to get current time in python and break up into year, month, day, hour, minute?

Three libraries for accessing and manipulating dates and times, namely datetime, arrow and pendulum, all make these items available in namedtuples whose elements are accessible either by name or index. Moreover, the items are accessible in precisely the same way. (I suppose if I were more intelligent I wouldn't be surprised.)

>>> YEARS, MONTHS, DAYS, HOURS, MINUTES = range(5)
>>> import datetime
>>> import arrow
>>> import pendulum
>>> [datetime.datetime.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]]
[2017, 6, 16, 19, 15]
>>> [arrow.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]]
[2017, 6, 16, 19, 15]
>>> [pendulum.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]]
[2017, 6, 16, 19, 16]

Memory errors and list limits?

If you want to circumvent this problem you could also use the shelve. Then you would create files that would be the size of your machines capacity to handle, and only put them on the RAM when necessary, basically writing to the HD and pulling the information back in pieces so you can process it.

Create binary file and check if information is already in it if yes make a local variable to hold it else write some data you deem necessary.

Data = shelve.open('File01')
   for i in range(0,100):
     Matrix_Shelve = 'Matrix' + str(i)
     if Matrix_Shelve in Data:
        Matrix_local = Data[Matrix_Shelve]
     else:
        Data[Matrix_Selve] = 'somenthingforlater'

Hope it doesn't sound too arcaic.

How do I launch a Git Bash window with particular working directory using a script?

Windows 10

This is basically @lengxuehx's answer, but updated for Win 10, and it assumes your bash installation is from Git Bash for Windows from git's official downloads.

cmd /c (start /b "%cd%" "C:\Program Files\GitW\git-bash.exe") && exit

I ended up using this after I lost my context-menu items for Git Bash as my command to run from the registry settings. In case you're curious about that, I did this:

  1. Create a new key called Bash in the shell key at HKEY_CLASSES_ROOT\Directory\Background\shell
  2. Add a string value to Icon (not a new key!) that is the full path to your git-bash.exe, including the git-bash.exe part. You might need to wrap this in quotes.
  3. Edit the default value of Bash to the text you want to use in the context menu enter image description here
  4. Add a sub-key to Bash called command
  5. Modify command's default value to cmd /c (start /b "%cd%" "C:\Program Files\GitW\git-bash.exe") && exit enter image description here

Then you should be able to close the registry and start using Git Bash from anywhere that's a real directory. For example, This PC is not a real directory.

enter image description here

How to combine date from one field with time from another field - MS SQL Server

  1. If both of your fields are datetime then simply adding those will work.

    eg:

    Declare @d datetime, @t datetime
    set @d = '2009-03-12 00:00:00.000';
    set @t = '1899-12-30 12:30:00.000';
    select @d + @t
    
  2. If you used Date & Time datatype then just cast the time to datetime

    eg:

    Declare @d date, @t time
    set @d = '2009-03-12';
    set @t = '12:30:00.000';
    select @d + cast(@t as datetime)
    

How to launch an application from a browser?

Some applications launches themselves by protocols. like itunes with "itms://" links. I don't know however how you can register that with windows.

How to pass a list from Python, by Jinja2 to JavaScript

I had a similar problem using Flask, but I did not have to resort to JSON. I just passed a list letters = ['a','b','c'] with render_template('show_entries.html', letters=letters), and set

var letters = {{ letters|safe }}

in my javascript code. Jinja2 replaced {{ letters }} with ['a','b','c'], which javascript interpreted as an array of strings.

How to create helper file full of functions in react native?

If you want to use class, you can do this.

Helper.js

  function x(){}

  function y(){}

  export default class Helper{

    static x(){ x(); }

    static y(){ y(); }

  }

App.js

import Helper from 'helper.js';

/****/

Helper.x

HTML/Javascript: how to access JSON data loaded in a script tag with src set

Another solution would be to make use of a server-side scripting language and to simply include json-data inline. Here's an example that uses PHP:

<script id="data" type="application/json"><?php include('stuff.json'); ?></script>
<script>
var jsonData = JSON.parse(document.getElementById('data').textContent)
</script>

The above example uses an extra script tag with type application/json. An even simpler solution is to include the JSON directly into the JavaScript:

<script>var jsonData = <?php include('stuff.json');?>;</script>

The advantage of the solution with the extra tag is that JavaScript code and JSON data are kept separated from each other.

How do I write a SQL query for a specific date range and date time using SQL Server 2008?

"SELECT Applicant.applicantId, Applicant.lastName, Applicant.firstName, Applicant.middleName, Applicant.status,Applicant.companyId, Company.name, Applicant.createDate FROM (Applicant INNER JOIN Company ON Applicant.companyId = Company.companyId) WHERE Applicant.createDate between  '" +dateTimePicker1.Text.ToString() + "'and '"+dateTimePicker2.Text.ToString() +"'";

this is what i did!!

IE11 Document mode defaults to IE7. How to reset?

For the website ensure that IIS HTTP response headers setting and add new key X-UA-Compatible pointing to "IE=edge"

Click here for more details

If you have access to the server, the most reliable way of doing this is to do it on the server itself, in IIS. Go in to IIS HTTP Response Headers. Add Name: X-UA-Compatible Value: IE=edge This will override your browser and your code.

Export DataTable to Excel File

I have done the DataTable to Excel conversion with the following code. Hope it's very easy no need to change more just copy & pest the code replace your variable with your variable, and it will work properly.

First create a folder in your solution Document, and create an Excel file MyTemplate.xlsx. you can change those name according to your requirement. But remember for that you have to change the name in code also.

Please find the following code...

    protected void GetExcel_Click(object sender, EventArgs e)
    {            

        ManageTicketBS objManageTicket = new ManageTicketBS();
        DataTable DT = objManageTicket.GetAlldataByDate();   //this function will bring the data in DataTable format, you can use your function instate of that.  

        string DownloadFileName;
        string FolderPath;
        string FileName = "MyTemplate.xlsx";
        DownloadFileName = Path.GetFileNameWithoutExtension(FileName) + new Random().Next(10000, 99999) + Path.GetExtension(FileName);
        FolderPath = ".\\" + DownloadFileName;

        GetParents(Server.MapPath("~/Document/" + FileName), Server.MapPath("~/Document/" + DownloadFileName), DT);

        string path = Server.MapPath("~/Document/" + FolderPath);
        FileInfo file = new FileInfo(path);
        if (file.Exists)
        {
            try
            {
                HttpResponse response = HttpContext.Current.Response;
                response.Clear();
                response.ClearContent();
                response.ClearHeaders();
                response.Buffer = true;
                response.ContentType = MimeType(Path.GetExtension(FolderPath));
                response.AddHeader("Content-Disposition", "attachment;filename=" + DownloadFileName);
                byte[] data = File.ReadAllBytes(path);
                response.BinaryWrite(data);
                HttpContext.Current.ApplicationInstance.CompleteRequest();
                response.End();
            }

            catch (Exception ex)
            {
                ex.ToString();
            }
            finally
            {
                DeleteOrganisationtoSupplierTemplate(path);
            }
        }
    }
    public string GetParents(string FilePath, string TempFilePath, DataTable DTTBL)
    {
        File.Copy(Path.Combine(FilePath), Path.Combine(TempFilePath), true);
        FileInfo file = new FileInfo(TempFilePath);
        try
        {
            DatatableToExcel(DTTBL, TempFilePath, 0);

            return TempFilePath;

        }

        catch (Exception ex)
        {                
            return "";
        }

    }


    public static string MimeType(string Extension)
    {
        string mime = "application/octetstream";
        if (string.IsNullOrEmpty(Extension))
            return mime;
        string ext = Extension.ToLower();
        Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
        if (rk != null && rk.GetValue("Content Type") != null)
            mime = rk.GetValue("Content Type").ToString();
        return mime;
    }


    static bool DeleteOrganisationtoSupplierTemplate(string filePath)
    {
        try
        {                
            File.Delete(filePath);
            return true;
        }
        catch (IOException)
        {               
            return false;
        }
    }


    public void DatatableToExcel(DataTable dtable, string pFilePath, int excelSheetIndex=1)
    {

        try
        {
            if (dtable != null && dtable.Rows.Count > 0)
            {
                IWorkbook workbook = null;
                ISheet worksheet = null;

                using (FileStream stream = new FileStream(pFilePath, FileMode.Open, FileAccess.ReadWrite))
                {

                    workbook = WorkbookFactory.Create(stream);
                    worksheet = workbook.GetSheetAt(excelSheetIndex);

                    int iRow = 1;



                    foreach (DataRow row in dtable.Rows)
                    {
                        IRow file = worksheet.CreateRow(iRow);
                        int iCol = 0;
                        foreach (DataColumn column in dtable.Columns)
                        {
                            ICell cell = null;
                            object cellValue = row[iCol];

                            switch (column.DataType.ToString())
                            {
                                case "System.Boolean":
                                    if (cellValue != DBNull.Value)
                                    {
                                        cell = file.CreateCell(iCol, CellType.Boolean);

                                        if (Convert.ToBoolean(cellValue)) { cell.SetCellFormula("TRUE()"); }
                                        else { cell.SetCellFormula("FALSE()"); }

                                        //cell.CellStyle = _boolCellStyle;
                                    }
                                    break;

                                case "System.String":
                                    if (cellValue != DBNull.Value)
                                    {
                                        cell = file.CreateCell(iCol, CellType.String);
                                        cell.SetCellValue(Convert.ToString(cellValue));
                                    }
                                    break;

                                case "System.Int32":
                                    if (cellValue != DBNull.Value)
                                    {
                                        cell = file.CreateCell(iCol, CellType.Numeric);
                                        cell.SetCellValue(Convert.ToInt32(cellValue));
                                        //cell.CellStyle = _intCellStyle;
                                    }
                                    break;
                                case "System.Int64":
                                    if (cellValue != DBNull.Value)
                                    {
                                        cell = file.CreateCell(iCol, CellType.Numeric);
                                        cell.SetCellValue(Convert.ToInt64(cellValue));
                                        //cell.CellStyle = _intCellStyle;
                                    }
                                    break;
                                case "System.Decimal":
                                    if (cellValue != DBNull.Value)
                                    {
                                        cell = file.CreateCell(iCol, CellType.Numeric);
                                        cell.SetCellValue(Convert.ToDouble(cellValue));
                                        //cell.CellStyle = _doubleCellStyle;
                                    }
                                    break;
                                case "System.Double":
                                    if (cellValue != DBNull.Value)
                                    {
                                        cell = file.CreateCell(iCol, CellType.Numeric);
                                        cell.SetCellValue(Convert.ToDouble(cellValue));
                                        //cell.CellStyle = _doubleCellStyle;
                                    }
                                    break;

                                case "System.DateTime":
                                    if (cellValue != DBNull.Value)
                                    {
                                        cell = file.CreateCell(iCol, CellType.String);
                                        DateTime dateTime = Convert.ToDateTime(cellValue);
                                        cell.SetCellValue(dateTime.ToString("dd/MM/yyyy"));

                                        DateTime cDate = Convert.ToDateTime(cellValue);
                                        if (cDate != null && cDate.Hour > 0)
                                        {
                                            //cell.CellStyle = _dateTimeCellStyle; 
                                        }
                                        else
                                        {
                                            // cell.CellStyle = _dateCellStyle; 
                                        }
                                    }
                                    break;
                                default:
                                    break;
                            }
                            iCol++;
                        }
                        iRow++;
                    }
                    using (var WritetoExcelfile = new FileStream(pFilePath, FileMode.Create, FileAccess.ReadWrite))
                    {
                        workbook.Write(WritetoExcelfile);
                        WritetoExcelfile.Close();
                        //workbook.Write(stream);
                        stream.Close();
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

This code you just need to copy & pest in your script and add the Namespace as following, Also change the excel file name as previously discussed.

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.SS.Util;

ExecJS and could not find a JavaScript runtime

FYI, this fixed the problem for me... it's a pathing problem: http://forums.freebsd.org/showthread.php?t=35539

Exception in thread "main" java.lang.UnsupportedClassVersionError: a (Unsupported major.minor version 51.0)

Assuming you are using Eclipse, on a MAC you can:

  1. Launch Eclipse.app
  2. Choose Eclipse -> Preferences
  3. Choose Java -> Installed JREs
  4. Click the Add... button
  5. Choose MacOS X VM as the JRE type. Press Next.
  6. In the "JRE Home:" field, type /Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Home
  7. You should see the system libraries in the list titled "JRE system libraries:"
  8. Give the JRE a name. The recommended name is JDK 1.7. Click Finish.
  9. Check the checkbox next to the JRE entry you just created. This will cause Eclipse to use it as the default JRE for all new Java projects. Click OK.
  10. Now, create a new project. For this verification, from the menu, select File -> New -> Java Project.
  11. In the dialog that appears, enter a new name for your project. For this verification, type Test17Project
  12. In the JRE section of the dialog, select Use default JRE (currently JDK 1.7)
  13. Click Finish.

Hope this helps

R * not meaningful for factors ERROR

new[,2] is a factor, not a numeric vector. Transform it first

new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5

pointer to array c++

The parenthesis are superfluous in your example. The pointer doesn't care whether there's an array involved - it only knows that its pointing to an int

  int g[] = {9,8};
  int (*j) = g;

could also be rewritten as

  int g[] = {9,8};
  int *j = g;

which could also be rewritten as

  int g[] = {9,8};
  int *j = &g[0];

a pointer-to-an-array would look like

  int g[] = {9,8};
  int (*j)[2] = &g;

  //Dereference 'j' and access array element zero
  int n = (*j)[0];

There's a good read on pointer declarations (and how to grok them) at this link here: http://www.codeproject.com/Articles/7042/How-to-interpret-complex-C-C-declarations

CSS3 Fade Effect

You can't transition between two background images, as there's no way for the browser to know what you want to interpolate. As you've discovered, you can transition the background position. If you want the image to fade in on mouse over, I think the best way to do it with CSS transitions is to put the image on a containing element and then animate the background colour to transparent on the link itself:

span {
    background: url(button.png) no-repeat 0 0;
}
a {
    width: 32px;
    height: 32px;
    text-align: left;
    background: rgb(255,255,255);

    -webkit-transition: background 300ms ease-in 200ms; /* property duration timing-function delay */
    -moz-transition: background 300ms ease-in 200ms;
    -o-transition: background 300ms ease-in 200ms;
    transition: background 300ms ease-in 200ms;
    }
a:hover {
    background: rgba(255,255,255,0);
}

ASP.NET set hiddenfield a value in Javascript

Prior to ASP.Net 4.0

ClientID

Get the client id generated in the page that uses Master page. As Master page is UserControl type, It will have its own Id and it treats the page as Child control and generates a different id with prefix like ctrl_.

This can be resolved by using <%= ControlName.ClientID %> in a page and can be assigned to any string or a javascript variables that can be referred later.

var myHidden=document.getElementById('<%= hdntxtbxTaksit.ClientID %>');
  • Asp.net server control id will be vary if you use Master page.

ASP.Net 4.0 +

ClientIDMode Property

Use this property to control how you want to generate the ID for you. For your case setting ClientIDMode="static" in page level will resolve the problem. The same thing can be applied at control level as well.

E: gnupg, gnupg2 and gnupg1 do not seem to be installed, but one of them is required for this operation

In addition to existing answers:

RUN apt-get update && apt-get install -y gnupg

-y flag agrees to terms during installation process. It is important not to break the build

using where and inner join in mysql

Try this:

SELECT Locations.Name, Schools.Name
FROM Locations
INNER JOIN School_Locations ON School_Locations.Locations_Id = Locations.Id
INNER JOIN Schools ON School.Id = Schools_Locations.School_Id
WHERE Locations.Type = "coun"

You can join Locations to School_Locations and then School_Locations to School. This forms a set of all related Locations and Schools, which you can then widdle down using the WHERE clause to those whose Location is of type "coun."

A better way to check if a path exists or not in PowerShell

The alias solution you posted is clever, but I would argue against its use in scripts, for the same reason I don't like using any aliases in scripts; it tends to harm readability.

If this is something you want to add to your profile so you can type out quick commands or use it as a shell, then I could see that making sense.

You might consider piping instead:

if ($path | Test-Path) { ... }
if (-not ($path | Test-Path)) { ... }
if (!($path | Test-Path)) { ... }

Alternatively, for the negative approach, if appropriate for your code, you can make it a positive check then use else for the negative:

if (Test-Path $path) {
    throw "File already exists."
} else {
   # The thing you really wanted to do.
}

What is the best way to update the entity in JPA

Using executeUpdate() on the Query API is faster because it bypasses the persistent context .However , by-passing persistent context would cause the state of instance in the memory and the actual values of that record in the DB are not synchronized.

Consider the following example :

 Employee employee= (Employee)entityManager.find(Employee.class , 1);
 entityManager
     .createQuery("update Employee set name = \'xxxx\' where id=1")
     .executeUpdate();

After flushing, the name in the DB is updated to the new value but the employee instance in the memory still keeps the original value .You have to call entityManager.refresh(employee) to reload the updated name from the DB to the employee instance.It sounds strange if your codes still have to manipulate the employee instance after flushing but you forget to refresh() the employee instance as the employee instance still contains the original values.

Normally , executeUpdate() is used in the bulk update process as it is faster due to bypassing the persistent context

The right way to update an entity is that you just set the properties you want to updated through the setters and let the JPA to generate the update SQL for you during flushing instead of writing it manually.

   Employee employee= (Employee)entityManager.find(Employee.class ,1);
   employee.setName("Updated Name");

Android: Quit application when press back button

It means your previous activity in stack when you start this activity. Add finish(); after the line in which you calling this activity.

In your all previous activity. when you start new activity like-

startActivity(I);

Add finish(); after this.

UTF-8, UTF-16, and UTF-32

In short:

  • UTF-8: Variable-width encoding, backwards compatible with ASCII. ASCII characters (U+0000 to U+007F) take 1 byte, code points U+0080 to U+07FF take 2 bytes, code points U+0800 to U+FFFF take 3 bytes, code points U+10000 to U+10FFFF take 4 bytes. Good for English text, not so good for Asian text.
  • UTF-16: Variable-width encoding. Code points U+0000 to U+FFFF take 2 bytes, code points U+10000 to U+10FFFF take 4 bytes. Bad for English text, good for Asian text.
  • UTF-32: Fixed-width encoding. All code points take four bytes. An enormous memory hog, but fast to operate on. Rarely used.

In long: see Wikipedia: UTF-8, UTF-16, and UTF-32.

Listing all the folders subfolders and files in a directory using php

https://3v4l.org/VsQLb Example Here

function listdirs($dir) {
    static $alldirs = array();
    $dirs = glob($dir . '/*', GLOB_ONLYDIR);
    if (count($dirs) > 0) {
        foreach ($dirs as $d) $alldirs[] = $d;
    }
    foreach ($dirs as $dir) listdirs($dir);
    return $alldirs;
}

How to Set Opacity (Alpha) for View in Android

For API < 11 for textView color I did the following:

int textViewColor = textView.getTextColors().getDefaultColor(); 
textView.setTextColor(Color.argb(128, Color.red(textViewColor), Color.green(textViewColor), Color.blue(textViewColor))); //50% transparent

A little cumbersome, but hey, it works :-)

phpmyadmin - count(): Parameter must be an array or an object that implements Countable

Based on @jbator's answer, you can edit /usr/share/phpmyadmin/libraries/plugin_interface.lib.php and replace this line:

if ($options != null && count($options) > 0) {

with these lines:

if ($options != null &&
   ((is_array($options) || $options instanceof Countable) && count($options) > 0) ||
   (method_exists($options, 'getProperties') && $options->getProperties() != null && (is_array($options->getProperties()) || $options->getProperties() instanceof Countable) && count($options->getProperties()) > 0)) {

In this way, we won't have empty exported file.

Display filename before matching line

No trick necessary.

grep --with-filename 'pattern' file

With line numbers:

grep -n --with-filename 'pattern' file

Clicking a checkbox with ng-click does not update the model

Replacing ng-model with ng-checked works for me.

What is the advantage of using REST instead of non-REST HTTP?

Discovery is far easier in REST. We have WADL documents (similar to WSDL in traditional webservices) that will help you to advertise your service to the world. You can use UDDI discoveries as well. With traditional HTTP POST and GET people may not know your message request and response schemas to call you.

Function not defined javascript

The actual problem is with your

showList function.

There is an extra ')' after 'visible'.

Remove that and it will work fine.

function showList()
{
  if (document.getElementById("favSports").style.visibility == "hidden") 
    {
       // document.getElementById("favSports").style.visibility = "visible");  
       // your code
       document.getElementById("favSports").style.visibility = "visible";
       // corrected code
    }
}

<strong> vs. font-weight:bold & <em> vs. font-style:italic

The <em> element - from W3C (HTML5 reference)

YES! There is a clear difference.

The <em> element represents stress emphasis of its contents. The level of emphasis that a particular piece of content has is given by its number of ancestor <em> elements.

<strong>  =  important content
<em>      =  stress emphasis of its contents

The placement of emphasis changes the meaning of the sentence. The element thus forms an integral part of the content. The precise way in which emphasis is used in this way depends on the language.

Note!

  1. The <em> element also isnt intended to convey importance; for that purpose, the <strong> element is more appropriate.

  2. The <em> element isn't a generic "italics" element. Sometimes, text is intended to stand out from the rest of the paragraph, as if it was in a different mood or voice. For this, the i element is more appropriate.

Reference (examples): See W3C Reference

What's the difference between HEAD, working tree and index, in Git?

This is an inevitably long yet easy to follow explanation from ProGit book:

Note: For reference you can read Chapter 7.7 of the book, Reset Demystified

Git as a system manages and manipulates three trees in its normal operation:

  • HEAD: Last commit snapshot, next parent
  • Index: Proposed next commit snapshot
  • Working Directory: Sandbox

The HEAD

HEAD is the pointer to the current branch reference, which is in turn a pointer to the last commit made on that branch. That means HEAD will be the parent of the next commit that is created. It’s generally simplest to think of HEAD as the snapshot of your last commit on that branch.

What does it contain?
To see what that snapshot looks like run the following in root directory of your repository:

                                 git ls-tree -r HEAD

it would result in something like this:

                       $ git ls-tree -r HEAD  
                       100644 blob a906cb2a4a904a152... README  
                       100644 blob 8f94139338f9404f2... Rakefile  
                       040000 tree 99f1a6d12cb4b6f19... lib  

The Index

Git populates this index with a list of all the file contents that were last checked out into your working directory and what they looked like when they were originally checked out. You then replace some of those files with new versions of them, and git commit converts that into the tree for a new commit.

What does it contain?
Use git ls-files -s to see what it looks like. You should see something like this:

                 100644 a906cb2a4a904a152e80877d4088654daad0c859 0 README   
                 100644 8f94139338f9404f26296befa88755fc2598c289 0 Rakefile  
                 100644 47c6340d6459e05787f644c2447d2595f5d3a54b 0 lib/simplegit.rb  

The Working Directory

This is where your files reside and where you can try changes out before committing them to your staging area (index) and then into history.

Visualized Sample

Let's see how do these three trees (As the ProGit book refers to them) work together?
Git’s typical workflow is to record snapshots of your project in successively better states, by manipulating these three trees. Take a look at this picture:

enter image description here

To get a good visualized understanding consider this scenario. Say you go into a new directory with a single file in it. Call this v1 of the file. It is indicated in blue. Running git init will create a Git repository with a HEAD reference which points to the unborn master branch

enter image description here

At this point, only the working directory tree has any content. Now we want to commit this file, so we use git add to take content in the working directory and copy it to the index.

enter image description here

Then we run git commit, which takes the contents of the index and saves it as a permanent snapshot, creates a commit object which points to that snapshot, and updates master to point to that commit.

enter image description here

If we run git status, we’ll see no changes, because all three trees are the same.

The beautiful point

git status shows the difference between these trees in the following manner:

  • If the Working Tree is different from index, then git status will show there are some changes not staged for commit
  • If the Working Tree is the same as index, but they are different from HEAD, then git status will show some files under changes to be committed section in its result
  • If the Working Tree is different from the index, and index is different from HEAD, then git status will show some files under changes not staged for commit section and some other files under changes to be committed section in its result.

For the more curious

Note about git reset command
Hopefully, knowing how reset command works will further brighten the reason behind the existence of these three trees.

reset command is your Time Machine in git which can easily take you back in time and bring some old snapshots for you to work on. In this manner, HEAD is the wormhole through which you can travel in time. Let's see how it works with an example from the book:

Consider the following repository which has a single file and 3 commits which are shown in different colours and different version numbers:

enter image description here

The state of trees is like the next picture:

enter image description here

Step 1: Moving HEAD (--soft):

The first thing reset will do is move what HEAD points to. This isn’t the same as changing HEAD itself (which is what checkout does). reset moves the branch that HEAD is pointing to. This means if HEAD is set to the master branch, running git reset 9e5e6a4 will start by making master point to 9e5e6a4. If you call reset with --soft option it will stop here, without changing index and working directory. Our repo will look like this now:
Notice: HEAD~ is the parent of HEAD

enter image description here

Looking a second time at the image, we can see that the command essentially undid the last commit. As the working tree and the index are the same but different from HEAD, git status will now show changes in green ready to be committed.

Step 2: Updating the index (--mixed):

This is the default option of the command

Running reset with --mixed option updates the index with the contents of whatever snapshot HEAD points to currently, leaving Working Directory intact. Doing so, your repository will look like when you had done some work that is not staged and git status will show that as changes not staged for commit in red. This option will also undo the last commit and also unstage all the changes. It's like you made changes but have not called git add command yet. Our repo would look like this now:

enter image description here

Step 3: Updating the Working Directory (--hard)

If you call reset with --hard option it will copy contents of the snapshot HEAD is pointing to into HEAD, index and Working Directory. After executing reset --hard command, it would mean like you got back to a previous point in time and haven't done anything after that at all. see the picture below:

enter image description here

Conclusion

I hope now you have a better understanding of these trees and have a great idea of the power they bring to you by enabling you to change your files in your repository to undo or redo things you have done mistakenly.

msvcr110.dll is missing from computer error while installing PHP

I had installed PHP in IIS7 on Windows Server 2008 R2 using the Web Platform Installer. It did not work out of the box. I had to install the Visual C++ Redistributable for VS 2012 Update 4 (32bit) as found here http://www.microsoft.com/en-us/download/details.aspx?id=30679 .

shell script to remove a file if it already exist

Something like this would work

#!/bin/sh

if [ -fe FILE ]
then 
    rm FILE
fi 

-f checks if it's a regular file

-e checks if the file exist

Introduction to if for more information

EDIT : -e used with -f is redundant, fo using -f alone should work too

Opening a folder in explorer and selecting a file

Use this method:

Process.Start(String, String)

First argument is an application (explorer.exe), second method argument are arguments of the application you run.

For example:

in CMD:

explorer.exe -p

in C#:

Process.Start("explorer.exe", "-p")

How to remove "disabled" attribute using jQuery?

I think you are trying to toggle the disabled state, in witch case you should use this (from this question):

$(".inputDisabled").prop('disabled', function (_, val) { return ! val; });

Here is a working fiddle.

Remove characters after specific character in string, then remove substring?

I second Hightechrider: there is a specialized Url class already built for you.

I must also point out, however, that the PHP's replaceAll uses regular expressions for search pattern, which you can do in .NET as well - look at the RegEx class.

Looping through a hash, or using an array in PowerShell

You can also do this without a variable

@{
  'foo' = 222
  'bar' = 333
  'baz' = 444
  'qux' = 555
} | % getEnumerator | % {
  $_.key
  $_.value
}

adb shell command to make Android package uninstall dialog appear

In my case, I do an adb shell pm list packages to see first what are the packages/apps installed in my Android device or emulator, then upon locating the desired package/app, I do an adb shell pm uninstall -k com.package.name.

How can I get the MAC and the IP address of a connected client in PHP?

under linux using iptables you can log to a file each request to web server with mac address and ip. from php lookup last item with ip address and get mac address.

As stated remember that the mac address is from last router on the trace.

How to remove time portion of date in C# in DateTime object only?

Here is another method using String.Format

    DateTime todaysDate = DateTime.UtcNow;

    string dateString = String.Format("{0:dd/MM/yyyy}", todaysDate);

    Console.WriteLine("Date with Time: "+ todaysDate.ToString());

    Console.WriteLine("Date Only : " + dateString);

Output:

Date with Time: 9/4/2016 11:42:16 AM

Date Only : 04/09/2016

This also works if the Date Time is stored in database.

For More Date and Time formatting check these links:

Reference 1

Reference 2

Hope helps.

Setting environment variables in Linux using Bash

export VAR=value will set VAR to value. Enclose it in single quotes if you want spaces, like export VAR='my val'. If you want the variable to be interpolated, use double quotes, like export VAR="$MY_OTHER_VAR".

How do I find the data directory for a SQL Server instance?

You can find default Data and Log locations for the current SQL Server instance by using the following T-SQL:

DECLARE @defaultDataLocation nvarchar(4000)
DECLARE @defaultLogLocation nvarchar(4000)

EXEC master.dbo.xp_instance_regread
    N'HKEY_LOCAL_MACHINE',
    N'Software\Microsoft\MSSQLServer\MSSQLServer',
    N'DefaultData', 
    @defaultDataLocation OUTPUT

EXEC master.dbo.xp_instance_regread
    N'HKEY_LOCAL_MACHINE',
    N'Software\Microsoft\MSSQLServer\MSSQLServer',
    N'DefaultLog', 
    @defaultLogLocation OUTPUT

SELECT @defaultDataLocation AS 'Default Data Location',
       @defaultLogLocation AS 'Default Log Location'

JavaFX How to set scene background image

You can change style directly for scene using .root class:

.root {
    -fx-background-image: url("https://www.google.com/images/srpr/logo3w.png");
}

Add this to CSS and load it as "Uluk Biy" described in his answer.

UILabel font size?

**You can set font size by these properties **

timedisplayLabel= [[UILabel alloc]initWithFrame:CGRectMake(70, 194, 180, 60)];

[timedisplayLabel setTextAlignment:NSTextAlignmentLeft];

[timedisplayLabel setBackgroundColor:[UIColor clearColor]];

[timedisplayLabel setAdjustsFontSizeToFitWidth:YES];

[timedisplayLabel setTextColor:[UIColor blackColor]];

[timedisplayLabel setUserInteractionEnabled:NO];

[timedisplayLabel setFont:[UIFont fontWithName:@"digital-7" size:60]];

timedisplayLabel.layer.shadowColor =[[UIColor whiteColor ]CGColor ];

timedisplayLabel.layer.shadowOffset=(CGSizeMake(0, 0));

timedisplayLabel.layer.shadowOpacity=1;

timedisplayLabel.layer.shadowRadius=3.0;

timedisplayLabel.layer.masksToBounds=NO;

timedisplayLabel.shadowColor=[UIColor darkGrayColor];

timedisplayLabel.shadowOffset=CGSizeMake(0, 2);

C# DLL config file

Seems like this config files are really confusing to clarify as their behaviour changes from the dev environment to deployment. Apparently a DLL can have its own config file, but once you copy and paste the dll (together with their config file) elsewhere, the whole thing stopped working. The only solution is to manually merge the app.config files into a single file, which will only be used by the exec. For e.g. myapp.exe will have a myapp.exe.config file that contains all settings for all dlls used by myapp.exe. I'm using VS 2008.

Reload activity in Android

Reloading your whole activity may be a heavy task. Just put the part of code that has to be refreshed in (kotlin):

override fun onResume() {
    super.onResume()
    //here...
}

Java:

@Override
public void onResume(){
    super.onResume();
    //here...

}

And call "onResume()" whenever needed.

xsl: how to split strings?

If your XSLT processor supports EXSLT, you can use str:tokenize, otherwise, the link contains an implementation using functions like substring-before.

What is the advantage of using heredoc in PHP?

First of all, all the reasons are subjective. It's more like a matter of taste rather than a reason.

Personally, I find heredoc quite useless and use it occasionally, most of the time when I need to get some HTML into a variable and don't want to bother with output buffering, to form an HTML email message for example.

Formatting doesn't fit general indentation rules, but I don't think it's a big deal.

       //some code at it's proper level
       $this->body = <<<HERE
heredoc text sticks to the left border
but it seems OK to me.
HERE;
       $this->title = "Feedback";
       //and so on

As for the examples in the accepted answer, it is merely cheating.
String examples, in fact, being more concise if one won't cheat on them

$sql = "SELECT * FROM $tablename
        WHERE id in [$order_ids_list]
        AND product_name = 'widgets'";

$x = 'The point of the "argument" was to illustrate the use of here documents';

How to add to an existing hash in Ruby

my_hash = {:a => 5}
my_hash[:key] = "value"

How to convert IPython notebooks to PDF and HTML?

From the docs:

If you want to provide others with a static HTML or PDF view of your notebook, use the Print button. This opens a static view of the document, which you can print to PDF using your operating system’s facilities, or save to a file with your web browser’s ‘Save’ option (note that typically, this will create both an html file and a directory called notebook_name_files next to it that contains all the necessary style information, so if you intend to share this, you must send the directory along with the main html file).