Programs & Examples On #Oracleinternals

wampserver doesn't go green - stays orange

Make a Ctrl+Alt+Suppr in order to see if no other Apache version is ever runing on your computer. It was the case for me, I just stop them and the light pass green!

Cheers!

Failed to build gem native extension — Rails install

mkmf is part of the ruby1.9.1-dev package. This package contains the header files needed for extension libraries for Ruby 1.9.1. You need to install the ruby1.9.1-dev package by doing:

sudo apt-get install ruby1.9.1-dev

Then you can install Rails as per normal.

Generally it's easier to just do:

sudo apt-get install ruby-dev

Two submit buttons in one form

Since you didn't specify what server-side scripting method you're using, I'll give you an example that works for Python, using CherryPy (although it may be useful for other contexts, too):

<button type="submit" name="register">Create a new account</button>
<button type="submit" name="login">Log into your account</button>

Rather than using the value to determine which button was pressed, you can use the name (with the <button> tag instead of <input>). That way, if your buttons happen to have the same text, it won't cause problems. The names of all form items, including buttons, are sent as part of the URL. In CherryPy, each of those is an argument for a method that does the server-side code. So, if your method just has **kwargs for its parameter list (instead of tediously typing out every single name of each form item) then you can check to see which button was pressed like this:

if "register" in kwargs:
    pass #Do the register code
elif "login" in kwargs:
    pass #Do the login code

How to make an ng-click event conditional?

I use the && expression which works perfectly for me.

For example,

<button ng-model="vm.slideOneValid" ng-disabled="!vm.slideOneValid" ng-click="vm.slideOneValid && vm.nextSlide()" class="btn btn-light-green btn-medium pull-right">Next</button>

If vm.slideOneValid is false, the second part of the expression is not fired. I know this is putting logic into the DOM, but it's a quick a dirty way to get ng-disabled and ng-click to place nice.

Just remember to add ng-model to the element to make ng-disabled work.

Access Session attribute on jstl

You don't need the jsp:useBean to set the model if you already have a controller which prepared the model.

Just access it plain by EL:

<p>${Questions.questionPaperID}</p>
<p>${Questions.question}</p>

or by JSTL <c:out> tag if you'd like to HTML-escape the values or when you're still working on legacy Servlet 2.3 containers or older when EL wasn't supported in template text yet:

<p><c:out value="${Questions.questionPaperID}" /></p>
<p><c:out value="${Questions.question}" /></p>

See also:


Unrelated to the problem, the normal practice is by the way to start attribute name with a lowercase, like you do with normal variable names.

session.setAttribute("questions", questions);

and alter EL accordingly to use ${questions}.

Also note that you don't have any JSTL tag in your code. It's all plain JSP.

Converting std::__cxx11::string to std::string

In my case, I was having a similar problem:

/usr/bin/ld: Bank.cpp:(.text+0x19c): undefined reference to 'Account::SetBank(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)' collect2: error: ld returned 1 exit status

After some researches, I realized that the problem was being generated by the way that Visual Studio Code was compiling the Bank.cpp file. So, to solve that, I just prompted the follow command in order to compile the c++ file sucessful:

g++ Bank.cpp Account.cpp -o Bank

With the command above, It was able to linkage correctly the Header, Implementations and Main c++ files.

OBS: My g++ version: 9.3.0 on Ubuntu 20.04

How to add new line in Markdown presentation?

How to add new line in Markdown presentation?

Check the following resource Line Return

To force a line return, place two empty spaces at the end of a line.

Why can't I call a public method in another class?

For example 1 and 2 you need to create static methods:

public static string InstanceMethod() {return "Hello World";}

Then for example 3 you need an instance of your object to invoke the method:

object o = new object();
string s = o.InstanceMethod();

How to get a random number between a float range?

Most commonly, you'd use:

import random
random.uniform(a, b) # range [a, b) or [a, b] depending on floating-point rounding

Python provides other distributions if you need.

If you have numpy imported already, you can used its equivalent:

import numpy as np
np.random.uniform(a, b) # range [a, b)

Again, if you need another distribution, numpy provides the same distributions as python, as well as many additional ones.

Angular CLI Error: The serve command requires to be run in an Angular project, but a project definition could not be found

I am using ionciv1, in the file ionic.config.json delete the angular type key and it worked correctly

example:

  {
  "name": "nombre",
  "integrations": {
    "cordova": {}
  },
  "type": "angular", // delete
  "gulpStartupTasks": [
    "sass",
    "templatecache",
    "ng_annotate",
    "useref",
    "watch"
  ],
  "watchPatterns": [
    "www/**/*",
    "!www/lib/**/*"
  ],
  "browsers": [
    {
      "platform": "android",
      "browser": "crosswalk",
      "version": "12.41.296.5"
    }
  ],
  "id": "0.1"
}

solved

     {
      "name": "nombre",
      "integrations": {
        "cordova": {}
      },
      "gulpStartupTasks": [
        "sass",
        "templatecache",
        "ng_annotate",
        "useref",
        "watch"
      ],
      "watchPatterns": [
        "www/**/*",
        "!www/lib/**/*"
      ],
      "browsers": [
        {
          "platform": "android",
          "browser": "crosswalk",
          "version": "12.41.296.5"
        }
      ],
      "id": "0.1"
    }

Is there an equivalent to the SUBSTRING function in MS Access SQL?

I have worked alot with msaccess vba. I think you are looking for MID function

example

    dim myReturn as string
    myreturn = mid("bonjour tout le monde",9,4)

will give you back the value "tout"

How to check Oracle patches are installed?

Maybe you need "sys." before:

select * from sys.registry$history;

Meaning of @classmethod and @staticmethod for beginner?

Rostyslav Dzinko's answer is very appropriate. I thought I could highlight one other reason you should choose @classmethod over @staticmethod when you are creating an additional constructor.

In the example above, Rostyslav used the @classmethod from_string as a Factory to create Date objects from otherwise unacceptable parameters. The same can be done with @staticmethod as is shown in the code below:

class Date:
  def __init__(self, month, day, year):
    self.month = month
    self.day   = day
    self.year  = year


  def display(self):
    return "{0}-{1}-{2}".format(self.month, self.day, self.year)


  @staticmethod
  def millenium(month, day):
    return Date(month, day, 2000)

new_year = Date(1, 1, 2013)               # Creates a new Date object
millenium_new_year = Date.millenium(1, 1) # also creates a Date object. 

# Proof:
new_year.display()           # "1-1-2013"
millenium_new_year.display() # "1-1-2000"

isinstance(new_year, Date) # True
isinstance(millenium_new_year, Date) # True

Thus both new_year and millenium_new_year are instances of the Date class.

But, if you observe closely, the Factory process is hard-coded to create Date objects no matter what. What this means is that even if the Date class is subclassed, the subclasses will still create plain Date objects (without any properties of the subclass). See that in the example below:

class DateTime(Date):
  def display(self):
      return "{0}-{1}-{2} - 00:00:00PM".format(self.month, self.day, self.year)


datetime1 = DateTime(10, 10, 1990)
datetime2 = DateTime.millenium(10, 10)

isinstance(datetime1, DateTime) # True
isinstance(datetime2, DateTime) # False

datetime1.display() # returns "10-10-1990 - 00:00:00PM"
datetime2.display() # returns "10-10-2000" because it's not a DateTime object but a Date object. Check the implementation of the millenium method on the Date class for more details.

datetime2 is not an instance of DateTime? WTF? Well, that's because of the @staticmethod decorator used.

In most cases, this is undesired. If what you want is a Factory method that is aware of the class that called it, then @classmethod is what you need.

Rewriting Date.millenium as (that's the only part of the above code that changes):

@classmethod
def millenium(cls, month, day):
    return cls(month, day, 2000)

ensures that the class is not hard-coded but rather learnt. cls can be any subclass. The resulting object will rightly be an instance of cls.
Let's test that out:

datetime1 = DateTime(10, 10, 1990)
datetime2 = DateTime.millenium(10, 10)

isinstance(datetime1, DateTime) # True
isinstance(datetime2, DateTime) # True


datetime1.display() # "10-10-1990 - 00:00:00PM"
datetime2.display() # "10-10-2000 - 00:00:00PM"

The reason is, as you know by now, that @classmethod was used instead of @staticmethod

Java better way to delete file if exists

if you have the file inside a dirrectory called uploads in your project. bellow code can be used.

Path root = Paths.get("uploads");
File existingFile = new File(this.root.resolve("img.png").toUri());

if (existingFile.exists() && existingFile.isFile()) {
     existingFile.delete();
   }

OR

If it is inside a different directory this solution can be used.

File existingFile = new File("D:\\<path>\\img.png");

if (existingFile.exists() && existingFile.isFile()) {
    existingFile.delete();
  }

How can I get date and time formats based on Culture Info?

You can retrieve the format strings from the CultureInfo DateTimeFormat property, which is a DateTimeFormatInfo instance. This in turn has properties like ShortDatePattern and ShortTimePattern, containing the format strings:

CultureInfo us = new CultureInfo("en-US");
string shortUsDateFormatString = us.DateTimeFormat.ShortDatePattern;
string shortUsTimeFormatString = us.DateTimeFormat.ShortTimePattern;

CultureInfo uk = new CultureInfo("en-GB");
string shortUkDateFormatString = uk.DateTimeFormat.ShortDatePattern;
string shortUkTimeFormatString = uk.DateTimeFormat.ShortTimePattern;

If you simply want to format the date/time using the CultureInfo, pass it in as your IFormatter when converting the DateTime to a string, using the ToString method:

string us = myDate.ToString(new CultureInfo("en-US"));
string uk = myDate.ToString(new CultureInfo("en-GB"));

Am I trying to connect to a TLS-enabled daemon without TLS?

The underlining problem is simple – lack of permission to /var/run/docker.sock unix domain socket.

From Daemon socket option chapter of Docker Command Line reference for Docker 1.6.0:

By default, a unix domain socket (or IPC socket) is created at /var/run/docker.sock, requiring either root permission, or docker group membership.

Steps necessary to grant rights to users are nicely described in Docker installation instructions for Fedora:

Granting rights to users to use Docker

The docker command line tool contacts the docker daemon process via a socket file /var/run/docker.sock owned by root:root. Though it's recommended to use sudo for docker commands, if users wish to avoid it, an administrator can create a docker group, have it own /var/run/docker.sock, and add users to this group.

$ sudo groupadd docker
$ sudo chown root:docker /var/run/docker.sock
$ sudo usermod -a -G docker $USERNAME

Log out and log back in for above changes to take effect. Please note that Docker packages of some Linux distributions (Ubuntu) do already place /var/run/docker.sock in the docker group making the first two of above steps unnecessary.

In case of OS X and boot2docker the situation is different; the Docker daemon runs inside a VM so the DOCKER_HOST environment variable must be set to this VM so that the Docker client could find the Docker daemon. This is done by running $(boot2docker shellinit) in the shell.

How to serve an image using nodejs

Vanilla node version as requested:

var http = require('http');
var url = require('url');
var path = require('path');
var fs = require('fs');

http.createServer(function(req, res) {
  // parse url
  var request = url.parse(req.url, true);
  var action = request.pathname;
  // disallow non get requests
  if (req.method !== 'GET') {
    res.writeHead(405, {'Content-Type': 'text/plain' });
    res.end('405 Method Not Allowed');
    return;
  }
  // routes
  if (action === '/') {
    res.writeHead(200, {'Content-Type': 'text/plain' });
    res.end('Hello World \n');
    return;
  }
  // static (note not safe, use a module for anything serious)
  var filePath = path.join(__dirname, action).split('%20').join(' ');
  fs.exists(filePath, function (exists) {
    if (!exists) {
       // 404 missing files
       res.writeHead(404, {'Content-Type': 'text/plain' });
       res.end('404 Not Found');
       return;
    }
    // set the content type
    var ext = path.extname(action);
    var contentType = 'text/plain';
    if (ext === '.gif') {
       contentType = 'image/gif'
    }
    res.writeHead(200, {'Content-Type': contentType });
    // stream the file
    fs.createReadStream(filePath, 'utf-8').pipe(res);
  });
}).listen(8080, '127.0.0.1');

How to set max and min value for Y axis

In my case, I used a callback in yaxis ticks, my values are in percent and when it reaches 100% it doesn't show the dot, I used this :

      yAxes: [{
                   ticks: {
                       beginAtZero: true,
                       steps: 10,
                       stepValue: 5,
                       min: 0,
                       max: 100.1,
                       callback: function(value, index, values) {
                           if (value !== 100.1) {
                               return values[index]
                           }
                       }
                   }
               }],

And it worked well.

How do I manage MongoDB connections in a Node.js web application?

I have been using generic-pool with redis connections in my app - I highly recommend it. Its generic and I definitely know it works with mysql so I don't think you'll have any problems with it and mongo

https://github.com/coopernurse/node-pool

PHP Converting Integer to Date, reverse of strtotime

Can you try this,

echo date("Y-m-d H:i:s", 1388516401);

As noted by theGame,

This means that you pass in a string value for the time, and optionally a value for the current time, which is a UNIX timestamp. The value that is returned is an integer which is a UNIX timestamp.

echo strtotime("2014-01-01 00:00:01");

This will return into the value 1388516401, which is the UNIX timestamp for the date 2014-01-01. This can be confirmed using the date() function as like below:

echo date('Y-m-d', 1198148400); // echos 2014-01-01

How to initialize struct?

Your struct can have methods and properties... why not try

public struct MyStruct { 
    public string s;
    public int length { return s.Length; }
}

Correction @Guffa's answer shows that it is possible... more info here: http://www.codeproject.com/KB/cs/Csharp_implicit_operator.aspx

How to stop/cancel 'git log' command in terminal?

You can hit the key q (for quit) and it should take you to the prompt.

Please see this link.

Why do I get "Exception; must be caught or declared to be thrown" when I try to compile my Java code?

In actionPerformed(ActionEvent e) you call encrypt(), which is declared to throw Exception. However, actionPerformed neither catches this Exception (with try/catch around the call to encrypt()) nor declares that it throws Exception itself.

Your encrypt method, however, does not truly throw Exception. It swallows all Exceptions without even as much as logging a complaint. (Bad practice and bad style!)

Also, your encrypt method does the following:

public static byte[] encrypt(String toEncrypt) throws Exception {
  try{
    ....
    return encrypted; // HERE YOU CORRECTLY RETURN A VALUE
  } catch(Exception e) {
  }
  // YOU DO NOT RETURN ANYTHING HERE
}

That is, if you do catch any Exception, you discard it silently and then fall off the bottom of your encrypt method without actually returning anything. This won't compile (as you see), because a method that is declared to return a value must either return a value or throw an Exception for every single possible code path.

How to extract text from a string using sed?

How about using grep -E?

echo "This is 02G05 a test string 20-Jul-2012" | grep -Eo '[0-9]+G[0-9]+'

Detect change to ngModel on a select tag (Angular 2)

Update:

Separate the event and property bindings:

<select [ngModel]="selectedItem" (ngModelChange)="onChange($event)">
onChange(newValue) {
    console.log(newValue);
    this.selectedItem = newValue;  // don't forget to update the model here
    // ... do other stuff here ...
}

You could also use

<select [(ngModel)]="selectedItem" (ngModelChange)="onChange($event)">

and then you wouldn't have to update the model in the event handler, but I believe this causes two events to fire, so it is probably less efficient.


Old answer, before they fixed a bug in beta.1:

Create a local template variable and attach a (change) event:

<select [(ngModel)]="selectedItem" #item (change)="onChange(item.value)">

plunker

See also How can I get new selection in "select" in Angular 2?

How to convert string to boolean in typescript Angular 4

Define extension: String+Extension.ts

interface String {
  toBoolean(): boolean
}

String.prototype.toBoolean = function (): boolean {
  switch (this) {
    case 'true':
    case '1':
    case 'on':
    case 'yes':
      return true
    default:
      return false
  }
}

And import in any file where you want to use it '@/path/to/String+Extension'

./xx.py: line 1: import: command not found

It's not an issue related to authentication at the first step. Your import is not working. So, try writing this on first line:

#!/usr/bin/python

and for the time being run using

python xx.py

For you here is one explanation:

>>> abc = "Hei Buddy"
>>> print "%s" %abc
Hei Buddy
>>> 

>>> print "%s" %xyz

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    print "%s" %xyz
NameError: name 'xyz' is not defined

At first, I initialized abc variable and it works fine. On the otherhand, xyz doesn't work as it is not initialized!

HTML: How to center align a form

This will have the field take 50% of the width and be centered and resized properly


    {    
        width: 50%;
        margin-left : 25%
    }

May also use "vw" (view width) units instead of "%"

How to serve static files in Flask

If you are just trying to open a file, you could use app.open_resource(). So reading a file would look something like

with app.open_resource('/static/path/yourfile'):
      #code to read the file and do something

Add an element to an array in Swift

In Swift 4.2: You can use

myArray.append("Tim") //To add "Tim" into array

or

myArray.insert("Tim", at: 0) //Change 0 with specific location 

How to keep indent for second line in ordered lists via CSS?

Update

This answer is outdated. You can do this a lot more simply, as pointed out in another answer below:

ul {
  list-style-position: outside;
}

See https://www.w3schools.com/cssref/pr_list-style-position.asp

Original Answer

I'm surprised to see this hasn't been solved yet. You can make use of the browser's table layout algorithm (without using tables) like this:

ol {
    counter-reset: foo;
    display: table;
}

ol > li {
    counter-increment: foo;
    display: table-row;
}

ol > li::before {
    content: counter(foo) ".";
    display: table-cell; /* aha! */
    text-align: right;
}

Demo: http://jsfiddle.net/4rnNK/1/

enter image description here

To make it work in IE8, use the legacy :before notation with one colon.

Error:(9, 5) error: resource android:attr/dialogCornerRadius not found

If you are migrated for AndroidX and getting this error, you need to set the compile SDK to Android 9.0 (API level 28) or higher

Deny all, allow only one IP through htaccess

I know this question already has an accepted answer, but the Apache documentation says:

The Allow, Deny, and Order directives, provided by mod_access_compat, are deprecated and will go away in a future version. You should avoid using them, and avoid outdated tutorials recommending their use.

So, a more future-proof answer would be:

<RequireAll>
    Require ip xx.xx.xx.xx yy.yy.yy.yy
</RequireAll>

Hopefully, I've helped prevent this page from becoming one of those "outdated tutorials". :)

Retain precision with double in Java

Use a BigDecimal. It even lets you specify rounding rules (like ROUND_HALF_EVEN, which will minimize statistical error by rounding to the even neighbor if both are the same distance; i.e. both 1.5 and 2.5 round to 2).

App not setup: This app is still in development mode

2021 UPDATE

I have done successfully Login with Facebook by doing below things. Now it is working fine.

As per described by George Mano

Visit Facebook Apps Page and select your application.

Go to Settings -> Basic.

Add a 1 Contact Email, 2 Privacy Policy URL, 3 User Data Deletion and choose 4 Category and Last 5. Live your application

The Privacy Policy URL should be a webpage where you have hosted the terms and conditions of your application and data used.

The General Data Protection Regulation (GDPR) requires developers to provide a way for people to request that their data be deleted. To be compliant with these requirements, you must provide either a data deletion request callback or instructions to inform people how to delete their data from your app or website

Toggle the button in the top of the screen, as seen below, in order to switch from Development to Live.

enter image description here

How to create a stopwatch using JavaScript?

Please see stopwatch.js for a very clean and simple Vanilla Javascript ES6 solution.

Javascript Equivalent to PHP Explode()

try like this,

ans = str.split (":");

And you can use two parts of the string like,

ans[0] and ans[1]

Function pointer as a member of a C struct

You can use also "void*" (void pointer) to send an address to the function.

typedef struct pstring_t {
    char * chars;
    int(*length)(void*);
} PString;

int length(void* self) {
    return strlen(((PString*)self)->chars);
}

PString initializeString() {
    PString str;
    str.length = &length;
    return str;
}

int main()
{
    PString p = initializeString();

    p.chars = "Hello";

    printf("Length: %i\n", p.length(&p));

    return 0;
}

Output:

Length: 5

CSS: image link, change on hover

If you give generally give a span the property display:block, it'll then behave like a div, i.e you can set width and height.

You can also skip the div or span and just set the a the to display: block and apply the backgound style to it.

<a href="" class="myImage"><!----></a>


    <style>
      .myImage {display: block; width: 160px; height: 20px; margin:0 0 10px 0; background: url(image.png) center top no-repeat;}
.myImage:hover{background-image(image_hover.png);}
    </style>

Markdown and image alignment

this work for me

<p align="center">
 <img src="/LogoOfficial.png" width="300" >
</p>

Split string in Lua?

Here is my really simple solution. Use the gmatch function to capture strings which contain at least one character of anything other than the desired separator. The separator is **any* whitespace (%s in Lua) by default:

function mysplit (inputstr, sep)
        if sep == nil then
                sep = "%s"
        end
        local t={}
        for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
                table.insert(t, str)
        end
        return t
end

.

adding onclick event to dynamically added button?

try this:

but.onclick = callJavascriptFunction;

or create the button by wrapping it with another element and use innerHTML:

var span = document.createElement('span');
span.innerHTML = '<button id="but' + inc +'" onclick="callJavascriptFunction()" />';

Is it possible to cast a Stream in Java 8?

I don't think there is a way to do that out-of-the-box. A possibly cleaner solution would be:

Stream.of(objects)
    .filter(c -> c instanceof Client)
    .map(c -> (Client) c)
    .map(Client::getID)
    .forEach(System.out::println);

or, as suggested in the comments, you could use the cast method - the former may be easier to read though:

Stream.of(objects)
    .filter(Client.class::isInstance)
    .map(Client.class::cast)
    .map(Client::getID)
    .forEach(System.out::println);

"The breakpoint will not currently be hit. The source code is different from the original version." What does this mean?

A new way to get this problem has appeared as of Visual Studio 2017 15.3.1 through 15.3.5. If you are using EditorConfig, the charset=utf8 option causes these symptoms. The VS team has reproduced this and says they are working on it.

So one fix is to comment out your charset=utf8 line in the .editorconfig file.

Edit: This should be fixed as of VS 15.5.

How can I update a row in a DataTable in VB.NET?

You can access columns by index, by name and some other ways:

dtResult.Rows(i)("columnName") = strVerse

You should probably make sure your DataTable has some columns first...

Why do I get a C malloc assertion failure?

I got the following message, similar to your one:


    program: malloc.c:2372: sysmalloc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 *(sizeof(size_t))) - 1)) & ~((2 *(sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long) old_end & pagemask) == 0)' failed.

Made a mistake some method call before, when using malloc. Erroneously overwrote the multiplication sign '*' with a '+', when updating the factor after sizeof()-operator on adding a field to unsigned char array.

Here is the code responsible for the error in my case:


    UCHAR* b=(UCHAR*)malloc(sizeof(UCHAR)+5);
    b[INTBITS]=(some calculation);
    b[BUFSPC]=(some calculation);
    b[BUFOVR]=(some calculation);
    b[BUFMEM]=(some calculation);
    b[MATCHBITS]=(some calculation);

In another method later, I used malloc again and it produced the error message shown above. The call was (simple enough):


    UCHAR* b=(UCHAR*)malloc(sizeof(UCHAR)*50);

Think using the '+'-sign on the 1st call, which lead to mis-calculus in combination with immediate initialization of the array after (overwriting memory that was not allocated to the array), brought some confusion to malloc's memory map. Therefore the 2nd call went wrong.

How to check if a div is visible state or not?

You can use (':hidden') method to find if your div is visible or not.. Also its a good practice to cache a element if you are using it multiple times in your code..

$(".subpanel a").click(function() 
     {
        var chatterNickname = $(this).text();
        var $chatPanel = $("#singlechatpanel-1");

        if(!$chatPanel.is(':hidden'))
        {
            alert("Room 1 is filled.");
            $chatPanel.show();
            $("#singlechatpanel-1 #chatter_nickname").html("Chatting with: " + chatterNickname);
        }
});

How can I know when an EditText loses focus?

Kotlin way

editText.setOnFocusChangeListener { _, hasFocus ->
    if (!hasFocus) {  }
}

How to set a CheckBox by default Checked in ASP.Net MVC

Old question, but another "pure razor" answer would be:

@Html.CheckBoxFor(model => model.As, htmlAttributes: new { @checked = true} )

Sort hash by key, return hash in Ruby

I liked the solution in the earlier post.

I made a mini-class, called it class AlphabeticalHash. It also has a method called ap, which accepts one argument, a Hash, as input: ap variable. Akin to pp (pp variable)

But it will (try and) print in alphabetical list (its keys). Dunno if anyone else wants to use this, it's available as a gem, you can install it as such: gem install alphabetical_hash

For me, this is simple enough. If others need more functionality, let me know, I'll include it into the gem.

EDIT: Credit goes to Peter, who gave me the idea. :)

JQuery Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

Looks like your buttons are not declared correctly (according to the latest jQuery UI documentation anyway).

try the following:

$( ".selector" ).dialog({ 
   buttons: [{ 
      text: "Ok", 
      click: function() { 
         $( this ).dialog( "close" ); 
      }
   }]
});

Load dimension value from res/values/dimension.xml from source code

The Resource class also has a method getDimensionPixelSize() which I think will fit your needs.

How can I verify if an AD account is locked?

Here's another one:

PS> Search-ADAccount -Locked | Select Name, LockedOut, LastLogonDate

Name                                       LockedOut LastLogonDate
----                                       --------- -------------
Yxxxxxxx                                        True 14/11/2014 10:19:20
Bxxxxxxx                                        True 18/11/2014 08:38:34
Administrator                                   True 03/11/2014 20:32:05

Other parameters worth mentioning:

Search-ADAccount -AccountExpired
Search-ADAccount -AccountDisabled
Search-ADAccount -AccountInactive

Get-Help Search-ADAccount -ShowWindow

CSS: styled a checkbox to look like a button, is there a hover?

Do what Kelly said...

BUT. Instead of having the input positioned absolute and top -20px (just hiding it off the page), make the input box hidden.

example:

<input type="checkbox" hidden> 

Works better and can put it anywhere on the page.

Remove Array Value By index in jquery

  1. Find the element in array and get its position
  2. Remove using the position

_x000D_
_x000D_
var array = new Array();_x000D_
  _x000D_
array.push('123');_x000D_
array.push('456');_x000D_
array.push('789');_x000D_
                 _x000D_
var _searchedIndex = $.inArray('456',array);_x000D_
alert(_searchedIndex );_x000D_
if(_searchedIndex >= 0){_x000D_
  array.splice(_searchedIndex,1);_x000D_
  alert(array );_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

  • inArray() - helps you to find the position.
  • splice() - helps you to remove the element in that position.

How to Right-align flex item?

A more flex approach would be to use an auto left margin (flex items treat auto margins a bit differently than when used in a block formatting context).

.c {
    margin-left: auto;
}

Updated fiddle:

_x000D_
_x000D_
.main { display: flex; }_x000D_
.a, .b, .c { background: #efefef; border: 1px solid #999; }_x000D_
.b { flex: 1; text-align: center; }_x000D_
.c {margin-left: auto;}
_x000D_
<h2>With title</h2>_x000D_
<div class="main">_x000D_
    <div class="a"><a href="#">Home</a></div>_x000D_
    <div class="b"><a href="#">Some title centered</a></div>_x000D_
    <div class="c"><a href="#">Contact</a></div>_x000D_
</div>_x000D_
<h2>Without title</h2>_x000D_
<div class="main">_x000D_
    <div class="a"><a href="#">Home</a></div>_x000D_
    <!--<div class="b"><a href="#">Some title centered</a></div>-->_x000D_
    <div class="c"><a href="#">Contact</a></div>_x000D_
</div>_x000D_
<h1>Problem</h1>_x000D_
<p>Is there a more flexbox-ish way to right align "Contact" than to use position absolute?</p>
_x000D_
_x000D_
_x000D_

How to allow download of .json file with ASP.NET

When adding support for mimetype (as suggested by @ProVega) then it is also best practice to remove the type before adding it - this is to prevent unexpected errors when deploying to servers where support for the type already exists, for example:

<staticContent>
    <remove fileExtension=".json" />
    <mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>

How to get the CPU Usage in C#?

After spending some time reading over a couple different threads that seemed pretty complicated I came up with this. I needed it for an 8 core machine where I wanted to monitor SQL server. For the code below then I passed in "sqlservr" as appName.

private static void RunTest(string appName)
{
    bool done = false;
    PerformanceCounter total_cpu = new PerformanceCounter("Process", "% Processor Time", "_Total");
    PerformanceCounter process_cpu = new PerformanceCounter("Process", "% Processor Time", appName);
    while (!done)
    {
        float t = total_cpu.NextValue();
        float p = process_cpu.NextValue();
        Console.WriteLine(String.Format("_Total = {0}  App = {1} {2}%\n", t, p, p / t * 100));
        System.Threading.Thread.Sleep(1000);
    }
}

It seems to correctly measure the % of CPU being used by SQL on my 8 core server.

Convert JSON string to array of JSON objects in Javascript

Using jQuery:

var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}';
var jsonObj = $.parseJSON('[' + str + ']');

jsonObj is your JSON object.

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);

How can I get a Bootstrap column to span multiple rows?

<div class="row">
  <div class="col-4 alert alert-primary">
     1
  </div>
  <div class="col-8">
    <div class="row">
      <div class="col-6 alert alert-primary">
        2
      </div>
      <div class="col-6 alert alert-primary">
        3
      </div>
      <div class="col-6 alert alert-primary">
        4
      </div>
      <div class="col-6 alert alert-primary">
        5
      </div>
    </div>
  </div>
</div>
<div class="row">
  <div class="col-4 alert alert-primary">
    6
  </div>
  <div class="col-4 alert alert-primary">
    7
  </div>
  <div class="col-4 alert alert-primary">
    8
  </div>
</div>

How to remove margin space around body or clear default css styles

That's the default margin/padding of the body element.

Some browsers have a default margin, some a default padding, and both are applied as a padding in the body element.

Add this to your CSS:

body { margin: 0; padding: 0; }

Convert serial.read() into a useable string using Arduino?

Credit for this goes to magma. Great answer, but here it is using c++ style strings instead of c style strings. Some users may find that easier.

String string = "";
char ch; // Where to store the character read

void setup() {
    Serial.begin(9600);
    Serial.write("Power On");
}
    
boolean Comp(String par) {
    while (Serial.available() > 0) // Don't read unless
                                       // there you know there is data
    {
        ch = Serial.read(); // Read a character
        string += ch; // Add it
    }
    
    if (par == string) {
       string = "";
       return(true);
    }
    else {
       //dont reset string
       return(false);
    }
}
    
void loop()
{
    if (Comp("m1 on")) {
        Serial.write("Motor 1 -> Online\n");
    }
    if (Comp("m1 off")) {
        Serial.write("Motor 1 -> Offline\n");
    }
}

The VMware Authorization Service is not running

You can fix this by starting the service manually.

  1. Type services in the Windows search bar.
  2. Open Services; scroll to the VMware Authorization Service (should be close to the bottom of the page)
  3. Double-click to open the Properties page of the service.
  4. Change the startup type to Automatic and then start the service. That way, the service will be started automatically every time you log in.

More detailed info can be found at Powering on a virtual machine fails with the error: The VMware Authorization Service is not running (1007131)

How to convert byte array to string

Assuming that you are using UTF-8 encoding:

string convert = "This is the string to be converted";

// From string to byte array
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(convert);

// From byte array to string
string s = System.Text.Encoding.UTF8.GetString(buffer, 0, buffer.Length);

"unary operator expected" error in Bash if condition

Try assigning a value to $aug1 before use it in if[] statements; the error message will disappear afterwards.

How to create an empty DataFrame with a specified schema?

As of Spark 2.0.0, you can do the following.

Case Class

Let's define a Person case class:

scala> case class Person(id: Int, name: String)
defined class Person

Import spark SparkSession implicit Encoders:

scala> import spark.implicits._
import spark.implicits._

And use SparkSession to create an empty Dataset[Person]:

scala> spark.emptyDataset[Person]
res0: org.apache.spark.sql.Dataset[Person] = [id: int, name: string]

Schema DSL

You could also use a Schema "DSL" (see Support functions for DataFrames in org.apache.spark.sql.ColumnName).

scala> val id = $"id".int
id: org.apache.spark.sql.types.StructField = StructField(id,IntegerType,true)

scala> val name = $"name".string
name: org.apache.spark.sql.types.StructField = StructField(name,StringType,true)

scala> import org.apache.spark.sql.types.StructType
import org.apache.spark.sql.types.StructType

scala> val mySchema = StructType(id :: name :: Nil)
mySchema: org.apache.spark.sql.types.StructType = StructType(StructField(id,IntegerType,true), StructField(name,StringType,true))

scala> import org.apache.spark.sql.Row
import org.apache.spark.sql.Row

scala> val emptyDF = spark.createDataFrame(sc.emptyRDD[Row], mySchema)
emptyDF: org.apache.spark.sql.DataFrame = [id: int, name: string]

scala> emptyDF.printSchema
root
 |-- id: integer (nullable = true)
 |-- name: string (nullable = true)

GDB: break if variable equal value

First, you need to compile your code with appropriate flags, enabling debug into code.

$ gcc -Wall -g -ggdb -o ex1 ex1.c

then just run you code with your favourite debugger

$ gdb ./ex1

show me the code.

(gdb) list
1   #include <stdio.h>
2   int main(void)
3   { 
4     int i = 0;
5     for(i=0;i<7;++i)
6       printf("%d\n", i);
7   
8     return 0;
9   }

break on lines 5 and looks if i == 5.

(gdb) b 5
Breakpoint 1 at 0x4004fb: file ex1.c, line 5.
(gdb) rwatch i if i==5
Hardware read watchpoint 5: i

checking breakpoints

(gdb) info b
Num     Type           Disp Enb Address            What
1       breakpoint     keep y   0x00000000004004fb in main at ex1.c:5
    breakpoint already hit 1 time
5       read watchpoint keep y                      i
    stop only if i==5

running the program

(gdb) c
Continuing.
0
1
2
3
4
Hardware read watchpoint 5: i

Value = 5
0x0000000000400523 in main () at ex1.c:5
5     for(i=0;i<7;++i)

How do I call one constructor from another in Java?

Yes, it is possible:

public class Foo {
    private int x;

    public Foo() {
        this(1);
    }

    public Foo(int x) {
        this.x = x;
    }
}

To chain to a particular superclass constructor instead of one in the same class, use super instead of this. Note that you can only chain to one constructor, and it has to be the first statement in your constructor body.

See also this related question, which is about C# but where the same principles apply.

How to initialize a JavaScript Date to a particular time zone

Maybe this will help you

_x000D_
_x000D_
/**_x000D_
 * Shift any Date timezone._x000D_
 * @param {Date} date - Date to update._x000D_
 * @param {string} timezone - Timezone as `-03:00`._x000D_
 */_x000D_
function timezoneShifter(date, timezone) {_x000D_
  let isBehindGTM = false;_x000D_
  if (timezone.startsWith("-")) {_x000D_
    timezone = timezone.substr(1);_x000D_
    isBehindGTM = true;_x000D_
  }_x000D_
_x000D_
  const [hDiff, mDiff] = timezone.split(":").map((t) => parseInt(t));_x000D_
  const diff = hDiff * 60 + mDiff * (isBehindGTM ? 1 : -1);_x000D_
  const currentDiff = new Date().getTimezoneOffset();_x000D_
_x000D_
  return new Date(date.valueOf() + (currentDiff - diff) * 60 * 1000);_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
const _now = new Date()_x000D_
console.log(_x000D_
  [_x000D_
    "Here: " + _now.toLocaleString(),_x000D_
    "Greenwich: " + timezoneShifter(_now, "00:00").toLocaleString(),_x000D_
    "New York: " + timezoneShifter(_now, "-04:00").toLocaleString(),_x000D_
    "Tokyo: " + timezoneShifter(_now, "+09:00").toLocaleString(),_x000D_
    "Buenos Aires: " + timezoneShifter(_now, "-03:00").toLocaleString(),_x000D_
  ].join('\n')_x000D_
);
_x000D_
_x000D_
_x000D_

Solr vs. ElasticSearch

I see some of the above answers are now a bit out of date. From my perspective, and I work with both Solr(Cloud and non-Cloud) and ElasticSearch on a daily basis, here are some interesting differences:

  • Community: Solr has a bigger, more mature user, dev, and contributor community. ES has a smaller, but active community of users and a growing community of contributors
  • Maturity: Solr is more mature, but ES has grown rapidly and I consider it stable
  • Performance: hard to judge. I/we have not done direct performance benchmarks. A person at LinkedIn did compare Solr vs. ES vs. Sensei once, but the initial results should be ignored because they used non-expert setup for both Solr and ES.
  • Design: People love Solr. The Java API is somewhat verbose, but people like how it's put together. Solr code is unfortunately not always very pretty. Also, ES has sharding, real-time replication, document and routing built-in. While some of this exists in Solr, too, it feels a bit like an after-thought.
  • Support: there are companies providing tech and consulting support for both Solr and ElasticSearch. I think the only company that provides support for both is Sematext (disclosure: I'm Sematext founder)
  • Scalability: both can be scaled to very large clusters. ES is easier to scale than pre-Solr 4.0 version of Solr, but with Solr 4.0 that's no longer the case.

For more thorough coverage of Solr vs. ElasticSearch topic have a look at https://sematext.com/blog/solr-vs-elasticsearch-part-1-overview/ . This is the first post in the series of posts from Sematext doing direct and neutral Solr vs. ElasticSearch comparison. Disclosure: I work at Sematext.

Capture Video of Android's Screen

Android 4.4 (KitKat) and higher devices have a shell utility for recording the Android device screen. Connect a device in developer/debug mode running KitKat with the adb utility over USB and then type the following:

adb shell screenrecord /sdcard/movie.mp4
(Press Ctrl-C to stop)
adb pull /sdcard/movie.mp4

Screen recording is limited to a maximum of 3 minutes.

Reference: https://developer.android.com/studio/command-line/adb.html#screenrecord

Spark java.lang.OutOfMemoryError: Java heap space

Did you dump your master gc log? So I met similar issue and I found SPARK_DRIVER_MEMORY only set the Xmx heap. The initial heap size remains 1G and the heap size never scale up to the Xmx heap.

Passing "--conf "spark.driver.extraJavaOptions=-Xms20g" resolves my issue.

ps aux | grep java and the you'll see the follow log:=

24501 30.7 1.7 41782944 2318184 pts/0 Sl+ 18:49 0:33 /usr/java/latest/bin/java -cp /opt/spark/conf/:/opt/spark/jars/* -Xmx30g -Xms20g

SEVERE: Unable to create initial connections of pool - tomcat 7 with context.xml file

I have also dealt with this exception after a fully working context.xml setup was adjusted. I didn't want environment details in the context.xml, so I took them out and saw this error. I realized I must fully create this datasource resource in code based on System Property JVM -D args.

Original error with just user/pwd/host removed: org.apache.tomcat.jdbc.pool.ConnectionPool init SEVERE: Unable to create initial connections of pool.

Removed entire contents of context.xml and try this: Initialize on startup of app server the datasource object sometime before using first connection. If using Spring this is good to do in an @Configuration bean in @Bean Datasource constructor.

package to use: org.apache.tomcat.jdbc.pool.*

PoolProperties p = new PoolProperties();
p.setUrl(jdbcUrl);
            p.setDriverClassName(driverClass);
            p.setUsername(user);
            p.setPassword(pwd);
            p.setJmxEnabled(true);
            p.setTestWhileIdle(false);
            p.setTestOnBorrow(true);
            p.setValidationQuery("SELECT 1");
            p.setTestOnReturn(false);
            p.setValidationInterval(30000);
            p.setValidationQueryTimeout(100);
            p.setTimeBetweenEvictionRunsMillis(30000);
            p.setMaxActive(100);
            p.setInitialSize(5);
            p.setMaxWait(10000);
            p.setRemoveAbandonedTimeout(60);
            p.setMinEvictableIdleTimeMillis(30000);
            p.setMinIdle(5);
            p.setLogAbandoned(true);
            p.setRemoveAbandoned(true);
            p.setJdbcInterceptors(
              "org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"+
              "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
            org.apache.tomcat.jdbc.pool.DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource();
            ds.setPoolProperties(p);
            return ds;

How to run function in AngularJS controller on document ready?

Angular has several timepoints to start executing functions. If you seek for something like jQuery's

$(document).ready();

You may find this analog in angular to be very useful:

$scope.$watch('$viewContentLoaded', function(){
    //do something
});

This one is helpful when you want to manipulate the DOM elements. It will start executing only after all te elements are loaded.

UPD: What is said above works when you want to change css properties. However, sometimes it doesn't work when you want to measure the element properties, such as width, height, etc. In this case you may want to try this:

$scope.$watch('$viewContentLoaded', 
    function() { 
        $timeout(function() {
            //do something
        },0);    
});

Sending "User-agent" using Requests library in Python

It's more convenient to use a session, this way you don't have to remember to set headers each time:

session = requests.Session()
session.headers.update({'User-Agent': 'Custom user agent'})

session.get('https://httpbin.org/headers')

By default, session also manages cookies for you. In case you want to disable that, see this question.

What is ModelState.IsValid valid for in ASP.NET MVC in NerdDinner?

From the Errata: ModelState.AddRuleViolations(dinner.GetRuleViolations());

Should be:

ModelState.AddModelErrors(dinner.GetRuleViolations());

Reference: http://www.wrox.com/WileyCDA/WroxTitle/Professional-ASP-NET-MVC-1-0.productCd-0470384611,descCd-ERRATA.html

How to include header files in GCC search path?

Try gcc -c -I/home/me/development/skia sample.c.

Nginx sites-enabled, sites-available: Cannot create soft-link between config files in Ubuntu 12.04

My site configuration file is example.conf in sites-available folder So you can create a symbolic link as

ln -s /etc/nginx/sites-available/example.conf /etc/nginx/sites-enabled/

How to avoid the "divide by zero" error in SQL?

You can also do this at the beginning of the query:

SET ARITHABORT OFF 
SET ANSI_WARNINGS OFF

So if you have something like 100/0 it will return NULL. I've only done this for simple queries, so I don't know how it will affect longer/complex ones.

How to stop the Timer in android?

It says timer() is not available on android? You might find this article useful.

http://developer.android.com/resources/articles/timed-ui-updates.html


I was wrong. Timer() is available. It seems you either implement it the way it is one shot operation:

schedule(TimerTask task, Date when) // Schedule a task for single execution.

Or you cancel it after the first execution:

cancel()  // Cancels the Timer and all scheduled tasks.

http://developer.android.com/reference/java/util/Timer.html

How to calculate the time interval between two time strings

Concise if you are just interested in the time elapsed that is under 24 hours. You can format the output as needed in the return statement :

import datetime
def elapsed_interval(start,end):
    elapsed = end - start
    min,secs=divmod(elapsed.days * 86400 + elapsed.seconds, 60)
    hour, minutes = divmod(min, 60)
    return '%.2d:%.2d:%.2d' % (hour,minutes,secs)

if __name__ == '__main__':
    time_start=datetime.datetime.now()
    """ do your process """
    time_end=datetime.datetime.now()
    total_time=elapsed_interval(time_start,time_end)

In SQL, how can you "group by" in ranges?

Neither of the highest voted answers are correct on SQL Server 2000. Perhaps they were using a different version.

Here are the correct versions of both of them on SQL Server 2000.

select t.range as [score range], count(*) as [number of occurences]
from (
  select case  
    when score between 0 and 9 then ' 0- 9'
    when score between 10 and 19 then '10-19'
    else '20-99' end as range
  from scores) t
group by t.range

or

select t.range as [score range], count(*) as [number of occurrences]
from (
      select user_id,
         case when score >= 0 and score< 10 then '0-9'
         when score >= 10 and score< 20 then '10-19'
         else '20-99' end as range
     from scores) t
group by t.range

How to format a Date in MM/dd/yyyy HH:mm:ss format in JavaScript?


var d = new Date();

// calling the function
formatDate(d,4);


function formatDate(dateObj,format)
{
    var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];
    var curr_date = dateObj.getDate();
    var curr_month = dateObj.getMonth();
    curr_month = curr_month + 1;
    var curr_year = dateObj.getFullYear();
    var curr_min = dateObj.getMinutes();
    var curr_hr= dateObj.getHours();
    var curr_sc= dateObj.getSeconds();
    if(curr_month.toString().length == 1)
    curr_month = '0' + curr_month;      
    if(curr_date.toString().length == 1)
    curr_date = '0' + curr_date;
    if(curr_hr.toString().length == 1)
    curr_hr = '0' + curr_hr;
    if(curr_min.toString().length == 1)
    curr_min = '0' + curr_min;

    if(format ==1)//dd-mm-yyyy
    {
        return curr_date + "-"+curr_month+ "-"+curr_year;       
    }
    else if(format ==2)//yyyy-mm-dd
    {
        return curr_year + "-"+curr_month+ "-"+curr_date;       
    }
    else if(format ==3)//dd/mm/yyyy
    {
        return curr_date + "/"+curr_month+ "/"+curr_year;       
    }
    else if(format ==4)// MM/dd/yyyy HH:mm:ss
    {
        return curr_month+"/"+curr_date +"/"+curr_year+ " "+curr_hr+":"+curr_min+":"+curr_sc;       
    }
}

phpMyAdmin ERROR: mysqli_real_connect(): (HY000/1045): Access denied for user 'pma'@'localhost' (using password: NO)

Linux / Ubuntu: If installed phpmyadmin via apt: sudo apt-get install phpmyadmin php-mbstring

Can check /etc/phpmyadmin/config-db.php for changing the user credentials.

$dbuser='pma';
$dbpass='my_pass';
$basepath='';
$dbname='phpmyadmin';
$dbserver='localhost';
$dbport='3306';
$dbtype='mysql';

size of struct in C

Your default alignment is probably 4 bytes. Either the 30 byte element got 32, or the structure as a whole was rounded up to the next 4 byte interval.

How to show math equations in general github's markdown(not github's blog)

Mathcha is a sophisticated mathematics editor, but it can be used to render individual equations and save them as pure html, which you can then add to your documents as inline html OR you can save as SVG and insert as an image. https://www.mathcha.io/

Load content with ajax in bootstrap modal

The top voted answer is deprecated in Bootstrap 3.3 and will be removed in v4. Try this instead:

JavaScript:

// Fill modal with content from link href
$("#myModal").on("show.bs.modal", function(e) {
    var link = $(e.relatedTarget);
    $(this).find(".modal-body").load(link.attr("href"));
});

Html (Based on the official example. Note that for Bootstrap 3.* we set data-remote="false" to disable the deprecated Bootstrap load function):

<!-- Link trigger modal -->
<a href="remoteContent.html" data-remote="false" data-toggle="modal" data-target="#myModal" class="btn btn-default">
    Launch Modal
</a>

<!-- Default bootstrap modal example -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

Try it yourself: https://jsfiddle.net/ednon5d1/

C++11 reverse range-based for-loop

Got this example from cppreference. It works with:

GCC 10.1+ with flag -std=c++20

#include <ranges>
#include <iostream>
 
int main()
{
    static constexpr auto il = {3, 1, 4, 1, 5, 9};
 
    std::ranges::reverse_view rv {il};
    for (int i : rv)
        std::cout << i << ' ';
 
    std::cout << '\n';
 
    for(int i : il | std::views::reverse)
        std::cout << i << ' ';
}

Get filename in batch for loop

If you want to remain both filename (only) and extension, you may use %~nxF:

FOR /R C:\Directory %F in (*.*) do echo %~nxF

Allowing Java to use an untrusted certificate for SSL/HTTPS connection

Following code from here is a useful solution. No keystores etc. Just call method SSLUtilities.trustAllHttpsCertificates() before initializing the service and port (in SOAP).

import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * This class provide various static methods that relax X509 certificate and
 * hostname verification while using the SSL over the HTTP protocol.
 *  
 * @author Jiramot.info
 */
public final class SSLUtilities {

  /**
   * Hostname verifier for the Sun's deprecated API.
   *
   * @deprecated see {@link #_hostnameVerifier}.
   */
  private static com.sun.net.ssl.HostnameVerifier __hostnameVerifier;
  /**
   * Thrust managers for the Sun's deprecated API.
   *
   * @deprecated see {@link #_trustManagers}.
   */
  private static com.sun.net.ssl.TrustManager[] __trustManagers;
  /**
   * Hostname verifier.
   */
  private static HostnameVerifier _hostnameVerifier;
  /**
   * Thrust managers.
   */
  private static TrustManager[] _trustManagers;

  /**
   * Set the default Hostname Verifier to an instance of a fake class that
   * trust all hostnames. This method uses the old deprecated API from the
   * com.sun.ssl package.
   *  
   * @deprecated see {@link #_trustAllHostnames()}.
   */
  private static void __trustAllHostnames() {
    // Create a trust manager that does not validate certificate chains
    if (__hostnameVerifier == null) {
        __hostnameVerifier = new SSLUtilities._FakeHostnameVerifier();
    } // if
    // Install the all-trusting host name verifier
    com.sun.net.ssl.HttpsURLConnection
            .setDefaultHostnameVerifier(__hostnameVerifier);
  } // __trustAllHttpsCertificates

  /**
   * Set the default X509 Trust Manager to an instance of a fake class that
   * trust all certificates, even the self-signed ones. This method uses the
   * old deprecated API from the com.sun.ssl package.
   *
   * @deprecated see {@link #_trustAllHttpsCertificates()}.
   */
  private static void __trustAllHttpsCertificates() {
    com.sun.net.ssl.SSLContext context;

    // Create a trust manager that does not validate certificate chains
    if (__trustManagers == null) {
        __trustManagers = new com.sun.net.ssl.TrustManager[]{new SSLUtilities._FakeX509TrustManager()};
    } // if
    // Install the all-trusting trust manager
    try {
        context = com.sun.net.ssl.SSLContext.getInstance("SSL");
        context.init(null, __trustManagers, new SecureRandom());
    } catch (GeneralSecurityException gse) {
        throw new IllegalStateException(gse.getMessage());
    } // catch
    com.sun.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(context
            .getSocketFactory());
  } // __trustAllHttpsCertificates

  /**
   * Return true if the protocol handler property java. protocol.handler.pkgs
   * is set to the Sun's com.sun.net.ssl. internal.www.protocol deprecated
   * one, false otherwise.
   *
   * @return true if the protocol handler property is set to the Sun's
   * deprecated one, false otherwise.
   */
  private static boolean isDeprecatedSSLProtocol() {
    return ("com.sun.net.ssl.internal.www.protocol".equals(System
            .getProperty("java.protocol.handler.pkgs")));
  } // isDeprecatedSSLProtocol

  /**
   * Set the default Hostname Verifier to an instance of a fake class that
   * trust all hostnames.
   */
  private static void _trustAllHostnames() {
      // Create a trust manager that does not validate certificate chains
      if (_hostnameVerifier == null) {
          _hostnameVerifier = new SSLUtilities.FakeHostnameVerifier();
      } // if
      // Install the all-trusting host name verifier:
      HttpsURLConnection.setDefaultHostnameVerifier(_hostnameVerifier);
  } // _trustAllHttpsCertificates

  /**
   * Set the default X509 Trust Manager to an instance of a fake class that
   * trust all certificates, even the self-signed ones.
   */
  private static void _trustAllHttpsCertificates() {
    SSLContext context;

      // Create a trust manager that does not validate certificate chains
      if (_trustManagers == null) {
          _trustManagers = new TrustManager[]{new SSLUtilities.FakeX509TrustManager()};
      } // if
      // Install the all-trusting trust manager:
      try {
          context = SSLContext.getInstance("SSL");
          context.init(null, _trustManagers, new SecureRandom());
      } catch (GeneralSecurityException gse) {
          throw new IllegalStateException(gse.getMessage());
      } // catch
      HttpsURLConnection.setDefaultSSLSocketFactory(context
            .getSocketFactory());
  } // _trustAllHttpsCertificates

  /**
   * Set the default Hostname Verifier to an instance of a fake class that
   * trust all hostnames.
   */
  public static void trustAllHostnames() {
      // Is the deprecated protocol setted?
      if (isDeprecatedSSLProtocol()) {
          __trustAllHostnames();
      } else {
          _trustAllHostnames();
      } // else
  } // trustAllHostnames

  /**
   * Set the default X509 Trust Manager to an instance of a fake class that
   * trust all certificates, even the self-signed ones.
   */
  public static void trustAllHttpsCertificates() {
    // Is the deprecated protocol setted?
    if (isDeprecatedSSLProtocol()) {
        __trustAllHttpsCertificates();
    } else {
        _trustAllHttpsCertificates();
    } // else
  } // trustAllHttpsCertificates

  /**
   * This class implements a fake hostname verificator, trusting any host
   * name. This class uses the old deprecated API from the com.sun. ssl
   * package.
   *
   * @author Jiramot.info
   *
   * @deprecated see {@link SSLUtilities.FakeHostnameVerifier}.
   */
  public static class _FakeHostnameVerifier implements
        com.sun.net.ssl.HostnameVerifier {

    /**
     * Always return true, indicating that the host name is an acceptable
     * match with the server's authentication scheme.
     *
     * @param hostname the host name.
     * @param session the SSL session used on the connection to host.
     * @return the true boolean value indicating the host name is trusted.
     */
    public boolean verify(String hostname, String session) {
        return (true);
    } // verify
  } // _FakeHostnameVerifier

  /**
   * This class allow any X509 certificates to be used to authenticate the
   * remote side of a secure socket, including self-signed certificates. This
   * class uses the old deprecated API from the com.sun.ssl package.
   *
   * @author Jiramot.info
   *
   * @deprecated see {@link SSLUtilities.FakeX509TrustManager}.
   */
  public static class _FakeX509TrustManager implements
        com.sun.net.ssl.X509TrustManager {

    /**
     * Empty array of certificate authority certificates.
     */
    private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{};

    /**
     * Always return true, trusting for client SSL chain peer certificate
     * chain.
     *
     * @param chain the peer certificate chain.
     * @return the true boolean value indicating the chain is trusted.
     */
    public boolean isClientTrusted(X509Certificate[] chain) {
        return (true);
    } // checkClientTrusted

    /**
     * Always return true, trusting for server SSL chain peer certificate
     * chain.
     *
     * @param chain the peer certificate chain.
     * @return the true boolean value indicating the chain is trusted.
     */
    public boolean isServerTrusted(X509Certificate[] chain) {
        return (true);
    } // checkServerTrusted

    /**
     * Return an empty array of certificate authority certificates which are
     * trusted for authenticating peers.
     *
     * @return a empty array of issuer certificates.
     */
    public X509Certificate[] getAcceptedIssuers() {
        return (_AcceptedIssuers);
    } // getAcceptedIssuers
  } // _FakeX509TrustManager

  /**
   * This class implements a fake hostname verificator, trusting any host
   * name.
   *
   * @author Jiramot.info
   */
  public static class FakeHostnameVerifier implements HostnameVerifier {

    /**
     * Always return true, indicating that the host name is an acceptable
     * match with the server's authentication scheme.
     *
     * @param hostname the host name.
     * @param session the SSL session used on the connection to host.
     * @return the true boolean value indicating the host name is trusted.
     */
    public boolean verify(String hostname, javax.net.ssl.SSLSession session) {
        return (true);
    } // verify
  } // FakeHostnameVerifier

  /**
   * This class allow any X509 certificates to be used to authenticate the
   * remote side of a secure socket, including self-signed certificates.
   *
   * @author Jiramot.info
   */
  public static class FakeX509TrustManager implements X509TrustManager {

    /**
     * Empty array of certificate authority certificates.
     */
    private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{};

    /**
     * Always trust for client SSL chain peer certificate chain with any
     * authType authentication types.
     *
     * @param chain the peer certificate chain.
     * @param authType the authentication type based on the client
     * certificate.
     */
    public void checkClientTrusted(X509Certificate[] chain, String authType) {
    } // checkClientTrusted

    /**
     * Always trust for server SSL chain peer certificate chain with any
     * authType exchange algorithm types.
     *
     * @param chain the peer certificate chain.
     * @param authType the key exchange algorithm used.
     */
    public void checkServerTrusted(X509Certificate[] chain, String authType) {
    } // checkServerTrusted

    /**
     * Return an empty array of certificate authority certificates which are
     * trusted for authenticating peers.
     *
     * @return a empty array of issuer certificates.
     */
    public X509Certificate[] getAcceptedIssuers() {
        return (_AcceptedIssuers);
    } // getAcceptedIssuers
  } // FakeX509TrustManager
} // SSLUtilities

How do I create a Java string from the contents of a file?

If you're looking for an alternative that doesn't involve a third-party library (e.g. Commons I/O), you can use the Scanner class:

private String readFile(String pathname) throws IOException {

    File file = new File(pathname);
    StringBuilder fileContents = new StringBuilder((int)file.length());        

    try (Scanner scanner = new Scanner(file)) {
        while(scanner.hasNextLine()) {
            fileContents.append(scanner.nextLine() + System.lineSeparator());
        }
        return fileContents.toString();
    }
}

How to return data from PHP to a jQuery ajax call

I figured it out. Need to use echo in PHP instead of return.

<?php 
  $output = some_function();
  echo $output;
?> 

And the jQ:

success: function(data) {
  doSomething(data);
}

PHP: get the value of TEXTBOX then pass it to a VARIABLE

Inside testing2.php you should print the $_POST array which contains all the data from the post. Also, $_POST['name'] should be available. For more info check $_POST on php.net.

How to get a web page's source code from Java

URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader(
            new InputStreamReader(
            yahoo.openStream()));

String inputLine;

while ((inputLine = in.readLine()) != null)
    System.out.println(inputLine);

in.close();

Index of duplicates items in a python list

I'll mention the more obvious way of dealing with duplicates in lists. In terms of complexity, dictionaries are the way to go because each lookup is O(1). You can be more clever if you're only interested in duplicates...

my_list = [1,1,2,3,4,5,5]
my_dict = {}
for (ind,elem) in enumerate(my_list):
    if elem in my_dict:
        my_dict[elem].append(ind)
    else:
        my_dict.update({elem:[ind]})

for key,value in my_dict.iteritems():
    if len(value) > 1:
        print "key(%s) has indices (%s)" %(key,value)

which prints the following:

key(1) has indices ([0, 1])
key(5) has indices ([5, 6])

Regex to check with starts with http://, https:// or ftp://

Unless there is some compelling reason to use a regex, I would just use String.startsWith:

bool matches = test.startsWith("http://")
            || test.startsWith("https://") 
            || test.startsWith("ftp://");

I wouldn't be surprised if this is faster, too.

Setting PHPMyAdmin Language

sounds like you downloaded the german xampp package instead of the english xampp package (yes, it's another download-link) where the language is set according to the package you loaded. to change the language afterwards, simply edit the config.inc.php and set:

$cfg['Lang'] = 'en-utf-8';

How to put space character into a string name in XML?

xml:space="preserve"

Works like a charm.

Edit: Wrong. Actually, it only works when the content is comprised of white spaces only.

Link

Select count(*) from multiple tables

select (select count() from tab1 where field like 'value') + (select count() from tab2 where field like 'value') count

Identifying Exception Type in a handler Catch Block

When dealing with situations where I don't exactly know what type of exception might come out of a method, a little "trick" I like to do is to recover the Exception's class name and add it to the error log so there is more information.

try
{
   <code>

} catch ( Exception caughtEx )
{
   throw new Exception("Unknown Exception Thrown: "
                       + "\n  Type:    " + caughtEx.GetType().Name
                       + "\n  Message: " + caughtEx.Message);
}

I do vouch for always handling Exceptions types individually, but the extra bit of info can be helpful, specially when dealing with code from people who love to capture catch-all generic types.

How to capitalize the first letter of text in a TextView in an Android Application

StringBuilder sb = new StringBuilder(name);
sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));  
return sb.toString();

Python convert tuple to string

here is an easy way to use join.

''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))

What are all the different ways to create an object in Java?

Method 1

Using new keyword. This is the most common way to create an object in java. Almost 99% of objects are created in this way.

Employee object = new Employee();

Method 2

Using Class.forName(). Class.forName() gives you the class object, which is useful for reflection. The methods that this object has are defined by Java, not by the programmer writing the class. They are the same for every class. Calling newInstance() on that gives you an instance of that class (i.e. callingClass.forName("ExampleClass").newInstance() it is equivalent to calling new ExampleClass()), on which you can call the methods that the class defines, access the visible fields etc.

Employee object2 = (Employee) Class.forName(NewEmployee).newInstance();

Class.forName() will always use the ClassLoader of the caller, whereas ClassLoader.loadClass() can specify a different ClassLoader. I believe that Class.forName initializes the loaded class as well, whereas the ClassLoader.loadClass() approach doesn’t do that right away (it’s not initialized until it’s used for the first time).

Another must read:

Java: Thread State Introduction with Example Simple Java Enum Example

Method 3

Using clone(). The clone() can be used to create a copy of an existing object.

Employee secondObject = new Employee();
Employee object3 = (Employee) secondObject.clone();

Method 4

Using newInstance() method

Object object4 = Employee.class.getClassLoader().loadClass(NewEmployee).newInstance();

Method 5

Using Object Deserialization. Object Deserialization is nothing but creating an object from its serialized form.

// Create Object5
// create a new file with an ObjectOutputStream
FileOutputStream out = new FileOutputStream("");
ObjectOutputStream oout = new ObjectOutputStream(out);

// write something in the file
oout.writeObject(object3);
oout.flush();

// create an ObjectInputStream for the file we created before
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("crunchify.txt"));
Employee object5 = (Employee) ois.readObject();

Get POST data in C#/ASP.NET

I'm a little surprised that this question has been asked so many times before, but the most reuseable and friendly solution hasn't been documented.

I often have webpages using AngularJS, and when I click on a Save button, I'll "POST" this data back to my .aspx page or .ashx handler to save this back to the database. The data will be in the form of a JSON record.

On the server, to turn the raw posted data back into a C# class, here's what I would do.

First, define a C# class which will contain the posted data.

Supposing my webpage is posting JSON data like this:

{
    "UserID" : 1,
    "FirstName" : "Mike",
    "LastName" : "Mike",
    "Address1" : "10 Really Street",
    "Address2" : "London"
}

Then I'd define a C# class like this...

public class JSONRequest
{
    public int UserID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
}

(These classes can be nested, but the structure must match the format of the JSON data. So, if you're posting a JSON User record, with a list of Order records within it, your C# class should also contain a List<> of Order records.)

Now, in my .aspx.cs or .ashx file, I just need to do this, and leave JSON.Net to do the hard work...

    protected void Page_Load(object sender, EventArgs e)
    {
        string jsonString = "";
        HttpContext.Current.Request.InputStream.Position = 0;
        using (StreamReader inputStream = new StreamReader(this.Request.InputStream))
        {
            jsonString = inputStream.ReadToEnd();
        }
        JSONRequest oneQuestion = JsonConvert.DeserializeObject<JSONRequest>(jsonString);

And that's it. You now have a JSONRequest class containing the various fields which were POSTed to your server.

How do I revert a Git repository to a previous commit?

If you want to temporarily revert changes because

  • someone committed code that is breaking the build or breaking the functionality you're working on

You can search for the last working commit using git log and then run:

git rebase --onto <commitId>

When the remote branch is working again, you can

git pull --rebase

This method is better than git checkout for temporary changes, because you're not in a detached state.

sql primary key and index

You are right, it's confusing that SQL Server allows you to create duplicate indexes on the same field(s). But the fact that you can create another doesn't indicate that the PK index doesn't also already exist.

The additional index does no good, but the only harm (very small) is the additional file size and row-creation overhead.

substring index range

public class SubstringExample
{
    public static void main(String[] args) 
    {
        String str="OOPs is a programming paradigm...";

        System.out.println(" Length is: " + str.length());

        System.out.println(" Substring is: " + str.substring(10, 30));
    }
}

Output:

length is: 31

Substring is: programming paradigm

Selenium Webdriver: Entering text into text field

Agree with Subir Kumar Sao and Faiz.

element_enter.findElement(By.xpath("//html/body/div[1]/div[3]/div[1]/form/div/div/input")).sendKeys(barcode);

Passing data to components in vue.js

The best way to send data from a parent component to a child is using props.

Passing data from parent to child via props

  • Declare props (array or object) in the child
  • Pass it to the child via <child :name="variableOnParent">

See demo below:

_x000D_
_x000D_
Vue.component('child-comp', {
  props: ['message'], // declare the props
  template: '<p>At child-comp, using props in the template: {{ message }}</p>',
  mounted: function () {
    console.log('The props are also available in JS:', this.message);
  }
})

new Vue({
  el: '#app',
  data: {
    variableAtParent: 'DATA FROM PARENT!'
  }
})
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>

<div id="app">
  <p>At Parent: {{ variableAtParent }}<br>And is reactive (edit it) <input v-model="variableAtParent"></p>
  <child-comp :message="variableAtParent"></child-comp>
</div>
_x000D_
_x000D_
_x000D_

Why am I getting a " Traceback (most recent call last):" error?

At the beginning of your file you set raw_input to 0. Do not do this, at it modifies the built-in raw_input() function. Therefore, whenever you call raw_input(), it is essentially calling 0(), which raises the error. To remove the error, remove the first line of your code:

M = 1.6
# Miles to Kilometers 
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54


def intro():
    print("Welcome! This program will convert measures for you.")
    main()

def main():
    print("Select operation.")
    print("1.Miles to Kilometers")
    print("2.Fahrenheit to Celsius")
    print("3.Gallons to liters")
    print("4.Pounds to kilograms")
    print("5.Inches to centimeters")

    choice = input("Enter your choice by number: ")

    if choice == '1':
        convertMK()

    elif choice == '2':
        converCF()

    elif choice == '3':
        convertGL()

    elif choice == '4':
        convertPK()

    elif choice == '5':
        convertPK()

    else:
        print("Error")


def convertMK():
    input_M = float(raw_input(("Miles: ")))
    M_conv = (M) * input_M
    print("Kilometers: %f\n" % M_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def converCF():
    input_F = float(raw_input(("Fahrenheit: ")))
    F_conv = (input_F - 32) * 5/9
    print("Celcius: %f\n") % F_conv
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def convertGL():
    input_G = float(raw_input(("Gallons: ")))
    G_conv = input_G * 3.6
    print("Centimeters: %f\n" % G_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertPK():
    input_P = float(raw_input(("Pounds: ")))
    P_conv = input_P * 0.45
    print("Centimeters: %f\n" % P_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertIC():
    input_cm = float(raw_input(("Inches: ")))
    inches_conv = input_cm * 2.54
    print("Centimeters: %f\n" % inches_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def end():
    print("This program will close.")
    exit()

intro()

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

This can be done without terminal, directly from IDE. Netbeans, for example.

  1. Create a separate project with packages (Create Project - Java - Java Class Library).
  2. Put your .java classes there.
  3. Build this project.
  4. Go to your project folder and find build and dist folders there.
  5. Find .jar file in your dist folder.
  6. Get your other project and add this .jar file to project libraries.
  7. You can now reference classes from this library and its methods directly from code, if import is automatically done for you.

Web API optional parameters

I figured it out. I was using a bad example I found in the past of how to map query string to the method parameters.

In case anyone else needs it, in order to have optional parameters in a query string such as:

  • ~/api/products/filter?apc=AA&xpc=BB
  • ~/api/products/filter?sku=7199123

you would use:

[Route("products/filter/{apc?}/{xpc?}/{sku?}")]
public IHttpActionResult Get(string apc = null, string xpc = null, int? sku = null)
{ ... }

It seems odd to have to define default values for the method parameters when these types already have a default.

Add IIS 7 AppPool Identities as SQL Server Logons

If you're going across machines, you either need to be using NETWORK SERVICE, LOCAL SYSTEM, a domain account, or a SQL 2008 R2 (if you have it) Managed Service Account (which is my preference if you had such an infrastructure). You can not use an account which is not visible to the Active Directory domain.

Convert int to a bit array in .NET

    public static bool[] Convert(int[] input, int length)
    {
        var ret = new bool[length];
        var siz = sizeof(int) * 8;
        var pow = 0;
        var cur = 0;

        for (var a = 0; a < input.Length && cur < length; ++a)
        {
            var inp = input[a];

            pow = 1;

            if (inp > 0)
            {
                for (var i = 0; i < siz && cur < length; ++i)
                {
                    ret[cur++] = (inp & pow) == pow;

                    pow *= 2;
                }
            }
            else
            {
                for (var i = 0; i < siz && cur < length; ++i)
                {
                    ret[cur++] = (inp & pow) != pow;

                    pow *= 2;
                }
            }
        }

        return ret;
    }

Why aren't python nested functions called closures?

def nested1(num1): 
    print "nested1 has",num1
    def nested2(num2):
        print "nested2 has",num2,"and it can reach to",num1
        return num1+num2    #num1 referenced for reading here
    return nested2

Gives:

In [17]: my_func=nested1(8)
nested1 has 8

In [21]: my_func(5)
nested2 has 5 and it can reach to 8
Out[21]: 13

This is an example of what a closure is and how it can be used.

How to Execute SQL Script File in Java?

Flyway library is really good for this:

    Flyway flyway = new Flyway();
    flyway.setDataSource(dbConfig.getUrl(), dbConfig.getUsername(), dbConfig.getPassword());
    flyway.setLocations("classpath:db/scripts");
    flyway.clean();
    flyway.migrate();

This scans the locations for scripts and runs them in order. Scripts can be versioned with V01__name.sql so if just the migrate is called then only those not already run will be run. Uses a table called 'schema_version' to keep track of things. But can do other things too, see the docs: flyway.

The clean call isn't required, but useful to start from a clean DB. Also, be aware of the location (default is "classpath:db/migration"), there is no space after the ':', that one caught me out.

Write string to output stream

You can create a PrintStream wrapping around your OutputStream and then just call it's print(String):

final OutputStream os = new FileOutputStream("/tmp/out");
final PrintStream printStream = new PrintStream(os);
printStream.print("String");
printStream.close();

Dialog to pick image from gallery or from camera

I think that's up to you to show that dialog for choosing. For Gallery you'll use that code, and for Camera try this.

Android new Bottom Navigation bar or BottomNavigationView

I have referred this github post and I have set the three layouts for three fragment pages in bottom tab bar.

FourButtonsActivity.java:

bottomBar.setFragmentItems(getSupportFragmentManager(), R.id.fragmentContainer,
            new BottomBarFragment(LibraryFragment.newInstance(R.layout.library_fragment_layout), R.drawable.ic_update_white_24dp, "Recents"),
            new BottomBarFragment(PhotoEffectFragment.newInstance(R.layout.photo_effect_fragment), R.drawable.ic_local_dining_white_24dp, "Food"),
            new BottomBarFragment(VideoFragment.newInstance(R.layout.video_layout), R.drawable.ic_favorite_white_24dp, "Favorites")

    );

To set the badge count :

  BottomBarBadge unreadMessages = bottomBar.makeBadgeForTabAt(1, "#E91E63", 4);
  unreadMessages.show();
  unreadMessages.setCount(4);
  unreadMessages.setAnimationDuration(200);
  unreadMessages.setAutoShowAfterUnSelection(true);

LibraryFragment.java:

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class LibraryFragment extends Fragment {
    private static final String STARTING_TEXT = "Four Buttons Bottom Navigation";

    public LibraryFragment() {
    }

    public static LibraryFragment newInstance(int resource) {
        Bundle args = new Bundle();
        args.putInt(STARTING_TEXT, resource);

        LibraryFragment sampleFragment = new LibraryFragment();
        sampleFragment.setArguments(args);

        return sampleFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {


        View view = LayoutInflater.from(getActivity()).inflate(
                getArguments().getInt(STARTING_TEXT), null);
        return view;


    }

How to force reloading php.ini file?

To force a reload of the php.ini you should restart apache.

Try sudo service apache2 restart from the command line. Or sudo /etc/init.d/apache2 restart

Specifing width of a flexbox flex item: width or basis?

The bottom statement is equivalent to:

.half {
   flex-grow: 0;
   flex-shrink: 0;
   flex-basis: 50%;
}

Which, in this case, would be equivalent as the box is not allowed to flex and therefore retains the initial width set by flex-basis.

Flex-basis defines the default size of an element before the remaining space is distributed so if the element were allowed to flex (grow/shrink) it may not be 50% of the width of the page.

I've found that I regularly return to https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for help regarding flexbox :)

INSERT with SELECT

Yes, it is. You can write :

INSERT INTO courses (name, location, gid) 
SELECT name, location, 'whatever you want' 
FROM courses 
WHERE cid = $ci

or you can get values from another join of the select ...

Better way to convert an int to a boolean

I assume 0 means false (which is the case in a lot of programming languages). That means true is not 0 (some languages use -1 some others use 1; doesn't hurt to be compatible to either). So assuming by "better" you mean less typing, you can just write:

bool boolValue = intValue != 0;

Cannot run Eclipse; JVM terminated. Exit code=13

use the configuration below;

    -startup
    plugins/org.eclipse.equinox.launcher_1.3.0.v20130327-1440.jar
    --launcher.library
    plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20130807-1835
    -product
    org.springsource.ggts.ide
    --launcher.defaultAction
    openFile
    --launcher.XXMaxPermSize
    256M
    -vm
    C:\Program Files\Java\jdk1.7.0_51\jre\bin\javaw.exe
    -vmargs
    -Dorg.eclipse.swt.browser.IEVersion=10001
    -Dgrails.console.enable.interactive=false
    -Dgrails.console.enable.terminal=false
    -Djline.terminal=jline.UnsupportedTerminal
    -Dgrails.console.class=grails.build.logging.GrailsEclipseConsole
    -Dosgi.requiredJavaVersion=1.6
    -Xms40m
    -Xmx768m
    -XX:MaxPermSize=256m
    -Dorg.eclipse.swt.browser.IEVersion=10001

What's the regular expression that matches a square bracket?

Are you escaping it with \?

/\[/

Here's a helpful resource to get started with Regular Expressions:

Regular-Expressions.info

How to convert array to a string using methods other than JSON?

There are different ways to do this some of them has given. implode(), join(), var_export(), print_r(), serialize(), json_encode()exc... You can also write your own function without these:

A For() loop is very useful. You can add your array's value to another variable like this:

<?php
    $dizi=array('mother','father','child'); //This is array

    $sayi=count($dizi);
    for ($i=0; $i<$sayi; $i++) {
        $dizin.=("'$dizi[$i]',"); //Now it is string...
    }
         echo substr($dizin,0,-1); //Write it like string :D
?>

In this code we added $dizi's values and comma to $dizin:

$dizin.=("'$dizi[$i]',");

Now

$dizin = 'mother', 'father', 'child',

It's a string, but it has an extra comma :)

And then we deleted the last comma, substr($dizin, 0, -1);

Output:

'mother','father','child'

Using $state methods with $stateChangeStart toState and fromState in Angular ui-router

Suggestion 1

When you add an object to $stateProvider.state that object is then passed with the state. So you can add additional properties which you can read later on when needed.

Example route configuration

$stateProvider
.state('public', {
    abstract: true,
    module: 'public'
})
.state('public.login', {
    url: '/login',
    module: 'public'
})
.state('tool', {
    abstract: true,
    module: 'private'
})
.state('tool.suggestions', {
    url: '/suggestions',
    module: 'private'
});

The $stateChangeStart event gives you acces to the toState and fromState objects. These state objects will contain the configuration properties.

Example check for the custom module property

$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
    if (toState.module === 'private' && !$cookies.Session) {
        // If logged out and transitioning to a logged in page:
        e.preventDefault();
        $state.go('public.login');
    } else if (toState.module === 'public' && $cookies.Session) {
        // If logged in and transitioning to a logged out page:
        e.preventDefault();
        $state.go('tool.suggestions');
    };
});

I didn't change the logic of the cookies because I think that is out of scope for your question.

Suggestion 2

You can create a Helper to get you this to work more modular.

Value publicStates

myApp.value('publicStates', function(){
    return {
      module: 'public',
      routes: [{
        name: 'login', 
        config: { 
          url: '/login'
        }
      }]
    };
});

Value privateStates

myApp.value('privateStates', function(){
    return {
      module: 'private',
      routes: [{
        name: 'suggestions', 
        config: { 
          url: '/suggestions'
        }
      }]
    };
});

The Helper

myApp.provider('stateshelperConfig', function () {
  this.config = {
    // These are the properties we need to set
    // $stateProvider: undefined
    process: function (stateConfigs){
      var module = stateConfigs.module;
      $stateProvider = this.$stateProvider;
      $stateProvider.state(module, {
        abstract: true,
        module: module
      });
      angular.forEach(stateConfigs, function (route){
        route.config.module = module;
        $stateProvider.state(module + route.name, route.config);
      });
    }
  };

  this.$get = function () {
    return {
      config: this.config
    };
  };
});

Now you can use the helper to add the state configuration to your state configuration.

myApp.config(['$stateProvider', '$urlRouterProvider', 
    'stateshelperConfigProvider', 'publicStates', 'privateStates',
  function ($stateProvider, $urlRouterProvider, helper, publicStates, privateStates) {
    helper.config.$stateProvider = $stateProvider;
    helper.process(publicStates);
    helper.process(privateStates);
}]);

This way you can abstract the repeated code, and come up with a more modular solution.

Note: the code above isn't tested

How to stretch children to fill cross-axis?

  • The children of a row-flexbox container automatically fill the container's vertical space.

  • Specify flex: 1; for a child if you want it to fill the remaining horizontal space:

_x000D_
_x000D_
.wrapper {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  align-items: stretch;_x000D_
  width: 100%;_x000D_
  height: 5em;_x000D_
  background: #ccc;_x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
  background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
  background: #ccf;_x000D_
  flex: 1; _x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="left">Left</div>_x000D_
  <div class="right">Right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

  • Specify flex: 1; for both children if you want them to fill equal amounts of the horizontal space:

_x000D_
_x000D_
.wrapper {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  align-items: stretch;_x000D_
  width: 100%;_x000D_
  height: 5em;_x000D_
  background: #ccc;_x000D_
}_x000D_
.wrapper > div _x000D_
{_x000D_
  flex: 1; _x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
  background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
  background: #ccf;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="left">Left</div>_x000D_
  <div class="right">Right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

mongodb service is not starting up

I had struggled with the similar issue and sharing the solution accordingly. We use a mongo replica set and mongo service on my secondary server was taking too long to start. (approx 10-15 minutes)

Couldn't find anything until attempted to configure the mongo with some different folder in --dbpath And that worked fine, so we got to know that the earlier path, which was a mount directory had some issues. So followed with nss team to get the network mount issue solved.

Hope this helps someone

How do I test axios in Jest?

I used axios-mock-adapter. In this case the service is described in ./chatbot. In the mock adapter you specify what to return when the API endpoint is consumed.

import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import chatbot from './chatbot';

describe('Chatbot', () => {
    it('returns data when sendMessage is called', done => {
        var mock = new MockAdapter(axios);
        const data = { response: true };
        mock.onGet('https://us-central1-hutoma-backend.cloudfunctions.net/chat').reply(200, data);

        chatbot.sendMessage(0, 'any').then(response => {
            expect(response).toEqual(data);
            done();
        });
    });
});

You can see it the whole example here:

Service: https://github.com/lnolazco/hutoma-test/blob/master/src/services/chatbot.js

Test: https://github.com/lnolazco/hutoma-test/blob/master/src/services/chatbot.test.js

Python : Trying to POST form using requests

You can use the Session object

import requests
headers = {'User-Agent': 'Mozilla/5.0'}
payload = {'username':'niceusername','password':'123456'}

session = requests.Session()
session.post('https://admin.example.com/login.php',headers=headers,data=payload)
# the session instance holds the cookie. So use it to get/post later.
# e.g. session.get('https://example.com/profile')

Replace one substring for another string in shell script

Pure POSIX shell method, which unlike Roman Kazanovskyi's sed-based answer needs no external tools, just the shell's own native parameter expansions. Note that long file names are minimized so the code fits better on one line:

f="I love Suzi and Marry"
s=Sara
t=Suzi
[ "${f%$t*}" != "$f" ] && f="${f%$t*}$s${f#*$t}"
echo "$f"

Output:

I love Sara and Marry

How it works:

  • Remove Smallest Suffix Pattern. "${f%$t*}" returns "I love" if the suffix $t "Suzi*" is in $f "I love Suzi and Marry".

  • But if t=Zelda, then "${f%$t*}" deletes nothing, and returns the whole string "I love Suzi and Marry".

  • This is used to test if $t is in $f with [ "${f%$t*}" != "$f" ] which will evaluate to true if the $f string contains "Suzi*" and false if not.

  • If the test returns true, construct the desired string using Remove Smallest Suffix Pattern ${f%$t*} "I love" and Remove Smallest Prefix Pattern ${f#*$t} "and Marry", with the 2nd string $s "Sara" in between.

Prevent text selection after double click

I had the same problem. I solved it by switching to <a> and add onclick="return false;" (so that clicking on it won't add a new entry to browser history).

Manage toolbar's navigation and back button from fragment in android

The easiest solution I found was to simply put that in your fragment :

androidx.appcompat.widget.Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            NavController navController = Navigation.findNavController(getActivity(), 
R.id.nav_host_fragment);
            navController.navigate(R.id.action_position_to_destination);
        }
    });

Personnaly I wanted to go to another page but of course you can replace the 2 lines in the onClick method by the action you want to perform.

How to convert Java String into byte[]?

Simply:

String abc="abcdefghight";

byte[] b = abc.getBytes();

When a 'blur' event occurs, how can I find out which element focus went *to*?

I've been playing with this same feature and found out that FF, IE, Chrome and Opera have the ability to provide the source element of an event. I haven't tested Safari but my guess is it might have something similar.

$('#Form').keyup(function (e) {
    var ctrl = null;
    if (e.originalEvent.explicitOriginalTarget) { // FF
        ctrl = e.originalEvent.explicitOriginalTarget;
    }
    else if (e.originalEvent.srcElement) { // IE, Chrome and Opera
        ctrl = e.originalEvent.srcElement;
    }
    //...
});

Remove part of string in Java

Using StringUtils from commons lang

A null source string will return null. An empty ("") source string will return the empty string. A null remove string will return the source string. An empty ("") remove string will return the source string.

String str = StringUtils.remove("Test remove", "remove");
System.out.println(str);
//result will be "Test"

What does Docker add to lxc-tools (the userspace LXC tools)?

From the Docker FAQ:

Docker is not a replacement for lxc. "lxc" refers to capabilities of the linux kernel (specifically namespaces and control groups) which allow sandboxing processes from one another, and controlling their resource allocations.

On top of this low-level foundation of kernel features, Docker offers a high-level tool with several powerful functionalities:

  • Portable deployment across machines. Docker defines a format for bundling an application and all its dependencies into a single object which can be transferred to any docker-enabled machine, and executed there with the guarantee that the execution environment exposed to the application will be the same. Lxc implements process sandboxing, which is an important pre-requisite for portable deployment, but that alone is not enough for portable deployment. If you sent me a copy of your application installed in a custom lxc configuration, it would almost certainly not run on my machine the way it does on yours, because it is tied to your machine's specific configuration: networking, storage, logging, distro, etc. Docker defines an abstraction for these machine-specific settings, so that the exact same docker container can run - unchanged - on many different machines, with many different configurations.

  • Application-centric. Docker is optimized for the deployment of applications, as opposed to machines. This is reflected in its API, user interface, design philosophy and documentation. By contrast, the lxc helper scripts focus on containers as lightweight machines - basically servers that boot faster and need less ram. We think there's more to containers than just that.

  • Automatic build. Docker includes a tool for developers to automatically assemble a container from their source code, with full control over application dependencies, build tools, packaging etc. They are free to use make, maven, chef, puppet, salt, debian packages, rpms, source tarballs, or any combination of the above, regardless of the configuration of the machines.

  • Versioning. Docker includes git-like capabilities for tracking successive versions of a container, inspecting the diff between versions, committing new versions, rolling back etc. The history also includes how a container was assembled and by whom, so you get full traceability from the production server all the way back to the upstream developer. Docker also implements incremental uploads and downloads, similar to "git pull", so new versions of a container can be transferred by only sending diffs.

  • Component re-use. Any container can be used as an "base image" to create more specialized components. This can be done manually or as part of an automated build. For example you can prepare the ideal python environment, and use it as a base for 10 different applications. Your ideal postgresql setup can be re-used for all your future projects. And so on.

  • Sharing. Docker has access to a public registry (https://registry.hub.docker.com/) where thousands of people have uploaded useful containers: anything from redis, couchdb, postgres to irc bouncers to rails app servers to hadoop to base images for various distros. The registry also includes an official "standard library" of useful containers maintained by the docker team. The registry itself is open-source, so anyone can deploy their own registry to store and transfer private containers, for internal server deployments for example.

  • Tool ecosystem. Docker defines an API for automating and customizing the creation and deployment of containers. There are a huge number of tools integrating with docker to extend its capabilities. PaaS-like deployment (Dokku, Deis, Flynn), multi-node orchestration (maestro, salt, mesos, openstack nova), management dashboards (docker-ui, openstack horizon, shipyard), configuration management (chef, puppet), continuous integration (jenkins, strider, travis), etc. Docker is rapidly establishing itself as the standard for container-based tooling.

I hope this helps!

JSON.parse unexpected token s

valid json string must have double quote.

JSON.parse({"u1":1000,"u2":1100})       // will be ok

no quote cause error

JSON.parse({u1:1000,u2:1100})    
// error Uncaught SyntaxError: Unexpected token u in JSON at position 2

single quote cause error

JSON.parse({'u1':1000,'u2':1100})    
// error Uncaught SyntaxError: Unexpected token u in JSON at position 2

You must valid json string at https://jsonlint.com

getActionBar() returns null

The main reason for that is using themes that are not supporting ActionBar:

In manifest file add the following either in your target activity or application element (if you want to unify the theme over whole application)

Examples of themes that are supporting action bar "Theme.AppCompat.Light" or "Theme.Holo.Light" ...

android:theme="@android:style/Theme.Holo.Light"

It is better to put all styles in styles.xml and use it everywhere using "@style/themName" so the previous one will be

android:theme="@style/AppTheme"

and styles.xml will have the following:

 <style name="AppTheme" parent="Theme.AppCompat.Light">

Hints:

  • There is some themes that can not be used in old SDKs like "@android:style/Theme.Holo.Light.DarkActionBar" is not supported before SDKs version 14.
  • To allow your app to support minimum specific version of SDK you could add the following under <app> element:

    <uses-sdk android:minSdkVersion="14" />
    
  • To specify min SDK version in AndroidStudio, you could by using app's Gradle file.

    android{
      defaultConfig{
        minSdkVersion 14
        targetSdkVersion 21
      }
    }
    

Simple 'if' or logic statement in Python

If key isn't an int or float but a string, you need to convert it to an int first by doing

key = int(key)

or to a float by doing

key = float(key)

Otherwise, what you have in your question should work, but

if (key < 1) or (key > 34):

or

if not (1 <= key <= 34):

would be a bit clearer.

How to disable and then enable onclick event on <div> with javascript

I'm confused by your question, seems to me that the question title and body are asking different things. If you want to disable/enable a click event on a div simply do:

$("#id").on('click', function(){ //enables click event
    //do your thing here
});

$("#id").off('click'); //disables click event

If you want to disable a div, use the following code:

$("#id").attr('disabled','disabled');

Hope this helps.

edit: oops, didn't see the other bind/unbind answer. Sorry. Those methods are also correct, though they've been deprecated in jQuery 1.7, and replaced by on()/off()

Fetch API with Cookie

Fetch does not use cookie by default. To enable cookie, do this:

fetch(url, {
  credentials: "same-origin"
}).then(...).catch(...);

git: Your branch is ahead by X commits

Though this question is a bit old...I was in a similar situation and my answer here helped me fix a similar issue I had

First try with push -f or force option

If that did not work it is possible that (as in my case) the remote repositories (or rather the references to remote repositories that show up on git remote -v) might not be getting updated.

Outcome of above being your push synced your local/branch with your remote/branch however, the cache in your local repo still shows previous commit (of local/branch ...provided only single commit was pushed) as HEAD.

To confirm the above clone the repo at a different location and try to compare local/branch HEAD and remote/branch HEAD. If they both are same then you are probably facing the issue I did.

Solution:

$ git remote -v
github  [email protected]:schacon/hw.git (fetch)
github  [email protected]:schacon/hw.git (push)
$ git remote add origin git://github.com/pjhyett/hw.git
$ git remote -v
github  [email protected]:schacon/hw.git (fetch)
github  [email protected]:schacon/hw.git (push)
origin  git://github.com/pjhyett/hw.git (fetch)
origin  git://github.com/pjhyett/hw.git (push)
$ git remote rm origin
$ git remote -v
github  [email protected]:schacon/hw.git (fetch)
github  [email protected]:schacon/hw.git (push)

Now do a push -f as follows

git push -f github master ### Note your command does not have origin anymore!

Do a git pull now git pull github master

on git status receive

# On branch master

nothing to commit (working directory clean)

I hope this useful for someone as the number of views is so high that searching for this error almost always lists this thread on the top

Also refer gitref for details

Enabling error display in PHP via htaccess only

php_flag display_errors on

To turn the actual display of errors on.

To set the types of errors you are displaying, you will need to use:

php_value error_reporting <integer>

Combined with the integer values from this page: http://php.net/manual/en/errorfunc.constants.php

Note if you use -1 for your integer, it will show all errors, and be future proof when they add in new types of errors.

Binding objects defined in code-behind

While Guy's answer is correct (and probably fits 9 out of 10 cases), it's worth noting that if you are attempting to do this from a control that already has its DataContext set further up the stack, you'll resetting this when you set DataContext back to itself:

DataContext="{Binding RelativeSource={RelativeSource Self}}"

This will of course then break your existing bindings.

If this is the case, you should set the RelativeSource on the control you are trying to bind, rather than its parent.

i.e. for binding to a UserControl's properties:

Binding Path=PropertyName, 
        RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}

Given how difficult it can be currently to see what's going on with data binding, it's worth bearing this in mind even if you find that setting RelativeSource={RelativeSource Self} currently works :)

Application Installation Failed in Android Studio

I had the same issue in MIUI. Enabling OEM unlocking worked for me without disabling MIUI optimization.

Below is a screenshot of my Redmi 3s prime developer options setting:

screenshot of my Redmi 3s prime developer options setting

Get original URL referer with PHP?

As Johnathan Suggested, you would either want to save it in a cookie or a session.

The easier way would be to use a Session variable.

session_start();
if(!isset($_SESSION['org_referer']))
{
    $_SESSION['org_referer'] = $_SERVER['HTTP_REFERER'];
}

Put that at the top of the page, and you will always be able to access the first referer that the site visitor was directed by.

Styling of Select2 dropdown select boxes

Here is a working example of above. http://jsfiddle.net/z7L6m2sc/ Now select2 has been updated the classes have change may be why you cannot get it to work. Here is the css....

.select2-dropdown.select2-dropdown--below{
    width: 148px !important;
}

.select2-container--default .select2-selection--single{
    padding:6px;
    height: 37px;
    width: 148px; 
    font-size: 1.2em;  
    position: relative;
}

.select2-container--default .select2-selection--single .select2-selection__arrow {
    background-image: -khtml-gradient(linear, left top, left bottom, from(#424242), to(#030303));
    background-image: -moz-linear-gradient(top, #424242, #030303);
    background-image: -ms-linear-gradient(top, #424242, #030303);
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #424242), color-stop(100%, #030303));
    background-image: -webkit-linear-gradient(top, #424242, #030303);
    background-image: -o-linear-gradient(top, #424242, #030303);
    background-image: linear-gradient(#424242, #030303);
    width: 40px;
    color: #fff;
    font-size: 1.3em;
    padding: 4px 12px;
    height: 27px;
    position: absolute;
    top: 0px;
    right: 0px;
    width: 20px;
}

Make A List Item Clickable (HTML/CSS)

I think you could use the following HTML and CSS combo instead:

<li>
  <a href="#">Backback</a>
</li>

Then use CSS background for the basket visibility on hover:

.listblock ul li a {
    padding: 5px 30px 5px 10px;
    display: block;
}

.listblock ul li a:hover {
    background: transparent url('../img/basket.png') no-repeat 3px 170px;
}

Simples!

Do Facebook Oauth 2.0 Access Tokens Expire?

Yes, they do expire. There is an 'expires' value that is passed along with the 'access_token', and from what I can tell it's about 2 hours. I've been searching, but I don't see a way to request a longer expiration time.

Which characters need to be escaped when using Bash?

format that can be reused as shell input

Edit february 2021: ${var@Q}

Under bash, you could store your variable content with Parameter Expansion's @ command for Parameter transformation:

${parameter@operator}
       Parameter transformation.  The expansion is either a transforma-
       tion of the value of parameter or  information  about  parameter
       itself,  depending on the value of operator.  Each operator is a
       single letter:

       Q      The expansion is a string that is the value of  parameter
              quoted in a format that can be reused as input.
...
       A      The  expansion  is  a string in the form of an assignment
              statement or declare command  that,  if  evaluated,  will
              recreate parameter with its attributes and value.

Sample:

$ var=$'Hello\nGood world.\n'
$ echo "$var"
Hello
Good world.

$ echo "${var@Q}"
$'Hello\nGood world.\n'

$ echo "${var@A}"
var=$'Hello\nGood world.\n'

Old answer

There is a special printf format directive (%q) built for this kind of request:

printf [-v var] format [arguments]

 %q     causes printf to output the corresponding argument
        in a format that can be reused as shell input.

Some samples:

read foo
Hello world
printf "%q\n" "$foo"
Hello\ world

printf "%q\n" $'Hello world!\n'
$'Hello world!\n'

This could be used through variables too:

printf -v var "%q" "$foo
"
echo "$var"
$'Hello world\n'

Quick check with all (128) ascii bytes:

Note that all bytes from 128 to 255 have to be escaped.

for i in {0..127} ;do
    printf -v var \\%o $i
    printf -v var $var
    printf -v res "%q" "$var"
    esc=E
    [ "$var" = "$res" ] && esc=-
    printf "%02X %s %-7s\n" $i $esc "$res"
done |
    column

This must render something like:

00 E ''         1A E $'\032'    34 - 4          4E - N          68 - h      
01 E $'\001'    1B E $'\E'      35 - 5          4F - O          69 - i      
02 E $'\002'    1C E $'\034'    36 - 6          50 - P          6A - j      
03 E $'\003'    1D E $'\035'    37 - 7          51 - Q          6B - k      
04 E $'\004'    1E E $'\036'    38 - 8          52 - R          6C - l      
05 E $'\005'    1F E $'\037'    39 - 9          53 - S          6D - m      
06 E $'\006'    20 E \          3A - :          54 - T          6E - n      
07 E $'\a'      21 E \!         3B E \;         55 - U          6F - o      
08 E $'\b'      22 E \"         3C E \<         56 - V          70 - p      
09 E $'\t'      23 E \#         3D - =          57 - W          71 - q      
0A E $'\n'      24 E \$         3E E \>         58 - X          72 - r      
0B E $'\v'      25 - %          3F E \?         59 - Y          73 - s      
0C E $'\f'      26 E \&         40 - @          5A - Z          74 - t      
0D E $'\r'      27 E \'         41 - A          5B E \[         75 - u      
0E E $'\016'    28 E \(         42 - B          5C E \\         76 - v      
0F E $'\017'    29 E \)         43 - C          5D E \]         77 - w      
10 E $'\020'    2A E \*         44 - D          5E E \^         78 - x      
11 E $'\021'    2B - +          45 - E          5F - _          79 - y      
12 E $'\022'    2C E \,         46 - F          60 E \`         7A - z      
13 E $'\023'    2D - -          47 - G          61 - a          7B E \{     
14 E $'\024'    2E - .          48 - H          62 - b          7C E \|     
15 E $'\025'    2F - /          49 - I          63 - c          7D E \}     
16 E $'\026'    30 - 0          4A - J          64 - d          7E E \~     
17 E $'\027'    31 - 1          4B - K          65 - e          7F E $'\177'
18 E $'\030'    32 - 2          4C - L          66 - f      
19 E $'\031'    33 - 3          4D - M          67 - g      

Where first field is hexa value of byte, second contain E if character need to be escaped and third field show escaped presentation of character.

Why ,?

You could see some characters that don't always need to be escaped, like ,, } and {.

So not always but sometime:

echo test 1, 2, 3 and 4,5.
test 1, 2, 3 and 4,5.

or

echo test { 1, 2, 3 }
test { 1, 2, 3 }

but care:

echo test{1,2,3}
test1 test2 test3

echo test\ {1,2,3}
test 1 test 2 test 3

echo test\ {\ 1,\ 2,\ 3\ }
test  1 test  2 test  3

echo test\ {\ 1\,\ 2,\ 3\ }
test  1, 2 test  3 

in iPhone App How to detect the screen resolution of the device

Use this code it will help for getting any type of device's screen resolution

 [[UIScreen mainScreen] bounds].size.height
 [[UIScreen mainScreen] bounds].size.width

Whether a variable is undefined

You can just check the variable directly. If not defined it will return a falsy value.

var string = "?z=z";
if (page_name) { string += "&page_name=" + page_name; }
if (table_name) { string += "&table_name=" + table_name; }
if (optionResult) { string += "&optionResult=" + optionResult; }

Getting IP address of client

I use the following static helper method to retrieve the IP of a client:

public static String getClientIpAddr(HttpServletRequest request) {  
    String ip = request.getHeader("X-Forwarded-For");  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("Proxy-Client-IP");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("WL-Proxy-Client-IP");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_X_FORWARDED_FOR");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_X_FORWARDED");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_X_CLUSTER_CLIENT_IP");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_CLIENT_IP");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_FORWARDED_FOR");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_FORWARDED");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_VIA");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("REMOTE_ADDR");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getRemoteAddr();  
    }  
    return ip;  
}

URL encoding in Android

For android, I would use String android.net.Uri.encode(String s)

Encodes characters in the given string as '%'-escaped octets using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes all other characters.

Ex/

String urlEncoded = "http://stackoverflow.com/search?q=" + Uri.encode(query);

Convert string to int if string is a number

To put it on one line:

currentLoad = IIf(IsNumeric(oXLSheet2.Cells(4, 6).Value), CInt(oXLSheet2.Cells(4, 6).Value), 0)

If condition inside of map() React

This one I found simple solutions:

row = myArray.map((cell, i) => {

    if (i == myArray.length - 1) {
      return <div> Test Data 1</div>;
    }
    return <div> Test Data 2</div>;
  });

Removing the first 3 characters from a string

Use the substring method of the String class :

String removeCurrency=amount.getText().toString().substring(3);

How to iterate over a string in C?

You want:

for (i = 0; i < strlen(source); i++){

sizeof gives you the size of the pointer, not the string. However, it would have worked if you had declared the pointer as an array:

char source[] = "This is an example.";

but if you pass the array to function, that too will decay to a pointer. For strings it's best to always use strlen. And note what others have said about changing printf to use %c. And also, taking mmyers comments on efficiency into account, it would be better to move the call to strlen out of the loop:

int len = strlen( source );
for (i = 0; i < len; i++){

or rewrite the loop:

for (i = 0; source[i] != 0; i++){

How to linebreak an svg text within javascript?

With the tspan solution, let's say you don't know in advance where to put your line breaks: you can use this nice function, that I found here: http://bl.ocks.org/mbostock/7555321

That automatically does line breaks for long text svg for a given width in pixel.

function wrap(text, width) {
  text.each(function() {
    var text = d3.select(this),
        words = text.text().split(/\s+/).reverse(),
        word,
        line = [],
        lineNumber = 0,
        lineHeight = 1.1, // ems
        y = text.attr("y"),
        dy = parseFloat(text.attr("dy")),
        tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
    while (word = words.pop()) {
      line.push(word);
      tspan.text(line.join(" "));
      if (tspan.node().getComputedTextLength() > width) {
        line.pop();
        tspan.text(line.join(" "));
        line = [word];
        tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
      }
    }
  });
}

Number of elements in a javascript object

if you are already using jQuery in your build just do this:

$(yourObject).length

It works nicely for me on objects, and I already had jQuery as a dependancy.

How do I convert a org.w3c.dom.Document object to a String?

If you are ok to do transformation, you may try this.

DocumentBuilderFactory domFact = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = domFact.newDocumentBuilder();
Document doc = builder.parse(st);
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
System.out.println("XML IN String format is: \n" + writer.toString());

Displaying a webcam feed using OpenCV and Python

As in the opencv-doc you can get video feed from a camera which is connected to your computer by following code.

import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()
    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # Display the resulting frame
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

You can change cap = cv2.VideoCapture(0) index from 0 to 1 to access the 2nd camera.
Tested in opencv-3.2.0

Vuex - passing multiple parameters to mutation

i think this can be as simple let as assume that you are going to pass multiple parameters to you action as you read up there actions accept only two parameters context and payload which is your data you want to pass in action so let take an example

Setting up Action

instead of

actions: {
        authenticate: ({ commit }, token, expiration) => commit('authenticate', token, expiration)
    }

do

actions: {
        authenticate: ({ commit }, {token, expiration}) => commit('authenticate', token, expiration)
    }

Calling (dispatching) Action

instead of

this.$store.dispatch({
                  type: 'authenticate',
                  token: response.body.access_token,
                  expiration: response.body.expires_in + Date.now()
              })

do

this.$store.dispatch('authenticate',{
                  token: response.body.access_token,
                  expiration: response.body.expires_in + Date.now()
              })

hope this gonna help

What is .htaccess file?

.htaccess file create in directory /var/www/html/.htaccess

<IfModule mod_rewrite.c>

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
</IfModule>

Failed to resolve version for org.apache.maven.archetypes

Read carefully about the reason.

"Failed to resolve version for org.apache.maven.archetypes:maven-archetype- webapp:pom:RELEASE: Could not find metadata org.apache.maven.archetypes:maven-archetype- webapp/maven-metadata.xml in local"

So all you need to do is download the maven-metadata.xml to your {HOME}.m2\repository

That's it.

How to format numbers?

Short solution:

var n = 1234567890;
String(n).replace(/(.)(?=(\d{3})+$)/g,'$1,')
// "1,234,567,890"

jQuery each loop in table row

Use immediate children selector >:

$('#tblOne > tbody  > tr')

Description: Selects all direct child elements specified by "child" of elements specified by "parent".

How to automatically reload a page after a given period of inactivity

And finally the most simple solution:

With alert confirmation:

<script type="text/javascript">
    // Set timeout variables.
    var timoutWarning = 3000; // Display warning in 1Mins.
    var timoutNow = 4000; // Timeout in 2 mins.

    var warningTimer;
    var timeoutTimer;

    // Start timers.
    function StartTimers() {
        warningTimer = setTimeout("IdleWarning()", timoutWarning);
        timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
    }

    // Reset timers.
    function ResetTimers() {
        clearTimeout(warningTimer);
        clearTimeout(timeoutTimer);
        StartTimers();
        $("#timeout").dialog('close');
    }

    // Show idle timeout warning dialog.
    function IdleWarning() {
        var answer = confirm("Session About To Timeout\n\n       You will be automatically logged out.\n       Confirm to remain logged in.")
            if (answer){

                ResetTimers();
            }
            else{
                IdleTimeout();
            }
    }       

    // Logout the user and auto reload or use this window.open('http://www.YourPageAdress.com', '_self'); to auto load a page.
    function IdleTimeout() {
        window.open(self.location,'_top');
    }
</script>

Without alert confirmation:

<script type="text/javascript">
    // Set timeout variables.
    var timoutWarning = 3000; // Display warning in 1Mins.
    var timoutNow = 4000; // Timeout in 2 mins.

    var warningTimer;
    var timeoutTimer;

    // Start timers.
    function StartTimers() {
        warningTimer = setTimeout(timoutWarning);
        timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
    }

    // Reset timers.
    function ResetTimers() {
        clearTimeout(warningTimer);
        clearTimeout(timeoutTimer);
        StartTimers();
        $("#timeout").dialog('close');
    }

    // Logout the user and auto reload or use this window.open('http://www.YourPageAdress.com', '_self'); to auto load a page.
    function IdleTimeout() {
        window.open(self.location,'_top');
    }
</script>

Body code is the SAME for both solutions

<body onload="StartTimers();" onmousemove="ResetTimers();" onKeyPress="ResetTimers();">

TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT maximum storage sizes

From the documentation (MySQL 8) :

      Type | Maximum length
-----------+-------------------------------------
  TINYTEXT |           255 (2 8−1) bytes
      TEXT |        65,535 (216−1) bytes = 64 KiB
MEDIUMTEXT |    16,777,215 (224−1) bytes = 16 MiB
  LONGTEXT | 4,294,967,295 (232−1) bytes =  4 GiB

Note that the number of characters that can be stored in your column will depend on the character encoding.

Unable to connect PostgreSQL to remote database using pgAdmin

I didn't have to change my prostgresql.conf file but, i did have to do the following based on my psql via command line was connecting and pgAdmin not connecting on RDS with AWS.

I did have my RDS set to Publicly Accessible. I made sure my ACL and security groups were wide open and still problem so, I did the following: sudo find . -name *.conf then sudo nano ./data/pg_hba.conf then added to top of directives in pg_hba.conf file host all all 0.0.0.0/0 md5 and pgAdmin automatically logged me in.

This also worked in pg_hba.conf file host all all md5 without any IP address and this also worked with my IP address host all all <myip>/32 md5

As a side note, my RDS was in my default VPC. I had an identical RDS instance in my non-default VPC with identical security group, ACL and security group settings to my default VPC and I could not get it to work. Not sure why but, that's for another day.

Extract year from date

As discussed in the comments, this can be achieved by converting the entry into Date format and extracting the year, for instance like this:

format(as.Date(df1$Date, format="%d/%m/%Y"),"%Y")

How to show what a commit did?

Does

$ git log -p

do what you need?

Check out the chapter on Git Log in the Git Community Book for more examples. (Or look at the the documentation.)

Update: As others (Jakub and Bombe) already pointed out: although the above works, git show is actually the command that is intended to do exactly what was asked for.

Simple VBA selection: Selecting 5 cells to the right of the active cell

This example selects a new Range of Cells defined by the current cell to a cell 5 to the right.

Note that .Offset takes arguments of Offset(row, columns) and can be quite useful.


Sub testForStackOverflow()
    Range(ActiveCell, ActiveCell.Offset(0, 5)).Copy
End Sub

How to extract a string using JavaScript Regex?

This code works:

  let str = "governance[string_i_want]"; 
  let res = str.match(/[^governance\[](.*)[^\]]/g);

res will equal "string_i_want". However, in this example res is still an array, so do not treat res like a string.

By grouping the characters I do not want, using [^string], and matching on what is between the brackets, the code extracts the string I want!

You can try it out here: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_match_regexp

Good luck.

Sorting a List<int>

Sort list of int descending you could just sort first and reverse

class Program
{
    static void Main(string[] args)
    {

        List<int> myList = new List<int>();

        myList.Add(38);
        myList.Add(34);
        myList.Add(35);
        myList.Add(36);
        myList.Add(37);


        myList.Sort();
        myList.Reverse();
        myList.ForEach(Console.WriteLine);


    }



}

Splitting a table cell into two columns in HTML

Please try the following way.

<table>
  <tr>
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
  </tr>
  <tr>
    <td>February</td>
    <td>$80</td>
  </tr>
  <tr>
    <td colspan="2">Sum: $180</td>
  </tr>
</table>

In SSRS, why do I get the error "item with same key has already been added" , when I'm making a new report?

If you are using SPs and if the sps have multiple Select statements (within if conditions) all those selects needs to be handled with unique field names.

How to use ConcurrentLinkedQueue?

Use poll to get the first element, and add to add a new last element. That's it, no synchronization or anything else.

Generating a SHA-256 hash from the Linux command line

echo produces a trailing newline character which is hashed too. Try:

/bin/echo -n foobar | sha256sum 

Launch an app on OS X with command line

Simple, here replace the "APP" by name of the app you want to launch.

export APP_HOME=/Applications/APP.app/Contents/MacOS
export PATH=$PATH:$APP_HOME

Thanks me later.

get index of DataTable column with name

You can use DataColumn.Ordinal to get the index of the column in the DataTable. So if you need the next column as mentioned use Column.Ordinal + 1:

row[row.Table.Columns["ColumnName"].Ordinal + 1] = someOtherValue;

python exception message capturing

The syntax is no longer supported in python 3. Use the following instead.

try:
    do_something()
except BaseException as e:
    logger.error('Failed to do something: ' + str(e))

Xcode 4 - "Valid signing identity not found" error on provisioning profiles on a new Macintosh install

You need to copy over the private key and certificate from your old Mac. Open Keychain Access on the old Mac and look in the Keys category of the login keychain: the key should be there. You need to export both the public and private key, then copy yourkey.pem and yourkey.p12 to the new Mac.

Importing them using Keychain Access will probably fail, at least under 10.6; you can use these commands instead:

security import yourkey.p12
security import yourkey.pem

maven-dependency-plugin (goals "copy-dependencies", "unpack") is not supported by m2e

I had the same problem when trying to load Hadoop project in eclipse. I tried the solutions above, and I believe it might have worked in Eclipse Kepler... not even sure anymore (tried too many things).

With all the problems I was having, I decided to move on to Eclipse Luna, and the solutions above did not work for me.

There was another post that recommended changing the ... tag to package. I started doing that, and it would "clear" the errors... However, I start to think that the changes would bite me later - I am not an expert on Maven.

Fortunately, I found out how to remove all the errors. Go to Window->Preferences->Maven-> Error/Warnings and change "Plugin execution not covered by lifecycle..." option to "Ignore". Hope it helps.

Copy folder recursively, excluding some folders

Similar to Jeff's idea (untested):

find . -name * -print0 | grep -v "exclude" | xargs -0 -I {} cp -a {} destination/

Sort a list alphabetically

You can sort a list in-place just by calling List<T>.Sort:

list.Sort();

That will use the natural ordering of elements, which is fine in your case.

EDIT: Note that in your code, you'd need

_details.Sort();

as the Sort method is only defined in List<T>, not IList<T>. If you need to sort it from the outside where you don't have access to it as a List<T> (you shouldn't cast it as the List<T> part is an implementation detail) you'll need to do a bit more work.

I don't know of any IList<T>-based in-place sorts in .NET, which is slightly odd now I come to think of it. IList<T> provides everything you'd need, so it could be written as an extension method. There are lots of quicksort implementations around if you want to use one of those.

If you don't care about a bit of inefficiency, you could always use:

public void Sort<T>(IList<T> list)
{
    List<T> tmp = new List<T>(list);
    tmp.Sort();
    for (int i = 0; i < tmp.Count; i++)
    {
        list[i] = tmp[i];
    }
}

In other words, copy, sort in place, then copy the sorted list back.


You can use LINQ to create a new list which contains the original values but sorted:

var sortedList = list.OrderBy(x => x).ToList();

It depends which behaviour you want. Note that your shuffle method isn't really ideal:

  • Creating a new Random within the method runs into some of the problems shown here
  • You can declare val inside the loop - you're not using that default value
  • It's more idiomatic to use the Count property when you know you're working with an IList<T>
  • To my mind, a for loop is simpler to understand than traversing the list backwards with a while loop

There are other implementations of shuffling with Fisher-Yates on Stack Overflow - search and you'll find one pretty quickly.

c# foreach (property in object)... Is there a simple way of doing this?

Give this a try:

foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
{
   // do stuff here
}

Also please note that Type.GetProperties() has an overload which accepts a set of binding flags so you can filter out properties on a different criteria like accessibility level, see MSDN for more details: Type.GetProperties Method (BindingFlags) Last but not least don't forget to add the "system.Reflection" assembly reference.

For instance to resolve all public properties:

foreach (var propertyInfo in obj.GetType()
                                .GetProperties(
                                        BindingFlags.Public 
                                        | BindingFlags.Instance))
{
   // do stuff here
}

Please let me know whether this works as expected.

Trim last character from a string

"Hello! world!".TrimEnd('!');

read more

EDIT:

What I've noticed in this type of questions that quite everyone suggest to remove the last char of given string. But this does not fulfill the definition of Trim method.

Trim - Removes all occurrences of white space characters from the beginning and end of this instance.

MSDN-Trim

Under this definition removing only last character from string is bad solution.

So if we want to "Trim last character from string" we should do something like this

Example as extension method:

public static class MyExtensions
{
  public static string TrimLastCharacter(this String str)
  {
     if(String.IsNullOrEmpty(str)){
        return str;
     } else {
        return str.TrimEnd(str[str.Length - 1]);
     }
  }
}

Note if you want to remove all characters of the same value i.e(!!!!)the method above removes all existences of '!' from the end of the string, but if you want to remove only the last character you should use this :

else { return str.Remove(str.Length - 1); }

How to tell if UIViewController's view is visible

If you are using a navigation controller and just want to know if you are in the active and topmost controller, then use:

if navigationController?.topViewController == self {
    // Do something
}

This answer is based on @mattdipasquale's comment.

If you have a more complicated scenario, see the other answers above.

C# 'or' operator?

C# supports two boolean or operators: the single bar | and the double-bar ||.

The difference is that | always checks both the left and right conditions, while || only checks the right-side condition if it's necessary (if the left side evaluates to false).

This is significant when the condition on the right-side involves processing or results in side effects. (For example, if your ErrorDumpWriter.Close method took a while to complete or changed something's state.)

How can I tell if a DOM element is visible in the current viewport?

A better solution:

function getViewportSize(w) {
    var w = w || window;
    if(w.innerWidth != null)
        return {w:w.innerWidth, h:w.innerHeight};
    var d = w.document;
    if (document.compatMode == "CSS1Compat") {
        return {
            w: d.documentElement.clientWidth,
            h: d.documentElement.clientHeight
        };
    }
    return { w: d.body.clientWidth, h: d.body.clientWidth };
}


function isViewportVisible(e) {
    var box = e.getBoundingClientRect();
    var height = box.height || (box.bottom - box.top);
    var width = box.width || (box.right - box.left);
    var viewport = getViewportSize();
    if(!height || !width)
        return false;
    if(box.top > viewport.h || box.bottom < 0)
        return false;
    if(box.right < 0 || box.left > viewport.w)
        return false;
    return true;
}

ActiveSheet.UsedRange.Columns.Count - 8 what does it mean?

UsedRange represents not only nonempty cells, but also formatted cells without any value. And that's why you should be very vigilant.

SCRIPT5: Access is denied in IE9 on xmlhttprequest

This example illustrate how to use AJAX to pull resourcess from any website. it works across browsers. i have tested it on IE8-IE10, safari, chrome, firefox, opera.

if (window.XDomainRequest) xmlhttp = new XDomainRequest();
else if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

xmlhttp.open("GET", "http://api.hostip.info/get_html.php", false);
xmlhttp.send();

hostipInfo = xmlhttp.responseText.split("\n");
var IP = false;
for (i = 0; hostipInfo.length >= i; i++) {
    if (hostipInfo[i]) {

        ipAddress = hostipInfo[i].split(":");
        if (ipAddress[0] == "IP") {
            IP = ipAddress[1];
        }
    }
}
return IP;