Programs & Examples On #Combinations

A combination is a selection of objects from a larger collection in no particular order.

Generating combinations in c++

A simple way using std::next_permutation:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    int n, r;
    std::cin >> n;
    std::cin >> r;

    std::vector<bool> v(n);
    std::fill(v.end() - r, v.end(), true);

    do {
        for (int i = 0; i < n; ++i) {
            if (v[i]) {
                std::cout << (i + 1) << " ";
            }
        }
        std::cout << "\n";
    } while (std::next_permutation(v.begin(), v.end()));
    return 0;
}

or a slight variation that outputs the results in an easier to follow order:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
   int n, r;
   std::cin >> n;
   std::cin >> r;

   std::vector<bool> v(n);
   std::fill(v.begin(), v.begin() + r, true);

   do {
       for (int i = 0; i < n; ++i) {
           if (v[i]) {
               std::cout << (i + 1) << " ";
           }
       }
       std::cout << "\n";
   } while (std::prev_permutation(v.begin(), v.end()));
   return 0;
}

A bit of explanation:

It works by creating a "selection array" (v), where we place r selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v.


You can implement it if you note that for each level r you select a number from 1 to n.

In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance

#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>

using namespace std;

struct combinations
{
    typedef vector<int> combination_t;

    // initialize status
   combinations(int N, int R) :
       completed(N < 1 || R > N),
       generated(0),
       N(N), R(R)
   {
       for (int c = 1; c <= R; ++c)
           curr.push_back(c);
   }

   // true while there are more solutions
   bool completed;

   // count how many generated
   int generated;

   // get current and compute next combination
   combination_t next()
   {
       combination_t ret = curr;

       // find what to increment
       completed = true;
       for (int i = R - 1; i >= 0; --i)
           if (curr[i] < N - R + i + 1)
           {
               int j = curr[i] + 1;
               while (i <= R-1)
                   curr[i++] = j++;
               completed = false;
               ++generated;
               break;
           }

       return ret;
   }

private:

   int N, R;
   combination_t curr;
};

int main(int argc, char **argv)
{
    int N = argc >= 2 ? atoi(argv[1]) : 5;
    int R = argc >= 3 ? atoi(argv[2]) : 2;
    combinations cs(N, R);
    while (!cs.completed)
    {
        combinations::combination_t c = cs.next();
        copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
        cout << endl;
    }
    return cs.generated;
}

test output:

1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,

Statistics: combinations in Python

Using only standard library distributed with Python:

import itertools

def nCk(n, k):
    return len(list(itertools.combinations(range(n), k)))

How to get all possible combinations of a list’s elements?

3 functions:

  1. all combinations of n elements list
  2. all combinations of n elements list where order is not distinct
  3. all permutations
import sys

def permutations(a):
    return combinations(a, len(a))

def combinations(a, n):
    if n == 1:
        for x in a:
            yield [x]
    else:
        for i in range(len(a)):
            for x in combinations(a[:i] + a[i+1:], n-1):
                yield [a[i]] + x

def combinationsNoOrder(a, n):
    if n == 1:
        for x in a:
            yield [x]
    else:
        for i in range(len(a)):
            for x in combinationsNoOrder(a[:i], n-1):
                yield [a[i]] + x
    
if __name__ == "__main__":
    for s in combinations(list(map(int, sys.argv[2:])), int(sys.argv[1])):
        print(s)

All combinations of a list of lists

Nothing wrong with straight up recursion for this task, and if you need a version that works with strings, this might fit your needs:

combinations = []

def combine(terms, accum):
    last = (len(terms) == 1)
    n = len(terms[0])
    for i in range(n):
        item = accum + terms[0][i]
        if last:
            combinations.append(item)
        else:
            combine(terms[1:], item)


>>> a = [['ab','cd','ef'],['12','34','56']]
>>> combine(a, '')
>>> print(combinations)
['ab12', 'ab34', 'ab56', 'cd12', 'cd34', 'cd56', 'ef12', 'ef34', 'ef56']

How to calculate combination and permutation in R?

The Combinations package is not part of the standard CRAN set of packages, but is rather part of a different repository, omegahat. To install it you need to use

install.packages("Combinations", repos = "http://www.omegahat.org/R")

See the documentation at http://www.omegahat.org/Combinations/

Finding all possible combinations of numbers to reach a given sum

An iterative C++ stack solution for a flavor of this problem. Unlike some other iterative solutions, it doesn't make unnecessary copies of intermediate sequences.

// Given a positive integer, return all possible combinations of
// positive integers that sum up to it. 

vector<vector<int>> print_all_sum(int target){
    vector<vector<int>> output;
    vector<int> stack;

    int curr_min = 1;
    int sum = 0;
    while (curr_min < target) {
        sum += curr_min;
        if (sum >= target) {
            if (sum == target) {
                output.push_back(stack); // make a copy
                output.back().push_back(curr_min);
            }
            sum -= curr_min + stack.back();
            curr_min = stack.back() + 1;
            stack.pop_back();
        } else {
            stack.push_back(curr_min);
        }
    }

    return output;
}

How to combine two strings together in PHP?

combine two strings together in PHP?

$result = $data1 . ' ' . $data2;

Creating all possible k combinations of n items in C++

Behind the link below is a generic C# answer to this problem: How to format all combinations out of a list of objects. You can limit the results only to the length of k pretty easily.

https://stackoverflow.com/a/40417765/2613458

Algorithm to return all combinations of k elements from n

yet another recursive solution (you should be able to port this to use letters instead of numbers) using a stack, a bit shorter than most though:

stack = [] 
def choose(n,x):
   r(0,0,n+1,x)

def r(p, c, n,x):
   if x-c == 0:
      print stack
      return

   for i in range(p, n-(x-1)+c):
      stack.append(i)
      r(i+1,c+1,n,x)
      stack.pop()

4 choose 3 or I want all 3 combinations of numbers starting with 0 to 4

choose(4,3) 

[0, 1, 2]
[0, 1, 3]
[0, 1, 4]
[0, 2, 3]
[0, 2, 4]
[0, 3, 4]
[1, 2, 3]
[1, 2, 4]
[1, 3, 4]
[2, 3, 4]

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

python save image from url

import requests

img_data = requests.get(image_url).content
with open('image_name.jpg', 'wb') as handler:
    handler.write(img_data)

HTML5 record audio to file

Update now Chrome also supports MediaRecorder API from v47. The same thing to do would be to use it( guessing native recording method is bound to be faster than work arounds), the API is really easy to use, and you would find tons of answers as to how to upload a blob for the server.

Demo - would work in Chrome and Firefox, intentionally left out pushing blob to server...

Code Source


Currently, there are three ways to do it:

  1. as wav[ all code client-side, uncompressed recording], you can check out --> Recorderjs. Problem: file size is quite big, more upload bandwidth required.
  2. as mp3[ all code client-side, compressed recording], you can check out --> mp3Recorder. Problem: personally, I find the quality bad, also there is this licensing issue.
  3. as ogg [ client+ server(node.js) code, compressed recording, infinite hours of recording without browser crash ], you can check out --> recordOpus, either only client-side recording, or client-server bundling, the choice is yours.

    ogg recording example( only firefox):

    var mediaRecorder = new MediaRecorder(stream);
    mediaRecorder.start();  // to start recording.    
    ...
    mediaRecorder.stop();   // to stop recording.
    mediaRecorder.ondataavailable = function(e) {
        // do something with the data.
    }
    

    Fiddle Demo for ogg recording.

Gradle Sync failed could not find constraint-layout:1.0.0-alpha2

gradle com.android.tools.build:gradle:2.2.0-alpha6

constraint layout dependency com.android.support.constraint:constraint-layout:1.0.0-alpha4

works for me

onchange file input change img src and change image color

in your HTML : <input type="file" id="yourFile"> don't forget to reference your js file or put the following script between <script></script> in your script :

var fileToRead = document.getElementById("yourFile");

fileToRead.addEventListener("change", function(event) {
    var files = fileToRead.files;
    if (files.length) {
        console.log("Filename: " + files[0].name);
        console.log("Type: " + files[0].type);
        console.log("Size: " + files[0].size + " bytes");
    }

}, false);

How to save a dictionary to a file?

Pickle is probably the best option, but in case anyone wonders how to save and load a dictionary to a file using NumPy:

import numpy as np

# Save
dictionary = {'hello':'world'}
np.save('my_file.npy', dictionary) 

# Load
read_dictionary = np.load('my_file.npy',allow_pickle='TRUE').item()
print(read_dictionary['hello']) # displays "world"

FYI: NPY file viewer

ggplot combining two plots from different data.frames

The only working solution for me, was to define the data object in the geom_line instead of the base object, ggplot.

Like this:

ggplot() + 
geom_line(data=Data1, aes(x=A, y=B), color='green') + 
geom_line(data=Data2, aes(x=C, y=D), color='red')

instead of

ggplot(data=Data1, aes(x=A, y=B), color='green') + 
geom_line() + 
geom_line(data=Data2, aes(x=C, y=D), color='red')

More info here

How to assign text size in sp value using java code

You can use a DisplayMetrics object to help convert between pixels and scaled pixels with the scaledDensity attribute.

DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
pixelSize = (int)scaledPixelSize * dm.scaledDensity; 

How do I associate file types with an iPhone application?

File type handling is new with iPhone OS 3.2, and is different than the already-existing custom URL schemes. You can register your application to handle particular document types, and any application that uses a document controller can hand off processing of these documents to your own application.

For example, my application Molecules (for which the source code is available) handles the .pdb and .pdb.gz file types, if received via email or in another supported application.

To register support, you will need to have something like the following in your Info.plist:

<key>CFBundleDocumentTypes</key>
<array>
    <dict>
        <key>CFBundleTypeIconFiles</key>
        <array>
            <string>Document-molecules-320.png</string>
            <string>Document-molecules-64.png</string>
        </array>
        <key>CFBundleTypeName</key>
        <string>Molecules Structure File</string>
        <key>CFBundleTypeRole</key>
        <string>Viewer</string>
        <key>LSHandlerRank</key>
        <string>Owner</string>
        <key>LSItemContentTypes</key>
        <array>
            <string>com.sunsetlakesoftware.molecules.pdb</string>
            <string>org.gnu.gnu-zip-archive</string>
        </array>
    </dict>
</array>

Two images are provided that will be used as icons for the supported types in Mail and other applications capable of showing documents. The LSItemContentTypes key lets you provide an array of Uniform Type Identifiers (UTIs) that your application can open. For a list of system-defined UTIs, see Apple's Uniform Type Identifiers Reference. Even more detail on UTIs can be found in Apple's Uniform Type Identifiers Overview. Those guides reside in the Mac developer center, because this capability has been ported across from the Mac.

One of the UTIs used in the above example was system-defined, but the other was an application-specific UTI. The application-specific UTI will need to be exported so that other applications on the system can be made aware of it. To do this, you would add a section to your Info.plist like the following:

<key>UTExportedTypeDeclarations</key>
<array>
    <dict>
        <key>UTTypeConformsTo</key>
        <array>
            <string>public.plain-text</string>
            <string>public.text</string>
        </array>
        <key>UTTypeDescription</key>
        <string>Molecules Structure File</string>
        <key>UTTypeIdentifier</key>
        <string>com.sunsetlakesoftware.molecules.pdb</string>
        <key>UTTypeTagSpecification</key>
        <dict>
            <key>public.filename-extension</key>
            <string>pdb</string>
            <key>public.mime-type</key>
            <string>chemical/x-pdb</string>
        </dict>
    </dict>
</array>

This particular example exports the com.sunsetlakesoftware.molecules.pdb UTI with the .pdb file extension, corresponding to the MIME type chemical/x-pdb.

With this in place, your application will be able to handle documents attached to emails or from other applications on the system. In Mail, you can tap-and-hold to bring up a list of applications that can open a particular attachment.

When the attachment is opened, your application will be started and you will need to handle the processing of this file in your -application:didFinishLaunchingWithOptions: application delegate method. It appears that files loaded in this manner from Mail are copied into your application's Documents directory under a subdirectory corresponding to what email box they arrived in. You can get the URL for this file within the application delegate method using code like the following:

NSURL *url = (NSURL *)[launchOptions valueForKey:UIApplicationLaunchOptionsURLKey];

Note that this is the same approach we used for handling custom URL schemes. You can separate the file URLs from others by using code like the following:

if ([url isFileURL])
{
    // Handle file being passed in
}
else
{
    // Handle custom URL scheme
}

How to display a range input slider vertically

First, set height greater than width. In theory, this is all you should need. The HTML5 Spec suggests as much:

... the UA determined the orientation of the control from the ratio of the style-sheet-specified height and width properties.

Opera had it implemented this way, but Opera is now using WebKit Blink. As of today, no browser implements a vertical slider based solely on height being greater than width.

Regardless, setting height greater than width is needed to get the layout right between browsers. Applying left and right padding will also help with layout and positioning.

For Chrome, use -webkit-appearance: slider-vertical.

For IE, use writing-mode: bt-lr.

For Firefox, add an orient="vertical" attribute to the html. Pity that they did it this way. Visual styles should be controlled via CSS, not HTML.

_x000D_
_x000D_
input[type=range][orient=vertical]
{
    writing-mode: bt-lr; /* IE */
    -webkit-appearance: slider-vertical; /* WebKit */
    width: 8px;
    height: 175px;
    padding: 0 5px;
}
_x000D_
<input type="range" orient="vertical" />
_x000D_
_x000D_
_x000D_


Disclaimers:

This solution is based on current browser implementations of as yet undefined or unfinalized CSS properties. If you intend to use it in your code, be prepared to make code adjustments as newer browser versions are released and w3c recommendations are completed.

MDN contains an explicit warning against using -webkit-appearance on the web:

Do not use this property on Web sites: not only is it non-standard, but its behavior change from one browser to another. Even the keyword none has not the same behavior on each form element on different browsers, and some doesn't support it at all.

The caption for the vertical slider demo in the IE documentation erroneously indicates that setting height greater than width will display a range slider vertically, but this does not work. In the code section, it plainly does not set height or width, and instead uses writing-mode. The writing-mode property, as implemented by IE, is very robust. Sadly, the values defined in the current working draft of the spec as of this writing, are much more limited. Should future versions of IE drop support of bt-lr in favor of the currently proposed vertical-lr (which would be the equivalent of tb-lr), the slider would display upside down. Most likely, future versions would extend the writing-mode to accept new values rather than drop support for existing values. But, it's good to know what you are dealing with.

How to discover number of *logical* cores on Mac OS X?

CLARIFICATION

When this question was asked the OP did not say that he wanted the number of LOGICAL cores rather than the actual number of cores, so this answer logically (no pun intended) answers with a way to get the actual number of real physical cores, not the number that the OS tries to virtualize through hyperthreading voodoo.

UPDATE TO HANDLE FLAW IN YOSEMITE

Due to a weird bug in OS X Yosemite (and possibly newer versions, such as the upcoming El Capitan), I've made a small modification. (The old version still worked perfectly well if you just ignore STDERR, which is all the modification does for you.)


Every other answer given here either

  1. gives incorrect information
  2. gives no information, due to an error in the command implementation
  3. runs unbelievably slowly (taking the better part of a minute to complete), or
  4. gives too much data, and thus might be useful for interactive use, but is useless if you want to use the data programmatically (for instance, as input to a command like bundle install --jobs 3 where you want the number in place of 3 to be one less than the number of cores you've got, or at least not more than the number of cores)

The way to get just the number of cores, reliably, correctly, reasonably quickly, and without extra information or even extra characters around the answer, is this:

system_profiler SPHardwareDataType 2> /dev/null | grep 'Total Number of Cores' | cut -d: -f2 | tr -d ' '

Pandas rename column by position?

You can do this:

df.rename(columns={ df.columns[1]: "whatever" })

How to find cube root using Python?

You could use x ** (1. / 3) to compute the (floating-point) cube root of x.

The slight subtlety here is that this works differently for negative numbers in Python 2 and 3. The following code, however, handles that:

def is_perfect_cube(x):
    x = abs(x)
    return int(round(x ** (1. / 3))) ** 3 == x

print(is_perfect_cube(63))
print(is_perfect_cube(64))
print(is_perfect_cube(65))
print(is_perfect_cube(-63))
print(is_perfect_cube(-64))
print(is_perfect_cube(-65))
print(is_perfect_cube(2146689000)) # no other currently posted solution
                                   # handles this correctly

This takes the cube root of x, rounds it to the nearest integer, raises to the third power, and finally checks whether the result equals x.

The reason to take the absolute value is to make the code work correctly for negative numbers across Python versions (Python 2 and 3 treat raising negative numbers to fractional powers differently).

how to permit an array with strong parameters

This https://github.com/rails/strong_parameters seems like the relevant section of the docs:

The permitted scalar types are String, Symbol, NilClass, Numeric, TrueClass, FalseClass, Date, Time, DateTime, StringIO, IO, ActionDispatch::Http::UploadedFile and Rack::Test::UploadedFile.

To declare that the value in params must be an array of permitted scalar values map the key to an empty array:

params.permit(:id => [])

In my app, the category_ids are passed to the create action in an array

"category_ids"=>["", "2"],

Therefore, when declaring strong parameters, I explicitly set category_ids to be an array

params.require(:question).permit(:question_details, :question_content, :user_id, :accepted_answer_id, :province_id, :city, :category_ids => [])

Works perfectly now!

(IMPORTANT: As @Lenart notes in the comments, the array declarations must be at the end of the attributes list, otherwise you'll get a syntax error.)

SASS :not selector

I tried re-creating this, and .someclass.notip was being generated for me but .someclass:not(.notip) was not, for as long as I did not have the @mixin tip() defined. Once I had that, it all worked.

http://sassmeister.com/gist/9775949

$dropdown-width: 100px;
$comp-tip: true;

@mixin tip($pos:right) {

}

@mixin dropdown-pos($pos:right) {
  &:not(.notip) {
    @if $comp-tip == true{
      @if $pos == right {
        top:$dropdown-width * -0.6;
        background-color: #f00;
        @include tip($pos:$pos);
      }
    }
  }
  &.notip {
    @if $pos == right {
      top: 0;
      left:$dropdown-width * 0.8;
      background-color: #00f;
    }
  }
}

.someclass { @include dropdown-pos(); }

EDIT: http://sassmeister.com/ is a good place to debug your SASS because it gives you error messages. Undefined mixin 'tip'. it what I get when I remove @mixin tip($pos:right) { }

How to retrieve form values from HTTPPOST, dictionary or?

The answers are very good but there is another way in the latest release of MVC and .NET that I really like to use, instead of the "old school" FormCollection and Request keys.


Consider a HTML snippet contained within a form tag that either does an AJAX or FORM POST.

<input type="hidden"   name="TrackingID" 
<input type="text"     name="FirstName"  id="firstnametext" />
<input type="checkbox" name="IsLegal"  value="Do you accept terms and conditions?" />

Your controller will actually parse the form data and try to deliver it to you as parameters of the defined type. I included checkbox because it is a tricky one. It returns text "on" if checked and null if not checked. The requirement though is that these defined variables MUST exists (unless nullable(remember though that string is nullable)) otherwise the AJAX or POST back will fail.

[HttpPost]
public ActionResult PostBack(int TrackingID, string FirstName, string IsLegal){
    MyData.SaveRequest(TrackingID,FirstName, IsLegal == null ? false : true);
}

You can also post back a model without using any razor helpers. I have come across that this is needed some times.

public Class HomeModel
{
  public int HouseNumber { get; set; }
  public string StreetAddress { get; set; }
}

The HTML markup will simply be ...

<input type="text" name="variableName.HouseNumber" id="whateverid" >

and your controller(Razor Engine) will intercept the Form Variable "variableName" (name is as you like but keep it consistent) and try to build it up and cast it to MyModel.

[HttpPost]
public ActionResult PostBack(HomeModel variableName){
    postBack.HouseNumber; //The value user entered
    postBack.StreetAddress; //the default value of NULL.
}

When a controller is expecting a Model (in this case HomeModel) you do not have to define ALL the fields as the parser will just leave them at default, usually NULL. The nice thing is you can mix and match various models on the Mark-up and the post back parse will populate as much as possible. You do not need to define a model on the page or use any helpers.

TIP: The name of the parameter in the controller is the name defined in the HTML mark-up "name=" not the name of the Model but the name of the expected variable in the !


Using List<> is bit more complex in its mark-up.

<input type="text" name="variableNameHere[0].HouseNumber" id="id"           value="0">
<input type="text" name="variableNameHere[1].HouseNumber" id="whateverid-x" value="1">
<input type="text" name="variableNameHere[2].HouseNumber"                   value="2">
<input type="text" name="variableNameHere[3].HouseNumber" id="whateverid22" value="3">

Index on List<> MUST always be zero based and sequential. 0,1,2,3.

[HttpPost]
public ActionResult PostBack(List<HomeModel> variableNameHere){
     int counter = MyHomes.Count()
     foreach(var home in MyHomes)
     { ... }
}

Using IEnumerable<> for non zero based and non sequential indices post back. We need to add an extra hidden input to help the binder.

<input type="hidden" name="variableNameHere.Index" value="278">
<input type="text" name="variableNameHere[278].HouseNumber" id="id"      value="3">

<input type="hidden" name="variableNameHere.Index" value="99976">
<input type="text" name="variableNameHere[99976].HouseNumber" id="id3"   value="4">

<input type="hidden" name="variableNameHere.Index" value="777">
<input type="text" name="variableNameHere[777].HouseNumber" id="id23"    value="5">

And the code just needs to use IEnumerable and call ToList()

[HttpPost]
public ActionResult PostBack(IEnumerable<MyModel> variableNameHere){
     int counter = variableNameHere.ToList().Count()
     foreach(var home in variableNameHere)
     { ... }
}

It is recommended to use a single Model or a ViewModel (Model contianing other models to create a complex 'View' Model) per page. Mixing and matching as proposed could be considered bad practice, but as long as it works and is readable its not BAD. It does however, demonstrate the power and flexiblity of the Razor engine.

So if you need to drop in something arbitrary or override another value from a Razor helper, or just do not feel like making your own helpers, for a single form that uses some unusual combination of data, you can quickly use these methods to accept extra data.

nginx - nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)

I had the same problem in letsencrypt (certbot) and nginx,

ref: https://github.com/certbot/certbot/issues/5486

this error does not have a solution yet

so, a changed a cron for renew (putting a reload after renew) (using suggest from certbot)

-- in /etc/cron.d/certbot
from
0 */12 * * * root test -x /usr/bin/certbot -a \! -d /run/systemd/system && perl -e 'sleep int(rand(3600))' && certbot -q renew 
to
0 */12 * * * root test -x /usr/bin/certbot -a \! -d /run/systemd/system && perl -e 'sleep int(rand(3600))' && certbot -q renew --pre-hook "service nginx stop" --post-hook "service nginx start"

logs (short):

-- in /var/log/syslog
Jun 10 00:14:25 localhost systemd[1]: Starting Certbot...
Jun 10 00:14:38 localhost certbot[22222]: nginx: [error] open() "/run/nginx.pid$
Jun 10 00:14:41 localhost certbot[22222]: Hook command "nginx" returned error c$
Jun 10 00:14:41 localhost certbot[22222]: Error output from nginx:
Jun 10 00:14:41 localhost certbot[22222]: nginx: [emerg] bind() to 0.0.0.0:443 $
Jun 10 00:14:41 localhost certbot[22222]: nginx: [emerg] bind() to 0.0.0.0:80 f$
Jun 10 00:14:41 localhost certbot[22222]: nginx: [emerg] bind() to 0.0.0.0:443 $
Jun 10 00:14:41 localhost certbot[22222]: nginx: [emerg] bind() to 0.0.0.0:80 f$
Jun 10 00:14:41 localhost certbot[22222]: nginx: [emerg] bind() to 0.0.0.0:443 $
Jun 10 00:14:41 localhost certbot[22222]: nginx: [emerg] bind() to 0.0.0.0:80 f$
Jun 10 00:14:41 localhost certbot[22222]: nginx: [emerg] bind() to 0.0.0.0:443 $
Jun 10 00:14:41 localhost certbot[22222]: nginx: [emerg] bind() to 0.0.0.0:80 f$
Jun 10 00:14:41 localhost certbot[22222]: nginx: [emerg] bind() to 0.0.0.0:443 $
Jun 10 00:14:41 localhost certbot[22222]: nginx: [emerg] bind() to 0.0.0.0:80 f$
Jun 10 00:14:41 localhost certbot[22222]: nginx: [emerg] still could not bind()
Jun 10 00:14:41 localhost systemd[1]: Started Certbot.


-- in /var/log/nginx/error.log
2018/06/10 00:14:27 [notice] 22233#22233: signal process started
2018/06/10 00:14:31 [notice] 22237#22237: signal process started
2018/06/10 00:14:33 [notice] 22240#22240: signal process started
2018/06/10 00:14:34 [notice] 22245#22245: signal process started
2018/06/10 00:14:38 [notice] 22255#22255: signal process started
2018/06/10 00:14:38 [error] 22255#22255: open() "/run/nginx.pid" failed (2: No $
2018/06/10 00:14:39 [emerg] 22261#22261: bind() to 0.0.0.0:443 failed (98: Addr$
2018/06/10 00:14:39 [emerg] 22261#22261: bind() to 0.0.0.0:80 failed (98: Addre$
2018/06/10 00:14:39 [emerg] 22261#22261: bind() to 0.0.0.0:443 failed (98: Addr$
2018/06/10 00:14:39 [emerg] 22261#22261: bind() to 0.0.0.0:80 failed (98: Addre$
2018/06/10 00:14:39 [emerg] 22261#22261: bind() to 0.0.0.0:443 failed (98: Addr$
2018/06/10 00:14:39 [emerg] 22261#22261: bind() to 0.0.0.0:80 failed (98: Addre$
2018/06/10 00:14:39 [emerg] 22261#22261: bind() to 0.0.0.0:443 failed (98: Addr$
2018/06/10 00:14:39 [emerg] 22261#22261: bind() to 0.0.0.0:80 failed (98: Addre$
2018/06/10 00:14:39 [emerg] 22261#22261: bind() to 0.0.0.0:443 failed (98: Addr$
2018/06/10 00:14:39 [emerg] 22261#22261: bind() to 0.0.0.0:80 failed (98: Addre$
2018/06/10 00:14:39 [emerg] 22261#22261: still could not bind()

What does this GCC error "... relocation truncated to fit..." mean?

I ran into this problem while building a program that requires a huge amount of stack space (over 2 GiB). The solution was to add the flag -mcmodel=medium, which is supported by both GCC and Intel compilers.

Firebase (FCM) how to get token

FASTEST AND GOOD FOR PROTOTYPE

The quick solution is to store it in sharedPrefs and add this logic to onCreate method in your MainActivity or class which is extending Application.

FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(this, instanceIdResult -> {
    String newToken = instanceIdResult.getToken();
    Log.e("newToken", newToken);
    getActivity().getPreferences(Context.MODE_PRIVATE).edit().putString("fb", newToken).apply();
});

Log.d("newToken", getActivity().getPreferences(Context.MODE_PRIVATE).getString("fb", "empty :("));

CLEANER WAY

A better option is to create a service and keep inside a similar logic. Firstly create new Service

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
        Log.e("newToken", s);
        getSharedPreferences("_", MODE_PRIVATE).edit().putString("fb", s).apply();
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
    }

    public static String getToken(Context context) {
        return context.getSharedPreferences("_", MODE_PRIVATE).getString("fb", "empty");
    }
}

And then add it to AndroidManifest file

<service
        android:name=".MyFirebaseMessagingService"
        android:stopWithTask="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
</service>

Finally, you are able to use a static method from your Service MyFirebaseMessagingService.getToken(Context);

THE FASTEST BUT DEPRECATED

Log.d("Firebase", "token "+ FirebaseInstanceId.getInstance().getToken());

It's still working when you are using older firebase library than version 17.x.x

How can I replace a regex substring match in Javascript?

I would get the part before and after what you want to replace and put them either side.

Like:

var str   = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;

var matches = str.match(regex);

var result = matches[1] + "1" + matches[2];

// With ES6:
var result = `${matches[1]}1${matches[2]}`;

How do I activate a specific workbook and a specific sheet?

The code that worked for me is:

ThisWorkbook.Sheets("sheetName").Activate

How to assign the output of a command to a Makefile variable

Use the Make shell builtin like in MY_VAR=$(shell echo whatever)

me@Zack:~$make
MY_VAR IS whatever

me@Zack:~$ cat Makefile 
MY_VAR := $(shell echo whatever)

all:
    @echo MY_VAR IS $(MY_VAR)

How to hide command output in Bash

Use this.

{
  /your/first/command
  /your/second/command
} &> /dev/null

Explanation

To eliminate output from commands, you have two options:

  • Close the output descriptor file, which keeps it from accepting any more input. That looks like this:

    your_command "Is anybody listening?" >&-
    

    Usually, output goes either to file descriptor 1 (stdout) or 2 (stderr). If you close a file descriptor, you'll have to do so for every numbered descriptor, as &> (below) is a special BASH syntax incompatible with >&-:

    /your/first/command >&- 2>&-
    

    Be careful to note the order: >&- closes stdout, which is what you want to do; &>- redirects stdout and stderr to a file named - (hyphen), which is not what what you want to do. It'll look the same at first, but the latter creates a stray file in your working directory. It's easy to remember: >&2 redirects stdout to descriptor 2 (stderr), >&3 redirects stdout to descriptor 3, and >&- redirects stdout to a dead end (i.e. it closes stdout).

    Also beware that some commands may not handle a closed file descriptor particularly well ("write error: Bad file descriptor"), which is why the better solution may be to...

  • Redirect output to /dev/null, which accepts all output and does nothing with it. It looks like this:

    your_command "Hello?" > /dev/null
    

    For output redirection to a file, you can direct both stdout and stderr to the same place very concisely, but only in bash:

    /your/first/command &> /dev/null
    

Finally, to do the same for a number of commands at once, surround the whole thing in curly braces. Bash treats this as a group of commands, aggregating the output file descriptors so you can redirect all at once. If you're familiar instead with subshells using ( command1; command2; ) syntax, you'll find the braces behave almost exactly the same way, except that unless you involve them in a pipe the braces will not create a subshell and thus will allow you to set variables inside.

{
  /your/first/command
  /your/second/command
} &> /dev/null

See the bash manual on redirections for more details, options, and syntax.

How to split strings over multiple lines in Bash?

This isn't exactly what the user asked, but another way to create a long string that spans multiple lines is by incrementally building it up, like so:

$ greeting="Hello"
$ greeting="$greeting, World"
$ echo $greeting
Hello, World

Obviously in this case it would have been simpler to build it one go, but this style can be very lightweight and understandable when dealing with longer strings.

Compare two dates in Java

The easiest way to compare two dates is converting them to numeric value (like unix timestamp).

You can use Date.getTime() method that return the unix time.

Date questionDate = question.getStartDate();
Date today = new Date();
if((today.getTime() == questionDate.getTime())) {
    System.out.println("Both are equals");
}

How to add RSA key to authorized_keys file?

I know I am replying too late but for anyone else who needs this, run following command from your local machine

cat ~/.ssh/id_rsa.pub | ssh [email protected] "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"

this has worked perfectly fine. All you need to do is just to replace

[email protected]

with your own user for that particular host

Load local javascript file in chrome for testing?

Not sure why @user3133050 is voted down, that's all you need to do...

Here's the structure you need, based on your script tag's src, assuming you are trying to load moment.js into index.html:

/js/moment.js
/some-other-directory/index.html

The ../ looks "up" at the "some-other-directory" folder level, finds the js folder next to it, and loads the moment.js inside.

It sounds like your index.html is at root level, or nested even deeper.

If you're still struggling, create a test.js file in the same location as index.html, and add a <script src="test.js"></script> and see if that loads. If that fails, check your syntax. Tested in Chrome 46.

There is an error in XML document (1, 41)

Agreed with the answer from sll, but experienced another hurdle which was having specified a namespace in the attributes, when receiving the return xml that namespace wasn't included and thus failed finding the class.

i had to find a workaround to specifying the namespace in the attribute and it worked.

ie.

[Serializable()]
    [XmlRoot("Patient", Namespace = "http://www.xxxx.org/TargetNamespace")]
    public class Patient

generated

<Patient xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.xxxx.org/TargetNamespace">

but I had to change it to

[Serializable()]
[XmlRoot("Patient")]
public class Patient

which generated to

<Patient xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

This solved my problem, hope it helps someone else.

Powershell send-mailmessage - email to multiple recipients

to send a .NET / C# powershell eMail use such a structure:

for best behaviour create a class with a method like this

 using (PowerShell PowerShellInstance = PowerShell.Create())
            {
                PowerShellInstance.AddCommand("Send-MailMessage")
                                  .AddParameter("SMTPServer", "smtp.xxx.com")
                                  .AddParameter("From", "[email protected]")
                                  .AddParameter("Subject", "xxx Notification")
                                  .AddParameter("Body", body_msg)
                                  .AddParameter("BodyAsHtml")
                                  .AddParameter("To", recipients);

                // invoke execution on the pipeline (ignore output) --> nothing will be displayed
                PowerShellInstance.Invoke();
            }              

Whereby these instance is called in a function like:

        public void sendEMailPowerShell(string body_msg, string[] recipients)

Never forget to use a string array for the recepients, which can be look like this:

string[] reportRecipient = { 
                        "xxx <[email protected]>",
                        "xxx <[email protected]>"
                        };

body_msg

this message can be overgiven as parameter to the method itself, HTML coding enabled!!

recipients

never forget to use a string array in case of multiple recipients, otherwise only the last address in the string will be used!!!

calling the function can look like this:

        mail reportMail = new mail(); //instantiate from class
        reportMail.sendEMailPowerShell(reportMessage, reportRecipient); //msg + email addresses

ThumbUp

Quadratic and cubic regression in Excel

You need to use an undocumented trick with Excel's LINEST function:

=LINEST(known_y's, [known_x's], [const], [stats])

Background

A regular linear regression is calculated (with your data) as:

=LINEST(B2:B21,A2:A21)

which returns a single value, the linear slope (m) according to the formula:

enter image description here

which for your data:

enter image description here

is:

enter image description here

Undocumented trick Number 1

You can also use Excel to calculate a regression with a formula that uses an exponent for x different from 1, e.g. x1.2:

enter image description here

using the formula:

=LINEST(B2:B21, A2:A21^1.2)

which for you data:

enter image description here

is:

enter image description here

You're not limited to one exponent

Excel's LINEST function can also calculate multiple regressions, with different exponents on x at the same time, e.g.:

=LINEST(B2:B21,A2:A21^{1,2})

Note: if locale is set to European (decimal symbol ","), then comma should be replaced by semicolon and backslash, i.e. =LINEST(B2:B21;A2:A21^{1\2})

Now Excel will calculate regressions using both x1 and x2 at the same time:

enter image description here

How to actually do it

The impossibly tricky part there's no obvious way to see the other regression values. In order to do that you need to:

  • select the cell that contains your formula:

    enter image description here

  • extend the selection the left 2 spaces (you need the select to be at least 3 cells wide):

    enter image description here

  • press F2

  • press Ctrl+Shift+Enter

    enter image description here

You will now see your 3 regression constants:

  y = -0.01777539x^2 + 6.864151123x + -591.3531443

Bonus Chatter

I had a function that I wanted to perform a regression using some exponent:

y = m×xk + b

But I didn't know the exponent. So I changed the LINEST function to use a cell reference instead:

=LINEST(B2:B21,A2:A21^F3, true, true)

With Excel then outputting full stats (the 4th paramter to LINEST):

enter image description here

I tell the Solver to maximize R2:

enter image description here

And it can figure out the best exponent. Which for you data:

enter image description here

is:

enter image description here

How to save a figure in MATLAB from the command line?

Use saveas:

h=figure;
plot(x,y,'-bs','Linewidth',1.4,'Markersize',10);
% ...
saveas(h,name,'fig')
saveas(h,name,'jpg')

This way, the figure is plotted, and automatically saved to '.jpg' and '.fig'. You don't need to wait for the plot to appear and click 'save as' in the menu. Way to go if you need to plot/save a lot of figures.

If you really do not want to let the plot appear (it has to be loaded anyway, can't avoid that, else there is also nothing to save), you can hide it:

h=figure('visible','off')

Is there any way to call a function periodically in JavaScript?

You will want to have a look at setInterval() and setTimeout().

Here is a decent tutorial article.

Reset input value in angular 2

  1. check the @viewchild in your .ts

    @ViewChild('ngOtpInput') ngOtpInput:any;
    
  2. set the below code in your method were you want the fields to be clear.

    yourMethod(){
        this.ngOtpInput.setValue(yourValue);
    }
    

In angular $http service, How can I catch the "status" of error?

Your arguments are incorrect, error doesn't return an object containing status and message, it passed them as separate parameters in the order described below.

Taken from the angular docs:

  • data – {string|Object} – The response body transformed with the transform functions.
  • status – {number} – HTTP status code of the response.
  • headers – {function([headerName])} – Header getter function.
  • config – {Object} – The configuration object that was used to generate the request.
  • statusText – {string} – HTTP status text of the response.

So you'd need to change your code to:

$http.get(dataUrl)
    .success(function (data){
        $scope.data.products = data;
    })
    .error(function (error, status){
        $scope.data.error = { message: error, status: status};
        console.log($scope.data.error.status); 
  }); 

Obviously, you don't have to create an object representing the error, you could just create separate scope properties but the same principle applies.

How to show "Done" button on iPhone number pad

I describe one solution for iOS 4.2+ here but the dismiss button fades in after the keyboard appears. It's not terrible, but not ideal either.

The solution described in the question linked above includes a more elegant illusion to dismiss the button, where I fade and vertically displace the button to provide the appearance that the keypad and the button are dismissing together.

Wrap a text within only two lines inside div

@Asiddeen bn Muhammad's solution worked for me with a little modification to the css

    .text {
 line-height: 1.5;
  height: 6em; 
white-space: normal;
overflow: hidden;
text-overflow: ellipsis;
display: block;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
 }

Cannot delete directory with Directory.Delete(path, true)

The directory or a file in it is locked and cannot be deleted. Find the culprit who locks it and see if you can eliminate it.

How to change the background color of Action Bar's Option Menu in Android 4.2?

Following are the changes required in your theme for changing action bar & overflow menu background color. You need to configure "android:background" of actionBarStyle & popupMenuStyle

<application
            android:name="...."
            android:theme="@style/AppLightTheme">

<style name="AppLightTheme" parent="android:Theme.Holo.Light">      
        <item name="android:actionBarStyle">@style/ActionBarLight</item>
        <item name="android:popupMenuStyle">@style/ListPopupWindowLight</item>
</style>

<style name="ActionBarLight" parent="android:style/Widget.Holo.Light.ActionBar">
        <item name="android:background">@color/white</item>
</style>


<style name="ListPopupWindowLight"parent="@android:style/Widget.Holo.Light.ListPopupWindow">
        <item name="android:background">@color/white</item>
</style>

Can't escape the backslash with regex?

From http://www.regular-expressions.info/charclass.html :

Note that the only special characters or metacharacters inside a character class are the closing bracket (]), the backslash (\\), the caret (^) and the hyphen (-). The usual metacharacters are normal characters inside a character class, and do not need to be escaped by a backslash. To search for a star or plus, use [+*]. Your regex will work fine if you escape the regular metacharacters inside a character class, but doing so significantly reduces readability.

To include a backslash as a character without any special meaning inside a character class, you have to escape it with another backslash. [\\x] matches a backslash or an x. The closing bracket (]), the caret (^) and the hyphen (-) can be included by escaping them with a backslash, or by placing them in a position where they do not take on their special meaning. I recommend the latter method, since it improves readability. To include a caret, place it anywhere except right after the opening bracket. [x^] matches an x or a caret. You can put the closing bracket right after the opening bracket, or the negating caret. []x] matches a closing bracket or an x. [^]x] matches any character that is not a closing bracket or an x. The hyphen can be included right after the opening bracket, or right before the closing bracket, or right after the negating caret. Both [-x] and [x-] match an x or a hyphen.

What language are you writing the regex in?

Abstract variables in Java?

No, Java doesn't support abstract variables. It doesn't really make a lot of sense, either.

What specific change to the "implementation" of a variable to you expect a sub class to do?

When I have a abstract String variable in the base class, what should the sub class do to make it non-abstract?

How to save a BufferedImage as a File

The answer lies within the Java Documentation's Tutorial for Writing/Saving an Image.

The Image I/O class provides the following method for saving an image:

static boolean ImageIO.write(RenderedImage im, String formatName, File output)  throws IOException

The tutorial explains that

The BufferedImage class implements the RenderedImage interface.

so it's able to be used in the method.

For example,

try {
    BufferedImage bi = getMyImage();  // retrieve image
    File outputfile = new File("saved.png");
    ImageIO.write(bi, "png", outputfile);
} catch (IOException e) {
    // handle exception
}

It's important to surround the write call with a try block because, as per the API, the method throws an IOException "if an error occurs during writing"

Also explained are the method's objective, parameters, returns, and throws, in more detail:

Writes an image using an arbitrary ImageWriter that supports the given format to a File. If there is already a File present, its contents are discarded.

Parameters:

im - a RenderedImage to be written.

formatName - a String containg the informal name of the format.

output - a File to be written to.

Returns:

false if no appropriate writer is found.

Throws:

IllegalArgumentException - if any parameter is null.

IOException - if an error occurs during writing.

However, formatName may still seem rather vague and ambiguous; the tutorial clears it up a bit:

The ImageIO.write method calls the code that implements PNG writing a “PNG writer plug-in”. The term plug-in is used since Image I/O is extensible and can support a wide range of formats.

But the following standard image format plugins : JPEG, PNG, GIF, BMP and WBMP are always be present.

For most applications it is sufficient to use one of these standard plugins. They have the advantage of being readily available.

There are, however, additional formats you can use:

The Image I/O class provides a way to plug in support for additional formats which can be used, and many such plug-ins exist. If you are interested in what file formats are available to load or save in your system, you may use the getReaderFormatNames and getWriterFormatNames methods of the ImageIO class. These methods return an array of strings listing all of the formats supported in this JRE.

String writerNames[] = ImageIO.getWriterFormatNames();

The returned array of names will include any additional plug-ins that are installed and any of these names may be used as a format name to select an image writer.

For a full and practical example, one can refer to Oracle's SaveImage.java example.

QByteArray to QString

Qt 4.8

QString(byteArray).toStdString();

Qt 5.12

byteArray.toStdString();

Is the LIKE operator case-sensitive with MSSQL Server?

You have an option to define collation order at the time of defining your table. If you define a case-sensitive order, your LIKE operator will behave in a case-sensitive way; if you define a case-insensitive collation order, the LIKE operator will ignore character case as well:

CREATE TABLE Test (
    CI_Str VARCHAR(15) COLLATE Latin1_General_CI_AS -- Case-insensitive
,   CS_Str VARCHAR(15) COLLATE Latin1_General_CS_AS -- Case-sensitive
);

Here is a quick demo on sqlfiddle showing the results of collation order on searches with LIKE.

Why are C++ inline functions in the header?

There are two ways to look at it:

  1. Inline functions are defined in the header because, in order to inline a function call, the compiler must be able to see the function body. For a naive compiler to do that, the function body must be in the same translation unit as the call. (A modern compiler can optimize across translation units, and so a function call may be inlined even though the function definition is in a separate translation unit, but these optimizations are expensive, aren't always enabled, and weren't always supported by the compiler)

  2. functions defined in the header must be marked inline because otherwise, every translation unit which includes the header will contain a definition of the function, and the linker will complain about multiple definitions (a violation of the One Definition Rule). The inline keyword suppresses this, allowing multiple translation units to contain (identical) definitions.

The two explanations really boil down to the fact that the inline keyword doesn't exactly do what you'd expect.

A C++ compiler is free to apply the inlining optimization (replace a function call with the body of the called function, saving the call overhead) any time it likes, as long as it doesn't alter the observable behavior of the program.

The inline keyword makes it easier for the compiler to apply this optimization, by allowing the function definition to be visible in multiple translation units, but using the keyword doesn't mean the compiler has to inline the function, and not using the keyword doesn't forbid the compiler from inlining the function.

How to import an Excel file into SQL Server?

There are many articles about writing code to import an excel file, but this is a manual/shortcut version:

If you don't need to import your Excel file programmatically using code you can do it very quickly using the menu in SQL Management Studio.

The quickest way to get your Excel file into SQL is by using the import wizard:

  1. Open SSMS (Sql Server Management Studio) and connect to the database where you want to import your file into.
  2. Import Data: in SSMS in Object Explorer under 'Databases' right-click the destination database, select Tasks, Import Data. An import wizard will pop up (you can usually just click 'Next' on the first screen).

enter image description here

  1. The next window is 'Choose a Data Source', select Excel:

    • In the 'Data Source' dropdown list select Microsoft Excel (this option should appear automatically if you have excel installed).

    • Click the 'Browse' button to select the path to the Excel file you want to import.

    • Select the version of the excel file (97-2003 is usually fine for files with a .XLS extension, or use 2007 for newer files with a .XLSX extension)
    • Tick the 'First Row has headers' checkbox if your excel file contains headers.
    • Click next.

enter image description here

  1. On the 'Choose a Destination' screen, select destination database:
    • Select the 'Server name', Authentication (typically your sql username & password) and select a Database as destination. Click Next.

enter image description here

  1. On the 'Specify Table Copy or Query' window:

    • For simplicity just select 'Copy data from one or more tables or views', click Next.
  2. 'Select Source Tables:' choose the worksheet(s) from your Excel file and specify a destination table for each worksheet. If you don't have a table yet the wizard will very kindly create a new table that matches all the columns from your spreadsheet. Click Next.

enter image description here

  1. Click Finish.

How to extract closed caption transcript from YouTube video?

Following document says only the owner of the channel can do this via standard youtube interface: https://developers.google.com/youtube/2.0/developers_guide_protocol_captions?hl=en

Cheap fix: You can click on the "interactive transscript" button - and copy the content this way. Of course you lose the milliseconds this way.

Extremely cheap fix: A shared youtube account - so that multiple people can edit and upload caption files.

Challenging solution: The youtube API allows downloading and uploading of caption files via HTTP... You may write a youtube API application to provide a browser user interface for uploading or downloading for ANY user or particular users.

Here is an example project for this in java http://apiblog.youtube.com/2011/01/youtube-captions-uploader-web-app.html

Here is very simple example of a working upload for everybody: http://yt-captions-uploader.appspot.com/

Make install, but not to default directories?

try using INSTALL_ROOT.

make install INSTALL_ROOT=$INSTALL_DIRECTORY

Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

I had the same problem. The only thing that solved it was merge the content of META-INF/spring.handler and META-INF/spring.schemas of each spring jar file into same file names under my META-INF project.

This two threads explain it better:

How to represent empty char in Java Character class

As chars can be represented as Integers (ASCII-Codes), you can simply write:

char c = 0;

The 0 in ASCII-Code is null.

Can we make unsigned byte in Java

Adamski provided the best answer, but it is not quite complete, so read his reply, as it explains the details I'm not.

If you have a system function that requires an unsigned byte to be passed to it, you can pass a signed byte as it will automatically treat it as an unsigned byte.

So if a system function requires four bytes, for example, 192 168 0 1 as unsigned bytes you can pass -64 -88 0 1, and the function will still work, because the act of passing them to the function will un-sign them.

However you are unlikely to have this problem as system functions are hidden behind classes for cross-platform compatibility, though some of the java.io read methods return unsighed bytes as an int.

If you want to see this working, try writing signed bytes to a file and read them back as unsigned bytes.

Forward X11 failed: Network error: Connection refused

fill in the "X display location" did not work for me. but install MobaXterm did the job.

How to make UIButton's text alignment center? Using IB

Actually you can do it in interface builder.

You should set Title to "Attributed" and then choose center alignment.

How to convert a date String to a Date or Calendar object?

The highly regarded Joda Time library is also worth a look. This is basis for the new date and time api that is pencilled in for Java 7. The design is neat, intuitive, well documented and avoids a lot of the clumsiness of the original java.util.Date / java.util.Calendar classes.

Joda's DateFormatter can parse a String to a Joda DateTime.

How can I add raw data body to an axios request?

Here is my solution:

axios({
  method: "POST",
  url: "https://URL.com/api/services/fetchQuizList",
  headers: {
    "x-access-key": data,
    "x-access-token": token,
  },
  data: {
    quiz_name: quizname,
  },
})
.then(res => {
  console.log("res", res.data.message);
})
.catch(err => {
  console.log("error in request", err);
});

This should help

How to name variables on the fly?

And this option?

list_name<-list()
for(i in 1:100){
    paste("orca",i,sep="")->list_name[[i]]
}

It works perfectly. In the example you put, first line is missing, and then gives you the error message.

How to enable SOAP on CentOS

After hours of searching I think my problem was that command yum install php-soap installs the latest version of soap for the latest php version.

My php version was 7.027, but latest php version is 7.2 so I had to search for the right soap version and finaly found it HERE!

yum install rh-php70-php-soap

Now php -m | grep -i soap works, Output: soap

Do not forget to restart httpd service.

nodejs npm global config missing on windows

It looks like the files npm uses to edit its config files are not created on a clean install, as npm has a default option for each one. This is why you can still get options with npm config get <option>: having those files only overrides the defaults, it doesn't create the options from scratch.

I had never touched my npm config stuff before today, even though I had had it for months now. None of the files were there yet, such as ~/.npmrc (on a Windows 8.1 machine with Git Bash), yet I could run npm config get <something> and, if it was a correct npm option, it returned a value. When I ran npm config set <option> <value>, the file ~/.npmrc seemed to be created automatically, with the option & its value as the only non-commented-out line.

As for deleting options, it looks like this just sets the value back to the default value, or does nothing if that option was never set or was unset & never reset. Additionally, if that option is the only explicitly set option, it looks like ~/.npmrc is deleted, too, and recreated if you set anything else later.

In your case (assuming it is still the same over a year later), it looks like you never set the proxy option in npm. Therefore, as npm's config help page says, it is set to whatever your http_proxy (case-insensitive) environment variable is. This means there is nothing to delete, unless you want to "delete" your HTTP proxy, although you could set the option or environment variable to something else and hope neither breaks your set-up somehow.

How can I wait for a thread to finish with .NET?

I can see five options available:

1. Thread.Join

As with Mitch's answer. But this will block your UI thread, however you get a Timeout built in for you.


2. Use a WaitHandle

ManualResetEvent is a WaitHandle as jrista suggested.

One thing to note is if you want to wait for multiple threads: WaitHandle.WaitAll() won't work by default, as it needs an MTA thread. You can get around this by marking your Main() method with MTAThread - however this blocks your message pump and isn't recommended from what I've read.


3. Fire an event

See this page by Jon Skeet about events and multi-threading. It's possible that an event can become unsubcribed between the if and the EventName(this,EventArgs.Empty) - it's happened to me before.

(Hopefully these compile, I haven't tried)

public class Form1 : Form
{
    int _count;

    void ButtonClick(object sender, EventArgs e)
    {
        ThreadWorker worker = new ThreadWorker();
        worker.ThreadDone += HandleThreadDone;

        Thread thread1 = new Thread(worker.Run);
        thread1.Start();

        _count = 1;
    }

    void HandleThreadDone(object sender, EventArgs e)
    {
        // You should get the idea this is just an example
        if (_count == 1)
        {
            ThreadWorker worker = new ThreadWorker();
            worker.ThreadDone += HandleThreadDone;

            Thread thread2 = new Thread(worker.Run);
            thread2.Start();

            _count++;
        }
    }

    class ThreadWorker
    {
        public event EventHandler ThreadDone;

        public void Run()
        {
            // Do a task

            if (ThreadDone != null)
                ThreadDone(this, EventArgs.Empty);
        }
    }
}

4. Use a delegate

public class Form1 : Form
{
    int _count;

    void ButtonClick(object sender, EventArgs e)
    {
        ThreadWorker worker = new ThreadWorker();

        Thread thread1 = new Thread(worker.Run);
        thread1.Start(HandleThreadDone);

        _count = 1;
    }

    void HandleThreadDone()
    {
        // As before - just a simple example
        if (_count == 1)
        {
            ThreadWorker worker = new ThreadWorker();

            Thread thread2 = new Thread(worker.Run);
            thread2.Start(HandleThreadDone);

            _count++;
        }
    }

    class ThreadWorker
    {
        // Switch to your favourite Action<T> or Func<T>
        public void Run(object state)
        {
            // Do a task

            Action completeAction = (Action)state;
            completeAction.Invoke();
        }
    }
}

If you do use the _count method, it might be an idea (to be safe) to increment it using

Interlocked.Increment(ref _count)

I'd be interested to know the difference between using delegates and events for thread notification, the only difference I know are events are called synchronously.


5. Do it asynchronously instead

The answer to this question has a very clear description of your options with this method.


Delegate/Events on the wrong thread

The event/delegate way of doing things will mean your event handler method is on thread1/thread2 not the main UI thread, so you will need to switch back right at the top of the HandleThreadDone methods:

// Delegate example
if (InvokeRequired)
{
    Invoke(new Action(HandleThreadDone));
    return;
}

How to bind RadioButtons to an enum?

I've created a new class to handle binding RadioButtons and CheckBoxes to enums. It works for flagged enums (with multiple checkbox selections) and non-flagged enums for single-selection checkboxes or radio buttons. It also requires no ValueConverters at all.

This might look more complicated at first, however, once you copy this class into your project, it's done. It's generic so it can easily be reused for any enum.

public class EnumSelection<T> : INotifyPropertyChanged where T : struct, IComparable, IFormattable, IConvertible
{
  private T value; // stored value of the Enum
  private bool isFlagged; // Enum uses flags?
  private bool canDeselect; // Can be deselected? (Radio buttons cannot deselect, checkboxes can)
  private T blankValue; // what is considered the "blank" value if it can be deselected?

  public EnumSelection(T value) : this(value, false, default(T)) { }
  public EnumSelection(T value, bool canDeselect) : this(value, canDeselect, default(T)) { }
  public EnumSelection(T value, T blankValue) : this(value, true, blankValue) { }
  public EnumSelection(T value, bool canDeselect, T blankValue)
  {
    if (!typeof(T).IsEnum) throw new ArgumentException($"{nameof(T)} must be an enum type"); // I really wish there was a way to constrain generic types to enums...
    isFlagged = typeof(T).IsDefined(typeof(FlagsAttribute), false);

    this.value = value;
    this.canDeselect = canDeselect;
    this.blankValue = blankValue;
  }

  public T Value
  {
    get { return value; }
    set 
    {
      if (this.value.Equals(value)) return;
      this.value = value;
      OnPropertyChanged();
      OnPropertyChanged("Item[]"); // Notify that the indexer property has changed
    }
  }

  [IndexerName("Item")]
  public bool this[T key]
  {
    get
    {
      int iKey = (int)(object)key;
      return isFlagged ? ((int)(object)value & iKey) == iKey : value.Equals(key);
    }
    set
    {
      if (isFlagged)
      {
        int iValue = (int)(object)this.value;
        int iKey = (int)(object)key;

        if (((iValue & iKey) == iKey) == value) return;

        if (value)
          Value = (T)(object)(iValue | iKey);
        else
          Value = (T)(object)(iValue & ~iKey);
      }
      else
      {
        if (this.value.Equals(key) == value) return;
        if (!value && !canDeselect) return;

        Value = value ? key : blankValue;
      }
    }
  }

  public event PropertyChangedEventHandler PropertyChanged;

  private void OnPropertyChanged([CallerMemberName] string propertyName = "")
  {
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  }
}

And for how to use it, let's say you have an enum for running a task manually or automatically, and can be scheduled for any days of the week, and some optional options...

public enum StartTask
{
  Manual,
  Automatic
}

[Flags()]
public enum DayOfWeek
{
  Sunday = 1 << 0,
  Monday = 1 << 1,
  Tuesday = 1 << 2,
  Wednesday = 1 << 3,
  Thursday = 1 << 4,
  Friday = 1 << 5,
  Saturday = 1 << 6
}

public enum AdditionalOptions
{
  None = 0,
  OptionA,
  OptionB
}

Now, here's how easy it is to use this class:

public class MyViewModel : ViewModelBase
{
  public MyViewModel()
  {
    StartUp = new EnumSelection<StartTask>(StartTask.Manual);
    Days = new EnumSelection<DayOfWeek>(default(DayOfWeek));
    Options = new EnumSelection<AdditionalOptions>(AdditionalOptions.None, true, AdditionalOptions.None);
  }

  public EnumSelection<StartTask> StartUp { get; private set; }
  public EnumSelection<DayOfWeek> Days { get; private set; }
  public EnumSelection<AdditionalOptions> Options { get; private set; }
}

And here's how easy it is to bind checkboxes and radio buttons with this class:

<StackPanel Orientation="Vertical">
  <StackPanel Orientation="Horizontal">
    <!-- Using RadioButtons for exactly 1 selection behavior -->
    <RadioButton IsChecked="{Binding StartUp[Manual]}">Manual</RadioButton>
    <RadioButton IsChecked="{Binding StartUp[Automatic]}">Automatic</RadioButton>
  </StackPanel>
  <StackPanel Orientation="Horizontal">
    <!-- Using CheckBoxes for 0 or Many selection behavior -->
    <CheckBox IsChecked="{Binding Days[Sunday]}">Sunday</CheckBox>
    <CheckBox IsChecked="{Binding Days[Monday]}">Monday</CheckBox>
    <CheckBox IsChecked="{Binding Days[Tuesday]}">Tuesday</CheckBox>
    <CheckBox IsChecked="{Binding Days[Wednesday]}">Wednesday</CheckBox>
    <CheckBox IsChecked="{Binding Days[Thursday]}">Thursday</CheckBox>
    <CheckBox IsChecked="{Binding Days[Friday]}">Friday</CheckBox>
    <CheckBox IsChecked="{Binding Days[Saturday]}">Saturday</CheckBox>
  </StackPanel>
  <StackPanel Orientation="Horizontal">
    <!-- Using CheckBoxes for 0 or 1 selection behavior -->
    <CheckBox IsChecked="{Binding Options[OptionA]}">Option A</CheckBox>
    <CheckBox IsChecked="{Binding Options[OptionB]}">Option B</CheckBox>
  </StackPanel>
</StackPanel>
  1. When the UI loads, the "Manual" radio button will be selected and you can alter your selection between "Manual" or "Automatic" but either one of them must always be selected.
  2. Every day of the week will be unchecked, but any number of them can be checked or unchecked.
  3. "Option A" and "Option B" will both initially be unchecked. You can check one or the other, checking one will uncheck the other (similar to RadioButtons), but now you can also uncheck both of them (which you cannot do with WPF's RadioButton, which is why CheckBox is being used here)

How can I remove the extension of a filename in a shell script?

Using POSIX's built-in only:

#!/usr/bin/env sh
path=this.path/with.dots/in.path.name/filename.tar.gz

# Get the basedir without external command
# by stripping out shortest trailing match of / followed by anything
dirname=${path%/*}

# Get the basename without external command
# by stripping out longest leading match of anything followed by /
basename=${path##*/}

# Strip uptmost trailing extension only
# by stripping out shortest trailing match of dot followed by anything
oneextless=${basename%.*}; echo "$noext" 

# Strip all extensions
# by stripping out longest trailing match of dot followed by anything
noext=${basename%%.*}; echo "$noext"

# Printout demo
printf %s\\n "$path" "$dirname" "$basename" "$oneextless" "$noext"

Printout demo:

this.path/with.dots/in.path.name/filename.tar.gz
this.path/with.dots/in.path.name
filename.tar.gz
filename.tar
filename

How to add buttons at top of map fragment API v2 layout

Button Above The Map

If this is what you want ...simply add button inside the Fragment.

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.LocationChooser">


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right|top"
        android:text="Demo Button" 
        android:padding="10dp"
        android:layout_marginTop="20dp"
        android:paddingRight="10dp"/>

</fragment>

Add to Array jQuery

You are right. This has nothing to do with jQuery though.

var myArray = [];
myArray.push("foo");
// myArray now contains "foo" at index 0.

How to replace multiple patterns at once with sed?

Here is an awk based on oogas sed

echo 'abbc' | awk '{gsub(/ab/,"xy");gsub(/bc/,"ab");gsub(/xy/,"bc")}1'
bcab

How do I use a pipe to redirect the output of one command to the input of another?

You can also run exactly same command at Cmd.exe command-line using PowerShell. I'd go with this approach for simplicity...

C:\>PowerShell -Command "temperature | prismcom.exe usb"

Please read up on Understanding the Windows PowerShell Pipeline

You can also type in C:\>PowerShell at the command-line and it'll put you in PS C:\> mode instanctly, where you can directly start writing PS.

Get the last item in an array

Whatever you do don't just use reverse() !!!

A few answers mention reverse but don't mention the fact that reverse modifies the original array, and doesn't (as in some other language or frameworks) return a copy.

var animals = ['dog', 'cat'];

animals.reverse()[0]
"cat"

animals.reverse()[0]
"dog"

animals.reverse()[1]
"dog"

animals.reverse()[1]
"cat"

This can be the worst type of code to debug!

How to Create simple drag and Drop in angularjs

Using HTML 5 Drag and Drop
You can easily archive this using HTML 5 drag and drop feature along with angular directives.

  1. Enable drag by setting draggable = true.
  2. Add directives for parent container and child items.
  3. Override drag and drop functions - 'ondragstart' for parent and 'ondrop' for child.

Find the example below in which list is array of items.
HTML code:

    <div class="item_content" ng-repeat="item in list" draggrble-container>
        <div class="item" draggable-item draggable="true">{{item}}</div>
    </div>

Javascript:

    module.directive("draggableItem",function(){
     return {
      link:function(scope,elem,attr){
        elem[0].ondragstart = function(event){
            scope.$parent.selectedItem = scope.item;
        };
      }
     };
    });


    module.directive("draggrbleContainer",function(){
     return {
        link:function(scope,elem,attr){
            elem[0].ondrop = function(event){
                event.preventDefault();
                let selectedIndex = scope.list.indexOf(scope.$parent.selectedItem);
                let newPosition = scope.list.indexOf(scope.item);
                scope.$parent.list.splice(selectedIndex,1);
                scope.$parent.list.splice(newPosition,0,scope.$parent.selectedItem);
                scope.$apply();
            };
            elem[0].ondragover = function(event){
                event.preventDefault();

            };
        }
     };
    });

Find the complete code here https://github.com/raghavendrarai/SimpleDragAndDrop

WPF Add a Border to a TextBlock

A TextBlock does not actually inherit from Control so it does not have properties that you would generally associate with a Control. Your best bet for adding a border in a style is to replace the TextBlock with a Label

See this link for more on the differences between a TextBlock and other Controls

Order Bars in ggplot2 bar graph

Using scale_x_discrete (limits = ...) to specify the order of bars.

positions <- c("Goalkeeper", "Defense", "Striker")
p <- ggplot(theTable, aes(x = Position)) + scale_x_discrete(limits = positions)

Find and replace strings in vim on multiple lines

Replace All:

:%s/foo/bar/g

Find each occurrence of 'foo' (in all lines), and replace it with 'bar'.

For specific lines:

:6,10s/foo/bar/g

Change each 'foo' to 'bar' for all lines from line 6 to line 10 inclusive.

Why is <deny users="?" /> included in the following example?

Example 1 is for asp.net applications using forms authenication. This is common practice for internet applications because user is unauthenticated until it is authentcation against some security module.

Example 2 is for asp.net application using windows authenication. Windows Authentication uses Active Directory to authenticate users. The will prevent access to your application. I use this feature on intranet applications.

Jquery .on('scroll') not firing the event while scrolling

Can you place the #ulId in the document prior to the ajax load (with css display: none;), or wrap it in a containing div (with css display: none;), then just load the inner html during ajax page load, that way the scroll event will be linked to the div that is already there prior to the ajax?

Then you can use:

$('#ulId').on('scroll',function(){ console.log('Event Fired'); })

obviously replacing ulId with whatever the actual id of the scrollable div is.

Then set css display: block; on the #ulId (or containing div) upon load?

TCP vs UDP on video stream

Usually a video stream is somewhat fault tolerant. So if some packages get lost (due to some router along the way being overloaded, for example), then it will still be able to display the content, but with reduced quality.

If your live stream was using TCP/IP, then it would be forced to wait for those dropped packages before it could continue processing newer data.

That's doubly bad:

  • old data be re-transmitted (that's probably for a frame that was already displayed and therefore worthless) and
  • new data can't arrive until after old data was re-transmitted

If your goal is to display as up-to-date information as possible (and for a live-stream you usually want to be up-to-date, even if your frames look a bit worse), then TCP will work against you.

For a recorded stream the situation is slightly different: you'll probably be buffering a lot more (possibly several minutes!) and would rather have data re-transmitted than have some artifacts due to lost packages. In this case TCP is a good match (this could still be implemented in UDP, of course, but TCP doesn't have as much drawbacks as for the live stream case).

Multiple ping script in Python

This script:

import subprocess
import os
with open(os.devnull, "wb") as limbo:
        for n in xrange(1, 10):
                ip="192.168.0.{0}".format(n)
                result=subprocess.Popen(["ping", "-c", "1", "-n", "-W", "2", ip],
                        stdout=limbo, stderr=limbo).wait()
                if result:
                        print ip, "inactive"
                else:
                        print ip, "active"

will produce something like this output:

192.168.0.1 active
192.168.0.2 active
192.168.0.3 inactive
192.168.0.4 inactive
192.168.0.5 inactive
192.168.0.6 inactive
192.168.0.7 active
192.168.0.8 inactive
192.168.0.9 inactive

You can capture the output if you replace limbo with subprocess.PIPE and use communicate() on the Popen object:

p=Popen( ... )
output=p.communicate()
result=p.wait()

This way you get the return value of the command and can capture the text. Following the manual this is the preferred way to operate a subprocess if you need flexibility:

The underlying process creation and management in this module is handled by the Popen class. It offers a lot of flexibility so that developers are able to handle the less common cases not covered by the convenience functions.

Bad operand type for unary +: 'str'

You say that if int(splitLine[0]) > int(lastUnix): is causing the trouble, but you don't actually show anything which suggests that. I think this line is the problem instead:

print 'Pulled', + stock

Do you see why this line could cause that error message? You want either

>>> stock = "AAAA"
>>> print 'Pulled', stock
Pulled AAAA

or

>>> print 'Pulled ' + stock
Pulled AAAA

not

>>> print 'Pulled', + stock
PulledTraceback (most recent call last):
  File "<ipython-input-5-7c26bb268609>", line 1, in <module>
    print 'Pulled', + stock
TypeError: bad operand type for unary +: 'str'

You're asking Python to apply the + symbol to a string like +23 makes a positive 23, and she's objecting.

Resetting MySQL Root Password with XAMPP on Localhost

You can configure it with the "XAMPP Shell" (command prompt). Open the shell and execute this command:

mysqladmin.exe -u root password secret

How to change TIMEZONE for a java.util.Calendar/Date

  1. The class Date/Timestamp represents a specific instant in time, with millisecond precision, since January 1, 1970, 00:00:00 GMT. So this time difference (from epoch to current time) will be same in all computers across the world with irrespective of Timezone.

  2. Date/Timestamp doesn't know about the given time is on which timezone.

  3. If we want the time based on timezone we should go for the Calendar or SimpleDateFormat classes in java.

  4. If you try to print a Date/Timestamp object using toString(), it will convert and print the time with the default timezone of your machine.

  5. So we can say (Date/Timestamp).getTime() object will always have UTC (time in milliseconds)

  6. To conclude Date.getTime() will give UTC time, but toString() is on locale specific timezone, not UTC.

Now how will I create/change time on specified timezone?

The below code gives you a date (time in milliseconds) with specified timezones. The only problem here is you have to give date in string format.

   DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
   dateFormatLocal.setTimeZone(timeZone);
   java.util.Date parsedDate = dateFormatLocal.parse(date);

Use dateFormat.format for taking input Date (which is always UTC), timezone and return date as String.

How to store UTC/GMT time in DB:

If you print the parsedDate object, the time will be in default timezone. But you can store the UTC time in DB like below.

        Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
        Timestamp tsSchedStartTime = new Timestamp (parsedDate.getTime());
        if (tsSchedStartTime != null) {
            stmt.setTimestamp(11, tsSchedStartTime, calGMT );
        } else {
            stmt.setNull(11, java.sql.Types.DATE);
        }

Node JS Error: ENOENT

change

"/tmp/test.jpg".

to

"./tmp/test.jpg"

Global variables in AngularJS

I just found another method by mistake :

What I did was to declare a var db = null above app declaration and then modified it in the app.js then when I accessed it in the controller.js I was able to access it without any problem.There might be some issues with this method which I'm not aware of but It's a good solution I guess.

How to getElementByClass instead of GetElementById with JavaScript?

Append IDs at the class declaration

.aclass, #hashone, #hashtwo{ ...codes... }
document.getElementById( "hashone" ).style.visibility = "hidden";

One line if statement not working

In Ruby, the condition and the then part of an if expression must be separated by either an expression separator (i.e. ; or a newline) or the then keyword.

So, all of these would work:

if @item.rigged then 'Yes' else 'No' end

if @item.rigged; 'Yes' else 'No' end

if @item.rigged
  'Yes' else 'No' end

There is also a conditional operator in Ruby, but that is completely unnecessary. The conditional operator is needed in C, because it is an operator: in C, if is a statement and thus cannot return a value, so if you want to return a value, you need to use something which can return a value. And the only things in C that can return a value are functions and operators, and since it is impossible to make if a function in C, you need an operator.

In Ruby, however, if is an expression. In fact, everything is an expression in Ruby, so it already can return a value. There is no need for the conditional operator to even exist, let alone use it.

BTW: it is customary to name methods which are used to ask a question with a question mark at the end, like this:

@item.rigged?

This shows another problem with using the conditional operator in Ruby:

@item.rigged? ? 'Yes' : 'No'

It's simply hard to read with the multiple question marks that close to each other.

Safely casting long to int in Java

With Google Guava's Ints class, your method can be changed to:

public static int safeLongToInt(long l) {
    return Ints.checkedCast(l);
}

From the linked docs:

checkedCast

public static int checkedCast(long value)

Returns the int value that is equal to value, if possible.

Parameters: value - any value in the range of the int type

Returns: the int value that equals value

Throws: IllegalArgumentException - if value is greater than Integer.MAX_VALUE or less than Integer.MIN_VALUE

Incidentally, you don't need the safeLongToInt wrapper, unless you want to leave it in place for changing out the functionality without extensive refactoring of course.

Get list of Excel files in a folder using VBA

Sub test()
    Dim FSO As Object
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set folder1 = FSO.GetFolder(FromPath).Files
    FolderPath_1 = "D:\Arun\Macro Files\UK Marco\External Sales Tool for Au\Example Files\"
    Workbooks.Add
    Set Movenamelist = ActiveWorkbook
    For Each fil In folder1
        Movenamelist.Activate
        Range("A100000").End(xlUp).Offset(1, 0).Value = fil
        ActiveCell.Offset(1, 0).Select
    Next
End Sub

How to bind to a PasswordBox in MVVM

I am using succinct MVVM-friendly solution that hasn't been mentioned yet. First, I name the PasswordBox in XAML:

<PasswordBox x:Name="Password" />

Then I add a single method call into view constructor:

public LoginWindow()
{
    InitializeComponent();
    ExposeControl<LoginViewModel>.Expose(this, view => view.Password,
        (model, box) => model.SetPasswordBox(box));
}

And that's it. View model will receive notification when it is attached to a view via DataContext and another notification when it is detached. The contents of this notification are configurable via the lambdas, but usually it's just a setter or method call on the view model, passing the problematic control as a parameter.

It can be made MVVM-friendly very easily by having the view expose interface instead of child controls.

The above code relies on helper class published on my blog.

WPF TabItem Header Styling

Try this style instead, it modifies the template itself. In there you can change everything you need to transparent:

<Style TargetType="{x:Type TabItem}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type TabItem}">
        <Grid>
          <Border Name="Border" Margin="0,0,0,0" Background="Transparent"
                  BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="5">
            <ContentPresenter x:Name="ContentSite" VerticalAlignment="Center"
                              HorizontalAlignment="Center"
                              ContentSource="Header" Margin="12,2,12,2"
                              RecognizesAccessKey="True">
              <ContentPresenter.LayoutTransform>
            <RotateTransform Angle="270" />
          </ContentPresenter.LayoutTransform>
        </ContentPresenter>
          </Border>
        </Grid>
        <ControlTemplate.Triggers>
          <Trigger Property="IsSelected" Value="True">
            <Setter Property="Panel.ZIndex" Value="100" />
            <Setter TargetName="Border" Property="Background" Value="Red" />
            <Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
          </Trigger>
          <Trigger Property="IsEnabled" Value="False">
            <Setter TargetName="Border" Property="Background" Value="DarkRed" />
            <Setter TargetName="Border" Property="BorderBrush" Value="Black" />
            <Setter Property="Foreground" Value="DarkGray" />
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

What is token-based authentication?

The question is old and the technology has advanced, here is the current state:

JSON Web Token (JWT) is a JSON-based open standard (RFC 7519) for passing claims between parties in web application environment. The tokens are designed to be compact, URL-safe and usable especially in web browser single sign-on (SSO) context.

https://en.wikipedia.org/wiki/JSON_Web_Token

Laravel 5 Carbon format datetime

Just use the date() and strtotime() function and save your time

$suborder['payment_date'] = date('d-m-Y', strtotime($item['created_at']));

Don't stress!!!

Why has it failed to load main-class manifest attribute from a JAR file?

  1. set the classpath and compile

    javac -classpath "C:\Program Files\Java\jdk1.6.0_updateVersion\tools.jar" yourApp.java

  2. create manifest.txt

    Main-Class: yourApp newline

  3. create yourApp.jar

    jar cvf0m yourApp.jar manifest.txt yourApp.class

  4. run yourApp.jar

    java -jar yourApp.jar

Encrypt & Decrypt using PyCrypto AES 256

Grateful for the other answers which inspired but didn't work for me.

After spending hours trying to figure out how it works, I came up with the implementation below with the newest PyCryptodomex library (it is another story how I managed to set it up behind proxy, on Windows, in a virtualenv.. phew)

Working on your implementation, remember to write down padding, encoding, encrypting steps (and vice versa). You have to pack and unpack keeping in mind the order.

import base64
import hashlib
from Cryptodome.Cipher import AES
from Cryptodome.Random import get_random_bytes

__key__ = hashlib.sha256(b'16-character key').digest()

def encrypt(raw):
    BS = AES.block_size
    pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)

    raw = base64.b64encode(pad(raw).encode('utf8'))
    iv = get_random_bytes(AES.block_size)
    cipher = AES.new(key= __key__, mode= AES.MODE_CFB,iv= iv)
    return base64.b64encode(iv + cipher.encrypt(raw))

def decrypt(enc):
    unpad = lambda s: s[:-ord(s[-1:])]

    enc = base64.b64decode(enc)
    iv = enc[:AES.block_size]
    cipher = AES.new(__key__, AES.MODE_CFB, iv)
    return unpad(base64.b64decode(cipher.decrypt(enc[AES.block_size:])).decode('utf8'))

How to make unicode string with python3

This how I solved my problem to convert chars like \uFE0F, \u000A, etc. And also emojis that encoded with 16 bytes.

example = 'raw vegan chocolate cocoa pie w chocolate &amp; vanilla cream\\uD83D\\uDE0D\\uD83D\\uDE0D\\u2764\\uFE0F Present Moment Caf\\u00E8 in St.Augustine\\u2764\\uFE0F\\u2764\\uFE0F '
import codecs
new_str = codecs.unicode_escape_decode(example)[0]
print(new_str)
>>> 'raw vegan chocolate cocoa pie w chocolate &amp; vanilla cream\ud83d\ude0d\ud83d\ude0d?? Present Moment Cafè in St.Augustine???? '
new_new_str = new_str.encode('utf-16', 'surrogatepass').decode('utf-16')
print(new_new_str)
>>> 'raw vegan chocolate cocoa pie w chocolate &amp; vanilla cream?? Present Moment Cafè in St.Augustine???? '

Entity Framework vs LINQ to SQL

I found a very good answer here which explains when to use what in simple words:

The basic rule of thumb for which framework to use is how to plan on editing your data in your presentation layer.

  • Linq-To-Sql - use this framework if you plan on editing a one-to-one relationship of your data in your presentation layer. Meaning you don't plan on combining data from more than one table in any one view or page.

  • Entity Framework - use this framework if you plan on combining data from more than one table in your view or page. To make this clearer, the above terms are specific to data that will be manipulated in your view or page, not just displayed. This is important to understand.

With the Entity Framework you are able to "merge" tabled data together to present to the presentation layer in an editable form, and then when that form is submitted, EF will know how to update ALL the data from the various tables.

There are probably more accurate reasons to choose EF over L2S, but this would probably be the easiest one to understand. L2S does not have the capability to merge data for view presentation.

Selecting a row in DataGridView programmatically

 <GridViewName>.ClearSelection(); ----------------------------------------------------1
 foreach(var item in itemList) -------------------------------------------------------2
 {
    rowHandle =<GridViewName>.LocateByValue("UniqueProperty_Name", item.unique_id );--3
    if (rowHandle != GridControl.InvalidRowHandle)------------------------------------4
    {
        <GridViewName>.SelectRow(rowHandle);------------------------------------ -----5
    }
  }
  1. Clear all previous selection.
  2. Loop through rows needed to be selected in your grid.
  3. Get their row handles from grid (Note here grid is already updated with new rows)
  4. Checking if the row handle is valid or not.
  5. When valid row handle then select it.

Where itemList is list of rows to be selected in the grid view.

Create a Maven project in Eclipse complains "Could not resolve archetype"

You can resolve it by configuring settings.xml in Eclipse.

Go to Window --> Preferences --> Maven --> User Settings --> select the actual path of settings.xml

subtract two times in python

datetime.time does not support this, because it's nigh meaningless to subtract times in this manner. Use a full datetime.datetime if you want to do this.

How do I declare an array with a custom class?

Your class:

class name {
  public:
    string first;
    string last;

  name() { }  //Default constructor.

  name(string a, string b){
    first = a;
    last = b;
  }
};

Has an explicit constructor that requires two string parameters. Classes with no constructor written explicitly get default constructors taking no parameters. Adding the explicit one stopped the compiler from generating that default constructor for you.

So, if you wish to make an array of uninitialized objects, add a default constructor to your class so the compiler knows how to create them without providing those two string parameters - see the commented line above.

PHP error: Notice: Undefined index:

Are you putting the form processor in the same script as the form? If so, it is attempting to process before the post values are set (everything is executing).

Wrap all the processing code in a conditional that checks if the form has even been sent.

if(isset($_POST) && array_key_exists('name_of_your_submit_input',$_POST)){
//process form!
}else{
//show form, don't process yet!  You can break out of php here and render your form
}

Scripts execute from the top down when programming procedurally. You need to make sure the program knows to ignore the processing logic if the form has not been sent. Likewise, after processing, you should redirect to a success page with something like

header('Location:http://www.yourdomainhere.com/formsuccess.php');

I would not get into the habit of supressing notices or errors.

Please don't take offense if I suggest that if you are having these problems and you are attempting to build a shopping cart, that you instead utilize a mature ecommerce solution like Magento or OsCommerce. A shopping cart is an interface that requires a high degree of security and if you are struggling with these kind of POST issues I can guarantee you will be fraught with headaches later. There are many great stable releases, some as simple as mere object models, that are available for download.

How to search for a part of a word with ElasticSearch

I'm using nGram, too. I use standard tokenizer and nGram just as a filter. Here is my setup:

{
  "index": {
    "index": "my_idx",
    "type": "my_type",
    "analysis": {
      "index_analyzer": {
        "my_index_analyzer": {
          "type": "custom",
          "tokenizer": "standard",
          "filter": [
            "lowercase",
            "mynGram"
          ]
        }
      },
      "search_analyzer": {
        "my_search_analyzer": {
          "type": "custom",
          "tokenizer": "standard",
          "filter": [
            "standard",
            "lowercase",
            "mynGram"
          ]
        }
      },
      "filter": {
        "mynGram": {
          "type": "nGram",
          "min_gram": 2,
          "max_gram": 50
        }
      }
    }
  }
}

Let's you find word parts up to 50 letters. Adjust the max_gram as you need. In german words can get really big, so I set it to a high value.

How to call Makefile from another Makefile?

It seems clear that $(TESTS) is empty so your 1.4.0 makefile is effectively

all: 

clean:
  rm -f  gtest.a gtest_main.a *.o

Indeed, all has nothing to do. and clean does exactly what it says rm -f gtest.a ...

node.js http 'get' request with query string parameters

If you ever need to send GET request to an IP as well as a Domain (Other answers did not mention you can specify a port variable), you can make use of this function:

function getCode(host, port, path, queryString) {
    console.log("(" + host + ":" + port + path + ")" + "Running httpHelper.getCode()")

    // Construct url and query string
    const requestUrl = url.parse(url.format({
        protocol: 'http',
        hostname: host,
        pathname: path,
        port: port,
        query: queryString
    }));

    console.log("(" + host + path + ")" + "Sending GET request")
    // Send request
    console.log(url.format(requestUrl))
    http.get(url.format(requestUrl), (resp) => {
        let data = '';

        // A chunk of data has been received.
        resp.on('data', (chunk) => {
            console.log("GET chunk: " + chunk);
            data += chunk;
        });

        // The whole response has been received. Print out the result.
        resp.on('end', () => {
            console.log("GET end of response: " + data);
        });

    }).on("error", (err) => {
        console.log("GET Error: " + err);
    });
}

Don't miss requiring modules at the top of your file:

http = require("http");
url = require('url')

Also bare in mind that you may use https module for communicating over secured network.

How do I get a YouTube video thumbnail from the YouTube API?

// Get image form video URL
$url = $video['video_url'];

$urls = parse_url($url);

//Expect the URL to be http://youtu.be/abcd, where abcd is the video ID
if ($urls['host'] == 'youtu.be') :

    $imgPath = ltrim($urls['path'],'/');

//Expect the URL to be http://www.youtube.com/embed/abcd
elseif (strpos($urls['path'],'embed') == 1) :

    $imgPath = end(explode('/',$urls['path']));

//Expect the URL to be abcd only
elseif (strpos($url,'/') === false):

    $imgPath = $url;

//Expect the URL to be http://www.youtube.com/watch?v=abcd
else :

    parse_str($urls['query']);

    $imgPath = $v;

endif;

C# IPAddress from string

You've probably miss-typed something above that bit of code or created your own class called IPAddress. If you're using the .net one, that function should be available.

Have you tried using System.Net.IPAddress just in case?

System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse("127.0.0.1");  //127.0.0.1 as an example

The docs on Microsoft's site have a complete example which works fine on my machine.

Using setDate in PreparedStatement

Not sure, but what I think you're looking for is to create a java.util.Date from a String, then convert that java.util.Date to a java.sql.Date.

try this:

private static java.sql.Date getCurrentDate(String date) {

    java.util.Date today;
    java.sql.Date rv = null;
    try {

        SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
        today = format.parse(date);
        rv = new java.sql.Date(today.getTime());
        System.out.println(rv.getTime());

    } catch (Exception e) {
        System.out.println("Exception: " + e.getMessage());
    } finally {
        return rv;
    }

}    

Will return a java.sql.Date object for setDate();

The function above will print out a long value:

1375934400000

php.ini: which one?

It really depends on the situation, for me its in fpm as I'm using PHP5-FPM. A solution to your problem could be a universal php.ini and then using a symbolic link created like:

ln -s /etc/php5/php.ini php.ini

Then any modifications you make will be in one general .ini file. This is probably not really the best solution though, you might want to look into modifying some configuration so that you literally use one file, on one location. Not multiple locations hacked together.

Where can I find a list of Mac virtual key codes?

Here are the all keycodes.

Here is a table with some keycodes for the three platforms. It is based on a US Extended keyboard layout.

http://web.archive.org/web/20100501161453/http://www.classicteck.com/rbarticles/mackeyboard.php

Or, there is an app in the Mac App Store named "Key Codes". Download it to see the keycodes of the keys you press.

Key Codes:
https://itunes.apple.com/tr/app/key-codes/id414568915?l=tr&mt=12

How do I point Crystal Reports at a new database

Use the Database menu and "Set Datasource Location" menu option to change the name or location of each table in a report.

This works for changing the location of a database, changing to a new database, and changing the location or name of an individual table being used in your report.

To change the datasource connection, go the Database menu and click Set Datasource Location.

  1. Change the Datasource Connection:
    1. From the Current Data Source list (the top box), click once on the datasource connection that you want to change.
    2. In the Replace with list (the bottom box), click once on the new datasource connection.
    3. Click Update.
  2. Change Individual Tables:
    1. From the Current Data Source list (the top box), expand the datasource connection that you want to change.
    2. Find the table for which you want to update the location or name.
    3. In the Replace with list (the bottom box), expand the new datasource connection.
    4. Find the new table you want to update to point to.
    5. Click Update.
    6. Note that if the table name has changed, the old table name will still appear in the Field Explorer even though it is now using the new table. (You can confirm this be looking at the Table Name of the table's properties in Current Data Source in Set Datasource Location. Screenshot http://i.imgur.com/gzGYVTZ.png) It's possible to rename the old table name to the new name from the context menu in Database Expert -> Selected Tables.
  3. Change Subreports:
    1. Repeat each of the above steps for any subreports you might have embedded in your report.
    2. Close the Set Datasource Location window.
  4. Any Commands or SQL Expressions:
    1. Go to the Database menu and click Database Expert.
    2. If the report designer used "Add Command" to write custom SQL it will be shown in the Selected Tables box on the right.
    3. Right click that command and choose "Edit Command".
    4. Check if that SQL is specifying a specific database. If so you might need to change it.
    5. Close the Database Expert window.
    6. In the Field Explorer pane on the right, right click any SQL Expressions.
    7. Check if the SQL Expressions are specifying a specific database. If so you might need to change it also.
    8. Save and close your Formula Editor window when you're done editing.

And try running the report again.

The key is to change the datasource connection first, then any tables you need to update, then the other stuff. The connection won't automatically change the tables underneath. Those tables are like goslings that've imprinted on the first large goose-like animal they see. They'll continue to bypass all reason and logic and go to where they've always gone unless you specifically manually change them.

To make it more convenient, here's a tip: You can "Show SQL Query" in the Database menu, and you'll see table names qualified with the database (like "Sales"."dbo"."Customers") for any tables that go straight to a specific database. That might make the hunting easier if you have a lot of stuff going on. When I tackled this problem I had to change each and every table to point to the new table in the new database.

Relational Database Design Patterns?

Depends what you mean by a pattern. If you're thinking Person/Company/Transaction/Product and such, then yes - there are a lot of generic database schemas already available.

If you're thinking Factory, Singleton... then no - you don't need any of these as they're too low level for DB programming.

If you're thinking database object naming, then it's under the category of conventions, not design per se.

BTW, S.Lott, one-to-many and many-to-many relationships aren't "patterns". They're the basic building blocks of the relational model.

Convert Promise to Observable

You can add a wrapper around promise functionality to return an Observable to observer.

  • Creating a Lazy Observable using defer() operator which allows you to create the Observable only when the Observer subscribes.
import { of, Observable, defer } from 'rxjs'; 
import { map } from 'rxjs/operators';


function getTodos$(): Observable<any> {
  return defer(()=>{
    return fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json())
      .then(json => {
        return json;
      })
  });
}

getTodos$().
 subscribe(
   (next)=>{
     console.log('Data is:', next);
   }
)

mysql query result into php array

I think you wanted to do this:

while( $row = mysql_fetch_assoc( $result)){
    $new_array[] = $row; // Inside while loop
}

Or maybe store id as key too

 $new_array[ $row['id']] = $row;

Using the second ways you would be able to address rows directly by their id, such as: $new_array[ 5].

Import numpy on pycharm

In PyCharm go to

  1. File ? Settings, or use Ctrl + Alt + S
  2. < project name > ? Project Interpreter ? gear symbol ? Add Local
  3. navigate to C:\Miniconda3\envs\my_env\python.exe, where my_env is the environment you want to use

Alternatively, in step 3 use C:\Miniconda3\python.exe if you did not create any further environments (if you never invoked conda create -n my_env python=3).

You can get a list of your current environments with conda info -e and switch to one of them using activate my_env.

SimpleXML - I/O warning : failed to load external entity

You can also load the content with cURL, if file_get_contents insn't enabled on your server.

Example:

$ch = curl_init();  

curl_setopt($ch,CURLOPT_URL,"http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=int");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

$output = curl_exec($ch);

curl_close($ch);

$items = simplexml_load_string($output);

Randomize numbers with jQuery?

This doesn't require jQuery. The JavaScript Math.random function returns a random number between 0 and 1, so if you want a number between 1 and 6, you can do:

var number = 1 + Math.floor(Math.random() * 6);

Update: (as per comment) If you want to display a random number that changes every so often, you can use setInterval to create a timer:

setInterval(function() {
  var number = 1 + Math.floor(Math.random() * 6);
  $('#my_div').text(number);
},
1000); // every 1 second

How to find minimum value from vector?

You have an error in your code. This line:

for(int i=0;i<v[n];i++)

should be

for(int i=0;i<n;i++)

because you want to search n places in your vector, not v[n] places (which wouldn't mean anything)

Determine what attributes were changed in Rails after_save callback?

To anyone seeing this later on, as it currently (Aug. 2017) tops google: It is worth mentioning, that this behavior will be altered in Rails 5.2, and has deprecation warnings as of Rails 5.1, as ActiveModel::Dirty changed a bit.

What do I change?

If you're using attribute_changed? method in the after_*-callbacks, you'll see a warning like:

DEPRECATION WARNING: The behavior of attribute_changed? inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after save returned (e.g. the opposite of what it returns now). To maintain the current behavior, use saved_change_to_attribute? instead. (called from some_callback at /PATH_TO/app/models/user.rb:15)

As it mentions, you could fix this easily by replacing the function with saved_change_to_attribute?. So for example, name_changed? becomes saved_change_to_name?.

Likewise, if you're using the attribute_change to get the before-after values, this changes as well and throws the following:

DEPRECATION WARNING: The behavior of attribute_change inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after save returned (e.g. the opposite of what it returns now). To maintain the current behavior, use saved_change_to_attribute instead. (called from some_callback at /PATH_TO/app/models/user.rb:20)

Again, as it mentions, the method changes name to saved_change_to_attribute which returns ["old", "new"]. or use saved_changes, which returns all the changes, and these can be accessed as saved_changes['attribute'].

Python socket.error: [Errno 111] Connection refused

The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND command on another connection, but it apparently was "not opening [it] up in sync with the client side".

Well, the main reason would be there was no synchronisation whatsoever. Calling:

cs.send("SEND " + FILE)
cs.close()

would just place the data into a OS buffer; close would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep after close might mitigate the problem, but this is not synchronisation.

The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK, or better PORT 36250 to indicate where to connect). This would make sure the server is already listening.

The other thing is you must check the return values of send to make sure how many bytes was taken from your buffer. Or use sendall.

(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)

how to display full stored procedure code?

Normally speaking you'd use a DB manager application like pgAdmin, browse to the object you're interested in, and right click your way to "script as create" or similar.

Are you trying to do this... without a management app?

Why does AngularJS include an empty option in select?

Something similar was happening to me too and was caused by an upgrade to angular 1.5.ng-init seems to be being parsed for type in newer versions of Angular. In older Angular ng-init="myModelName=600" would map to an option with value "600" i.e. <option value="600">First</option> but in Angular 1.5 it won't find this as it seems to be expecting to find an option with value 600 i.e <option value=600>First</option>. Angular would then insert a random first item:

<option value="? number:600 ?"></option>

Angular < 1.2.x

<select ng-model="myModelName" ng-init="myModelName=600">
  <option value="600">First</option>
  <option value="700">Second</option>
</select>

Angular > 1.2

<select ng-model="myModelName" ng-init="myModelName='600'">
  <option value="600">First</option>
  <option value="700">Second</option>
</select>

Flutter position stack widget in center

A Stack allows you to stack elements on top of each other, with the last element in the array taking the highest priority. You can use Align, Positioned, or Container to position the children of a stack.

Align

Widgets are moved by setting the alignment with Alignment, which has static properties like topCenter, bottomRight, and so on. Or you can take full control and set Alignment(1.0, -1.0), which takes x,y values ranging from 1.0 to -1.0, with (0,0) being the center of the screen.

  Stack(
      children: [
        Align(
          alignment: Alignment.topCenter,
          child: Container(
              height: 80,
              width: 80, color: Colors.blueAccent
          ),
        ),
        Align(
          alignment: Alignment.center,
          child: Container(
              height: 80,
              width: 80, color: Colors.deepPurple
          ),
        ),
        Container(
          alignment: Alignment.bottomCenter,
          // alignment: Alignment(1.0, -1.0),
          child: Container(
              height: 80,
              width: 80, color: Colors.amber
          ),
        )
      ]
  )

enter image description here

Cannot get to $rootScope

You can not ask for instance during configuration phase - you can ask only for providers.

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

// configure stuff
app.config(function($routeProvider, $locationProvider) {
  // you can inject any provider here
});

// run blocks
app.run(function($rootScope) {
  // you can inject any instance here
});

See http://docs.angularjs.org/guide/module for more info.

Python: Total sum of a list of numbers with the for loop

l = [1,2,3,4,5]
sum = 0
for x in l:
    sum = sum + x

And you can change l for any list you want.

How to use the switch statement in R functions?

This is a more general answer to the missing "Select cond1, stmt1, ... else stmtelse" connstruction in R. It's a bit gassy, but it works an resembles the switch statement present in C

while (TRUE) {
  if (is.na(val)) {
    val <- "NULL"
    break
  }
  if (inherits(val, "POSIXct") || inherits(val, "POSIXt")) {
    val <- paste0("#",  format(val, "%Y-%m-%d %H:%M:%S"), "#")
    break
  }
  if (inherits(val, "Date")) {
    val <- paste0("#",  format(val, "%Y-%m-%d"), "#")
    break
  }
  if (is.numeric(val)) break
  val <- paste0("'", gsub("'", "''", val), "'")
  break
}

How can I update the current line in a C# Windows Console App?

Here is my take on s soosh's and 0xA3's answers. It can update the console with user messages while updating the spinner and has an elapsed time indicator aswell.

public class ConsoleSpiner : IDisposable
{
    private static readonly string INDICATOR = "/-\\|";
    private static readonly string MASK = "\r{0} {1:c} {2}";
    int counter;
    Timer timer;
    string message;

    public ConsoleSpiner() {
        counter = 0;
        timer = new Timer(200);
        timer.Elapsed += TimerTick;
    }

    public void Start() {
        timer.Start();
    }

    public void Stop() {
        timer.Stop();
        counter = 0;
    }

    public string Message {
        get { return message; }
        set { message = value; }
    }

    private void TimerTick(object sender, ElapsedEventArgs e) {
        Turn();
    }

    private void Turn() {
        counter++;
        var elapsed = TimeSpan.FromMilliseconds(counter * 200);
        Console.Write(MASK, INDICATOR[counter % 4], elapsed, this.Message);
    }

    public void Dispose() {
        Stop();
        timer.Elapsed -= TimerTick;
        this.timer.Dispose();
    }
}

usage is something like this:

class Program
{
    static void Main(string[] args)
    {
        using (var spinner = new ConsoleSpiner())
        {
            spinner.Start();
            spinner.Message = "About to do some heavy staff :-)"
            DoWork();
            spinner.Message = "Now processing other staff".
            OtherWork();
            spinner.Stop();
        }
        Console.WriteLine("COMPLETED!!!!!\nPress any key to exit.");

    }
}

How to write palindrome in JavaScript

Frist I valid this word with converting lowercase and removing whitespace and then compare with reverse word within parameter word.

function isPalindrome(input) {
    const toValid = input.trim("").toLowerCase();
    const reverseWord = toValid.split("").reverse().join("");
    return reverseWord == input.toLowerCase().trim() ? true : false;
}
isPalindrome("    madam ");
//true

How to write UPDATE SQL with Table alias in SQL Server 2008?

You can always take the CTE, (Common Tabular Expression), approach.

;WITH updateCTE AS
(
    SELECT ID, TITLE 
    FROM HOLD_TABLE
    WHERE ID = 101
)

UPDATE updateCTE
SET TITLE = 'TEST';

How can I split a text file using PowerShell?

Sounds like a job for the UNIX command split:

split MyBigFile.csv

Just split my 55 GB csv file in 21k chunks in less than 10 minutes.

It's not native to PowerShell though, but comes with, for instance, the git for windows package https://git-scm.com/download/win

ReactJS: Warning: setState(...): Cannot update during an existing state transition

From react docs Passing arguments to event handlers

<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>

What is a good pattern for using a Global Mutex in C#?

Neither Mutex nor WinApi CreateMutex() works for me.

An alternate solution:

static class Program
{
    [STAThread]
    static void Main()
    {
        if (SingleApplicationDetector.IsRunning()) {
            return;
        }

        Application.Run(new MainForm());

        SingleApplicationDetector.Close();
    }
}

And the SingleApplicationDetector:

using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Threading;

public static class SingleApplicationDetector
{
    public static bool IsRunning()
    {
        string guid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();
        var semaphoreName = @"Global\" + guid;
        try {
            __semaphore = Semaphore.OpenExisting(semaphoreName, SemaphoreRights.Synchronize);

            Close();
            return true;
        }
        catch (Exception ex) {
            __semaphore = new Semaphore(0, 1, semaphoreName);
            return false;
        }
    }

    public static void Close()
    {
        if (__semaphore != null) {
            __semaphore.Close();
            __semaphore = null;
        }
    }

    private static Semaphore __semaphore;
}

Reason to use Semaphore instead of Mutex:

The Mutex class enforces thread identity, so a mutex can be released only by the thread that acquired it. By contrast, the Semaphore class does not enforce thread identity.

<< System.Threading.Mutex

Ref: Semaphore.OpenExisting()

Prevent HTML5 video from being downloaded (right-click saved)?

Using a service such as Vimeo: Sign in Vimeo > Goto Video > Settings > Privacy > Mark as Secured, and also select embed domains. Once the embed domains are set, it will not allow anyone to embed the video or display it from the browser unless connecting from the domains specified. So, if you have a page that is secured on your server which loads the Vimeo player in iframe, this makes it pretty difficult to get around.

Lightweight Javascript DB for use in Node.js

Maybe you should try LocallyDB it's easy-to-use and lightweight in addition to the with advanced selecting system similar to javascript conditional expression...

https://github.com/btwael/locallydb

javac: invalid target release: 1.8

Maven setting:

<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

Jquery, checking if a value exists in array or not

Try jQuery.inArray()

Here is a jsfiddle link using the same code : http://jsfiddle.net/yrshaikh/SUKn2/

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0

Example Code :

<html>
   <head>
      <style>
         div { color:blue; }
         span { color:red; }
  </style>
      <script src="http://code.jquery.com/jquery-latest.js"></script>
   </head>
   <body>    
      <div>"John" found at <span></span></div>
      <div>4 found at <span></span></div>
      <div>"Karl" not found, so <span></span></div>
      <div>
         "Pete" is in the array, but not at or after index 2, so <span></span>
      </div>
      <script>
         var arr = [ 4, "Pete", 8, "John" ];
         var $spans = $("span");
         $spans.eq(0).text(jQuery.inArray("John", arr));
         $spans.eq(1).text(jQuery.inArray(4, arr));
         $spans.eq(2).text(jQuery.inArray("Karl", arr));
         $spans.eq(3).text(jQuery.inArray("Pete", arr, 2));
      </script>  
   </body>
</html>

Output:

"John" found at 3
4 found at 0
"Karl" not found, so -1
"Pete" is in the array, but not at or after index 2, so -1

How do you remove all the options of a select box and then add one option and select it with jQuery?

I saw this code in Select2 - Clearing Selections

$('#mySelect').val(null).trigger('change');

This code works well with jQuery even without Select2

scp or sftp copy multiple files with single command

Copy multiple files from remote to local:

$ scp [email protected]:/some/remote/directory/\{a,b,c\} ./

Copy multiple files from local to remote:

$ scp foo.txt bar.txt [email protected]:~
$ scp {foo,bar}.txt [email protected]:~
$ scp *.txt [email protected]:~

Copy multiple files from remote to remote:

$ scp [email protected]:/some/remote/directory/foobar.txt \
[email protected]:/some/remote/directory/

Source: http://www.hypexr.org/linux_scp_help.php

Go to next item in ForEach-Object

I know this is an old post, but I wanted to add something I learned for the next folks who land here while googling.

In Powershell 5.1, you want to use continue to move onto the next item in your loop. I tested with 6 items in an array, had a foreach loop through, but put an if statement with:

foreach($i in $array){    
    write-host -fore green "hello $i"
    if($i -like "something"){
        write-host -fore red "$i is bad"
        continue
        write-host -fore red "should not see this"
    }
}

Of the 6 items, the 3rd one was something. As expected, it looped through the first 2, then the matching something gave me the red line where $i matched, I saw something is bad and then it went on to the next item in the array without saying should not see this. I tested with return and it exited the loop altogether.

How to run a C# application at Windows startup?

You could try copying a shortcut to your application into the startup folder instead of adding things to the registry. You can get the path with Environment.SpecialFolder.Startup. This is available in all .net frameworks since 1.1.

Alternatively, maybe this site will be helpful to you, it lists a lot of the different ways you can get an application to auto-start.

How can I convert String to Int?

You can write your own extension method

public static class IntegerExtensions
{
    public static int ParseInt(this string value, int defaultValue = 0)
    {
        int parsedValue;
        if (int.TryParse(value, out parsedValue))
        {
            return parsedValue;
        }

        return defaultValue;
    }

    public static int? ParseNullableInt(this string value)
    {
        if (string.IsNullOrEmpty(value))
        {
            return null;
        }

        return value.ParseInt();
    }
}

And wherever in code just call

int myNumber = someString.ParseInt(); // Returns value or 0
int age = someString.ParseInt(18); // With default value 18
int? userId = someString.ParseNullableInt(); // Returns value or null

In this concrete case

int yourValue = TextBoxD1.Text.ParseInt();

How to use timeit module

You would create two functions and then run something similar to this. Notice, you want to choose the same number of execution/run to compare apple to apple.
This was tested under Python 3.7.

enter image description here Here is the code for ease of copying it

!/usr/local/bin/python3
import timeit

def fibonacci(n):
    """
    Returns the n-th Fibonacci number.
    """
    if(n == 0):
        result = 0
    elif(n == 1):
        result = 1
    else:
        result = fibonacci(n-1) + fibonacci(n-2)
    return result

if __name__ == '__main__':
    import timeit
    t1 = timeit.Timer("fibonacci(13)", "from __main__ import fibonacci")
    print("fibonacci ran:",t1.timeit(number=1000), "milliseconds")

MaxJsonLength exception in ASP.NET MVC during JavaScriptSerializer

I solved the issue by following this link

namespace System.Web.Mvc
{
public sealed class JsonDotNetValueProviderFactory : ValueProviderFactory
{
    public override IValueProvider GetValueProvider(ControllerContext controllerContext)
    {
        if (controllerContext == null)
            throw new ArgumentNullException("controllerContext");

        if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
            return null;

        var reader = new StreamReader(controllerContext.HttpContext.Request.InputStream);
        var bodyText = reader.ReadToEnd();

        return String.IsNullOrEmpty(bodyText) ? null : new DictionaryValueProvider<object>(JsonConvert.DeserializeObject<ExpandoObject>(bodyText, new ExpandoObjectConverter()), CultureInfo.CurrentCulture);
    }
}

}

protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);

        //Remove and JsonValueProviderFactory and add JsonDotNetValueProviderFactory
        ValueProviderFactories.Factories.Remove(ValueProviderFactories.Factories.OfType<JsonValueProviderFactory>().FirstOrDefault());
        ValueProviderFactories.Factories.Add(new JsonDotNetValueProviderFactory());
    }

DECODE( ) function in SQL Server

when I use the function

select dbo.decode(10>1 ,'yes' ,'no')

then say syntax error near '>'

Unfortunately, that does not get you around having the CASE clause in the SQL, since you would need it to convert the logical expression to a bit parameter to match the type of the first function argument:

create function decode(@var1 as bit, @var2 as nvarchar(100), @var3 as nvarchar(100))
returns nvarchar(100)
begin
return case when @var1 = 1 then @var2 else @var3 end;
end;

select dbo.decode(case when 10 > 1 then 1 else 0 end, 'Yes', 'No');

How do I draw a grid onto a plot in Python?

Using rcParams you can show grid very easily as follows

plt.rcParams['axes.facecolor'] = 'white'
plt.rcParams['axes.edgecolor'] = 'white'
plt.rcParams['axes.grid'] = True
plt.rcParams['grid.alpha'] = 1
plt.rcParams['grid.color'] = "#cccccc"

If grid is not showing even after changing these parameters then use

plt.grid(True)

before calling

plt.show()

Limiting double to 3 decimal places

In C lang:

double truncKeepDecimalPlaces(double value, int numDecimals)
{
    int x = pow(10, numDecimals);
    return (double)trunc(value * x) / x;
}

How to trigger click on page load?

$(function(){

    $(selector).click();

});

datetime.parse and making it work with a specific format

DateTime.ParseExact(input,"yyyyMMdd HH:mm",null);

assuming you meant to say that minutes followed the hours, not seconds - your example is a little confusing.

The ParseExact documentation details other overloads, in case you want to have the parse automatically convert to Universal Time or something like that.

As @Joel Coehoorn mentions, there's also the option of using TryParseExact, which will return a Boolean value indicating success or failure of the operation - I'm still on .Net 1.1, so I often forget this one.

If you need to parse other formats, you can check out the Standard DateTime Format Strings.

How to convert milliseconds to "hh:mm:ss" format?

I tried as shown in the first answer. It works, but minus brought me into confusion. My answer by Groovy:

import static java.util.concurrent.TimeUnit.*

...

private static String formatElapsedTime(long millis) {

    int hrs = MILLISECONDS.toHours(millis) % 24
    int min = MILLISECONDS.toMinutes(millis) % 60
    int sec = MILLISECONDS.toSeconds(millis) % 60
    int mls = millis % 1000

    sprintf( '%02d:%02d:%02d (%03d)', [hrs, min, sec, mls])
}

Not able to launch IE browser using Selenium2 (Webdriver) with Java

  1. Go to IE->Tools->Internet Options.
  2. Go to Security tab.
  3. Either Enable/Disable the protected mode for all(Internet, Local Intranet, Trusted Sites & Restricted Sites.)

Count unique values with pandas per groups

df.domain.value_counts()

>>> df.domain.value_counts()

vk.com          5

twitter.com     2

google.com      1

facebook.com    1

Name: domain, dtype: int64

Disable browser cache for entire ASP.NET website

You may want to disable browser caching for all pages rendered by controllers (i.e. HTML pages), but keep caching in place for resources such as scripts, style sheets, and images. If you're using MVC4+ bundling and minification, you'll want to keep the default cache durations for scripts and stylesheets (very long durations, since the cache gets invalidated based on a change to a unique URL, not based on time).

In MVC4+, to disable browser caching across all controllers, but retain it for anything not served by a controller, add this to FilterConfig.RegisterGlobalFilters:

filters.Add(new DisableCache());

Define DisableCache as follows:

class DisableCache : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    }
}

Is there a code obfuscator for PHP?

I'm not sure you can label obfuscation of an interpreted language as pointless (I'm unable to add a comment to Schwern's post, so here goes a new entry).

I think it's a little shortsighted to assume you know all the possible scenarios where someone would like to obfuscate code, and you assume that anyone will actually be willing to go to whatever necessary lengths to view that code once obfuscated. Consider my current scenario:

I work for a consulting company that is developing a large and fairly sophisticated PHP-based site. The project will be hosted on a client's server that is hosting other sites developed by other consultancies. Technically any code we write is owned by the client, so we can't license it. However, any other consultancy (competitor) with access to the server can copy our code without getting permission from the client first. We therefore have a genuine reason for obfuscation - to make the effort required for a competitor to understand our code more than the effort of creating a copy of our work from scratch.

What does the "__block" keyword mean?

It means that the variable it is a prefix to is available to be used within a block.

html select option separator

Instead of the regular hyphon I replaced it using a horizontal bar symbol from the extended character set, it won't look very nice if the user is in another country that replaces that character but works fine for me. There is a range of different chacters you could use for some great effects and there is no css involved.

<option value='-' disabled>----</option>

Java: How to check if object is null?

DIY

private boolean isNull(Object obj) {
    return obj == null;
}

Drawable drawable = Common.getDrawableFromUrl(this, product.getMapPath());
if (isNull(drawable)) {
    drawable = getRandomDrawable();
}

Get month and year from a datetime in SQL Server 2005

How about this?

Select DateName( Month, getDate() ) + ' ' + DateName( Year, getDate() )

checking if number entered is a digit in jquery

var yourfield = $('fieldname').val();

if($.isNumeric(yourfield)) { 
        console.log('IM A NUMBER');
} else { 
        console.log('not a number');
}

JQUERY DOCS:

https://api.jquery.com/jQuery.isNumeric/

Position of a string within a string using Linux shell script?

You can use grep to get the byte-offset of the matching part of a string:

echo $str | grep -b -o str

As per your example:

[user@host ~]$ echo "The cat sat on the mat" | grep -b -o cat
4:cat

you can pipe that to awk if you just want the first part

echo $str | grep -b -o str | awk 'BEGIN {FS=":"}{print $1}'

No converter found capable of converting from type to type

Return ABDeadlineType from repository:

public interface ABDeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {
    List<ABDeadlineType> findAllSummarizedBy();
}

and then convert to DeadlineType. Manually or use mapstruct.

Or call constructor from @Query annotation:

public interface DeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {

    @Query("select new package.DeadlineType(a.id, a.code) from ABDeadlineType a ")
    List<DeadlineType> findAllSummarizedBy();
}

Or use @Projection:

@Projection(name = "deadline", types = { ABDeadlineType.class })
public interface DeadlineType {

    @Value("#{target.id}")
    String getId();

    @Value("#{target.code}")
    String getText();

}

Update: Spring can work without @Projection annotation:

public interface DeadlineType {
    String getId();    
    String getText();
}

Writing data into CSV file in C#

Instead of calling every time AppendAllText() you could think about opening the file once and then write the whole content once:

var file = @"C:\myOutput.csv";

using (var stream = File.CreateText(file))
{
    for (int i = 0; i < reader.Count(); i++)
    {
        string first = reader[i].ToString();
        string second = image.ToString();
        string csvRow = string.Format("{0},{1}", first, second);

        stream.WriteLine(csvRow);
    }
}

How to change the style of a DatePicker in android?

Create a new style

<style name="my_dialog_theme" parent="ThemeOverlay.AppCompat.Dialog">
    <item name="colorAccent">@color/colorAccent</item>                   <!--header background-->
    <item name="android:windowBackground">@color/colorPrimary</item>     <!--calendar background-->
    <item name="android:colorControlActivated">@color/colorAccent</item> <!--selected day-->
    <item name="android:textColorPrimary">@color/colorPrimaryText</item> <!--days of the month-->
    <item name="android:textColorSecondary">@color/colorAccent</item>    <!--days of the week-->
</style>

Then initialize the dialog

Calendar mCalendar = new GregorianCalendar();
mCalendar.setTime(new Date());

new DatePickerDialog(mContext, R.style.my_dialog_theme, new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        //do something with the date
    }
}, mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH)).show();

Result:

enter image description here

Select info from table where row has max date

Using an in can have a performance impact. Joining two subqueries will not have the same performance impact and can be accomplished like this:

SELECT *
  FROM (SELECT msisdn
              ,callid
              ,Change_color
              ,play_file_name
              ,date_played
          FROM insert_log
         WHERE play_file_name NOT IN('Prompt1','Conclusion_Prompt_1','silent')
        ORDER BY callid ASC) t1
       JOIN (SELECT MAX(date_played) AS date_played
               FROM insert_log GROUP BY callid) t2
         ON t1.date_played = t2.date_played

Angular HttpClient "Http failure during parsing"

if you have options

return this.http.post(`${this.endpoint}/account/login`,payload, { ...options, responseType: 'text' })

Convert textbox text to integer

You don't need to write a converter, just do this in your handler/codebehind:

int i = Convert.ToInt32(txtMyTextBox.Text);

OR

int i = int.Parse(txtMyTextBox.Text);

The Text property of your textbox is a String type, so you have to perform the conversion in the code.

Best way to add Activity to an Android project in Eclipse?

The R.* classes are generated dynamically. I leave the "Build automatically" option on in the Project menu so that mine R.* classes are always up-to-date.

Additionally, when creating new Activities, I copy and rename old ones, especially if they are similar to the new Activity that I need because Eclipse renames everything for you.

Otherwise, as others have said, the File->New->Class command works well and will build your file for you including templates for required methods based on your class, its inheritance and interfaces.

How to add item to the beginning of List<T>?

Update: a better idea, set the "AppendDataBoundItems" property to true, then declare the "Choose item" declaratively. The databinding operation will add to the statically declared item.

<asp:DropDownList ID="ddl" runat="server" AppendDataBoundItems="true">
    <asp:ListItem Value="0" Text="Please choose..."></asp:ListItem>
</asp:DropDownList>

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.appenddatabounditems.aspx

-Oisin

What is the difference between i = i + 1 and i += 1 in a 'for' loop?

The short form(a += 1) has the option to modify a in-place , instead of creating a new object representing the sum and rebinding it back to the same name(a = a + 1).So,The short form(a += 1) is much efficient as it doesn't necessarily need to make a copy of a unlike a = a + 1.

Also even if they are outputting the same result, notice they are different because they are separate operators: + and +=

What are ABAP and SAP?

SAP is a company and offers a full Enterprise Resource Planning (ERP) system, business platform, and the associated modules (financials, general ledger, &c).

ABAP is the primary programming language used to write SAP software and customizations. It would do it injustice to think of it as COBOL and SQL on steroids, but that gives you an idea. ABAP runs within the SAP system.

SAP and ABAP abstract the DB and run atop various underlying DBMSs.

SAP produces other things as well and even publicly says they dabble in Java and even produce a J2EE container, but tried-and-true SAP is ABAP through-and-through.

The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security

I know, I am a little late to the party ... what happen a lot, you just use default settings in your app pool in IIS. In IIS Administration utility, go to app pools->select pool-->advanced settings->Process Model/Identity and select a user identity which has right permissions. By default it is set to ApplicationPoolIdentity. If you're developer, you most likely admin on your machine, so you can select your account to run app pool. On the deployment servers, let admins to deal with it.

In NetBeans how do I change the Default JDK?

If I remember correctly, you'll need to set the netbeans_jdkhome property in your netbeans config file. Should be in your etc/netbeans.conf file.

Sublime Text 2 multiple line edit

I'm not sure it's possible "out of the box". And, unfortunately, I don't know an appropriate plugin either. To solve the problem you suggested you could use regular expressions.

  1. Cmd + F (Find)
  2. Regexp: [^ ]+ (or \d+, or whatever you prefer)
  3. Option + F (Find All)
  4. Edit it

Hotkeys may vary depending on you OS and personal preferences (mine are for OS X).

How can I label points in this scatterplot?

Your call to text() doesn't output anything because you inverted your x and your y:

plot(abs_losses, percent_losses, 
     main= "Absolute Losses vs. Relative Losses(in%)",
     xlab= "Losses (absolute, in miles of millions)",
     ylab= "Losses relative (in % of January´2007 value)",
     col= "blue", pch = 19, cex = 1, lty = "solid", lwd = 2)

text(abs_losses, percent_losses, labels=namebank, cex= 0.7)

Now if you want to move your labels down, left, up or right you can add argument pos= with values, respectively, 1, 2, 3 or 4. For instance, to place your labels up:

 text(abs_losses, percent_losses, labels=namebank, cex= 0.7, pos=3)

enter image description here

You can of course gives a vector of value to pos if you want some of the labels in other directions (for instance for Goldman_Sachs, UBS and Société_Generale since they are overlapping with other labels):

 pos_vector <- rep(3, length(namebank))
 pos_vector[namebank %in% c("Goldman_Sachs", "Societé_Generale", "UBS")] <- 4
 text(abs_losses, percent_losses, labels=namebank, cex= 0.7, pos=pos_vector)

enter image description here

How do I prevent site scraping?

Method One (Small Sites Only):
Serve encrypted / encoded data.
I Scape the web using python (urllib, requests, beautifulSoup etc...) and found many websites that serve encrypted / encoded data that is not decrypt-able in any programming language simply because the encryption method does not exist.

I achieved this in a PHP website by encrypting and minimizing the output (WARNING: this is not a good idea for large sites) the response was always jumbled content.

Example of minimizing output in PHP (How to minify php page html output?):

<?php
  function sanitize_output($buffer) {
    $search = array(
      '/\>[^\S ]+/s', // strip whitespaces after tags, except space
      '/[^\S ]+\</s', // strip whitespaces before tags, except space
      '/(\s)+/s'      // shorten multiple whitespace sequences
    );
    $replace = array('>', '<', '\\1');
    $buffer = preg_replace($search, $replace, $buffer);
    return $buffer;
  }
  ob_start("sanitize_output");
?>

Method Two:
If you can't stop them screw them over serve fake / useless data as a response.

Method Three:
block common scraping user agents, you'll see this in major / large websites as it is impossible to scrape them with "python3.4" as you User-Agent.

Method Four:
Make sure all the user headers are valid, I sometimes provide as many headers as possible to make my scraper seem like an authentic user, some of them are not even true or valid like en-FU :).
Here is a list of some of the headers I commonly provide.

headers = {
  "Requested-URI": "/example",
  "Request-Method": "GET",
  "Remote-IP-Address": "656.787.909.121",
  "Remote-IP-Port": "69696",
  "Protocol-version": "HTTP/1.1",
  "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
  "Accept-Encoding": "gzip,deflate",
  "Accept-Language": "en-FU,en;q=0.8",
  "Cache-Control": "max-age=0",
  "Connection": "keep-alive",
  "Dnt": "1",  
  "Host": "http://example.com",
  "Referer": "http://example.com",
  "Upgrade-Insecure-Requests": "1",
  "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36"
}

C# ASP.NET Send Email via TLS

On SmtpClient there is an EnableSsl property that you would set.

i.e.

SmtpClient client = new SmtpClient(exchangeServer);
client.EnableSsl = true;
client.Send(msg);

Bold & Non-Bold Text In A Single UILabel?

That's easy to do in Interface Builder:

1) make UILabel Attributed in Attributes Inspector

Bold Example Step 1

2) select part of phrase you want to make bold

Bold Example Step 2

3) change its font (or bold typeface of the same font) in font selector

Bold Example Step 3

That's all!

Python integer division yields float

Hope it might help someone instantly.

Behavior of Division Operator in Python 2.7 and Python 3

In Python 2.7: By default, division operator will return integer output.

to get the result in double multiple 1.0 to "dividend or divisor"

100/35 => 2 #(Expected is 2.857142857142857)
(100*1.0)/35 => 2.857142857142857
100/(35*1.0) => 2.857142857142857

In Python 3

// => used for integer output
/ => used for double output

100/35 => 2.857142857142857
100//35 => 2
100.//35 => 2.0    # floating-point result if divsor or dividend real

Git fetch remote branch

[Quick Answer]

There are many alternatives, and my favourites are:

- Alternative 1:

git fetch --all
git checkout YourBranch

Using this alternative using a branch that exist remotely, but not in your local.

- Alternative 2:

git checkout -b 'YourBranch' origin/'YourRemote'

Probably, this is the simplest way.

How can I delete a user in linux when the system says its currently used in a process

First use pkill or kill -9 <pid> to kill the process.

Then use following userdel command to delete user,

userdel -f cafe_fixer

According to userdel man page:

-f, --force

This option forces the removal of the user account, even if the user is still logged in. It also forces userdel to remove the user's home directory and mail spool, even if another user uses the same home directory or if the mail spool is not owned by the specified user. If USERGROUPS_ENAB is defined to yes in /etc/login.defs and if a group exists with the same name as the deleted user, then this group will be removed, even if it is still the primary group of another user.

Edit 1: (by @Ajedi32)

Note: This option (i.e. --force) is dangerous and may leave your system in an inconsistent state.

Edit 2: (by @socketpair)

In spite of the description about some files, this key allows removing the user while it is in use. Don't forget to chdir / before, because this command will also remove home directory.

Floating point inaccuracy examples

A cute piece of numerical weirdness may be observed if one converts 9999999.4999999999 to a float and back to a double. The result is reported as 10000000, even though that value is obviously closer to 9999999, and even though 9999999.499999999 correctly rounds to 9999999.

Number of regex matches

If you find you need to stick with finditer(), you can simply use a counter while you iterate through the iterator.

Example:

>>> from re import *
>>> pattern = compile(r'.ython')
>>> string = 'i like python jython and dython (whatever that is)'
>>> iterator = finditer(pattern, string)
>>> count = 0
>>> for match in iterator:
        count +=1
>>> count
3

If you need the features of finditer() (not matching to overlapping instances), use this method.

Why would a JavaScript variable start with a dollar sign?

As I have experienced for the last 4 years, it will allow some one to easily identify whether the variable pointing a value/object or a jQuery wrapped DOM element

_x000D_
_x000D_
Ex:_x000D_
var name = 'jQuery';_x000D_
var lib = {name:'jQuery',version:1.6};_x000D_
_x000D_
var $dataDiv = $('#myDataDiv');
_x000D_
_x000D_
_x000D_

in the above example when I see the variable "$dataDiv" i can easily say that this variable pointing to a jQuery wrapped DOM element (in this case it is div). and also I can call all the jQuery methods with out wrapping the object again like $dataDiv.append(), $dataDiv.html(), $dataDiv.find() instead of $($dataDiv).append().

Hope it may helped. so finally want to say that it will be a good practice to follow this but not mandatory.

JRE 1.7 - java version - returns: java/lang/NoClassDefFoundError: java/lang/Object

I downloaded new JDK today (1.8.0.73) started c:> java.exe and got the infamous:

Error occurred during initialization of VM
java/lang/NoClassDefFoundError: java/lang/Object

I just wanted to share my working solution on here.

When I cd'ied into the jdk\bin folder, Java would run fine so I knew it was the PATH. I set PATH to just \jdk\bin at CMD to prove it and it worked.

So, one of the folders in the PATH must have had java.exe that was causing the conflict, I thought. As it turned out, it was C:\>ProgramData\Oracle\Java\javapath that holds symlinks to the executables.

java.exe was pointing to jre\bin. The file was corrupt, when I started \jre\bin\java.exe--the exact same error. Bingo. I re-installed JRE and the problem went away. Happy coding...

How to create an integer array in Python?

Use the array module. With it you can store collections of the same type efficiently.

>>> import array
>>> import itertools
>>> a = array_of_signed_ints = array.array("i", itertools.repeat(0, 10))

For more information - e.g. different types, look at the documentation of the array module. For up to 1 million entries this should feel pretty snappy. For 10 million entries my local machine thinks for 1.5 seconds.

The second parameter to array.array is a generator, which constructs the defined sequence as it is read. This way, the array module can consume the zeros one-by-one, but the generator only uses constant memory. This generator does not get bigger (memory-wise) if the sequence gets longer. The array will grow of course, but that should be obvious.

You use it just like a list:

>>> a.append(1)
>>> a.extend([1, 2, 3])
>>> a[-4:]
array('i', [1, 1, 2, 3])
>>> len(a)
14

...or simply convert it to a list:

>>> l = list(a)
>>> len(l)
14

Surprisingly

>>> a = [0] * 10000000

is faster at construction than the array method. Go figure! :)

Valid characters in a Java class name

Further to previous answers its worth noting that:

  1. Java allows any Unicode currency symbol in symbol names, so the following will all work:

$var1 £var2 €var3

I believe the usage of currency symbols originates in C/C++, where variables added to your code by the compiler conventionally started with '$'. An obvious example in Java is the names of '.class' files for inner classes, which by convention have the format 'Outer$Inner.class'

  1. Many C# and C++ programmers adopt the convention of placing 'I' in front of interfaces (aka pure virtual classes in C++). This is not required, and hence not done, in Java because the implements keyword makes it very clear when something is an interface.

Compare:

class Employee : public IPayable //C++

with

class Employee : IPayable //C#

and

class Employee implements Payable //Java

  1. Many projects use the convention of placing an underscore in front of field names, so that they can readily be distinguished from local variables and parameters e.g.

private double _salary;

A tiny minority place the underscore after the field name e.g.

private double salary_;

Why should I use core.autocrlf=true in Git?

Update 2:

Xcode 9 appears to have a "feature" where it will ignore the file's current line endings, and instead just use your default line-ending setting when inserting lines into a file, resulting in files with mixed line endings.

I'm pretty sure this bug didn't exist in Xcode 7; not sure about Xcode 8. The good news is that it appears to be fixed in Xcode 10.

For the time it existed, this bug caused a small amount of hilarity in the codebase I refer to in the question (which to this day uses autocrlf=false), and led to many "EOL" commit messages and eventually to my writing a git pre-commit hook to check for/prevent introducing mixed line endings.

Update:

Note: As noted by VonC, starting from Git 2.8, merge markers will not introduce Unix-style line-endings to a Windows-style file.

Original:

One little hiccup that I've noticed with this setup is that when there are merge conflicts, the lines git adds to mark up the differences do not have Windows line-endings, even when the rest of the file does, and you can end up with a file with mixed line endings, e.g.:

// Some code<CR><LF>
<<<<<<< Updated upstream<LF>
// Change A<CR><LF>
=======<LF>
// Change B<CR><LF>
>>>>>>> Stashed changes<LF>
// More code<CR><LF>

This doesn't cause us any problems (I imagine any tool that can handle both types of line-endings will also deal sensible with mixed line-endings--certainly all the ones we use do), but it's something to be aware of.

The other thing* we've found, is that when using git diff to view changes to a file that has Windows line-endings, lines that have been added display their carriage returns, thus:

    // Not changed

+   // New line added in^M
+^M
    // Not changed
    // Not changed

* It doesn't really merit the term: "issue".

AppendChild() is not a function javascript

Just change

var div = '<div>top div</div>'; // you just created a text string

to

var div = document.createElement("div"); // we want a DIV element instead
div.innerHTML = "top div";

Python: CSV write by column rather than row

Let's assume that (1) you don't have a large memory (2) you have row headings in a list (3) all the data values are floats; if they're all integers up to 32- or 64-bits worth, that's even better.

On a 32-bit Python, storing a float in a list takes 16 bytes for the float object and 4 bytes for a pointer in the list; total 20. Storing a float in an array.array('d') takes only 8 bytes. Increasingly spectacular savings are available if all your data are int (any negatives?) that will fit in 8, 4, 2 or 1 byte(s) -- especially on a recent Python where all ints are longs.

The following pseudocode assumes floats stored in array.array('d'). In case you don't really have a memory problem, you can still use this method; I've put in comments to indicate the changes needed if you want to use a list.

# Preliminary:
import array # list: delete
hlist = []
dlist = []
for each row: 
    hlist.append(some_heading_string)
    dlist.append(array.array('d')) # list: dlist.append([])
# generate data
col_index = -1
for each column:
    col_index += 1
    for row_index in xrange(len(hlist)):
        v = calculated_data_value(row_index, colindex)
        dlist[row_index].append(v)
# write to csv file
for row_index in xrange(len(hlist)):
    row = [hlist[row_index]]
    row.extend(dlist[row_index])
    csv_writer.writerow(row)

Open Source HTML to PDF Renderer with Full CSS Support

Try ABCpdf from webSupergoo. It's a commercial solution, not open source, but the standard edition can be obtained free of charge and will do what you are asking.

ABCpdf fully supports HTML and CSS, live forms and live links. It also uses Microsoft XML Core Services (MSXML) while rendering, so the results should match exactly what you see in Internet Explorer.

The on-line demo can be used to test HTML to PDF rendering without needing to install any software. See: http://www.abcpdfeditor.com/

The following C# code example shows how to render a single page HTML document.

Doc theDoc = new Doc();
theDoc.AddImageUrl("http://www.example.com/");
theDoc.Save("htmlimport.pdf");
theDoc.Clear();

To render multiple pages you'll need the AddImageToChain function, documented here: http://www.websupergoo.com/helppdf7net/source/5-abcpdf6/doc/1-methods/addimagetochain.htm

Convert a python 'type' object to a string

print type(someObject).__name__

If that doesn't suit you, use this:

print some_instance.__class__.__name__

Example:

class A:
    pass
print type(A())
# prints <type 'instance'>
print A().__class__.__name__
# prints A

Also, it seems there are differences with type() when using new-style classes vs old-style (that is, inheritance from object). For a new-style class, type(someObject).__name__ returns the name, and for old-style classes it returns instance.

How to declare and add items to an array in Python?

{} represents an empty dictionary, not an array/list. For lists or arrays, you need [].

To initialize an empty list do this:

my_list = []

or

my_list = list()

To add elements to the list, use append

my_list.append(12)

To extend the list to include the elements from another list use extend

my_list.extend([1,2,3,4])
my_list
--> [12,1,2,3,4]

To remove an element from a list use remove

my_list.remove(2)

Dictionaries represent a collection of key/value pairs also known as an associative array or a map.

To initialize an empty dictionary use {} or dict()

Dictionaries have keys and values

my_dict = {'key':'value', 'another_key' : 0}

To extend a dictionary with the contents of another dictionary you may use the update method

my_dict.update({'third_key' : 1})

To remove a value from a dictionary

del my_dict['key']

import .css file into .less file

From the LESS website:

If you want to import a CSS file, and don’t want LESS to process it, just use the .css extension:

@import "lib.css"; The directive will just be left as is, and end up in the CSS output.

As jitbit points out in the comments below, this is really only useful for development purposes, as you wouldn't want to have unnecessary @imports consuming precious bandwidth.

Fetching data from MySQL database using PHP, Displaying it in a form for editing

please try these

<form action="Delegate_update.php" method="post">
Name
<input type="text" name= "Name" value= "<?php echo $row['Name']; ?> "size=10>
Username
<input type="text" name= "User_name" value= "<?php echo $row['User_name']; ?> "size=10>
Password
<input type="text" name= "User_password" value= "<?php echo $row['User_password']; ?>" size=17>
<input type="submit" name= "submit" value="Update">
</form>

How can I update npm on Windows?

Open PowerShell as administrator.

To install a first time you can use this small script to download the latest msi and run it

$nodeLatest=((curl https://nodejs.org/download/release/latest/).Content | findstr x64.msi) -replace "<(.*?)>", "" -replace "\s+.+", "";
wget "https://nodejs.org/download/release/latest/$nodeLatest" -OutFile (join-path $env:TEMP node.msi); Start-Process (join-path $env:TEMP node.msi)

On future upgrades you can download just node.exe and update npm with

wget https://nodejs.org/download/release/latest/win-x64/node.exe -OutFile 'C:\Program Files\nodejs\node.exe'
npm i -g npm

You should now have the latest node and npm.


I went a little further and decided to implement a nvm for Windows.

https://github.com/brunolm/nvm

Install-Module -Name power-nvm

nvm install latest
nvm default latest

How do I set the time zone of MySQL?

If you're using PDO:

$offset="+10:00";
$db->exec("SET time_zone='".$offset."';");

If you're using MySQLi:

$db->MySQLi->query("SET time_zone='".$offset."';");

More about formatting the offset here: https://www.sitepoint.com/synchronize-php-mysql-timezone-configuration/

Javascript String to int conversion

This is to do with JavaScript's + in operator - if a number and a string are "added" up, the number is converted into a string:

0 + 1; //1
'0' + 1; // '01'

To solve this, use the + unary operator, or use parseInt():

+'0' + 1; // 1
parseInt('0', 10) + 1; // 1

The unary + operator converts it into a number (however if it's a decimal it will retain the decimal places), and parseInt() is self-explanatory (converts into number, ignoring decimal places).

The second argument is necessary for parseInt() to use the correct base when leading 0s are placed:

parseInt('010'); // 8 in older browsers, 10 in newer browsers
parseInt('010', 10); // always 10 no matter what

There's also parseFloat() if you need to convert decimals in strings to their numeric value - + can do that too but it behaves slightly differently: that's another story though.

Javascript reduce on array of objects

If you have a complex object with a lot of data, like an array of objects, you can take a step by step approach to solve this.

For e.g:

const myArray = [{ id: 1, value: 10}, { id: 2, value: 20}];

First, you should map your array into a new array of your interest, it could be a new array of values in this example.

const values = myArray.map(obj => obj.value);

This call back function will return a new array containing only values from the original array and store it on values const. Now your values const is an array like this:

values = [10, 20];

And now your are ready to perform your reduce:

const sum = values.reduce((accumulator, currentValue) => { return accumulator + currentValue; } , 0);

As you can see, the reduce method executes the call back function multiple times. For each time, it takes the current value of the item in the array and sum with the accumulator. So to properly sum it you need to set the initial value of your accumulator as the second argument of the reduce method.

Now you have your new const sum with the value of 30.

Calculating the angle between the line defined by two points

Had a need for similar functionality myself, so after much hair pulling I came up with the function below

/**
 * Fetches angle relative to screen centre point
 * where 3 O'Clock is 0 and 12 O'Clock is 270 degrees
 * 
 * @param screenPoint
 * @return angle in degress from 0-360.
 */
public double getAngle(Point screenPoint) {
    double dx = screenPoint.getX() - mCentreX;
    // Minus to correct for coord re-mapping
    double dy = -(screenPoint.getY() - mCentreY);

    double inRads = Math.atan2(dy, dx);

    // We need to map to coord system when 0 degree is at 3 O'clock, 270 at 12 O'clock
    if (inRads < 0)
        inRads = Math.abs(inRads);
    else
        inRads = 2 * Math.PI - inRads;

    return Math.toDegrees(inRads);
}

Is there a float input type in HTML5?

I have started using inputmode="decimal" which works flawlessly with smartphones:

<input type="text" inputmode="decimal" value="1.5">

Note that we have to use type="text" instead of number. However, on desktop it still allows letters as values.

For desktop you could use:

<input type="number" inputmode="decimal">

which allows 0-9 and . as input and only numbers.

Note that some countries use , as decimal dividor which is activated as default on the NumPad. Thus entering a float number by Numpad would not work as the input field expects a . (in Chrome). That's why you should use type="text" if you have international users on your website.


You can try this on desktop (also with Numpad) and your phone:

_x000D_
_x000D_
<p>Input with type text:</p>
<input type="text" inputmode="decimal" value="1.5">
<br>
<p>Input with type number:</p>
<input type="number" inputmode="decimal" value="1.5">
_x000D_
_x000D_
_x000D_


Reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/inputmode

Favorite Visual Studio keyboard shortcuts

Ctrl + Alt + E = Exception/Catch Settings and code snippets

How to include jQuery in ASP.Net project?

You can include the script file directly in your page/master page, etc using:

 <script type="text/javascript" src="/scripts/jquery.min.js"></script> 

Us use a Content Delivery network like Google or Microsoft:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> 

or:

<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></script>     

Is it possible to program Android to act as physical USB keyboard?

The only way I could see this being possible is if you:

  • modified the Android firmware to give you usb level access at a low enough level that you could operate using the necessary protocol

or

  • Made some sort of special hardware level converter that you attached to the device.

(So I suppose, depending on how much work you want to do, it could be a hardware or software problem.)

What is MVC and what are the advantages of it?

MVC is just a general design pattern that, in the context of lean web app development, makes it easy for the developer to keep the HTML markup in an app’s presentation layer (the view) separate from the methods that receive and handle client requests (the controllers) and the data representations that are returned within the view (the models). It’s all about separation of concerns, that is, keeping code that serves one functional purpose (e.g. handling client requests) sequestered from code that serves an entirely different functional purpose (e.g. representing data).

It’s the same principle for why anybody who’s spent more than 5 min trying to build a website can appreciate the need to keep your HTML markup, JavaScript, and CSS in separate files: If you just dump all of your code into a single file, you end up with spaghetti that’s virtually un-editable later on.

Since you asked for possible "cons": I’m no authority on software architecture design, but based on my experience developing in MVC, I think it’s also important to point out that following a strict, no-frills MVC design pattern is most useful for 1) lightweight web apps, or 2) as the UI layer of a larger enterprise app. I’m surprised this specification isn’t talked about more, because MVC contains no explicit definitions for your business logic, domain models, or really anything in the data access layer of your app. When I started developing in ASP.NET MVC (i.e. before I knew other software architectures even existed), I would end up with very bloated controllers or even view models chock full of business logic that, had I been working on enterprise applications, would have made it difficult for other devs who were unfamiliar with my code to modify (i.e. more spaghetti).

How to get an IFrame to be responsive in iOS Safari?

The problem with all these solutions is that the height of the iframe never really changes.

This means you won't be able to center elements inside the iframe using Javascript, position:fixed;, or position:absolute; since the iframe itself never scrolls.

My solution detailed here is to wrap all the content of the iframe inside a div using this CSS:

#wrap {
    position: fixed;
    top: 0;
    right:0;
    bottom:0;
    left: 0;
    overflow-y: scroll;
    -webkit-overflow-scrolling: touch;
}

This way Safari believes the content has no height and lets you assign the height of the iframe properly. This also allows you to position elements in any way you wish.

You can see a quick and dirty demo here.

Understanding the difference between Object.create() and new SomeFunction()

The object used in Object.create actually forms the prototype of the new object, where as in the new Function() form the declared properties/functions do not form the prototype.

Yes, Object.create builds an object that inherits directly from the one passed as its first argument.

With constructor functions, the newly created object inherits from the constructor's prototype, e.g.:

var o = new SomeConstructor();

In the above example, o inherits directly from SomeConstructor.prototype.

There's a difference here, with Object.create you can create an object that doesn't inherit from anything, Object.create(null);, on the other hand, if you set SomeConstructor.prototype = null; the newly created object will inherit from Object.prototype.

You cannot create closures with the Object.create syntax as you would with the functional syntax. This is logical given the lexical (vs block) type scope of JavaScript.

Well, you can create closures, e.g. using property descriptors argument:

var o = Object.create({inherited: 1}, {
  foo: {
    get: (function () { // a closure
      var closured = 'foo';
      return function () {
        return closured+'bar';
      };
    })()
  }
});

o.foo; // "foobar"

Note that I'm talking about the ECMAScript 5th Edition Object.create method, not the Crockford's shim.

The method is starting to be natively implemented on latest browsers, check this compatibility table.