Programs & Examples On #Autoload

autoload is a language convention which allows missing classes or method dependencies to be loaded on-demand.

Best way to load module/class from lib folder in Rails 3?

If only certain files need access to the modules in lib, just add a require statement to the files that need it. For example, if one model needs to access one module, add:

require 'mymodule'

at the top of the model.rb file.

How do I use PHP namespaces with autoload?

I use this simple hack in one line:

spl_autoload_register(function($name){
        require_once 'lib/'.str_replace('\\','/',$name).'.php';
    });

Using Composer's Autoload

In my opinion, Sergiy's answer should be the selected answer for the given question. I'm sharing my understanding.

I was looking to autoload my package files using composer which I have under the dir structure given below.

<web-root>
    |--------src/
    |           |--------App/
    |           |
    |           |--------Test/
    |
    |---------library/
    |
    |---------vendor/
    |           |
    |           |---------composer/
    |           |           |---------autoload_psr4.php
    |           |           
    |           |----------autoload.php
    |
    |-----------composer.json
    |

I'm using psr-4 autoloading specification.

Had to add below lines to the project's composer.json. I intend to place my class files inside src/App , src/Test and library directory.

"autoload": {
        "psr-4": {
            "OrgName\\AppType\\AppName\\": ["src/App", "src/Test", "library/"]
        }
    } 

This is pretty much self explaining. OrgName\AppType\AppName is my intended namespace prefix. e.g for class User in src/App/Controller/Provider/User.php -

namespace OrgName\AppType\AppName\Controller\Provider; // namespace declaration

use OrgName\AppType\AppName\Controller\Provider\User; // when using the class

Also notice "src/App", "src/Test" .. are from your web-root that is where your composer.json is. Nothing to do with the vendor dir. take a look at vendor/autoload.php

Now if composer is installed properly all that is required is #composer update

After composer update my classes loaded successfully. What I observed is that composer is adding a line in vendor/composer/autoload_psr4.php

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'),
    'OrgName\\AppType\\AppName\\' => array($baseDir . '/src/App', $baseDir . '/src/Test', $baseDir . '/library'),
);

This is how composer maps. For psr-0 mapping is in vendor/composer/autoload_classmap.php

Accessing nested JavaScript objects and arrays by string path

ES6: Only one line in Vanila JS (it return null if don't find instead of giving error):

'path.string'.split('.').reduce((p,c)=>p&&p[c]||null, MyOBJ)

Or example:

'a.b.c'.split('.').reduce((p,c)=>p&&p[c]||null, {a:{b:{c:1}}})

With Optional chaining operator:

'a.b.c'.split('.').reduce((p,c)=>p?.[c], {a:{b:{c:1}}})

For a ready to use function that also recognizes false, 0 and negative number and accept default values as parameter:

const resolvePath = (object, path, defaultValue) => path
   .split('.')
   .reduce((o, p) => o ? o[p] : defaultValue, object)

Example to use:

resolvePath(window,'document.body') => <body>
resolvePath(window,'document.body.xyz') => undefined
resolvePath(window,'document.body.xyz', null) => null
resolvePath(window,'document.body.xyz', 1) => 1

Bonus:

To set a path (Requested by @rob-gordon) you can use:

const setPath = (object, path, value) => path
   .split('.')
   .reduce((o,p,i) => o[p] = path.split('.').length === ++i ? value : o[p] || {}, object)

Example:

let myVar = {}
setPath(myVar, 'a.b.c', 42) => 42
console.log(myVar) => {a: {b: {c: 42}}}

Access array with []:

const resolvePath = (object, path, defaultValue) => path
   .split(/[\.\[\]\'\"]/)
   .filter(p => p)
   .reduce((o, p) => o ? o[p] : defaultValue, object)

Example:

const myVar = {a:{b:[{c:1}]}}
resolvePath(myVar,'a.b[0].c') => 1
resolvePath(myVar,'a["b"][\'0\'].c') => 1

Difference between static and shared libraries?

On top of all the other answers, one thing not mentionned yet is decoupling :

Let me speak about a real world production code,that I have been dealing with :

A very big software, made of >300 projects (with visual studio), mostly build as static lib and finally all link together in one huge executable , you end up with the following problems :

-Link time is extremely long. You might end up by more than 15min of link, for let's say 10s of compilation time -Some tools are on their knee with such a big executable , like memory check tools that must instrument the code. You might fall into reaching limits that had been seen as fools.

More problematic is the decoupling of your software : on this real world example, headers files of every project were reacheable from any others projects. As a consequence it was extremely easy for one developer to add dependencies; it was just about including the header, because link at the end will allwaws find symbols. It ends up by horrible cycling dependencies and complete mess.

With shared library, it's a bit of extra work because developer must edit the project build system to add the dependent library. I observed that shared library code tends to offer a cleaner code API.

How to modify JsonNode in Java?

Adding an answer as some others have upvoted in the comments of the accepted answer they are getting this exception when attempting to cast to ObjectNode (myself included):

Exception in thread "main" java.lang.ClassCastException: 
com.fasterxml.jackson.databind.node.TextNode cannot be cast to com.fasterxml.jackson.databind.node.ObjectNode

The solution is to get the 'parent' node, and perform a put, effectively replacing the entire node, regardless of original node type.

If you need to "modify" the node using the existing value of the node:

  1. get the value/array of the JsonNode
  2. Perform your modification on that value/array
  3. Proceed to call put on the parent.

Code, where the goal is to modify subfield, which is the child node of NodeA and Node1:

JsonNode nodeParent = someNode.get("NodeA")
                .get("Node1");

// Manually modify value of 'subfield', can only be done using the parent.
((ObjectNode) nodeParent).put('subfield', "my-new-value-here");

Credits:

I got this inspiration from here, thanks to wassgreen@

How to detect if JavaScript is disabled?

If javascript is disabled your client-side code won't run anyway, so I assume you mean you want that info available server-side. In that case, noscript is less helpful. Instead, I'd have a hidden input and use javascript to fill in a value. After your next request or postback, if the value is there you know javascript is turned on.

Be careful of things like noscript, where the first request may show javascript disabled, but future requests turn it on.

Pure CSS checkbox image replacement

Using javascript seems to be unnecessary if you choose CSS3.

By using :before selector, you can do this in two lines of CSS. (no script involved).

Another advantage of this approach is that it does not rely on <label> tag and works even it is missing.

Note: in browsers without CSS3 support, checkboxes will look normal. (backward compatible).

input[type=checkbox]:before { content:""; display:inline-block; width:12px; height:12px; background:red; }
input[type=checkbox]:checked:before { background:green; }?

You can see a demo here: http://jsfiddle.net/hqZt6/1/

and this one with images:

http://jsfiddle.net/hqZt6/6/

ValidateAntiForgeryToken purpose, explanation and example

MVC's anti-forgery support writes a unique value to an HTTP-only cookie and then the same value is written to the form. When the page is submitted, an error is raised if the cookie value doesn't match the form value.

It's important to note that the feature prevents cross site request forgeries. That is, a form from another site that posts to your site in an attempt to submit hidden content using an authenticated user's credentials. The attack involves tricking the logged in user into submitting a form, or by simply programmatically triggering a form when the page loads.

The feature doesn't prevent any other type of data forgery or tampering based attacks.

To use it, decorate the action method or controller with the ValidateAntiForgeryToken attribute and place a call to @Html.AntiForgeryToken() in the forms posting to the method.

Showing data values on stacked bar chart in ggplot2

From ggplot 2.2.0 labels can easily be stacked by using position = position_stack(vjust = 0.5) in geom_text.

ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
  geom_bar(stat = "identity") +
  geom_text(size = 3, position = position_stack(vjust = 0.5))

enter image description here

Also note that "position_stack() and position_fill() now stack values in the reverse order of the grouping, which makes the default stack order match the legend."


Answer valid for older versions of ggplot:

Here is one approach, which calculates the midpoints of the bars.

library(ggplot2)
library(plyr)

# calculate midpoints of bars (simplified using comment by @DWin)
Data <- ddply(Data, .(Year), 
   transform, pos = cumsum(Frequency) - (0.5 * Frequency)
)

# library(dplyr) ## If using dplyr... 
# Data <- group_by(Data,Year) %>%
#    mutate(pos = cumsum(Frequency) - (0.5 * Frequency))

# plot bars and add text
p <- ggplot(Data, aes(x = Year, y = Frequency)) +
     geom_bar(aes(fill = Category), stat="identity") +
     geom_text(aes(label = Frequency, y = pos), size = 3)

Resultant chart

Comparing Arrays of Objects in JavaScript

There is a optimized code for case when function needs to equals to empty arrays (and returning false in that case)

const objectsEqual = (o1, o2) => {
    if (o2 === null && o1 !== null) return false;
    return o1 !== null && typeof o1 === 'object' && Object.keys(o1).length > 0 ?
        Object.keys(o1).length === Object.keys(o2).length && 
        Object.keys(o1).every(p => objectsEqual(o1[p], o2[p]))
        : (o1 !== null && Array.isArray(o1) && Array.isArray(o2) && !o1.length && 
        !o2.length) ? true : o1 === o2;
}

How can I upload files asynchronously?

A modern approach without Jquery is to use the FileList object you get back from <input type="file"> when user selects a file(s) and then use Fetch to post the FileList wrapped around a FormData object.

// The input DOM element // <input type="file">
const inputElement = document.querySelector('input[type=file]');

// Listen for a file submit from user
inputElement.addEventListener('change', () => {
    const data = new FormData();
    data.append('file', inputElement.files[0]);
    data.append('imageName', 'flower');

    // You can then post it to your server.
    // Fetch can accept an object of type FormData on its  body
    fetch('/uploadImage', {
        method: 'POST',
        body: data
    });
});

Filter dict to contain only certain keys?

This function will do the trick:

def include_keys(dictionary, keys):
    """Filters a dict by only including certain keys."""
    key_set = set(keys) & set(dictionary.keys())
    return {key: dictionary[key] for key in key_set}

Just like delnan's version, this one uses dictionary comprehension and has stable performance for large dictionaries (dependent only on the number of keys you permit, and not the total number of keys in the dictionary).

And just like MyGGan's version, this one allows your list of keys to include keys that may not exist in the dictionary.

And as a bonus, here's the inverse, where you can create a dictionary by excluding certain keys in the original:

def exclude_keys(dictionary, keys):
    """Filters a dict by excluding certain keys."""
    key_set = set(dictionary.keys()) - set(keys)
    return {key: dictionary[key] for key in key_set}

Note that unlike delnan's version, the operation is not done in place, so the performance is related to the number of keys in the dictionary. However, the advantage of this is that the function will not modify the dictionary provided.

Edit: Added a separate function for excluding certain keys from a dict.

Converting string to tuple without splitting characters

Just in case someone comes here trying to know how to create a tuple assigning each part of the string "Quattro" and "TT" to an element of the list, it would be like this print tuple(a.split())

Python error when trying to access list by index - "List indices must be integers, not str"

players is a list which needs to be indexed by integers. You seem to be using it like a dictionary. Maybe you could use unpacking -- Something like:

name, score = player

(if the player list is always a constant length).

There's not much more advice we can give you without knowing what query is and how it works.

It's worth pointing out that the entire code you posted doesn't make a whole lot of sense. There's an IndentationError on the second line. Also, your function is looping over some iterable, but unconditionally returning during the first iteration which isn't usually what you actually want to do.

Get statistics for each group (such as count, mean, etc) using pandas GroupBy?

Create a group object and call methods like below example:

grp = df.groupby(['col1',  'col2',  'col3']) 

grp.max() 
grp.mean() 
grp.describe() 

How to insert DECIMAL into MySQL database

Yes, 4,2 means "4 digits total, 2 of which are after the decimal place". That translates to a number in the format of 00.00. Beyond that, you'll have to show us your SQL query. PHP won't translate 3.80 into 99.99 without good reason. Perhaps you've misaligned your fields/values in the query and are trying to insert a larger number that belongs in another field.

How to create a link for all mobile devices that opens google maps with a route starting at the current location, destinating a given place?

This works for me on all devices [ iOS, Android and Window Mobile 8.1 ].

Does not look like the best way by any means... but cannot be more simpler :)

<a href="bingmaps:?cp=18.551464~73.951399">
 <a href="http://maps.apple.com/maps?q=18.551464, 73.951399"> 
   Open Maps
 </a>
</a>

http://jsbin.com/dibeq

How to get values from selected row in DataGrid for Windows Form Application?

You could just use

DataGridView1.CurrentRow.Cells["ColumnName"].Value

Using HTTPS with REST in Java

When you say "is there an easier way to... trust this cert", that's exactly what you're doing by adding the cert to your Java trust store. And this is very, very easy to do, and there's nothing you need to do within your client app to get that trust store recognized or utilized.

On your client machine, find where your cacerts file is (that's your default Java trust store, and is, by default, located at <java-home>/lib/security/certs/cacerts.

Then, type the following:

keytool -import -alias <Name for the cert> -file <the .cer file> -keystore <path to cacerts>

That will import the cert into your trust store, and after this, your client app will be able to connect to your Grizzly HTTPS server without issue.

If you don't want to import the cert into your default trust store -- i.e., you just want it to be available to this one client app, but not to anything else you run on your JVM on that machine -- then you can create a new trust store just for your app. Instead of passing keytool the path to the existing, default cacerts file, pass keytool the path to your new trust store file:

keytool -import -alias <Name for the cert> -file <the .cer file> -keystore <path to new trust store>

You'll be asked to set and verify a new password for the trust store file. Then, when you start your client app, start it with the following parameters:

java -Djavax.net.ssl.trustStore=<path to new trust store> -Djavax.net.ssl.trustStorePassword=<trust store password>

Easy cheesy, really.

Encoding Error in Panda read_csv

This works in Mac as well you can use

df= pd.read_csv('Region_count.csv', encoding ='latin1')

POST request with a simple string in body with Alamofire

You can do this:

  1. I created a separated request Alamofire object.
  2. Convert string to Data
  3. Put in httpBody the data

    var request = URLRequest(url: URL(string: url)!)
    request.httpMethod = HTTPMethod.post.rawValue
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    
    let pjson = attendences.toJSONString(prettyPrint: false)
    let data = (pjson?.data(using: .utf8))! as Data
    
    request.httpBody = data
    
    Alamofire.request(request).responseJSON { (response) in
    
    
        print(response)
    
    }
    

JDK on OSX 10.7 Lion

You can download jdk6 here http://support.apple.com/kb/DL1573

Wish it helps

If...Then...Else with multiple statements after Then

This works with multiple statements:

if condition1 Then stmt1:stmt2 Else if condition2 Then stmt3:stmt4 Else stmt5:stmt6

Or you can split it over multiple lines:

if condition1 Then stmt1:stmt2
Else if condition2 Then stmt3:stmt4
Else stmt5:stmt6

How to create a new img tag with JQuery, with the src and id from a JavaScript object?

You save some bytes by avoiding the .attr altogether by passing the properties to the jQuery constructor:

var img = $('<img />',
             { id: 'Myid',
               src: 'MySrc.gif', 
               width: 300
             })
              .appendTo($('#YourDiv'));

How much does it cost to develop an iPhone application?

I hate to admit how little I've done an iPhone app for, but I can tell you I won't be doing that again. The guy who said that "simple, one function apps can be done .. [by solo developers]... for $5K" is correct; however, that is still lowball, and presumes almost no project design, graphic design or network backend work.

Capturing browser logs with Selenium WebDriver using Java

Starting with Firefox 65 an about:config flag exists now so console API calls like console.log() land in the output stream and thus the log file (see (https://github.com/mozilla/geckodriver/issues/284#issuecomment-458305621).

profile = new FirefoxProfile();
profile.setPreference("devtools.console.stdout.content", true);

Get Folder Size from Windows Command Line

I guess this would only work if the directory is fairly static and its contents don't change between the execution of the two dir commands. Maybe a way to combine this into one command to avoid that, but this worked for my purpose (I didn't want the full listing; just the summary).

GetDirSummary.bat Script:

@echo off
rem  get total number of lines from dir output
FOR /F "delims=" %%i IN ('dir /S %1 ^| find "asdfasdfasdf" /C /V') DO set lineCount=%%i
rem  dir summary is always last 3 lines; calculate starting line of summary info
set /a summaryStart="lineCount-3"
rem  now output just the last 3 lines
dir /S %1 | more +%summaryStart%

Usage:

GetDirSummary.bat c:\temp

Output:

 Total Files Listed:
          22 File(s)         63,600 bytes
           8 Dir(s)  104,350,330,880 bytes free

Property '...' has no initializer and is not definitely assigned in the constructor

When you upgrade using [email protected] , its compiler strict the rules follows for array type declare inside the component class constructor.

For fix this issue either change the code where are declared in the code or avoid to compiler to add property "strictPropertyInitialization": false in the "tsconfig.json" file and run again npm start .

Angular web and mobile Application Development you can go to www.jtechweb.in

How to position text over an image in css

How about something like this: http://jsfiddle.net/EgLKV/3/

Its done by using position:absolute and z-index to place the text over the image.

_x000D_
_x000D_
#container {_x000D_
  height: 400px;_x000D_
  width: 400px;_x000D_
  position: relative;_x000D_
}_x000D_
#image {_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
}_x000D_
#text {_x000D_
  z-index: 100;_x000D_
  position: absolute;_x000D_
  color: white;_x000D_
  font-size: 24px;_x000D_
  font-weight: bold;_x000D_
  left: 150px;_x000D_
  top: 350px;_x000D_
}
_x000D_
<div id="container">_x000D_
  <img id="image" src="http://www.noao.edu/image_gallery/images/d4/androa.jpg" />_x000D_
  <p id="text">_x000D_
    Hello World!_x000D_
  </p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to hash some string with sha256 in Java?

import java.security.MessageDigest;

public class CodeSnippets {

 public static String getSha256(String value) {
    try{
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(value.getBytes());
        return bytesToHex(md.digest());
    } catch(Exception ex){
        throw new RuntimeException(ex);
    }
 }
 private static String bytesToHex(byte[] bytes) {
    StringBuffer result = new StringBuffer();
    for (byte b : bytes) result.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
    return result.toString();
 }
}

How can I call a method in Objective-C?

[self score]; instead of @selector(score)

Uploading Laravel Project onto Web Server

All of your Laravel files should be in one location. Laravel is exposing its public folder to server. That folder represents some kind of front-controller to whole application. Depending on you server configuration, you have to point your server path to that folder. As I can see there is www site on your picture. www is default root directory on Unix/Linux machines. It is best to take a look inside you server configuration and search for root directory location. As you can see, Laravel has already file called .htaccess, with some ready Apache configuration.

using lodash .groupBy. how to add your own keys for grouped output?

Isn't it this simple?

var result = _(data)
            .groupBy(x => x.color)
            .map((value, key) => ({color: key, users: value}))
            .value();

C# SQL Server - Passing a list to a stored procedure

Yep, make Stored proc parameter as VARCHAR(...) And then pass comma separated values to a stored procedure.

If you are using Sql Server 2008 you can leverage TVP (Table Value Parameters): SQL 2008 TVP and LINQ if structure of QueryTable more complex than array of strings otherwise it would be an overkill because requires table type to be created within SQl Server

How to randomize Excel rows

Here's a macro that allows you to shuffle selected cells in a column:

Option Explicit

Sub ShuffleSelectedCells()
  'Do nothing if selecting only one cell
  If Selection.Cells.Count = 1 Then Exit Sub
  'Save selected cells to array
  Dim CellData() As Variant
  CellData = Selection.Value
  'Shuffle the array
  ShuffleArrayInPlace CellData
  'Output array to spreadsheet
  Selection.Value = CellData
End Sub

Sub ShuffleArrayInPlace(InArray() As Variant)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' ShuffleArrayInPlace
' This shuffles InArray to random order, randomized in place.
' Source: http://www.cpearson.com/excel/ShuffleArray.aspx
' Modified by Tom Doan to work with Selection.Value two-dimensional arrays.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
  Dim J As Long, _
    N As Long, _
    Temp As Variant
  'Randomize
  For N = LBound(InArray) To UBound(InArray)
    J = CLng(((UBound(InArray) - N) * Rnd) + N)
    If J <> N Then
      Temp = InArray(N, 1)
      InArray(N, 1) = InArray(J, 1)
      InArray(J, 1) = Temp
    End If
  Next N
End Sub

You can read the comments to see what the macro is doing. Here's how to install the macro:

  1. Open the VBA editor (Alt + F11).
  2. Right-click on "ThisWorkbook" under your currently open spreadsheet (listed in parentheses after "VBAProject") and select Insert / Module.
  3. Paste the code above and save the spreadsheet.

Now you can assign the "ShuffleSelectedCells" macro to an icon or hotkey to quickly randomize your selected rows (keep in mind that you can only select one column of rows).

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.6 or one of its dependencies could not be resolved

This helped me: I created a new maven project which was working fine in my old workspace, but gave above errors in the new workspace. I had to do the following: - Open old workspace on Eclipse - open Preferences tab - Search Maven in filter - Copy the path for settings.xml from User Settings - User Settings - Switch to new workspace - Update the preferences - Maven - User Settings - User Settings path

After the build is completed, all errors are resolved.

Disable button in angular with two conditions?

It sounds like you need an OR instead:

<button type="submit" [disabled]="!validate || !SAForm.valid">Add</button>

This will disable the button if not validate or if not SAForm.valid.

Failed to resolve: com.android.support:appcompat-v7:28.0

in build.gradle , the version of bellow line should be same

implementation 'com.android.support:appcompat-v7:28.0.0-alpha1'
implementation 'com.android.support:design:28.0.0'

How do I get the path and name of the file that is currently executing?

if you want just the filename without ./ or .py you can try this

filename = testscript.py
file_name = __file__[2:-3]

file_name will print testscript you can generate whatever you want by changing the index inside []

Traverse all the Nodes of a JSON Object Tree with JavaScript

A JSON object is simply a Javascript object. That's actually what JSON stands for: JavaScript Object Notation. So you'd traverse a JSON object however you'd choose to "traverse" a Javascript object in general.

In ES2017 you would do:

Object.entries(jsonObj).forEach(([key, value]) => {
    // do something with key and val
});

You can always write a function to recursively descend into the object:

function traverse(jsonObj) {
    if( jsonObj !== null && typeof jsonObj == "object" ) {
        Object.entries(jsonObj).forEach(([key, value]) => {
            // key is either an array index or object key
            traverse(value);
        });
    }
    else {
        // jsonObj is a number or string
    }
}

This should be a good starting point. I highly recommend using modern javascript methods for such things, since they make writing such code much easier.

Get the name of a pandas DataFrame

Sometimes df.name doesn't work.

you might get an error message:

'DataFrame' object has no attribute 'name'

try the below function:

def get_df_name(df):
    name =[x for x in globals() if globals()[x] is df][0]
    return name

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

doThrow : Basically used when you want to throw an exception when a method is being called within a mock object.

public void validateEntity(final Object object){}
Mockito.doThrow(IllegalArgumentException.class)
.when(validationService).validateEntity(Matchers.any(AnyObjectClass.class));

doReturn : Used when you want to send back a return value when a method is executed.

public Socket getCosmosSocket() throws IOException {}
Mockito.doReturn(cosmosSocket).when(cosmosServiceImpl).getCosmosSocket();

doAnswer: Sometimes you need to do some actions with the arguments that are passed to the method, for example, add some values, make some calculations or even modify them doAnswer gives you the Answer interface that being executed in the moment that method is called, this interface allows you to interact with the parameters via the InvocationOnMock argument. Also, the return value of answer method will be the return value of the mocked method.

public ReturnValueObject quickChange(Object1 object);
Mockito.doAnswer(new Answer<ReturnValueObject>() {

        @Override
        public ReturnValueObject answer(final InvocationOnMock invocation) throws Throwable {

            final Object1 originalArgument = (invocation.getArguments())[0];
            final ReturnValueObject returnedValue = new ReturnValueObject();
            returnedValue.setCost(new Cost());

            return returnedValue ;
        }
}).when(priceChangeRequestService).quickCharge(Matchers.any(Object1.class));

doNothing: Is the easiest of the list, basically it tells Mockito to do nothing when a method in a mock object is called. Sometimes used in void return methods or method that does not have side effects, or are not related to the unit testing you are doing.

public void updateRequestActionAndApproval(final List<Object1> cmItems);

Mockito.doNothing().when(pagLogService).updateRequestActionAndApproval(
                Matchers.any(Object1.class));

How to set proxy for wget?

the following possible configs are located in /etc/wgetrc just uncomment and use...

# You can set the default proxies for Wget to use for http, https, and ftp.
# They will override the value in the environment.
#https_proxy = http://proxy.yoyodyne.com:18023/
#http_proxy = http://proxy.yoyodyne.com:18023/
#ftp_proxy = http://proxy.yoyodyne.com:18023/

# If you do not want to use proxy at all, set this to off.
#use_proxy = on

adb doesn't show nexus 5 device

This simple steps worked for me, I debug on my Nexus 5 and 5X devices on Windows 8.1.

The steps to follow are these:

1) Enable from Developers Options the Debug USB Mode

2) Unplug the device from the computer

3.1) Go to Settings ? Storage, in the ActionBar, click the option menu and choose USB computer connection.

3.2) If you didn't find the 3.1) option then go to Settings ? Developers Options ? Select USB Configuration.

4) Select Camera (PTP) connection.

5) Plug the device and you should have a popup on the device allowing you to accept the computer's incoming connection, or something like that.

6) If it doesn't work try to toggle the Debug USB Mode in the Developers Options Finally, you should see it now in the DDMS and voilà.

Proper usage of .net MVC Html.CheckBoxFor

That isn't the proper syntax

The first parameter is not checkbox value but rather view model binding for the checkbox hence:

@Html.CheckBoxFor(m => m.SomeBooleanProperty, new { @checked = "checked" });

The first parameter must identify a boolean property within your model (it's an Expression not an anonymous method returning a value) and second property defines any additional HTML element attributes. I'm not 100% sure that the above attribute will initially check your checkbox, but you can try. But beware. Even though it may work you may have issues later on, when loading a valid model data and that particular property is set to false.

The correct way

Although my proper suggestion would be to provide initialized model to your view with that particular boolean property initialized to true.

Property types

As per Asp.net MVC HtmlHelper extension methods and inner working, checkboxes need to bind to boolean values and not integers what seems that you'd like to do. In that case a hidden field could store the id.

Other helpers

There are of course other helper methods that you can use to get greater flexibility about checkbox values and behaviour:

@Html.CheckBox("templateId", new { value = item.TemplateID, @checked = true });

Note: checked is an HTML element boolean property and not a value attribute which means that you can assign any value to it. The correct HTML syntax doesn't include any assignments, but there's no way of providing an anonymous C# object with undefined property that would render as an HTML element property.

Is the sizeof(some pointer) always equal to four?

A pointer is just a container for an address. On a 32 bit machine, your address range is 32 bits, so a pointer will always be 4 bytes. On a 64 bit machine were you have an address range of 64 bits, a pointer will be 8 bytes.

understanding private setters

I think a few folks have danced around this, but for me, the value of private setters is that you can encapsulate the behavior of a property, even within a class. As abhishek noted, if you want to fire a property changed event every time a property changes, but you don't want a property to be read/write to the public, then you either must use a private setter, or you must raise the event anywhere you modify the backing field. The latter is error prone because you might forget. Relatedly, if updating a property value results in some calculation being performed or another field being modified, or a lazy initialization of something, then you will also want to wrap that up in the private setter rather than having to remember to do it everywhere you make use of the backing field.

Using Excel as front end to Access database (with VBA)

Just skip the excel part - the excel user forms are just a poor man's version of the way more robust Access forms. Also Access VBA is identical to Excel VBA - you just have to learn Access' object model. With a simple application you won't need to write much VBA anyways because in Access you can wire things together quite easily.

cannot download, $GOPATH not set

This problem occured to me in raspberry pi. I had logged in through VNC client The problem persisted despite setting and exporting the GOPATH. Then Ran the "go get" command without sudo and it worked perfectly.

Adding a simple UIAlertView

When you want the alert to show, do this:

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ROFL" 
                                                    message:@"Dee dee doo doo." 
                                                    delegate:self 
                                                    cancelButtonTitle:@"OK" 
                                                    otherButtonTitles:nil];
[alert show];

    // If you're not using ARC, you will need to release the alert view.
    // [alert release];

If you want to do something when the button is clicked, implement this delegate method:

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    // the user clicked OK
    if (buttonIndex == 0) {
        // do something here...
    }
}

And make sure your delegate conforms to UIAlertViewDelegate protocol:

@interface YourViewController : UIViewController <UIAlertViewDelegate> 

How to use count and group by at the same select statement

I know this is an old post, in SQL Server:

select  isnull(town,'TOTAL') Town, count(*) cnt
from    user
group by town WITH ROLLUP

Town         cnt
Copenhagen   58
NewYork      58
Athens       58
TOTAL        174

Is null reference possible?

Yes:

#include <iostream>
#include <functional>

struct null_ref_t {
   template <typename T>
   operator T&() {
      union TypeSafetyBreaker {
         T *ptr;

         // see https://stackoverflow.com/questions/38691282/use-of-union-with-reference
         std::reference_wrapper<T> ref; 
      };

      TypeSafetyBreaker ptr = {.ptr = nullptr};

      // unwrap the reference
      return ptr.ref.get();
   }
};

null_ref_t nullref;


int main() {
   int &a = nullref;

   // Segmentation fault
   a = 4;
   return 0;
}

What is the difference between float and double?

I just ran into a error that took me forever to figure out and potentially can give you a good example of float precision.

#include <iostream>
#include <iomanip>

int main(){
  for(float t=0;t<1;t+=0.01){
     std::cout << std::fixed << std::setprecision(6) << t << std::endl;
  }
}

The output is

0.000000
0.010000
0.020000
0.030000
0.040000
0.050000
0.060000
0.070000
0.080000
0.090000
0.100000
0.110000
0.120000
0.130000
0.140000
0.150000
0.160000
0.170000
0.180000
0.190000
0.200000
0.210000
0.220000
0.230000
0.240000
0.250000
0.260000
0.270000
0.280000
0.290000
0.300000
0.310000
0.320000
0.330000
0.340000
0.350000
0.360000
0.370000
0.380000
0.390000
0.400000
0.410000
0.420000
0.430000
0.440000
0.450000
0.460000
0.470000
0.480000
0.490000
0.500000
0.510000
0.520000
0.530000
0.540000
0.550000
0.560000
0.570000
0.580000
0.590000
0.600000
0.610000
0.620000
0.630000
0.640000
0.650000
0.660000
0.670000
0.680000
0.690000
0.700000
0.710000
0.720000
0.730000
0.740000
0.750000
0.760000
0.770000
0.780000
0.790000
0.800000
0.810000
0.820000
0.830000
0.839999
0.849999
0.859999
0.869999
0.879999
0.889999
0.899999
0.909999
0.919999
0.929999
0.939999
0.949999
0.959999
0.969999
0.979999
0.989999
0.999999

As you can see after 0.83, the precision runs down significantly.

However, if I set up t as double, such an issue won't happen.

It took me five hours to realize this minor error, which ruined my program.

dbms_lob.getlength() vs. length() to find blob size in oracle

length and dbms_lob.getlength return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength will return the number of bytes, which may differ from the number of characters in a multi-byte character set.

As the documentation doesn't specify what happens when you apply length on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength.

How to use LogonUser properly to impersonate domain user from workgroup client

this works for me, full working example (I wish more people would do this):

//logon impersonation
using System.Runtime.InteropServices; // DllImport
using System.Security.Principal; // WindowsImpersonationContext
using System.Security.Permissions; // PermissionSetAttribute

...

class Program {

    // obtains user token
    [DllImport("advapi32.dll", SetLastError = true)]
    public static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword,
        int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

    // closes open handes returned by LogonUser
    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public extern static bool CloseHandle(IntPtr handle);

    public void DoWorkUnderImpersonation() {
        //elevate privileges before doing file copy to handle domain security
        WindowsImpersonationContext impersonationContext = null;
        IntPtr userHandle = IntPtr.Zero;
        const int LOGON32_PROVIDER_DEFAULT = 0;
        const int LOGON32_LOGON_INTERACTIVE = 2;
        string domain = ConfigurationManager.AppSettings["ImpersonationDomain"];
        string user = ConfigurationManager.AppSettings["ImpersonationUser"];
        string password = ConfigurationManager.AppSettings["ImpersonationPassword"];

        try {
            Console.WriteLine("windows identify before impersonation: " + WindowsIdentity.GetCurrent().Name);

            // if domain name was blank, assume local machine
            if (domain == "")
                domain = System.Environment.MachineName;

            // Call LogonUser to get a token for the user
            bool loggedOn = LogonUser(user,
                                        domain,
                                        password,
                                        LOGON32_LOGON_INTERACTIVE,
                                        LOGON32_PROVIDER_DEFAULT,
                                        ref userHandle);

            if (!loggedOn) {
                Console.WriteLine("Exception impersonating user, error code: " + Marshal.GetLastWin32Error());
                return;
            }

            // Begin impersonating the user
            impersonationContext = WindowsIdentity.Impersonate(userHandle);

            Console.WriteLine("Main() windows identify after impersonation: " + WindowsIdentity.GetCurrent().Name);

            //run the program with elevated privileges (like file copying from a domain server)
            DoWork();

        } catch (Exception ex) {
            Console.WriteLine("Exception impersonating user: " + ex.Message);
        } finally {
            // Clean up
            if (impersonationContext != null) {
                impersonationContext.Undo();
            }

            if (userHandle != IntPtr.Zero) {
                CloseHandle(userHandle);
            }
        }
    }


    private void DoWork() {
        //everything in here has elevated privileges

        //example access files on a network share through e$ 
        string[] files = System.IO.Directory.GetFiles(@"\\domainserver\e$\images", "*.jpg");
    }
}

smtpclient " failure sending mail"

what error do you get is it a SmtpFailedrecipientException? if so you can check the innerexceptions list and view the StatusCode to get more information. the link below has some good information

MSDN

Edit for the new information

Thisis a problem with finding your SMTP server from what I can see, though you say that it only happens on some emails. Are you using more than one smtp server and if so maybe you can tract the issue down to one in particular, if not it may be that the speed/amount of emails you are sending is causing your smtp server some issue.

How to validate an OAuth 2.0 access token for a resource server?

An update on @Scott T.'s answer: the interface between Resource Server and Authorization Server for token validation was standardized in IETF RFC 7662 in October 2015, see: https://tools.ietf.org/html/rfc7662. A sample validation call would look like:

POST /introspect HTTP/1.1
Host: server.example.com
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Authorization: Bearer 23410913-abewfq.123483

token=2YotnFZFEjr1zCsicMWpAA

and a sample response:

HTTP/1.1 200 OK
Content-Type: application/json

{
  "active": true,
  "client_id": "l238j323ds-23ij4",
  "username": "jdoe",
  "scope": "read write dolphin",
  "sub": "Z5O3upPC88QrAjx00dis",
  "aud": "https://protected.example.net/resource",
  "iss": "https://server.example.com/",
  "exp": 1419356238,
  "iat": 1419350238,
  "extension_field": "twenty-seven"
}

Of course adoption by vendors and products will have to happen over time.

Move existing, uncommitted work to a new branch in Git

Update 2020 / Git 2.23

Git 2.23 adds the new switch subcommand in an attempt to clear some of the confusion that comes from the overloaded usage of checkout (switching branches, restoring files, detaching HEAD, etc.)

Starting with this version of Git, replace above's command with:

git switch -c <new-branch>

The behavior is identical and remains unchanged.


Before Update 2020 / Git 2.23

Use the following:

git checkout -b <new-branch>

This will leave your current branch as it is, create and checkout a new branch and keep all your changes. You can then stage changes in files to commit with:

git add <files>

and commit to your new branch with:

git commit -m "<Brief description of this commit>"

The changes in the working directory and changes staged in index do not belong to any branch yet. This changes the branch where those modifications would end in.

You don't reset your original branch, it stays as it is. The last commit on <old-branch> will still be the same. Therefore you checkout -b and then commit.

Move to next item using Java 8 foreach loop in stream

Using return; will work just fine. It will not prevent the full loop from completing. It will only stop executing the current iteration of the forEach loop.

Try the following little program:

public static void main(String[] args) {
    ArrayList<String> stringList = new ArrayList<>();
    stringList.add("a");
    stringList.add("b");
    stringList.add("c");

    stringList.stream().forEach(str -> {
        if (str.equals("b")) return; // only skips this iteration.

        System.out.println(str);
    });
}

Output:

a
c

Notice how the return; is executed for the b iteration, but c prints on the following iteration just fine.

Why does this work?

The reason the behavior seems unintuitive at first is because we are used to the return statement interrupting the execution of the whole method. So in this case, we expect the main method execution as a whole to be halted.

However, what needs to be understood is that a lambda expression, such as:

str -> {
    if (str.equals("b")) return;

    System.out.println(str);
}

... really needs to be considered as its own distinct "method", completely separate from the main method, despite it being conveniently located within it. So really, the return statement only halts the execution of the lambda expression.

The second thing that needs to be understood is that:

stringList.stream().forEach()

... is really just a normal loop under the covers that executes the lambda expression for every iteration.

With these 2 points in mind, the above code can be rewritten in the following equivalent way (for educational purposes only):

public static void main(String[] args) {
    ArrayList<String> stringList = new ArrayList<>();
    stringList.add("a");
    stringList.add("b");
    stringList.add("c");

    for(String s : stringList) {
        lambdaExpressionEquivalent(s);
    }
}

private static void lambdaExpressionEquivalent(String str) {
    if (str.equals("b")) {
        return;
    }

    System.out.println(str);
}

With this "less magic" code equivalent, the scope of the return statement becomes more apparent.

Exit Shell Script Based on Process Exit Code

After each command, the exit code can be found in the $? variable so you would have something like:

ls -al file.ext
rc=$?; if [[ $rc != 0 ]]; then exit $rc; fi

You need to be careful of piped commands since the $? only gives you the return code of the last element in the pipe so, in the code:

ls -al file.ext | sed 's/^/xx: /"

will not return an error code if the file doesn't exist (since the sed part of the pipeline actually works, returning 0).

The bash shell actually provides an array which can assist in that case, that being PIPESTATUS. This array has one element for each of the pipeline components, that you can access individually like ${PIPESTATUS[0]}:

pax> false | true ; echo ${PIPESTATUS[0]}
1

Note that this is getting you the result of the false command, not the entire pipeline. You can also get the entire list to process as you see fit:

pax> false | true | false; echo ${PIPESTATUS[*]}
1 0 1

If you wanted to get the largest error code from a pipeline, you could use something like:

true | true | false | true | false
rcs=${PIPESTATUS[*]}; rc=0; for i in ${rcs}; do rc=$(($i > $rc ? $i : $rc)); done
echo $rc

This goes through each of the PIPESTATUS elements in turn, storing it in rc if it was greater than the previous rc value.

Efficient iteration with index in Scala

How about this?

val a = Array("One", "Two", "Three")
a.foldLeft(0) ((i, x) => {println(i + ": " + x); i + 1;} )

Output:

0: One
1: Two
2: Three

How to iterate through XML in Powershell?

PowerShell has built-in XML and XPath functions. You can use the Select-Xml cmdlet with an XPath query to select nodes from XML object and then .Node.'#text' to access node value.

[xml]$xml = Get-Content $serviceStatePath
$nodes = Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml
$nodes | ForEach-Object {$_.Node.'#text'}

Or shorter

[xml]$xml = Get-Content $serviceStatePath
Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml |
  % {$_.Node.'#text'}

Active Menu Highlight CSS

Let's say we have a menu like this:

<div class="menu">
  <a href="link1.html">Link 1</a>
  <a href="link2.html">Link 2</a>
  <a href="link3.html">Link 3</a>
  <a href="link4.html">Link 4</a>
</div>

Let our current url be https://demosite.com/link1.html

With the following function we can add the active class to which menu's href is in our url.

let currentURL = window.location.href;

document.querySelectorAll(".menu a").forEach(p => {
  if(currentURL.indexOf(p.getAttribute("href")) !== -1){
    p.classList.add("active");
  }
})

How to run a command in the background on Windows?

You should also take a look at the at command in Windows. It will launch a program at a certain time in the background which works in this case.

Another option is to use the nssm service manager software. This will wrap whatever command you are running as a windows service.

UPDATE:

nssm isn't very good. You should instead look at WinSW project. https://github.com/kohsuke/winsw

For Restful API, can GET method use json data?

To answer your question, yes you may pass JSON in the URI as part of a GET request (provided you URL-encode). However, considering your reason for doing this is due to the length of the URI, using JSON will be self-defeating (introducing more characters than required).

I suggest you send your parameters in body of a POST request, either in regular CGI style (param1=val1&param2=val2) or JSON (parsed by your API upon receipt)

Issue with Task Scheduler launching a task

  • Right Click on the Task in Task Scheduler
  • Click on the Actions tab
  • Click on Edit
  • Remove the quotes around the path in the "Starts In" textbox.

Postgres: How to do Composite keys?

The error you are getting is in line 3. i.e. it is not in

CONSTRAINT no_duplicate_tag UNIQUE (question_id, tag_id)

but earlier:

CREATE TABLE tags
     (
              (question_id, tag_id) NOT NULL,

Correct table definition is like pilcrow showed.

And if you want to add unique on tag1, tag2, tag3 (which sounds very suspicious), then the syntax is:

CREATE TABLE tags (
    question_id INTEGER NOT NULL,
    tag_id SERIAL NOT NULL,
    tag1 VARCHAR(20),
    tag2 VARCHAR(20),
    tag3 VARCHAR(20),
    PRIMARY KEY(question_id, tag_id),
    UNIQUE (tag1, tag2, tag3)
);

or, if you want to have the constraint named according to your wish:

CREATE TABLE tags (
    question_id INTEGER NOT NULL,
    tag_id SERIAL NOT NULL,
    tag1 VARCHAR(20),
    tag2 VARCHAR(20),
    tag3 VARCHAR(20),
    PRIMARY KEY(question_id, tag_id),
    CONSTRAINT some_name UNIQUE (tag1, tag2, tag3)
);

..The underlying connection was closed: An unexpected error occurred on a receive

None of the solutions out there worked for me. What I eventually discovered was the following combination:

  • Client system: Windows XP Pro SP3
  • Client system has .NET Framework 2 SP1, 3, 3.5 installed
  • Software targeting .NET 2 using classic web services (.asmx)
  • Server: IIS6
  • Web site "Secure Communications" set to:
    • Require Secure Channel
    • Accept client certificates

enter image description here

Apparently, it was this last option that was causing the issue. I discovered this by trying to open the web service URL directly in Internet Explorer. It just hung indefinitely trying to load the page. Disabling "Accept client certificates" allowed the page to load normally. I am not sure if it was a problem with this specific system (maybe a glitched client certificate?) Since I wasn't using client certificates this option worked for me.

Why is @font-face throwing a 404 error on woff files?

I tried a ton of things around permissions, mime types, etc, but for me it ended up being that the web.config had removed the Static file handler in IIS, and then explicitly added it back in for directories that would have static files. As soon as I added a location node for my directory and added the handler back, the requests stopped getting 404s.

installing vmware tools: location of GCC binary?

sudo apt-get install build-essential is enough to get it working.

Troubleshooting BadImageFormatException

You can also get this exception when your application target .NET Framework 4.5 (for example) and you have the following app.config :

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v2.0.50727" />
    <supportedRuntime version="v4.0" />
  </startup>
</configuration>

When trying to launch the debug of the application you will get the BadImageFormatException.

Removing the line declaring the v2.0 version will clear the error.

I had this issue recently when I tried to change the target platform from an old .NET 2.0 project to .NET 4.5.

Upload video files via PHP and save them in appropriate folder and have a database entry

HTML Code

<html>
<body>

<head>
<title></title>
</head>

<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
    <label for="file"><span>Filename:</span></label>
    <input type="file" name="file" id="file" /> 
    <br />
<input type="submit" name="submit" value="Submit" />
</form>



<?php

    //============================= DATABASE CONNECTIVITY d ====================
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "test";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 
    else

    //============================= DATABASE CONNECTIVITY u ====================
    //============================= Retrieve data from DB d ====================
    $sql = "SELECT name, size, type FROM videos";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) 
        {
        $path = "uploaded/" . $row["name"];

            echo $path . "<br>";

        }
    } else {
        echo "0 results";
    }
    $conn->close();
    //============================= Retrieve data from DB d ====================

?>


</body>
</html>

How do I merge a specific commit from one branch into another in Git?

SOURCE: https://git-scm.com/book/en/v2/Distributed-Git-Maintaining-a-Project#Integrating-Contributed-Work

The other way to move introduced work from one branch to another is to cherry-pick it. A cherry-pick in Git is like a rebase for a single commit. It takes the patch that was introduced in a commit and tries to reapply it on the branch you’re currently on. This is useful if you have a number of commits on a topic branch and you want to integrate only one of them, or if you only have one commit on a topic branch and you’d prefer to cherry-pick it rather than run rebase. For example, suppose you have a project that looks like this:

enter image description here

If you want to pull commit e43a6 into your master branch, you can run

$ git cherry-pick e43a6
Finished one cherry-pick.
[master]: created a0a41a9: "More friendly message when locking the index fails."
 3 files changed, 17 insertions(+), 3 deletions(-)

This pulls the same change introduced in e43a6, but you get a new commit SHA-1 value, because the date applied is different. Now your history looks like this:

enter image description here

Now you can remove your topic branch and drop the commits you didn’t want to pull in.

SQL How to Select the most recent date item

Assuming your RDBMS know window functions and CTE and USER_ID is the patient's id:

WITH TT AS (
    SELECT *, ROW_NUMBER() OVER(PARTITION BY USER_ID ORDER BY DOCUMENT_DATE DESC) AS N
    FROM test_table
)
SELECT *
FROM TT
WHERE N = 1;

I assumed you wanted to sort by DOCUMENT_DATE, you can easily change that if wanted. If your RDBMS doesn't know window functions, you'll have to do a join :

SELECT *
FROM test_table T1
INNER JOIN (SELECT USER_ID, MAX(DOCUMENT_DATE) AS maxDate
            FROM test_table
            GROUP BY USER_ID) T2
    ON T1.USER_ID = T2.USER_ID
        AND T1.DOCUMENT_DATE = T2.maxDate;

It would be good to tell us what your RDBMS is though. And this query selects the most recent date for every patient, you can add a condition for a given patient.

What does if [ $? -eq 0 ] mean for shell scripts?

It's checking the return value ($?) of grep. In this case it's comparing it to 0 (success).

Usually when you see something like this (checking the return value of grep) it's checking to see whether the particular string was detected. Although the redirect to /dev/null isn't necessary, the same thing can be accomplished using -q.

Java Embedded Databases Comparison

I use Apache Derby for pretty much all of my embedded database needs. You can also use Sun's Java DB that is based on Derby but the latest version of Derby is much newer. It supports a lot of options that commercial, native databases support but is much smaller and easier to embed. I've had some database tables with more than a million records with no issues.

I used to use HSQLDB and Hypersonic about 3 years ago. It has some major performance issues at the time and I switch to Derby from it because of those issues. Derby has been solid even when it was in incubator at Apache.

How to exit git log or git diff

You're in the less program, which makes the output of git log scrollable.

Type q to exit this screen. Type h to get help.

If you don't want to read the output in a pager and want it to be just printed to the terminal define the environment variable GIT_PAGER to cat or set core.pager to cat (execute git config --global core.pager cat).

How do I automatically play a Youtube video (IFrame API) muted?

The accepted answer works pretty good. I wanted more control so I added a couple of functions more to the script:

function unmuteVideo() {
    player.unMute();
    return false;
  }
  function muteVideo() {
    player.mute();
    return false;
  }
  function setVolumeVideo(volume) {
    player.setVolume(volume);
    return false;
  }

And here is the HTML:

<br>
<button type="button" onclick="unmuteVideo();">Unmute Video</button>
<button type="button" onclick="muteVideo();">Mute Video</button>
<br>
<br>
<button type="button" onclick="setVolumeVideo(100);">Volume 100%</button>
<button type="button" onclick="setVolumeVideo(75);">Volume 75%</button>
<button type="button" onclick="setVolumeVideo(50);">Volume 50%</button>
<button type="button" onclick="setVolumeVideo(25);">Volume 25%</button>

Now you have more control of the sound... Check the reference URL for more:

YouTube IFrame Player API

How to auto resize and adjust Form controls with change in resolution

float widthRatio = Screen.PrimaryScreen.Bounds.Width / 1280;
float heightRatio = Screen.PrimaryScreen.Bounds.Height / 800f;
SizeF scale = new SizeF(widthRatio, heightRatio);
this.Scale(scale);
foreach (Control control in this.Controls)
{
control.Font = new Font("Verdana", control.Font.SizeInPoints * heightRatio * widthRatio);
}

TypeScript sorting an array

The easiest way seems to be subtracting the second number from the first:

var numericArray:Array<number> = [2,3,4,1,5,8,11];

var sorrtedArray:Array<number> = numericArray.sort((n1,n2) => n1 - n2);

https://alligator.io/js/array-sort-numbers/

React.js, wait for setState to finish before triggering a function?

       this.setState(
        {
            originId: input.originId,
            destinationId: input.destinationId,
            radius: input.radius,
            search: input.search
        },
        function() { console.log("setState completed", this.state) }
       )

this might be helpful

How to get the first column of a pandas DataFrame as a Series?

This works great when you want to load a series from a csv file

x = pd.read_csv('x.csv', index_col=False, names=['x'],header=None).iloc[:,0]
print(type(x))
print(x.head(10))


<class 'pandas.core.series.Series'>
0    110.96
1    119.40
2    135.89
3    152.32
4    192.91
5    177.20
6    181.16
7    177.30
8    200.13
9    235.41
Name: x, dtype: float64

Get width/height of SVG element

FireFox have problemes for getBBox(), i need to do this in vanillaJS.

I've a better Way and is the same result as real svg.getBBox() function !

With this good post : Get the real size of a SVG/G element

var el   = document.getElementById("yourElement"); // or other selector like querySelector()
var rect = el.getBoundingClientRect(); // get the bounding rectangle

console.log( rect.width );
console.log( rect.height);

Is it valid to replace http:// with // in a <script src="http://...">?

1. Summary

Answer for 2019: you can still use protocol-relative URLs, but this technique an anti-pattern.

Also:

  1. You may have problems in developing.
  2. Some third-party tools may not support them.

Migrating from protocol-relative URLs to https:// it would be nice.


2. Relevance

This answer is relevant for January 2019. In the future, the data of this answer may be obsolete.


3. Anti-pattern

3.1. Argumentation

Paul Irish — front-end engineer and a developer advocate for the Google Chromewrite in 2014, December:

Now that SSL is encouraged for everyone and doesn’t have performance concerns, this technique is now an anti-pattern. If the asset you need is available on SSL, then always use the https:// asset.

Allowing the snippet to request over HTTP opens the door for attacks like the recent GitHub Man-on-the-side attack. It’s always safe to request HTTPS assets even if your site is on HTTP, however the reverse is not true.

3.2. Another links

3.3. Examples


4. Developing process

For example, I try to use clean-console.

  • Example file KiraCleanConsole__cdn_links_demo.html:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>clean-console without protocol demonstration</title>
    <!-- Really dead link -->
    <script src="https://unpkg.com/bowser@latest/bowser.min.js"></script>
    <!-- Package exists; link without “https:” -->
    <script src="//cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
    <!-- Package exists: link with “https:” -->
    <script src="https://cdn.jsdelivr.net/npm/gemini-scrollbar/index.js"></script>
</head>
<body>
    Kira Goddess!
</body>
</html>
  • output:
D:\SashaDebugging>clean-console -i KiraCleanConsole__cdn_links_demo.html
checking KiraCleanConsole__cdn_links_demo.html
phantomjs: opening page KiraCleanConsole__cdn_links_demo.html

phantomjs: Unable to load resource (#3URL:file://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js)


phantomjs:   phantomjs://code/runner.js:30 in onResourceError
Error code: 203. Description: Error opening //cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js: The network path was not found.

  phantomjs://code/runner.js:31 in onResourceError

phantomjs: Unable to load resource (#5URL:https://unpkg.com/[email protected]/bowser.min.js)


phantomjs:   phantomjs://code/runner.js:30 in onResourceError
Error code: 203. Description: Error downloading https://unpkg.com/[email protected]/bowser.min.js - server replied: Not Found

  phantomjs://code/runner.js:31 in onResourceError

phantomjs: Checking errors after sleeping for 1000ms
2 error(s) on KiraCleanConsole__cdn_links_demo.html

phantomjs process exited with code 2

Link //cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js is valid, but I getting an error.

Pay attention to file://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js and read Thilo and bg17aw answers about file://.

I didn't know about this behavior and couldn't understand why I have problems like this for pageres.


5. Third-party tools

I use Clickable URLs Sublime Text package. Use it, I can simply open links from my text editor in browser.

CSS links examples

Both links in example are valid. But first link I can successfully open in browser use Clickable URLs, second link — no. This may not be very convenient.


6. Conclusion

Yes:

  1. If you have problems as in Developing process item, you can set your development workflow.
  2. Else you have problems as in Third-party tools item, you can contribute tools.

But you don't need this additional problems. Read information by links in Anti-pattern item: protocol-relative URLs is obsolete.

ASP.NET MVC ActionLink and post method

Came across this needing to POST from a Search (Index) page to the Result page. I did not need as much as @Vitaliy stated but it pointed me in the right direction. All I had to do was this:

@using (Html.BeginForm("Result", "Search", FormMethod.Post)) {
  <div class="row">
    <div class="col-md-4">
      <div class="field">Search Term:</div>
      <input id="k" name="k" type="text" placeholder="Search" />
    </div>
  </div>
  <br />
  <div class="row">
    <div class="col-md-12">
      <button type="submit" class="btn btn-default">Search</button>
    </div>
  </div>
}

My Controller had the following signature method:

[HttpPost]
public async Task<ActionResult> Result(string k)

Get the value of bootstrap Datetimepicker in JavaScript

This is working for me using this Bootsrap Datetimepiker, it returns the value as it is shown in the datepicker input, e.g. 2019-04-11

$('#myDateTimePicker').on('click,focusout', function (){
    var myDate = $("#myDateTimePicker").val();
    //console.log(myDate);
    //alert(myDate);
});

Java how to sort a Linked List?

Elegant solution since JAVA 8:

LinkedList<String>list = new LinkedList<String>();
list.add("abc");
list.add("Bcd");
list.add("aAb");

list.sort(String::compareToIgnoreCase);

Another option would be using lambda expressions:

list.sort((o1, o2) -> o1.compareToIgnoreCase(o2));

New line character in VB.Net?

You need to use HTML on a web page to get line breaks. For example "<br/>" will give you a line break.

Flask Python Buttons

I handle it in the following way:

<html>
    <body>

        <form method="post" action="/">

                <input type="submit" value="Encrypt" name="Encrypt"/>
                <input type="submit" value="Decrypt" name="Decrypt" />

        </form>
    </body>
</html>
    

Python Code :

    from flask import Flask, render_template, request
    
    
    app = Flask(__name__)
    
    
    @app.route("/", methods=['GET', 'POST'])
    def index():
        print(request.method)
        if request.method == 'POST':
            if request.form.get('Encrypt') == 'Encrypt':
                # pass
                print("Encrypted")
            elif  request.form.get('Decrypt') == 'Decrypt':
                # pass # do something else
                print("Decrypted")
            else:
                # pass # unknown
                return render_template("index.html")
        elif request.method == 'GET':
            # return render_template("index.html")
            print("No Post Back Call")
        return render_template("index.html")
    
    
    if __name__ == '__main__':
        app.run()

Why does Git say my master branch is "already up to date" even though it is not?

Any changes you commit, like deleting all your project files, will still be in place after a pull. All a pull does is merge the latest changes from somewhere else into your own branch, and if your branch has deleted everything, then at best you'll get merge conflicts when upstream changes affect files you've deleted. So, in short, yes everything is up to date.

If you describe what outcome you'd like to have instead of "all files deleted", maybe someone can suggest an appropriate course of action.

Update:

GET THE MOST RECENT OF THE CODE ON MY SYSTEM

What you don't seem to understand is that you already have the most recent code, which is yours. If what you really want is to see the most recent of someone else's work that's on the master branch, just do:

git fetch upstream
git checkout upstream/master

Note that this won't leave you in a position to immediately (re)start your own work. If you need to know how to undo something you've done or otherwise revert changes you or someone else have made, then please provide details. Also, consider reading up on what version control is for, since you seem to misunderstand its basic purpose.

How to update attributes without validation

All the validation from model are skipped when we use validate: false

user = User.new(....)
user.save(validate: false)

Error: Uncaught (in promise): Error: Cannot match any routes Angular 2

For me adding AppRoutingModule to my imports solved the problem.

    imports: [
     BrowserModule,
     AppRoutingModule,
     RouterModule.forRoot([
      {
        path: 'new-cmp',
        component: NewCmpComponent
      }
     ])
    ]

PHP import Excel into database (xls & xlsx)

If you can convert .xls to .csv before processing, you can use the query below to import the csv to the database:

load data local infile 'FILE.CSV' into table TABLENAME fields terminated by ',' enclosed by '"' lines terminated by '\n' (FIELD1,FIELD2,FIELD3)

Check whether IIS is installed or not?

For Windows 7:
Control Panel > Programs > Programs and Features > Turn Windows Features On or Off > to turn on IIS click on Check box.

How to cherry-pick multiple commits

If you have selective revisions to merge, say A, C, F, J from A,B,C,D,E,F,G,H,I,J commits, simply use below command:

git cherry-pick A C F J

How to write html code inside <?php ?>, I want write html code within the PHP script so that it can be echoed from Backend

Try it like,

<?php 
    $name='your name';
    echo '<table>
       <tr><th>Name</th></tr>
       <tr><td>'.$name.'</td></tr>
    </table>';
?>

Updated

<?php 
    echo '<table>
       <tr><th>Rst</th><th>Marks</th></tr>
       <tr><td>'.$rst4.'</td><td>'.$marks4.'</td></tr>
    </table>';
?>

How to output MySQL query results in CSV format?

The following bash script works for me. It optionally also gets the schema for the requested tables.

#!/bin/bash
#
# export mysql data to CSV
#https://stackoverflow.com/questions/356578/how-to-output-mysql-query-results-in-csv-format
#

#ansi colors
#http://www.csc.uvic.ca/~sae/seng265/fall04/tips/s265s047-tips/bash-using-colors.html
blue='\033[0;34m'
red='\033[0;31m'
green='\033[0;32m' # '\e[1;32m' is too bright for white bg.
endColor='\033[0m'

#
# a colored message 
#   params:
#     1: l_color - the color of the message
#     2: l_msg - the message to display
#
color_msg() {
  local l_color="$1"
  local l_msg="$2"
  echo -e "${l_color}$l_msg${endColor}"
}


#
# error
#
# show the given error message on stderr and exit
#
#   params:
#     1: l_msg - the error message to display
#
error() {
  local l_msg="$1"
  # use ansi red for error
  color_msg $red "Error:" 1>&2
  color_msg $red "\t$l_msg" 1>&2
  usage
}

#
# display usage 
#
usage() {
  echo "usage: $0 [-h|--help]" 1>&2
  echo "               -o  | --output      csvdirectory"    1>&2
  echo "               -d  | --database    database"   1>&2
  echo "               -t  | --tables      tables"     1>&2
  echo "               -p  | --password    password"   1>&2
  echo "               -u  | --user        user"       1>&2
  echo "               -hs | --host        host"       1>&2
  echo "               -gs | --get-schema"             1>&2
  echo "" 1>&2
  echo "     output: output csv directory to export mysql data into" 1>&2
  echo "" 1>&2
  echo "         user: mysql user" 1>&2
  echo "     password: mysql password" 1>&2
  echo "" 1>&2
  echo "     database: target database" 1>&2
  echo "       tables: tables to export" 1>&2
  echo "         host: host of target database" 1>&2
  echo "" 1>&2
  echo "  -h|--help: show help" 1>&2
  exit 1
}

#
# show help 
#
help() {
  echo "$0 Help" 1>&2
  echo "===========" 1>&2
  echo "$0 exports a csv file from a mysql database optionally limiting to a list of tables" 1>&2
  echo "   example: $0 --database=cms --user=scott --password=tiger  --tables=person --output person.csv" 1>&2
  echo "" 1>&2
  usage
}

domysql() {
  mysql --host $host -u$user --password=$password $database
}

getcolumns() {
  local l_table="$1"
  echo "describe $l_table" | domysql | cut -f1 | grep -v "Field" | grep -v "Warning" | paste -sd "," - 2>/dev/null
}

host="localhost"
mysqlfiles="/var/lib/mysql-files/"

# parse command line options
while true; do
  #echo "option $1"
  case "$1" in
    # options without arguments
    -h|--help) usage;;
    -d|--database)     database="$2" ; shift ;;
    -t|--tables)       tables="$2" ; shift ;;
    -o|--output)       csvoutput="$2" ; shift ;;
    -u|--user)         user="$2" ; shift ;;
    -hs|--host)        host="$2" ; shift ;;
    -p|--password)     password="$2" ; shift ;;
    -gs|--get-schema)  option="getschema";; 
    (--) shift; break;;
    (-*) echo "$0: error - unrecognized option $1" 1>&2; usage;;
    (*) break;;
  esac
  shift
done

# checks
if [ "$csvoutput" == "" ]
then
  error "ouput csv directory not set"
fi
if [ "$database" == "" ]
then
  error "mysql database not set"
fi
if [ "$user" == "" ]
then
  error "mysql user not set"
fi
if [ "$password" == "" ]
then
  error "mysql password not set"
fi

color_msg $blue "exporting tables of database $database"
if [ "$tables" = "" ]
then
tables=$(echo "show tables" | domysql)
fi

case $option in
  getschema) 
   rm $csvoutput$database.schema
   for table in $tables
   do
     color_msg $blue "getting schema for $table"
     echo -n "$table:" >> $csvoutput$database.schema
     getcolumns $table >> $csvoutput$database.schema
   done  
   ;;
  *)
for table in $tables
do
  color_msg $blue "exporting table $table"
  cols=$(grep "$table:" $csvoutput$database.schema | cut -f2 -d:)
  if [  "$cols" = "" ]
  then
    cols=$(getcolumns $table)
  fi
  ssh $host rm $mysqlfiles/$table.csv
cat <<EOF | mysql --host $host -u$user --password=$password $database 
SELECT $cols FROM $table INTO OUTFILE '$mysqlfiles$table.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';
EOF
  scp $host:$mysqlfiles/$table.csv $csvoutput$table.csv.raw
  (echo "$cols"; cat $csvoutput$table.csv.raw) > $csvoutput$table.csv
  rm $csvoutput$table.csv.raw
done
  ;;
esac

Unresponsive KeyListener for JFrame

Deion (and anyone else asking a similar question), you could use Peter's code above but instead of printing to standard output, you test for the key code PRESSED, RELEASED, or TYPED.

@Override
public boolean dispatchKeyEvent(KeyEvent e) {
    if (e.getID() == KeyEvent.KEY_PRESSED) {
        if (e.getKeyCode() == KeyEvent.VK_F4) {
            dispose();
        }
    } else if (e.getID() == KeyEvent.KEY_RELEASED) {
        if (e.getKeyCode() == KeyEvent.VK_F4) {
            dispose();
        }
    } else if (e.getID() == KeyEvent.KEY_TYPED) {
        if (e.getKeyCode() == KeyEvent.VK_F4) {
            dispose();
        }
    }
    return false;
}

Spring: How to get parameters from POST body?

In class do like this

@RequestMapping(value = "/saveData", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Boolean> saveData(
    HttpServletResponse response,
    Bean beanName
) throws MyException {
    return new ResponseEntity<Boolean>(uiRequestProcessor.saveData(a), HttpStatus.OK);
}

In page do like this:

<form enctype="multipart/form-data" action="<%=request.getContextPath()%>/saveData" method="post" name="saveForm" id="saveForm">
<input type="text" value="${beanName.userName }" id="username" name="userName" />

</from>

How to convert an ArrayList containing Integers to primitive int array?

   List<Integer> list = new ArrayList<Integer>();

    list.add(1);
    list.add(2);

    int[] result = null;
    StringBuffer strBuffer = new StringBuffer();
    for (Object o : list) {
        strBuffer.append(o);
        result = new int[] { Integer.parseInt(strBuffer.toString()) };
        for (Integer i : result) {
            System.out.println(i);
        }
        strBuffer.delete(0, strBuffer.length());
    }

GridView Hide Column by code

There is a small change to happen, it will not come under rowdatabound, first all the rows should get bound, only then could we hide that. So it will be a separate method after the grid is dataBound.

CAST DECIMAL to INT

Try cast (columnName as unsigned)

unsigned is positive value only

If you want to include negative value, then cast (columnName as signed),
The difference between sign (negative include) and unsigned (twice the size of sign, but non-negative)

Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6

As it is written in the using-maven docs from the Kotlin website:

You just have to put <kotlin.compiler.jvmTarget>1.8</kotlin.compiler.jvmTarget> into the properties section of your pom.xml

How to merge a specific commit in Git

In my use case we had a similar need for CI CD. We used git flow with develop and master branches. Developers are free to merge their changes directly to develop or via a pull request from a feature branch. However to master we merge only the stable commits from the develop branch in an automated way via Jenkins.

In this case doing cherry-pick is not a good option. However we create a local-branch from the commit-id then merge that local-branch to master and perform mvn clean verify(we use maven). If success then release production version artifact to nexus using maven release plugin with localCheckout=true option and pushChanges=false. Finally when everything is success then push the changes and tag to origin.

A sample code snippet:

Assuming you are on master if done manually. However on jenkins, when you checkout the repo you will be on the default branch(master if configured).

git pull  // Just to pull any changes.
git branch local-<commitd-id> <commit-id>  // Create a branch from the given commit-id
git merge local-<commit-id>  // Merge that local branch to master.
mvn clean verify   // Verify if the code is build able
mvn <any args> release:clean release:prepare release:perform // Release artifacts
git push origin/master  // Push the local changes performed above to origin.
git push origin <tag>  // Push the tag to origin

This will give you a full control with a fearless merge or conflict hell.

Feel free to advise in case there is any better option.

IF/ELSE Stored Procedure

Nick is right. The next error is the else should be else if (you currently have a boolean expression in your else which makes no sense). Here is what it should be

ELSE IF(@Trans_type = 'subscr_cancel')
    BEGIN
    SET @tmpType = 'basic'
    END

You currently have the following (which is wrong):

ELSE(@Trans_type = 'subscr_cancel')
    BEGIN
    SET @tmpType = 'basic'
    END

Here's a tip for the future- double click on the error and SQL Server management Studio will go to the line where the error resides. If you think SQL Server gives cryptic errors (which I don't think it does), then you haven't worked with Oracle!

Java array reflection: isArray vs. instanceof

There is no difference in behavior that I can find between the two (other than the obvious null-case). As for which version to prefer, I would go with the second. It is the standard way of doing this in Java.

If it confuses readers of your code (because String[] instanceof Object[] is true), you may want to use the first to be more explicit if code reviewers keep asking about it.

ActionLink htmlAttributes

Replace the desired hyphen with an underscore; it will automatically be rendered as a hyphen:

@Html.ActionLink("Edit", "edit", "markets",
    new { id = 1 },
    new {@class="ui-btn-right", data_icon="gear"})

becomes:

<form action="markets/Edit/1" class="ui-btn-right" data-icon="gear" .../>

Best Practice for Forcing Garbage Collection in C#

Large objects are allocated on LOH (large object heap), not on gen 0. If you're saying that they don't get garbage-collected with gen 0, you're right. I believe they are collected only when the full GC cycle (generations 0, 1 and 2) happens.

That being said, I believe on the other side GC will adjust and collect memory more aggressively when you work with large objects and the memory pressure is going up.

It is hard to say whether to collect or not and in which circumstances. I used to do GC.Collect() after disposing of dialog windows/forms with numerous controls etc. (because by the time the form and its controls end up in gen 2 due to creating many instances of business objects/loading much data - no large objects obviously), but actually didn't notice any positive or negative effects in the long term by doing so.

if statement checks for null but still throws a NullPointerException

Change Below line

if (str == null | str.length() == 0) {

into

if (str == null || str.isEmpty()) {

now your code will run corectlly. Make sure str.isEmpty() comes after str == null because calling isEmpty() on null will cause NullPointerException. Because of Java uses Short-circuit evaluation when str == null is true it will not evaluate str.isEmpty()

What is the best way to get all the divisors of a number?

Old question, but here is my take:

def divs(n, m):
    if m == 1: return [1]
    if n % m == 0: return [m] + divs(n, m - 1)
    return divs(n, m - 1)

You can proxy with:

def divisorGenerator(n):
    for x in reversed(divs(n, n)):
        yield x

NOTE: For languages that support, this could be tail recursive.

FAIL - Application at context path /Hello could not be started

I've had the same problem, was missing a slash in servlet url in web.xml

replace

<servlet-mapping>
    <servlet-name>jsonservice</servlet-name>
    <url-pattern>jsonservice</url-pattern>
</servlet-mapping>

with

<servlet-mapping>
    <servlet-name>jsonservice</servlet-name>
    <url-pattern>/jsonservice</url-pattern>
</servlet-mapping>

How to resolve Unneccessary Stubbing exception

Replace

@RunWith(MockitoJUnitRunner.class)

with

@RunWith(MockitoJUnitRunner.Silent.class)

or remove @RunWith(MockitoJUnitRunner.class)

or just comment out the unwanted mocking calls (shown as unauthorised stubbing).

Python csv string to array

Per the documentation:

And while the module doesn’t directly support parsing strings, it can easily be done:

import csv
for row in csv.reader(['one,two,three']):
    print row

Just turn your string into a single element list.

Importing StringIO seems a bit excessive to me when this example is explicitly in the docs.

Change the Textbox height?

You can set the MinimumSize and/or the MaximumSize properties of the textbox. This does not affect the size immediately, but when you resize the textbox in the forms designer, the size will automatically be adjusted to satisfy the minimum/maximum size constraints. This works even when Multiline is set to false and does not depend on the font size.

Fatal error: Class 'PHPMailer' not found

all answers are outdated now. Most current version (as of Feb 2018) does not have autoload anymore, and PHPMailer should be initialized as follows:

<?php

  require("/home/site/libs/PHPMailer-master/src/PHPMailer.php");
  require("/home/site/libs/PHPMailer-master/src/SMTP.php");

    $mail = new PHPMailer\PHPMailer\PHPMailer();
    $mail->IsSMTP(); // enable SMTP

    $mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
    $mail->SMTPAuth = true; // authentication enabled
    $mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
    $mail->Host = "smtp.gmail.com";
    $mail->Port = 465; // or 587
    $mail->IsHTML(true);
    $mail->Username = "xxxxxx";
    $mail->Password = "xxxx";
    $mail->SetFrom("[email protected]");
    $mail->Subject = "Test";
    $mail->Body = "hello";
    $mail->AddAddress("[email protected]");

     if(!$mail->Send()) {
        echo "Mailer Error: " . $mail->ErrorInfo;
     } else {
        echo "Message has been sent";
     }
?>

Generate a random number in a certain range in MATLAB

r = 13 + 7.*rand(100,1);

Where 100,1 is the size of the desidered vector

Canvas width and height in HTML5

A canvas has 2 sizes, the dimension of the pixels in the canvas (it's backingstore or drawingBuffer) and the display size. The number of pixels is set using the the canvas attributes. In HTML

<canvas width="400" height="300"></canvas>

Or in JavaScript

someCanvasElement.width = 400;
someCanvasElement.height = 300;

Separate from that are the canvas's CSS style width and height

In CSS

canvas {  /* or some other selector */
   width: 500px;
   height: 400px;
}

Or in JavaScript

canvas.style.width = "500px";
canvas.style.height = "400px";

The arguably best way to make a canvas 1x1 pixels is to ALWAYS USE CSS to choose the size then write a tiny bit of JavaScript to make the number of pixels match that size.

function resizeCanvasToDisplaySize(canvas) {
   // look up the size the canvas is being displayed
   const width = canvas.clientWidth;
   const height = canvas.clientHeight;

   // If it's resolution does not match change it
   if (canvas.width !== width || canvas.height !== height) {
     canvas.width = width;
     canvas.height = height;
     return true;
   }

   return false;
}

Why is this the best way? Because it works in most cases without having to change any code.

Here's a full window canvas:

_x000D_
_x000D_
const ctx = document.querySelector("#c").getContext("2d");_x000D_
_x000D_
function render(time) {_x000D_
  time *= 0.001;_x000D_
  resizeCanvasToDisplaySize(ctx.canvas);_x000D_
 _x000D_
  ctx.fillStyle = "#DDE";_x000D_
  ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);_x000D_
  ctx.save();_x000D_
 _x000D_
  const spacing = 64;_x000D_
  const size = 48;_x000D_
  const across = ctx.canvas.width / spacing + 1;_x000D_
  const down = ctx.canvas.height / spacing + 1;_x000D_
  const s = Math.sin(time);_x000D_
  const c = Math.cos(time);_x000D_
  for (let y = 0; y < down; ++y) {_x000D_
    for (let x = 0; x < across; ++x) {_x000D_
      ctx.setTransform(c, -s, s, c, x * spacing, y * spacing);_x000D_
      ctx.strokeRect(-size / 2, -size / 2, size, size);_x000D_
    }_x000D_
  }_x000D_
  _x000D_
  ctx.restore();_x000D_
  _x000D_
  requestAnimationFrame(render);_x000D_
}_x000D_
requestAnimationFrame(render);_x000D_
_x000D_
function resizeCanvasToDisplaySize(canvas) {_x000D_
   // look up the size the canvas is being displayed_x000D_
   const width = canvas.clientWidth;_x000D_
   const height = canvas.clientHeight;_x000D_
_x000D_
   // If it's resolution does not match change it_x000D_
   if (canvas.width !== width || canvas.height !== height) {_x000D_
     canvas.width = width;_x000D_
     canvas.height = height;_x000D_
     return true;_x000D_
   }_x000D_
_x000D_
   return false;_x000D_
}
_x000D_
body { margin: 0; }_x000D_
canvas { display: block; width: 100vw; height: 100vh; }
_x000D_
<canvas id="c"></canvas>
_x000D_
_x000D_
_x000D_

And Here's a canvas as a float in a paragraph

_x000D_
_x000D_
const ctx = document.querySelector("#c").getContext("2d");_x000D_
_x000D_
function render(time) {_x000D_
  time *= 0.001;_x000D_
  resizeCanvasToDisplaySize(ctx.canvas);_x000D_
 _x000D_
  ctx.fillStyle = "#DDE";_x000D_
  ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);_x000D_
  ctx.save();_x000D_
 _x000D_
  const spacing = 64;_x000D_
  const size = 48;_x000D_
  const across = ctx.canvas.width  / spacing + 1;_x000D_
  const down   = ctx.canvas.height / spacing + 1;_x000D_
  const s = Math.sin(time);_x000D_
  const c = Math.cos(time);_x000D_
  for (let y = 0; y <= down; ++y) {_x000D_
    for (let x = 0; x <= across; ++x) {_x000D_
      ctx.setTransform(c, -s, s, c, x * spacing, y * spacing);_x000D_
      ctx.strokeRect(-size / 2, -size / 2, size, size);_x000D_
    }_x000D_
  }_x000D_
  _x000D_
  ctx.restore();_x000D_
  _x000D_
  requestAnimationFrame(render);_x000D_
}_x000D_
requestAnimationFrame(render);_x000D_
_x000D_
function resizeCanvasToDisplaySize(canvas) {_x000D_
   // look up the size the canvas is being displayed_x000D_
   const width = canvas.clientWidth;_x000D_
   const height = canvas.clientHeight;_x000D_
_x000D_
   // If it's resolution does not match change it_x000D_
   if (canvas.width !== width || canvas.height !== height) {_x000D_
     canvas.width = width;_x000D_
     canvas.height = height;_x000D_
     return true;_x000D_
   }_x000D_
_x000D_
   return false;_x000D_
}
_x000D_
span { _x000D_
   width: 250px; _x000D_
   height: 100px; _x000D_
   float: left; _x000D_
   padding: 1em 1em 1em 0;_x000D_
   display: inline-block;_x000D_
}_x000D_
canvas {_x000D_
   width: 100%;_x000D_
   height: 100%;_x000D_
}
_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent cursus venenatis metus. Mauris ac nibh at odio scelerisque scelerisque. Donec ut enim <span class="diagram"><canvas id="c"></canvas></span>_x000D_
vel urna gravida imperdiet id ac odio. Aenean congue hendrerit eros id facilisis. In vitae leo ullamcorper, aliquet leo a, vehicula magna. Proin sollicitudin vestibulum aliquet. Sed et varius justo._x000D_
<br/><br/>_x000D_
Quisque tempor metus in porttitor placerat. Nulla vehicula sem nec ipsum commodo, at tincidunt orci porttitor. Duis porttitor egestas dui eu viverra. Sed et ipsum eget odio pharetra semper. Integer tempor orci quam, eget aliquet velit consectetur sit amet. Maecenas maximus placerat arcu in varius. Morbi semper, quam a ullamcorper interdum, augue nisl sagittis urna, sed pharetra lectus ex nec elit. Nullam viverra lacinia tellus, bibendum maximus nisl dictum id. Phasellus mauris quam, rutrum ut congue non, hendrerit sollicitudin urna._x000D_
</p>
_x000D_
_x000D_
_x000D_

Here's a canvas in a sizable control panel

_x000D_
_x000D_
const ctx = document.querySelector("#c").getContext("2d");_x000D_
_x000D_
function render(time) {_x000D_
  time *= 0.001;_x000D_
  resizeCanvasToDisplaySize(ctx.canvas);_x000D_
_x000D_
  ctx.fillStyle = "#DDE";_x000D_
  ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);_x000D_
  ctx.save();_x000D_
 _x000D_
  const spacing = 64;_x000D_
  const size = 48;_x000D_
  const across = ctx.canvas.width / spacing + 1;_x000D_
  const down = ctx.canvas.height / spacing + 1;_x000D_
  const s = Math.sin(time);_x000D_
  const c = Math.cos(time);_x000D_
  for (let y = 0; y < down; ++y) {_x000D_
    for (let x = 0; x < across; ++x) {_x000D_
      ctx.setTransform(c, -s, s, c, x * spacing, y * spacing);_x000D_
      ctx.strokeRect(-size / 2, -size / 2, size, size);_x000D_
    }_x000D_
  }_x000D_
  _x000D_
  ctx.restore();_x000D_
  _x000D_
  requestAnimationFrame(render);_x000D_
}_x000D_
requestAnimationFrame(render);_x000D_
_x000D_
function resizeCanvasToDisplaySize(canvas) {_x000D_
   // look up the size the canvas is being displayed_x000D_
   const width = canvas.clientWidth;_x000D_
   const height = canvas.clientHeight;_x000D_
_x000D_
   // If it's resolution does not match change it_x000D_
   if (canvas.width !== width || canvas.height !== height) {_x000D_
     canvas.width = width;_x000D_
     canvas.height = height;_x000D_
     return true;_x000D_
   }_x000D_
_x000D_
   return false;_x000D_
}_x000D_
_x000D_
// ----- the code above related to the canvas does not change ----_x000D_
// ---- the code below is related to the slider ----_x000D_
const $ = document.querySelector.bind(document);_x000D_
const left = $(".left");_x000D_
const slider = $(".slider");_x000D_
let dragging;_x000D_
let lastX;_x000D_
let startWidth;_x000D_
_x000D_
slider.addEventListener('mousedown', e => {_x000D_
 lastX = e.pageX;_x000D_
 dragging = true;_x000D_
});_x000D_
_x000D_
window.addEventListener('mouseup', e => {_x000D_
 dragging = false;_x000D_
});_x000D_
_x000D_
window.addEventListener('mousemove', e => {_x000D_
  if (dragging) {_x000D_
    const deltaX = e.pageX - lastX;_x000D_
    left.style.width = left.clientWidth + deltaX + "px";_x000D_
    lastX = e.pageX;_x000D_
  }_x000D_
});
_x000D_
body { _x000D_
  margin: 0;_x000D_
}_x000D_
.frame {_x000D_
  display: flex;_x000D_
  align-items: space-between;_x000D_
  height: 100vh;_x000D_
}_x000D_
.left {_x000D_
  width: 70%;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
}  _x000D_
canvas {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}_x000D_
pre {_x000D_
  padding: 1em;_x000D_
}_x000D_
.slider {_x000D_
  width: 10px;_x000D_
  background: #000;_x000D_
}_x000D_
.right {_x000D_
  flex 1 1 auto;_x000D_
}
_x000D_
<div class="frame">_x000D_
  <div class="left">_x000D_
     <canvas id="c"></canvas>_x000D_
  </div>_x000D_
  <div class="slider">_x000D_
  _x000D_
  </div>_x000D_
  <div class="right">_x000D_
     <pre>_x000D_
* controls_x000D_
* go _x000D_
* here_x000D_
_x000D_
&lt;- drag this_x000D_
     </pre>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

here's a canvas as a background

_x000D_
_x000D_
const ctx = document.querySelector("#c").getContext("2d");_x000D_
_x000D_
function render(time) {_x000D_
  time *= 0.001;_x000D_
  resizeCanvasToDisplaySize(ctx.canvas);_x000D_
 _x000D_
  ctx.fillStyle = "#DDE";_x000D_
  ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);_x000D_
  ctx.save();_x000D_
 _x000D_
  const spacing = 64;_x000D_
  const size = 48;_x000D_
  const across = ctx.canvas.width / spacing + 1;_x000D_
  const down = ctx.canvas.height / spacing + 1;_x000D_
  const s = Math.sin(time);_x000D_
  const c = Math.cos(time);_x000D_
  for (let y = 0; y < down; ++y) {_x000D_
    for (let x = 0; x < across; ++x) {_x000D_
      ctx.setTransform(c, -s, s, c, x * spacing, y * spacing);_x000D_
      ctx.strokeRect(-size / 2, -size / 2, size, size);_x000D_
    }_x000D_
  }_x000D_
  _x000D_
  ctx.restore();_x000D_
  _x000D_
  requestAnimationFrame(render);_x000D_
}_x000D_
requestAnimationFrame(render);_x000D_
_x000D_
function resizeCanvasToDisplaySize(canvas) {_x000D_
   // look up the size the canvas is being displayed_x000D_
   const width = canvas.clientWidth;_x000D_
   const height = canvas.clientHeight;_x000D_
_x000D_
   // If it's resolution does not match change it_x000D_
   if (canvas.width !== width || canvas.height !== height) {_x000D_
     canvas.width = width;_x000D_
     canvas.height = height;_x000D_
     return true;_x000D_
   }_x000D_
_x000D_
   return false;_x000D_
}
_x000D_
body { margin: 0; }_x000D_
canvas { _x000D_
  display: block; _x000D_
  width: 100vw; _x000D_
  height: 100vh;  _x000D_
  position: fixed;_x000D_
}_x000D_
#content {_x000D_
  position: absolute;_x000D_
  margin: 0 1em;_x000D_
  font-size: xx-large;_x000D_
  font-family: sans-serif;_x000D_
  font-weight: bold;_x000D_
  text-shadow: 2px  2px 0 #FFF, _x000D_
              -2px -2px 0 #FFF,_x000D_
              -2px  2px 0 #FFF,_x000D_
               2px -2px 0 #FFF;_x000D_
}
_x000D_
<canvas id="c"></canvas>_x000D_
<div id="content">_x000D_
<p>_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent cursus venenatis metus. Mauris ac nibh at odio scelerisque scelerisque. Donec ut enim vel urna gravida imperdiet id ac odio. Aenean congue hendrerit eros id facilisis. In vitae leo ullamcorper, aliquet leo a, vehicula magna. Proin sollicitudin vestibulum aliquet. Sed et varius justo._x000D_
</p>_x000D_
<p>_x000D_
Quisque tempor metus in porttitor placerat. Nulla vehicula sem nec ipsum commodo, at tincidunt orci porttitor. Duis porttitor egestas dui eu viverra. Sed et ipsum eget odio pharetra semper. Integer tempor orci quam, eget aliquet velit consectetur sit amet. Maecenas maximus placerat arcu in varius. Morbi semper, quam a ullamcorper interdum, augue nisl sagittis urna, sed pharetra lectus ex nec elit. Nullam viverra lacinia tellus, bibendum maximus nisl dictum id. Phasellus mauris quam, rutrum ut congue non, hendrerit sollicitudin urna._x000D_
</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Because I didn't set the attributes the only thing that changed in each sample is the CSS (as far as the canvas is concerned)

Notes:

  • Don't put borders or padding on a canvas element. Computing the size to subtract from the number of dimensions of the element is troublesome

How do you determine what technology a website is built on?

URLs can give a lot of clues, especially with Content Management Systems.

For example "http://abcxyz.com/node/46" looks a lot like Drupal.

Also many frameworks have standard JavaScript and CSS files they use.

How to initialize a JavaScript Date to a particular time zone

//For mumbai time diffrence is 5.5 hrs so
// city_time_diff=5.5 (change according to your city) 

let timee= Date.now()
    timee=timee+(3600000*city_time_diff); //Add our city time (in msec) 
    let new_date=new Date(timee)
console.log("My city time is: ",new_date);

When should I use mmap for file access?

mmap is great if you have multiple processes accessing data in a read only fashion from the same file, which is common in the kind of server systems I write. mmap allows all those processes to share the same physical memory pages, saving a lot of memory.

mmap also allows the operating system to optimize paging operations. For example, consider two programs; program A which reads in a 1MB file into a buffer creating with malloc, and program B which mmaps the 1MB file into memory. If the operating system has to swap part of A's memory out, it must write the contents of the buffer to swap before it can reuse the memory. In B's case any unmodified mmap'd pages can be reused immediately because the OS knows how to restore them from the existing file they were mmap'd from. (The OS can detect which pages are unmodified by initially marking writable mmap'd pages as read only and catching seg faults, similar to Copy on Write strategy).

mmap is also useful for inter process communication. You can mmap a file as read / write in the processes that need to communicate and then use synchronization primitives in the mmap'd region (this is what the MAP_HASSEMAPHORE flag is for).

One place mmap can be awkward is if you need to work with very large files on a 32 bit machine. This is because mmap has to find a contiguous block of addresses in your process's address space that is large enough to fit the entire range of the file being mapped. This can become a problem if your address space becomes fragmented, where you might have 2 GB of address space free, but no individual range of it can fit a 1 GB file mapping. In this case you may have to map the file in smaller chunks than you would like to make it fit.

Another potential awkwardness with mmap as a replacement for read / write is that you have to start your mapping on offsets of the page size. If you just want to get some data at offset X you will need to fixup that offset so it's compatible with mmap.

And finally, read / write are the only way you can work with some types of files. mmap can't be used on things like pipes and ttys.

Plotting histograms from grouped data in a pandas DataFrame

One solution is to use matplotlib histogram directly on each grouped data frame. You can loop through the groups obtained in a loop. Each group is a dataframe. And you can create a histogram for each one.

from pandas import DataFrame
import numpy as np
x = ['A']*300 + ['B']*400 + ['C']*300
y = np.random.randn(1000)
df = DataFrame({'Letter':x, 'N':y})
grouped = df.groupby('Letter')

for group in grouped:
  figure()
  matplotlib.pyplot.hist(group[1].N)
  show()

Android Log.v(), Log.d(), Log.i(), Log.w(), Log.e() - When to use each one?

Even though that this question was already answered I feel that there are missing examples in the answer that was answered.

Therefore I'll bring here what I wrote in a blog post "Android Log Levels"

Verbose

Is the lowest level of logging. If you want to go nuts with logging then you go with this level. I never understood when to use Verbose and when to use Debug. The difference sounded to me very arbitrary. I finally understood it once I was pointed to the source code of Android¹ “Verbose should never be compiled into an application except during development.” Now it is clear to me, whenever you are developing and want to add deletable logs that help you during the development it is useful to have the verbose level this will help you delete all these logs before you go into production.

Debug

Is for debugging purposes. This is the lowest level that should be in production. Information that is here is to help during development. Most times you’ll disable this log in production so that less information will be sent and only enable this log if you have a problem. I like to log in debug all the information that the app sends/receives from the server (take care not to log passwords!!!). This is very helpful to understand if the bug lies in the server or the app. I also make logs of entering and exiting of important functions.

Info

For informational messages that highlight the progress of the application. For example, when initialising of the app is finished. Add info when the user moves between activities and fragments. Log each API call but just little information like the URL , status and the response time.

Warning

When there is a potentially harmful situation.

This log is in my experience a tricky level. When do you have a potential harmful situation? In general or that it is OK or that it is an error. I personally don’t use this level much. Examples of when I use it are usually when stuff happens several times. For example, a user has a wrong password more than 3 times. This could be because he entered the password wrongly 3 times, it could also be because there is a problem with a character that isn’t being accepted in our system. Same goes with network connection problems.

Error

Error events. The application can still continue to run after the error. This can be for example when I get a null pointer where I’m not supposed to get one. There was an error parsing the response of the server. Got an error from the server.

WTF (What a Terrible Failure)

Fatal is for severe error events that will lead the application to exit. In Android the fatal is in reality the Error level, the difference is that it also adds the fullstack.

Removing a model in rails (reverse of "rails g model Title...")

Try this

rails destroy model Rating

It will remove model, migration, tests and fixtures

Convert from enum ordinal to enum type

You could use a static lookup table:

public enum Suit {
  spades, hearts, diamonds, clubs;

  private static final Map<Integer, Suit> lookup = new HashMap<Integer, Suit>();

  static{
    int ordinal = 0;
    for (Suit suit : EnumSet.allOf(Suit.class)) {
      lookup.put(ordinal, suit);
      ordinal+= 1;
    }
  }

  public Suit fromOrdinal(int ordinal) {
    return lookup.get(ordinal);
  }
}

Angular 2 change event - model changes

That's a known issue. Currently you have to use a workaround like shown in your question.

This is working as intended. When the change event is emitted ngModelChange (the (...) part of [(ngModel)] hasn't updated the bound model yet:

<input type="checkbox"  (ngModelChange)="myModel=$event" [ngModel]="mymodel">

See also

Add centered text to the middle of a <hr/>-like line

You can accomplish this with :before and :after without knowing the width of container or background color, and using them allows for greater styling of the line breaks. For example, this can be modified to make double-lines, dotted lines, etc.

JSFiddle

CSS, and HTML usage:

_x000D_
_x000D_
.hr-sect {
    display: flex;
    flex-basis: 100%;
    align-items: center;
    color: rgba(0, 0, 0, 0.35);
    margin: 8px 0px;
}
.hr-sect:before,
.hr-sect:after {
    content: "";
    flex-grow: 1;
    background: rgba(0, 0, 0, 0.35);
    height: 1px;
    font-size: 0px;
    line-height: 0px;
    margin: 0px 8px;
}
_x000D_
<div class="hr-sect">CATEGORY</div>
_x000D_
_x000D_
_x000D_

SCSS Version:

.hr-sect {
    display: flex;
    flex-basis: 100%;
    align-items: center;
    color: rgba(0, 0, 0, 0.35);
    margin: 8px 0;

    &:before, &:after {
        content: "";
        flex-grow: 1;
        background: rgba(0, 0, 0, 0.35);
        height: 1px;
        font-size: 0;
        line-height: 0;
        margin: 0 8px;
    }
}

How to substitute shell variables in complex text files

If you really only want to use bash (and sed), then I would go through each of your environment variables (as returned by set in posix mode) and build a bunch of -e 'regex' for sed from that, terminated by a -e 's/\$[a-zA-Z_][a-zA-Z0-9_]*//g', then pass all that to sed.

Perl would do a nicer job though, you have access to the environment vars as an array and you can do executable replacements so you only match any environment variable once.

How different is Scrum practice from Agile Practice?

Agile is the practice and Scrum is the process to following this practice same as eXtreme Programming (XP) and Kanban are the alternative process to following Agile development practice.

How to rsync only a specific list of files?

There is a flag --files-from that does exactly what you want. From man rsync:

--files-from=FILE

Using this option allows you to specify the exact list of files to transfer (as read from the specified FILE or - for standard input). It also tweaks the default behavior of rsync to make transferring just the specified files and directories easier:

  • The --relative (-R) option is implied, which preserves the path information that is specified for each item in the file (use --no-relative or --no-R if you want to turn that off).

  • The --dirs (-d) option is implied, which will create directories specified in the list on the destination rather than noisily skipping them (use --no-dirs or --no-d if you want to turn that off).

  • The --archive (-a) option’s behavior does not imply --recursive (-r), so specify it explicitly, if you want it.

  • These side-effects change the default state of rsync, so the position of the --files-from option on the command-line has no bearing on how other options are parsed (e.g. -a works the same before or after --files-from, as does --no-R and all other options).

The filenames that are read from the FILE are all relative to the source dir -- any leading slashes are removed and no ".." references are allowed to go higher than the source dir. For example, take this command:

rsync -a --files-from=/tmp/foo /usr remote:/backup

If /tmp/foo contains the string "bin" (or even "/bin"), the /usr/bin directory will be created as /backup/bin on the remote host. If it contains "bin/" (note the trailing slash), the immediate contents of the directory would also be sent (without needing to be explicitly mentioned in the file -- this began in version 2.6.4). In both cases, if the -r option was enabled, that dir’s entire hierarchy would also be transferred (keep in mind that -r needs to be specified explicitly with --files-from, since it is not implied by -a). Also note that the effect of the (enabled by default) --relative option is to duplicate only the path info that is read from the file -- it does not force the duplication of the source-spec path (/usr in this case).

In addition, the --files-from file can be read from the remote host instead of the local host if you specify a "host:" in front of the file (the host must match one end of the transfer). As a short-cut, you can specify just a prefix of ":" to mean "use the remote end of the transfer". For example:

rsync -a --files-from=:/path/file-list src:/ /tmp/copy

This would copy all the files specified in the /path/file-list file that was located on the remote "src" host.

If the --iconv and --protect-args options are specified and the --files-from filenames are being sent from one host to another, the filenames will be translated from the sending host’s charset to the receiving host’s charset.

NOTE: sorting the list of files in the --files-from input helps rsync to be more efficient, as it will avoid re-visiting the path elements that are shared between adjacent entries. If the input is not sorted, some path elements (implied directories) may end up being scanned multiple times, and rsync will eventually unduplicate them after they get turned into file-list elements.

unbound method f() must be called with fibo_ instance as first argument (got classobj instance instead)

fibo = f.fibo references the class itself. You probably wanted fibo = f.fibo() (note the parentheses) to make an instance of the class, after which fibo.f() should succeed correctly.

f.fibo.f() fails because you are essentially calling f(self, a=0) without supplying self; self is "bound" automatically when you have an instance of the class.

Chosen Jquery Plugin - getting selected values

$("#select-id").chosen().val()

this is the right answer, I tried, and the value passed is the values separated by ","

Eclipse: How to build an executable jar with external jar?

As a good practice you can use an Ant Script (Eclipse comes with it) to generate your JAR file. Inside this JAR you can have all dependent libs.

You can even set the MANIFEST's Class-path header to point to files in your filesystem, it's not a good practice though.

Ant build.xml script example:

<project name="jar with libs" default="compile and build" basedir=".">
<!-- this is used at compile time -->
<path id="example-classpath">
    <pathelement location="${root-dir}" />
    <fileset dir="D:/LIC/xalan-j_2_7_1" includes="*.jar" />
</path>

<target name="compile and build">
    <!-- deletes previously created jar -->
    <delete file="test.jar" />

    <!-- compile your code and drop .class into "bin" directory -->
    <javac srcdir="${basedir}" destdir="bin" debug="true" deprecation="on">
        <!-- this is telling the compiler where are the dependencies -->
        <classpath refid="example-classpath" />
    </javac>

    <!-- copy the JARs that you need to "bin" directory  -->
    <copy todir="bin">
        <fileset dir="D:/LIC/xalan-j_2_7_1" includes="*.jar" />
    </copy>

    <!-- creates your jar with the contents inside "bin" (now with your .class and .jar dependencies) -->
    <jar destfile="test.jar" basedir="bin" duplicate="preserve">
        <manifest>
            <!-- Who is building this jar? -->
            <attribute name="Built-By" value="${user.name}" />
            <!-- Information about the program itself -->
            <attribute name="Implementation-Vendor" value="ACME inc." />
            <attribute name="Implementation-Title" value="GreatProduct" />
            <attribute name="Implementation-Version" value="1.0.0beta2" />
            <!-- this tells which class should run when executing your jar -->
            <attribute name="Main-class" value="ApplyXPath" />
        </manifest>
    </jar>
</target>

Python loop that also accesses previous and next values

AFAIK this should be pretty fast, but I didn't test it:

def iterate_prv_nxt(my_list):
    prv, cur, nxt = None, iter(my_list), iter(my_list)
    next(nxt, None)

    while True:
        try:
            if prv:
                yield next(prv), next(cur), next(nxt, None)
            else:
                yield None, next(cur), next(nxt, None)
                prv = iter(my_list)
        except StopIteration:
            break

Example usage:

>>> my_list = ['a', 'b', 'c']
>>> for prv, cur, nxt in iterate_prv_nxt(my_list):
...    print prv, cur, nxt
... 
None a b
a b c
b c None

How to split a comma separated string and process in a loop using JavaScript

Try the following snippet:

var mystring = 'this,is,an,example';
var splits = mystring.split(",");
alert(splits[0]); // output: this

change text of button and disable button in iOS

SWIFT 4 with extension

set:

// set button label for all states
extension UIButton {
    public func setAllStatesTitle(_ newTitle: String){
        self.setTitle(newTitle, for: .normal)
        self.setTitle(newTitle, for: .selected)
        self.setTitle(newTitle, for: .disabled)
    }
}

and use:

yourBtn.setAllStatesTitle("btn title")

The remote server returned an error: (403) Forbidden

This probably won't help too many people, but this was my case: I was using the Jira Rest Api and was using my personal credentials (the ones I use to log into Jira). I had updated my Jira password but forgot to update them in my code. I got the 403 error, I tried updating my password in the code but still got the error.

The solution: I tried logging into Jira (from their login page) and I had to enter the text to prove I wasn't a bot. After that I tried again from the code and it worked. Takeaway: The server may have locked you out.

jQuery add blank option to top of list and make selected to existing dropdown

This worked:

$("#theSelectId").prepend("<option value='' selected='selected'></option>");

Firebug Output:

<select id="theSelectId">
  <option selected="selected" value=""/>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

You could also use .prependTo if you wanted to reverse the order:

?$("<option>", { value: '', selected: true }).prependTo("#theSelectId");???????????

django admin - add custom form fields that are not part of the model

Either in your admin.py or in a separate forms.py you can add a ModelForm class and then declare your extra fields inside that as you normally would. I've also given an example of how you might use these values in form.save():

from django import forms
from yourapp.models import YourModel


class YourModelForm(forms.ModelForm):

    extra_field = forms.CharField()

    def save(self, commit=True):
        extra_field = self.cleaned_data.get('extra_field', None)
        # ...do something with extra_field here...
        return super(YourModelForm, self).save(commit=commit)

    class Meta:
        model = YourModel

To have the extra fields appearing in the admin just:

  1. edit your admin.py and set the form property to refer to the form you created above
  2. include your new fields in your fields or fieldsets declaration

Like this:

class YourModelAdmin(admin.ModelAdmin):

    form = YourModelForm

    fieldsets = (
        (None, {
            'fields': ('name', 'description', 'extra_field',),
        }),
    )

UPDATE: In django 1.8 you need to add fields = '__all__' to the metaclass of YourModelForm.

How many threads can a Java VM support?

I recall hearing a Clojure talk where he got to run one of his apps on some specialized machine at a trade show with thousands of cores (9000?), and it loaded them all. Unfortunately, I can't find the link right now (help?).

Based on that, I think it's safe to say that the hardware and your code are the limiting factors, not the JVM.

Adding rows to dataset

 DataSet ds = new DataSet();

 DataTable dt = new DataTable("MyTable");
 dt.Columns.Add(new DataColumn("id",typeof(int)));
 dt.Columns.Add(new DataColumn("name", typeof(string)));

 DataRow dr = dt.NewRow();
 dr["id"] = 123;
 dr["name"] = "John";
 dt.Rows.Add(dr);
 ds.Tables.Add(dt);

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

You can run with:

java -cp .;app.jar package.MainClass

It works for me if there is no manifest in the JAR file.

Hiding elements in responsive layout?

Additional CSS Remove Sidebar from all pages in Mobile view:

@media only screen and (max-width:767px)
{
#secondary {
display: none;
}
}

Building executable jar with maven?

The answer of Pascal Thivent helped me out, too. But if you manage your plugins within the <pluginManagement>element, you have to define the assembly again outside of the plugin management, or else the dependencies are not packed in the jar if you run mvn install.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>jar</packaging>


    <build>
        <pluginManagement>
            <plugins>

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.1</version>
                    <configuration>
                        <source>1.6</source>
                        <target>1.6</target>
                    </configuration>
                </plugin>

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-assembly-plugin</artifactId>
                    <version>2.4</version>
                    <configuration>
                        <archive>
                            <manifest>
                                <mainClass>main.App</mainClass>
                            </manifest>
                        </archive>
                        <descriptorRefs>
                            <descriptorRef>jar-with-dependencies</descriptorRef>
                        </descriptorRefs>
                    </configuration>
                    <executions>
                        <execution>
                            <id>make-assembly</id>
                            <phase>package</phase>
                            <goals>
                                <goal>single</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>

            </plugins>

        </pluginManagement>

        <plugins> <!-- did NOT work without this  -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
            </plugin>
        </plugins>

    </build>


    <dependencies>
       <!--  dependencies commented out to shorten example -->
    </dependencies>

</project>

Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '='

The default collation for stored procedure parameters is utf8_general_ci and you can't mix collations, so you have four options:

Option 1: add COLLATE to your input variable:

SET @rUsername = ‘aname’ COLLATE utf8_unicode_ci; -- COLLATE added
CALL updateProductUsers(@rUsername, @rProductID, @rPerm);

Option 2: add COLLATE to the WHERE clause:

CREATE PROCEDURE updateProductUsers(
    IN rUsername VARCHAR(24),
    IN rProductID INT UNSIGNED,
    IN rPerm VARCHAR(16))
BEGIN
    UPDATE productUsers
        INNER JOIN users
        ON productUsers.userID = users.userID
        SET productUsers.permission = rPerm
        WHERE users.username = rUsername COLLATE utf8_unicode_ci -- COLLATE added
        AND productUsers.productID = rProductID;
END

Option 3: add it to the IN parameter definition:

CREATE PROCEDURE updateProductUsers(
    IN rUsername VARCHAR(24) COLLATE utf8_unicode_ci, -- COLLATE added
    IN rProductID INT UNSIGNED,
    IN rPerm VARCHAR(16))
BEGIN
    UPDATE productUsers
        INNER JOIN users
        ON productUsers.userID = users.userID
        SET productUsers.permission = rPerm
        WHERE users.username = rUsername
        AND productUsers.productID = rProductID;
END

Option 4: alter the field itself:

ALTER TABLE users CHARACTER SET utf8 COLLATE utf8_general_ci;

Unless you need to sort data in Unicode order, I would suggest altering all your tables to use utf8_general_ci collation, as it requires no code changes, and will speed sorts up slightly.

UPDATE: utf8mb4/utf8mb4_unicode_ci is now the preferred character set/collation method. utf8_general_ci is advised against, as the performance improvement is negligible. See https://stackoverflow.com/a/766996/1432614

Install-Module : The term 'Install-Module' is not recognized as the name of a cmdlet

I have Windows 10 and PowerShell 5.1 was already installed. For whatever reason the x86 version works and can find "Install-Module", but the other version cannot.

Search your Start Menu for "powershell", and find the entry that ends in "(x86)":

Windows 10 Start Menu searching for PowerShell

Here is what I experience between the two different versions:

PowerShell x86 vs x64 running Install-Module cmdlet comparison

C++ Matrix Class

You could use a template like :

#include <iostream>
using std::cerr;
using std::endl;

//qt4type
typedef unsigned int quint32;

template <typename T>
void deletep(T &) {}
template <typename T>
void deletep(T* & ptr) {
    delete ptr;
    ptr = 0;
}
template<typename T>
class Matrix {
    public:
        typedef T value_type;
        Matrix() : _cols(0), _rows(0), _data(new T[0]), auto_delete(true) {};
        Matrix(quint32 rows, quint32 cols, bool auto_del = true);

        bool exists(quint32 row, quint32 col) const;
        T & operator()(quint32 row, quint32 col);
        T operator()(quint32 row, quint32 col) const;
        virtual ~Matrix();

        int size() const { return _rows * _cols; }
        int rows() const { return _rows; }
        int cols() const { return _cols; }
    private:
        Matrix(const Matrix &);
        quint32 _rows, _cols;
        mutable T * _data;
        const bool auto_delete;
};
template<typename T>
Matrix<T>::Matrix(quint32 rows, quint32 cols, bool auto_del) : _rows(rows), _cols(cols), auto_delete(auto_del) {
    _data = new T[rows * cols];
}
template<typename T>
inline T & Matrix<T>::operator()(quint32 row, quint32 col) {
    return _data[_cols * row + col];
}
template<typename T>
inline T Matrix<T>::operator()(quint32 row, quint32 col) const {
    return _data[_cols * row + col];
}

template<typename T>
bool Matrix<T>::exists(quint32 row, quint32 col) const {
    return (row < _rows && col < _cols);
}

template<typename T>
Matrix<T>::~Matrix() {
    if(auto_delete){
        for(int i = 0, c = size(); i < c; ++i){
            //will do nothing if T isn't a pointer
            deletep(_data[i]);
        }
    }
    delete [] _data;
}

int main() {
    Matrix< int > m(10,10);
    quint32 i = 0;
    for(int x = 0; x < 10; ++x) {
        for(int y = 0; y < 10; ++y, ++i) {
            m(x, y) = i;
        }
    }
    for(int x = 0; x < 10; ++x) {
        for(int y = 0; y < 10; ++y) {
            cerr << "@(" << x << ", " << y << ") : " << m(x,y) << endl;
        }
    }
}

*edit, fixed a typo.

Get parent of current directory from Python script

import os
import sys
from os.path import dirname, abspath

d = dirname(dirname(abspath(__file__)))
print(d)
path1 = os.path.dirname(os.path.realpath(sys.argv[0]))
print(path1)
path = os.path.split(os.path.realpath(__file__))[0]
print(path)

How to prevent scrollbar from repositioning web page?

html {
  overflow-x: hidden;
  margin-right: calc(-1 * (100vw - 100%));
}

Example. Click "change min-height" button.

With calc(100vw - 100%) we can calculate the width of the scrollbar (and if it is not displayed, it will be 0). Idea: using negative margin-right, we can increase the width of <html> to this width. You will see a horizontal scroll bar — it should be hidden using overflow-x: hidden.

How to use Tomcat 8 in Eclipse?

Downloaded Eclipse Luna and installed WTP using http://download.eclipse.org/webtools/repository/luna

Downloaded Tomcat 8 and configured new server in Eclipse. I am able to setup tomcat 8 now in Eclipse luna

What does 'low in coupling and high in cohesion' mean

Inheritance or generalization is an example of high coupling (i.e. high interdependence). What I meant by this is that in inheritance often the parent class defines base functionalities that is used by its child class and change in methods of parent class directly impact its child classes. Hence we can say that there is a greater degree of interdependence between classes.

Realization or using interface is an example of high cohesion (i.e. low interdependence). What this means is that an interface put forward a contract for any class that implements it but each class has the right to implement methods declared in interface in its own way and changes in method declared in one class doesn't affect any other class.

How to subtract a day from a date?

Also just another nice function i like to use when i want to compute i.e. first/last day of the last month or other relative timedeltas etc. ...

The relativedelta function from dateutil function (a powerful extension to the datetime lib)

import datetime as dt
from dateutil.relativedelta import relativedelta
#get first and last day of this and last month)
today = dt.date.today()
first_day_this_month = dt.date(day=1, month=today.month, year=today.year)
last_day_last_month = first_day_this_month - relativedelta(days=1)
print (first_day_this_month, last_day_last_month)

>2015-03-01 2015-02-28

What's the easiest way to call a function every 5 seconds in jQuery?

A good example where to subscribe a setInterval(), and use a clearInterval() to stop the forever loop:

function myTimer() {
    console.log(' each 1 second...');
}

var myVar = setInterval(myTimer, 1000);

call this line to stop the loop:

 clearInterval(myVar);

A generic error occurred in GDI+, JPEG Image to MemoryStream

I found that if one of the parent folders where I was saving the file had a trailing space then GDI+ would throw the generic exception.

In other words, if I tried to save to "C:\Documents and Settings\myusername\Local Settings\Temp\ABC DEF M1 Trended Values \Images\picture.png" then it threw the generic exception.

My folder name was being generated from a file name that happened to have a trailing space so it was easy to .Trim() that and move on.

Android Studio cannot resolve R in imported project?

Had this error when importing project from Eclipse. The reason was some of the xml files had errors. Check ALL your XML files for errors. Including androidmanifest.xml, and values, themes, styles, layouts folders, etc. Warnings in xml are ok, but errors will generate this error.

Afterwards, do a Clean Project and rebuild.

Pure JavaScript Send POST Data Without a Form

const data = { username: 'example' };

fetch('https://example.com/profile', {
  method: 'POST', // or 'PUT'
  headers: {
 '           Content-Type': 'application/json',
           },
  body: JSON.stringify(data),
})
  .then(response => response.json())
  .then(data => {
      console.log('Success:', data);
     })
 .catch((error) => {
         console.error('Error:', error);
   });

Div Size Automatically size of content

If you are coming here, there is high chance width: min-content or width: max-content can fix your problem. This can force an element to use the smallest or largest space the browser could choose…

This is the modern solution. Here is a small tutorial for that.

There is also fit-content, which often works like min-content, but is more flexible. (But also has worse browser support.)

This is a quite new feature and some browsers do not support it yet, but browser support is growing. See the current browser status here.

error: Error parsing XML: not well-formed (invalid token) ...?

Verify that you don't have any spaces or tabs before

<?xml version="1.0" encoding="utf-8"?>

also refresh and clean your project in eclipse.

I get this error every now and then and the above suggestions fix the issue 99% of the time

Deserializing a JSON file with JavaScriptSerializer()

  1. You need to create a class that holds the user values, just like the response class User.
  2. Add a property to the Response class 'user' with the type of the new class for the user values User.

    public class Response {
    
        public string id { get; set; }
        public string text { get; set; }
        public string url { get; set; }
        public string width { get; set; }
        public string height { get; set; }
        public string size { get; set; }
        public string type { get; set; }
        public string timestamp { get; set; }
        public User user { get; set; }
    
    }
    
    public class User {
    
        public int id { get; set; }
        public string screen_name { get; set; }
    
    }
    

In general you should make sure the property types of the json and your CLR classes match up. It seems that the structure that you're trying to deserialize contains multiple number values (most likely int). I'm not sure if the JavaScriptSerializer is able to deserialize numbers into string fields automatically, but you should try to match your CLR type as close to the actual data as possible anyway.

How to create <input type=“text”/> dynamically

<button id="add" onclick="add()">Add Element</button>

<div id="hostI"></div>

<template id="templateInput">
    <input type="text">
</template>

<script>
    function add() {

        // Using Template, element is created
        var templateInput = document.querySelector('#templateInput');
        var clone = document.importNode(templateInput.content, true);

        // The Element is added to document
        var hostI = document.querySelector('#hostI');
        hostI.appendChild(clone);
    }

</script>

HTML Templates are now the recommended standards to generate dynamic content.

How to send a HTTP OPTIONS request from the command line?

The curl installed by default in Debian supports HTTPS since a great while back. (a long time ago there were two separate packages, one with and one without SSL but that's not the case anymore)

OPTIONS /path

You can send an OPTIONS request with curl like this:

curl -i -X OPTIONS http://example.org/path

You may also use -v instead of -i to see more output.

OPTIONS *

To send a plain * (instead of the path, see RFC 7231) with the OPTIONS method, you need curl 7.55.0 or later as then you can run a command line like:

curl -i --request-target "*" -X OPTIONS http://example.org

Disabling enter key for form

Just add following code in <Head> Tag in your HTML Code. It will Form submission on Enter Key For all fields on form.

<script type="text/javascript">
    function stopEnterKey(evt) {
        var evt = (evt) ? evt : ((event) ? event : null);
        var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
        if ((evt.keyCode == 13) && (node.type == "text")) { return false; }
    }
    document.onkeypress = stopEnterKey;
</script>

angular 2 how to return data from subscribe

I have used this way lots time ...

_x000D_
_x000D_
@Component({_x000D_
   selector: "data",_x000D_
   template: "<h1>{{ getData() }}</h1>"_x000D_
})_x000D_
_x000D_
export class DataComponent{_x000D_
    this.http.get(path).subscribe({_x000D_
       DataComponent.setSubscribeData(res);_x000D_
    })_x000D_
}_x000D_
_x000D_
_x000D_
static subscribeData:any;_x000D_
static setSubscribeData(data):any{_x000D_
    DataComponent.subscribeData=data;_x000D_
    return data;_x000D_
}
_x000D_
_x000D_
_x000D_

use static keyword and save your time... here either you can use static variable or directly return object you want.... hope it will help you.. happy coding...

Do Facebook Oauth 2.0 Access Tokens Expire?

I came here with the same question as the OP, but the answers suggesting the use of offline_access are raising red flags for me.

Security-wise, getting offline access to a user's Facebook account is qualitatively different and far more powerful than just using Facebook for single sign on, and should not be used lightly (unless you really need it). When a user grants this permission, "the application" can examine the user's account from anywhere at any time. I put "the application" in quotes because it's actually any tool that has the credentials -- you could script up a whole suite of tools that have nothing to do with the web server that can access whatever info the user has agreed to share to those credentials.

I would not use this feature to work around a short token lifetime; that's not its intended purpose. Indeed, token lifetime itself is a security feature. I'm still looking for details about the proper usage of these tokens (Can I persist them? How do/should I secure them? Does Facebook embed the OAuth 2.0 "refresh token" inside the main one? If not, where is it and/or how do I refresh?), but I'm pretty sure offline_access isn't the right way.

Kotlin: How to get and set a text to TextView in Android using Kotlin?

  <TextView
        android:id="@+id/usage"
        android:layout_marginTop="220dip"
        android:layout_marginLeft="45dip"
        android:layout_marginRight="15dip"
        android:typeface="serif"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Google "
        android:textColor="#030900"/>


usage.text="hello world"

How to extract img src, title and alt from html using php?

Just to give a small example of using PHP's XML functionality for the task:

$doc=new DOMDocument();
$doc->loadHTML("<html><body>Test<br><img src=\"myimage.jpg\" title=\"title\" alt=\"alt\"></body></html>");
$xml=simplexml_import_dom($doc); // just to make xpath more simple
$images=$xml->xpath('//img');
foreach ($images as $img) {
    echo $img['src'] . ' ' . $img['alt'] . ' ' . $img['title'];
}

I did use the DOMDocument::loadHTML() method because this method can cope with HTML-syntax and does not force the input document to be XHTML. Strictly speaking the conversion to a SimpleXMLElement is not necessary - it just makes using xpath and the xpath results more simple.

jQuery UI 1.10: dialog and zIndex option

To sandwich an my element between the modal screen and a dialog, I need to lift my element above the modal-screen, and then lift the dialog above my element.

I had a small success by doing the following after creating the dialog on element $dlg.

$dlg.closest('.ui-dialog').css('zIndex',adjustment);

Since each dialog has a different starting z-index (they incrementally get larger) I make adjustment a string with a boost value, like this:

const adjustment = "+=99";

However, jQuery just keeps increasing the zIndex value on the modal screen, so by the second dialog, the sandwich no longer worked. I gave up on ui-dialog "modal", made it "false", and just created my own modal. It imitates jQueryUI exactly. Here it is:

CoverAll = {};
CoverAll.modalDiv = null;

CoverAll.modalCloak = function(zIndex) {
  var div = CoverAll.modalDiv;
  if(!CoverAll.modalDiv) {
    div = CoverAll.modalDiv = document.createElement('div');
    div.style.background = '#aaaaaa';
    div.style.opacity    = '0.3';
    div.style.position   = 'fixed';
    div.style.top        = '0';
    div.style.left       = '0';
    div.style.width      = '100%';
    div.style.height     = '100%';
  }
  if(!div.parentElement) {
    document.body.appendChild(div);
  }
  if(zIndex == null)
    zIndex = 100;
  div.style.zIndex  = zIndex;
  return div;
}

CoverAll.modalUncloak = function() {
  var div = CoverAll.modalDiv;
  if(div && div.parentElement) {
    document.body.removeChild(div);
  }
  return div;
}

Difference between static class and singleton pattern?

Here's a good article: http://javarevisited.blogspot.com.au/2013/03/difference-between-singleton-pattern-vs-static-class-java.html

Static classes

  • a class having all static methods.
  • better performance (static methods are bonded on compile time)
  • can't override methods, but can use method hiding. (What is method hiding in Java? Even the JavaDoc explanation is confusing)

    public class Animal {
        public static void foo() {
            System.out.println("Animal");
        }
    }
    
    public class Cat extends Animal {
        public static void foo() {  // hides Animal.foo()
            System.out.println("Cat");
        }
    }
    

Singleton

In summary, I would only use static classes for holding util methods, and using Singleton for everything else.


Edits

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

For those who have no errors in Debug mode, but do have the specified error in Release mode (and yet the project runs fine), here is something simple to try:

  1. Open the XAML file corresponding to the offending xaml.cs file.
  2. Make an edit--any edit, like add a space somewhere
  3. Save the file and close it

This method worked for me in VS 2015, and according to other users, also 2017 and 2019

.bashrc: Permission denied

The .bashrc file is in your user home directory (~/.bashrc or ~vagrant/.bashrc both resolve to the same path), inside the VM's filesystem. This file is invisible on the host machine, so you can't use any Windows editors to edit it directly.

You have two simple choices:

  1. Learn how to use a console-based text editor. My favourite is vi (or vim), which takes 15 minutes to learn the basics and is much quicker for simple edits than anything else.

    vi .bashrc

  2. Copy .bashrc out to /vagrant (which is a shared directory) and edit it using your Windows editors. Make sure not to save it back with any extensions.

    cp .bashrc /vagrant ... edit using your host machine ... cp /vagrant/.bashrc .

I'd recommend getting to know the command-line based editors. Once you're working inside the VM, it's best to stay there as otherwise you might just get confused.

You (the vagrant user) are the owner of your home .bashrc so you do have permissions to edit it.

Once edited, you can execute it by typing source .bashrc I prefer to logout and in again (there may be more than one file executed on login).

Difference between JSON.stringify and JSON.parse

They are opposing each other. JSON.Stringify() converts JSON to string and JSON.Parse() parses a string into JSON.

How to use Google App Engine with my own naked domain (not subdomain)?

Here is a tutorial from Google about mapping your App on custom domain: https://cloud.google.com/appengine/docs/domain?hl=FR

It should be the latest update. But please note these 2 things:

1- You may not find you App in the new developer console, then the only workaround for that is download your source code, create a new app from the new developer console and deploy it.

2- You find your App on the developer console, but under the Compute menu you may not find the App Engine Settings as mentioned in the tutorial, then you have to proceed the same as i explained in the first point (create another application)

I hope this helps !

C# declare empty string array

You can try this

string[] arr = {};

How to find time complexity of an algorithm

Taken from here - Introduction to Time Complexity of an Algorithm

1. Introduction

In computer science, the time complexity of an algorithm quantifies the amount of time taken by an algorithm to run as a function of the length of the string representing the input.

2. Big O notation

The time complexity of an algorithm is commonly expressed using big O notation, which excludes coefficients and lower order terms. When expressed this way, the time complexity is said to be described asymptotically, i.e., as the input size goes to infinity.

For example, if the time required by an algorithm on all inputs of size n is at most 5n3 + 3n, the asymptotic time complexity is O(n3). More on that later.

Few more Examples:

  • 1 = O(n)
  • n = O(n2)
  • log(n) = O(n)
  • 2 n + 1 = O(n)

3. O(1) Constant Time:

An algorithm is said to run in constant time if it requires the same amount of time regardless of the input size.

Examples:

  • array: accessing any element
  • fixed-size stack: push and pop methods
  • fixed-size queue: enqueue and dequeue methods

4. O(n) Linear Time

An algorithm is said to run in linear time if its time execution is directly proportional to the input size, i.e. time grows linearly as input size increases.

Consider the following examples, below I am linearly searching for an element, this has a time complexity of O(n).

int find = 66;
var numbers = new int[] { 33, 435, 36, 37, 43, 45, 66, 656, 2232 };
for (int i = 0; i < numbers.Length - 1; i++)
{
    if(find == numbers[i])
    {
        return;
    }
}

More Examples:

  • Array: Linear Search, Traversing, Find minimum etc
  • ArrayList: contains method
  • Queue: contains method

5. O(log n) Logarithmic Time:

An algorithm is said to run in logarithmic time if its time execution is proportional to the logarithm of the input size.

Example: Binary Search

Recall the "twenty questions" game - the task is to guess the value of a hidden number in an interval. Each time you make a guess, you are told whether your guess is too high or too low. Twenty questions game implies a strategy that uses your guess number to halve the interval size. This is an example of the general problem-solving method known as binary search

6. O(n2) Quadratic Time

An algorithm is said to run in quadratic time if its time execution is proportional to the square of the input size.

Examples:

7. Some Useful links

Storing Images in DB - Yea or Nay?

As with most issues, it's not as simple as it sounds. There are cases where it would make sense to store the images in the database.

  • You are storing images that are changing dynamically, say invoices and you wanted to get an invoice as it was on 1 Jan 2007?
  • The government wants you to maintain 6 years of history
  • Images stored in the database do not require a different backup strategy. Images stored on filesystem do
  • It is easier to control access to the images if they are in a database. Idle admins can access any folder on disk. It takes a really determined admin to go snooping in a database to extract the images

On the other hand there are problems associated

  • Require additional code to extract and stream the images
  • Latency may be slower than direct file access
  • Heavier load on the database server

How to hide a div element depending on Model value? MVC

Try:

<div style="@(Model.booleanVariable ? "display:block" : "display:none")">Some links</div>

Use the "Display" style attribute with your bool model attribute to define the div's visibility.

How to open a different activity on recyclerView item onclick

public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private ArrayList<Android> android;
Context context;
private ImageView img;
public DataAdapter(Context contextN, ArrayList<Android> android) {
    this.android = android;
    this.context=contextN;
}

@Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.adapter_list, viewGroup, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(DataAdapter.ViewHolder viewHolder, int i) {

    viewHolder.tv_name.setText(android.get(i).getOffer());
    viewHolder.tv_version.setText(android.get(i).getOfferType());
    Picasso.with(context).load(android.get(i).getImg()).transform(new CircleTransform()).into(img);

}

@Override
public int getItemCount() {
    return android.size();
}

public class ViewHolder extends RecyclerView.ViewHolder{
    private TextView tv_name,tv_version,tv_api_level;

    public ViewHolder(View view) {
        super(view);

        tv_name = (TextView)view.findViewById(R.id.tv_name);
        tv_version = (TextView)view.findViewById(R.id.tv_version);
        img = (ImageView) view.findViewById(R.id.img);

                context = itemView.getContext();

                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        int itemPosition = getLayoutPosition();
                        Toast.makeText(context, "" + itemPosition, Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(context,Show.class);
                        intent.putExtra("name",""+android.get(itemPosition).getOffer());
                        intent.putExtra("img",""+android.get(itemPosition).getImg());
                        context.startActivity(intent);

            }
        });
    }
}
}

What is the best way to paginate results in SQL Server

This bit gives you ability to paginate using SQL Server, and newer versions of MySQL and carries the total number of rows in every row. Uses your pimary key to count number of unique rows.

WITH T AS
(  
  SELECT TABLE_ID, ROW_NUMBER() OVER (ORDER BY TABLE_ID) AS RN
  , (SELECT COUNT(TABLE_ID) FROM TABLE) AS TOTAL 
  FROM TABLE (NOLOCK)
)

SELECT T2.FIELD1, T2.FIELD2, T2.FIELD3, T.TOTAL 
FROM TABLE T2 (NOLOCK)
INNER JOIN T ON T2.TABLE_ID=T.TABLE_ID
WHERE T.RN >= 100
AND T.RN < 200

What is a provisioning profile used for when developing iPhone applications?

Apple cares about security and as you know it is not possible to install any application on a real iOS device. Apple has several legal ways to do it:

  • When you need to test/debug an app on a real device the Development Provisioning Profile allows you to do it
  • When you publish an app you send a Distribution Provisioning Profile[About] and Apple after review reassign it by they own key

Development Provisioning Profile is stored on device and contains:

  • Application ID - application which are going to run
  • List of Development certificates - who can debug the app
  • List of devices - which devices can run this app

Xcode by default take cares about

Create a HTML table where each TR is a FORM

You may have issues with column width, but you can set those explicitly.

<table>
  <tr>
    <td>
       <form>
         <table>
           <tr>
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
           </tr>
         </table>
       </form>
     </td>
    </tr>
  <tr>
    <td>
       <form>
         <table>
           <tr>
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
           </tr>
         </table>
       </form>
     </td>
    </tr>
  </table>

You may want to also consider making it a single form, and then using jQuery to select the form elements from the row you want, serialize them, and submit them as the form.

See: http://api.jquery.com/serialize/

Also, there are a number of very nice grid plugins: http://www.google.com/search?q=jquery+grid&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a

Error "File google-services.json is missing from module root folder. The Google Services Plugin cannot function without it"

You must go on Firebase console-->Settings-->Project Settings and there will be section with Download the latest config file. Download google-service.json and put into app folder. It's work for me. Links: https://developers.google.com/identity/sign-in/android/start-integrating https://developers.google.com/android/guides/client-auth

dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac

For me brew reinstall nodejs fixed this - my issue was with running Elixir/Phoenix so not PHP specific, I think it was caused by brew install postgres, but reinstalling that didn't help. I was getting it from npm commands.

What is AF_INET, and why do I need it?

it defines the protocols address family.this determines the type of socket created. pocket pc support AF_INET.

the content in the following page is quite decent http://etutorials.org/Programming/Pocket+pc+network+programming/Chapter+1.+Winsock/Streaming+TCP+Sockets/

What is a magic number, and why is it bad?

A magic number is a direct usage of a number in the code.

For example, if you have (in Java):

public class Foo {
    public void setPassword(String password) {
         // don't do this
         if (password.length() > 7) {
              throw new InvalidArgumentException("password");
         }
    }
}

This should be refactored to:

public class Foo {
    public static final int MAX_PASSWORD_SIZE = 7;

    public void setPassword(String password) {
         if (password.length() > MAX_PASSWORD_SIZE) {
              throw new InvalidArgumentException("password");
         }
    }
}

It improves readability of the code and it's easier to maintain. Imagine the case where I set the size of the password field in the GUI. If I use a magic number, whenever the max size changes, I have to change in two code locations. If I forget one, this will lead to inconsistencies.

The JDK is full of examples like in Integer, Character and Math classes.

PS: Static analysis tools like FindBugs and PMD detects the use of magic numbers in your code and suggests the refactoring.

Image resizing client-side with JavaScript before upload to the server

Here's a gist which does this: https://gist.github.com/dcollien/312bce1270a5f511bf4a

(an es6 version, and a .js version which can be included in a script tag)

You can use it as follows:

<input type="file" id="select">
<img id="preview">
<script>
document.getElementById('select').onchange = function(evt) {
    ImageTools.resize(this.files[0], {
        width: 320, // maximum width
        height: 240 // maximum height
    }, function(blob, didItResize) {
        // didItResize will be true if it managed to resize it, otherwise false (and will return the original file as 'blob')
        document.getElementById('preview').src = window.URL.createObjectURL(blob);
        // you can also now upload this blob using an XHR.
    });
};
</script>

It includes a bunch of support detection and polyfills to make sure it works on as many browsers as I could manage.

(it also ignores gif images - in case they're animated)

Dynamically add child components in React

Firstly a warning: you should never tinker with DOM that is managed by React, which you are doing by calling ReactDOM.render(<SampleComponent ... />);

With React, you should use SampleComponent directly in the main App.

var App = require('./App.js');
var SampleComponent = require('./SampleComponent.js');
ReactDOM.render(<App/>, document.body);

The content of your Component is irrelevant, but it should be used like this:

var App = React.createClass({
    render: function() {
        return (
            <div>
                <h1>App main component! </h1>
                <SampleComponent name="SomeName"/>
            </div>
        );
    }
});

You can then extend your app component to use a list.

var App = React.createClass({
    render: function() {
        var componentList = [
            <SampleComponent name="SomeName1"/>,
            <SampleComponent name="SomeName2"/>
        ]; // Change this to get the list from props or state
        return (
            <div>
                <h1>App main component! </h1>
                {componentList}
            </div>
        );
    }
});

I would really recommend that you look at the React documentation then follow the "Get Started" instructions. The time you spend on that will pay off later.

https://facebook.github.io/react/index.html

Giving height to table and row in Bootstrap

The simple solution that worked for me as below, wrap the table with a div and change the line-height, this line-height is taken as a ratio.

_x000D_
_x000D_
<div class="col-md-6" style="line-height: 0.5">_x000D_
                                <table class="table table-striped" >_x000D_
                                    <thead>_x000D_
                                    <tr>_x000D_
                                        <th>Parameter</th>_x000D_
                                        <th>Recorded Value</th>_x000D_
                                        <th>Individual Score</th>_x000D_
                                    </tr>_x000D_
                                    </thead>_x000D_
                                    <tbody>_x000D_
                                    <tr>_x000D_
                                        <td>Respiratory Rate</td>_x000D_
                                        <td>Doe</td>_x000D_
                                        <td>[email protected]</td>_x000D_
                                    </tr>_x000D_
                                    <tr>_x000D_
                                        <td>Respiratory Effort</td>_x000D_
                                        <td>Moe</td>_x000D_
                                        <td>[email protected]</td>_x000D_
                                    </tr>_x000D_
                                    <tr>_x000D_
                                        <td>Oxygon Saturation</td>_x000D_
                                        <td>Dooley</td>_x000D_
                                        <td>[email protected]</td>_x000D_
                                    </tr>_x000D_
                                    </tbody>_x000D_
                                </table>_x000D_
                            </div>
_x000D_
_x000D_
_x000D_

Try changing the value as it fits for you.

Finding last occurrence of substring in string, replacing that

a = "A long string with a . in the middle ending with ."

# if you want to find the index of the last occurrence of any string, In our case we #will find the index of the last occurrence of with

index = a.rfind("with") 

# the result will be 44, as index starts from 0.

Number of days between two dates in Joda-Time

Annoyingly, the withTimeAtStartOfDay answer is wrong, but only occasionally. You want:

Days.daysBetween(start.toLocalDate(), end.toLocalDate()).getDays()

It turns out that "midnight/start of day" sometimes means 1am (daylight savings happen this way in some places), which Days.daysBetween doesn't handle properly.

// 5am on the 20th to 1pm on the 21st, October 2013, Brazil
DateTimeZone BRAZIL = DateTimeZone.forID("America/Sao_Paulo");
DateTime start = new DateTime(2013, 10, 20, 5, 0, 0, BRAZIL);
DateTime end = new DateTime(2013, 10, 21, 13, 0, 0, BRAZIL);
System.out.println(daysBetween(start.withTimeAtStartOfDay(),
                               end.withTimeAtStartOfDay()).getDays());
// prints 0
System.out.println(daysBetween(start.toLocalDate(),
                               end.toLocalDate()).getDays());
// prints 1

Going via a LocalDate sidesteps the whole issue.

Create a global variable in TypeScript

This is how I have fixed it:

Steps:

  1. Declared a global namespace, for e.g. custom.d.ts as below :
declare global {
    namespace NodeJS {
        interface Global {
            Config: {}
        }
    }
}
export default global;
  1. Map the above created a file into "tsconfig.json" as below:
"typeRoots": ["src/types/custom.d.ts" ]
  1. Get the above created global variable in any of the files as below:
console.log(global.config)

Note:

  1. typescript version: "3.0.1".

  2. In my case, the requirement was to set the global variable before boots up the application and the variable should access throughout the dependent objects so that we can get the required config properties.

Hope this helps!

Thank you

Change background color of selected item on a ListView

I'm also doing the similar thing: highlight the selected list item's background (change it to red) and set text color within the item to white.

I can think out a "simple but not efficient" way: maintain a selected item's position in the custom adapter, and change it in the ListView's OnItemClickListener implement:

// The OnItemClickListener implementation
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    mListViewAdapter.setSelectedItem(position);
}

// The custom Adapter
private int mSelectedPosition = -1;
public void setSelectedItem (int itemPosition) {
    mSelectedPosition = itemPosition;
    notifyDataSetChanged();
}

Then update the selected item's background and text color in getView() method.

// The custom Adapter
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ...
    if (position == mSelectedPosition) {
        // customize the selected item's background and sub views
        convertView.setBackgroundColor(YOUR_HIGHLIGHT_COLOR);
        textView.setTextColor(TEXT_COLOR);
    } else {
        ...
    }
}

After searching for a while, I found that many people mentioned about to set android:listSelector="YOUR_SELECTOR". After tried for a while, I found the simplest way to highlight selected ListView item's background can be done with only two lines set to the ListView's layout resource:

android:choiceMode="singleChoice"
android:listSelector="YOUR_COLOR"

There's also other way to make it work, like customize activatedBackgroundIndicator theme. But I think that would be a much more generic solution since it will affect the whole theme.

Android: where are downloaded files saved?

Most devices have some form of emulated storage. if they support sd cards they are usually mounted to /sdcard (or some variation of that name) which is usually symlinked to to a directory in /storage like /storage/sdcard0 or /storage/0 sometimes the emulated storage is mounted to /sdcard and the actual path is something like /storage/emulated/legacy. You should be able to use to get the downloads directory. You are best off using the api calls to get directories. Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

Since the filesystems and sdcard support varies among devices.

see similar question for more info how to access downloads folder in android?

Usually the DownloadManager handles downloads and the files are then accessed by requesting the file's uri fromthe download manager using a file id to get where file was places which would usually be somewhere in the sdcard/ real or emulated since apps can only read data from certain places on the filesystem outside of their data directory like the sdcard

MongoDB "root" user

"userAdmin is effectively the superuser role for a specific database. Users with userAdmin can grant themselves all privileges. However, userAdmin does not explicitly authorize a user for any privileges beyond user administration." from the link you posted

How to vertically center content with variable height within a div?

For me the best way to do this is:

.container{
  position: relative;
}

.element{
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

The advantage is not having to make the height explicit

PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?

This is a verbose translation of what Symfony uses to get the host name (see the second example for a more literal translation):

function getHost() {
    $possibleHostSources = array('HTTP_X_FORWARDED_HOST', 'HTTP_HOST', 'SERVER_NAME', 'SERVER_ADDR');
    $sourceTransformations = array(
        "HTTP_X_FORWARDED_HOST" => function($value) {
            $elements = explode(',', $value);
            return trim(end($elements));
        }
    );
    $host = '';
    foreach ($possibleHostSources as $source)
    {
        if (!empty($host)) break;
        if (empty($_SERVER[$source])) continue;
        $host = $_SERVER[$source];
        if (array_key_exists($source, $sourceTransformations))
        {
            $host = $sourceTransformations[$source]($host);
        } 
    }

    // Remove port number from host
    $host = preg_replace('/:\d+$/', '', $host);

    return trim($host);
}

Outdated:

This is my translation to bare PHP of a method used in Symfony framework that tries to get the hostname from every way possible in order of best practice:

function get_host() {
    if ($host = $_SERVER['HTTP_X_FORWARDED_HOST'])
    {
        $elements = explode(',', $host);

        $host = trim(end($elements));
    }
    else
    {
        if (!$host = $_SERVER['HTTP_HOST'])
        {
            if (!$host = $_SERVER['SERVER_NAME'])
            {
                $host = !empty($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : '';
            }
        }
    }

    // Remove port number from host
    $host = preg_replace('/:\d+$/', '', $host);

    return trim($host);
}

jQuery UI - Close Dialog When Clicked Outside

This question is a bit old, but in case someone wants to close a dialog that is NOT modal when user clicks somewhere, you can use this that I took from the JQuery UI Multiselect plugin. The main advantage is that the click is not "lost" (if user wants to click on a link or a button, the action is done).

$myselector.dialog({
            title: "Dialog that closes when user clicks outside",
            modal:false,
            close: function(){
                        $(document).off('mousedown.mydialog');
                    },
            open: function(event, ui) { 
                    var $dialog = $(this).dialog('widget');
                    $(document).on('mousedown.mydialog', function(e) {
                        // Close when user clicks elsewhere
                        if($dialog.dialog('isOpen') && !$.contains($myselector.dialog('widget')[0], e.target)){
                            $myselector.dialog('close');
                        }            
                    });
                }                    
            });

How can I search Git branches for a file or directory?

Although ididak's response is pretty cool, and Handyman5 provides a script to use it, I found it a little restricted to use that approach.

Sometimes you need to search for something that can appear/disappear over time, so why not search against all commits? Besides that, sometimes you need a verbose response, and other times only commit matches. Here are two versions of those options. Put these scripts on your path:

git-find-file

for branch in $(git rev-list --all)
do
  if (git ls-tree -r --name-only $branch | grep --quiet "$1")
  then
     echo $branch
  fi
done

git-find-file-verbose

for branch in $(git rev-list --all)
do
  git ls-tree -r --name-only $branch | grep "$1" | sed 's/^/'$branch': /'
done

Now you can do

$ git find-file <regex>
sha1
sha2

$ git find-file-verbose <regex>
sha1: path/to/<regex>/searched
sha1: path/to/another/<regex>/in/same/sha
sha2: path/to/other/<regex>/in/other/sha

See that using getopt you can modify that script to alternate searching all commits, refs, refs/heads, been verbose, etc.

$ git find-file <regex>
$ git find-file --verbose <regex>
$ git find-file --verbose --decorated --color <regex>

Checkout https://github.com/albfan/git-find-file for a possible implementation.

How to update a value in a json file and save it through node.js

Doing this asynchronously is quite easy. It's particularly useful if you're concerned for blocking the thread (likely).

const fs = require('fs');
const fileName = './file.json';
const file = require(fileName);
    
file.key = "new value";
    
fs.writeFile(fileName, JSON.stringify(file), function writeJSON(err) {
  if (err) return console.log(err);
  console.log(JSON.stringify(file));
  console.log('writing to ' + fileName);
});

The caveat is that json is written to the file on one line and not prettified. ex:

{
  "key": "value"
}

will be...

{"key": "value"}

To avoid this, simply add these two extra arguments to JSON.stringify

JSON.stringify(file, null, 2)

null - represents the replacer function. (in this case we don't want to alter the process)

2 - represents the spaces to indent.

How can I clear or empty a StringBuilder?

If performance is the main concern then the irony, in my opinion, is the Java constructs to format the text that goes into the buffer, will be far more time consuming on the CPU than the allocation/reallocation/garbage collection ... well, possibly not the GC (garbage collection) depending on how many builders you create and discard.

But simply appending a compound string ("Hello World of " + 6E9 + " earthlings.") to the buffer is likely to make the whole matter inconsequential.

And, really, if an instance of StringBuilder is involved, then the content is complex and/or longer than a simple String str = "Hi"; (never mind that Java probably uses a builder in the background anyway).

Personally, I try not to abuse the GC. So if it's something that's going to be used a lot in a rapid fire scenario - like, say, writing debug output messages - I just assume declare it elsewhere and zero it out for reuse.

class MyLogger {
    StringBuilder strBldr = new StringBuilder(256);

    public void logMsg( String stuff, SomeLogWriterClass log ) {

        // zero out strBldr's internal index count, not every
        // index in strBldr's internal buffer
        strBldr.setLength(0);

        // ... append status level
        strBldr.append("Info");

        // ... append ' ' followed by timestamp
        // assuming getTimestamp() returns a String
        strBldr.append(' ').append(getTimestamp());

        // ... append ':' followed by user message
        strBldr.append(':').append(msg);

        log.write(strBldr.toString());
    }
}

Markdown to create pages and table of contents?

On Gitlab, markdown supports this : [[_TOC_]]

How to position the Button exactly in CSS

Try using absolute positioning, rather than relative positioning

this should get you close - you can adjust by tweaking margins or top/left positions

#play_button {
    position:absolute;
    transition: .5s ease;
    top: 50%;
    left: 50%;
}

http://jsfiddle.net/rolfsf/9pNqS/

Foreach in a Foreach in MVC View

Assuming your controller's action method is something like this:

public ActionResult AllCategories(int id = 0)
{
    return View(db.Categories.Include(p => p.Products).ToList());
}

Modify your models to be something like this:

public class Product
{
    [Key]
    public int ID { get; set; }
    public int CategoryID { get; set; }
    //new code
    public virtual Category Category { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string Path { get; set; }

    //remove code below
    //public virtual ICollection<Category> Categories { get; set; }
}

public class Category
{
    [Key]
    public int CategoryID { get; set; }
    public string Name { get; set; }
    //new code
    public virtual ICollection<Product> Products{ get; set; }
}

Then your since now the controller takes in a Category as Model (instead of a Product):

foreach (var category in Model)
{
    <h3><u>@category.Name</u></h3>
    <div>
        <ul>    
            @foreach (var product in Model.Products)
            {
                // cut for brevity, need to add back more code from original
                <li>@product.Title</li>
            }
        </ul>
    </div>
}

UPDATED: Add ToList() to the controller return statement.