Programs & Examples On #Nameerror

The Ruby or Python `NameError` exception.

python NameError: global name '__file__' is not defined

I'm having exacty the same problem and using probably the same tutorial. The function definition:

def read(*rnames):
    return open(os.path.join(os.path.dirname(__file__), *rnames)).read()

is buggy, since os.path.dirname(__file__) will not return what you need. Try replacing os.path.dirname(__file__) with os.path.dirname(os.path.abspath(__file__)):

def read(*rnames):
    return open(os.path.join(os.path.dirname(os.path.abspath(__file__)), *rnames)).read()

I've just posted Andrew that the code snippet in current docs don't work, hopefully, it'll be corrected.

NameError: name 'python' is not defined

When you run the Windows Command Prompt, and type in python, it starts the Python interpreter.

Typing it again tries to interpret python as a variable, which doesn't exist and thus won't work:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\USER>python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> python
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined
>>> print("interpreter has started")
interpreter has started
>>> quit() # leave the interpreter, and go back to the command line

C:\Users\USER>

If you're not doing this from the command line, and instead running the Python interpreter (python.exe or IDLE's shell) directly, you are not in the Windows Command Line, and python is interpreted as a variable, which you have not defined.

NameError: name 'self' is not defined

For cases where you also wish to have the option of setting 'b' to None:

def p(self, **kwargs):
    b = kwargs.get('b', self.a)
    print b

NameError: global name 'unicode' is not defined - in Python 3

If you need to have the script keep working on python2 and 3 as I did, this might help someone

import sys
if sys.version_info[0] >= 3:
    unicode = str

and can then just do for example

foo = unicode.lower(foo)

python: NameError:global name '...‘ is not defined

You need to call self.a() to invoke a from b. a is not a global function, it is a method on the class.

You may want to read through the Python tutorial on classes some more to get the finer details down.

Python NameError: name is not defined

Note that sometimes you will want to use the class type name inside its own definition, for example when using Python Typing module, e.g.

class Tree:
    def __init__(self, left: Tree, right: Tree):
        self.left = left
        self.right = right

This will also result in

NameError: name 'Tree' is not defined

That's because the class has not been defined yet at this point. The workaround is using so called Forward Reference, i.e. wrapping a class name in a string, i.e.

class Tree:
    def __init__(self, left: 'Tree', right: 'Tree'):
        self.left = left
        self.right = right

input() error - NameError: name '...' is not defined

You are running Python 2, not Python 3. For this to work in Python 2, use raw_input.

input_variable = raw_input ("Enter your name: ")
print ("your name is" + input_variable)

HttpServlet cannot be resolved to a type .... is this a bug in eclipse?

You have to set the runtime for your web project to the Tomcat installation you are using; you can do it in the "Targeted runtimes" section of the project configuration.

In this way you will allow Eclipse to add Tomcat's Java EE Web Profile jars to the build path.

Remember that the HttpServlet class isn't in a JRE, but at least in an Enterprise Web Profile (e.g. a servlet container runtime /lib folder).

How to show alert message in mvc 4 controller?

<a href="@Url.Action("DeleteBlog")" class="btn btn-sm btn-danger" onclick="return confirm ('Are you sure want to delete blog?');">

make *** no targets specified and no makefile found. stop

Unpack the source from a working directory and cd into the file directory as root. Use the commands ./configure then make and make install

What are naming conventions for MongoDB?

  1. Keep'em short: Optimizing Storage of Small Objects, SERVER-863. Silly but true.

  2. I guess pretty much the same rules that apply to relation databases should apply here. And after so many decades there is still no agreement whether RDBMS tables should be named singular or plural...

  3. MongoDB speaks JavaScript, so utilize JS naming conventions of camelCase.

  4. MongoDB official documentation mentions you may use underscores, also built-in identifier is named _id (but this may be be to indicate that _id is intended to be private, internal, never displayed or edited.

What's the correct way to convert bytes to a hex string in Python 3?

New in python 3.8, you can pass a delimiter argument to the hex function, as in this example

>>> value = b'\xf0\xf1\xf2'
>>> value.hex('-')
'f0-f1-f2'
>>> value.hex('_', 2)
'f0_f1f2'
>>> b'UUDDLRLRAB'.hex(' ', -4)
'55554444 4c524c52 4142'

https://docs.python.org/3/library/stdtypes.html#bytes.hex

Resolving tree conflict

What you can do to resolve your conflict is

svn resolve --accept working -R <path>

where <path> is where you have your conflict (can be the root of your repo).

Explanations:

  • resolve asks svn to resolve the conflict
  • accept working specifies to keep your working files
  • -R stands for recursive

Hope this helps.

EDIT:

To sum up what was said in the comments below:

  • <path> should be the directory in conflict (C:\DevBranch\ in the case of the OP)
  • it's likely that the origin of the conflict is
    • either the use of the svn switch command
    • or having checked the Switch working copy to new branch/tag option at branch creation
  • more information about conflicts can be found in the dedicated section of Tortoise's documentation.
  • to be able to run the command, you should have the CLI tools installed together with Tortoise:

Command line client tools

Build an iOS app without owning a mac?

Let me tell you step by step few years back I was in same situation.

So We have two Phases

  1. iPhone/iPad (iOS) app development
  2. iPhone/iPad (iOS) app development and Publish to iTunes Store

1. iPhone/iPad (iOS) app development

So If you just want to develop iOS apps you don't want to pay anything,

You just need Mac + XCode IDE

  1. Get Mac Mini or Mac Machine
  2. Create Developer Account on Apple its free
  3. After login developer account you can download Xcode IDE's .dmg file
  4. That's all.

Now you just install Xcode and start developing iOS apps and test/debug with Simulator..

2. iPhone/iPad (iOS) app development and Publish to iTunes Store

for publishing your app on iTunes store you need to pay (example $99 / year) .

So For complete iOS Development Setup you need

  1. Get Mac Mini or Mac Machine
  2. Create Developer Account on Apple its free
  3. After login developer account you can download Xcode IDE's .dmg file
  4. pay $99 for publish apps on iTunes
  5. create your certificates for development/distribution on your apple account
  6. download all certificate on mac machine and install into XCode using Keychain tool
  7. Get at least one iOS Device
  8. Register you device on your apple account
  9. Now you can develop iOS app, test on Real Device and also publish on iTunes Store

Is there a way to get rid of accents and convert a whole string to regular letters?

Use java.text.Normalizer to handle this for you.

string = Normalizer.normalize(string, Normalizer.Form.NFD);
// or Normalizer.Form.NFKD for a more "compatable" deconstruction 

This will separate all of the accent marks from the characters. Then, you just need to compare each character against being a letter and throw out the ones that aren't.

string = string.replaceAll("[^\\p{ASCII}]", "");

If your text is in unicode, you should use this instead:

string = string.replaceAll("\\p{M}", "");

For unicode, \\P{M} matches the base glyph and \\p{M} (lowercase) matches each accent.

Thanks to GarretWilson for the pointer and regular-expressions.info for the great unicode guide.

Revert to a commit by a SHA hash in Git?

Updated:

This answer is simpler than my answer: https://stackoverflow.com/a/21718540/541862

Original answer:

# Create a backup of master branch
git branch backup_master

# Point master to '56e05fce' and
# make working directory the same with '56e05fce'
git reset --hard 56e05fce

# Point master back to 'backup_master' and
# leave working directory the same with '56e05fce'.
git reset --soft backup_master

# Now working directory is the same '56e05fce' and
# master points to the original revision. Then we create a commit.
git commit -a -m "Revert to 56e05fce"

# Delete unused branch
git branch -d backup_master

The two commands git reset --hard and git reset --soft are magic here. The first one changes the working directory, but it also changes head (the current branch) too. We fix the head by the second one.

How to format background color using twitter bootstrap?

Move your row before <div class="container marketing"> and wrap it with a new container, because current container width is 1170px (not 100%):

<div class='hero'>
  <div class="row">
   ...
  </div>
</div>

CSS:

.hero {
  background-color: #2ba6cb;
  padding: 0 90px;
}

Nuget connection attempt failed "Unable to load the service index for source"

Something may have change your proxy setting, like Fiddler. Close Fiddler, then close Visual Studio and open it again.

How to force garbage collection in Java?

Really, I don't get you. But to be clear about "Infinite Object Creation" I meant that there is some piece of code at my big system do creation of objects whom handles and alive in memory, I could not get this piece of code actually, just gesture!!

This is correct, only gesture. You have pretty much the standard answers already given by several posters. Let's take this one by one:

  1. I could not get this piece of code actually

Correct, there is no actual jvm - such is only a specification, a bunch of computer science describing a desired behaviour ... I recently dug into initializing Java objects from native code. To get what you want, the only way is to do what is called aggressive nulling. The mistakes if done wrong are so bad doing that we have to limit ourselves to the original scope of the question:

  1. some piece of code at my big system do creation of objects

Most of the posters here will assume you are saying you are working to an interface, if such we would have to see if you are being handed the entire object or one item at a time.

If you no longer need an object, you can assign null to the object but if you get it wrong there is a null pointer exception generated. I bet you can achieve better work if you use NIO

Any time you or I or anyone else gets: "Please I need that horribly." it is almost universal precursor to near total destruction of what you are trying to work on .... write us a small sample code, sanitizing from it any actual code used and show us your question.

Do not get frustrated. Often what this resolves to is your dba is using a package bought somewhere and the original design is not tweaked for massive data structures.

That is very common.

Generating Random Passwords

validChars can be any construct, but I decided to select based on ascii code ranges removing control chars. In this example, it is a 12 character string.

string validChars = String.Join("", Enumerable.Range(33, (126 - 33)).Where(i => !(new int[] { 34, 38, 39, 44, 60, 62, 96 }).Contains(i)).Select(i => { return (char)i; }));
string.Join("", Enumerable.Range(1, 12).Select(i => { return validChars[(new Random(Guid.NewGuid().GetHashCode())).Next(0, validChars.Length - 1)]; }))

Why there is this "clear" class before footer?

Most likely, as mentioned by others, it is a class carrying the css values:

.clear{clear: both;} 

in order to prevent any more page elements from extending into the footer element. It is a quick and easy way of making sure that pages with columns of varying heights don't cause the footer to render oddly, by possibly setting its top position at the end of a shorter column.

In many cases it is not necessary, but if you are using best-practice standards it is a good idea to use, if you are floating page elements left and right. It functions with page elements similar to the way a horizontal rule works with text, to ensure proper and complete sepperation.

Redirecting to a page after submitting form in HTML

For anyone else having the same problem, I figured it out myself.

_x000D_
_x000D_
    <html>_x000D_
      <body>_x000D_
        <form target="_blank" action="https://website.com/action.php" method="POST">_x000D_
          <input type="hidden" name="fullname" value="Sam" />_x000D_
          <input type="hidden" name="city" value="Dubai&#32;" />_x000D_
          <input onclick="window.location.href = 'https://website.com/my-account';" type="submit" value="Submit request" />_x000D_
        </form>_x000D_
      </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

All I had to do was add the target="_blank" attribute to inline on form to open the response in a new page and redirect the other page using onclick on the submit button.

Spring MVC - How to return simple String as JSON in Rest Controller

Add @ResponseBody annotation, which will write return data in output stream.

set date in input type date

I usually create these two helper functions when using date inputs:

// date is expected to be a date object (e.g., new Date())
const dateToInput = date =>
  `${date.getFullYear()
  }-${('0' + (date.getMonth() + 1)).slice(-2)
  }-${('0' + date.getDate()).slice(-2)
  }`;

// str is expected in yyyy-mm-dd format (e.g., "2017-03-14")
const inputToDate = str => new Date(str.split('-'));

You can then set the date input value as:

$('#datePicker').val(dateToInput(new Date()));

And retrieve the selected value like so

const dateVal = inputToDate($('#datePicker').val())

jQuery ui datepicker with Angularjs

I have almost exactly the same code as you and mine works.

Do you have jQueryUI.js included in the page?

There's a fiddle here

<input type="text" ng-model="date" jqdatepicker />
<br/>
{{ date }}


var datePicker = angular.module('app', []);

datePicker.directive('jqdatepicker', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
         link: function (scope, element, attrs, ngModelCtrl) {
            element.datepicker({
                dateFormat: 'DD, d  MM, yy',
                onSelect: function (date) {
                    scope.date = date;
                    scope.$apply();
                }
            });
        }
    };
});

You'll also need the ng-app="app" somewhere in your HTML

Xcode iOS 8 Keyboard types not supported

I have fixed this issue by unchecking 'Connect Hardware Keyboard'. Please refer to the image below to fix this issueenter image description here

Youtube autoplay not working on mobile devices with embedded HTML5 player

There is a way to make youtube autoplay, and complete playlists play through. Get Adblock browser for Android, and then go to the youtube website, and and configure it for the desktop version of the page, close Adblock browser out, and then reopen, and you will have the desktop version, where autoplay will work.

Using the desktop version will also mean that AdBlock will work. The mobile version invokes the standalone YouTube player, which is why you want the desktop version of the page, so that autoplay will work, and so ad blocking will work.

Tesseract OCR simple example

Here's a great working example project; Tesseract OCR Sample (Visual Studio) with Leptonica Preprocessing Tesseract OCR Sample (Visual Studio) with Leptonica Preprocessing

Tesseract OCR 3.02.02 API can be confusing, so this guides you through including the Tesseract and Leptonica dll into a Visual Studio C++ Project, and provides a sample file which takes an image path to preprocess and OCR. The preprocessing script in Leptonica converts the input image into black and white book-like text.

Setup

To include this in your own projects, you will need to reference the header files and lib and copy the tessdata folders and dlls.

Copy the tesseract-include folder to the root folder of your project. Now Click on your project in Visual Studio Solution Explorer, and go to Project>Properties.

VC++ Directories>Include Directories:

..\tesseract-include\tesseract;..\tesseract-include\leptonica;$(IncludePath) C/C++>Preprocessor>Preprocessor Definitions:

_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) C/C++>Linker>Input>Additional Dependencies:

..\tesseract-include\libtesseract302.lib;..\tesseract-include\liblept168.lib;%(AdditionalDependencies) Now you can include headers in your project's file:

include

include

Now copy the two dll files in tesseract-include and the tessdata folder in Debug to the Output Directory of your project.

When you initialize tesseract, you need to specify the location of the parent folder (!important) of the tessdata folder if it is not already the current directory of your executable file. You can copy my script, which assumes tessdata is installed in the executable's folder.

tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI(); api->Init("D:\tessdataParentFolder\", ... Sample

You can compile the provided sample, which takes one command line argument of the image path to use. The preprocess() function uses Leptonica to create a black and white book-like copy of the image which makes tesseract work with 90% accuracy. The ocr() function shows the functionality of the Tesseract API to return a string output. The toClipboard() can be used to save text to clipboard on Windows. You can copy these into your own projects.

Set default option in mat-select

Read this if you are populating your mat-select asyncronously via an http request.

If you are using a service to make an api call to return the mat-select options values, you must set the 'selected value' on your form control as part of the 'complete' section of your service api call subscribe().

For example:

  this.customerService.getCustomers().subscribe(
  customers => this.customers = customers ,
  error => this.errorMessage = error as any,
  () => this.customerSelectControl.setValue(this.mySelectedValue));

How do I dynamically change the content in an iframe using jquery?

var handle = setInterval(changeIframe, 30000);
var sites = ["google.com", "yahoo.com"];
var index = 0;

function changeIframe() {
  $('#frame')[0].src = sites[index++];
  index = index >= sites.length ? 0 : index;
}

Reference alias (calculated in SELECT) in WHERE clause

You can do this using cross apply

SELECT c.BalanceDue AS BalanceDue
FROM Invoices
cross apply (select (InvoiceTotal - PaymentTotal - CreditTotal) as BalanceDue) as c
WHERE  c.BalanceDue  > 0;

Div Size Automatically size of content

If display: inline; isn't working, try out display: inline-block;. :)

How to test if a double is zero?

Numeric primitives in class scope are initialized to zero when not explicitly initialized.

Numeric primitives in local scope (variables in methods) must be explicitly initialized.

If you are only worried about division by zero exceptions, checking that your double is not exactly zero works great.

if(value != 0)
    //divide by value is safe when value is not exactly zero.

Otherwise when checking if a floating point value like double or float is 0, an error threshold is used to detect if the value is near 0, but not quite 0.

public boolean isZero(double value, double threshold){
    return value >= -threshold && value <= threshold;
}

C# "internal" access modifier when doing unit testing

Internal classes need to be tested and there is an assemby attribute:

using System.Runtime.CompilerServices;

[assembly:InternalsVisibleTo("MyTests")]

Add this to the project info file, e.g. Properties\AssemblyInfo.cs.

Java - Create a new String instance with specified length and filled with specific character. Best solution?

In Java 11, you have repeat:

String s = " ";
s = s.repeat(1);

(Although at the time of writing still subject to change)

MySQL Select Query - Get only first 10 characters of a value

Using the below line

SELECT LEFT(subject , 10) FROM tbl 

MySQL Doc.

How do I get the base URL with PHP?

Fun 'base_url' snippet!

if (!function_exists('base_url')) {
    function base_url($atRoot=FALSE, $atCore=FALSE, $parse=FALSE){
        if (isset($_SERVER['HTTP_HOST'])) {
            $http = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
            $hostname = $_SERVER['HTTP_HOST'];
            $dir =  str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);

            $core = preg_split('@/@', str_replace($_SERVER['DOCUMENT_ROOT'], '', realpath(dirname(__FILE__))), NULL, PREG_SPLIT_NO_EMPTY);
            $core = $core[0];

            $tmplt = $atRoot ? ($atCore ? "%s://%s/%s/" : "%s://%s/") : ($atCore ? "%s://%s/%s/" : "%s://%s%s");
            $end = $atRoot ? ($atCore ? $core : $hostname) : ($atCore ? $core : $dir);
            $base_url = sprintf( $tmplt, $http, $hostname, $end );
        }
        else $base_url = 'http://localhost/';

        if ($parse) {
            $base_url = parse_url($base_url);
            if (isset($base_url['path'])) if ($base_url['path'] == '/') $base_url['path'] = '';
        }

        return $base_url;
    }
}

Use as simple as:

//  url like: http://stackoverflow.com/questions/2820723/how-to-get-base-url-with-php

echo base_url();    //  will produce something like: http://stackoverflow.com/questions/2820723/
echo base_url(TRUE);    //  will produce something like: http://stackoverflow.com/
echo base_url(TRUE, TRUE); || echo base_url(NULL, TRUE);    //  will produce something like: http://stackoverflow.com/questions/
//  and finally
echo base_url(NULL, NULL, TRUE);
//  will produce something like: 
//      array(3) {
//          ["scheme"]=>
//          string(4) "http"
//          ["host"]=>
//          string(12) "stackoverflow.com"
//          ["path"]=>
//          string(35) "/questions/2820723/"
//      }

Wait for async task to finish

How about calling a function from within your callback instead of returning a value in sync_call()?

function sync_call(input) {
    var value;

    // Assume the async call always succeed
    async_call(input, function(result) {
        value = result;
        use_value(value);
    } );
}

Using Django time/date widgets in custom form

Yep, I ended up overriding the /admin/jsi18n/ url.

Here's what I added in my urls.py. Make sure it's above the /admin/ url

    (r'^admin/jsi18n', i18n_javascript),

And here is the i18n_javascript function I created.

from django.contrib import admin
def i18n_javascript(request):
  return admin.site.i18n_javascript(request)

Sending mail attachment using Java

To send html file I have used below code in my project.

final String userID = "[email protected]";
final String userPass = "userpass";
final String emailTo = "[email protected]"

Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");

Session session = Session.getDefaultInstance(props,
        new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userID, userPass);
            }
        });
try {

    Message message = new MimeMessage(session);
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailTo));
    message.setSubject("Hello, this is a test mail..");

    Multipart multipart = new MimeMultipart();
    String fileName = "fileName";

    addAttachment(multipart, fileName);

    MimeBodyPart messageBodyPart1 = new MimeBodyPart();
    messageBodyPart1.setText("No need to reply.");
    multipart.addBodyPart(messageBodyPart1);

    message.setContent(multipart);

    Transport.send(message);
    System.out.println("Email successfully sent to: " + emailTo);

} catch (MessagingException e) {
    e.printStackTrace();
}



private static void addAttachment(Multipart multipart, String fileName){
    DataSource source = null;
    File f = new File("filepath" +"/"+ fileName);
    if(f.exists() && !f.isDirectory()) {
        source = new FileDataSource("filepath" +"/"+ fileName);
        BodyPart messageBodyPart = new MimeBodyPart();
        try {
            messageBodyPart.setHeader("Content-Type", "text/html");
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(fileName);
            multipart.addBodyPart(messageBodyPart);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

The name 'ConfigurationManager' does not exist in the current context

Just install

Install-Package System.Configuration.ConfigurationManager -Version 4.5.0

then use

using System.Configuration;

svn list of files that are modified in local copy

svn status | grep 'M ' works fine on MacOSX.

I just tested this.

What is the correct format to use for Date/Time in an XML file

What does the DTD have to say?

If the XML file is for communicating with other existing software (e.g., SOAP), then check that software for what it expects.

If the XML file is for serialisation or communication with non-existing software (e.g., the one you're writing), you can define it. In which case, I'd suggest something that is both easy to parse in your language(s) of choice, and easy to read for humans. e.g., if your language (whether VB.NET or C#.NET or whatever) allows you to parse ISO dates (YYYY-MM-DD) easily, that's the one I'd suggest.

what is Segmentation fault (core dumped)?

"Segmentation fault" means that you tried to access memory that you do not have access to.

The first problem is with your arguments of main. The main function should be int main(int argc, char *argv[]), and you should check that argc is at least 2 before accessing argv[1].

Also, since you're passing in a float to printf (which, by the way, gets converted to a double when passing to printf), you should use the %f format specifier. The %s format specifier is for strings ('\0'-terminated character arrays).

Check whether an input string contains a number in javascript

Using Regular Expressions with JavaScript. A regular expression is a special text string for describing a search pattern, which is written in the form of /pattern/modifiers where "pattern" is the regular expression itself, and "modifiers" are a series of characters indicating various options.
         The character class is the most basic regex concept after a literal match. It makes one small sequence of characters match a larger set of characters. For example, [A-Z] could stand for the upper case alphabet, and \d could mean any digit.

From below example

  • contains_alphaNumeric « It checks for string contains either letter or number (or) both letter and number. The hyphen (-) is ignored.
  • onlyMixOfAlphaNumeric « It checks for string contain both letters and numbers only of any sequence order.

Example:

function matchExpression( str ) {
    var rgularExp = {
        contains_alphaNumeric : /^(?!-)(?!.*-)[A-Za-z0-9-]+(?<!-)$/,
        containsNumber : /\d+/,
        containsAlphabet : /[a-zA-Z]/,

        onlyLetters : /^[A-Za-z]+$/,
        onlyNumbers : /^[0-9]+$/,
        onlyMixOfAlphaNumeric : /^([0-9]+[a-zA-Z]+|[a-zA-Z]+[0-9]+)[0-9a-zA-Z]*$/
    }

    var expMatch = {};
    expMatch.containsNumber = rgularExp.containsNumber.test(str);
    expMatch.containsAlphabet = rgularExp.containsAlphabet.test(str);
    expMatch.alphaNumeric = rgularExp.contains_alphaNumeric.test(str);

    expMatch.onlyNumbers = rgularExp.onlyNumbers.test(str);
    expMatch.onlyLetters = rgularExp.onlyLetters.test(str);
    expMatch.mixOfAlphaNumeric = rgularExp.onlyMixOfAlphaNumeric.test(str);

    return expMatch;
}

// HTML Element attribute's[id, name] with dynamic values.
var id1 = "Yash", id2="777", id3= "Yash777", id4= "Yash777Image4"
    id11= "image5.64", id22= "55-5.6", id33= "image_Yash", id44= "image-Yash"
    id12= "_-.";
console.log( "Only Letters:\n ", matchExpression(id1) );
console.log( "Only Numbers:\n ", matchExpression(id2) );
console.log( "Only Mix of Letters and Numbers:\n ", matchExpression(id3) );
console.log( "Only Mix of Letters and Numbers:\n ", matchExpression(id4) );

console.log( "Mixed with Special symbols" );
console.log( "Letters and Numbers :\n ", matchExpression(id11) );
console.log( "Numbers [-]:\n ", matchExpression(id22) );
console.log( "Letters :\n ", matchExpression(id33) );
console.log( "Letters [-]:\n ", matchExpression(id44) );

console.log( "Only Special symbols :\n ", matchExpression(id12) );

Out put:

Only Letters:
  {containsNumber: false, containsAlphabet: true, alphaNumeric: true, onlyNumbers: false, onlyLetters: true, mixOfAlphaNumeric: false}
Only Numbers:
  {containsNumber: true, containsAlphabet: false, alphaNumeric: true, onlyNumbers: true, onlyLetters: false, mixOfAlphaNumeric: false}
Only Mix of Letters and Numbers:
  {containsNumber: true, containsAlphabet: true, alphaNumeric: true, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: true}
Only Mix of Letters and Numbers:
  {containsNumber: true, containsAlphabet: true, alphaNumeric: true, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: true}
Mixed with Special symbols
Letters and Numbers :
  {containsNumber: true, containsAlphabet: true, alphaNumeric: false, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}
Numbers [-]:
  {containsNumber: true, containsAlphabet: false, alphaNumeric: false, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}
Letters :
  {containsNumber: false, containsAlphabet: true, alphaNumeric: false, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}
Letters [-]:
  {containsNumber: false, containsAlphabet: true, alphaNumeric: true, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}
Only Special symbols :
  {containsNumber: false, containsAlphabet: false, alphaNumeric: false, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}

java Pattern Matching with Regular Expressions.

When do I need to do "git pull", before or after "git add, git commit"?

I think git pull --rebase is the cleanest way to set your locally recent commits on top of the remote commits which you don't have at a certain point.

So this way you don't have to pull every time you want to start making changes.

Why is ZoneOffset.UTC != ZoneId.of("UTC")?

The answer comes from the javadoc of ZoneId (emphasis mine) ...

A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:

  • Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
  • Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply

Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.

... and from the javadoc of ZoneId#of (emphasis mine):

This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.

The argument id is specified as "UTC", therefore it will return a ZoneId with an offset, which also presented in the string form:

System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));

Outputs:

2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]

As you use the equals method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false.

When the normalized() method is used as proposed in the documentation, the comparison using equals will return true, as normalized() will return the corresponding ZoneOffset:

Normalizes the time-zone ID, returning a ZoneOffset where possible.

now.withZoneSameInstant(ZoneOffset.UTC)
    .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true

As the documentation states, if you use "Z" or "+0" as input id, of will return the ZoneOffset directly and there is no need to call normalized():

now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true

To check if they store the same date time, you can use the isEqual method instead:

now.withZoneSameInstant(ZoneOffset.UTC)
    .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true

Sample

System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
        .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));

Output:

equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true

How do I bottom-align grid elements in bootstrap fluid layout

.align-bottom {
    position: absolute;
    bottom: 10px;
    right: 10px;
}

How to read a specific line using the specific line number from a file in Java?

They are all wrong I just wrote this in about 10 seconds. With this I managed to just call the object.getQuestion("linenumber") in the main method to return whatever line I want.

public class Questions {

File file = new File("Question2Files/triviagame1.txt");

public Questions() {

}

public String getQuestion(int numLine) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line = "";
    for(int i = 0; i < numLine; i++) {
        line = br.readLine();
    }
    return line; }}

Variable name as a string in Javascript

In ES6, you could write something like:

let myVar = 'something';
let nameObject = {myVar};
let getVarNameFromObject = (nameObject) => {
  for(let varName in nameObject) {
    return varName;
  }
}
let varName = getVarNameFromObject(nameObject);

Not really the best looking thing, but it gets the job done.

This leverages ES6's object destructuring.

More info here: https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/

How to resolve "could not execute statement; SQL [n/a]; constraint [numbering];"?

Hibernate tries to insert data that violate underlying database integrity contraints.

There's probably misconfiguration in hibernate persistent classes and/or mapping configuration (*.hbm.xml or annotations in persitent classes).

Maybe a property of the bean you want to save is not type-compatible with its related field in database (could explain the constraint [numbering] part).

How to get the caller class in Java

I know this is an old question but I believed the asker wanted the class, not the class name. I wrote a little method that will get the actual class. It is sort of cheaty and may not always work, but sometimes when you need the actual class, you will have to use this method...

/**
     * Get the caller class.
     * @param level The level of the caller class.
     *              For example: If you are calling this class inside a method and you want to get the caller class of that method,
     *                           you would use level 2. If you want the caller of that class, you would use level 3.
     *
     *              Usually level 2 is the one you want.
     * @return The caller class.
     * @throws ClassNotFoundException We failed to find the caller class.
     */
    public static Class getCallerClass(int level) throws ClassNotFoundException {
        StackTraceElement[] stElements = Thread.currentThread().getStackTrace();
        String rawFQN = stElements[level+1].toString().split("\\(")[0];
        return Class.forName(rawFQN.substring(0, rawFQN.lastIndexOf('.')));
    }

JavaScript getElementByID() not working

At the point you are calling your function, the rest of the page has not rendered and so the element is not in existence at that point. Try calling your function on window.onload maybe. Something like this:

<html>
<head>
    <title></title>
    <script type="text/javascript">
        window.onload = function(){
           var refButton = document.getElementById("btnButton");

            refButton.onclick = function() {
                alert('I am clicked!');
            }
        };
    </script>
</head>
<body>
    <form id="form1">
    <div>
        <input id="btnButton" type="button" value="Click me"/>
    </div>
    </form>
</body>
</html>

How to add number of days to today's date?

you can try this and don't need JQuery: timeSolver.js

For example, add 5 day on today:

var newDay = timeSolver.add(new Date(),5,"day");

You also can add by hour, month...etc. please see for more infomation.

Best way to get value from Collection by index

I agree that this is generally a bad idea. However, Commons Collections had a nice routine for getting the value by index if you really need to:

CollectionUtils.get(collection, index)

If input field is empty, disable submit button

For those that use coffeescript, I've put the code we use globally to disable the submit buttons on our most widely used form. An adaption of Adil's answer above.

$('#new_post button').prop 'disabled', true
$('#new_post #post_message').keyup ->
    $('#new_post button').prop 'disabled', if @value == '' then true else false
    return

Excel VBA Run-time Error '32809' - Trying to Understand it

I have encountered similar (nearly unexplainable) behavior

Found a reference to deleting .exd files under the directory C:\Users\username\AppData\Local\Temp Located one in each of the directory Excel8.0 and VBE. Typical name is MSForms.exd

Google "Excel exd" or "KB 2553154" From my perspective, it is a completely unacceptable situation which has been there for at least a month now.

Run task only if host does not belong to a group

Here's another way to do this:

- name: my command
  command: echo stuff
  when: "'groupname' not in group_names"

group_names is a magic variable as documented here: https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#accessing-information-about-other-hosts-with-magic-variables :

group_names is a list (array) of all the groups the current host is in.

How to make this Header/Content/Footer layout using CSS?

Using flexbox, this is easy to achieve.

Set the wrapper containing your 3 compartments to display: flex; and give it a height of 100% or 100vh. The height of the wrapper will fill the entire height, and the display: flex; will cause all children of this wrapper which has the appropriate flex-properties (for example flex:1;) to be controlled with the flexbox-magic.

Example markup:

<div class="wrapper">
    <header>I'm a 30px tall header</header>
    <main>I'm the main-content filling the void!</main>
    <footer>I'm a 30px tall footer</footer>
</div>

And CSS to accompany it:

.wrapper {
    height: 100vh;
    display: flex;

    /* Direction of the items, can be row or column */
    flex-direction: column;
}

header,
footer {
    height: 30px;
}

main {
    flex: 1;
}

Here's that code live on Codepen: http://codepen.io/enjikaka/pen/zxdYjX/left

You can see more flexbox-magic here: http://philipwalton.github.io/solved-by-flexbox/

Or find a well made documentation here: http://css-tricks.com/snippets/css/a-guide-to-flexbox/

--[Old answer below]--

Here you go: http://jsfiddle.net/pKvxN/

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Layout</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
  header {
    height: 30px;
    background: green;
  }
  footer {
    height: 30px;
    background: red;
  }
</style>
</head>
<body>
  <header>
    <h1>I am a header</h1>
  </header>
  <article>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a ligula dolor.
    </p>
  </article>
  <footer>
    <h4>I am a footer</h4>
  </footer>
</body>
</html>

That works on all modern browsers (FF4+, Chrome, Safari, IE8 and IE9+)

Partition Function COUNT() OVER possible using DISTINCT

I use a solution that is similar to that of David above, but with an additional twist if some rows should be excluded from the count. This assumes that [UserAccountKey] is never null.

-- subtract an extra 1 if null was ranked within the partition,
-- which only happens if there were rows where [Include] <> 'Y'
dense_rank() over (
  partition by [Mth] 
  order by case when [Include] = 'Y' then [UserAccountKey] else null end asc
) 
+ dense_rank() over (
  partition by [Mth] 
  order by case when [Include] = 'Y' then [UserAccountKey] else null end desc
)
- max(case when [Include] = 'Y' then 0 else 1 end) over (partition by [Mth])
- 1

An SQL Fiddle with an extended example can be found here.

How to get the Android Emulator's IP address?

If you need to refer to your host computer's localhost, such as when you want the emulator client to contact a server running on the same host, use the alias 10.0.2.2 to refer to the host computer's loopback interface. From the emulator's perspective, localhost (127.0.0.1) refers to its own loopback interface.More details: http://developer.android.com/guide/faq/commontasks.html#localhostalias

How to order a data frame by one descending and one ascending column?

I use rank:

rum <- read.table(textConnection("P1  P2  P3  T1  T2  T3  I1  I2
2   3   5   52  43  61  6   b
6   4   3   72  NA  59  1   a
1   5   6   55  48  60  6   f
2   4   4   65  64  58  2   b
1   5   6   55  48  60  6   c"), header = TRUE)

> rum[order(rum$I1, -rank(rum$I2), decreasing = TRUE), ]
  P1 P2 P3 T1 T2 T3 I1 I2
1  2  3  5 52 43 61  6  b
5  1  5  6 55 48 60  6  c
3  1  5  6 55 48 60  6  f
4  2  4  4 65 64 58  2  b
2  6  4  3 72 NA 59  1  a

HTML-encoding lost when attribute read from input field

HtmlEncodes the given value

  var htmlEncodeContainer = $('<div />');
  function htmlEncode(value) {
    if (value) {
      return htmlEncodeContainer.text(value).html();
    } else {
      return '';
    }
  }

MySQL Cannot Add Foreign Key Constraint

I had a similar error in creating foreign key in a Many to Many table where the primary key consisted of 2 foreign keys and another normal column. I fixed the issue by correcting the referenced table name i.e. company, as shown in the corrected code below:

create table company_life_cycle__history -- (M-M)
(
company_life_cycle_id tinyint unsigned not null,
Foreign Key (company_life_cycle_id) references company_life_cycle(id) ON DELETE    CASCADE ON UPDATE CASCADE,
company_id MEDIUMINT unsigned not null,
Foreign Key (company_id) references company(id) ON DELETE CASCADE ON UPDATE CASCADE,
activity_on date NOT NULL,
PRIMARY KEY pk_company_life_cycle_history (company_life_cycle_id, company_id,activity_on),
created_on datetime DEFAULT NULL,
updated_on datetime DEFAULT NULL,
created_by varchar(50) DEFAULT NULL,
updated_by varchar(50) DEFAULT NULL
);

Best way to "negate" an instanceof

I don't know what you imagine when you say "beautiful", but what about this? I personally think it's worse than the classic form you posted, but somebody might like it...

if (str instanceof String == false) { /* ... */ }

MySQL Update Column +1?

How about:

update table
set columnname = columnname + 1
where id = <some id>

Is there a command like "watch" or "inotifywait" on the Mac?

watchdog is a cross-platform python API for watching files / directories, and it has builtin "tricks" tool that allows you to trigger actions (including shell commands) when events occur (including new added file, removed file and changed file).

RecyclerView: Inconsistency detected. Invalid item position

I ran into this nasty stack trace with the new Android Architecture Components recently. Essentially, I have a list of items in my ViewModel that are observed by my Fragment, using LiveData. When the ViewModel posts a new value for the data, the Fragment updates the adapter, passing in these new data elements and notifying the adapter that there have been changes.

Unfortunately, when passing in the new data elements to the adapter, I failed to account for the fact that both the ViewModel and the Adapter would be pointing to the same object reference! Meaning that if I update the data and call postValue() from within the ViewModel, there's a very small window where the data could be updated and the adapter not yet notified!

My fix was to instantiate a fresh copy of the elements when passed in to the adapter:

mList = new ArrayList<>(passedList);

With this super easy fix you can be ensured your adapter data will not change until right before your adapter is notified.

Is there any difference between a GUID and a UUID?

Not really. GUID is more Microsoft-centric whereas UUID is used more widely (e.g., as in the urn:uuid: URN scheme, and in CORBA).

Sheet.getRange(1,1,1,12) what does the numbers in bracket specify?

Found these docu on the google docu pages:

  • row --- int --- top row of the range
  • column --- int--- leftmost column of the range
  • optNumRows --- int --- number of rows in the range.
  • optNumColumns --- int --- number of columns in the range

In your example, you would get (if you picked the 3rd row) "C3:O3", cause C --> O is 12 columns

edit

Using the example on the docu:

// The code below will get the number of columns for the range C2:G8
// in the active spreadsheet, which happens to be "4"
var count = SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).getNumColumns(); Browser.msgBox(count);

The values between brackets:
2: the starting row = 2
3: the starting col = C
6: the number of rows = 6 so from 2 to 8
4: the number of cols = 4 so from C to G

So you come to the range: C2:G8

What is the difference between char * const and const char *?

I would like to point out that using int const * (or const int *) isn't about a pointer pointing to a const int variable, but that this variable is const for this specific pointer.

For example:

int var = 10;
int const * _p = &var;

The code above compiles perfectly fine. _p points to a const variable, although var itself isn't constant.

Remote Linux server to remote linux server dir copy. How?

Well, quick answer would to take a look at the 'scp' manpage, or perhaps rsync - depending exactly on what you need to copy. If you had to, you could even do tar-over-ssh:

tar cvf - | ssh server tar xf -

How can I get a precise time, for example in milliseconds in Objective-C?

NSDate and the timeIntervalSince* methods will return a NSTimeInterval which is a double with sub-millisecond accuracy. NSTimeInterval is in seconds, but it uses the double to give you greater precision.

In order to calculate millisecond time accuracy, you can do:

// Get a current time for where you want to start measuring from
NSDate *date = [NSDate date];

// do work...

// Find elapsed time and convert to milliseconds
// Use (-) modifier to conversion since receiver is earlier than now
double timePassed_ms = [date timeIntervalSinceNow] * -1000.0;

Documentation on timeIntervalSinceNow.

There are many other ways to calculate this interval using NSDate, and I would recommend looking at the class documentation for NSDate which is found in NSDate Class Reference.

Transform only one axis to log10 scale with ggplot2

The simplest is to just give the 'trans' (formerly 'formatter' argument the name of the log function:

m + geom_boxplot() + scale_y_continuous(trans='log10')

EDIT: Or if you don't like that, then either of these appears to give different but useful results:

m <- ggplot(diamonds, aes(y = price, x = color), log="y")
m + geom_boxplot() 
m <- ggplot(diamonds, aes(y = price, x = color), log10="y")
m + geom_boxplot()

EDIT2 & 3: Further experiments (after discarding the one that attempted successfully to put "$" signs in front of logged values):

fmtExpLg10 <- function(x) paste(round_any(10^x/1000, 0.01) , "K $", sep="")
ggplot(diamonds, aes(color, log10(price))) + 
  geom_boxplot() + 
  scale_y_continuous("Price, log10-scaling", trans = fmtExpLg10)

alt text

Note added mid 2017 in comment about package syntax change:

scale_y_continuous(formatter = 'log10') is now scale_y_continuous(trans = 'log10') (ggplot2 v2.2.1)

High-precision clock in Python

Python 3.7 introduces 6 new time functions with nanosecond resolution, for example instead of time.time() you can use time.time_ns() to avoid floating point imprecision issues:

import time
print(time.time())
# 1522915698.3436284
print(time.time_ns())
# 1522915698343660458

These 6 functions are described in PEP 564:

time.clock_gettime_ns(clock_id)

time.clock_settime_ns(clock_id, time:int)

time.monotonic_ns()

time.perf_counter_ns()

time.process_time_ns()

time.time_ns()

These functions are similar to the version without the _ns suffix, but return a number of nanoseconds as a Python int.

SQL set values of one column equal to values of another column in the same table

I would do it this way:

UPDATE YourTable SET B = COALESCE(B, A);

COALESCE is a function that returns its first non-null argument.

In this example, if B on a given row is not null, the update is a no-op.

If B is null, the COALESCE skips it and uses A instead.

Keep the order of the JSON keys during JSON conversion to CSV

The most safe way is probably overriding keys method that is used to generate output:

new JSONObject(){
  @Override
  public Iterator keys(){
    TreeSet<Object> sortedKeys = new TreeSet<Object>();
    Iterator keys = super.keys();
    while(keys.hasNext()){
      sortedKeys.add(keys.next());
    }
    return sortedKeys.iterator();
  }
};

How to create a new text file using Python

    file = open("path/of/file/(optional)/filename.txt", "w") #a=append,w=write,r=read
    any_string = "Hello\nWorld"
    file.write(any_string)
    file.close()

File.separator vs FileSystem.getSeparator() vs System.getProperty("file.separator")?

If your code doesn't cross filesystem boundaries, i.e. you're just working with one filesystem, then use java.io.File.separator.

This will, as explained, get you the default separator for your FS. As Bringer128 explained, System.getProperty("file.separator") can be overriden via command line options and isn't as type safe as java.io.File.separator.

The last one, java.nio.file.FileSystems.getDefault().getSeparator(); was introduced in Java 7, so you might as well ignore it for now if you want your code to be portable across older Java versions.

So, every one of these options is almost the same as others, but not quite. Choose one that suits your needs.

T-SQL split string based on delimiter

SELECT CASE 
        WHEN CHARINDEX('/', myColumn, 0) = 0
            THEN myColumn
        ELSE LEFT(myColumn, CHARINDEX('/', myColumn, 0)-1)
        END AS FirstName
    ,CASE 
        WHEN CHARINDEX('/', myColumn, 0) = 0
            THEN ''
        ELSE RIGHT(myColumn, CHARINDEX('/', REVERSE(myColumn), 0)-1)
        END AS LastName
FROM MyTable

How to set margin of ImageView using code, not xml

Here is an example to add 8px Margin on left, top, right, bottom.


ImageView imageView = new ImageView(getApplicationContext());

ViewGroup.MarginLayoutParams marginLayoutParams = new ViewGroup.MarginLayoutParams(
    ViewGroup.MarginLayoutParams.MATCH_PARENT,
    ViewGroup.MarginLayoutParams.WRAP_CONTENT
);

marginLayoutParams.setMargins(8, 8, 8, 8);

imageView.setLayoutParams(marginLayoutParams);

Import a module from a relative path

You could also add the subdirectory to your Python path so that it imports as a normal script.

import sys
sys.path.insert(0, <path to dirFoo>)
import Bar

Angular2, what is the correct way to disable an anchor element?

This is for anchor tags that act as tabs:

[ngStyle]="{'pointer-events': isSaving ? 'none': 'auto'}"

Adding a collaborator to my free GitHub account?

In the repository, click Admin, then go to the Collaborators tab.

Angular - Can't make ng-repeat orderBy work

orderby works on arrays that contain objects with immidiate values which can be used as filters, ie

controller.images = [{favs:1,name:"something"},{favs:0,name:"something else"}];

When the above array is repeated, you may use | orderBy:'favs' to refer to that value immidiately, or use a minus in front to order descending

<div class="timeline-image" ng-repeat="image in controller.images | orderBy:'-favs'">
    <img ng-src="{{ images.name }}"/>
</div>

mailto using javascript

You can use the simple mailto, see below for the simple markup.

<a href="mailto:[email protected]">Click here to mail</a>

Once clicked, it will open your Outlook or whatever email client you have set.

Format a Go string without printing?

We can custom A new String type via define new Type with Format support.

package main

import (
    "fmt"
    "text/template"
    "strings"
)

type String string
func (s String) Format(data map[string]interface{}) (out string, err error) {
    t := template.Must(template.New("").Parse(string(s)))
    builder := &strings.Builder{}
    if err = t.Execute(builder, data); err != nil {
        return
    }
    out = builder.String()
    return
}


func main() {
    const tmpl = `Hi {{.Name}}!  {{range $i, $r := .Roles}}{{if $i}}, {{end}}{{.}}{{end}}`
    data := map[string]interface{}{
        "Name":     "Bob",
        "Roles":    []string{"dbteam", "uiteam", "tester"},
    }

    s ,_:= String(tmpl).Format(data)
    fmt.Println(s)
}

How do I find the number of arguments passed to a Bash script?

that value is contained in the variable $#

Set cookies for cross origin requests

What you need to do

To allow receiving & sending cookies by a CORS request successfully, do the following.

Back-end (server): Set the HTTP header Access-Control-Allow-Credentials value to true. Also, make sure the HTTP headers Access-Control-Allow-Origin and Access-Control-Allow-Headers are set and not with a wildcard *.

Recommended Cookie settings per Chrome and Firefox update in 2021: SameSite=None and Secure. See MDN documentation

For more info on setting CORS in express js read the docs here

Front-end (client): Set the XMLHttpRequest.withCredentials flag to true, this can be achieved in different ways depending on the request-response library used:

Or

Avoid having to use CORS in combination with cookies. You can achieve this with a proxy.

If you for whatever reason don't avoid it. The solution is above.

It turned out that Chrome won't set the cookie if the domain contains a port. Setting it for localhost (without port) is not a problem. Many thanks to Erwin for this tip!

How to correctly get image from 'Resources' folder in NetBeans

Thanks, Valter Henrique, with your tip i managed to realise, that i simply entered incorrect path to this image. In one of my tries i use

    String pathToImageSortBy = "resources/testDataIcons/filling.png";
    ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));

But correct way was use name of my project in path to resource

String pathToImageSortBy = "nameOfProject/resources/testDataIcons/filling.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));

Warning about SSL connection when connecting to MySQL database

This was OK for me:

this.conn = (Connection)DriverManager
    .getConnection(url + dbName + "?useSSL=false", userName, password);

Android - How To Override the "Back" button so it doesn't Finish() my Activity?

@Override
public void onBackPressed() {
// Put your code here.
}

//I had to go back to the dashboard. Hence,

@Override
public void onBackPressed() {
    Intent intent = new Intent(this,Dashboard.class);
    startActivity(intent);
}
Just write this above or below the onCreate Method(within the class)

The calling thread must be STA, because many UI components require this

Just mark your program with the [STAThread] attribute and the error goes away! it's magic :)

How do I scroll to an element within an overflowed Div?

The accepted answer only works with direct children of the scrollable element, while the other answers didn't centered the child in the scrollable element.

Example HTML:

<div class="scrollable-box">
    <div class="row">
        <div class="scrollable-item">
            Child 1
        </div>
        <div class="scrollable-item">
            Child 2
        </div>
        <div class="scrollable-item">
            Child 3
        </div>
        <div class="scrollable-item">
            Child 4
        </div>
        <div class="scrollable-item">
            Child 5
        </div>
        <div class="scrollable-item">
            Child 6
        </div>
        <div class="scrollable-item">
            Child 7
        </div>
        <div class="scrollable-item">
            Child 8
        </div>
        <div class="scrollable-item">
            Child 9
        </div>
        <div class="scrollable-item">
            Child 10
        </div>
        <div class="scrollable-item">
            Child 11
        </div>
        <div class="scrollable-item">
            Child 12
        </div>
        <div class="scrollable-item">
            Child 13
        </div>
        <div class="scrollable-item">
            Child 14
        </div>
        <div class="scrollable-item">
            Child 15
        </div>
        <div class="scrollable-item">
            Child 16
        </div>
    </div>
</div>

<style>
.scrollable-box {
    width: 800px;
    height: 150px;
    overflow-x: hidden;
    overflow-y: scroll;
    border: 1px solid #444;
}
.scrollable-item {
    font-size: 20px;
    padding: 10px;
    text-align: center;
}
</style>

Build a small jQuery plugin:

$.fn.scrollDivToElement = function(childSel) {
    if (! this.length) return this;

    return this.each(function() {
        let parentEl = $(this);
        let childEl = parentEl.find(childSel);

        if (childEl.length > 0) {
            parentEl.scrollTop(
                parentEl.scrollTop() - parentEl.offset().top + childEl.offset().top - (parentEl.outerHeight() / 2) + (childEl.outerHeight() / 2)
            );
        }
    });
};

Usage:

$('.scrollable-box').scrollDivToElement('.scrollable-item:eq(12)');

Explanation:

  1. parentEl.scrollTop(...) sets current vertical position of the scroll bar.

  2. parentEl.scrollTop() gets the current vertical position of the scroll bar.

  3. parentEl.offset().top gets the current coordinates of the parentEl relative to the document.

  4. childEl.offset().top gets the current coordinates of the childEl relative to the document.

  5. parentEl.outerHeight() / 2 gets the outer height divided in half (because we want it centered) of the child element.

  6. when used:

$(parent).scrollDivToElement(child);

The parent is the scrollable div and it can be a string or a jQuery object of the DOM element.
The child is any child that you want to scroll to and it can be a string or a jQuery object of the DOM element.

Codepen demo

Why am I getting the message, "fatal: This operation must be run in a work tree?"

Same issue i got, i did following steps,

  1. git init
  2. git add .
  3. git commit -m"inital setup"
  4. git push -f origin master

then it work starts working.

Unable to establish SSL connection, how do I fix my SSL cert?

I had this problem when setting up a new EC2 instance. I had not added HTTPS to my security group, and so port 443 was not open.

Find out time it took for a python script to complete execution

import sys
import timeit

start = timeit.default_timer()

#do some nice things...

stop = timeit.default_timer()
total_time = stop - start

# output running time in a nice format.
mins, secs = divmod(total_time, 60)
hours, mins = divmod(mins, 60)

sys.stdout.write("Total running time: %d:%d:%d.\n" % (hours, mins, secs))

How to check if file already exists in the folder

'In Visual Basic

Dim FileName = "newfile.xml" ' The Name of file with its Extension Example A.txt or A.xml

Dim FilePath ="C:\MyFolderName" & "\" & FileName  'First Name of Directory and Then Name of Folder if it exists and then attach the name of file you want to search.

If System.IO.File.Exists(FilePath) Then
    MsgBox("The file exists")
Else
    MsgBox("the file doesn't exist")
End If

How do I merge changes to a single file, rather than merging commits?

Assuming B is the current branch:

$ git diff A <file-path> > patch.tmp
$ git apply patch.tmp -R

Note that this only applies changes to the local file. You'll need to commit afterwards.

How do I find if a string starts with another string in Ruby?

The method mentioned by steenslag is terse, and given the scope of the question it should be considered the correct answer. However it is also worth knowing that this can be achieved with a regular expression, which if you aren't already familiar with in Ruby, is an important skill to learn.

Have a play with Rubular: http://rubular.com/

But in this case, the following ruby statement will return true if the string on the left starts with 'abc'. The \A in the regex literal on the right means 'the beginning of the string'. Have a play with rubular - it will become clear how things work.

'abcdefg' =~  /\Aabc/ 

How to set variable from a SQL query?

Select @ModelID =m.modelid 
From   MODELS m
Where  m.areaid = 'South Coast'

In this case if you have two or more results returned then your result is the last record. So be aware of this if you might have two more records returned as you might not see the expected result.

Java: How to insert CLOB into oracle database

Converting clob to string:

Clob clob=rs.getClob(2);      
String str=(String)clob.getSubString(1,(int)clob.length());      
System.out.println("Clob Data is : "+str);

Difference between EXISTS and IN in SQL?

The reason is that the EXISTS operator works based on the “at least found” principle. It returns true and stops scanning table once at least one matching row found.

On the other hands, when the IN operator is combined with a subquery, MySQL must process the subquery first, and then uses the result of the subquery to process the whole query.

The general rule of thumb is that if the subquery contains a large volume of data, the EXISTS operator provides a better performance.

However, the query that uses the IN operator will perform faster if the result set returned from the subquery is very small.

Android EditText delete(backspace) key event

Based on @Jiff ZanyEditText here is WiseEditText with setSoftKeyListener(OnKeyListener)

package com.locopixel.seagame.ui.custom;

import java.util.Random;

import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.AppCompatEditText;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputConnectionWrapper;

public class WiseEditText extends AppCompatEditText {

    private Random r = new Random();
    private OnKeyListener keyListener;

    public WiseEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public WiseEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public WiseEditText(Context context) {
        super(context);
    }

    @Override
    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
        return new MyInputConnection(super.onCreateInputConnection(outAttrs),
                true);
    }

    private class MyInputConnection extends InputConnectionWrapper {

        public MyInputConnection(InputConnection target, boolean mutable) {
            super(target, mutable);
        }

        @Override
        public boolean sendKeyEvent(KeyEvent event) {
            if (keyListener != null) {
                keyListener.onKey(WiseEditText.this,event.getKeyCode(),event);
            }
            return super.sendKeyEvent(event);
        }

        @Override
        public boolean deleteSurroundingText(int beforeLength, int afterLength) {       
            // magic: in latest Android, deleteSurroundingText(1, 0) will be called for backspace
            if (beforeLength == 1 && afterLength == 0) {
                // backspace
                return sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL))
                    && sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL));
            }

            return super.deleteSurroundingText(beforeLength, afterLength);
        }

    }

    public void setSoftKeyListener(OnKeyListener listener){
        keyListener = listener;
    }

}

Java reverse an int value without using array

If you wanna reverse any number like 1234 and you want to revers this number to let it looks like 4321. First of all, initialize 3 variables int org ; int reverse = 0; and int reminder ; then put your logic like

    Scanner input = new Scanner (System.in);
    System.out.println("Enter number to reverse ");
    int org = input.nextInt();
    int getReminder;
    int r = 0;
    int count = 0;

    while (org !=0){
        getReminder = org%10;
         r = 10 * r + getReminder;
         org = org/10;



    }
        System.out.println(r);

    }

Adding a stylesheet to asp.net (using Visual Studio 2010)

Add your style here:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="BSC.SiteMaster" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head runat="server">
    <title></title>
    <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
    <link href="~/Styles/NewStyle.css" rel="stylesheet" type="text/css" />

    <asp:ContentPlaceHolder ID="HeadContent" runat="server">
    </asp:ContentPlaceHolder>
</head>

Then in the page:

<asp:Table CssClass=NewStyleExampleClass runat="server" >

How to install OpenSSL for Python

SSL development libraries have to be installed

CentOS:

$ yum install openssl-devel libffi-devel

Ubuntu:

$ apt-get install libssl-dev libffi-dev

OS X (with Homebrew installed):

$ brew install openssl

Submitting a form by pressing enter without a submit button

Have you tried this ?

<input type="submit" style="visibility: hidden;" />

Since most browsers understand visibility:hidden and it doesn't really work like display:none, I'm guessing that it should be fine, though. Haven't really tested it myself, so CMIIW.

jQuery: outer html()

No siblings solution:

var x = $('#xxx').parent().html();
alert(x);

Universal solution:

// no cloning necessary    
var x = $('#xxx').wrapAll('<div>').parent().html(); 
alert(x);

Fiddle here: http://jsfiddle.net/ezmilhouse/Mv76a/

Spring Boot - How to get the running port

You can get the server port from the

HttpServletRequest
@Autowired
private HttpServletRequest request;

@GetMapping(value = "/port")
public Object getServerPort() {
   System.out.println("I am from " + request.getServerPort());
   return "I am from  " + request.getServerPort();
}
    

Populate dropdown select with array using jQuery

You can also do this:

var list = $('#items')[0]; // HTMLSelectElement
$.each(numbers, function(index, text) { 
    list.options[list.options.length] = new Option(index, text);
}); 

scrollTop animation without jquery

HTML:

<button onclick="scrollToTop(1000);"></button>

1# JavaScript (linear):

function scrollToTop (duration) {
    // cancel if already on top
    if (document.scrollingElement.scrollTop === 0) return;

    const totalScrollDistance = document.scrollingElement.scrollTop;
    let scrollY = totalScrollDistance, oldTimestamp = null;

    function step (newTimestamp) {
        if (oldTimestamp !== null) {
            // if duration is 0 scrollY will be -Infinity
            scrollY -= totalScrollDistance * (newTimestamp - oldTimestamp) / duration;
            if (scrollY <= 0) return document.scrollingElement.scrollTop = 0;
            document.scrollingElement.scrollTop = scrollY;
        }
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}

2# JavaScript (ease in and out):

function scrollToTop (duration) {
    // cancel if already on top
    if (document.scrollingElement.scrollTop === 0) return;

    const cosParameter = document.scrollingElement.scrollTop / 2;
    let scrollCount = 0, oldTimestamp = null;

    function step (newTimestamp) {
        if (oldTimestamp !== null) {
            // if duration is 0 scrollCount will be Infinity
            scrollCount += Math.PI * (newTimestamp - oldTimestamp) / duration;
            if (scrollCount >= Math.PI) return document.scrollingElement.scrollTop = 0;
            document.scrollingElement.scrollTop = cosParameter + cosParameter * Math.cos(scrollCount);
        }
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}
/* 
  Explanation:
  - pi is the length/end point of the cosinus intervall (see below)
  - newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
    (for more information see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
  - newTimestamp - oldTimestamp equals the delta time

    a * cos (bx + c) + d                        | c translates along the x axis = 0
  = a * cos (bx) + d                            | d translates along the y axis = 1 -> only positive y values
  = a * cos (bx) + 1                            | a stretches along the y axis = cosParameter = window.scrollY / 2
  = cosParameter + cosParameter * (cos bx)  | b stretches along the x axis = scrollCount = Math.PI / (scrollDuration / (newTimestamp - oldTimestamp))
  = cosParameter + cosParameter * (cos scrollCount * x)
*/

Note:

  • Duration in milliseconds (1000ms = 1s)
  • Second script uses the cos function. Example curve:

enter image description here

3# Simple scrolling library on Github

add elements to object array

You can try

Subject[] subjects = new Subject[2];
subjects[0] = new Subject{....};
subjects[1] = new Subject{....};

alternatively you can use List

List<Subject> subjects = new List<Subject>();
subjects.add(new Subject{....});
subjects.add(new Subject{....});

Artisan, creating tables in database

in laravel 5 first we need to create migration and then run the migration

Step 1.

php artisan make:migration create_users_table --create=users

Step 2.

php artisan migrate

Unable to find velocity template resources

you can try to add these code:

VelocityEngine ve = new VelocityEngine();
String vmPath = request.getSession().getServletContext().getRealPath("${your dir}");
Properties p = new Properties();
p.setProperty("file.resource.loader.path", vmPath+"//");
ve.init(p);

I do this, and pass!

ASP.NET Core Get Json Array using IConfiguration

Add a level in your appsettings.json :

{
  "MySettings": {
    "MyArray": [
      "str1",
      "str2",
      "str3"
    ]
  }
}

Create a class representing your section :

public class MySettings
{
     public List<string> MyArray {get; set;}
}

In your application startup class, bind your model an inject it in the DI service :

services.Configure<MySettings>(options => Configuration.GetSection("MySettings").Bind(options));

And in your controller, get your configuration data from the DI service :

public class HomeController : Controller
{
    private readonly List<string> _myArray;

    public HomeController(IOptions<MySettings> mySettings)
    {
        _myArray = mySettings.Value.MyArray;
    }

    public IActionResult Index()
    {
        return Json(_myArray);
    }
}

You can also store your entire configuration model in a property in your controller, if you need all the data :

public class HomeController : Controller
{
    private readonly MySettings _mySettings;

    public HomeController(IOptions<MySettings> mySettings)
    {
        _mySettings = mySettings.Value;
    }

    public IActionResult Index()
    {
        return Json(_mySettings.MyArray);
    }
}

The ASP.NET Core's dependency injection service works just like a charm :)

Visual Studio 2010 always thinks project is out of date, but nothing has changed

For Visual Studio/Express 2010 only. See other (easier) answers for VS2012, VS2013, etc

To find the missing file(s), use info from the article Enable C++ project system logging to enable debug logging in Visual Studio and let it just tell you what's causing the rebuild:

  1. Open the devenv.exe.config file (found in %ProgramFiles%\Microsoft Visual Studio 10.0\Common7\IDE\ or in %ProgramFiles(x86)%\Microsoft Visual Studio 10.0\Common7\IDE\). For Express versions the config file is named V*Express.exe.config.
  2. Add the following after the </configSections> line:

    <system.diagnostics>
      <switches>
        <add name="CPS" value="4" />
      </switches>
    </system.diagnostics>
    
  3. Restart Visual Studio
  4. Open up DbgView and make sure it's capturing debug output
  5. Try to debug (hit F5 in Visual Studio)
  6. Search the debug log for any lines of the form:

    devenv.exe Information: 0 : Project 'Bla\Bla\Dummy.vcxproj' not up to date because build input 'Bla\Bla\SomeFile.h' is missing.

    (I just hit Ctrl+F and searched for not up to date) These will be the references causing the project to be perpetually "out of date".

To correct this, either remove any references to the missing files from your project, or update the references to indicate their actual locations.

Note: If using 2012 or later then the snippet should be:

<system.diagnostics>
  <switches>
   <add name="CPS" value="Verbose" />
  </switches>
</system.diagnostics>

Why am I getting AttributeError: Object has no attribute

You can't access outside private fields of a class. private fields are starting with __ . for example -

class car:
    def __init__(self):
        self.__updatesoftware()

    def drive(self):
        print("driving")

    def __updatesoftware(self):
        print("updating software:")

obj = car()
obj.drive()  
obj.__updatesoftware()  ## here it will throw an error because 

__updatesoftware is an private method.

While, Do While, For loops in Assembly Language (emu8086)

For-loops:

For-loop in C:

for(int x = 0; x<=3; x++)
{
    //Do something!
}

The same loop in 8086 assembler:

        xor cx,cx   ; cx-register is the counter, set to 0
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        inc cx      ; Increment
        cmp cx,3    ; Compare cx to the limit
        jle loop1   ; Loop while less or equal

That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:

        mov cx,4    ; 4 iterations
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        loop loop1  ; loop instruction decrements cx and jumps to label if not 0

If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction

times 4 nop

Do-while-loops

Do-while-loop in C:

int x=1;
do{
    //Do something!
}
while(x==1)

The same loop in assembler:

        mov ax,1
loop1   nop         ; Whatever you wanna do goes here
        cmp ax,1    ; Check wether cx is 1
        je loop1    ; And loop if equal

While-loops

While-loop in C:

while(x==1){
    //Do something
}

The same loop in assembler:

        jmp loop1   ; Jump to condition first
cloop1  nop         ; Execute the content of the loop
loop1   cmp ax,1    ; Check the condition
        je cloop1   ; Jump to content of the loop if met

For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.

Creating a Plot Window of a Particular Size

Use dev.new(). (See this related question.)

plot(1:10)
dev.new(width=5, height=4)
plot(1:20)

To be more specific which units are used:

dev.new(width=5, height=4, unit="in")
plot(1:20)
dev.new(width = 550, height = 330, unit = "px")
plot(1:15)

edit additional argument for Rstudio (May 2020), (thanks user Soren Havelund Welling)

For Rstudio, add dev.new(width=5,height=4,noRStudioGD = TRUE)

Timeout a command in bash without unnecessary delay

Here is a version that does not rely on spawning a child process - I needed a standalone script which embedded this functionality. It also does a fractional poll interval, so you can poll quicker. timeout would have been preferred - but I'm stuck on an old server

# wait_on_command <timeout> <poll interval> command
wait_on_command()
{
    local timeout=$1; shift
    local interval=$1; shift
    $* &
    local child=$!

    loops=$(bc <<< "($timeout * (1 / $interval)) + 0.5" | sed 's/\..*//g')
    ((t = loops))
    while ((t > 0)); do
        sleep $interval
        kill -0 $child &>/dev/null || return
        ((t -= 1))
    done

    kill $child &>/dev/null || kill -0 $child &>/dev/null || return
    sleep $interval
    kill -9 $child &>/dev/null
    echo Timed out
}

slow_command()
{
    sleep 2
    echo Completed normally
}

# wait 1 sec in 0.1 sec increments
wait_on_command 1 0.1 slow_command

# or call an external command
wait_on_command 1 0.1 sleep 10

WinForms DataGridView font size

In winform datagrid, right click to view its properties. It has a property called DefaultCellStyle. Click the ellipsis on DefaultCellStyle, then it will present Cell Style Builder window which has the option to change the font size.

Its easy.

In jQuery, what's the best way of formatting a number to 2 decimal places?

Maybe something like this, where you could select more than one element if you'd like?

$("#number").each(function(){
    $(this).val(parseFloat($(this).val()).toFixed(2));
});

How to round an image with Glide library?

Now in Glide V4 you can directly use CircleCrop()

Glide.with(fragment)
  .load(url)
  .circleCrop()
  .into(imageView);

Built in types

  • CenterCrop
  • FitCenter
  • CircleCrop

How to check object is nil or not in swift?

Swift 4 You cannot compare Any to nil.Because an optional can be nil and hence it always succeeds to true. The only way is to cast it to your desired object and compare it to nil.

if (someone as? String) != nil
{
   //your code`enter code here`
}

How to populate a sub-document in mongoose after creating it?

This might have changed since the original answer was written, but it looks like you can now use the Models populate function to do this without having to execute an extra findOne. See: http://mongoosejs.com/docs/api.html#model_Model.populate. You'd want to use this inside the save handler just like the findOne is.

How to display an activity indicator with text on iOS 8 with Swift?

import UIKit

class ViewControllerUtils {

    let containerView: UIView = {

        let view = UIView()
        view.translatesAutoresizingMaskIntoConstraints = false
        view.backgroundColor = UIColor(white: 0, alpha: 0.3)
        return view
    }()

    let loadingView: UIView = {

        let view = UIView()
        view.translatesAutoresizingMaskIntoConstraints = false
        view.backgroundColor = UIColor(white: 0, alpha: 0.7)
        view.clipsToBounds = true
        view.layer.cornerRadius = 10
        return view
    }()

    let activityIndicatorView: UIActivityIndicatorView = {

        let aiv = UIActivityIndicatorView()
        aiv.translatesAutoresizingMaskIntoConstraints = false
        aiv.style = UIActivityIndicatorView.Style.whiteLarge
        return aiv
    }()

    let loadingLabel: UILabel = {

        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.text = "Loading..."
        label.textAlignment = .center
        label.textColor = .white
        label.font = .systemFont(ofSize: 15, weight: UIFont.Weight.medium)
        return label
    }()

    func showLoader() {

        guard let window = UIApplication.shared.keyWindow else { return }

        window.addSubview(containerView)
        containerView.addSubview(loadingView)
        loadingView.addSubview(activityIndicatorView)
        loadingView.addSubview(loadingLabel)

        containerView.leftAnchor.constraint(equalTo: window.leftAnchor).isActive = true
        containerView.rightAnchor.constraint(equalTo: window.rightAnchor).isActive = true
        containerView.topAnchor.constraint(equalTo: window.topAnchor).isActive = true
        containerView.bottomAnchor.constraint(equalTo: window.bottomAnchor).isActive = true

        loadingView.centerXAnchor.constraint(equalTo: window.centerXAnchor).isActive = true
        loadingView.centerYAnchor.constraint(equalTo: window.centerYAnchor).isActive = true
        loadingView.widthAnchor.constraint(equalToConstant: 120).isActive = true
        loadingView.heightAnchor.constraint(equalToConstant: 120).isActive = true

        activityIndicatorView.centerXAnchor.constraint(equalTo: window.centerXAnchor).isActive = true
        activityIndicatorView.centerYAnchor.constraint(equalTo: window.centerYAnchor).isActive = true
        activityIndicatorView.widthAnchor.constraint(equalToConstant: 60).isActive = true
        activityIndicatorView.heightAnchor.constraint(equalToConstant: 60).isActive = true

        loadingLabel.leftAnchor.constraint(equalTo: loadingView.leftAnchor).isActive = true
        loadingLabel.rightAnchor.constraint(equalTo: loadingView.rightAnchor).isActive = true
        loadingLabel.bottomAnchor.constraint(equalTo: loadingView.bottomAnchor).isActive = true
        loadingLabel.heightAnchor.constraint(equalToConstant: 40).isActive = true

        DispatchQueue.main.async {

            self.activityIndicatorView.startAnimating()
        }
    }

    func hideLoader() {

        DispatchQueue.main.async {

            self.activityIndicatorView.stopAnimating()
            self.activityIndicatorView.removeFromSuperview()
            self.loadingLabel.removeFromSuperview()
            self.loadingView.removeFromSuperview()
            self.containerView.removeFromSuperview()
        }
    }
}

//// In order to show the activity indicator, call the function from your view controller
// let viewControllerUtils = ViewControllerUtils()
// viewControllerUtils.showLoader()

//// In order to hide the activity indicator, call the function from your view controller
// viewControllerUtils.hideLoader()

class ViewControllerUtils2 {

    var container: UIView = UIView()
    var loadingView: UIView = UIView()
    var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView()
    let loadingLabel = UILabel()

    func showLoader(_ uiView: UIView) {

        container.frame = uiView.frame
        container.center = uiView.center
        container.backgroundColor = UIColor(white: 0, alpha: 0.3)

        loadingView.frame = CGRect(x: 0, y: 0, width: 120, height: 120)
        loadingView.center = uiView.center
        loadingView.backgroundColor = UIColor(white: 0, alpha: 0.7)
        loadingView.clipsToBounds = true
        loadingView.layer.cornerRadius = 10

        activityIndicator.frame = CGRect(x: 0, y: 0, width: 60, height: 60)
        activityIndicator.style = UIActivityIndicatorView.Style.whiteLarge
        activityIndicator.center = CGPoint(x: loadingView.frame.size.width / 2, y: loadingView.frame.size.height / 2)

        loadingLabel.frame = CGRect(x: 0, y: 80, width: 120, height: 40)
        loadingLabel.text = "Loading..."
        loadingLabel.textAlignment = .center
        loadingLabel.textColor = .white
        loadingLabel.font = .systemFont(ofSize: 15, weight: UIFont.Weight.medium)

        uiView.addSubview(container)
        container.addSubview(loadingView)
        loadingView.addSubview(activityIndicator)
        loadingView.addSubview(loadingLabel)

        DispatchQueue.main.async {

            self.activityIndicator.startAnimating()
        }
    }

    func hideLoader() {

        DispatchQueue.main.async {

            self.activityIndicator.stopAnimating()
            self.activityIndicator.removeFromSuperview()
            self.loadingLabel.removeFromSuperview()
            self.loadingView.removeFromSuperview()
            self.container.removeFromSuperview()
        }
    }
}

Deleting multiple columns based on column names in Pandas

The below worked for me:

for col in df:
    if 'Unnamed' in col:
        #del df[col]
        print col
        try:
            df.drop(col, axis=1, inplace=True)
        except Exception:
            pass

Python object deleting itself

This is something I have done in the past. Create a list of objects, and you can then have objects delete themselves with the list.remove() method.

bullet_list = []

class Bullet:
    def kill_self(self):
        bullet_list.remove(self)

bullet_list += [Bullet()]

How to force Chrome browser to reload .css file while debugging in Visual Studio?

Why is it needed to refresh the whole page? Just refresh only css files without reloading the page. It is very helpful when, for example, you have to wait a long response from DB. Once you get data from DB and populate the page, then edit your css files and reload them in Chrome (or in Firefox). To do that you need to install CSS Reloader extension. Firefox version is also available.

Priority queue in .Net

AlgoKit

I wrote an open source library called AlgoKit, available via NuGet. It contains:

  • Implicit d-ary heaps (ArrayHeap),
  • Binomial heaps,
  • Pairing heaps.

The code has been extensively tested. I definitely recommend you to give it a try.

Example

var comparer = Comparer<int>.Default;
var heap = new PairingHeap<int, string>(comparer);

heap.Add(3, "your");
heap.Add(5, "of");
heap.Add(7, "disturbing.");
heap.Add(2, "find");
heap.Add(1, "I");
heap.Add(6, "faith");
heap.Add(4, "lack");

while (!heap.IsEmpty)
    Console.WriteLine(heap.Pop().Value);

Why those three heaps?

The optimal choice of implementation is strongly input-dependent — as Larkin, Sen, and Tarjan show in A back-to-basics empirical study of priority queues, arXiv:1403.0252v1 [cs.DS]. They tested implicit d-ary heaps, pairing heaps, Fibonacci heaps, binomial heaps, explicit d-ary heaps, rank-pairing heaps, quake heaps, violation heaps, rank-relaxed weak heaps, and strict Fibonacci heaps.

AlgoKit features three types of heaps that appeared to be most efficient among those tested.

Hint on choice

For a relatively small number of elements, you would likely be interested in using implicit heaps, especially quaternary heaps (implicit 4-ary). In case of operating on larger heap sizes, amortized structures like binomial heaps and pairing heaps should perform better.

How do I format a number in Java?

There are two approaches in the standard library. One is to use java.text.DecimalFormat. The other more cryptic methods (String.format, PrintStream.printf, etc) based around java.util.Formatter should keep C programmers happy(ish).

What Are Some Good .NET Profilers?

We selected YourKit Profiler for .NET in my company as it was the best value (price vs. feature). For a small company that wants to have flexible licensing (floating licenses) it was a perfect choice - ANTS was developer seat locket at the time.

Also, it provided us with the ability to attach to the running process which was not possible with dotTrace. Beware though that attaching is not the best option as everything .NET will slow down, but this was the only way to profile .NET applications started by other processes. Feature wise, ANTS and dotTrace were better - but in the end YourKit was good enough.

Use ssh from Windows command prompt

Cygwin can give you this functionality.

How to check if a column exists in a datatable

myDataTable.Columns.Contains("col_name")

Resize a picture to fit a JLabel

You can try it:

ImageIcon imageIcon = new ImageIcon(new ImageIcon("icon.png").getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT));
label.setIcon(imageIcon);

Or in one line:

label.setIcon(new ImageIcon(new ImageIcon("icon.png").getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT)));

The execution time is much more faster than File and ImageIO.

I recommend you to compare the two solutions in a loop.

Bootstrap 4: responsive sidebar menu to top navbar

Big screen:

navigation side bar in big screen size

Small screen (Mobile)

sidebar in small mobile size screen

if this is what you wanted this is code https://plnkr.co/edit/PCCJb9f7f93HT4OubLmM?p=preview

CSS + HTML + JQUERY :

_x000D_
_x000D_
    _x000D_
    @import "https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700";_x000D_
    body {_x000D_
      font-family: 'Poppins', sans-serif;_x000D_
      background: #fafafa;_x000D_
    }_x000D_
    _x000D_
    p {_x000D_
      font-family: 'Poppins', sans-serif;_x000D_
      font-size: 1.1em;_x000D_
      font-weight: 300;_x000D_
      line-height: 1.7em;_x000D_
      color: #999;_x000D_
    }_x000D_
    _x000D_
    a,_x000D_
    a:hover,_x000D_
    a:focus {_x000D_
      color: inherit;_x000D_
      text-decoration: none;_x000D_
      transition: all 0.3s;_x000D_
    }_x000D_
    _x000D_
    .navbar {_x000D_
      padding: 15px 10px;_x000D_
      background: #fff;_x000D_
      border: none;_x000D_
      border-radius: 0;_x000D_
      margin-bottom: 40px;_x000D_
      box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);_x000D_
    }_x000D_
    _x000D_
    .navbar-btn {_x000D_
      box-shadow: none;_x000D_
      outline: none !important;_x000D_
      border: none;_x000D_
    }_x000D_
    _x000D_
    .line {_x000D_
      width: 100%;_x000D_
      height: 1px;_x000D_
      border-bottom: 1px dashed #ddd;_x000D_
      margin: 40px 0;_x000D_
    }_x000D_
    /* ---------------------------------------------------_x000D_
    SIDEBAR STYLE_x000D_
----------------------------------------------------- */_x000D_
    _x000D_
    #sidebar {_x000D_
      width: 250px;_x000D_
      position: fixed;_x000D_
      top: 0;_x000D_
      left: 0;_x000D_
      height: 100vh;_x000D_
      z-index: 999;_x000D_
      background: #7386D5;_x000D_
      color: #fff !important;_x000D_
      transition: all 0.3s;_x000D_
    }_x000D_
    _x000D_
    #sidebar.active {_x000D_
      margin-left: -250px;_x000D_
    }_x000D_
    _x000D_
    #sidebar .sidebar-header {_x000D_
      padding: 20px;_x000D_
      background: #6d7fcc;_x000D_
    }_x000D_
    _x000D_
    #sidebar ul.components {_x000D_
      padding: 20px 0;_x000D_
      border-bottom: 1px solid #47748b;_x000D_
    }_x000D_
    _x000D_
    #sidebar ul p {_x000D_
      color: #fff;_x000D_
      padding: 10px;_x000D_
    }_x000D_
    _x000D_
    #sidebar ul li a {_x000D_
      padding: 10px;_x000D_
      font-size: 1.1em;_x000D_
      display: block;_x000D_
      color:white;_x000D_
    }_x000D_
    _x000D_
    #sidebar ul li a:hover {_x000D_
      color: #7386D5;_x000D_
      background: #fff;_x000D_
    }_x000D_
    _x000D_
    #sidebar ul li.active>a,_x000D_
    a[aria-expanded="true"] {_x000D_
      color: #fff;_x000D_
      background: #6d7fcc;_x000D_
    }_x000D_
    _x000D_
    a[data-toggle="collapse"] {_x000D_
      position: relative;_x000D_
    }_x000D_
    _x000D_
    a[aria-expanded="false"]::before,_x000D_
    a[aria-expanded="true"]::before {_x000D_
      content: '\e259';_x000D_
      display: block;_x000D_
      position: absolute;_x000D_
      right: 20px;_x000D_
      font-family: 'Glyphicons Halflings';_x000D_
      font-size: 0.6em;_x000D_
    }_x000D_
    _x000D_
    a[aria-expanded="true"]::before {_x000D_
      content: '\e260';_x000D_
    }_x000D_
    _x000D_
    ul ul a {_x000D_
      font-size: 0.9em !important;_x000D_
      padding-left: 30px !important;_x000D_
      background: #6d7fcc;_x000D_
    }_x000D_
    _x000D_
    ul.CTAs {_x000D_
      padding: 20px;_x000D_
    }_x000D_
    _x000D_
    ul.CTAs a {_x000D_
      text-align: center;_x000D_
      font-size: 0.9em !important;_x000D_
      display: block;_x000D_
      border-radius: 5px;_x000D_
      margin-bottom: 5px;_x000D_
    }_x000D_
    _x000D_
    a.download {_x000D_
      background: #fff;_x000D_
      color: #7386D5;_x000D_
    }_x000D_
    _x000D_
    a.article,_x000D_
    a.article:hover {_x000D_
      background: #6d7fcc !important;_x000D_
      color: #fff !important;_x000D_
    }_x000D_
    /* ---------------------------------------------------_x000D_
    CONTENT STYLE_x000D_
----------------------------------------------------- */_x000D_
    _x000D_
    #content {_x000D_
      width: calc(100% - 250px);_x000D_
      padding: 40px;_x000D_
      min-height: 100vh;_x000D_
      transition: all 0.3s;_x000D_
      position: absolute;_x000D_
      top: 0;_x000D_
      right: 0;_x000D_
    }_x000D_
    _x000D_
    #content.active {_x000D_
      width: 100%;_x000D_
    }_x000D_
    /* ---------------------------------------------------_x000D_
    MEDIAQUERIES_x000D_
----------------------------------------------------- */_x000D_
    _x000D_
    @media (max-width: 768px) {_x000D_
      #sidebar {_x000D_
        margin-left: -250px;_x000D_
      }_x000D_
      #sidebar.active {_x000D_
        margin-left: 0;_x000D_
      }_x000D_
      #content {_x000D_
        width: 100%;_x000D_
      }_x000D_
      #content.active {_x000D_
        width: calc(100% - 250px);_x000D_
      }_x000D_
      #sidebarCollapse span {_x000D_
        display: none;_x000D_
      }_x000D_
    }
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
  <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
_x000D_
  <title>Collapsible sidebar using Bootstrap 3</title>_x000D_
_x000D_
  <!-- Bootstrap CSS CDN -->_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <!-- Our Custom CSS -->_x000D_
  <link rel="stylesheet" href="style2.css">_x000D_
  <!-- Scrollbar Custom CSS -->_x000D_
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.min.css">_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
_x000D_
_x000D_
  <div class="wrapper">_x000D_
    <!-- Sidebar Holder -->_x000D_
    <nav id="sidebar">_x000D_
      <div class="sidebar-header">_x000D_
        <h3>Header as you want </h3>_x000D_
        </h3>_x000D_
      </div>_x000D_
_x000D_
      <ul class="list-unstyled components">_x000D_
        <p>Dummy Heading</p>_x000D_
        <li class="active">_x000D_
          <a href="#menu">Animación</a>_x000D_
_x000D_
        </li>_x000D_
        <li>_x000D_
          <a href="#menu">Ilustración</a>_x000D_
_x000D_
_x000D_
        </li>_x000D_
        <li>_x000D_
          <a href="#menu">Interacción</a>_x000D_
        </li>_x000D_
        <li>_x000D_
          <a href="#">Blog</a>_x000D_
        </li>_x000D_
        <li>_x000D_
          <a href="#">Acerca</a>_x000D_
        </li>_x000D_
        <li>_x000D_
          <a href="#">contacto</a>_x000D_
        </li>_x000D_
_x000D_
_x000D_
      </ul>_x000D_
_x000D_
_x000D_
    </nav>_x000D_
_x000D_
    <!-- Page Content Holder -->_x000D_
    <div id="content">_x000D_
_x000D_
      <nav class="navbar navbar-default">_x000D_
        <div class="container-fluid">_x000D_
_x000D_
          <div class="navbar-header">_x000D_
            <button type="button" id="sidebarCollapse" class="btn btn-info navbar-btn">_x000D_
                                <i class="glyphicon glyphicon-align-left"></i>_x000D_
                                <span>Toggle Sidebar</span>_x000D_
                            </button>_x000D_
          </div>_x000D_
_x000D_
          <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
            <ul class="nav navbar-nav navbar-right">_x000D_
              <li><a href="#">Page</a></li>_x000D_
            </ul>_x000D_
          </div>_x000D_
        </div>_x000D_
      </nav>_x000D_
_x000D_
_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
  <!-- jQuery CDN -->_x000D_
  <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>_x000D_
  <!-- Bootstrap Js CDN -->_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
  <!-- jQuery Custom Scroller CDN -->_x000D_
  <script src="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.concat.min.js"></script>_x000D_
_x000D_
  <script type="text/javascript">_x000D_
    $(document).ready(function() {_x000D_
_x000D_
_x000D_
      $('#sidebarCollapse').on('click', function() {_x000D_
        $('#sidebar, #content').toggleClass('active');_x000D_
        $('.collapse.in').toggleClass('in');_x000D_
        $('a[aria-expanded=true]').attr('aria-expanded', 'false');_x000D_
      });_x000D_
    });_x000D_
  </script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

if this is what you want .

How to declare global variables in Android?

Like there was discussed above OS could kill the APPLICATION without any notification (there is no onDestroy event) so there is no way to save these global variables.

SharedPreferences could be a solution EXCEPT you have COMPLEX STRUCTURED variables (in my case I had integer array to store the IDs that the user has already handled). The problem with the SharedPreferences is that it is hard to store and retrieve these structures each time the values needed.

In my case I had a background SERVICE so I could move this variables to there and because the service has onDestroy event, I could save those values easily.

How to add a touch event to a UIView?

In Swift 4.2 and Xcode 10

Use UITapGestureRecognizer for to add touch event

//Add tap gesture to your view
let tap = UITapGestureRecognizer(target: self, action: #selector(handleGesture))
yourView.addGestureRecognizer(tap)

// GestureRecognizer
@objc func handleGesture(gesture: UITapGestureRecognizer) -> Void {
//Write your code here
}

If you want to use SharedClass

//This is my shared class
import UIKit

class SharedClass: NSObject {

    static let sharedInstance = SharedClass()

    //Tap gesture function
    func addTapGesture(view: UIView, target: Any, action: Selector) {
        let tap = UITapGestureRecognizer(target: target, action: action)
        view.addGestureRecognizer(tap)
    }
} 

I have 3 views in my ViewController called view1, view2 and view3.

override func viewDidLoad() {
    super.viewDidLoad()
    //Add gestures to your views
    SharedClass.sharedInstance.addTapGesture(view: view1, target: self, action: #selector(handleGesture))
    SharedClass.sharedInstance.addTapGesture(view: view2, target: self, action: #selector(handleGesture))
    SharedClass.sharedInstance.addTapGesture(view: view3, target: self, action: #selector(handleGesture2))

}

// GestureRecognizer
@objc func handleGesture(gesture: UITapGestureRecognizer) -> Void {
    print("printed 1&2...")
}
// GestureRecognizer
@objc func handleGesture2(gesture: UITapGestureRecognizer) -> Void {
    print("printed3...")
}

What's the opposite of 'make install', i.e. how do you uninstall a library in Linux?

If sudo make uninstall is unavailable:

In a Debian based system, instead of (or after*) doing make install you can run sudo checkinstall to make a .deb file that gets automatically installed. You can then remove it using the system package manager (e.g. apt/synaptic/aptitude/dpkg). Checkinstall also supports creating other types of package, e.g. RPM.

See also http://community.linuxmint.com/tutorial/view/162 and some basic checkinstall usage and debian checkinstall package.


*: If you're reading this after having installed with make install you can still follow the above instructions and do a dpkg -r $PACKAGE_NAME_YOU_CHOSEN afterwards.

How to force open links in Chrome not download them?

Google, as of now, cannot open w/out saving. As a workaround, I use IE Tab from the Chrome Store. It is an extension that runs IE - which does allow opening w/ out saving- inside of the Chrome browser application.

Not the best solution, but it's an effective "patch" for now.

How do I install a JRE or JDK to run the Android Developer Tools on Windows 7?

The most likely reason why the Java Runtime Environment JRE or Java Development Kit JDK is that it's owned by Oracle not Google and they would need a redistribution agreement which if you know there is some history between the two companies.

Lucky for us that Sun Microsystems before it was bought by Oracle open sourced Java and MySQL a win for us little guys.... Thank you Sun!

Google should probably have a caveat saying you may also need JRE OR JDK

INSTALL_FAILED_UPDATE_INCOMPATIBLE when I try to install compiled .apk on device

If your Manifest file has this line -

android:sharedUserId="android.uid.system"

is causing this error! just comment this line and you are good to go!!

regex with space and letters only?

Allowed only characters & spaces. Ex : Jayant Lonari

if (!/^[a-zA-Z\s]+$/.test(NAME)) {
    //Throw Error
}

Switch case in C# - a constant value is expected

switch is very picky in the sense that the values in the switch must be a compile time constant. and also the value that's being compared must be a primitive (or string now). For this you should use an if statement.

The reason may go back to the way that C handles them in that it creates a jump table (because the values are compile time constants) and it tries to copy the same semantics by not allowing evaluated values in your cases.

Underscore prefix for property and method names in JavaScript

import/export is now doing the job with ES6. I still tend to prefix not exported functions with _ if most of my functions are exported.

If you export only a class (like in angular projects), it's not needed at all.

export class MyOpenClass{

    open(){
         doStuff()
         this._privateStuff()
         return close();
    }

    _privateStuff() { /* _ only as a convention */} 

}

function close(){ /*... this is really private... */ }

Emulate/Simulate iOS in Linux

You might want to try screenfly. It worked great for me.

java.lang.ClassNotFoundException: org.apache.log4j.Level

You also need to include the Log4J JAR file in the classpath.

Note that slf4j-log4j12-1.6.4.jar is only an adapter to make it possible to use Log4J via the SLF4J API. It does not contain the actual implementation of Log4J.

What does ${} (dollar sign and curly braces) mean in a string in Javascript?

You're talking about template literals.

They allow for both multiline strings and string interpolation.

Multiline strings:

_x000D_
_x000D_
console.log(`foo_x000D_
bar`);_x000D_
// foo_x000D_
// bar
_x000D_
_x000D_
_x000D_

String interpolation:

_x000D_
_x000D_
var foo = 'bar';_x000D_
console.log(`Let's meet at the ${foo}`);_x000D_
// Let's meet at the bar
_x000D_
_x000D_
_x000D_

"405 method not allowed" in IIS7.5 for "PUT" method

This is my solution, alhamdulillah it worked.

  1. Open Notepad as Administrator.
  2. Open this file %windir%\system32\inetsrv\config\applicationhost.config
  3. Press Ctrl-F to find word "handlers accessPolicy"
  4. Add word "DELETE" after word "GET,HEAD,POST".
  5. The sentence will become <add name="PHP_via_FastCGI" path="*.php" verb="GET,HEAD,POST,DELETE"
  6. The word "PHP_via_FastCGI" can have alternate word such as "PHP_via_FastCGI1" or "PHP_via_FastCGI2".
  7. Save file.

Reference: https://docs.microsoft.com/en-US/troubleshoot/iis/http-error-405-website

ExpressJS How to structure an application?

UPDATE (2013-10-29): Please see my other answer as well which has JavaScript instead of CoffeeScript by popular demand as well as a boilerplate github repo and an extensive README detailing my latest recommendations on this topic.

Config

What you are doing is fine. I like to have my own config namespace set up in a top-level config.coffee file with a nested namespace like this.

#Set the current environment to true in the env object
currentEnv = process.env.NODE_ENV or 'development'
exports.appName = "MyApp"
exports.env =
  production: false
  staging: false
  test: false
  development: false
exports.env[currentEnv] = true
exports.log =
  path: __dirname + "/var/log/app_#{currentEnv}.log"
exports.server =
  port: 9600
  #In staging and production, listen loopback. nginx listens on the network.
  ip: '127.0.0.1'
if currentEnv not in ['production', 'staging']
  exports.enableTests = true
  #Listen on all IPs in dev/test (for testing from other machines)
  exports.server.ip = '0.0.0.0'
exports.db =
  URL: "mongodb://localhost:27017/#{exports.appName.toLowerCase()}_#{currentEnv}"

This is friendly for sysadmin editing. Then when I need something, like the DB connection info, it`s

require('./config').db.URL

Routes/Controllers

I like to leave my routes with my controllers and organize them in an app/controllers subdirectory. Then I can load them up and let them add whatever routes they need.

In my app/server.coffee coffeescript file I do:

[
  'api'
  'authorization'
  'authentication'
  'domains'
  'users'
  'stylesheets'
  'javascripts'
  'tests'
  'sales'
].map (controllerName) ->
  controller = require './controllers/' + controllerName
  controller.setup app

So I have files like:

app/controllers/api.coffee
app/controllers/authorization.coffee
app/controllers/authentication.coffee
app/controllers/domains.coffee

And for example in my domains controller, I have a setup function like this.

exports.setup = (app) ->
  controller = new exports.DomainController
  route = '/domains'
  app.post route, controller.create
  app.put route, api.needId
  app.delete route, api.needId
  route = '/domains/:id'
  app.put route, controller.loadDomain, controller.update
  app.del route, controller.loadDomain, exports.delete
  app.get route, controller.loadDomain, (req, res) ->
    res.sendJSON req.domain, status.OK

Views

Putting views in app/views is becoming the customary place. I lay it out like this.

app/views/layout.jade
app/views/about.jade
app/views/user/EditUser.jade
app/views/domain/EditDomain.jade

Static Files

Go in a public subdirectory.

Github/Semver/NPM

Put a README.md markdown file at your git repo root for github.

Put a package.json file with a semantic version number in your git repo root for NPM.

css transform, jagged edges in chrome

For canvas in Chrome (Version 52)

All listed answers is about images. But my issue is about canvas in chrome (v.52) with transform rotate. They became jagged and all this methods can't help.

Solution that works for me:

  1. Make canvas larger on 1 px for each side => +2 px for width and height;
  2. Draw image with offset + 1px (in position 1,1 instead of 0,0) and fixed size (size of image should be 2px less than size of canvas)
  3. Apply required rotation

So important code blocks:

_x000D_
_x000D_
// Unfixed version
ctx.drawImage(img, 0, 0, 335, 218);
// Fixed version
ctx.drawImage(img, 1, 1, 335, 218);
_x000D_
/* This style should be applied for fixed version */
canvas {
  margin-left: -1px;
  margin-top:-1px;
}        
_x000D_
<!--Unfixed version-->
<canvas width="335" height="218"></canvas>
<!--Fixed version-->
<canvas width="337" height="220"></canvas>
_x000D_
_x000D_
_x000D_

Sample: https://jsfiddle.net/tLbxgusx/1/

Note: there is a lot of nested divs because it is simplified version from my project.


This issue is reproduced also for Firefox for me. There is no such issue on Safari and FF with retina.

And other founded solution is to place canvas into div of same size and apply following css to this div:

overflow: hidden;
box-shadow: 0 0 1px rgba(255,255,255,0);
// Or
//outline:1px solid transparent;

And rotation should be applied to this wrapping div. So listed solution is worked but with small modification.

And modified example for such solution is: https://jsfiddle.net/tLbxgusx/2/

Note: See style of div with class 'third'.

Center/Set Zoom of Map to cover all visible Markers?

There is this MarkerClusterer client side utility available for google Map as specified here on Google Map developer Articles, here is brief on what's it's usage:

There are many approaches for doing what you asked for:

  • Grid based clustering
  • Distance based clustering
  • Viewport Marker Management
  • Fusion Tables
  • Marker Clusterer
  • MarkerManager

You can read about them on the provided link above.

Marker Clusterer uses Grid Based Clustering to cluster all the marker wishing the grid. Grid-based clustering works by dividing the map into squares of a certain size (the size changes at each zoom) and then grouping the markers into each grid square.

Before Clustering Before Clustering

After Clustering After Clustering

I hope this is what you were looking for & this will solve your problem :)

Get first and last date of current month with JavaScript or jQuery

I fixed it with Datejs

This is alerting the first day:

var fd = Date.today().clearTime().moveToFirstDayOfMonth();
var firstday = fd.toString("MM/dd/yyyy");
alert(firstday);

This is for the last day:

var ld = Date.today().clearTime().moveToLastDayOfMonth();
var lastday = ld.toString("MM/dd/yyyy");
alert(lastday);

How to use MySQL dump from a remote machine

Have you got access to SSH?

You can use this command in shell to backup an entire database:

mysqldump -u [username] -p[password] [databasename] > [filename.sql]

This is actually one command followed by the > operator, which says, "take the output of the previous command and store it in this file."

Note: The lack of a space between -p and the mysql password is not a typo. However, if you leave the -p flag present, but the actual password blank then you will be prompted for your password. Sometimes this is recommended to keep passwords out of your bash history.

Android Button setOnClickListener Design

If you're targeting 1.6 or later, you can use the android:onClick xml attribute to remove some of the repetitive code. See this blog post by Romain Guy.

<Button 
   android:height="wrap_content"
   android:width="wrap_content"
   android:onClick="myClickHandler" />

And in the Java class, use these below lines of code:

class MyActivity extends Activity {
    public void myClickHandler(View target) {
        // Do stuff
    }
}

moment.js 24h format

Stating your time as HH will give you 24h format, and hh will give 12h format.

You can also find it here in the documentation :

    H, HH       24 hour time
    h, or hh    12 hour time (use in conjunction with a or A)

Twitter bootstrap float div right

bootstrap 3 has a class to align the text within a div

<div class="text-right">

will align the text on the right

<div class="pull-right">

will pull to the right all the content not only the text

Get user location by IP address

    public static string GetLocationIPAPI(string ipaddress)
    {
        try
        {
            IPDataIPAPI ipInfo = new IPDataIPAPI();
            string strResponse = new WebClient().DownloadString("http://ip-api.com/json/" + ipaddress);
            if (strResponse == null || strResponse == "") return "";
            ipInfo = JsonConvert.DeserializeObject<IPDataIPAPI>(strResponse);
            if (ipInfo == null || ipInfo.status.ToLower().Trim() == "fail") return "";
            else return ipInfo.city + "; " + ipInfo.regionName + "; " + ipInfo.country + "; " + ipInfo.countryCode;
        }
        catch (Exception)
        {
            return "";
        }
    }

public class IPDataIPINFO
{
    public string ip { get; set; }
    public string city { get; set; }
    public string region { get; set; }
    public string country { get; set; }
    public string loc { get; set; }
    public string postal { get; set; }
    public int org { get; set; }

}

==========================

    public static string GetLocationIPINFO(string ipaddress)
    {            
        try
        {
            IPDataIPINFO ipInfo = new IPDataIPINFO();
            string strResponse = new WebClient().DownloadString("http://ipinfo.io/" + ipaddress);
            if (strResponse == null || strResponse == "") return "";
            ipInfo = JsonConvert.DeserializeObject<IPDataIPINFO>(strResponse);
            if (ipInfo == null || ipInfo.ip == null || ipInfo.ip == "") return "";
            else return ipInfo.city + "; " + ipInfo.region + "; " + ipInfo.country + "; " + ipInfo.postal;
        }
        catch (Exception)
        {
            return "";
        }
    }

public class IPDataIPAPI
{
    public string status { get; set; }
    public string country { get; set; }
    public string countryCode { get; set; }
    public string region { get; set; }
    public string regionName { get; set; }
    public string city { get; set; }
    public string zip { get; set; }
    public string lat { get; set; }
    public string lon { get; set; }
    public string timezone { get; set; }
    public string isp { get; set; }
    public string org { get; set; }
    public string @as { get; set; }
    public string query { get; set; }
}

==============================

    private static string GetLocationIPSTACK(string ipaddress)
    {
        try
        {
            IPDataIPSTACK ipInfo = new IPDataIPSTACK();
            string strResponse = new WebClient().DownloadString("http://api.ipstack.com/" + ipaddress + "?access_key=XX384X1XX028XX1X66XXX4X04XXXX98X");
            if (strResponse == null || strResponse == "") return "";
            ipInfo = JsonConvert.DeserializeObject<IPDataIPSTACK>(strResponse);
            if (ipInfo == null || ipInfo.ip == null || ipInfo.ip == "") return "";
            else return ipInfo.city + "; " + ipInfo.region_name + "; " + ipInfo.country_name + "; " + ipInfo.zip;
        }
        catch (Exception)
        {
            return "";
        }
    }

public class IPDataIPSTACK
{
    public string ip { get; set; }
    public int city { get; set; }
    public string region_code { get; set; }
    public string region_name { get; set; }
    public string country_code { get; set; }
    public string country_name { get; set; }
    public string zip { get; set; }


}

Sort objects in an array alphabetically on one property of the array

DEMO

var DepartmentFactory = function(data) {
    this.id = data.Id;
    this.name = data.DepartmentName;
    this.active = data.Active;
}

var objArray = [];
objArray.push(new DepartmentFactory({Id: 1, DepartmentName: 'Marketing', Active: true}));
objArray.push(new DepartmentFactory({Id: 2, DepartmentName: 'Sales', Active: true}));
objArray.push(new DepartmentFactory({Id: 3, DepartmentName: 'Development', Active: true}));
objArray.push(new DepartmentFactory({Id: 4, DepartmentName: 'Accounting', Active: true}));

console.log(objArray.sort(function(a, b) { return a.name > b.name}));

Using LINQ to find item in a List but get "Value cannot be null. Parameter name: source"

I think you can get this error if your database model is not correct and the underlying data contains a null which the model is attempting to map to a non-null object.

For example, some auto-generated models can attempt to map nvarchar(1) columns to char rather than string and hence if this column contains nulls it will throw an error when you attempt to access the data.

Note, LinqPad has a compatibility option if you want it to generate a model like that, but probably doesn't do this by default, which might explain it doesn't give you the error.

Mismatched anonymous define() module

I had this error because I included the requirejs file along with other librairies included directly in a script tag. Those librairies (like lodash) used a define function that was conflicting with require's define. The requirejs file was loading asynchronously so I suspect that the require's define was defined after the other libraries define, hence the conflict.

To get rid of the error, include all your other js files by using requirejs.

Mailto links do nothing in Chrome but work in Firefox?

I solved the problem using this code:

_x000D_
_x000D_
    _x000D_
<button onclick="email()">Contact me !</button> _x000D_
_x000D_
<script>_x000D_
function email() {_x000D_
    var str = window.open('mailto:[email protected]', '_blank');_x000D_
}_x000D_
</script>
_x000D_
_x000D_
_x000D_

It worked for me like a charm !

2 ways for "ClearContents" on VBA Excel, but 1 work fine. Why?

It is because you haven't qualified Cells(1, 1) with a worksheet object, and the same holds true for Cells(10, 2). For the code to work, it should look something like this:

Dim ws As Worksheet

Set ws = Sheets("SheetName")
Range(ws.Cells(1, 1), ws.Cells(10, 2)).ClearContents

Alternately:

With Sheets("SheetName")
    Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With

EDIT: The Range object will inherit the worksheet from the Cells objects when the code is run from a standard module or userform. If you are running the code from a worksheet code module, you will need to qualify Range also, like so:

ws.Range(ws.Cells(1, 1), ws.Cells(10, 2)).ClearContents

or

With Sheets("SheetName")
    .Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With

An unhandled exception was generated during the execution of the current web request

You have more than one form tags with runat="server" on your template, most probably you have one in your master page, remove one on your aspx page, it is not needed if already have form in master page file which is surrounding your content place holders.

Try to remove that tag:

<form id="formID" runat="server">

and of course closing tag:

</form>

How to remove all CSS classes using jQuery/JavaScript?

Just set the className attribute of the real DOM element to '' (nothing).

$('#item')[0].className = ''; // the real DOM element is at [0]

Edit: Other people have said that just calling removeClass works - I tested this with the Google JQuery Playground: http://savedbythegoog.appspot.com/?id=ag5zYXZlZGJ5dGhlZ29vZ3ISCxIJU2F2ZWRDb2RlGIS61gEM ... and it works. So you can also do it this way:

$("#item").removeClass();

Regex Until But Not Including

The explicit way of saying "search until X but not including X" is:

(?:(?!X).)*

where X can be any regular expression.

In your case, though, this might be overkill - here the easiest way would be

[^z]*

This will match anything except z and therefore stop right before the next z.

So .*?quick[^z]* will match The quick fox jumps over the la.

However, as soon as you have more than one simple letter to look out for, (?:(?!X).)* comes into play, for example

(?:(?!lazy).)* - match anything until the start of the word lazy.

This is using a lookahead assertion, more specifically a negative lookahead.

.*?quick(?:(?!lazy).)* will match The quick fox jumps over the.

Explanation:

(?:        # Match the following but do not capture it:
 (?!lazy)  # (first assert that it's not possible to match "lazy" here
 .         # then match any character
)*         # end of group, zero or more repetitions.

Furthermore, when searching for keywords, you might want to surround them with word boundary anchors: \bfox\b will only match the complete word fox but not the fox in foxy.

Note

If the text to be matched can also include linebreaks, you will need to set the "dot matches all" option of your regex engine. Usually, you can achieve that by prepending (?s) to the regex, but that doesn't work in all regex engines (notably JavaScript).

Alternative solution:

In many cases, you can also use a simpler, more readable solution that uses a lazy quantifier. By adding a ? to the * quantifier, it will try to match as few characters as possible from the current position:

.*?(?=(?:X)|$)

will match any number of characters, stopping right before X (which can be any regex) or the end of the string (if X doesn't match). You may also need to set the "dot matches all" option for this to work. (Note: I added a non-capturing group around X in order to reliably isolate it from the alternation)

How to pass 2D array (matrix) in a function in C?

Easiest Way in Passing A Variable-Length 2D Array

Most clean technique for both C & C++ is: pass 2D array like a 1D array, then use as 2D inside the function.

#include <stdio.h>

void func(int row, int col, int* matrix){
    int i, j;
    for(i=0; i<row; i++){
        for(j=0; j<col; j++){
            printf("%d ", *(matrix + i*col + j)); // or better: printf("%d ", *matrix++);
        }
        printf("\n");
    }
}

int main(){
    int matrix[2][3] = { {0, 1, 2}, {3, 4, 5} };
    func(2, 3, matrix[0]);

    return 0;
}

Internally, no matter how many dimensions an array has, C/C++ always maintains a 1D array. And so, we can pass any multi-dimensional array like this.

Logical operators ("and", "or") in DOS batch

De Morgan's laws allow us to convert disjunctions ("OR") into logical equivalents using only conjunctions ("AND") and negations ("NOT"). This means we can chain disjunctions ("OR") on to one line.

This means if name is "Yakko" or "Wakko" or "Dot", then echo "Warner brother or sister".

set warner=true
if not "%name%"=="Yakko" if not "%name%"=="Wakko" if not "%name%"=="Dot" set warner=false
if "%warner%"=="true" echo Warner brother or sister

This is another version of paxdiablo's "OR" example, but the conditions are chained on to one line. (Note that the opposite of leq is gtr, and the opposite of geq is lss.)

set res=true
if %hour% gtr 6 if %hour% lss 22 set res=false
if "%res%"=="true" set state=asleep

Android Webview - Completely Clear the Cache

To clear cookie and cache from Webview,

    // Clear all the Application Cache, Web SQL Database and the HTML5 Web Storage
    WebStorage.getInstance().deleteAllData();

    // Clear all the cookies
    CookieManager.getInstance().removeAllCookies(null);
    CookieManager.getInstance().flush();

    webView.clearCache(true);
    webView.clearFormData();
    webView.clearHistory();
    webView.clearSslPreferences();

How can I fill a column with random numbers in SQL? I get the same value in every row

Instead of rand(), use newid(), which is recalculated for each row in the result. The usual way is to use the modulo of the checksum. Note that checksum(newid()) can produce -2,147,483,648 and cause integer overflow on abs(), so we need to use modulo on the checksum return value before converting it to absolute value.

UPDATE CattleProds
SET    SheepTherapy = abs(checksum(NewId()) % 10000)
WHERE  SheepTherapy IS NULL

This generates a random number between 0 and 9999.

Expand a random range from 1–5 to 1–7

Another answer which appears to have not been covered here:

int rand7() {
  int r = 7 / 2;
  for (int i = 0; i < 28; i++)
    r = ((rand5() - 1) * 7 + r) / 5;
  return r + 1;
}

On every iteration r is a random value between 0 and 6 inclusive. This is appended (base 7) to a random value between 0 and 4 inclusive, and the result is divided by 5, giving a new random value in the range of 0 to 6 inclusive. r starts with a substantial bias (r = 3 is very biased!) but each iteration divides that bias by 5.

This method is not perfectly uniform; however, the bias is vanishingly small. Something in the order of 1/(2**64). What's important about this approach is that it has constant execution time (assuming rand5() also has constant execution time). No theoretical concerns that an unlucky call could iterate forever picking bad values.


Also, a sarcastic answer for good measure (deliberately or not, it has been covered):

1-5 is already within the range 1-7, therefore the following is a valid implementation:

int rand7() {
  return rand5();
}

Question did not ask for uniform distribution.

SQL SELECT everything after a certain character

Try this (it should work if there are multiple '=' characters in the string):

SELECT RIGHT(supplier_reference, (CHARINDEX('=',REVERSE(supplier_reference),0))-1) FROM ps_product

Reload parent window from child window

You can reload parent window location using :

window.opener.location.href = window.opener.location.href;

CSS Circle with border

Try this:

.circle {
    height: 20px;
    width: 20px;
    padding: 5px;
    text-align: center; 
    border-radius: 50%;
    display: inline-block;
    color:#fff;
    font-size:1.1em;
    font-weight:600;
    background-color: rgba(0,0,0,0.1);
    border: 1px solid rgba(0,0,0,0.2);
}

A method to reverse effect of java String.split()?

Google also provides a joiner class in their Google Collections library:

Joiner API

Google Collections

Twitter Bootstrap Datepicker within modal window

As mccannf said in his comment:

I recommend you look at your bootstrap CSS and JS. Your modal is being set at a very high z-index value (99999). Just compare my jsfiddle above with yours

Re-assign host access permission to MySQL user

I received the same error with RENAME USER and GRANTS aren't covered by the currently accepted solution:

The most reliable way seems to be to run SHOW GRANTS for the old user, find/replace what you want to change regarding the user's name and/or host and run them and then finally DROP USER the old user. Not forgetting to run FLUSH PRIVILEGES (best to run this after adding the new users' grants, test the new user, then drop the old user and flush again for good measure).

    > SHOW GRANTS FOR 'olduser'@'oldhost';
    +-----------------------------------------------------------------------------------+
    | Grants for olduser@oldhost                                                        |
    +-----------------------------------------------------------------------------------+
    | GRANT USAGE ON *.* TO 'olduser'@'oldhost' IDENTIFIED BY PASSWORD '*PASSHASH'      |
    | GRANT SELECT ON `db`.* TO 'olduser'@'oldhost'                                     |
    +-----------------------------------------------------------------------------------+
    2 rows in set (0.000 sec)

    > GRANT USAGE ON *.* TO 'newuser'@'newhost' IDENTIFIED BY PASSWORD '*SAME_PASSHASH';
    Query OK, 0 rows affected (0.006 sec)

    > GRANT SELECT ON `db`.* TO 'newuser'@'newhost';
    Query OK, 0 rows affected (0.007 sec)

    > DROP USER 'olduser'@'oldhost';
    Query OK, 0 rows affected (0.016 sec)

Change date format in a Java string

[edited to include BalusC's corrections] The SimpleDateFormat class should do the trick:

String pattern = "yyyy-MM-dd HH:mm:ss.S";
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
  Date date = format.parse("2011-01-18 00:00:00.0");
  System.out.println(date);
} catch (ParseException e) {
  e.printStackTrace();
}

String comparison using '==' vs. 'strcmp()'

if ($password === $password2) { ... } is not a safe thing to do when comparing passwords or password hashes where one of the inputs is user controlled.
In that case it creates a timing oracle allowing an attacker to derive the actual password hash from execution time differences.
Use if (hash_equals($password, $password2)) { ... } instead, because hash_equals performs "timing attack safe string comparison".

Android Get Current timestamp?

You can use the SimpleDateFormat class:

SimpleDateFormat s = new SimpleDateFormat("ddMMyyyyhhmmss");
String format = s.format(new Date());

replace anchor text with jquery

To reference an element by id, you need to use the # qualifier.

Try:

alert($("#link1").text());

To replace it, you could use:

$("#link1").text('New text');

The .html() function would work in this case too.

AngularJs $http.post() does not send data

Just proposing a modernized version of @FelipeMiosso's answer:

.config(["$httpProvider", function ($httpProvider) {

  function buildKey(parentKey, subKey) {
    return parentKey + "[" + subKey + "]";
  }

  function buildObject(key, value) {
    var object = {};
    object[key] = value;
    return object;
  }

  function join(array) {
    return array.filter(function (entry) {
      return entry;
    }).join("&");
  }

  function arrayToQueryString(parentKey, array) {
    return join(array.map(function (value, subKey) {
      return toQueryString(buildObject(buildKey(parentKey, subKey), value));
    }));
  }

  function objectToQueryString(parentKey, object) {
    return join(Object.keys(object).map(function (subKey) {
      return toQueryString(buildObject(buildKey(parentKey, subKey), object[subKey]));
    }));
  }

  function toQueryString(input) {
    return join(Object.keys(input).map(function (key) {
      var value = input[key];
      if (value instanceof Array) {
        return arrayToQueryString(key, value);
      } else if (value instanceof Object) {
        return objectToQueryString(key, value);
      } else if (undefined !== value && null !== value) {
        return encodeURIComponent(key) + "=" + encodeURIComponent(value);
      } else {
        return "";
      }
    }));
  }

  function isQueryStringEligible(input) {
    return null !== input && "object" === typeof input && "[object File]" !== String(input);
  }

  var interceptor = [function () {
    return {
      request: function (config) {
        if (0 <= ["post", "put", "patch"].indexOf(config.method.toLowerCase()) && isQueryStringEligible(config.data)) {
          config.headers["Content-Type"] = "application/x-www-form-urlencoded;charset=utf-8";
          config.data = toQueryString(config.data);
        }
        return config;
      }
    };
  }];

  $httpProvider.interceptors.push(interceptor);

}])

ES6 version:

.config(["$httpProvider", function ($httpProvider) {

  "use strict";

  const buildKey = (parentKey, subKey) => `${parentKey}[${subKey}]`;

  const buildObject = (key, value) => ({ [key]: value });

  const join = (array) => array.filter((entry) => entry).join("&");

  const arrayToQueryString = (parentKey, array) =>
    join(array.map((value, subKey) =>
      toQueryString(buildObject(buildKey(parentKey, subKey), value))));

  const objectToQueryString = (parentKey, object) =>
    join(Object.keys(object).map((subKey) =>
      toQueryString(buildObject(buildKey(parentKey, subKey), object[subKey]))));

  const toQueryString = (input) => join(Object.keys(input).map((key) => {
    const value = input[key];
    if (value instanceof Array) {
      return arrayToQueryString(key, value);
    } else if (value instanceof Object) {
      return objectToQueryString(key, value);
    } else if (undefined !== value && null !== value) {
      return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
    } else {
      return "";
    }
  }));

  const isQueryStringEligible = (input) =>
    null !== input && "object" === typeof input && "[object File]" !== String(input);

  const interceptor = [() => ({
    request(config) {
      if (0 <= ["post", "put", "patch"].indexOf(config.method.toLowerCase()) && isQueryStringEligible(config.data)) {
        config.headers["Content-Type"] = "application/x-www-form-urlencoded;charset=utf-8";
        config.data = toQueryString(config.data);
      }
      return config;
    }
  })];

  $httpProvider.interceptors.push(interceptor);

}])

ImportError: Cannot import name X

Not specifically for this asker, but this same error will show if the class name in your import doesn't match the definition in the file you're importing from.

How to get DropDownList SelectedValue in Controller in MVC

MVC 5/6/Razor Pages

I think the best way is with strongly typed model, because Viewbags are being aboused too much already :)

MVC 5 example

Your Get Action

public async Task<ActionResult> Register()
    {
        var model = new RegistrationViewModel
        {
            Roles = GetRoles()
        };

        return View(model);
    }

Your View Model

    public class RegistrationViewModel
    {
        public string Name { get; set; }

        public int? RoleId { get; set; }

        public List<SelectListItem> Roles { get; set; }
    }    

Your View

    <div class="form-group">
        @Html.LabelFor(model => model.RoleId, htmlAttributes: new { @class = "col-form-label" })
        <div class="col-form-txt">
            @Html.DropDownListFor(model => model.RoleId, Model.Roles, "--Select Role--", new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.RoleId, "", new { @class = "text-danger" })
        </div>
    </div>                                   

Your Post Action

    [HttpPost, ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegistrationViewModel model)
    {
        if (ModelState.IsValid)
        {
            var _roleId = model.RoleId, 

MVC 6 It'll be a little different

Get Action

public async Task<ActionResult> Register()
    {
        var _roles = new List<SelectListItem>();
        _roles.Add(new SelectListItem
        {
           Text = "Select",
           Value = ""
        });
        foreach (var role in GetRoles())
        {
          _roles.Add(new SelectListItem
          {
            Text = z.Name,
            Value = z.Id
          });
        }

        var model = new RegistrationViewModel
        {
            Roles = _roles
        };

        return View(model);
    }

Your View Model will be same as MVC 5

Your View will be like

<select asp-for="RoleId" asp-items="Model.Roles"></select>

Post will also be same

Razor Pages

Your Page Model

[BindProperty]
public int User User { get; set; } = 1;

public List<SelectListItem> Roles { get; set; }

public void OnGet()
{
    Roles = new List<SelectListItem> {
        new SelectListItem { Value = "1", Text = "X" },
        new SelectListItem { Value = "2", Text = "Y" },
        new SelectListItem { Value = "3", Text = "Z" },
   };
}

<select asp-for="User" asp-items="Model.Roles">
    <option value="">Select Role</option>
</select>

I hope it may help someone :)

How to handle-escape both single and double quotes in an SQL-Update statement

Use two single quotes to escape them in the sql statement. The double quotes should not be a problem:

SELECT 'How is my son''s school helping him learn?  "Not as good as Stack Overflow would!"'

Print:

How is my son's school helping him learn? "Not as good as Stack Overflow would!"

Set default value of javascript object attributes

I saw an article yesterday that mentions an Object.__noSuchMethod__ property: JavascriptTips I've not had a chance to play around with it, so I don't know about browser support, but maybe you could use that in some way?

How to run crontab job every week on Sunday

To have a cron executed on Sunday you can use either of these:

5 8 * * 0
5 8 * * 7
5 8 * * Sun

Where 5 8 stands for the time of the day when this will happen: 8:05.

In general, if you want to execute something on Sunday, just make sure the 5th column contains either of 0, 7 or Sun. You had 6, so it was running on Saturday.

The format for cronjobs is:

 +---------------- minute (0 - 59)
 |  +------------- hour (0 - 23)
 |  |  +---------- day of month (1 - 31)
 |  |  |  +------- month (1 - 12)
 |  |  |  |  +---- day of week (0 - 6) (Sunday=0 or 7)
 |  |  |  |  |
 *  *  *  *  *  command to be executed

You can always use crontab.guru as a editor to check your cron expressions.

Test a weekly cron job

I'm using Webmin because its a productivity gem for someone who finds command line administration a bit daunting and impenetrable.

There is a "Save and Run Now" button in the "System > Scheduled Cron Jobs > Edit Cron Job" web interface.

It displays the output of the command and is exactly what I needed.

How can I add a new column and data to a datatable that already contains data?

Just keep going with your code - you're on the right track:

//call SQL helper class to get initial data 
DataTable dt = sql.ExecuteDataTable("sp_MyProc");

dt.Columns.Add("NewColumn", typeof(System.Int32));

foreach(DataRow row in dt.Rows)
{
    //need to set value to NewColumn column
    row["NewColumn"] = 0;   // or set it to some other value
}

// possibly save your Dataset here, after setting all the new values

How do I convert a Swift Array to a String?

Try This:

let categories = dictData?.value(forKeyPath: "listing_subcategories_id") as! NSMutableArray
                        let tempArray = NSMutableArray()
                        for dc in categories
                        {
                            let dictD = dc as? NSMutableDictionary
                            tempArray.add(dictD?.object(forKey: "subcategories_name") as! String)
                        }
                        let joinedString = tempArray.componentsJoined(by: ",")

Quick Way to Implement Dictionary in C

Create a simple hash function and some linked lists of structures , depending on the hash , assign which linked list to insert the value in . Use the hash for retrieving it as well .

I did a simple implementation some time back :

...
#define K 16 // chaining coefficient

struct dict
{
    char *name; /* name of key */
    int val;   /*  value */
    struct dict *next; /* link field */
};

typedef struct dict dict;
dict *table[K];
int initialized = 0;


void  putval ( char *,int);

void init_dict()
{   
    initialized = 1;
    int i;  
    for(i=0;iname = (char *) malloc (strlen(key_name)+1);
    ptr->val = sval;
    strcpy (ptr->name,key_name);


    ptr->next = (struct dict *)table[hsh];
    table[hsh] = ptr;

}


int getval ( char *key_name )
{   
    int hsh = hash(key_name);   
    dict *ptr;
    for (ptr = table[hsh]; ptr != (dict *) 0;
        ptr = (dict *)ptr->next)
    if (strcmp (ptr->name,key_name) == 0)
        return ptr->val;
    return -1;
}

Placing an image to the top right corner - CSS

While looking at the same problem, I found an example

<style type="text/css">
#topright {
    position: absolute;
    right: 0;
    top: 0;
    display: block;
    height: 125px;
    width: 125px;
    background: url(TRbanner.gif) no-repeat;
    text-indent: -999em;
    text-decoration: none;
}
</style>

<a id="topright" href="#" title="TopRight">Top Right Link Text</a>

The trick here is to create a small, (I used GIMP) a PNG (or GIF) that has a transparent background, (and then just delete the opposite bottom corner.)

how to send a post request with a web browser

with a form, just set method to "post"

<form action="blah.php" method="post">
  <input type="text" name="data" value="mydata" />
  <input type="submit" />
</form>

Converting HTML to Excel?

Change the content type to ms-excel in the html and browser shall open the html in the Excel as xls. If you want control over the transformation of HTML to excel use POI libraries to do so.

Hash string in c#

I think what you're looking for is not hashing but encryption. With hashing, you will not be able to retrieve the original filename from the "hash" variable. With encryption you can, and it is secure.

See AES in ASP.NET with VB.NET for more information about encryption in .NET.

T-SQL string replace in Update

update YourTable
    set YourColumn = replace(YourColumn, '@domain2', '@domain1')
    where charindex('@domain2', YourColumn) <> 0

How to set background color of a View

You made your button transparent. The first byte is the alpha.

Try v.setBackgroundColor(0xFF00FF00);

How to run .jar file by double click on Windows 7 64-bit?

http://www.wikihow.com/Run-a-.Jar-Java-File

  1. Assuming you've loaded the Java JRE and/or Java SDK, then
  2. To do associations, go to "My Computer", click on one of your drives (C: for instance).
  3. When it is shown, choose "Tools" »» "Folder options" (or Properties... it's in different places depending on the Windows version).
  4. Open Windows Explorer (just open any folder) to get the "Tools" -> "Folder options" window.
  5. When you get the "Folder options" window, click on the tab "File types". You should be able to either edit or add JAR files (.jar extension)
  6. Change the program used to open JAR files. In the file select window, go to the folder where the JRE is installed (should be C:/Program Files/Java/..., mark "Always open with", and select the javaw.exe file.

How to count the number of occurrences of an element in a List

Actually, Collections class has a static method called : frequency(Collection c, Object o) which returns the number of occurrences of the element you are searching for, by the way, this will work perfectly for you:

ArrayList<String> animals = new ArrayList<String>();
animals.add("bat");
animals.add("owl");
animals.add("bat");
animals.add("bat");
System.out.println("Freq of bat: "+Collections.frequency(animals, "bat"));

Java JTable getting the data of the selected row

using from ListSelectionModel:

ListSelectionModel cellSelectionModel = table.getSelectionModel();
cellSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

cellSelectionModel.addListSelectionListener(new ListSelectionListener() {
  public void valueChanged(ListSelectionEvent e) {
    String selectedData = null;

    int[] selectedRow = table.getSelectedRows();
    int[] selectedColumns = table.getSelectedColumns();

    for (int i = 0; i < selectedRow.length; i++) {
      for (int j = 0; j < selectedColumns.length; j++) {
        selectedData = (String) table.getValueAt(selectedRow[i], selectedColumns[j]);
      }
    }
    System.out.println("Selected: " + selectedData);
  }

});

see here.

Redirect stderr and stdout in Bash

I wanted a solution to have the output from stdout plus stderr written into a log file and stderr still on console. So I needed to duplicate the stderr output via tee.

This is the solution I found:

command 3>&1 1>&2 2>&3 1>>logfile | tee -a logfile
  • First swap stderr and stdout
  • then append the stdout to the log file
  • pipe stderr to tee and append it also to the log file

docker: executable file not found in $PATH

In the error message shown:

Error response from daemon: Cannot start container foo_1: \
    exec: "grunt serve": executable file not found in $PATH

It is complaining that it cannot find the executable grunt serve, not that it could not find the executable grunt with the argument serve. The most likely explanation for that specific error is running the command with the json syntax:

[ "grunt serve" ]

in something like your compose file. That's invalid since the json syntax requires you to split up each parameter that would normally be split by the shell on each space for you. E.g.:

[ "grunt", "serve" ]

The other possible way you can get both of those into a single parameter is if you were to quote them into a single arg in your docker run command, e.g.

docker run your_image_name "grunt serve"

and in that case, you need to remove the quotes so it gets passed as separate args to the run command:

docker run your_image_name grunt serve

For others seeing this, the executable file not found means that Linux does not see the binary you are trying to run inside your container with the default $PATH value. That could mean lots of possible causes, here are a few:

  • Did you remember to include the binary inside your image? If you run a multi-stage image, make sure that binary install is run in the final stage. Run your image with an interactive shell and verify it exists:

    docker run -it --rm your_image_name /bin/sh
    
  • Your path when shelling into the container may be modified for the interactive shell, particularly if you use bash, so you may need to specify the full path to the binary inside the container, or you may need to update the path in your Dockerfile with:

    ENV PATH=$PATH:/custom/dir/bin
    
  • The binary may not have execute bits set on it, so you may need to make it executable. Do that with chmod:

    RUN chmod 755 /custom/dir/bin/executable
    
  • If you run the image with a volume, that volume can overlay the directory where the executable exists in your image. Volumes do not merge with the image, they get mounted in the filesystem tree same as any other Linux filesystem mount. That means files from the parent filesystem at the mount point are no longer visible. (Note that named volumes are initialized by docker from the image content, but this only happens when the named volume is empty.) So the fix is to not mount volumes on top of paths where you have executables you want to run from the image.