Programs & Examples On #Incognito mode

Incognito mode is Google's name for the Privacy mode of the Google Chrome browser.

Filtering a spark dataframe based on date

The following solutions are applicable since spark 1.5 :

For lower than :

// filter data where the date is lesser than 2015-03-14
data.filter(data("date").lt(lit("2015-03-14")))      

For greater than :

// filter data where the date is greater than 2015-03-14
data.filter(data("date").gt(lit("2015-03-14"))) 

For equality, you can use either equalTo or === :

data.filter(data("date") === lit("2015-03-14"))

If your DataFrame date column is of type StringType, you can convert it using the to_date function :

// filter data where the date is greater than 2015-03-14
data.filter(to_date(data("date")).gt(lit("2015-03-14"))) 

You can also filter according to a year using the year function :

// filter data where year is greater or equal to 2016
data.filter(year($"date").geq(lit(2016))) 

How can I make a float top with CSS?

I know this question is old. But anyone looking to do it today here you go.

_x000D_
_x000D_
div.floatablediv{_x000D_
 -webkit-column-break-inside: avoid;_x000D_
 -moz-column-break-inside: avoid;_x000D_
 column-break-inside: avoid;_x000D_
}_x000D_
div.floatcontainer{_x000D_
  -webkit-column-count: 2;_x000D_
 -webkit-column-gap: 1px;_x000D_
 -webkit-column-fill: auto;_x000D_
 -moz-column-count: 2;_x000D_
 -moz-column-gap: 1px;_x000D_
 -moz-column-fill: auto;_x000D_
 column-count: 2;_x000D_
 column-gap: 1px;_x000D_
 column-fill: auto;_x000D_
}
_x000D_
<div style="background-color: #ccc; width: 100px;" class="floatcontainer">_x000D_
  <div style="height: 50px; width: 50px; background-color: #ff0000;" class="floatablediv">_x000D_
  </div>_x000D_
    <div style="height: 70px; width: 50px; background-color: #00ff00;" class="floatablediv">  _x000D_
  </div>_x000D_
    <div style="height: 30px; width: 50px; background-color: #0000ff;" class="floatablediv">  _x000D_
  </div>_x000D_
    <div style="height: 40px; width: 50px; background-color: #ffff00;" class="floatablediv">  _x000D_
  </div>_x000D_
  <div style="clear:both;"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is Parse/parsing?

Parsing is to read the value of one object to convert it to another type. For example you may have a string with a value of "10". Internally that string contains the Unicode characters '1' and '0' not the actual number 10. The method Integer.parseInt takes that string value and returns a real number.

String tenString = "10"

//This won't work since you can't add an integer and a string
Integer result = 20 + tenString;

//This will set result to 30
Integer result = 20 + Integer.parseInt(tenString);

Automatic HTTPS connection/redirect with node.js/express

This works with express for me:

app.get("*",(req,res,next) => {
    if (req.headers["x-forwarded-proto"]) {
        res.redirect("https://" + req.headers.host + req.url)
    }
    if (!res.headersSent) {
        next()
    }
})

Put this before all HTTP handlers.

Laravel-5 'LIKE' equivalent (Eloquent)

If you want to see what is run in the database use dd(DB::getQueryLog()) to see what queries were run.

Try this

BookingDates::where('email', Input::get('email'))
    ->orWhere('name', 'like', '%' . Input::get('name') . '%')->get();

Import and insert sql.gz file into database with putty

If you have scp then:

To move your file from local to remote:

$scp /home/user/file.gz user@ipaddress:path/to/file.gz 

To move your file from remote to local:

$scp user@ipaddress:path/to/file.gz /home/user/file.gz

To export your mysql file without login in to remote system:

$mysqldump -h ipaddressofremotehost -Pportnumber -u usernameofmysql -p  databasename | gzip -9 > databasename.sql.gz

To import your mysql file withoug login in to remote system:

$gunzip < databasename.sql.gz | mysql -h ipaddressofremotehost -Pportnumber -u usernameofmysql -p 

Note: Make sure you have network access to the ipaddress of remote host

To check network access:

$ping ipaddressofremotehost

Bootstrap datepicker hide after selection

Haven't seen this mentioned, but this is what fixed it for me:

switchOnClick: true

What does '&' do in a C++ declaration?

Your function declares a constant reference to a string:

int foo(const string &myname) {
  cout << "called foo for: " << myname << endl;
  return 0;
}

A reference has some special properties, which make it a safer alternative to pointers in many ways:

  • it can never be NULL
  • it must always be initialised
  • it cannot be changed to refer to a different variable once set
  • it can be used in exactly the same way as the variable to which it refers (which means you do not need to deference it like a pointer)

How does the function signature differ from the equivalent C:

int foo(const char *myname)

There are several differences, since the first refers directly to an object, while const char* must be dereferenced to point to the data.

Is there a difference between using string *myname vs string &myname?

The main difference when dealing with parameters is that you do not need to dereference &myname. A simpler example is:

int add_ptr(int *x, int* y)
{
    return *x + *y;
}
int add_ref(int &x, int &y)
{
    return x + y;
}

which do exactly the same thing. The only difference in this case is that you do not need to dereference x and y as they refer directly to the variables passed in.

const string &GetMethodName() { ... }

What is the & doing here? Is there some website that explains how & is used differently in C vs C++?

This returns a constant reference to a string. So the caller gets to access the returned variable directly, but only in a read-only sense. This is sometimes used to return string data members without allocating extra memory.

There are some subtleties with references - have a look at the C++ FAQ on References for some more details.

Opening a new tab to read a PDF file

On Chrome this has proven to work well for me.

<a href="newsletter_01.pdf" target="_new">Read more</a>

I can not find my.cnf on my windows computer

To answer your question, on Windows, the my.cnf file may be called my.ini. MySQL looks for it in the following locations (in this order):

  • %PROGRAMDATA%\MySQL\MySQL Server 5.7\my.ini, %PROGRAMDATA%\MySQL\MySQL Server 5.7\my.cnf
  • %WINDIR%\my.ini, %WINDIR%\my.cnf
  • C:\my.ini, C:\my.cnf
  • INSTALLDIR\my.ini, INSTALLDIR\my.cnf

See also http://dev.mysql.com/doc/refman/5.7/en/option-files.html

Then you can edit the config file and add an entry like this:

[mysqld]
skip-grant-tables

Then restart the MySQL Service and you can log in and do what you need to do. Of course you want to disable that entry in the config file as soon as possible!

See also http://dev.mysql.com/doc/refman/5.7/en/resetting-permissions.html

Python 2.7: %d, %s, and float()

Try the following:

print "First is: %f" % (first)
print "Second is: %f" % (second)

I am unsure what answer is. But apart from that, this will be:

print "DONE: %f DIVIDED BY %f EQUALS %f, SWEET MATH BRO!" % (first, second, ans)

There's a lot of text on Format String Specifiers. You can google it and get a list of specifiers. One thing I forgot to note:

If you try this:

print "First is: %s" % (first)

It converts the float value in first to a string. So that would work as well.

How to convert characters to HTML entities using plain JavaScript

Having a lookup table with a bazillion replace() calls is slow and not maintainable.

Fortunately, the build-in escape() function also encodes most of the same characters, and puts them in a consistent format (%XX, where XX is the hex value of the character).

So, you can let escape() method do most of the work for you and just change its answer to be HTML entities instead of URL-escaped characters:

htmlescaped = escape(mystring).replace(/%(..)/g,"&#x$1;");

This uses the hex format for escaping values rather than the named entities, but for storing and displaying the values, it works just as well as named entities.

Of course, escape also escapes characters you don't need to escape in HTML (spaces, for instance), but you can unescape them with a few replace calls.

Edit: I like bucabay's answer better than my own... handles a larger range of characters, and requires no hacking afterward to get spaces, slashes, etc. unescaped.

How to serve up images in Angular2?

Just put your images in the assets folder refer them in your html pages or ts files with that link.

How to overlay density plots in R?

use lines for the second one:

plot(density(MyData$Column1))
lines(density(MyData$Column2))

make sure the limits of the first plot are suitable, though.

How to select ALL children (in any level) from a parent in jQuery?

I think you could do:

$('#google_translate_element').find('*').each(function(){
    $(this).unbind('click');
});

but it would cause a lot of overhead

Getting IP address of client

As basZero mentioned, X-Forwarded-For should be checked for comma. (Look at : http://en.wikipedia.org/wiki/X-Forwarded-For). The general format of the field is: X-Forwarded-For: clientIP, proxy1, proxy2... and so on. So we will be seeing something like this : X-FORWARDED-FOR: 129.77.168.62, 129.77.63.62.

How to pass values arguments to modal.show() function in Bootstrap

Use

$(document).ready(function() {
    $('#createFormId').on('show.bs.modal', function(event) {
        $("#cafeId").val($(event.relatedTarget).data('id'));
    });
});

Python, how to read bytes from file and save it?

In my examples I use the 'b' flag ('wb', 'rb') when opening the files because you said you wanted to read bytes. The 'b' flag tells Python not to interpret end-of-line characters which can differ between operating systems. If you are reading text, then omit the 'b' and use 'w' and 'r' respectively.

This reads the entire file in one chunk using the "simplest" Python code. The problem with this approach is that you could run out memory when reading a large file:

ifile = open(input_filename,'rb')
ofile = open(output_filename, 'wb')
ofile.write(ifile.read())
ofile.close()
ifile.close()

This example is refined to read 1MB chunks to ensure it works for files of any size without running out of memory:

ifile = open(input_filename,'rb')
ofile = open(output_filename, 'wb')
data = ifile.read(1024*1024)
while data:
    ofile.write(data)
    data = ifile.read(1024*1024)
ofile.close()
ifile.close()

This example is the same as above but leverages using with to create a context. The advantage of this approach is that the file is automatically closed when exiting the context:

with open(input_filename,'rb') as ifile:
    with open(output_filename, 'wb') as ofile:
        data = ifile.read(1024*1024)
        while data:
            ofile.write(data)
            data = ifile.read(1024*1024)

See the following:

Generate fixed length Strings filled with whitespaces

This simple function works for me:

public static String leftPad(String string, int length, String pad) {
      return pad.repeat(length - string.length()) + string;
    }

Invocation:

String s = leftPad(myString, 10, "0");

Setting a checkbox as checked with Vue.js

In the v-model the value of the property might not be a strict boolean value and the checkbox might not 'recognise' the value as checked/unchecked. There is a neat feature in VueJS to make the conversion to true or false:

<input
  type="checkbox"
  v-model="toggle"
  true-value="yes"
  false-value="no"
>

How to monitor the memory usage of Node.js?

You can use node.js memoryUsage

const formatMemoryUsage = (data) => `${Math.round(data / 1024 / 1024 * 100) / 100} MB`

const memoryData = process.memoryUsage()

const memoryUsage = {
                rss: `${formatMemoryUsage(memoryData.rss)} -> Resident Set Size - total memory allocated for the process execution`,
                heapTotal: `${formatMemoryUsage(memoryData.heapTotal)} -> total size of the allocated heap`,
                heapUsed: `${formatMemoryUsage(memoryData.heapUsed)} -> actual memory used during the execution`,
                external: `${formatMemoryUsage(memoryData.external)} -> V8 external memory`,
}

console.log(memoryUsage)
/*
{
    "rss": "177.54 MB -> Resident Set Size - total memory allocated for the process execution",
    "heapTotal": "102.3 MB -> total size of the allocated heap",
    "heapUsed": "94.3 MB -> actual memory used during the execution",
    "external": "3.03 MB -> V8 external memory"
}
*/

Scale the contents of a div by a percentage?

This cross-browser lib seems safer - just zoom and moz-transform won't cover as many browsers as jquery.transform2d's scale().

http://louisremi.github.io/jquery.transform.js/

For example

$('#div').css({ transform: 'scale(.5)' });

Update

OK - I see people are voting this down without an explanation. The other answer here won't work in old Safari (people running Tiger), and it won't work consistently in some older browsers - that is, it does scale things but it does so in a way that's either very pixellated or shifts the position of the element in a way that doesn't match other browsers.

http://www.browsersupport.net/CSS/zoom

Or just look at this question, which this one is likely just a dupe of:

complete styles for cross browser CSS zoom

Get a Windows Forms control by name in C#

Since you're generating them dynamically, keep a map between a string and the menu item, that will allow fast retrieval.

// in class scope
private readonly Dictionary<string, ToolStripMenuItem> _menuItemsByName = new Dictionary<string, ToolStripMenuItem>();

// in your method creating items
ToolStripMenuItem createdItem = ...
_menuItemsByName.Add("<name here>", createdItem);

// to access it
ToolStripMenuItem menuItem = _menuItemsByName["<name here>"];

Time complexity of accessing a Python dict

As others have pointed out, accessing dicts in Python is fast. They are probably the best-oiled data structure in the language, given their central role. The problem lies elsewhere.

How many tuples are you memoizing? Have you considered the memory footprint? Perhaps you are spending all your time in the memory allocator or paging memory.

How to Automatically Close Alerts using Twitter Bootstrap

I could not get it to work with alert.('close') either.

However I am using this and it works a treat! The alert will fade away after 5 seconds, and once gone, the content below it will slide up to its natural position.

window.setTimeout(function() {
    $(".alert-message").fadeTo(500, 0).slideUp(500, function(){
        $(this).remove(); 
    });
}, 5000);

What is the difference between React Native and React?

React:

React is a declarative, efficient, and flexible JavaScript library for building user interfaces.

React Native:

React Native lets you build mobile apps using only JavaScript. It uses the same design as React, letting you compose a rich mobile UI from declarative components.
With React Native, you don't build a “mobile web app”, an “HTML5 app”, or a “hybrid app”. You build a real mobile app that's indistinguishable from an app built using Objective-C or Java. React Native uses the same fundamental UI building blocks as regular iOS and Android apps. You just put those building blocks together using JavaScript and React.
React Native lets you build your app faster. Instead of recompiling, you can reload your app instantly. With hot reloading, you can even run new code while retaining your application state. Give it a try - it's a magical experience.
React Native combines smoothly with components written in Objective-C, Java, or Swift. It's simple to drop down to native code if you need to optimize a few aspects of your application. It's also easy to build part of your app in React Native, and part of your app using native code directly - that's how the Facebook app works.

So basically React is UI library for the view of your web app, using javascript and JSX, React native is an extra library on the top of React, to make a native app for iOS and Android devices.

React code sample:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);


React Native code sample:

import React, { Component } from 'react';
import { Text, View } from 'react-native';

class WhyReactNativeIsSoGreat extends Component {
  render() {
    return (
      <View>
        <Text>
          If you like React on the web, you'll like React Native.
        </Text>
        <Text>
          You just use native components like 'View' and 'Text',
          instead of web components like 'div' and 'span'.
        </Text>
      </View>
    );
  }
}

For more information about React, visit their official website created by facebook team:

https://facebook.github.io/react

For more information about React Native, visit React native website below:

https://facebook.github.io/react-native

Groovy write to file (newline)

I came across this question and inspired by other contributors. I need to append some content to a file once per line. Here is what I did.

class Doh {
   def ln = System.getProperty('line.separator')
   File file //assume it's initialized 

   void append(String content) {
       file << "$content$ln"
   }
}

Pretty neat I think :)

Selecting the last value of a column

Found a slight variation that worked to eliminate blanks from the bottom of the table. =index(G2:G,COUNTIF(G2:G,"<>"))

How to get current url in view in asp.net core 1.0

You have to get the host and path separately.

 @[email protected]

Calculating Covariance with Python and Numpy

When a and b are 1-dimensional sequences, numpy.cov(a,b)[0][1] is equivalent to your cov(a,b).

The 2x2 array returned by np.cov(a,b) has elements equal to

cov(a,a)  cov(a,b)

cov(a,b)  cov(b,b)

(where, again, cov is the function you defined above.)

How do I use a regular expression to match any string, but at least 3 characters?

I tried find similiar as topic first post.

For my needs I find this

http://answers.oreilly.com/topic/217-how-to-match-whole-words-with-a-regular-expression/

"\b[a-zA-Z0-9]{3}\b"

3 char words only "iokldöajf asd alkjwnkmd asd kja wwda da aij ednm <.jkakla "

Hibernate table not mapped error in HQL query

In the Spring configuration typo applicationContext.xml where the sessionFactory configured put this property

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <property name="packagesToScan" value="${package.name}"/>

Is there a way to make text unselectable on an HTML page?

If it looks bad you can use CSS to change the appearance of selected sections.

How to copy files from host to Docker container?

Copy from container to host dir

docker cp [container-name/id]:./app/[index.js] index.js

(assume you have created a workdir /app in your dockerfile)

Copy from host to container

docker cp index.js [container-name/id]:./app/index.js

Converting string to number in javascript/jQuery

var votevalue = $.map($(this).data('votevalue'), Number);

How to zip a whole folder using PHP

There is a useful undocumented method in the ZipArchive class: addGlob();

$zipFile = "./testZip.zip";
$zipArchive = new ZipArchive();

if ($zipArchive->open($zipFile, (ZipArchive::CREATE | ZipArchive::OVERWRITE)) !== true)
    die("Failed to create archive\n");

$zipArchive->addGlob("./*.txt");
if ($zipArchive->status != ZIPARCHIVE::ER_OK)
    echo "Failed to write files to zip\n";

$zipArchive->close();

Now documented at: www.php.net/manual/en/ziparchive.addglob.php

How to increment datetime by custom months in python without using library

Perhaps add the number of days in the current month using calendar.monthrange()?

import calendar, datetime

def increment_month(when):
    days = calendar.monthrange(when.year, when.month)[1]
    return when + datetime.timedelta(days=days)

now = datetime.datetime.now()
print 'It is now %s' % now
print 'In a month, it will be %s' % increment_month(now)

How to insert values into the database table using VBA in MS access

You can't run two SQL statements into one like you are doing.

You can't "execute" a select query.

db is an object and you haven't set it to anything: (e.g. set db = currentdb)

In VBA integer types can hold up to max of 32767 - I would be tempted to use Long.

You might want to be a bit more specific about the date you are inserting:

INSERT INTO Test (Start_Date) VALUES ('#" & format(InDate, "mm/dd/yyyy") & "#' );"

Python: Binding Socket: "Address already in use"

another solution, in development environment of course, is killing process using it, for example

def serve():
    server = HTTPServer(('', PORT_NUMBER), BaseHTTPRequestHandler)
    print 'Started httpserver on port ' , PORT_NUMBER
    server.serve_forever()
try:
    serve()
except Exception, e:
    print "probably port is used. killing processes using given port %d, %s"%(PORT_NUMBER,e)
    os.system("xterm -e 'sudo fuser -kuv %d/tcp'" % PORT_NUMBER)
    serve()
    raise e

How to hide navigation bar permanently in android activity?

For people looking at a simpler solution, I think you can just have this one line of code in onStart()

  getWindow().getDecorView().setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|
            View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);

It's called Immersive mode. You may look at the official documentation for other possibilities.

How to re import an updated package while in Python Interpreter?

Basically reload as in allyourcode's asnwer. But it won't change underlying the code of already instantiated object or referenced functions. Extending from his answer:

#Make a simple function that prints "version 1"
shell1$ echo 'def x(): print "version 1"' > mymodule.py

# Run the module
shell2$ python
>>> import mymodule
>>> mymodule.x()
version 1
>>> x = mymodule.x
>>> x()
version 1
>>> x is mymodule.x
True


# Change mymodule to print "version 2" (without exiting the python REPL)
shell2$ echo 'def x(): print "version 2"' > mymodule.py

# Back in that same python session
>>> reload(mymodule)
<module 'mymodule' from 'mymodule.pyc'>
>>> mymodule.x()
version 2
>>> x()
version 1
>>> x is mymodule.x
False

RequiredIf Conditional Validation Attribute

I got it to work on ASP.NET MVC 5

I saw many people interested in and suffering from this code and i know it's really confusing and disrupting for the first time.

Notes

  • worked on MVC 5 on both server and client side :D
  • I didn't install "ExpressiveAnnotations" library at all.
  • I'm taking about the Original code from "@Dan Hunex", Find him above

Tips To Fix This Error

"The type System.Web.Mvc.RequiredAttributeAdapter must have a public constructor which accepts three parameters of types System.Web.Mvc.ModelMetadata, System.Web.Mvc.ControllerContext, and ExpressiveAnnotations.Attributes.RequiredIfAttribute Parameter name: adapterType"

Tip #1: make sure that you're inheriting from 'ValidationAttribute' not from 'RequiredAttribute'

 public class RequiredIfAttribute : ValidationAttribute, IClientValidatable { ...}

Tip #2: OR remove this entire line from 'Global.asax', It is not needed at all in the newer version of the code (after edit by @Dan_Hunex), and yes this line was a must in the old version ...

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredIfAttribute), typeof(RequiredAttributeAdapter));

Tips To Get The Javascript Code Part Work

1- put the code in a new js file (ex:requiredIfValidator.js)

2- warp the code inside a $(document).ready(function(){........});

3- include our js file after including the JQuery validation libraries, So it look like this now :

@Scripts.Render("~/bundles/jqueryval")
<script src="~/Content/JS/requiredIfValidator.js"></script>

4- Edit the C# code

from

rule.ValidationParameters["dependentproperty"] = (context as ViewContext).ViewData.TemplateInfo.GetFullHtmlFieldId(PropertyName);

to

rule.ValidationParameters["dependentproperty"] = PropertyName;

and from

if (dependentValue.ToString() == DesiredValue.ToString())

to

if (dependentValue != null && dependentValue.ToString() == DesiredValue.ToString())

My Entire Code Up and Running

Global.asax

Nothing to add here, keep it clean

requiredIfValidator.js

create this file in ~/content or in ~/scripts folder

    $.validator.unobtrusive.adapters.add('requiredif', ['dependentproperty', 'desiredvalue'], function (options)
{
    options.rules['requiredif'] = options.params;
    options.messages['requiredif'] = options.message;
});


$(document).ready(function ()
{

    $.validator.addMethod('requiredif', function (value, element, parameters) {
        var desiredvalue = parameters.desiredvalue;
        desiredvalue = (desiredvalue == null ? '' : desiredvalue).toString();
        var controlType = $("input[id$='" + parameters.dependentproperty + "']").attr("type");
        var actualvalue = {}
        if (controlType == "checkbox" || controlType == "radio") {
            var control = $("input[id$='" + parameters.dependentproperty + "']:checked");
            actualvalue = control.val();
        } else {
            actualvalue = $("#" + parameters.dependentproperty).val();
        }
        if ($.trim(desiredvalue).toLowerCase() === $.trim(actualvalue).toLocaleLowerCase()) {
            var isValid = $.validator.methods.required.call(this, value, element, parameters);
            return isValid;
        }
        return true;
    });
});

_Layout.cshtml or the View

@Scripts.Render("~/bundles/jqueryval")
<script src="~/Content/JS/requiredIfValidator.js"></script>

RequiredIfAttribute.cs Class

create it some where in your project, For example in ~/models/customValidation/

    using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace Your_Project_Name.Models.CustomValidation
{
    public class RequiredIfAttribute : ValidationAttribute, IClientValidatable
    {
        private String PropertyName { get; set; }
        private Object DesiredValue { get; set; }
        private readonly RequiredAttribute _innerAttribute;

        public RequiredIfAttribute(String propertyName, Object desiredvalue)
        {
            PropertyName = propertyName;
            DesiredValue = desiredvalue;
            _innerAttribute = new RequiredAttribute();
        }

        protected override ValidationResult IsValid(object value, ValidationContext context)
        {
            var dependentValue = context.ObjectInstance.GetType().GetProperty(PropertyName).GetValue(context.ObjectInstance, null);

            if (dependentValue != null && dependentValue.ToString() == DesiredValue.ToString())
            {
                if (!_innerAttribute.IsValid(value))
                {
                    return new ValidationResult(FormatErrorMessage(context.DisplayName), new[] { context.MemberName });
                }
            }
            return ValidationResult.Success;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = ErrorMessageString,
                ValidationType = "requiredif",
            };
            rule.ValidationParameters["dependentproperty"] = PropertyName;
            rule.ValidationParameters["desiredvalue"] = DesiredValue is bool ? DesiredValue.ToString().ToLower() : DesiredValue;

            yield return rule;
        }
    }
}

The Model

    using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using Your_Project_Name.Models.CustomValidation;

namespace Your_Project_Name.Models.ViewModels
{

    public class CreateOpenActivity
    {
        public Nullable<int> ORG_BY_CD { get; set; }

        [RequiredIf("ORG_BY_CD", "5", ErrorMessage = "Coordinator ID is required")] // This means: IF 'ORG_BY_CD' is equal 5 (for the example)  > make 'COR_CI_ID_NUM' required and apply its all validation / data annotations
        [RegularExpression("[0-9]+", ErrorMessage = "Enter Numbers Only")]
        [MaxLength(9, ErrorMessage = "Enter a valid ID Number")]
        [MinLength(9, ErrorMessage = "Enter a valid ID Number")]
        public string COR_CI_ID_NUM { get; set; }
    }
}

The View

Nothing to note here actually ...

    @model Your_Project_Name.Models.ViewModels.CreateOpenActivity
@{
    ViewBag.Title = "Testing";
}

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>CreateOpenActivity</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">
            @Html.LabelFor(model => model.ORG_BY_CD, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ORG_BY_CD, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ORG_BY_CD, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.COR_CI_ID_NUM, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.COR_CI_ID_NUM, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.COR_CI_ID_NUM, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

I may upload a project sample for this later ...

Hope this was helpful

Thank You

"And" and "Or" troubles within an IF statement

This is not an answer, but too long for a comment.

In reply to JP's answers / comments, I have run the following test to compare the performance of the 2 methods. The Profiler object is a custom class - but in summary, it uses a kernel32 function which is fairly accurate (Private Declare Sub GetLocalTime Lib "kernel32" (lpSystemTime As SYSTEMTIME)).

Sub test()

  Dim origNum As String
  Dim creditOrDebit As String
  Dim b As Boolean
  Dim p As Profiler
  Dim i As Long

  Set p = New_Profiler

  origNum = "30062600006"
  creditOrDebit = "D"

  p.startTimer ("nested_ifs")

  For i = 1 To 1000000

    If creditOrDebit = "D" Then
      If origNum = "006260006" Then
        b = True
      ElseIf origNum = "30062600006" Then
        b = True
      End If
    End If

  Next i

  p.stopTimer ("nested_ifs")
  p.startTimer ("or_and")

  For i = 1 To 1000000

    If (origNum = "006260006" Or origNum = "30062600006") And creditOrDebit = "D" Then
      b = True
    End If

  Next i

  p.stopTimer ("or_and")

  p.printReport

End Sub

The results of 5 runs (in ms for 1m loops):

20-Jun-2012 19:28:25
nested_ifs (x1): 156 - Last Run: 156 - Average Run: 156
or_and (x1): 125 - Last Run: 125 - Average Run: 125

20-Jun-2012 19:28:26
nested_ifs (x1): 156 - Last Run: 156 - Average Run: 156
or_and (x1): 125 - Last Run: 125 - Average Run: 125

20-Jun-2012 19:28:27
nested_ifs (x1): 140 - Last Run: 140 - Average Run: 140
or_and (x1): 125 - Last Run: 125 - Average Run: 125

20-Jun-2012 19:28:28
nested_ifs (x1): 140 - Last Run: 140 - Average Run: 140
or_and (x1): 141 - Last Run: 141 - Average Run: 141

20-Jun-2012 19:28:29
nested_ifs (x1): 156 - Last Run: 156 - Average Run: 156
or_and (x1): 125 - Last Run: 125 - Average Run: 125

Note

If creditOrDebit is not "D", JP's code runs faster (around 60ms vs. 125ms for the or/and code).

Load text file as strings using numpy.loadtxt()

There is also read_csv in Pandas, which is fast and supports non-comma column separators and automatic typing by column:

import pandas as pd
df = pd.read_csv('your_file',sep='\t')

It can be converted to a NumPy array if you prefer that type with:

import numpy as np
arr = np.array(df)

This is by far the easiest and most mature text import approach I've come across.

Traverse all the Nodes of a JSON Object Tree with JavaScript

If you think jQuery is kind of overkill for such a primitive task, you could do something like that:

//your object
var o = { 
    foo:"bar",
    arr:[1,2,3],
    subo: {
        foo2:"bar2"
    }
};

//called with every property and its value
function process(key,value) {
    console.log(key + " : "+value);
}

function traverse(o,func) {
    for (var i in o) {
        func.apply(this,[i,o[i]]);  
        if (o[i] !== null && typeof(o[i])=="object") {
            //going one step down in the object tree!!
            traverse(o[i],func);
        }
    }
}

//that's all... no magic, no bloated framework
traverse(o,process);

Difference between Method and Function?

Both are same, there is no difference its just a different term for the same thing in C#.

Method:

In object-oriented programming, a method is a subroutine (or procedure or function) associated with a class.

With respect to Object Oriented programming the term "Method" is used, not functions.

jQuery plugin returning "Cannot read property of undefined"

The problem is that "i" is incremented, so by the time the click event is executed the value of i equals len. One possible solution is to capture the value of i inside a function:

var len = menuitems.length;
for (var i = 0; i < len; i++){
    (function(i) {
      $('<li/>',{
          'html':'<img src="'+menuitems[i].icon+'">'+menuitems[i].name,
          'click':function(){
              menuitems[i].action();
          },
          'class':o.itemClass
      }).appendTo('.'+o.listClass);
    })(i);
}

In the above sample, the anonymous function creates a new scope which captures the current value of i, so that when the click event is triggered the local variable is used instead of the i from the for loop.

How to get current foreground activity context in android?

I expand on the top of @gezdy's answer.

In every Activities, instead of having to "register" itself with Application with manual coding, we can make use of the following API since level 14, to help us achieve similar purpose with less manual coding.

public void registerActivityLifecycleCallbacks (Application.ActivityLifecycleCallbacks callback)

http://developer.android.com/reference/android/app/Application.html#registerActivityLifecycleCallbacks%28android.app.Application.ActivityLifecycleCallbacks%29

In Application.ActivityLifecycleCallbacks, you can get which Activity is "attached" to or "detached" to this Application.

However, this technique is only available since API level 14.

String.equals versus ==

Use Split rather than tokenizer,it will surely provide u exact output for E.g:

string name="Harry";
string salary="25000";
string namsal="Harry 25000";
string[] s=namsal.split(" ");
for(int i=0;i<s.length;i++)
{
System.out.println(s[i]);
}
if(s[0].equals("Harry"))
{
System.out.println("Task Complete");
}

After this I am sure you will get better results.....

Excel 2010 VBA Referencing Specific Cells in other worksheets

Sub Results2()

    Dim rCell As Range
    Dim shSource As Worksheet
    Dim shDest As Worksheet
    Dim lCnt As Long

    Set shSource = ThisWorkbook.Sheets("Sheet1")
    Set shDest = ThisWorkbook.Sheets("Sheet2")

    For Each rCell In shSource.Range("A1", shSource.Cells(shSource.Rows.Count, 1).End(xlUp)).Cells
        lCnt = lCnt + 1
        shDest.Range("A4").Offset(0, lCnt * 4).Formula = "=" & rCell.Address(False, False, , True) & "+" & rCell.Offset(0, 1).Address(False, False, , True)
    Next rCell

End Sub

This loops through column A of sheet1 and creates a formula in sheet2 for every cell. To find the last cell in Sheet1, I start at the bottom (shSource.Rows.Count) and .End(xlUp) to get the last cell in the column that's not blank.

To create the elements of the formula, I use the Address property of the cell on Sheet. I'm using three of the arguments to Address. The first two are RowAbsolute and ColumnAbsolute, both set to false. I don't care about the third argument, but I set the fourth argument (External) to True so that it includes the sheet name.

I prefer to go from Source to Destination rather than the other way. But that's just a personal preference. If you want to work from the destination,

Sub Results3()

    Dim i As Long, lCnt As Long
    Dim sh As Worksheet

    lCnt = Application.WorksheetFunction.CountA(ThisWorkbook.Sheets("Sheet1").Columns(1))
    Set sh = ThisWorkbook.Sheets("Sheet2")

    Const sSOURCE As String = "Sheet1!"

    For i = 1 To lCnt
        sh.Range("A1").Offset(0, 4 * (i - 1)).Formula = "=" & sSOURCE & "A" & i & " + " & sSOURCE & "B" & i
    Next i

End Sub

How to fix 'Notice: Undefined index:' in PHP form action

short way, you can use Ternary Operators

$filename = !empty($_POST['filename'])?$_POST['filename']:'-';

mysql_config not found when installing mysqldb python interface

The commands (mysql too) mPATH might be missing.

export PATH=$PATH:/usr/local/mysql/bin/

Error message "Linter pylint is not installed"

This solved the issue for me:

pip install pylint -U

I.e., upgrade the pylint package.

Cannot access a disposed object - How to fix?

because the solution folder was inside OneDrive folder.

If you moving the solution folders out of the one drive folder made the errors go away.

best

How to check if spark dataframe is empty?

I had the same question, and I tested 3 main solution :

  1. (df != null) && (df.count > 0)
  2. df.head(1).isEmpty() as @hulin003 suggest
  3. df.rdd.isEmpty() as @Justin Pihony suggest

and of course the 3 works, however in term of perfermance, here is what I found, when executing the these methods on the same DF in my machine, in terme of execution time :

  1. it takes ~9366ms
  2. it takes ~5607ms
  3. it takes ~1921ms

therefore I think that the best solution is df.rdd.isEmpty() as @Justin Pihony suggest

Create a OpenSSL certificate on Windows

You can download a native OpenSSL for Windows, or you can always use Cygwin.

How to call loading function with React useEffect only once

leave the dependency array blank . hope this will help you understand better.

   useEffect(() => {
      doSomething()
    }, []) 

empty dependency array runs Only Once, on Mount

useEffect(() => {
  doSomething(value)
}, [value])  

pass value as a dependency. if dependencies has changed since the last time, the effect will run again.

useEffect(() => {
  doSomething(value)
})  

no dependency. This gets called after every render.

How can I remove "\r\n" from a string in C#? Can I use a regular expression?

Try this:

private void txtEntry_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            string trimText;

            trimText = this.txtEntry.Text.Replace("\r\n", "").ToString();
            this.txtEntry.Text = trimText;
            btnEnter.PerformClick();
        }
    }

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize

The JDK 8 HotSpot JVM is now using native memory for the representation of class metadata and is called Metaspace.

The permanent generation has been removed. The PermSize and MaxPermSize are ignored and a warning is issued if they are present on the command line.

How to enable loglevel debug on Apache2 server

Do note that on newer Apache versions the RewriteLog and RewriteLogLevel have been removed, and in fact will now trigger an error when trying to start Apache (at least on my XAMPP installation with Apache 2.4.2):

AH00526: Syntax error on line xx of path/to/config/file.conf: Invalid command 'RewriteLog', perhaps misspelled or defined by a module not included in the server configuration`

Instead, you're now supposed to use the general LogLevel directive, with a level of trace1 up to trace8. 'debug' didn't display any rewrite messages in the log for me.

Example: LogLevel warn rewrite:trace3

For the official documentation, see here.

Of course this also means that now your rewrite logs will be written in the general error log file and you'll have to sort them out yourself.

Is there a C# case insensitive equals operator?

Operator? NO, but I think you can change your culture so that string comparison is not case-sensitive.

// you'll want to change this...
System.Threading.Thread.CurrentThread.CurrentCulture
// and you'll want to custimize this
System.Globalization.CultureInfo.CompareInfo

I'm confident that it will change the way that strings are being compared by the equals operator.

Caused by: java.security.UnrecoverableKeyException: Cannot recover key

The private key password defined in your app/config is incorrect. First try verifying the the private key password by changing to another one as follows:

keytool -keypasswd -new changeit -keystore cacerts -storepass changeit -alias someapp -keypass password

The above example changes the password from password to changeit. This command will succeed if the private key password was password.

How might I extract the property values of a JavaScript object into an array?

In case you use d3. you can do d3.values(dataObject) which will give

enter image description here

How do I get countifs to select all non-blank cells in Excel?

If you are using multiple criteria, and want to count the number of non-blank cells in a particular column, you probably want to look at DCOUNTA.

e.g

  A   B   C   D  E   F   G
1 Dog Cat Cow    Dog Cat
2 x   1          x   1
3 x   2 
4 x   1   nb     Result:
5 x   2   nb     1

Formula in E5: =DCOUNTA(A1:C5,"Cow",E1:F2)

Push git commits & tags simultaneously

@since Git 2.4

git push --atomic origin <branch name> <tag>

Best way to find the months between two dates

from datetime import datetime

def diff_month(start_date,end_date):
    qty_month = ((end_date.year - start_date.year) * 12) + (end_date.month - start_date.month)

    d_days = end_date.day - start_date.day

    if d_days >= 0:
        adjust = 0
    else:
        adjust = -1
    qty_month += adjust

    return qty_month

diff_month(datetime.date.today(),datetime(2019,08,24))


#Examples:
#diff_month(datetime(2018,02,12),datetime(2019,08,24)) = 18
#diff_month(datetime(2018,02,12),datetime(2018,08,10)) = 5

JavaScript module pattern with example

I would really recommend anyone entering this subject to read Addy Osmani's free book:

"Learning JavaScript Design Patterns".

http://addyosmani.com/resources/essentialjsdesignpatterns/book/

This book helped me out immensely when I was starting into writing more maintainable JavaScript and I still use it as a reference. Have a look at his different module pattern implementations, he explains them really well.

How do I convert a String to an InputStream in Java?

I find that using Apache Commons IO makes my life much easier.

String source = "This is the source of my input stream";
InputStream in = org.apache.commons.io.IOUtils.toInputStream(source, "UTF-8");

You may find that the library also offer many other shortcuts to commonly done tasks that you may be able to use in your project.

Best way to restrict a text field to numbers only?

This is a variation on Robert's answer that allows a single decimal point to be entered. If a decimal point has already been entered, only numbers are accepted as input.

JSFiddle - decimal number input

// Allow only decimal number input

$('#decimalInput').keypress(function (e) {
    var a = [];
    var k = e.which;

    for (i = 48; i < 58; i++)
    a.push(i);

    // allow a max of 1 decimal point to be entered
    if (this.value.indexOf(".") === -1) {
        a.push(46);
    }

    if (!(a.indexOf(k) >= 0)) e.preventDefault();

    $('span').text('KeyCode: ' + k);
});

jQuery - Call ajax every 10 seconds

Are you going to want to do a setInterval()?

setInterval(function(){get_fb();}, 10000);

Or:

setInterval(get_fb, 10000);

Or, if you want it to run only after successfully completing the call, you can set it up in your .ajax().success() callback:

function get_fb(){
    var feedback = $.ajax({
        type: "POST",
        url: "feedback.php",
        async: false
    }).success(function(){
        setTimeout(function(){get_fb();}, 10000);
    }).responseText;

    $('div.feedback-box').html(feedback);
}

Or use .ajax().complete() if you want it to run regardless of result:

function get_fb(){
    var feedback = $.ajax({
        type: "POST",
        url: "feedback.php",
        async: false
    }).complete(function(){
        setTimeout(function(){get_fb();}, 10000);
    }).responseText;

    $('div.feedback-box').html(feedback);
}

Here is a demonstration of the two. Note, the success works only once because jsfiddle is returning a 404 error on the ajax call.

http://jsfiddle.net/YXMPn/

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

Others have answered this to reasonable extent, but often with the name "ternary operator".

Being the pedant that I am, I'd like to make it clear that the name of the operator is the conditional operator or "conditional operator ?:". It's a ternary operator (in that it has three operands) and it happens to be the only ternary operator in Java at the moment.

However, the spec is pretty clear that its name is the conditional operator or "conditional operator ?:" to be absolutely unambiguous. I think it's clearer to call it by that name, as it indicates the behaviour of the operator to some extent (evaluating a condition) rather than just how many operands it has.

How to clone object in C++ ? Or Is there another solution?

In C++ copying the object means cloning. There is no any special cloning in the language.

As the standard suggests, after copying you should have 2 identical copies of the same object.

There are 2 types of copying: copy constructor when you create object on a non initialized space and copy operator where you need to release the old state of the object (that is expected to be valid) before setting the new state.

xxxxxx.exe is not a valid Win32 application

There are at least two solutions:

  1. You need Visual Studio 2010 installed, then from Visual Studio 2010, View -> Solution Explorer -> Right Click on your project -> Choose Properties from the context menu, you'll get the windows "your project name" Property Pages -> Configuration Properties -> General -> Platform toolset, choose "Visual Studio 2010 (v100)".
  2. You need the Visual Studio 2012 Update 1 described in Windows XP Targeting with C++ in Visual Studio 2012

Getting list of parameter names inside python function

Well we don't actually need inspect here.

>>> func = lambda x, y: (x, y)
>>> 
>>> func.__code__.co_argcount
2
>>> func.__code__.co_varnames
('x', 'y')
>>>
>>> def func2(x,y=3):
...  print(func2.__code__.co_varnames)
...  pass # Other things
... 
>>> func2(3,3)
('x', 'y')
>>> 
>>> func2.__defaults__
(3,)

For Python 2.5 and older, use func_code instead of __code__, and func_defaults instead of __defaults__.

Setting href attribute at runtime

Set the href attribute with

$(selector).attr('href', 'url_goes_here');

and read it using

$(selector).attr('href');

Where "selector" is any valid jQuery selector for your <a> element (".myClass" or "#myId" to name the most simple ones).

Hope this helps !

Excel VBA Code: Compile Error in x64 Version ('PtrSafe' attribute required)

I'm quite sure you won't get this 32Bit DLL working in Office 64Bit. The DLL needs to be updated by the author to be compatible with 64Bit versions of Office.

The code changes you have found and supplied in the question are used to convert calls to APIs that have already been rewritten for Office 64Bit. (Most Windows APIs have been updated.)

From: http://technet.microsoft.com/en-us/library/ee681792.aspx:

"ActiveX controls and add-in (COM) DLLs (dynamic link libraries) that were written for 32-bit Office will not work in a 64-bit process."

Edit: Further to your comment, I've tried the 64Bit DLL version on Win 8 64Bit with Office 2010 64Bit. Since you are using User Defined Functions called from the Excel worksheet you are not able to see the error thrown by Excel and just end up with the #VALUE returned.

If we create a custom procedure within VBA and try one of the DLL functions we see the exact error thrown. I tried a simple function of swe_day_of_week which just has a time as an input and I get the error Run-time error '48' File not found: swedll32.dll.

Now I have the 64Bit DLL you supplied in the correct locations so it should be found which suggests it has dependencies which cannot be located as per https://stackoverflow.com/a/8607250/1733206

I've got all the .NET frameworks installed which would be my first guess, so without further information from the author it might be difficult to find the problem.

Edit2: And after a bit more investigating it appears the 64Bit version you have supplied is actually a 32Bit version. Hence the error message on the 64Bit Office. You can check this by trying to access the '64Bit' version in Office 32Bit.

How can I change the class of an element with jQuery>

<script>
$(document).ready(function(){
      $('button').attr('class','btn btn-primary');
}); </script>

Permission denied (publickey,gssapi-keyex,gssapi-with-mic)

The trick here is to use the -C (comment) parameter to specify your GCE userid. It looks like Google introduced this change last in 2018.

If the Google user who owns the GCE instance is [email protected] (which you will use as your login userid), then generate the key pair with (for example)

ssh-keygen -b521 -t ecdsa -C myname -f mykeypair

When you paste mykeypair.pub into the instance's public key list, you should see "myname" appear as the userid of the key.

Setting this up will let you use ssh, scp, etc from your command line.

How do I trigger a macro to run after a new mail is received in Outlook?

Try something like this inside ThisOutlookSession:

Private Sub Application_NewMail()
    Call Your_main_macro
End Sub

My outlook vba just fired when I received an email and had that application event open.

Edit: I just tested a hello world msg box and it ran after being called in the application_newmail event when an email was received.

What does "res.render" do, and what does the html file look like?

Renders a view and sends the rendered HTML string to the client.

res.render('index');

Or

res.render('index', function(err, html) {
  if(err) {...}
  res.send(html);
});

DOCS HERE: https://expressjs.com/en/api.html#res.render

What is the better API to Reading Excel sheets in java - JXL or Apache POI

I am not familiar with JXL and but we use POI. POI is well maintained and can handle both the binary .xls format and the new xml based format that was introduced in Office 2007.

CSV files are not excel files, they are text based files, so these libraries don't read them. You will need to parse out a CSV file yourself. I am not aware of any CSV file libraries, but I haven't looked either.

CSS: how to position element in lower right?

Set the CSS position: relative; on the box. This causes all absolute positions of objects inside to be relative to the corners of that box. Then set the following CSS on the "Bet 5 days ago" line:

position: absolute;
bottom: 0;
right: 0;

If you need to space the text farther away from the edge, you could change 0 to 2px or similar.

Closing Application with Exit button

Don't ever put an Exit button on an Android app. Let the OS decide when to kill your Activity. Learn about the Android Activity lifecycle and implement any necessary callbacks.

Create a new line in Java's FileWriter

Try wrapping your FileWriter in a BufferedWriter:

BufferedWriter bw = new BufferedWriter(writer);
bw.newLine();

Javadocs for BufferedWriter here.

How to make a DIV not wrap?

The <span> tag is used to group inline-elements in a document.
(source)

Regular expression [Any number]

var mask = /^\d+$/;
if ( myString.exec(mask) ){
   /* That's a number */
}

Variable used in lambda expression should be final or effectively final

A final variable means that it can be instantiated only one time. in Java you can't use non-final variables in lambda as well as in anonymous inner classes.

You can refactor your code with the old for-each loop:

private TimeZone extractCalendarTimeZoneComponent(Calendar cal,TimeZone calTz) {
    try {
        for(Component component : cal.getComponents().getComponents("VTIMEZONE")) {
        VTimeZone v = (VTimeZone) component;
           v.getTimeZoneId();
           if(calTz==null) {
               calTz = TimeZone.getTimeZone(v.getTimeZoneId().getValue());
           }
        }
    } catch (Exception e) {
        log.warn("Unable to determine ical timezone", e);
    }
    return null;
}

Even if I don't get the sense of some pieces of this code:

  • you call a v.getTimeZoneId(); without using its return value
  • with the assignment calTz = TimeZone.getTimeZone(v.getTimeZoneId().getValue()); you don't modify the originally passed calTz and you don't use it in this method
  • You always return null, why don't you set void as return type?

Hope also these tips helps you to improve.

How to get streaming url from online streaming radio station

The provided answers didn't work for me. I'm adding another answer because this is where I ended up when searching for radio stream urls.

Radio Browser is a searchable site with streaming urls for radio stations around the world:

http://www.radio-browser.info/

Search for a station like FIP, Pinguin Radio or Radio Paradise, then click the save button, which downloads a PLS file that you can open in your radioplayer (Rhythmbox), or you open the file in a text editor and copy the URL to add in Goodvibes.

How do I add a ToolTip to a control?

Here is your article for doing it with code

private void Form1_Load(object sender, System.EventArgs e)
{
     // Create the ToolTip and associate with the Form container.
     ToolTip toolTip1 = new ToolTip();

     // Set up the delays for the ToolTip.
     toolTip1.AutoPopDelay = 5000;
     toolTip1.InitialDelay = 1000;
     toolTip1.ReshowDelay = 500;
     // Force the ToolTip text to be displayed whether or not the form is active.
     toolTip1.ShowAlways = true;

     // Set up the ToolTip text for the Button and Checkbox.
     toolTip1.SetToolTip(this.button1, "My button1");
     toolTip1.SetToolTip(this.checkBox1, "My checkBox1");
}

val() vs. text() for textarea

.val() always works with textarea elements.

.text() works sometimes and fails other times! It's not reliable (tested in Chrome 33)

What's best is that .val() works seamlessly with other form elements too (like input) whereas .text() fails.

Get Android API level of phone currently running my application

Check android.os.Build.VERSION, which is a static class that holds various pieces of information about the Android OS a system is running.

If you care about all versions possible (back to original Android version), as in minSdkVersion is set to anything less than 4, then you will have to use android.os.Build.VERSION.SDK, which is a String that can be converted to the integer of the release.

If you are on at least API version 4 (Android 1.6 Donut), the current suggested way of getting the API level would be to check the value of android.os.Build.VERSION.SDK_INT, which is an integer.

In either case, the integer you get maps to an enum value from all those defined in android.os.Build.VERSION_CODES:

SDK_INT value        Build.VERSION_CODES        Human Version Name       
    1                  BASE                      Android 1.0 (no codename)
    2                  BASE_1_1                  Android 1.1 Petit Four
    3                  CUPCAKE                   Android 1.5 Cupcake
    4                  DONUT                     Android 1.6 Donut
    5                  ECLAIR                    Android 2.0 Eclair
    6                  ECLAIR_0_1                Android 2.0.1 Eclair                  
    7                  ECLAIR_MR1                Android 2.1 Eclair
    8                  FROYO                     Android 2.2 Froyo
    9                  GINGERBREAD               Android 2.3 Gingerbread
   10                  GINGERBREAD_MR1           Android 2.3.3 Gingerbread
   11                  HONEYCOMB                 Android 3.0 Honeycomb
   12                  HONEYCOMB_MR1             Android 3.1 Honeycomb
   13                  HONEYCOMB_MR2             Android 3.2 Honeycomb
   14                  ICE_CREAM_SANDWICH        Android 4.0 Ice Cream Sandwich
   15                  ICE_CREAM_SANDWICH_MR1    Android 4.0.3 Ice Cream Sandwich
   16                  JELLY_BEAN                Android 4.1 Jellybean
   17                  JELLY_BEAN_MR1            Android 4.2 Jellybean
   18                  JELLY_BEAN_MR2            Android 4.3 Jellybean
   19                  KITKAT                    Android 4.4 KitKat
   20                  KITKAT_WATCH              Android 4.4 KitKat Watch
   21                  LOLLIPOP                  Android 5.0 Lollipop
   22                  LOLLIPOP_MR1              Android 5.1 Lollipop
   23                  M                         Android 6.0 Marshmallow
   24                  N                         Android 7.0 Nougat
   25                  N_MR1                     Android 7.1.1 Nougat
   26                  O                         Android 8.0 Oreo
   27                  O_MR1                     Android 8 Oreo MR1
   28                  P                         Android 9 Pie
   29                  Q                         Android 10
  10000                CUR_DEVELOPMENT           Current Development Version

Note that some time between Android N and O, the Android SDK began aliasing CUR_DEVELOPMENT and the developer preview of the next major Android version to be the same SDK_INT value (10000).

Matching a Forward Slash with a regex

You can escape it like this.

/\//ig; //  Matches /

or just use indexOf

if(str.indexOf("/") > -1)

Application Error - The connection to the server was unsuccessful. (file:///android_asset/www/index.html)

I had a similar issue and based on above suggestions I first added "super.setIntegerProperty("loadUrlTimeoutValue", 70000);" but that did not help. So I tried Project -> Clean, that worked and I can launch the app now !

Avinash...

Run local java applet in browser (chrome/firefox) "Your security settings have blocked a local application from running"

After reading Java 7 Update 21 Security Improvements in Detail mention..

With the introduced changes it is most likely that no end-user is able to run your application when they are either self-signed or unsigned.

..I was wondering how this would go for loose class files - the 'simplest' applets of all.

Local file system

Dialog: Your security settings have blocked a local application from running
Your security settings have blocked a local application from running

That is the dialog seen for an applet consisting of loose class files being loaded off the local file system when the JRE is set to the default 'High' security setting.


Note that a slight quirk of the JRE only produced that on point 3 of.

  1. Load the applet page to see a broken applet symbol that leads to an empty console.
    Open the Java settings and set the level to Medium.
    Close browser & Java settings.
  2. Load the applet page to see the applet.
    Open the Java settings and set the level to High.
    Close browser & Java settings.
  3. Load the applet page to see a broken applet symbol & the above dialog.

Internet

If you load the simple applet (loose class file) seen at this resizable applet demo off the internet - which boasts an applet element of:

<applet
    code="PlafChanger.class"
    codebase="."
    alt="Pluggable Look'n'Feel Changer appears here if Java is enabled"
    width='100%'
    height='250'>
<p>Pluggable Look'n'Feel Changer appears here in a Java capable browser.</p>
</applet>

It also seems to load successfully. Implying that:-

Applets loaded from the local file system are now subject to a stricter security sandbox than those loaded from the internet or a local server.

Security settings descriptions

As of Java 7 update 51.

  • Very High: Most secure setting - Only Java applications identified by a non-expired certificate from a trusted authority will be allowed to run.
  • High (minimum recommended): Java applications identified by a certificate from a trusted authority will be allowed to run.
  • Medium - All Java applications will be allowed to run after presenting a security prompt.

Check if a value is within a range of numbers

Here is an option with only a single comparison.

// return true if in range, otherwise false
function inRange(x, min, max) {
    return ((x-min)*(x-max) <= 0);
}

console.log(inRange(5, 1, 10));     // true
console.log(inRange(-5, 1, 10));    // false
console.log(inRange(20, 1, 10));    // false

Tools to get a pictorial function call graph of code

You can check out my bash-based C call tree generator here. It lets you specify one or more C functions for which you want caller and/or called information, or you can specify a set of functions and determine the reachability graph of function calls that connects them... I.e. tell me all the ways main(), foo(), and bar() are connected. It uses graphviz/dot for a graphing engine.

how to delete the content of text file without deleting itself

After copying from A to B open file A again to write mode and then write empty string in it

@viewChild not working - cannot read property nativeElement of undefined

This error occurs when you're trying to target an element that is wrapped in a condition.

So, here if I use ngIf in place of [hidden], it will give me TypeError: Cannot read property 'nativeElement' of undefined

So use [hidden], class.show or class.hide in place of *ngIf.

<button (click)="displayMap()" class="btn btn-primary">Display Map</button>

   <div [hidden]="!display">
      <div #mapContainer id="map">Content to render when condition is true.</div>
   </div>

How to move certain commits to be based on another branch in git?

The simplest thing you can do is cherry picking a range. It does the same as the rebase --onto but is easier for the eyes :)

git cherry-pick quickfix1..quickfix2

How to convert latitude or longitude to meters?

Based on average distance for degress in the Earth.

1° = 111km;

Converting this for radians and dividing for meters, take's a magic number for the RAD, in meters: 0.000008998719243599958;

then:

const RAD = 0.000008998719243599958;
Math.sqrt(Math.pow(lat1 - lat2, 2) + Math.pow(long1 - long2, 2)) / RAD;

Gets byte array from a ByteBuffer in java

If one does not know anything about the internal state of the given (Direct)ByteBuffer and wants to retrieve the whole content of the buffer, this can be used:

ByteBuffer byteBuffer = ...;
byte[] data = new byte[byteBuffer.capacity()];
((ByteBuffer) byteBuffer.duplicate().clear()).get(data);

Preferred way to create a Scala list

I always prefer List and I use "fold/reduce" before "for comprehension". However, "for comprehension" is preferred if nested "folds" are required. Recursion is the last resort if I can not accomplish the task using "fold/reduce/for".

so for your example, I will do:

((0 to 3) :\ List[Int]())(_ :: _)

before I do:

(for (x <- 0 to 3) yield x).toList

Note: I use "foldRight(:\)" instead of "foldLeft(/:)" here because of the order of "_"s. For a version that does not throw StackOverflowException, use "foldLeft" instead.

Saving any file to in the database, just convert it to a byte array?

Since it's not mentioned what database you mean I'm assuming SQL Server. Below solution works for both 2005 and 2008.

You have to create table with VARBINARY(MAX) as one of the columns. In my example I've created Table Raporty with column RaportPlik being VARBINARY(MAX) column.

Method to put file into database from drive:

public static void databaseFilePut(string varFilePath) {
    byte[] file;
    using (var stream = new FileStream(varFilePath, FileMode.Open, FileAccess.Read)) {
        using (var reader = new BinaryReader(stream)) {
            file = reader.ReadBytes((int) stream.Length);       
        }          
    }
    using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetails))
    using (var sqlWrite = new SqlCommand("INSERT INTO Raporty (RaportPlik) Values(@File)", varConnection)) {
        sqlWrite.Parameters.Add("@File", SqlDbType.VarBinary, file.Length).Value = file;
        sqlWrite.ExecuteNonQuery();
    }
}

This method is to get file from database and save it on drive:

public static void databaseFileRead(string varID, string varPathToNewLocation) {
    using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetails))
    using (var sqlQuery = new SqlCommand(@"SELECT [RaportPlik] FROM [dbo].[Raporty] WHERE [RaportID] = @varID", varConnection)) {
        sqlQuery.Parameters.AddWithValue("@varID", varID);
        using (var sqlQueryResult = sqlQuery.ExecuteReader())
            if (sqlQueryResult != null) {
                sqlQueryResult.Read();
                var blob = new Byte[(sqlQueryResult.GetBytes(0, 0, null, 0, int.MaxValue))];
                sqlQueryResult.GetBytes(0, 0, blob, 0, blob.Length);
                using (var fs = new FileStream(varPathToNewLocation, FileMode.Create, FileAccess.Write)) 
                    fs.Write(blob, 0, blob.Length);
            }
    }
}

This method is to get file from database and put it as MemoryStream:

public static MemoryStream databaseFileRead(string varID) {
    MemoryStream memoryStream = new MemoryStream();
    using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetails))
    using (var sqlQuery = new SqlCommand(@"SELECT [RaportPlik] FROM [dbo].[Raporty] WHERE [RaportID] = @varID", varConnection)) {
        sqlQuery.Parameters.AddWithValue("@varID", varID);
        using (var sqlQueryResult = sqlQuery.ExecuteReader())
            if (sqlQueryResult != null) {
                sqlQueryResult.Read();
                var blob = new Byte[(sqlQueryResult.GetBytes(0, 0, null, 0, int.MaxValue))];
                sqlQueryResult.GetBytes(0, 0, blob, 0, blob.Length);
                //using (var fs = new MemoryStream(memoryStream, FileMode.Create, FileAccess.Write)) {
                memoryStream.Write(blob, 0, blob.Length);
                //}
            }
    }
    return memoryStream;
}

This method is to put MemoryStream into database:

public static int databaseFilePut(MemoryStream fileToPut) {
        int varID = 0;
        byte[] file = fileToPut.ToArray();
        const string preparedCommand = @"
                    INSERT INTO [dbo].[Raporty]
                               ([RaportPlik])
                         VALUES
                               (@File)
                        SELECT [RaportID] FROM [dbo].[Raporty]
            WHERE [RaportID] = SCOPE_IDENTITY()
                    ";
        using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetails))
        using (var sqlWrite = new SqlCommand(preparedCommand, varConnection)) {
            sqlWrite.Parameters.Add("@File", SqlDbType.VarBinary, file.Length).Value = file;

            using (var sqlWriteQuery = sqlWrite.ExecuteReader())
                while (sqlWriteQuery != null && sqlWriteQuery.Read()) {
                    varID = sqlWriteQuery["RaportID"] is int ? (int) sqlWriteQuery["RaportID"] : 0;
                }
        }
        return varID;
    }

Happy coding :-)

Using the rJava package on Win7 64 bit with R

Getting rJava to work depends heavily on your computers configuration:

  1. You have to use the same 32bit or 64bit version for both: R and JDK/JRE. A mixture of this will never work (at least for me).
  2. If you use 64bit version make sure, that you do not set JAVA_HOME as a enviorment variable. If this variable is set, rJava will not work for whatever reason (at least for me). You can check easily within R is JAVA_HOME is set with

    Sys.getenv("JAVA_HOME")
    

If you need to have JAVA_HOME set (e.g. you need it for maven or something else), you could deactivate it within your R-session with the following code before loading rJava:

if (Sys.getenv("JAVA_HOME")!="")
  Sys.setenv(JAVA_HOME="")
library(rJava)

This should do the trick in most cases. Furthermore this will fix issue Using the rJava package on Win7 64 bit with R, too. I borrowed the idea of unsetting the enviorment variable from R: rJava package install failing.

casting Object array to Integer array error

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;

you try to cast an Array of Object to cast into Array of Integer. You cant do it. This type of downcast is not permitted.

You can make an array of Integer, and after that copy every value of the first array into second array.

How can I use Timer (formerly NSTimer) in Swift?

I tried to do in a NSObject Class and this worked for me:

DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(300)) {  
print("Bang!") }

How to loop through each and every row, column and cells in a GridView and get its value

As it's said by "Tim Schmelter" this is the best way : just change in it's code the seconde loop ( GridView2.Columns[i].Count by row.Cells.Count ) so it looks seem's that:

foreach(GridViewRow row in GridView2.Rows)
{
    for(int i = 0; i < GridView2.Columns.Count; i++)
    {
        String header = GridView2.Columns[i].HeaderText;
        String cellText = row.Cells[i].Text;
    }
}

thank you.

how to customise input field width in bootstrap 3

<div class="form-group">
                    <div class="input-group col-md-5">
                    <div class="input-group-addon">
                    <span class="glyphicon glyphicon-envelope"></span> 
            </div>
                        <input class="form-control" type="text" name="text" placeholder="Enter Your Email Id" width="50px">

                    </div>
                    <input type="button" name="SIGNUP" value="SIGNUP">
            </div>

How to present UIActionSheet iOS Swift?

Updated for Swift 3.x, Swift 4.x, Swift 5.x

// create an actionSheet
let actionSheetController: UIAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

// create an action
let firstAction: UIAlertAction = UIAlertAction(title: "First Action", style: .default) { action -> Void in

    print("First Action pressed")
}

let secondAction: UIAlertAction = UIAlertAction(title: "Second Action", style: .default) { action -> Void in

    print("Second Action pressed")
}

let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in }

// add actions
actionSheetController.addAction(firstAction)
actionSheetController.addAction(secondAction)
actionSheetController.addAction(cancelAction)


// present an actionSheet...
// present(actionSheetController, animated: true, completion: nil)   // doesn't work for iPad

actionSheetController.popoverPresentationController?.sourceView = yourSourceViewName // works for both iPhone & iPad

present(actionSheetController, animated: true) {
    print("option menu presented")
}

enter image description here

C# '@' before a String

As a side note, you also should keep in mind that "escaping" means "using the back-slash as an indicator for special characters". You can put an end of line in a string doing that, for instance:

String foo = "Hello\

There";

Evaluating a mathematical expression in a string

Use eval in a clean namespace:

>>> ns = {'__builtins__': None}
>>> eval('2 ** 4', ns)
16

The clean namespace should prevent injection. For instance:

>>> eval('__builtins__.__import__("os").system("echo got through")', ns)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute '__import__'

Otherwise you would get:

>>> eval('__builtins__.__import__("os").system("echo got through")')
got through
0

You might want to give access to the math module:

>>> import math
>>> ns = vars(math).copy()
>>> ns['__builtins__'] = None
>>> eval('cos(pi/3)', ns)
0.50000000000000011

How to POST a FORM from HTML to ASPX page

You sure can. Create an HTML page with the form in it that will contain the necessary components from the login.aspx page (i.e. username, etc), and make sure they have the same IDs. For you action, make sure it's a post.

You might have to do some code on the login.aspx page in the Page_Load function to read the form (in the Request.Form object) and call the appropriate functions to log the user in, but other than that, you should have access to the form, and can do what you want with it.

How to read files and stdout from a running Docker container

A bit late but this is what I'm doing with journald. It's pretty powerful.

You need to be running your docker containers on an OS with systemd-journald.

docker run -d --log-driver=journald myapp

This pipes the whole lot into host's journald which takes care of stuff like log pruning, storage format etc and gives you some cool options for viewing them:

journalctl CONTAINER_NAME=myapp -f

which will feed it to your console as it is logged,

journalctl CONTAINER_NAME=myapp > output.log

which gives you the whole lot in a file to take away, or

journalctl CONTAINER_NAME=myapp --since=17:45

Plus you can still see the logs via docker logs .... if that's your preference.

No more > my.log or -v "/apps/myapp/logs:/logs" etc

Empty responseText from XMLHttpRequest

The browser is preventing you from cross-site scripting.

If the url is outside of your domain, then you need to do this on the server side or move it into your domain.

Font.createFont(..) set color and size (java.awt.Font)

Because font doesn't have color, you need a panel to make a backgound color and give the foreground color for both JLabel (if you use JLabel) and JPanel to make font color, like example below :

JLabel lblusr = new JLabel("User name : ");
lblusr.setForeground(Color.YELLOW);

JPanel usrPanel = new JPanel();
Color maroon = new Color (128, 0, 0);
usrPanel.setBackground(maroon);
usrPanel.setOpaque(true);
usrPanel.setForeground(Color.YELLOW);
usrPanel.add(lblusr);

The background color of label is maroon with yellow font color.

Creating a copy of a database in PostgreSQL

For those still interested, I have come up with a bash script that does (more or less) what the author wanted. I had to make a daily business database copy on a production system, this script seems to do the trick. Remember to change the database name/user/pw values.

#!/bin/bash

if [ 1 -ne $# ]
then
  echo "Usage `basename $0` {tar.gz database file}"
  exit 65;
fi

if [ -f "$1" ]
then
  EXTRACTED=`tar -xzvf $1`
  echo "using database archive: $EXTRACTED";
else
  echo "file $1 does not exist"
  exit 1
fi


PGUSER=dbuser
PGPASSWORD=dbpw
export PGUSER PGPASSWORD

datestr=`date +%Y%m%d`


dbname="dbcpy_$datestr"
createdbcmd="CREATE DATABASE $dbname WITH OWNER = postgres ENCODING = 'UTF8' TABLESPACE = pg_default LC_COLLATE = 'en_US.UTF-8' LC_CTYPE = 'en_US.UTF-8' CONNECTION LIMIT = -1;"
dropdbcmp="DROP DATABASE $dbname"

echo "creating database $dbname"
psql -c "$createdbcmd"

rc=$?
if [[ $rc != 0 ]] ; then
  rm -rf "$EXTRACTED"
  echo "error occured while creating database $dbname ($rc)"
  exit $rc
fi


echo "loading data into database"
psql $dbname < $EXTRACTED > /dev/null

rc=$?

rm -rf "$EXTRACTED"

if [[ $rc != 0 ]] ; then
  psql -c "$dropdbcmd"
  echo "error occured while loading data to database $dbname ($rc)"
  exit $rc
fi


echo "finished OK"

Finding repeated words on a string and counting the repetitions

It may help you somehow.

String st="I am am not the one who is thinking I one thing at time";
String []ar = st.split("\\s");
Map<String, Integer> mp= new HashMap<String, Integer>();
int count=0;

for(int i=0;i<ar.length;i++){
    count=0;

    for(int j=0;j<ar.length;j++){
        if(ar[i].equals(ar[j])){
        count++;                
        }
    }

    mp.put(ar[i], count);
}

System.out.println(mp);

jquery change div text

best and simple way is to put title inside a span and replace then.

'<div id="'+div_id+'" class="widget" style="height:60px;width:110px">\n\
        <div class="widget-head ui-widget-header" 
                style="cursor:move;height:20px;width:130px">'+
     '<span id="'+span_id+'" style="float:right; cursor:pointer" 
            class="dialog_link ui-icon ui-icon-newwin ui-icon-pencil"></span>' +
      '<span id="spTitle">'+
      dialog_title+ '</span>'
 '</div></div>

now you can simply use this:

$('#'+div_id+' .widget-head sp#spTitle').text("new dialog title");

How to convert a plain object into an ES6 Map?

The answer by Nils describes how to convert objects to maps, which I found very useful. However, the OP was also wondering where this information is in the MDN docs. While it may not have been there when the question was originally asked, it is now on the MDN page for Object.entries() under the heading Converting an Object to a Map which states:

Converting an Object to a Map

The new Map() constructor accepts an iterable of entries. With Object.entries, you can easily convert from Object to Map:

const obj = { foo: 'bar', baz: 42 }; 
const map = new Map(Object.entries(obj));
console.log(map); // Map { foo: "bar", baz: 42 }

Zoom to fit all markers in Mapbox or Leaflet

var group = new L.featureGroup([marker1, marker2, marker3]);

map.fitBounds(group.getBounds());

See the documentation for more info.

How can I get the Google cache age of any URL or web page?

This one good also to view cachepage http://www.cachepage.net

  1. Cache page view via google: webcache.googleusercontent.com/search?q=cache: Your url

  2. Cache page view via archive.org: web.archive.org/web/*/Your url

When I run `npm install`, it returns with `ERR! code EINTEGRITY` (npm 5.3.0)

You should check Connection-specific DNS Suffix when type “ipconfig” or “ifconfig” in terminal

What is the difference between null and System.DBNull.Value?

Well, null is not an instance of any type. Rather, it is an invalid reference.

However, System.DbNull.Value, is a valid reference to an instance of System.DbNull (System.DbNull is a singleton and System.DbNull.Value gives you a reference to the single instance of that class) that represents nonexistent* values in the database.

*We would normally say null, but I don't want to confound the issue.

So, there's a big conceptual difference between the two. The keyword null represents an invalid reference. The class System.DbNull represents a nonexistent value in a database field. In general, we should try avoid using the same thing (in this case null) to represent two very different concepts (in this case an invalid reference versus a nonexistent value in a database field).

Keep in mind, this is why a lot of people advocate using the null object pattern in general, which is exactly what System.DbNull is an example of.

SQL Server datetime LIKE select?

Try this

SELECT top 10 * from record WHERE  IsActive = 1 and CONVERT(VARCHAR, register_date, 120) LIKE '2020-01%'

Convert String to Calendar Object in Java

SimpleDateFormat is great, just note that HH is different from hh when working with hours. HH will return 24 hour based hours and hh will return 12 hour based hours.

For example, the following will return 12 hour time:

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");

While this will return 24 hour time:

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

Remove all whitespaces from NSString

This for me is the best way SWIFT

        let myString = "  ciao   \n              ciao     "
        var finalString = myString as NSString

        for character in myString{
        if character == " "{

            finalString = finalString.stringByReplacingOccurrencesOfString(" ", withString: "")

        }else{
            finalString = finalString.stringByReplacingOccurrencesOfString("\n", withString: "")

        }

    }
     println(finalString)

and the result is : ciaociao

But the trick is this!

 extension String {

    var NoWhiteSpace : String {

    var miaStringa = self as NSString

    if miaStringa.containsString(" "){

      miaStringa =  miaStringa.stringByReplacingOccurrencesOfString(" ", withString: "")
    }
        return miaStringa as String

    }
}

let myString = "Ciao   Ciao       Ciao".NoWhiteSpace  //CiaoCiaoCiao

How do I configure different environments in Angular.js?

One cool solution might be separating all environment-specific values into some separate angular module, that all other modules depend on:

angular.module('configuration', [])
       .constant('API_END_POINT','123456')
       .constant('HOST','localhost');

Then your modules that need those entries can declare a dependency on it:

angular.module('services',['configuration'])
       .factory('User',['$resource','API_END_POINT'],function($resource,API_END_POINT){
           return $resource(API_END_POINT + 'user');
       });

Now you could think about further cool stuff:

The module, that contains the configuration can be separated into configuration.js, that will be included at your page.

This script can be easily edited by each of you, as long as you don’t check this separate file into git. But it's easier to not check in the configuration if it is in a separate file. Also, you could branch it locally.

Now, if you have a build-system, like ANT or Maven, your further steps could be implementing some placeholders for the values API_END_POINT, that will be replaced during build-time, with your specific values.

Or you have your configuration_a.js and configuration_b.js and decide at the backend which to include.

How to make a simple modal pop up form using jquery and html?

I have placed here complete bins for above query. you can check demo link too.

Demo: http://codebins.com/bin/4ldqp78/2/How%20to%20make%20a%20simple%20modal%20pop

HTML

<div id="panel">
  <input type="button" class="button" value="1" id="btn1">
  <input type="button" class="button" value="2" id="btn2">
  <input type="button" class="button" value="3" id="btn3">
  <br>
  <input type="text" id="valueFromMyModal">
  <!-- Dialog Box-->
  <div class="dialog" id="myform">
    <form>
      <label id="valueFromMyButton">
      </label>
      <input type="text" id="name">
      <div align="center">
        <input type="button" value="Ok" id="btnOK">
      </div>
    </form>
  </div>
</div>

JQuery

$(function() {
    $(".button").click(function() {
        $("#myform #valueFromMyButton").text($(this).val().trim());
        $("#myform input[type=text]").val('');
        $("#myform").show(500);
    });
    $("#btnOK").click(function() {
        $("#valueFromMyModal").val($("#myform input[type=text]").val().trim());
        $("#myform").hide(400);
    });
});

CSS

.button{
  border:1px solid #333;
  background:#6479fd;
}
.button:hover{
  background:#a4a9fd;
}
.dialog{
  border:5px solid #666;
  padding:10px;
  background:#3A3A3A;
  position:absolute;
  display:none;
}
.dialog label{
  display:inline-block;
  color:#cecece;
}
input[type=text]{
  border:1px solid #333;
  display:inline-block;
  margin:5px;
}
#btnOK{
  border:1px solid #000;
  background:#ff9999;
  margin:5px;
}

#btnOK:hover{
  border:1px solid #000;
  background:#ffacac;
}

Demo: http://codebins.com/bin/4ldqp78/2/How%20to%20make%20a%20simple%20modal%20pop

Defining a variable with or without export

export NAME=value for settings and variables that have meaning to a subprocess.

NAME=value for temporary or loop variables private to the current shell process.

In more detail, export marks the variable name in the environment that copies to a subprocesses and their subprocesses upon creation. No name or value is ever copied back from the subprocess.

  • A common error is to place a space around the equal sign:

    $ export FOO = "bar"  
    bash: export: `=': not a valid identifier
    
  • Only the exported variable (B) is seen by the subprocess:

    $ A="Alice"; export B="Bob"; echo "echo A is \$A. B is \$B" | bash
    A is . B is Bob
    
  • Changes in the subprocess do not change the main shell:

    $ export B="Bob"; echo 'B="Banana"' | bash; echo $B
    Bob
    
  • Variables marked for export have values copied when the subprocess is created:

    $ export B="Bob"; echo '(sleep 30; echo "Subprocess 1 has B=$B")' | bash &
    [1] 3306
    $ B="Banana"; echo '(sleep 30; echo "Subprocess 2 has B=$B")' | bash 
    Subprocess 1 has B=Bob
    Subprocess 2 has B=Banana
    [1]+  Done         echo '(sleep 30; echo "Subprocess 1 has B=$B")' | bash
    
  • Only exported variables become part of the environment (man environ):

     $ ALICE="Alice"; export BOB="Bob"; env | grep "ALICE\|BOB"
     BOB=Bob
    

So, now it should be as clear as is the summer's sun! Thanks to Brain Agnew, alexp, and William Prusell.

How to get item's position in a list?

If your list got large enough and you only expected to find the value in a sparse number of indices, consider that this code could execute much faster because you don't have to iterate every value in the list.

lookingFor = 1
i = 0
index = 0
try:
  while i < len(testlist):
    index = testlist.index(lookingFor,i)
    i = index + 1
    print index
except ValueError: #testlist.index() cannot find lookingFor
  pass

If you expect to find the value a lot you should probably just append "index" to a list and print the list at the end to save time per iteration.

Javascript reduce() on Object

One option would be to reduce the keys():

var o = { 
    a: {value:1}, 
    b: {value:2}, 
    c: {value:3} 
};

Object.keys(o).reduce(function (previous, key) {
    return previous + o[key].value;
}, 0);

With this, you'll want to specify an initial value or the 1st round will be 'a' + 2.

If you want the result as an Object ({ value: ... }), you'll have to initialize and return the object each time:

Object.keys(o).reduce(function (previous, key) {
    previous.value += o[key].value;
    return previous;
}, { value: 0 });

Laravel 5.4 create model, controller and migration in single artisan command

Laravel 5.4 You can use

 php artisan make:model --migration --controller --resource Test

This will create 1) Model 2) controller with default resource function 3) Migration file

And Got Answer

Model created successfully.

Created Migration: 2018_04_30_055346_create_tests_table

Controller created successfully.

Understanding ibeacon distancing

It's possible, but it depends on the power output of the beacon you're receiving, other rf sources nearby, obstacles and other environmental factors. Best thing to do is try it out in the environment you're interested in.

Column/Vertical selection with Keyboard in SublimeText 3

Commenting just so people can have a solution to the intended question.

You can do what you are wanting but it isn't quite as nice as Notepad++ but it may work for small solutions decently enough.

In sublime if you hold ctrl, or mac equiv., and select the word/characters you want on a single line with the mouse and still holding ctrl go to another line and select the word/characters you want on that line it will be additive and you will build your selection. I mainly use notepadd++ as my extractor and data cleanup and sublime for actual development.

The other way is if your columns are in perfect alignment you can simply middle click on windows or option + click on mac and this enables you to select text in a square like fashion, Columns, inside the lines of text.

Postgresql: Scripting psql execution with password

I find, that psql show password prompt even you define PGPASSWORD variable, but you can specify -w option for psql to omit password prompt.

How to echo out the values of this array?

foreach ($array as $key => $val) {
   echo $val;
}

What is the difference between POST and GET?

POST and GET are two HTTP request methods. GET is usually intended to retrieve some data, and is expected to be idempotent (repeating the query does not have any side-effects) and can only send limited amounts of parameter data to the server. GET requests are often cached by default by some browsers if you are not careful.

POST is intended for changing the server state. It carries more data, and repeating the query is allowed (and often expected) to have side-effects such as creating two messages instead of one.

[INSTALL_FAILED_NO_MATCHING_ABIS: Failed to extract native libraries, res=-113]

July 25, 2019 :

I was facing this issue in Android Studio 3.0.1 :

After checking lots of posts, here is Fix which works:

Go to module build.gradle and within Android block add this script:

splits {
    abi {
        enable true
        reset()
        include 'x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'mips', 'mips64', 'arm64-v8a'
        universalApk true
    }
}

Simple Solution. Feel free to comment. Thanks.

Get list of all tables in Oracle?

select * from dba_tables

gives all the tables of all the users only if the user with which you logged in is having the sysdba privileges.

Entity Framework Provider type could not be loaded?

I've created a static "startup" file and added the code to force the DLL to be copied to the bin folder in it as a way to separate this 'configuration'.


[DbConfigurationType(typeof(DbContextConfiguration))] public static class Startup { }

public class DbContextConfiguration : DbConfiguration
{
    public DbContextConfiguration()
    {
        // This is needed to force the EntityFramework.SqlServer DLL to be copied to the bin folder
        SetProviderServices(SqlProviderServices.ProviderInvariantName, SqlProviderServices.Instance);
    }
}

How Does Modulus Divison Work

The modulus operator takes a division statement and returns whatever is left over from that calculation, the "remaining" data, so to speak, such as 13 / 5 = 2. Which means, there is 3 left over, or remaining from that calculation. Why? because 2 * 5 = 10. Thus, 13 - 10 = 3.

The modulus operator does all that calculation for you, 13 % 5 = 3.

"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

The below code solved my problem :

request.ProtocolVersion = HttpVersion.Version10; // THIS DOES THE TRICK
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

Create Carriage Return in PHP String?

Fragment PHP (in console Cloud9):

echo "\n";
echo "1: first_srt=1\nsecnd_srt=2\n";
echo "\n";
echo '2: first_srt=1\nsecnd_srt=2\n';
echo "\n";
echo "==============\n";
echo "\n";

resulting output:

  1: first_srt=1
  secnd_srt=2

  2: first_srt=1\nsecnd_srt=2\n
  ==============

Difference between 1 and 2: " versus '

How to find all the subclasses of a class given its name?

How can I find all subclasses of a class given its name?

We can certainly easily do this given access to the object itself, yes.

Simply given its name is a poor idea, as there can be multiple classes of the same name, even defined in the same module.

I created an implementation for another answer, and since it answers this question and it's a little more elegant than the other solutions here, here it is:

def get_subclasses(cls):
    """returns all subclasses of argument, cls"""
    if issubclass(cls, type):
        subclasses = cls.__subclasses__(cls)
    else:
        subclasses = cls.__subclasses__()
    for subclass in subclasses:
        subclasses.extend(get_subclasses(subclass))
    return subclasses

Usage:

>>> import pprint
>>> list_of_classes = get_subclasses(int)
>>> pprint.pprint(list_of_classes)
[<class 'bool'>,
 <enum 'IntEnum'>,
 <enum 'IntFlag'>,
 <class 'sre_constants._NamedIntConstant'>,
 <class 'subprocess.Handle'>,
 <enum '_ParameterKind'>,
 <enum 'Signals'>,
 <enum 'Handlers'>,
 <enum 'RegexFlag'>]

How Can I Set the Default Value of a Timestamp Column to the Current Timestamp with Laravel Migrations?

This is how you do it, I have checked it and it works on my Laravel 4.2.

$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));

Hope this helps.

How can I fix "Design editor is unavailable until a successful build" error?

  1. First, find your build.gradle in your all modules in project, include app/build.gradle. Find the compileSdkVersion inside android tag, in this case, compile sdk version is 30:

In this case, SDK version is 30

  1. Next, open SDK Manager > SDK Platforms, check correct version then install selected platforms. After installed, go to menu File > Sync project with Gradle files....

Install the API version which module requires

This issue often appear when project has many modules, each module use different compile SDK version, so app may be able to build but IDE have some issue while processing your resources.

Moving Git repository content to another repository preserving history

I think the commands you are looking for are:

cd repo2
git checkout master
git remote add r1remote **url-of-repo1**
git fetch r1remote
git merge r1remote/master --allow-unrelated-histories
git remote rm r1remote

After that repo2/master will contain everything from repo2/master and repo1/master, and will also have the history of both of them.

How to "fadeOut" & "remove" a div in jQuery?

Have you tried this?

$("#notification").fadeOut(300, function(){ 
    $(this).remove();
});

That is, using the current this context to target the element in the inner function and not the id. I use this pattern all the time - it should work.

How do I push a local repo to Bitbucket using SourceTree without creating a repo on bitbucket first?

As this video illustrates, creating a repo online first is the usual way to go.

The SourceTree Release Notes do mention for SourceTree 1.5+:

Support creating new repositories under team / organisation accounts in Bitbucket.

So while there is no "publishing" feature, you could create your online repo from SourceTree.

The blog post "SourceTree for Windows 1.2 is here" (Sept 2013) also mention:

Now you can configure your Bitbucket, Stash and GitHub accounts in SourceTree and instantly see all your repositories on those services. Easily clone them, open the project on the web, and even create new repositories on the remote service without ever leaving SourceTree.
You’ll find it in the menu under View > Show Hosted Repositories, or using the new button at the bottom right of the bookmarks panel.

http://blog.sourcetreeapp.com/files/2013/09/hostedrepowindow.png

How to manually set an authenticated user in Spring Security / SpringMVC

Ultimately figured out the root of the problem.

When I create the security context manually no session object is created. Only when the request finishes processing does the Spring Security mechanism realize that the session object is null (when it tries to store the security context to the session after the request has been processed).

At the end of the request Spring Security creates a new session object and session ID. However this new session ID never makes it to the browser because it occurs at the end of the request, after the response to the browser has been made. This causes the new session ID (and hence the Security context containing my manually logged on user) to be lost when the next request contains the previous session ID.

How to convert index of a pandas dataframe into a column?

either:

df['index1'] = df.index

or, .reset_index:

df.reset_index(level=0, inplace=True)

so, if you have a multi-index frame with 3 levels of index, like:

>>> df
                       val
tick       tag obs        
2016-02-26 C   2    0.0139
2016-02-27 A   2    0.5577
2016-02-28 C   6    0.0303

and you want to convert the 1st (tick) and 3rd (obs) levels in the index into columns, you would do:

>>> df.reset_index(level=['tick', 'obs'])
          tick  obs     val
tag                        
C   2016-02-26    2  0.0139
A   2016-02-27    2  0.5577
C   2016-02-28    6  0.0303

Error: Cannot find module html

Install ejs if it is not.

npm install ejs

Then after just paste below two lines in your main file. (like app.js, main.js)

app.set('view engine', 'html');

app.engine('html', require('ejs').renderFile);

SQL Server 2005 Using DateAdd to add a day to a date

DECLARE @date DateTime
SET @date = GetDate()
SET @date = DateAdd(day, 1, @date)

SELECT @date

How can I compare two time strings in the format HH:MM:SS?

Try this code.

var startTime = "05:01:20";
var endTime = "09:00:00";
var regExp = /(\d{1,2})\:(\d{1,2})\:(\d{1,2})/;
if(parseInt(endTime .replace(regExp, "$1$2$3")) > parseInt(startTime .replace(regExp, "$1$2$3"))){
alert("End time is greater");
}

AngularJS passing data to $http.get request

Here's a complete example of an HTTP GET request with parameters using angular.js in ASP.NET MVC:

CONTROLLER:

public class AngularController : Controller
{
    public JsonResult GetFullName(string name, string surname)
    {
        System.Diagnostics.Debugger.Break();
        return Json(new { fullName = String.Format("{0} {1}",name,surname) }, JsonRequestBehavior.AllowGet);
    }
}

VIEW:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script type="text/javascript">
    var myApp = angular.module("app", []);

    myApp.controller('controller', function ($scope, $http) {

        $scope.GetFullName = function (employee) {

            //The url is as follows - ControllerName/ActionName?name=nameValue&surname=surnameValue

            $http.get("/Angular/GetFullName?name=" + $scope.name + "&surname=" + $scope.surname).
            success(function (data, status, headers, config) {
                alert('Your full name is - ' + data.fullName);
            }).
            error(function (data, status, headers, config) {
                alert("An error occurred during the AJAX request");
            });

        }
    });

</script>

<div ng-app="app" ng-controller="controller">

    <input type="text" ng-model="name" />
    <input type="text" ng-model="surname" />
    <input type="button" ng-click="GetFullName()" value="Get Full Name" />
</div>

How to create timer events using C++ 11?

Made a simple implementation of what I believe to be what you want to achieve. You can use the class later with the following arguments:

  • int (milliseconds to wait until to run the code)
  • bool (if true it returns instantly and runs the code after specified time on another thread)
  • variable arguments (exactly what you'd feed to std::bind)

You can change std::chrono::milliseconds to std::chrono::nanoseconds or microseconds for even higher precision and add a second int and a for loop to specify for how many times to run the code.

Here you go, enjoy:

#include <functional>
#include <chrono>
#include <future>
#include <cstdio>

class later
{
public:
    template <class callable, class... arguments>
    later(int after, bool async, callable&& f, arguments&&... args)
    {
        std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));

        if (async)
        {
            std::thread([after, task]() {
                std::this_thread::sleep_for(std::chrono::milliseconds(after));
                task();
            }).detach();
        }
        else
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(after));
            task();
        }
    }

};

void test1(void)
{
    return;
}

void test2(int a)
{
    printf("%i\n", a);
    return;
}

int main()
{
    later later_test1(1000, false, &test1);
    later later_test2(1000, false, &test2, 101);

    return 0;
}

Outputs after two seconds:

101

Using IF ELSE in Oracle

IF is a PL/SQL construct. If you are executing a query, you are using SQL not PL/SQL.

In SQL, you can use a CASE statement in the query itself

SELECT DISTINCT a.item, 
                (CASE WHEN b.salesman = 'VIKKIE'
                      THEN 'ICKY'
                      ELSE b.salesman
                  END), 
                NVL(a.manufacturer,'Not Set') Manufacturer
  FROM inv_items a, 
       arv_sales b
 WHERE  a.co = '100'
   AND a.co = b.co
   AND A.ITEM_KEY = b.item_key   
   AND a.item LIKE 'BX%'
   AND b.salesman in ('01','15')
   AND trans_date BETWEEN to_date('010113','mmddrr')
                      and to_date('011713','mmddrr')
ORDER BY a.item

Since you aren't doing any aggregation, you don't want a GROUP BY in your query. Are you really sure that you need the DISTINCT? People often throw that in haphazardly or add it when they are missing a join condition rather than considering whether it is really necessary to do the extra work to identify and remove duplicates.

Why when I transfer a file through SFTP, it takes longer than FTP?

SFTP will almost always be significantly slower than FTP or FTPS (usually by several orders of magnitude). The reason for the difference is that there is a lot of additional packet, encryption and handshaking overhead inherent in the SSH2 protocol that FTP doesn't have to worry about. FTP is a very lean and comparatively simple protocol with almost no data transfer overhead, and the protocol was specifically designed for transferring files quickly. Encryption will slow FTP down, but not nearly to the level of SFTP.

SFTP runs over SSH2 and is much more susceptible to network latency and client and server machine resource constraints. This increased susceptibility is due to the extra data handshaking involved with every packet sent between the client and server, and with the additional complexity inherent in decoding an SSH2 packet. SSH2 was designed as a replacement for Telnet and other insecure remote shells, not for very high speed communications. The flexibility that SSH2 provides for securely packaging and transferring almost any type of data also contributes a great deal of additional complexity and overhead to the protocol.

However, it is still possible to get a data transfer rate of several MB/s between client and server using SFTP if the right network conditions are present. The following are items to check when trying to maximize SFTP transfer speeds:

Is there a firewall or network device inspecting or throttling SSH2 traffic on your network? That might be slowing things down. Check you firewall settings. We've had users report solving extremely slow SFTP file transfers by modifying their firewall rules. The SFTP client you use can make a big difference. Try several different SFTP clients and see if you get different results. Network latency will drastically affect SFTP. If the link you are on has a high degree of latency then that is going to be a problem for fast transfers. How powerful is the server machine? Encryption with SFTP is very intensive. Make sure you have a sufficiently powerful machine that isn't being overtaxed during SFTP file transfers (high CPU utilization).

See more: https://support.cerberusftp.com/hc/en-us/articles/203333215-Why-is-SSH2-SFTP-so-much-slower-than-FTP-and-FTPS-

Regular expression for matching HH:MM time format

You can try the following

^\d{1,2}([:.]?\d{1,2})?([ ]?[a|p]m)?$

It can detect the following patterns :

2300 
23:00 
4 am 
4am 
4pm 
4 pm
04:30pm 
04:30 pm 
4:30pm 
4:30 pm
04.30pm
04.30 pm
4.30pm
4.30 pm
23:59 
0000 
00:00

How to run docker-compose up -d at system start up?

If your docker.service enabled on system startup

$ sudo systemctl enable docker

and your services in your docker-compose.yml has

restart: always

all of the services run when you reboot your system if you run below command only once

docker-compose up -d

How to fix "set SameSite cookie to none" warning?

I ended up fixing our Ubuntu 18.04 / Apache 2.4.29 / PHP 7.2 install for Chrome 80 by installing mod_headers:

a2enmod headers

Adding the following directive to our Apache VirtualHost configurations:

Header edit Set-Cookie ^(.*)$ "$1; Secure; SameSite=None"

And restarting Apache:

service apache2 restart

In reviewing the docs (http://www.balkangreenfoundation.org/manual/en/mod/mod_headers.html) I noticed the "always" condition has certain situations where it does not work from the same pool of response headers. Thus not using "always" is what worked for me with PHP but the docs suggest that if you want to cover all your bases you could add the directive both with and without "always". I have not tested that.

Access VBA | How to replace parts of a string with another string

I was reading this thread and would like to add information even though it is surely no longer timely for the OP.

BiggerDon above points out the difficulty of rote replacing "North" with "N". A similar problem exists with "Avenue" to "Ave" (e.g. "Avenue of the Americas" becomes "Ave of the Americas": still understandable, but probably not what the OP wants.

The replace() function is entirely context-free, but addresses are not. A complete solution needs to have additional logic to interpret the context correctly, and then apply replace() as needed.

Databases commonly contain addresses, and so I wanted to point out that the generalized version of the OP's problem as applied to addresses within the United States has been addressed (humor!) by the Coding Accuracy Support System (CASS). CASS is a database tool that accepts a U.S. address and completes or corrects it to meet a standard set by the U.S. Postal Service. The Wikipedia entry https://en.wikipedia.org/wiki/Postal_address_verification has the basics, and more information is available at the Post Office: https://ribbs.usps.gov/index.cfm?page=address_info_systems

replacing NA's with 0's in R dataframe

What Tyler Rinker says is correct:

AQ2 <- airquality
AQ2[is.na(AQ2)] <- 0

will do just this.

What you are originally doing is that you are taking from airquality all those rows (cases) that are complete. So, all the cases that do not have any NA's in them, and keep only those.

Show div on scrollDown after 800px

You can also, do this.

$(window).on("scroll", function () {
   if ($(this).scrollTop() > 800) {
      #code here
   } else {
      #code here
   }
});

SQL WITH clause example

This has been fully answered here.

See Oracle's docs on SELECT to see how subquery factoring works, and Mark's example:

WITH employee AS (SELECT * FROM Employees)
SELECT * FROM employee WHERE ID < 20
UNION ALL
SELECT * FROM employee WHERE Sex = 'M'

How to POST JSON request using Apache HttpClient?

Apache HttpClient doesn't know anything about JSON, so you'll need to construct your JSON separately. To do so, I recommend checking out the simple JSON-java library from json.org. (If "JSON-java" doesn't suit you, json.org has a big list of libraries available in different languages.)

Once you've generated your JSON, you can use something like the code below to POST it

StringRequestEntity requestEntity = new StringRequestEntity(
    JSON_STRING,
    "application/json",
    "UTF-8");

PostMethod postMethod = new PostMethod("http://example.com/action");
postMethod.setRequestEntity(requestEntity);

int statusCode = httpClient.executeMethod(postMethod);

Edit

Note - The above answer, as asked for in the question, applies to Apache HttpClient 3.1. However, to help anyone looking for an implementation against the latest Apache client:

StringEntity requestEntity = new StringEntity(
    JSON_STRING,
    ContentType.APPLICATION_JSON);

HttpPost postMethod = new HttpPost("http://example.com/action");
postMethod.setEntity(requestEntity);

HttpResponse rawResponse = httpclient.execute(postMethod);

npm start error with create-react-app

I had the same error when running

npm start

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `react-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script.

I broke my head on several tabs and applying Solutions from other devs and nothing.

Until, even using Ubuntu, I closed my vscode and restarted my pc and all my problems were solved. (kkkk zueira) just this one.

Execution failed for task ':app:processDebugResources' even with latest build tools

Issue SOLVED by making library and app build.gradle same ... compileSdkVersion and buildToolsVersion.

library build.gradle and

android {

    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    .....
    .....
}

app build.gradle

android {

    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    .....
    .....
}

Class file for com.google.android.gms.internal.zzaja not found

I have a also same problem.Change old version of FirebaseAuth to newer version. for me I change "com.google.firebase:firebase-auth:11.4.0" to "com.google.firebase:firebase-auth:11.8.0"

How to convert string to XML using C#

Use LoadXml Method of XmlDocument;

string xml = "<head><body><Inner> welcome </head> </Inner> <Outer> Bye</Outer></body></head>";
xDoc.LoadXml(xml);

Attaching click event to a JQuery object not yet added to the DOM

Try this.... Replace body with parent selector

$('body').on('click', '#my-button', function () {
    console.log("yeahhhh!!! but this doesn't work for me :(");
});

Why is vertical-align:text-top; not working in CSS

position:absolute;
top:0px; 
margin:5px;

Solved my problem.

WCFTestClient The HTTP request is unauthorized with client authentication scheme 'Anonymous'

I didn't have control over the security configuration for the service I was calling into, but got the same error. I was able to fix my client as follows.

  1. In the config, set up the security mode:

    <security mode="TransportCredentialOnly">
      <transport clientCredentialType="Windows" proxyCredentialType="None" realm="" />
      <message clientCredentialType="UserName" algorithmSuite="Default" />
    </security>
    
  2. In the code, set the proxy class to allow impersonation (I added a reference to a service called customer):

    Customer_PortClient proxy = new Customer_PortClient();
    proxy.ClientCredentials.Windows.AllowedImpersonationLevel =    
             System.Security.Principal.TokenImpersonationLevel.Impersonation;
    

Convert pandas timezone-aware DateTimeIndex to naive timestamp, but in certain timezone

To answer my own question, this functionality has been added to pandas in the meantime. Starting from pandas 0.15.0, you can use tz_localize(None) to remove the timezone resulting in local time.
See the whatsnew entry: http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#timezone-handling-improvements

So with my example from above:

In [4]: t = pd.date_range(start="2013-05-18 12:00:00", periods=2, freq='H',
                          tz= "Europe/Brussels")

In [5]: t
Out[5]: DatetimeIndex(['2013-05-18 12:00:00+02:00', '2013-05-18 13:00:00+02:00'],
                       dtype='datetime64[ns, Europe/Brussels]', freq='H')

using tz_localize(None) removes the timezone information resulting in naive local time:

In [6]: t.tz_localize(None)
Out[6]: DatetimeIndex(['2013-05-18 12:00:00', '2013-05-18 13:00:00'], 
                      dtype='datetime64[ns]', freq='H')

Further, you can also use tz_convert(None) to remove the timezone information but converting to UTC, so yielding naive UTC time:

In [7]: t.tz_convert(None)
Out[7]: DatetimeIndex(['2013-05-18 10:00:00', '2013-05-18 11:00:00'], 
                      dtype='datetime64[ns]', freq='H')

This is much more performant than the datetime.replace solution:

In [31]: t = pd.date_range(start="2013-05-18 12:00:00", periods=10000, freq='H',
                           tz="Europe/Brussels")

In [32]: %timeit t.tz_localize(None)
1000 loops, best of 3: 233 µs per loop

In [33]: %timeit pd.DatetimeIndex([i.replace(tzinfo=None) for i in t])
10 loops, best of 3: 99.7 ms per loop

Make a table fill the entire window

You can use position like this to stretch an element across the parent container.

<table style="position: absolute; top: 0; bottom: 0; left: 0; right: 0;">
    <tr style="height: 25%; font-size: 180px;">
        <td>Region</td>
    </tr>
    <tr style="height: 75%; font-size: 540px;">
        <td>100.00%</td>
    </tr>
</table>

Make docker use IPv4 for port binding

For CentOS users,

I've got same issue on CentOS7 and setting net.ipv4.ip_forward to 1 solves the issue. Please, refer to Docker Networking Disabled: WARNING: IPv4 forwarding is disabled. Networking will not work for more details.

jquery how to empty input field

You can clear the input field by using $('#shares').val('');

Getters \ setters for dummies

In addition to @millimoose's answer, setters can also be used to update other values.

function Name(first, last) {
    this.first = first;
    this.last = last;
}

Name.prototype = {
    get fullName() {
        return this.first + " " + this.last;
    },

    set fullName(name) {
        var names = name.split(" ");
        this.first = names[0];
        this.last = names[1];
    }
};

Now, you can set fullName, and first and last will be updated and vice versa.

n = new Name('Claude', 'Monet')
n.first # "Claude"
n.last # "Monet"
n.fullName # "Claude Monet"
n.fullName = "Gustav Klimt"
n.first # "Gustav"
n.last # "Klimt"

Entity Framework: "Store update, insert, or delete statement affected an unexpected number of rows (0)."

The line [DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.None)] did the trick in my case:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;


[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int? SomeNumber { get; set; }

'No JUnit tests found' in Eclipse

If none of the other answers work for you, here's what worked for me.

Restart eclipse

I had source folder configured correctly, and unit tests correctly annotated but was still getting "No JUnit tests found", for one project. After a restart it worked. I was using STS 3.6.2 based of eclipse Luna 4.4.1

Spring JSON request getting 406 (not Acceptable)

<dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.0</version>
    </dependency>

i don't use ssl authentication and this jackson-databind contain jackson-core.jar and jackson-databind.jar, and then change the RequestMapping content like this:

@RequestMapping(value = "/id/{number}", produces = "application/json; charset=UTF-8", method = RequestMethod.GET)
public @ResponseBody Customer findCustomer(@PathVariable int number){
    Customer result = customerService.findById(number);
    return result;
}

attention: if your produces is not "application/json" type and i had not noticed this and got an 406 error, help this can help you out.

What's the difference between ISO 8601 and RFC 3339 Date Formats?

Is one just an extension?

Pretty much, yes - RFC 3339 is listed as a profile of ISO 8601. Most notably RFC 3339 specifies a complete representation of date and time (only fractional seconds are optional). The RFC also has some small, subtle differences. For example truncated representations of years with only two digits are not allowed -- RFC 3339 requires 4-digit years, and the RFC only allows a period character to be used as the decimal point for fractional seconds. The RFC also allows the "T" to be replaced by a space (or other character), while the standard only allows it to be omitted (and only when there is agreement between all parties using the representation).

I wouldn't worry too much about the differences between the two, but on the off-chance your use case runs in to them, it'd be worth your while taking a glance at:

Docker expose all ports or range of ports from 7000 to 8000

Since Docker 1.5 you can now expose a range of ports to other linked containers using:

The Dockerfile EXPOSE command:

EXPOSE 7000-8000

or The Docker run command:

docker run --expose=7000-8000

Or instead you can publish a range of ports to the host machine via Docker run command:

docker run -p 7000-8000:7000-8000

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

There are two issues here.

Firstly, you can't use the [] syntax like you may be able to in other languages. Square brackets only apply to arrays in Java, and so can only be used with integer indexes.

data.put is correct but that is a statement and so must exist in a method block. Only field declarations can exist at the class level. Here is an example where everything is within the local scope of a method:

public class Data {
     public static void main(String[] args) {
         Map<String, String> data = new HashMap<String, String>();
         data.put("John", "Taxi Driver");
         data.put("Mark", "Professional Killer");
     }
 }

If you want to initialize a map as a static field of a class then you can use Map.of, since Java 9:

public class Data {
    private static final Map<String, String> DATA = Map.of("John", "Taxi Driver");
}

Before Java 9, you can use a static initializer block to accomplish the same thing:

public class Data {
    private static final Map<String, String> DATA = new HashMap<>();

    static {
        DATA.put("John", "Taxi Driver");
    }
}

How to select date from datetime column?

You can use:

DATEDIFF ( day , startdate , enddate ) = 0

Or:

DATEPART( day, startdate ) = DATEPART(day, enddate)
AND 
DATEPART( month, startdate ) = DATEPART(month, enddate)
AND
DATEPART( year, startdate ) = DATEPART(year, enddate)

Or:

CONVERT(DATETIME,CONVERT(VARCHAR(12), startdate, 105)) = CONVERT(DATETIME,CONVERT(VARCHAR(12), enddate, 105))

Check if specific input file is empty

if ($_FILES['cover_image']['size'] == 0 && $_FILES['cover_image']['error'] == 0)
{ 
      // Code comes here
}

This thing works for me........

SQL Server default character encoding

If you need to know the default collation for a newly created database use:

SELECT SERVERPROPERTY('Collation')

This is the server collation for the SQL Server instance that you are running.

Video 100% width and height

This works for me for video in a div container.

_x000D_
_x000D_
.videoContainer _x000D_
{_x000D_
    position:absolute;_x000D_
    height:100%;_x000D_
    width:100%;_x000D_
    overflow: hidden;_x000D_
}_x000D_
_x000D_
.videoContainer video _x000D_
{_x000D_
    min-width: 100%;_x000D_
    min-height: 100%;_x000D_
}
_x000D_
_x000D_
_x000D_

Reference: http://www.codesynthesis.co.uk/tutorials/html-5-full-screen-and-responsive-videos

Setting width/height as percentage minus pixels

I use Jquery for this

function setSizes() {
   var containerHeight = $("#listContainer").height();
   $("#myList").height(containerHeight - 18);
}

then I bind the window resize to recalc it whenever the browser window is resized (if container's size changed with window resize)

$(window).resize(function() { setSizes(); });

Why am I getting "Received fatal alert: protocol_version" or "peer not authenticated" from Maven Central?

For setting java properties on Windows app server:

  • configure tomcat > run as admin
  • then add Java opts:

  • restart service.

Register 32 bit COM DLL to 64 bit Windows 7

put the dll in system32 or syswow32 directory, and use appropriate regsvr32 to register it. wiered that even though it gave failed to register error, I rebooted my WIN 7 64 AND my vb app loaded the dll just fine!!

Can we call the function written in one JavaScript in another JS file?

The function could be called as if it was in the same JS File as long as the file containing the definition of the function has been loaded before the first use of the function.

I.e.

File1.js

function alertNumber(number) {
    alert(number);
}

File2.js

function alertOne() {
     alertNumber("one");
}

HTML

<head>
....
    <script src="File1.js" type="text/javascript"></script> 
    <script src="File2.js" type="text/javascript"></script> 
....
</head>
<body>
....
    <script type="text/javascript">
       alertOne();
    </script>
....
</body>

The other way won't work. As correctly pointed out by Stuart Wakefield. The other way will also work.

HTML

<head>
....
    <script src="File2.js" type="text/javascript"></script> 
    <script src="File1.js" type="text/javascript"></script> 
....
</head>
<body>
....
    <script type="text/javascript">
       alertOne();
    </script>
....
</body>

What will not work would be:

HTML

<head>
....
    <script src="File2.js" type="text/javascript"></script> 
    <script type="text/javascript">
       alertOne();
    </script>
    <script src="File1.js" type="text/javascript"></script> 
....
</head>
<body>
....
</body>

Although alertOne is defined when calling it, internally it uses a function that is still not defined (alertNumber).

How to expand a list to function arguments in Python

It exists, but it's hard to search for. I think most people call it the "splat" operator.

It's in the documentation as "Unpacking argument lists".

You'd use it like this: foo(*values). There's also one for dictionaries:

d = {'a': 1, 'b': 2}
def foo(a, b):
    pass
foo(**d)

How to abort makefile if variable not set?

For simplicity and brevity:

$ cat Makefile
check-%:
        @: $(if $(value $*),,$(error $* is undefined))

bar:| check-foo
        echo "foo is $$foo"

With outputs:

$ make bar
Makefile:2: *** foo is undefined. Stop.
$ make bar foo="something"
echo "foo is $$foo"
foo is something

How to generate a HTML page dynamically using PHP?

It looks funny but it works.

<?php 
$file = 'newpage.html';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "<!doctype html><html>
<head><meta charset='utf-8'>
<title>new file</title>
</head><body><h3>New HTML file</h3>
</body></html>
";
// Write the contents back to the file
file_put_contents($file, $current);
?>

How to identify server IP address in PHP

I found this to work for me: GetHostByName("");

Running XAMPP v1.7.1 on Windows 7 running Apache webserver. Unfortunately it just give my gateway IP address.