Programs & Examples On #Appfabric

AppFabric is Microsoft's brand for its cloud computing products. It is split into two divisions: Azure AppFabric (in the cloud) and Windows Server AppFabric (on-premise).

AppFabric installation failed because installer MSI returned with error code : 1603

I finally made it. I was able to install AppFabric for Win Server 2012 R2. I am not really sure what exact change made it worked. I saw and tried many many solutions from various websites but above solution of making changes to Registry - 'HKEY_CLASSES_ROOT'worked (please think twice before making changes to Registry on production environment - this was my demo environment so I just went ahead); I changed the temporary folder path but it did not worked first time. Then I deleted the registry entry and then uninstalled AppFabric 1.1 pre-installed instance from Control panel. Then I tried Installation and it worked. This also restored the Registry entry.

Margin while printing html page

I'd personally suggest using a different unit of measurement than px. I don't think that pixels have much relevance in terms of print; ideally you'd use:

  • point (pt)
  • centimetre (cm)

I'm sure there are others, and one excellent article about print-css can be found here: Going to Print, by Eric Meyer.

Running script upon login mac

  1. Create your shell script as login.sh in your $HOME folder.

  2. Paste the following one-line script into Script Editor:

    do shell script "$HOME/login.sh"

  3. Then save it as an application.

  4. Finally add the application to your login items.

If you want to make the script output visual, you can swap step 2 for this:

tell application "Terminal"
  activate
  do script "$HOME/login.sh"
end tell

If multiple commands are needed something like this can be used:

tell application "Terminal"
  activate
  do script "cd $HOME"
  do script "./login.sh" in window 1
end tell

How to add SHA-1 to android application

If you are using Google Play App Signing, you don't need to add your SHA-1 keys manually, just login into Firebase go into "project settings"->"integration" and press a button to link Google Play with firebase, SHA-1 will be added automatically.

How to store printStackTrace into a string

You have to use getStackTrace () method instead of printStackTrace(). Here is a good example:

import java.io.*;

/**
* Simple utilities to return the stack trace of an
* exception as a String.
*/
public final class StackTraceUtil {

  public static String getStackTrace(Throwable aThrowable) {
    final Writer result = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(result);
    aThrowable.printStackTrace(printWriter);
    return result.toString();
  }

  /**
  * Defines a custom format for the stack trace as String.
  */
  public static String getCustomStackTrace(Throwable aThrowable) {
    //add the class name and any message passed to constructor
    final StringBuilder result = new StringBuilder( "BOO-BOO: " );
    result.append(aThrowable.toString());
    final String NEW_LINE = System.getProperty("line.separator");
    result.append(NEW_LINE);

    //add each element of the stack trace
    for (StackTraceElement element : aThrowable.getStackTrace() ){
      result.append( element );
      result.append( NEW_LINE );
    }
    return result.toString();
  }

  /** Demonstrate output.  */
  public static void main (String... aArguments){
    final Throwable throwable = new IllegalArgumentException("Blah");
    System.out.println( getStackTrace(throwable) );
    System.out.println( getCustomStackTrace(throwable) );
  }
} 

class method generates "TypeError: ... got multiple values for keyword argument ..."

just add 'staticmethod' decorator to function and problem is fixed

class foo(object):
    @staticmethod
    def foodo(thing=None, thong='not underwear'):
        print thing if thing else "nothing" 
        print 'a thong is',thong

Command not found error in Bash variable assignment

Drop the spaces around the = sign:

#!/bin/bash 
STR="Hello World" 
echo $STR 

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

Try below code,

$cookieFile = "cookies.txt";
if(!file_exists($cookieFile)) {
    $fh = fopen($cookieFile, "w");
    fwrite($fh, "");
    fclose($fh);
}


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiCall);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile); // Cookie aware
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile); // Cookie aware
curl_setopt($ch, CURLOPT_VERBOSE, true);
if(!curl_exec($ch)){
    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
}
else{
    $response = curl_exec($ch); 
}
curl_close($ch);
$result = json_decode($response, true);

echo '<pre>';
var_dump($result);
echo'</pre>';

I hope this will help you.

Best regards, Dasitha.

JQuery datepicker language

A quick Update, for the text "Today", the right names are:

todayText: 'Huidige', todayStatus: 'Bekijk de huidige maand',

Escaping quotation marks in PHP

Save your text not in a PHP file, but in an ordinary text file called, say, "text.txt"

Then with one simple $text1 = file_get_contents('text.txt'); command have your text with not a single problem.

How to find out when an Oracle table was updated the last time

Ask your DBA about auditing. He can start an audit with a simple command like :

AUDIT INSERT ON user.table

Then you can query the table USER_AUDIT_OBJECT to determine if there has been an insert on your table since the last export.

google for Oracle auditing for more info...

VBoxManage: error: Failed to create the host-only adapter

I faced this issue on mac.

I did the following Go to: Launcher->Virtualbox

Click the icon to open Virtualbox

Start Virtualbox with the button that pops up once Virtualbox starts. Wait till the terminal window gives you the prompt,

docker@boot2docker

Then try to open docker. Hope it works!

Finding out current index in EACH loop (Ruby)

x.each_with_index { |v, i| puts "current index...#{i}" }

How to create PDFs in an Android app?

A trick to make a PDF with complex features is to make a dummy activity with the desired xml layout. You can then open this dummy activity, take a screenshot programmatically and convert that image to pdf using this library. Of course there are limitations such as not being able to scroll, not more than one page,but for a limited application this is quick and easy. Hope this helps someone!

`require': no such file to load -- mkmf (LoadError)

I got the similar error when install bundle

sudo apt-get install ruby-dev

Works great for me and solve the problem Mint 16 ruby1.9.3

"Expected an indented block" error?

You have to indent the docstring after the function definition there (line 3, 4):

def print_lol(the_list):
"""this doesn't works"""
    print 'Ain't happening'

Indented:

def print_lol(the_list):
    """this works!"""
    print 'Aaaand it's happening'

Or you can use # to comment instead:

def print_lol(the_list):
#this works, too!
    print 'Hohoho'

Also, you can see PEP 257 about docstrings.

Hope this helps!

Best way to remove an event handler in jQuery?

I know this comes in late, but why not use plain JS to remove the event?

var myElement = document.getElementById("your_ID");
myElement.onclick = null;

or, if you use a named function as an event handler:

function eh(event){...}
var myElement = document.getElementById("your_ID");
myElement.addEventListener("click",eh); // add event handler
myElement.removeEventListener("click",eh); //remove it

Format Date as "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

function converToLocalTime(serverDate) {

    var dt = new Date(Date.parse(serverDate));
    var localDate = dt;
    
    var gmt = localDate;
        var min = gmt.getTime() / 1000 / 60; // convert gmt date to minutes
        var localNow = new Date().getTimezoneOffset(); // get the timezone
        // offset in minutes
        var localTime = min - localNow; // get the local time

    var dateStr = new Date(localTime * 1000 * 60);
    // dateStr = dateStr.toISOString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // this will return as just the server date format i.e., yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
    dateStr = dateStr.toString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    return dateStr;
}

Run Bash Command from PHP

Check if have not set a open_basedir in php.ini or .htaccess of domain what you use. That will jail you in directory of your domain and php will get only access to execute inside this directory.

Check if object exists in JavaScript

If that's a global object, you can use if (!window.maybeObject)

Which Java library provides base64 encoding/decoding?

If you're an Android developer you can use android.util.Base64 class for this purpose.

How do I use PHP namespaces with autoload?

I recently found tanerkuc's answer very helpful! Just wanted to add that using strrpos() + substr() is slightly faster than explode() + end():

spl_autoload_register( function( $class ) {
    $pos = strrpos( $class, '\\' );
    include ( $pos === false ? $class : substr( $class, $pos + 1 ) ).'.php';
});

How does paintComponent work?

Calling object.paintComponent(g) is an error.

Instead this method is called automatically when the panel is created. The paintComponent() method can also be called explicitly by the repaint() method defined in Component class.

The effect of calling repaint() is that Swing automatically clears the graphic on the panel and executes the paintComponent method to redraw the graphics on this panel.

Key existence check in HashMap

Just use containsKey() for clarity. It's fast and keeps the code clean and readable. The whole point of HashMaps is that the key lookup is fast, just make sure the hashCode() and equals() are properly implemented.

How to change 1 char in the string?

While it does not answer the OP's question precisely, depending on what you're doing it might be a good solution. Below is going to solve my problem.

Let's say that you have to do a lot of individual manipulation of various characters in a string. Instead of using a string the whole time use a char[] array while you're doing the manipulation. Because you can do this:

 char[] array = "valta is the best place in the World".ToCharArray();

Then manipulate to your hearts content as much as you need...

 array[0] = "M";

Then convert it to a string once you're done and need to use it as a string:

string str = new string(array);

TortoiseGit-git did not exit cleanly (exit code 1)

I ran into the same issue after upgrading Git. Turns out I switched from 32-bit to 64-bit Git and I didn't realize it. TortoiseGit was still looking for "C:\Program Files (x86)\Git\bin", which didn't exist. Right-click the folder, go to Tortoise Git > Settings > General and update the Git.exe path.

How do you add a JToken to an JObject?

I think you're getting confused about what can hold what in JSON.Net.

  • A JToken is a generic representation of a JSON value of any kind. It could be a string, object, array, property, etc.
  • A JProperty is a single JToken value paired with a name. It can only be added to a JObject, and its value cannot be another JProperty.
  • A JObject is a collection of JProperties. It cannot hold any other kind of JToken directly.

In your code, you are attempting to add a JObject (the one containing the "banana" data) to a JProperty ("orange") which already has a value (a JObject containing {"colour":"orange","size":"large"}). As you saw, this will result in an error.

What you really want to do is add a JProperty called "banana" to the JObject which contains the other fruit JProperties. Here is the revised code:

JObject foodJsonObj = JObject.Parse(jsonText);
JObject fruits = foodJsonObj["food"]["fruit"] as JObject;
fruits.Add("banana", JObject.Parse(@"{""colour"":""yellow"",""size"":""medium""}"));

How to access html form input from asp.net code behind

Simplest way IMO is to include an ID and runat server tag on all your elements.

<div id="MYDIV" runat="server" />

Since it sounds like these are dynamically inserted controls, you might appreciate FindControl().

Anonymous method in Invoke call

I never understood why this makes a difference for the compiler, but this is sufficient.

public static class ControlExtensions
{
    public static void Invoke(this Control control, Action action)
    {
        control.Invoke(action);
    }
}

Bonus: add some error handling, because it is likely that, if you are using Control.Invoke from a background thread you are updating the text / progress / enabled state of a control and don't care if the control is already disposed.

public static class ControlExtensions
{
    public static void Invoke(this Control control, Action action)
    {
        try
        {
            if (!control.IsDisposed) control.Invoke(action);
        }
        catch (ObjectDisposedException) { }
    }
}

jQuery UI DatePicker to show year only

You can use this bootstrap datepicker

$("your-selector").datepicker({
    format: "yyyy",
    viewMode: "years", 
    minViewMode: "years"
});

"your-selector" you can use id(#your-selector) OR class(.your-selector).

How to indent a few lines in Markdown markup?

On gitlab.com a single en space (U+2002) followed by a single em space (U+2003) works decently.

Presumably other repetitions or combinations of not-exactly-accounted-for space characters would also suffice.

How to retrieve raw post data from HttpServletRequest in java

This worked for me: (notice that java 8 is required)

String requestData = request.getReader().lines().collect(Collectors.joining());
UserJsonParser u = gson.fromJson(requestData, UserJsonParser.class);

UserJsonParse is a class that shows gson how to parse the json formant.

class is like that:

public class UserJsonParser {

    private String username;
    private String name;
    private String lastname;
    private String mail;
    private String pass1;
//then put setters and getters
}

the json string that is parsed is like that:

$jsonData: {    "username": "testuser",    "pass1": "clave1234" }

The rest of values (mail, lastname, name) are set to null

How to prevent Right Click option using jquery

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
<script>
 $(document).ready(function(){
  $(document).bind("contextmenu",function(e){
  return false;
  });
});
</script>
</head>
<body>

<p>Right click is disabled on this page.</p>

</body>
</html>

How to create JSON post to api using C#

Try using Web API HttpClient

    static async Task RunAsync()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://domain.com/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


            // HTTP POST
            var obj = new MyObject() { Str = "MyString"};
            response = await client.PostAsJsonAsync("POST URL GOES HERE?", obj );
            if (response.IsSuccessStatusCode)
            {
                response.//.. Contains the returned content.
            }
        }
    }

You can find more details here Web API Clients

How to swap two variables in JavaScript

Swap using Bitwise

let a = 10;
let b = 20;
a ^= b;
y ^= a;
a ^= b;

Single line Swap "using Array"

[a, b] = [b, a]

Cannot kill Python script with Ctrl-C

Ctrl+C terminates the main thread, but because your threads aren't in daemon mode, they keep running, and that keeps the process alive. We can make them daemons:

f = FirstThread()
f.daemon = True
f.start()
s = SecondThread()
s.daemon = True
s.start()

But then there's another problem - once the main thread has started your threads, there's nothing else for it to do. So it exits, and the threads are destroyed instantly. So let's keep the main thread alive:

import time
while True:
    time.sleep(1)

Now it will keep print 'first' and 'second' until you hit Ctrl+C.

Edit: as commenters have pointed out, the daemon threads may not get a chance to clean up things like temporary files. If you need that, then catch the KeyboardInterrupt on the main thread and have it co-ordinate cleanup and shutdown. But in many cases, letting daemon threads die suddenly is probably good enough.

How do you create a UIImage View Programmatically - Swift

In Swift 4.2 and Xcode 10.1

//Create image view simply like this.
let imgView = UIImageView()
imgView.frame = CGRect(x: 200, y: 200, width: 200, height: 200)
imgView.image = UIImage(named: "yourimagename")//Assign image to ImageView
imgView.imgViewCorners()
view.addSubview(imgView)//Add image to our view

//Add image view properties like this(This is one of the way to add properties).  
extension UIImageView {
    //If you want only round corners
    func imgViewCorners() {
        layer.cornerRadius = 10
        layer.borderWidth = 1.0
        layer.masksToBounds = true
    }
}

GetElementByID - Multiple IDs

As stated by jfriend00,

document.getElementById() only supports one name at a time and only returns a single node not an array of nodes.

However, here's some example code I created which you can give one or a comma separated list of id's. It will give you one or many elements in an array. If there are any errors, it will return an array with an Error as the only entry.

function safelyGetElementsByIds(ids){
    if(typeof ids !== 'string') return new Error('ids must be a comma seperated string of ids or a single id string');
    ids = ids.split(",");
    let elements = [];
    for(let i=0, len = ids.length; i<len; i++){
        const currId = ids[i];
        const currElement = (document.getElementById(currId) || new Error(currId + ' is not an HTML Element'));
        if(currElement instanceof Error) return [currElement];
        elements.push(currElement);
    };
    return elements;
}

safelyGetElementsByIds('realId1'); //returns [<HTML Element>]
safelyGetElementsByIds('fakeId1'); //returns [Error : fakeId1 is not an HTML Element]
safelyGetElementsByIds('realId1', 'realId2', 'realId3'); //returns [<HTML Element>,<HTML Element>,<HTML Element>]
safelyGetElementsByIds('realId1', 'realId2', 'fakeId3'); //returns [Error : fakeId3 is not an HTML Element]

jQuery get the id/value of <li> element after click function

$("#myid li").click(function() {
    alert(this.id); // id of clicked li by directly accessing DOMElement property
    alert($(this).attr('id')); // jQuery's .attr() method, same but more verbose
    alert($(this).html()); // gets innerHTML of clicked li
    alert($(this).text()); // gets text contents of clicked li
});

If you are talking about replacing the ID with something:

$("#myid li").click(function() {
    this.id = 'newId';

    // longer method using .attr()
    $(this).attr('id', 'newId');
});

Demo here. And to be fair, you should have first tried reading the documentation:

check if directory exists and delete in one command unix

Why not just use rm -rf /some/dir? That will remove the directory if it's present, otherwise do nothing. Unlike rm -r /some/dir this flavor of the command won't crash if the folder doesn't exist.

How to set Toolbar text and back arrow color

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/actionBar"
app:titleTextAppearance="@style/ToolbarTitleText"
app:theme="@style/ToolBarStyle">

<TextView
    android:id="@+id/title"
    style="@style/ToolbarTitleText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="hh"/>

<!-- ToolBar -->
<style name="ToolBarStyle" parent="Widget.AppCompat.Toolbar">
    <item name="actionMenuTextColor">#ff63BBF7</item>
</style>

use app:theme="@style/ToolBarStyle"

Reference resources:http://blog.csdn.net/wyyl1/article/details/45972371

How does Subquery in select statement work in oracle

In the Oracle RDBMS, it is possible to use a multi-row subquery in the select clause as long as the (sub-)output is encapsulated as a collection. In particular, a multi-row select clause subquery can output each of its rows as an xmlelement that is encapsulated in an xmlforest.

How to generate a Makefile with source in sub-directories using just one makefile

Usually, you create a Makefile in each subdirectory, and write in the top-level Makefile to call make in the subdirectories.

This page may help: http://www.gnu.org/software/make/

Removing App ID from Developer Connection

Does deleting the AppID do anything to disable versions of an Enterprise distributed app "in the wild" ??

If not, is there any way to kill off an Enterprise app before it's expiry?

How to perform grep operation on all files in a directory?

grep $PATTERN * would be sufficient. By default, grep would skip all subdirectories. However, if you want to grep through them, grep -r $PATTERN * is the case.

INNER JOIN ON vs WHERE clause

The implicit join ANSI syntax is older, less obvious, and not recommended.

In addition, the relational algebra allows interchangeability of the predicates in the WHERE clause and the INNER JOIN, so even INNER JOIN queries with WHERE clauses can have the predicates rearranged by the optimizer.

I recommend you write the queries in the most readable way possible.

Sometimes this includes making the INNER JOIN relatively "incomplete" and putting some of the criteria in the WHERE simply to make the lists of filtering criteria more easily maintainable.

For example, instead of:

SELECT *
FROM Customers c
INNER JOIN CustomerAccounts ca
    ON ca.CustomerID = c.CustomerID
    AND c.State = 'NY'
INNER JOIN Accounts a
    ON ca.AccountID = a.AccountID
    AND a.Status = 1

Write:

SELECT *
FROM Customers c
INNER JOIN CustomerAccounts ca
    ON ca.CustomerID = c.CustomerID
INNER JOIN Accounts a
    ON ca.AccountID = a.AccountID
WHERE c.State = 'NY'
    AND a.Status = 1

But it depends, of course.

How does the JPA @SequenceGenerator annotation work

I use this and it works right

@Id
@GeneratedValue(generator = "SEC_ODON", strategy = GenerationType.SEQUENCE)
@SequenceGenerator(name = "SEC_ODON", sequenceName = "SO.SEC_ODON",allocationSize=1)
@Column(name="ID_ODON", unique=true, nullable=false, precision=10, scale=0)
public Long getIdOdon() {
    return this.idOdon;
}

What is the difference between JVM, JDK, JRE & OpenJDK?

JVM is abbreviated as Java Virtual Machine, JVM is the main component of java architecture. JVM is written in C programming language. Java compiler produce the byte code for JVM. JVM reading the byte code verifying the byte code and linking the code with the ibrary.

JRE is abbreviated as Java Runtime Environment. it is provide environment at runtime. It is physically exist. It contain JVM + set of libraries(jar) +other files.

JDK is abbreviated as Java Development Kit . it is develop java applications. And also Debugging and monitoring java applications . JDK contain JRE +development tools(javac,java)

OpenJDK OpenJDK is an open source version of sun JDK. Oracle JDK is Sun's official JDK.

Combining two sorted lists in Python

is there a smarter way to do this in Python

This hasn't been mentioned, so I'll go ahead - there is a merge stdlib function in the heapq module of python 2.6+. If all you're looking to do is getting things done, this might be a better idea. Of course, if you want to implement your own, the merge of merge-sort is the way to go.

>>> list1 = [1, 5, 8, 10, 50]
>>> list2 = [3, 4, 29, 41, 45, 49]
>>> from heapq import merge
>>> list(merge(list1, list2))
[1, 3, 4, 5, 8, 10, 29, 41, 45, 49, 50]

Here's the documentation.

How to check version of a CocoaPods framework

The highest voted answer (MishieMoo) is correct but it doesn't explain how to open Podfile.lock. Everytime I tried I kept getting:

enter image description here

You open it in terminal by going to the folder it's in and running:

vim Podfile.lock

I got the answer from here: how to open Podfile.lock

You close it by pressing the colon and typing quit or by pressing the colon and the letter q then enter

:quit // then return key
:q // then return key

Another way is in terminal, you can also cd to the folder that your Xcode project is in and enter

$ open Podfile.lock -a Xcode

Doing it the second way, after it opens just press the red X button in the upper left hand corner to close.

How to concat two ArrayLists?

var arr3 = new arraylist();
for(int i=0, j=0, k=0; i<arr1.size()+arr2.size(); i++){
    if(i&1)
        arr3.add(arr1[j++]);
    else
        arr3.add(arr2[k++]);
}

as you say, "the names and numbers beside each other".

ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)

If you use the WEB API with Claims, you can use this:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class AutorizeCompanyAttribute:  AuthorizationFilterAttribute
{
    public string Company { get; set; }

    public override void OnAuthorization(HttpActionContext actionContext)
    {
        var claims = ((ClaimsIdentity)Thread.CurrentPrincipal.Identity);
        var claim = claims.Claims.Where(x => x.Type == "Company").FirstOrDefault();

        string privilegeLevels = string.Join("", claim.Value);        

        if (privilegeLevels.Contains(this.Company)==false)
        {
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "Usuario de Empresa No Autorizado");
        }
    }
}
[HttpGet]
[AutorizeCompany(Company = "MyCompany")]
[Authorize(Roles ="SuperAdmin")]
public IEnumerable MyAction()
{....
}

Decode Hex String in Python 3

import codecs

decode_hex = codecs.getdecoder("hex_codec")

# for an array
msgs = [decode_hex(msg)[0] for msg in msgs]

# for a string
string = decode_hex(string)[0]

Everytime I run gulp anything, I get a assertion error. - Task function must be specified

It's not good to keep changing the gulp & npm versions in-order to fix the errors. I was getting several exceptions last days after reinstall my working machine. And wasted tons of minutes to re-install & fixing those.

So, I decided to upgrade all to latest versions:

npm -v : v12.13.0 
node -v : 6.13.0
gulp -v : CLI version: 2.2.0 Local version: 4.0.2

This error is getting because of the how it has coded in you gulpfile but not the version mismatch. So, Here you have to change 2 things in the gulpfile to aligned with Gulp version 4. Gulp 4 has changed how initiate the task than Version 3.

  1. In version 4, you have to defined the task as a function, before call it as a gulp task by it's string name. In V3:

gulp.task('serve', ['sass'], function() {..});

But in V4 it should be like:

function serve() {
...
}
gulp.task('serve', gulp.series(sass));
  1. As @Arthur has mentioned, you need to change the way of passing arguments to the task function. It was like this in V3:

gulp.task('serve', ['sass'], function() { ... });

But in V4, it should be:

gulp.task('serve', gulp.series(sass));

How to deal with bad_alloc in C++?

You can catch it like any other exception:

try {
  foo();
}
catch (const std::bad_alloc&) {
  return -1;
}

Quite what you can usefully do from this point is up to you, but it's definitely feasible technically.



In general you cannot, and should not try, to respond to this error. bad_alloc indicates that a resource cannot be allocated because not enough memory is available. In most scenarios your program cannot hope to cope with that, and terminating soon is the only meaningful behaviour.

Worse, modern operating systems often over-allocate: on such systems, malloc and new can return a valid pointer even if there is not enough free memory left – std::bad_alloc will never be thrown, or is at least not a reliable sign of memory exhaustion. Instead, attempts to access the allocated memory will then result in a segmentation fault, which is not catchable (you can handle the segmentation fault signal, but you cannot resume the program afterwards).

The only thing you could do when catching std::bad_alloc is to perhaps log the error, and try to ensure a safe program termination by freeing outstanding resources (but this is done automatically in the normal course of stack unwinding after the error gets thrown if the program uses RAII appropriately).

In certain cases, the program may attempt to free some memory and try again, or use secondary memory (= disk) instead of RAM but these opportunities only exist in very specific scenarios with strict conditions:

  1. The application must ensure that it runs on a system that does not overcommit memory, i.e. it signals failure upon allocation rather than later.
  2. The application must be able to free memory immediately, without any further accidental allocations in the meantime.

It’s exceedingly rare that applications have control over point 1 — userspace applications never do, it’s a system-wide setting that requires root permissions to change.1

OK, so let’s assume you’ve fixed point 1. What you can now do is for instance use a LRU cache for some of your data (probably some particularly large business objects that can be regenerated or reloaded on demand). Next, you need to put the actual logic that may fail into a function that supports retry — in other words, if it gets aborted, you can just relaunch it:

lru_cache<widget> widget_cache;

double perform_operation(int widget_id) {
    std::optional<widget> maybe_widget = widget_cache.find_by_id(widget_id);
    if (not maybe_widget) {
        maybe_widget = widget_cache.store(widget_id, load_widget_from_disk(widget_id));
    }
    return maybe_widget->frobnicate();
}

…

for (int num_attempts = 0; num_attempts < MAX_NUM_ATTEMPTS; ++num_attempts) {
    try {
        return perform_operation(widget_id);
    } catch (std::bad_alloc const&) {
        if (widget_cache.empty()) throw; // memory error elsewhere.
        widget_cache.remove_oldest();
    }
}

// Handle too many failed attempts here.

But even here, using std::set_new_handler instead of handling std::bad_alloc provides the same benefit and would be much simpler.


1 If you’re creating an application that does control point 1, and you’re reading this answer, please shoot me an email, I’m genuinely curious about your circumstances.


What is the C++ Standard specified behavior of new in c++?

The usual notion is that if new operator cannot allocate dynamic memory of the requested size, then it should throw an exception of type std::bad_alloc.
However, something more happens even before a bad_alloc exception is thrown:

C++03 Section 3.7.4.1.3: says

An allocation function that fails to allocate storage can invoke the currently installed new_handler(18.4.2.2), if any. [Note: A program-supplied allocation function can obtain the address of the currently installed new_handler using the set_new_handler function (18.4.2.3).] If an allocation function declared with an empty exception-specification (15.4), throw(), fails to allocate storage, it shall return a null pointer. Any other allocation function that fails to allocate storage shall only indicate failure by throw-ing an exception of class std::bad_alloc (18.4.2.1) or a class derived from std::bad_alloc.

Consider the following code sample:

#include <iostream>
#include <cstdlib>

// function to call if operator new can't allocate enough memory or error arises
void outOfMemHandler()
{
    std::cerr << "Unable to satisfy request for memory\n";

    std::abort();
}

int main()
{
    //set the new_handler
    std::set_new_handler(outOfMemHandler);

    //Request huge memory size, that will cause ::operator new to fail
    int *pBigDataArray = new int[100000000L];

    return 0;
}

In the above example, operator new (most likely) will be unable to allocate space for 100,000,000 integers, and the function outOfMemHandler() will be called, and the program will abort after issuing an error message.

As seen here the default behavior of new operator when unable to fulfill a memory request, is to call the new-handler function repeatedly until it can find enough memory or there is no more new handlers. In the above example, unless we call std::abort(), outOfMemHandler() would be called repeatedly. Therefore, the handler should either ensure that the next allocation succeeds, or register another handler, or register no handler, or not return (i.e. terminate the program). If there is no new handler and the allocation fails, the operator will throw an exception.

What is the new_handler and set_new_handler?

new_handler is a typedef for a pointer to a function that takes and returns nothing, and set_new_handler is a function that takes and returns a new_handler.

Something like:

typedef void (*new_handler)();
new_handler set_new_handler(new_handler p) throw();

set_new_handler's parameter is a pointer to the function operator new should call if it can't allocate the requested memory. Its return value is a pointer to the previously registered handler function, or null if there was no previous handler.

How to handle out of memory conditions in C++?

Given the behavior of newa well designed user program should handle out of memory conditions by providing a proper new_handlerwhich does one of the following:

Make more memory available: This may allow the next memory allocation attempt inside operator new's loop to succeed. One way to implement this is to allocate a large block of memory at program start-up, then release it for use in the program the first time the new-handler is invoked.

Install a different new-handler: If the current new-handler can't make any more memory available, and of there is another new-handler that can, then the current new-handler can install the other new-handler in its place (by calling set_new_handler). The next time operator new calls the new-handler function, it will get the one most recently installed.

(A variation on this theme is for a new-handler to modify its own behavior, so the next time it's invoked, it does something different. One way to achieve this is to have the new-handler modify static, namespace-specific, or global data that affects the new-handler's behavior.)

Uninstall the new-handler: This is done by passing a null pointer to set_new_handler. With no new-handler installed, operator new will throw an exception ((convertible to) std::bad_alloc) when memory allocation is unsuccessful.

Throw an exception convertible to std::bad_alloc. Such exceptions are not be caught by operator new, but will propagate to the site originating the request for memory.

Not return: By calling abort or exit.

"Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP

These errors occur whenever we are using a variable that is not set.

The best way to deal with these is set error reporting on while development.

To set error reporting on:

ini_set('error_reporting', 'on');
ini_set('display_errors', 'on');
error_reporting(E_ALL);

On production servers, error reporting is off, therefore, we do not get these errors.

On the development server, however, we can set error reporting on.

To get rid of this error, we see the following example:

if ($my == 9) {
 $test = 'yes';  // Will produce error as $my is not 9.
}
echo $test;

We can initialize the variables to NULL before assigning their values or using them.

So, we can modify the code as:

$test = NULL;
if ($my == 9) {
 $test = 'yes';  // Will produce error as $my is not 9.
}
echo $test;

This will not disturb any program logic and will not produce Notice even if $test does not have value.

So, basically, its always better to set error reporting ON for development.

And fix all the errors.

And on production, error reporting should be set to off.

What is JAVA_HOME? How does the JVM find the javac path stored in JAVA_HOME?

JAVA_HOME is an Environment Variable set to the location of the Java directory on your computer. PATH is an internal DOS command that finds the /bin directory of the version of Java that you are using. Usually they are the same, except that the PATH entry ends with /bin

How to detect incoming calls, in an Android device?

Here is a simple method which can avoid the use of PhonestateListener and other complications.
So here we are receiving the 3 events from android such as RINGING,OFFHOOK and IDLE. And in order to get the all possible state of call,we need to define our own states like RINGING, OFFHOOK, IDLE, FIRST_CALL_RINGING, SECOND_CALL_RINGING. It can handle every states in a phone call.
Please think in a way that we are receiving events from android and we will define our on call states. See the code.

public class CallListening  extends BroadcastReceiver {
    private static final String TAG ="broadcast_intent";
    public static String incoming_number;
    private String current_state,previus_state,event;
    public static Boolean dialog= false;
    private Context context;
    private SharedPreferences sp,sp1;
    private SharedPreferences.Editor spEditor,spEditor1;
    public void onReceive(Context context, Intent intent) {
        //Log.d("intent_log", "Intent" + intent);
        dialog=true;
        this.context = context;
        event = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
        incoming_number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
        Log.d(TAG, "The received event : "+event+", incoming_number : " + incoming_number);
        previus_state = getCallState(context);
        current_state = "IDLE";
        if(incoming_number!=null){
            updateIncomingNumber(incoming_number,context);
        }else {
            incoming_number=getIncomingNumber(context);
        }
        switch (event) {
            case "RINGING":
                Log.d(TAG, "State : Ringing, incoming_number : " + incoming_number);
            if((previus_state.equals("IDLE")) || (previus_state.equals("FIRST_CALL_RINGING"))){
                    current_state ="FIRST_CALL_RINGING";
                }
                if((previus_state.equals("OFFHOOK"))||(previus_state.equals("SECOND_CALL_RINGING"))){
                    current_state = "SECOND_CALL_RINGING";
                }

                break;
            case "OFFHOOK":
                Log.d(TAG, "State : offhook, incoming_number : " + incoming_number);
                if((previus_state.equals("IDLE")) ||(previus_state.equals("FIRST_CALL_RINGING")) || previus_state.equals("OFFHOOK")){
                    current_state = "OFFHOOK";
                }
                if(previus_state.equals("SECOND_CALL_RINGING")){
                    current_state ="OFFHOOK";
                    startDialog(context);
                }
                break;
            case "IDLE":
                Log.d(TAG, "State : idle and  incoming_number : " + incoming_number);
                if((previus_state.equals("OFFHOOK")) || (previus_state.equals("SECOND_CALL_RINGING")) || (previus_state.equals("IDLE"))){
                    current_state="IDLE";
                }
                if(previus_state.equals("FIRST_CALL_RINGING")){
                    current_state = "IDLE";
                    startDialog(context);
                }
                updateIncomingNumber("no_number",context);
                Log.d(TAG,"stored incoming number flushed");
                break;
        }
        if(!current_state.equals(previus_state)){
            Log.d(TAG, "Updating  state from "+previus_state +" to "+current_state);
            updateCallState(current_state,context);

        }
    }
    public void startDialog(Context context) {
        Log.d(TAG,"Starting Dialog box");
        Intent intent1 = new Intent(context, NotifyHangup.class);
        intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent1);

    }
    public void updateCallState(String state,Context context){
        sp = PreferenceManager.getDefaultSharedPreferences(context);
        spEditor = sp.edit();
        spEditor.putString("call_state", state);
        spEditor.commit();
        Log.d(TAG, "state updated");

    }
    public void updateIncomingNumber(String inc_num,Context context){
        sp = PreferenceManager.getDefaultSharedPreferences(context);
        spEditor = sp.edit();
        spEditor.putString("inc_num", inc_num);
        spEditor.commit();
        Log.d(TAG, "incoming number updated");
    }
    public String getCallState(Context context){
        sp1 = PreferenceManager.getDefaultSharedPreferences(context);
        String st =sp1.getString("call_state", "IDLE");
        Log.d(TAG,"get previous state as :"+st);
        return st;
    }
    public String getIncomingNumber(Context context){
        sp1 = PreferenceManager.getDefaultSharedPreferences(context);
        String st =sp1.getString("inc_num", "no_num");
        Log.d(TAG,"get incoming number as :"+st);
        return st;
    }
}

jQuery click events firing multiple times

Another solution I found was this, if you have multiple classes and are dealing with radio buttons while clicking on the label.

$('.btn').on('click', function(e) {
    e.preventDefault();

    // Hack - Stop Double click on Radio Buttons
    if (e.target.tagName != 'INPUT') {
        // Not a input, check to see if we have a radio
        $(this).find('input').attr('checked', 'checked').change();
    }
});

Rotating a view in Android

Rotating view with rotate() will not affect your view's measured size. As result, rotated view be clipped or not fit into the parent layout. This library fixes it though:

https://github.com/rongi/rotate-layout

enter image description here

How to display a range input slider vertically

Its very simple. I had implemented using -webkit-appearance: slider-vertical, It worked in chorme, Firefox, Edge

<input type="range">
input[type=range]{
    writing-mode: bt-lr; /* IE */
    -webkit-appearance: slider-vertical; /* WebKit */
    width: 50px;
    height: 200px;
    padding: 0 24px;
    outline: none;
    background:transparent;
}

How to pass multiple parameters to a get method in ASP.NET Core

To parse the search parameters from the URL, you need to annotate the controller method parameters with [FromQuery], for example:

[Route("api/person")]
public class PersonController : Controller
{
    [HttpGet]
    public string GetById([FromQuery]int id)
    {

    }

    [HttpGet]
    public string GetByName([FromQuery]string firstName, [FromQuery]string lastName)
    {

    }

    [HttpGet]
    public string GetByNameAndAddress([FromQuery]string firstName, [FromQuery]string lastName, [FromQuery]string address)
    {

    }
}

Compiling simple Hello World program on OS X via command line

The new version of this should read like so:

xcrun g++ hw.cpp
./a.out

Operand type clash: int is incompatible with date + The INSERT statement conflicted with the FOREIGN KEY constraint

Try wrapping your dates in single quotes, like this:

'15-6-2005'

It should be able to parse the date this way.

Token based authentication in Web API without any user interface

I think there is some confusion about the difference between MVC and Web Api. In short, for MVC you can use a login form and create a session using cookies. For Web Api there is no session. That's why you want to use the token.

You do not need a login form. The Token endpoint is all you need. Like Win described you'll send the credentials to the token endpoint where it is handled.

Here's some client side C# code to get a token:

    //using System;
    //using System.Collections.Generic;
    //using System.Net;
    //using System.Net.Http;
    //string token = GetToken("https://localhost:<port>/", userName, password);

    static string GetToken(string url, string userName, string password) {
        var pairs = new List<KeyValuePair<string, string>>
                    {
                        new KeyValuePair<string, string>( "grant_type", "password" ), 
                        new KeyValuePair<string, string>( "username", userName ), 
                        new KeyValuePair<string, string> ( "Password", password )
                    };
        var content = new FormUrlEncodedContent(pairs);
        ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
        using (var client = new HttpClient()) {
            var response = client.PostAsync(url + "Token", content).Result;
            return response.Content.ReadAsStringAsync().Result;
        }
    }

In order to use the token add it to the header of the request:

    //using System;
    //using System.Collections.Generic;
    //using System.Net;
    //using System.Net.Http;
    //var result = CallApi("https://localhost:<port>/something", token);

    static string CallApi(string url, string token) {
        ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
        using (var client = new HttpClient()) {
            if (!string.IsNullOrWhiteSpace(token)) {
                var t = JsonConvert.DeserializeObject<Token>(token);

                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + t.access_token);
            }
            var response = client.GetAsync(url).Result;
            return response.Content.ReadAsStringAsync().Result;
        }
    }

Where Token is:

//using Newtonsoft.Json;

class Token
{
    public string access_token { get; set; }
    public string token_type { get; set; }
    public int expires_in { get; set; }
    public string userName { get; set; }
    [JsonProperty(".issued")]
    public string issued { get; set; }
    [JsonProperty(".expires")]
    public string expires { get; set; }
}

Now for the server side:

In Startup.Auth.cs

        var oAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider("self"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            // https
            AllowInsecureHttp = false
        };
        // Enable the application to use bearer tokens to authenticate users
        app.UseOAuthBearerTokens(oAuthOptions);

And in ApplicationOAuthProvider.cs the code that actually grants or denies access:

//using Microsoft.AspNet.Identity.Owin;
//using Microsoft.Owin.Security;
//using Microsoft.Owin.Security.OAuth;
//using System;
//using System.Collections.Generic;
//using System.Security.Claims;
//using System.Threading.Tasks;

public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
    private readonly string _publicClientId;

    public ApplicationOAuthProvider(string publicClientId)
    {
        if (publicClientId == null)
            throw new ArgumentNullException("publicClientId");

        _publicClientId = publicClientId;
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

        var user = await userManager.FindAsync(context.UserName, context.Password);
        if (user == null)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }

        ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager);
        var propertyDictionary = new Dictionary<string, string> { { "userName", user.UserName } };
        var properties = new AuthenticationProperties(propertyDictionary);

        AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
        // Token is validated.
        context.Validated(ticket);
    }

    public override Task TokenEndpoint(OAuthTokenEndpointContext context)
    {
        foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
        {
            context.AdditionalResponseParameters.Add(property.Key, property.Value);
        }
        return Task.FromResult<object>(null);
    }

    public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        // Resource owner password credentials does not provide a client ID.
        if (context.ClientId == null)
            context.Validated();

        return Task.FromResult<object>(null);
    }

    public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
    {
        if (context.ClientId == _publicClientId)
        {
            var expectedRootUri = new Uri(context.Request.Uri, "/");

            if (expectedRootUri.AbsoluteUri == context.RedirectUri)
                context.Validated();
        }
        return Task.FromResult<object>(null);
    }

}

As you can see there is no controller involved in retrieving the token. In fact, you can remove all MVC references if you want a Web Api only. I have simplified the server side code to make it more readable. You can add code to upgrade the security.

Make sure you use SSL only. Implement the RequireHttpsAttribute to force this.

You can use the Authorize / AllowAnonymous attributes to secure your Web Api. Additionally you can add filters (like RequireHttpsAttribute) to make your Web Api more secure. I hope this helps.

setOnItemClickListener on custom ListView

If in the listener you get the root layout of the item (say itemLayout), and you gave some id's to the textviews, you can then get them with something like itemLayout.findViewById(R.id.textView1).

jQuery Determine if a matched class has a given id

update: sorry misunderstood the question, removed .has() answer.

another alternative way, create .hasId() plugin

_x000D_
_x000D_
// the plugin_x000D_
$.fn.hasId = function(id) {_x000D_
  return this.attr('id') == id;_x000D_
};_x000D_
_x000D_
// select first class_x000D_
$('.mydiv').hasId('foo') ?_x000D_
  console.log('yes') : console.log('no');_x000D_
_x000D_
// select second class_x000D_
// $('.mydiv').eq(1).hasId('foo')_x000D_
// or_x000D_
$('.mydiv:eq(1)').hasId('foo') ?_x000D_
  console.log('yes') : console.log('no');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="mydiv" id="foo"></div>_x000D_
<div class="mydiv"></div>
_x000D_
_x000D_
_x000D_

How to remove all of the data in a table using Django

You can use the Django-Truncate library to delete all data of a table without destroying the table structure.

Example:

  1. First, install django-turncate using your terminal/command line:
pip install django-truncate
  1. Add "django_truncate" to your INSTALLED_APPS in the settings.py file:
INSTALLED_APPS = [
    ...
    'django_truncate',
]
  1. Use this command in your terminal to delete all data of the table from the app.
python manage.py truncate --apps app_name --models table_name

Get HTML inside iframe using jQuery

Try this code:

$('#iframe').contents().find("html").html();

This will return all the html in your iframe. Instead of .find("html") you can use any selector you want eg: .find('body'),.find('div#mydiv').

Finding the max value of an attribute in an array of objects

var max = 0;                
jQuery.map(arr, function (obj) {
  if (obj.attr > max)
    max = obj.attr;
});

How do I parse JSON from a Java HTTPResponse?

You can use the Gson library for parsing

void getJson() throws IOException {
    HttpClient  httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet("some url of json");
    HttpResponse httpResponse = httpClient.execute(httpGet);
    String response = EntityUtils.toString(httpResponse.getEntity());

    Gson gson = new Gson();
    MyClass myClassObj = gson.fromJson(response, MyClass.class);

}

here is sample json file which is fetchd from server

{
"id":5,
"name":"kitkat",
"version":"4.4"
}

here is my class

class MyClass{
int id;
String name;
String version;
}

refer this

PHP, How to get current date in certain format

date("Y-m-d H:i:s"); // This should do it.

Convert a negative number to a positive one in JavaScript

Math.abs(x) or if you are certain the value is negative before the conversion just prepend a regular minus sign: x = -x.

Import module from subfolder

There's no need to mess with your PYTHONPATH or sys.path here.

To properly use absolute imports in a package you should include the "root" packagename as well, e.g.:

from dirFoo.dirFoo1.foo1 import Foo1
from dirFoo.dirFoo2.foo2 import Foo2

Or you can use relative imports:

from .dirfoo1.foo1 import Foo1
from .dirfoo2.foo2 import Foo2

How to pick just one item from a generator?

I believe the only way is to get a list from the iterator then get the element you want from that list.

l = list(myfunct())
l[4]

Compiling php with curl, where is curl installed?

If you're going to compile a 64bit version(x86_64) of php use: /usr/lib64/

For architectures (i386 ... i686) use /usr/lib/

I recommend compiling php to the same architecture as apache. As you're using a 64bit linux i asume your apache is also compiled for x86_64.

Trying Gradle build - "Task 'build' not found in root project"

You didn't do what you're being asked to do.

What is asked:

I have to execute ../gradlew build

What you do

cd ..
gradlew build

That's not the same thing.

The first one will use the gradlew command found in the .. directory (mdeinum...), and look for the build file to execute in the current directory, which is (for example) chapter1-bookstore.

The second one will execute the gradlew command found in the current directory (mdeinum...), and look for the build file to execute in the current directory, which is mdeinum....

So the build file executed is not the same.

Correct way to pause a Python program

It Seems fine to me (or raw_input() in Python 2.X). Alternatively, you could use time.sleep() if you want to pause for a certain number of seconds.

import time
print("something")
time.sleep(5.5)    # Pause 5.5 seconds
print("something")

How do you dynamically allocate a matrix?

Using the double-pointer is by far the best compromise between execution speed/optimisation and legibility. Using a single array to store matrix' contents is actually what a double-pointer does.

I have successfully used the following templated creator function (yes, I know I use old C-style pointer referencing, but it does make code more clear on the calling side with regards to changing parameters - something I like about pointers which is not possible with references. You will see what I mean):

///
/// Matrix Allocator Utility
/// @param pppArray Pointer to the double-pointer where the matrix should be allocated.
/// @param iRows Number of rows.
/// @param iColumns Number of columns.
/// @return Successful allocation returns true, else false.
template <typename T>
bool NewMatrix(T*** pppArray, 
               size_t iRows, 
               size_t iColumns)
{
   bool l_bResult = false;
   if (pppArray != 0) // Test if pointer holds a valid address.
   {                  // I prefer using the shorter 0 in stead of NULL.
      if (!((*pppArray) != 0)) // Test if the first element is currently unassigned.
      {                        // The "double-not" evaluates a little quicker in general.
         // Allocate and assign pointer array.
         (*pppArray) = new T* [iRows]; 
         if ((*pppArray) != 0) // Test if pointer-array allocation was successful.
         {
            // Allocate and assign common data storage array.
            (*pppArray)[0] = new T [iRows * iColumns]; 
            if ((*pppArray)[0] != 0) // Test if data array allocation was successful.
            {
               // Using pointer arithmetic requires the least overhead. There is no 
               // expensive repeated multiplication involved and very little additional 
               // memory is used for temporary variables.
               T** l_ppRow = (*pppArray);
               T* l_pRowFirstElement = l_ppRow[0];
               for (size_t l_iRow = 1; l_iRow < iRows; l_iRow++)
               {
                  l_ppRow++;
                  l_pRowFirstElement += iColumns;
                  l_ppRow[0] = l_pRowFirstElement;
               }
               l_bResult = true;
            }
         }
      }
   }
}

To de-allocate the memory created using the abovementioned utility, one simply has to de-allocate in reverse.

///
/// Matrix De-Allocator Utility
/// @param pppArray Pointer to the double-pointer where the matrix should be de-allocated.
/// @return Successful de-allocation returns true, else false.
template <typename T>
bool DeleteMatrix(T*** pppArray)
{
   bool l_bResult = false;
   if (pppArray != 0) // Test if pointer holds a valid address.
   {
      if ((*pppArray) != 0) // Test if pointer array was assigned.
      {
         if ((*pppArray)[0] != 0) // Test if data array was assigned.
         {
               // De-allocate common storage array.
               delete [] (*pppArray)[0];
            }
         }
         // De-allocate pointer array.
         delete [] (*pppArray);
         (*pppArray) = 0;
         l_bResult = true;
      }
   }
}

To use these abovementioned template functions is then very easy (e.g.):

   .
   .
   .
   double l_ppMatrix = 0;
   NewMatrix(&l_ppMatrix, 3, 3); // Create a 3 x 3 Matrix and store it in l_ppMatrix.
   .
   .
   .
   DeleteMatrix(&l_ppMatrix);

printf with std::string?

Use std::printf and c_str() example:

std::printf("Follow this command: %s", myString.c_str());

How to access a value defined in the application.properties file in Spring Boot

1.Injecting a property with the @Value annotation is straightforward:
@Value( "${jdbc.url}" )
private String jdbcUrl;

2. we can obtain the value of a property using the Environment API

@Autowired
private Environment env;
...
dataSource.setUrl(env.getProperty("jdbc.url"));

generate model using user:references vs user_id:integer

For the former, convention over configuration. Rails default when you reference another table with

 belongs_to :something

is to look for something_id.

references, or belongs_to is actually newer way of writing the former with few quirks.

Important is to remember that it will not create foreign keys for you. In order to do that, you need to set it up explicitly using either:

t.references :something, foreign_key: true
t.belongs_to :something_else, foreign_key: true

or (note the plural):

add_foreign_key :table_name, :somethings
add_foreign_key :table_name, :something_elses`

Github: Can I see the number of downloads for a repo?

To try to make this more clear:
for this github project: stant/mdcsvimporter2015
https://github.com/stant/mdcsvimporter2015
with releases at
https://github.com/stant/mdcsvimporter2015/releases

go to http or https: (note added "api." and "/repos")
https://api.github.com/repos/stant/mdcsvimporter2015/releases

you will get this json output and you can search for "download_count":

    "download_count": 2,
    "created_at": "2015-02-24T18:20:06Z",
    "updated_at": "2015-02-24T18:20:07Z",
    "browser_download_url": "https://github.com/stant/mdcsvimporter2015/releases/download/v18/mdcsvimporter-beta-18.zip"

or on command line do:
wget --no-check-certificate https://api.github.com/repos/stant/mdcsvimporter2015/releases

Prevent scrolling of parent element when inner element scroll position reaches top/bottom?

There are tons of questions like this out there, with many answers, but I could not find a satisfactory solution that did not involve events, scripts, plugins, etc. I wanted to keep it straight in HTML and CSS. I finally found a solution that worked, although it involved restructuring the markup to break the event chain.


1. Basic problem

Scrolling input (i.e.: mousewheel) applied to the modal element will spill over into an ancestor element and scroll it in the same direction, if some such element is scrollable:

(All examples are meant to be viewed on desktop resolutions)

https://jsfiddle.net/ybkbg26c/5/

HTML:

<div id="parent">
  <div id="modal">
    This text is pretty long here.  Hope fully, we will get some scroll bars.
  </div>
</div>

CSS:

#modal {
  position: absolute;
  height: 100px;
  width: 100px;
  top: 20%;
  left: 20%;
  overflow-y: scroll;
}
#parent {
  height: 4000px;
}

2. No parent scroll on modal scroll

The reason why the ancestor ends up scrolling is because the scroll event bubbles and some element on the chain is able to handle it. A way to stop that is to make sure none of the elements on the chain know how to handle the scroll. In terms of our example, we can refactor the tree to move the modal out of the parent element. For obscure reasons, it is not enough to keep the parent and the modal DOM siblings; the parent must be wrapped by another element that establishes a new stacking context. An absolutely positioned wrapper around the parent can do the trick.

The result we get is that as long as the modal receives the scroll event, the event will not bubble to the "parent" element.

It should typically be possible to redesign the DOM tree to support this behavior without affecting what the end user sees.

https://jsfiddle.net/0bqq31Lv/3/

HTML:

<div id="context">
  <div id="parent">
  </div>
</div>
<div id="modal">
  This text is pretty long here.  Hope fully, we will get some scroll bars.
</div>

CSS (new only):

#context {
  position: absolute;
  overflow-y: scroll;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

3. No scroll anywhere except in modal while it is up

The solution above still allows the parent to receive scroll events, as long as they are not intercepted by the modal window (i.e. if triggered by mousewheel while the cursor is not over the modal). This is sometimes undesirable and we may want to forbid all background scrolling while the modal is up. To do that, we need to insert an extra stacking context that spans the whole viewport behind the modal. We can do that by displaying an absolutely positioned overlay, which can be fully transparent if necessary (but not visibility:hidden).

https://jsfiddle.net/0bqq31Lv/2/

HTML:

<div id="context">
  <div id="parent">
  </div>
</div>
<div id="overlay">  
</div>
<div id="modal">
  This text is pretty long here.  Hope fully, we will get some scroll bars.
</div>

CSS (new on top of #2):

#overlay {
  background-color: transparent;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

Call of overloaded function is ambiguous

Use

p.setval(static_cast<const char *>(0));

or

p.setval(static_cast<unsigned int>(0));

As indicated by the error, the type of 0 is int. This can just as easily be cast to an unsigned int or a const char *. By making the cast manually, you are telling the compiler which overload you want.

How can I check if given int exists in array?

I think you are looking for std::any_of, which will return a true/false answer to detect if an element is in a container (array, vector, deque, etc.)

int val = SOME_VALUE; // this is the value you are searching for
bool exists = std::any_of(std::begin(myArray), std::end(myArray), [&](int i)
{
    return i == val;
});

If you want to know where the element is, std::find will return an iterator to the first element matching whatever criteria you provide (or a predicate you give it).

int val = SOME_VALUE;
int* pVal = std::find(std::begin(myArray), std::end(myArray), val);
if (pVal == std::end(myArray))
{
    // not found
}
else
{
    // found
}

Programmatically get own phone number in iOS

AppStore will reject it, as it's reaching outside of application container.

Apps should be self-contained in their bundles, and may not read or write data outside the designated container area

Section 2.5.2 : https://developer.apple.com/app-store/review/guidelines/#software-requirements

Calculate distance in meters when you know longitude and latitude in java

In C++ it is done like this:

#define LOCAL_PI 3.1415926535897932385 

double ToRadians(double degrees) 
{
  double radians = degrees * LOCAL_PI / 180;
  return radians;
}

double DirectDistance(double lat1, double lng1, double lat2, double lng2) 
{
  double earthRadius = 3958.75;
  double dLat = ToRadians(lat2-lat1);
  double dLng = ToRadians(lng2-lng1);
  double a = sin(dLat/2) * sin(dLat/2) + 
             cos(ToRadians(lat1)) * cos(ToRadians(lat2)) * 
             sin(dLng/2) * sin(dLng/2);
  double c = 2 * atan2(sqrt(a), sqrt(1-a));
  double dist = earthRadius * c;
  double meterConversion = 1609.00;
  return dist * meterConversion;
}

Are HTTPS headers encrypted?

The whole lot is encrypted - all the headers. That's why SSL on vhosts doesn't work too well - you need a dedicated IP address because the Host header is encrypted.

The Server Name Identification (SNI) standard means that the hostname may not be encrypted if you're using TLS. Also, whether you're using SNI or not, the TCP and IP headers are never encrypted. (If they were, your packets would not be routable.)

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

Building on D.A.'s suggestion that "the only way to do what you want is to modify the underlying data" and using numpy to modify the underlying data...

This works for me, and is pretty fast:

def tz_to_naive(datetime_index):
    """Converts a tz-aware DatetimeIndex into a tz-naive DatetimeIndex,
    effectively baking the timezone into the internal representation.

    Parameters
    ----------
    datetime_index : pandas.DatetimeIndex, tz-aware

    Returns
    -------
    pandas.DatetimeIndex, tz-naive
    """
    # Calculate timezone offset relative to UTC
    timestamp = datetime_index[0]
    tz_offset = (timestamp.replace(tzinfo=None) - 
                 timestamp.tz_convert('UTC').replace(tzinfo=None))
    tz_offset_td64 = np.timedelta64(tz_offset)

    # Now convert to naive DatetimeIndex
    return pd.DatetimeIndex(datetime_index.values + tz_offset_td64)

WooCommerce - get category for product page

<?php
   $terms = get_the_terms($product->ID, 'product_cat');
      foreach ($terms as $term) {

        $product_cat = $term->name;
           echo $product_cat;
             break;
  }
 ?>

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

Similar situation. It was working. Then, I started to include pytables. At first view, no reason to errors. I decided to use another function, that has a domain constraint (elipse) and received the following error:

TypeError: 'numpy.float64' object cannot be interpreted as an integer

or

TypeError: 'numpy.float64' object is not iterable

The crazy thing: the previous function I was using, no code changed, started to return the same error. My intermediary function, already used was:

def MinMax(x, mini=0, maxi=1)
    return max(min(x,mini), maxi)

The solution was avoid numpy or math:

def MinMax(x, mini=0, maxi=1)
    x = [x_aux if x_aux > mini else mini for x_aux in x]
    x = [x_aux if x_aux < maxi else maxi for x_aux in x]
    return max(min(x,mini), maxi)

Then, everything calm again. It was like one library possessed max and min!

addEventListener vs onclick

As far as I know, the DOM "load" event still does only work very limited. That means it'll only fire for the window object, images and <script> elements for instance. The same goes for the direct onload assignment. There is no technical difference between those two. Probably .onload = has a better cross-browser availabilty.

However, you cannot assign a load event to a <div> or <span> element or whatnot.

Convert a list to a dictionary in Python

You can also try this approach save the keys and values in different list and then use dict method

data=['test1', '1', 'test2', '2', 'test3', '3', 'test4', '4']

keys=[]
values=[]
for i,j in enumerate(data):
    if i%2==0:
        keys.append(j)
    else:
        values.append(j)

print(dict(zip(keys,values)))

output:

{'test3': '3', 'test1': '1', 'test2': '2', 'test4': '4'}

How to Delete Session Cookie?

Be sure to supply the exact same path as when you set it, i.e.

Setting:

$.cookie('foo','bar', {path: '/'});

Removing:

$.cookie('foo', null, {path: '/'});

Note that

$.cookie('foo', null); 

will NOT work, since it is actually not the same cookie.

Hope that helps. The same goes for the other options in the hash

Get the size of the screen, current web page and browser window

This how I managed to get the screen width in React JS Project:

If width is equal to 1680 then return 570 else return 200

var screenWidth = window.screen.availWidth;

<Label style={{ width: screenWidth == "1680" ? 570 : 200, color: "transparent" }}>a  </Label>

Screen.availWidth

Sending command line arguments to npm script

I had been using this one-liner in the past, and after a bit of time away from Node.js had to try and rediscover it recently. Similar to the solution mentioned by @francoisrv, it utilizes the node_config_* variables.

Create the following minimal package.json file:

{
  "name": "argument",
  "version": "1.0.0",
  "scripts": {
    "argument": "echo \"The value of --foo is '${npm_config_foo}'\""
  }
}

Run the following command:

npm run argument --foo=bar

Observe the following output:

The value of --foo is 'bar'

All of this is nicely documented in the npm official documentation:

Note: The Environment Variables heading explains that variables inside scripts do behave differently to what is defined in the documentation. This is true when it comes to case sensitivity, as well whether the argument is defined with a space or equals sign.

Note: If you are using an argument with hyphens, these will be replaced with underscores in the corresponding environment variable. For example, npm run example --foo-bar=baz would correspond to ${npm_config_foo_bar}.

Note: For non-WSL Windows users, see @Doctor Blue's comments below... TL;DR replace ${npm_config_foo} with %npm_config_foo%.

Python 3: ImportError "No Module named Setuptools"

I was doing this inside a virtualenv on Oracle Linux 6.4 using python-2.6 so the apt-based solutions weren't an option for me, nor were the python-2.7 ideas. My fix was to upgrade my version of setuptools that had been installed by virtualenv:

pip install --upgrade setuptools

After that, I was able to install packages into the virtualenv. I know this question has already had an answer selected but I hope this answer will help others in my situation.

Bootstrap 3 with remote Modal

As much as I dislike modifying Bootstrap code (makes upgrading more difficult), you can simply add ".find('.modal-body') to the load statement in modal.js as follows:

// original code
// if (this.options.remote) this.$element.load(this.options.remote)

// modified code
if (this.options.remote) this.$element.find('.modal-body').load(this.options.remote)

Get the full URL in PHP

My favorite cross platform method for finding the current URL is:

$url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

print call stack in C or C++

You can use Poppy for this. It is normally used to gather the stack trace during a crash but it can also output it for a running program as well.

Now here's the good part: it can output the actual parameter values for each function on the stack, and even local variables, loop counters, etc.

Access event to call preventdefault from custom function originating from onclick attribute of tag

Try this:

<script>
    $("a").click(function(event) {
        event.preventDefault(); 
    });
</script>

Can I access constants in settings.py from templates in Django?

Django provides access to certain, frequently-used settings constants to the template such as settings.MEDIA_URL and some of the language settings if you use django's built in generic views or pass in a context instance keyword argument in the render_to_response shortcut function. Here's an example of each case:

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.views.generic.simple import direct_to_template

def my_generic_view(request, template='my_template.html'):
    return direct_to_template(request, template)

def more_custom_view(request, template='my_template.html'):
    return render_to_response(template, {}, context_instance=RequestContext(request))

These views will both have several frequently used settings like settings.MEDIA_URL available to the template as {{ MEDIA_URL }}, etc.

If you're looking for access to other constants in the settings, then simply unpack the constants you want and add them to the context dictionary you're using in your view function, like so:

from django.conf import settings
from django.shortcuts import render_to_response

def my_view_function(request, template='my_template.html'):
    context = {'favorite_color': settings.FAVORITE_COLOR}
    return render_to_response(template, context)

Now you can access settings.FAVORITE_COLOR on your template as {{ favorite_color }}.

MySQL Query GROUP BY day / month / year

If your search is over several years, and you still want to group monthly, I suggest:

version #1:

SELECT SQL_NO_CACHE YEAR(record_date), MONTH(record_date), COUNT(*)
FROM stats
GROUP BY DATE_FORMAT(record_date, '%Y%m')

version #2 (more efficient):

SELECT SQL_NO_CACHE YEAR(record_date), MONTH(record_date), COUNT(*)
FROM stats
GROUP BY YEAR(record_date)*100 + MONTH(record_date)

I compared these versions on a big table with 1,357,918 rows (), and the 2nd version appears to have better results.

version1 (average of 10 executes): 1.404 seconds
version2 (average of 10 executes): 0.780 seconds

(SQL_NO_CACHE key added to prevent MySQL from CACHING to queries.)

How to Kill A Session or Session ID (ASP.NET/C#)

Session.Abandon()

This marks the session as Abandoned, but the session won't actually be Abandoned at that moment, the request has to complete first.

jQuery UI: Datepicker set year range dropdown to 100 years

Try the following:-

ChangeYear:- When set to true, indicates that the cells of the previous or next month indicated in the calendar of the current month can be selected. This option is used with options.showOtherMonths set to true.

YearRange:- Specifies the range of years in the year dropdown. (Default value: “-10:+10")

Example:-

$(document).ready(function() {
    $("#date").datepicker({
        changeYear:true,
        yearRange: "2005:2015"
    });
});

See:- set year range in jquery datepicker

Contains method for a slice

Currently there's Contains function in slice package. You can read the docs here.

Sample usage :

if !slice.Contains(sliceVar, valueToFind) {
    //code here
}

Group query results by month and year in postgresql

Postgres has few types of timestamps:

timestamp without timezone - (Preferable to store UTC timestamps) You find it in multinational database storage. The client in this case will take care of the timezone offset for each country.

timestamp with timezone - The timezone offset is already included in the timestamp.

In some cases, your database does not use the timezone but you still need to group records in respect with local timezone and Daylight Saving Time (e.g. https://www.timeanddate.com/time/zone/romania/bucharest)

To add timezone you can use this example and replace the timezone offset with yours.

"your_date_column" at time zone '+03'

To add the +1 Summer Time offset specific to DST you need to check if your timestamp falls into a Summer DST. As those intervals varies with 1 or 2 days, I will use an aproximation that does not affect the end of month records, so in this case i can ignore each year exact interval.

If more precise query has to be build, then you have to add conditions to create more cases. But roughly, this will work fine in splitting data per month in respect with timezone and SummerTime when you find timestamp without timezone in your database:

SELECT 
    "id", "Product", "Sale",
    date_trunc('month', 
        CASE WHEN 
            Extract(month from t."date") > 03 AND
            Extract(day from t."date") > 26 AND
            Extract(hour from t."date") > 3 AND
            Extract(month from t."date") < 10 AND
            Extract(day from t."date") < 29 AND
            Extract(hour from t."date") < 4
        THEN 
            t."date" at time zone '+03' -- Romania TimeZone offset + DST
        ELSE
            t."date" at time zone '+02' -- Romania TimeZone offset 
        END) as "date"
FROM 
    public."Table" AS t
WHERE 1=1
    AND t."date" >= '01/07/2015 00:00:00'::TIMESTAMP WITHOUT TIME ZONE
    AND t."date" < '01/07/2017 00:00:00'::TIMESTAMP WITHOUT TIME ZONE
GROUP BY date_trunc('month', 
    CASE WHEN 
        Extract(month from t."date") > 03 AND
        Extract(day from t."date") > 26 AND
        Extract(hour from t."date") > 3 AND
        Extract(month from t."date") < 10 AND
        Extract(day from t."date") < 29 AND
        Extract(hour from t."date") < 4
    THEN 
        t."date" at time zone '+03' -- Romania TimeZone offset + DST
    ELSE
        t."date" at time zone '+02' -- Romania TimeZone offset 
    END)

Bootstrap 3 - Set Container Width to 940px Maximum for Desktops?

If you don't wish to compile bootstrap, copy the following and insert it in your custom css file. It's not recommended to change the original bootstrap css file. Also, you won't be able to modify the bootstrap original css if you are loading it from a cdn.

Paste this in your custom css file:

@media (min-width:992px)
    {
        .container{width:960px}
    }
@media (min-width:1200px)
    {
        .container{width:960px}
    }

I am here setting my container to 960px for anything that can accommodate it, and keeping the rest media sizes to default values. You can set it to 940px for this problem.

How can I shuffle the lines of a text file on the Unix command line or in a shell script?

Another awk variant:

#!/usr/bin/awk -f
# usage:
# awk -f randomize_lines.awk lines.txt
# usage after "chmod +x randomize_lines.awk":
# randomize_lines.awk lines.txt

BEGIN {
  FS = "\n";
  srand();
}

{
  lines[ rand()] = $0;
}

END {
  for( k in lines ){
    print lines[k];
  }
}

How to append output to the end of a text file

Use >> instead of > when directing output to a file:

your_command >> file_to_append_to

If file_to_append_to does not exist, it will be created.

Example:

$ echo "hello" > file
$ echo "world" >> file
$ cat file 
hello
world

Convert a string to a double - is this possible?

Use doubleval(). But be very careful about using decimals in financial transactions, and validate that user input very carefully.

What's the difference between ng-model and ng-bind

ngModel

The ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope.

This directive executes at priority level 1.

Example Plunker

JAVASCRIPT

angular.module('inputExample', [])
   .controller('ExampleController', ['$scope', function($scope) {
     $scope.val = '1';
}]);

CSS

.my-input {
    -webkit-transition:all linear 0.5s;
    transition:all linear 0.5s;
    background: transparent;
}
.my-input.ng-invalid {
    color:white;
    background: red;
}

HTML

<p id="inputDescription">
   Update input to see transitions when valid/invalid.
   Integer is a valid value.
</p>
<form name="testForm" ng-controller="ExampleController">
    <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
         aria-describedby="inputDescription" />
</form>

ngModel is responsible for:

  • Binding the view into the model, which other directives such as input, textarea or select require.
  • Providing validation behavior (i.e. required, number, email, url).
  • Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  • Setting related css classes on the element (ng-valid, ng-invalid, ng-dirty, ng-pristine, ng-touched, ng-untouched) including animations.
  • Registering the control with its parent form.

ngBind

The ngBind attribute tells Angular to replace the text content of the specified HTML element with the value of a given expression, and to update the text content when the value of that expression changes.

This directive executes at priority level 0.

Example Plunker

JAVASCRIPT

angular.module('bindExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
    $scope.name = 'Whirled';
}]);

HTML

<div ng-controller="ExampleController">
  <label>Enter name: <input type="text" ng-model="name"></label><br>
  Hello <span ng-bind="name"></span>!
</div>

ngBind is responsible for:

  • Replacing the text content of the specified HTML element with the value of a given expression.

How to show full height background image?

You can do it with the code you have, you just need to ensure that html and body are set to 100% height.

Demo: http://jsfiddle.net/kevinPHPkevin/a7eGN/

html, body {
    height:100%;
} 

body {
    background-color: white;
    background-image: url('http://www.canvaz.com/portrait/charcoal-1.jpg');
    background-size: auto 100%;
    background-repeat: no-repeat;
    background-position: left top;
}

How can I divide one column of a data frame through another?

There are a plethora of ways in which this can be done. The problem is how to make R aware of the locations of the variables you wish to divide.

Assuming

d <- read.table(text = "263807.0    1582
196190.5    1016
586689.0    3479
")
names(d) <- c("min", "count2.freq")
> d
       min count2.freq
1 263807.0        1582
2 196190.5        1016
3 586689.0        3479

My preferred way

To add the desired division as a third variable I would use transform()

> d <- transform(d, new = min / count2.freq)
> d
       min count2.freq      new
1 263807.0        1582 166.7554
2 196190.5        1016 193.1009
3 586689.0        3479 168.6373

The basic R way

If doing this in a function (i.e. you are programming) then best to avoid the sugar shown above and index. In that case any of these would do what you want

## 1. via `[` and character indexes
d[, "new"] <- d[, "min"] / d[, "count2.freq"]

## 2. via `[` with numeric indices
d[, 3] <- d[, 1] / d[, 2]

## 3. via `$`
d$new <- d$min / d$count2.freq

All of these can be used at the prompt too, but which is easier to read:

d <- transform(d, new = min / count2.freq)

or

d$new <- d$min / d$count2.freq ## or any of the above examples

Hopefully you think like I do and the first version is better ;-)

The reason we don't use the syntactic sugar of tranform() et al when programming is because of how they do their evaluation (look for the named variables). At the top level (at the prompt, working interactively) transform() et al work just fine. But buried in function calls or within a call to one of the apply() family of functions they can and often do break.

Likewise, be careful using numeric indices (## 2. above); if you change the ordering of your data, you will select the wrong variables.

The preferred way if you don't need replacement

If you are just wanting to do the division (rather than insert the result back into the data frame, then use with(), which allows us to isolate the simple expression you wish to evaluate

> with(d, min / count2.freq)
[1] 166.7554 193.1009 168.6373

This is again much cleaner code than the equivalent

> d$min / d$count2.freq
[1] 166.7554 193.1009 168.6373

as it explicitly states that "using d, execute the code min / count2.freq. Your preference may be different to mine, so I have shown all options.

.NET Console Application Exit Event

You can use the ProcessExit event of the AppDomain:

class Program
{
    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);           
        // do some work

    }

    static void CurrentDomain_ProcessExit(object sender, EventArgs e)
    {
        Console.WriteLine("exit");
    }
}

Update

Here is a full example program with an empty "message pump" running on a separate thread, that allows the user to input a quit command in the console to close down the application gracefully. After the loop in MessagePump you will probably want to clean up resources used by the thread in a nice manner. It's better to do that there than in ProcessExit for several reasons:

  • Avoid cross-threading problems; if external COM objects were created on the MessagePump thread, it's easier to deal with them there.
  • There is a time limit on ProcessExit (3 seconds by default), so if cleaning up is time consuming, it may fail if pefromed within that event handler.

Here is the code:

class Program
{
    private static bool _quitRequested = false;
    private static object _syncLock = new object();
    private static AutoResetEvent _waitHandle = new AutoResetEvent(false);

    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
        // start the message pumping thread
        Thread msgThread = new Thread(MessagePump);
        msgThread.Start();
        // read input to detect "quit" command
        string command = string.Empty;
        do
        {
            command = Console.ReadLine();
        } while (!command.Equals("quit", StringComparison.InvariantCultureIgnoreCase));
        // signal that we want to quit
        SetQuitRequested();
        // wait until the message pump says it's done
        _waitHandle.WaitOne();
        // perform any additional cleanup, logging or whatever
    }

    private static void SetQuitRequested()
    {
        lock (_syncLock)
        {
            _quitRequested = true;
        }
    }

    private static void MessagePump()
    {
        do
        {
            // act on messages
        } while (!_quitRequested);
        _waitHandle.Set();
    }

    static void CurrentDomain_ProcessExit(object sender, EventArgs e)
    {
        Console.WriteLine("exit");
    }
}

Choosing bootstrap vs material design

As far as I know you can use all mentioned technologies separately or together. It's up to you. I think you look at the problem from the wrong angle. Material Design is just the way particular elements of the page are designed, behave and put together. Material Design provides great UI/UX, but it relies on the graphic layout (HTML/CSS) rather than JS (events, interactions).

On the other hand, AngularJS and Bootstrap are front-end frameworks that can speed up your development by saving you from writing tons of code. For example, you can build web app utilizing AngularJS, but without Material Design. Or You can build simple HTML5 web page with Material Design without AngularJS or Bootstrap. Finally you can build web app that uses AngularJS with Bootstrap and with Material Design. This is the best scenario. All technologies support each other.

  1. Bootstrap = responsive page
  2. AngularJS = MVC
  3. Material Design = great UI/UX

You can check awesome material design components for AngularJS:

https://material.angularjs.org


enter image description here

Demo: https://material.angularjs.org/latest/demo/ enter image description here

CSS align images and text on same line

try to insert your img inside your h4 DEMO

<h4 class='liketext'><img style='height: 24px; width: 24px; margin-right: 4px;' src='design/like.png'/>$likes</h4>
<h4 class='liketext'> <img style='height: 24px; width: 24px; margin-right: 4px;' src='design/dislike.png'/>$dislikes</h4>?

In Unix, how do you remove everything in the current directory and below it?

This simplest safe & general solution is probably:

find -mindepth 1 -maxdepth 1 -print0 | xargs -0 rm -rf

Find elements inside forms and iframe using Java and Selenium WebDriver

When using an iframe, you will first have to switch to the iframe, before selecting the elements of that iframe

You can do it using:

driver.switchTo().frame(driver.findElement(By.id("frameId")));
//do your stuff
driver.switchTo().defaultContent();

In case if your frameId is dynamic, and you only have one iframe, you can use something like:

driver.switchTo().frame(driver.findElement(By.tagName("iframe")));

Getting a browser's name client-side

Based on is.js you can write a helper file for getting browser name like this-

const Browser = {};
const vendor = (navigator && navigator.vendor || '').toLowerCase();
const userAgent = (navigator && navigator.userAgent || '').toLowerCase();

Browser.getBrowserName = () => {
  if(isOpera()) return 'opera'; // Opera
  else if(isChrome()) return 'chrome'; // Chrome
  else if(isFirefox()) return 'firefox'; // Firefox
  else if(isSafari()) return 'safari'; // Safari
  else if(isInternetExplorer()) return 'ie'; // Internet Explorer
}


// Start Detecting browser helpers functions
function isOpera() {
  const isOpera = userAgent.match(/(?:^opera.+?version|opr)\/(\d+)/);
  return isOpera !== null;
}

function isChrome() {
  const isChrome = /google inc/.test(vendor) ? userAgent.match(/(?:chrome|crios)\/(\d+)/) : null;
  return isChrome !== null;
}

function isFirefox() {
  const isFirefox = userAgent.match(/(?:firefox|fxios)\/(\d+)/);
  return isFirefox !== null;
}

function isSafari() {
  const isSafari = userAgent.match(/version\/(\d+).+?safari/);
  return isSafari !== null;
}

function isInternetExplorer() {
  const isInternetExplorer = userAgent.match(/(?:msie |trident.+?; rv:)(\d+)/);
  return isInternetExplorer !== null;
}
// End Detecting browser helpers functions

export default Browser;

And just import this file where you need.

import Browser from './Browser.js';

const userBrowserName = Browser.getBrowserName() // return your browser name
                                                 // opera | chrome | firefox | safari | ie

Entity framework linq query Include() multiple children entities

How do you construct a LINQ to Entities query to load child objects directly, instead of calling a Reference property or Load()

There is no other way - except implementing lazy loading.

Or manual loading....

myobj = context.MyObjects.First();
myobj.ChildA.Load();
myobj.ChildB.Load();
...

How to get the date from the DatePicker widget in Android?

Try this:

 DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker1);
 int day = datePicker.getDayOfMonth();
 int month = datePicker.getMonth() + 1;
 int year = datePicker.getYear();

Input and Output binary streams using JERSEY?

I have been composing my Jersey 1.17 services the following way:

FileStreamingOutput

public class FileStreamingOutput implements StreamingOutput {

    private File file;

    public FileStreamingOutput(File file) {
        this.file = file;
    }

    @Override
    public void write(OutputStream output)
            throws IOException, WebApplicationException {
        FileInputStream input = new FileInputStream(file);
        try {
            int bytes;
            while ((bytes = input.read()) != -1) {
                output.write(bytes);
            }
        } catch (Exception e) {
            throw new WebApplicationException(e);
        } finally {
            if (output != null) output.close();
            if (input != null) input.close();
        }
    }

}

GET

@GET
@Produces("application/pdf")
public StreamingOutput getPdf(@QueryParam(value="name") String pdfFileName) {
    if (pdfFileName == null)
        throw new WebApplicationException(Response.Status.BAD_REQUEST);
    if (!pdfFileName.endsWith(".pdf")) pdfFileName = pdfFileName + ".pdf";

    File pdf = new File(Settings.basePath, pdfFileName);
    if (!pdf.exists())
        throw new WebApplicationException(Response.Status.NOT_FOUND);

    return new FileStreamingOutput(pdf);
}

And the client, if you need it:

Client

private WebResource resource;

public InputStream getPDFStream(String filename) throws IOException {
    ClientResponse response = resource.path("pdf").queryParam("name", filename)
        .type("application/pdf").get(ClientResponse.class);
    return response.getEntityInputStream();
}

Oracle JDBC ojdbc6 Jar as a Maven Dependency

Since Oracle is the licensed product, there are issue in adding maven dependency directly. To add any version of the ojdbc.jar, below 2 steps could do.

  1. Run the below command to install ojdbc.jar into local maven repository.
/opt/apache-maven/bin/mvn install:install-file
    -Dfile=<path-to-file>/ojdbc7.jar
    -DgroupId=com.oracle
    -DartifactId=ojdbc7
    -Dversion=12.1.0.1.0
    -Dpackaging=jar

This will add the dependency into local repository.

  1. Now, add the dependency in the pom file
<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc7</artifactId>
    <version>12.1.0.1.0</version>
</dependency>

TypeError("'bool' object is not iterable",) when trying to return a Boolean

Look at the traceback:

Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
    out = iter(out)
TypeError: 'bool' object is not iterable

Your code isn't iterating the value, but the code receiving it is.

The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)) or enclose it in a tuple ((False,)).

Always read the traceback: it's correct, and it's helpful.

How to convert an address to a latitude/longitude?

If you need a one off solution, you can try: https://addresstolatlong.com/

I've used it for a long time and it has worked pretty well for me.

How to measure time taken by a function to execute

To extend vsync's code further to have the ability to return the timeEnd as a value in NodeJS use this little piece of code.

console.timeEndValue = function(label) { // Add console.timeEndValue, to add a return value
   var time = this._times[label];
   if (!time) {
     throw new Error('No such label: ' + label);
   }
   var duration = Date.now() - time;
   return duration;
};

Now use the code like so:

console.time('someFunction timer');

someFunction();

var executionTime = console.timeEndValue('someFunction timer');
console.log("The execution time is " + executionTime);


This gives you more possibilities. You can store the execution time to be used for more purposes like using it in equations, or stored in a database, sent to a remote client over websockets, served on a webpage, etc.

Viewing local storage contents on IE

Since localStorage is a global object, you can add a watch in the dev tools. Just enter the dev tools, goto "watch", click on "Click to add..." and type in "localStorage".

How to simulate a real mouse click using java?

Well I had the same exact requirement, and Robot class is perfectly fine for me. It works on windows 7 and XP (tried java 6 & 7).

public static void click(int x, int y) throws AWTException{
    Robot bot = new Robot();
    bot.mouseMove(x, y);    
    bot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
    bot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
}

May be you could share the name of the program that is rejecting your click?

Multiple submit buttons on HTML form – designate one button as default

bobince's solution has the downside of creating a button which can be Tab-d over, but otherwise unusable. This can create confusion for keyboard users.

A different solution is to use the little-known form attribute:

<form>
    <input name="data" value="Form data here">
    <input type="submit" name="do-secondary-action" form="form2" value="Do secondary action">
    <input type="submit" name="submit" value="Submit">
</form>

<form id="form2"></form>

This is standard HTML, however unfortunately not supported in Internet Explorer.

Send a file via HTTP POST with C#

To send the raw file only:

using(WebClient client = new WebClient()) {
    client.UploadFile(address, filePath);
}

If you want to emulate a browser form with an <input type="file"/>, then that is harder. See this answer for a multipart/form-data answer.

Throwing exceptions from constructors

The only time you would NOT throw exceptions from constructors is if your project has a rule against using exceptions (for instance, Google doesn't like exceptions). In that case, you wouldn't want to use exceptions in your constructor any more than anywhere else, and you'd have to have an init method of some sort instead.

How to style the parent element when hovering a child element?

Another, simpler approach (to an old question)..
would be to place elements as siblings and use:

Adjacent Sibling Selector (+) or General Sibling Selector (~)

<div id="parent">
  <!-- control should come before the target... think "cascading" ! -->
  <button id="control">Hover Me!</button>
  <div id="target">I'm hovered too!</div>
</div>
#parent {
  position: relative;
  height: 100px;
}

/* Move button control to bottom. */
#control {
  position: absolute;
  bottom: 0;
}

#control:hover ~ #target {
  background: red;
}

enter image description here

Demo Fiddle here.

Firebase Permission Denied

I was facing similar issue and found out that this error was due to incorrect rules set for read/write operations for real time database. By default google firebase nowadays loads cloud store not real time database. We need to switch to real time and apply the correct rules.

enter image description here

As we can see it says cloud Firestore not real time database, once switched to correct database apply below rules:

{
   "rules": {
       ".read": true,
       ".write": true
     }
 }

Which characters need to be escaped when using Bash?

format that can be reused as shell input

Edit february 2021: ${var@Q}

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

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

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

Sample:

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

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

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

Old answer

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

printf [-v var] format [arguments]

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

Some samples:

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

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

This could be used through variables too:

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

Quick check with all (128) ascii bytes:

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

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

This must render something like:

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

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

Why ,?

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

So not always but sometime:

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

or

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

but care:

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

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

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

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

Can't install nuget package because of "Failed to initialize the PowerShell host"

I had the same problem after upgrading to Windows 10.

This worked for me

  1. Close Visual Studio
  2. Run Powershell as admin
  3. Run Set-ExecutionPolicy Unrestricted
  4. Run Visual studio as admin
  5. Clean the project and add the nuget package

If it still doesn't work try editing devenv.exe.config

Visual Studio 2013: C:\Users\<UserName>\AppData\Local\Microsoft\VisualStudio\12.0

Visual Studio 2015: C:\Users\<UserName>\AppData\Local\Microsoft\VisualStudio\14.0

Add the following

    <dependentAssembly>
        <assemblyIdentity name="System.Management.Automation" publicKeyToken="31bf3856ad364e35" />
        <publisherPolicy apply="no" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="Microsoft.PowerShell.Commands.Utility" publicKeyToken="31bf3856ad364e35" />
      <publisherPolicy apply="no" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="Microsoft.PowerShell.ConsoleHost" publicKeyToken="31bf3856ad364e35" />
      <publisherPolicy apply="no" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="Microsoft.PowerShell.Commands.Management" publicKeyToken="31bf3856ad364e35" />
      <publisherPolicy apply="no" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="Microsoft.PowerShell.Security" publicKeyToken="31bf3856ad364e35" />
      <publisherPolicy apply="no" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="Microsoft.PowerShell.Commands.Diagnostics" publicKeyToken="31bf3856ad364e35" />
      <publisherPolicy apply="no" />
    </dependentAssembly>

Placeholder in UITextView

I made a few minor modifications to bcd's solution to allow for initialization from a Xib file, text wrapping, and to maintain background color. Hopefully it will save others the trouble.

UIPlaceHolderTextView.h:

#import <Foundation/Foundation.h>
IB_DESIGNABLE
@interface UIPlaceHolderTextView : UITextView

@property (nonatomic, retain) IBInspectable NSString *placeholder;
@property (nonatomic, retain) IBInspectable UIColor *placeholderColor;

-(void)textChanged:(NSNotification*)notification;

@end

UIPlaceHolderTextView.m:

#import "UIPlaceHolderTextView.h"

@interface UIPlaceHolderTextView ()

@property (nonatomic, retain) UILabel *placeHolderLabel;

@end

@implementation UIPlaceHolderTextView

CGFloat const UI_PLACEHOLDER_TEXT_CHANGED_ANIMATION_DURATION = 0.25;

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
#if __has_feature(objc_arc)
#else
    [_placeHolderLabel release]; _placeHolderLabel = nil;
    [_placeholderColor release]; _placeholderColor = nil;
    [_placeholder release]; _placeholder = nil;
    [super dealloc];
#endif
}

- (void)awakeFromNib
{
    [super awakeFromNib];

    // Use Interface Builder User Defined Runtime Attributes to set
    // placeholder and placeholderColor in Interface Builder.
    if (!self.placeholder) {
        [self setPlaceholder:@""];
    }

    if (!self.placeholderColor) {
        [self setPlaceholderColor:[UIColor lightGrayColor]];
    }

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
}

- (id)initWithFrame:(CGRect)frame
{
    if( (self = [super initWithFrame:frame]) )
    {
        [self setPlaceholder:@""];
        [self setPlaceholderColor:[UIColor lightGrayColor]];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
    }
    return self;
}

- (void)textChanged:(NSNotification *)notification
{
    if([[self placeholder] length] == 0)
    {
        return;
    }

    [UIView animateWithDuration:UI_PLACEHOLDER_TEXT_CHANGED_ANIMATION_DURATION animations:^{
    if([[self text] length] == 0)
    {
        [[self viewWithTag:999] setAlpha:1];
    }
    else
    {
        [[self viewWithTag:999] setAlpha:0];
    }
    }];
}

- (void)setText:(NSString *)text {
    [super setText:text];
    [self textChanged:nil];
}

- (void)drawRect:(CGRect)rect
{
    if( [[self placeholder] length] > 0 )
    {
        if (_placeHolderLabel == nil )
        {
            _placeHolderLabel = [[UILabel alloc] initWithFrame:CGRectMake(8,8,self.bounds.size.width - 16,0)];
            _placeHolderLabel.lineBreakMode = NSLineBreakByWordWrapping;
            _placeHolderLabel.numberOfLines = 0;
            _placeHolderLabel.font = self.font;
            _placeHolderLabel.backgroundColor = [UIColor clearColor];
            _placeHolderLabel.textColor = self.placeholderColor;
            _placeHolderLabel.alpha = 0;
            _placeHolderLabel.tag = 999;
            [self addSubview:_placeHolderLabel];
        }

        _placeHolderLabel.text = self.placeholder;
        [_placeHolderLabel sizeToFit];
        [self sendSubviewToBack:_placeHolderLabel];
    }

    if( [[self text] length] == 0 && [[self placeholder] length] > 0 )
    {
        [[self viewWithTag:999] setAlpha:1];
    }

    [super drawRect:rect];
}

@end

Multiple left-hand assignment with JavaScript

Assignment in javascript works from right to left. var var1 = var2 = var3 = 1;.

If the value of any of these variables is 1 after this statement, then logically it must have started from the right, otherwise the value or var1 and var2 would be undefined.

You can think of it as equivalent to var var1 = (var2 = (var3 = 1)); where the inner-most set of parenthesis is evaluated first.

How can prepared statements protect from SQL injection attacks?

Here is SQL for setting up an example:

CREATE TABLE employee(name varchar, paymentType varchar, amount bigint);

INSERT INTO employee VALUES('Aaron', 'salary', 100);
INSERT INTO employee VALUES('Aaron', 'bonus', 50);
INSERT INTO employee VALUES('Bob', 'salary', 50);
INSERT INTO employee VALUES('Bob', 'bonus', 0);

The Inject class is vulnerable to SQL injection. The query is dynamically pasted together with user input. The intent of the query was to show information about Bob. Either salary or bonus, based on user input. But the malicious user manipulates the input corrupting the query by tacking on the equivalent of an 'or true' to the where clause so that everything is returned, including the information about Aaron which was supposed to be hidden.

import java.sql.*;

public class Inject {

    public static void main(String[] args) throws SQLException {

        String url = "jdbc:postgresql://localhost/postgres?user=user&password=pwd";
        Connection conn = DriverManager.getConnection(url);

        Statement stmt = conn.createStatement();
        String sql = "SELECT paymentType, amount FROM employee WHERE name = 'bob' AND paymentType='" + args[0] + "'";
        System.out.println(sql);
        ResultSet rs = stmt.executeQuery(sql);

        while (rs.next()) {
            System.out.println(rs.getString("paymentType") + " " + rs.getLong("amount"));
        }
    }
}

Running this, the first case is with normal usage, and the second with the malicious injection:

c:\temp>java Inject salary
SELECT paymentType, amount FROM employee WHERE name = 'bob' AND paymentType='salary'
salary 50

c:\temp>java Inject "salary' OR 'a'!='b"
SELECT paymentType, amount FROM employee WHERE name = 'bob' AND paymentType='salary' OR 'a'!='b'
salary 100
bonus 50
salary 50
bonus 0

You should not build your SQL statements with string concatenation of user input. Not only is it vulnerable to injection, but it has caching implications on the server as well (the statement changes, so less likely to get a SQL statement cache hit whereas the bind example is always running the same statement).

Here is an example of Binding to avoid this kind of injection:

import java.sql.*;

public class Bind {

    public static void main(String[] args) throws SQLException {

        String url = "jdbc:postgresql://localhost/postgres?user=postgres&password=postgres";
        Connection conn = DriverManager.getConnection(url);

        String sql = "SELECT paymentType, amount FROM employee WHERE name = 'bob' AND paymentType=?";
        System.out.println(sql);

        PreparedStatement stmt = conn.prepareStatement(sql);
        stmt.setString(1, args[0]);

        ResultSet rs = stmt.executeQuery();

        while (rs.next()) {
            System.out.println(rs.getString("paymentType") + " " + rs.getLong("amount"));
        }
    }
}

Running this with the same input as the previous example shows the malicious code does not work because there is no paymentType matching that string:

c:\temp>java Bind salary
SELECT paymentType, amount FROM employee WHERE name = 'bob' AND paymentType=?
salary 50

c:\temp>java Bind "salary' OR 'a'!='b"
SELECT paymentType, amount FROM employee WHERE name = 'bob' AND paymentType=?

What does 'COLLATE SQL_Latin1_General_CP1_CI_AS' do?

Please be aware that the accepted answer is a bit incomplete. Yes, at the most basic level Collation handles sorting. BUT, the comparison rules defined by the chosen Collation are used in many places outside of user queries against user data.

If "What does COLLATE SQL_Latin1_General_CP1_CI_AS do?" means "What does the COLLATE clause of CREATE DATABASE do?", then:

The COLLATE {collation_name} clause of the CREATE DATABASE statement specifies the default Collation of the Database, and not the Server; Database-level and Server-level default Collations control different things.

Server (i.e. Instance)-level controls:

  • Database-level Collation for system Databases: master, model, msdb, and tempdb.
  • Due to controlling the DB-level Collation of tempdb, it is then the default Collation for string columns in temporary tables (global and local), but not table variables.
  • Due to controlling the DB-level Collation of master, it is then the Collation used for Server-level data, such as Database names (i.e. name column in sys.databases), Login names, etc.
  • Handling of parameter / variable names
  • Handling of cursor names
  • Handling of GOTO labels
  • Default Collation used for newly created Databases when the COLLATE clause is missing

Database-level controls:

  • Default Collation used for newly created string columns (CHAR, VARCHAR, NCHAR, NVARCHAR, TEXT, and NTEXT -- but don't use TEXT or NTEXT) when the COLLATE clause is missing from the column definition. This goes for both CREATE TABLE and ALTER TABLE ... ADD statements.
  • Default Collation used for string literals (i.e. 'some text') and string variables (i.e. @StringVariable). This Collation is only ever used when comparing strings and variables to other strings and variables. When comparing strings / variables to columns, then the Collation of the column will be used.
  • The Collation used for Database-level meta-data, such as object names (i.e. sys.objects), column names (i.e. sys.columns), index names (i.e. sys.indexes), etc.
  • The Collation used for Database-level objects: tables, columns, indexes, etc.

Also:

  • ASCII is an encoding which is 8-bit (for common usage; technically "ASCII" is 7-bit with character values 0 - 127, and "ASCII Extended" is 8-bit with character values 0 - 255). This group is the same across cultures.
  • The Code Page is the "extended" part of Extended ASCII, and controls which characters are used for values 128 - 255. This group varies between each culture.
  • Latin1 does not mean "ASCII" since standard ASCII only covers values 0 - 127, and all code pages (that can be represented in SQL Server, and even NVARCHAR) map those same 128 values to the same characters.

If "What does COLLATE SQL_Latin1_General_CP1_CI_AS do?" means "What does this particular collation do?", then:

  • Because the name start with SQL_, this is a SQL Server collation, not a Windows collation. These are definitely obsolete, even if not officially deprecated, and are mainly for pre-SQL Server 2000 compatibility. Although, quite unfortunately SQL_Latin1_General_CP1_CI_AS is very common due to it being the default when installing on an OS using US English as its language. These collations should be avoided if at all possible.

    Windows collations (those with names not starting with SQL_) are newer, more functional, have consistent sorting between VARCHAR and NVARCHAR for the same values, and are being updated with additional / corrected sort weights and uppercase/lowercase mappings. These collations also don't have the potential performance problem that the SQL Server collations have: Impact on Indexes When Mixing VARCHAR and NVARCHAR Types.

  • Latin1_General is the culture / locale.
    • For NCHAR, NVARCHAR, and NTEXT data this determines the linguistic rules used for sorting and comparison.
    • For CHAR, VARCHAR, and TEXT data (columns, literals, and variables) this determines the:
      • linguistic rules used for sorting and comparison.
      • code page used to encode the characters. For example, Latin1_General collations use code page 1252, Hebrew collations use code page 1255, and so on.
  • CP{code_page} or {version}

    • For SQL Server collations: CP{code_page}, is the 8-bit code page that determines what characters map to values 128 - 255. While there are four code pages for Double-Byte Character Sets (DBCS) that can use 2-byte combinations to create more than 256 characters, these are not available for the SQL Server collations.
    • For Windows collations: {version}, while not present in all collation names, refers to the SQL Server version in which the collation was introduced (for the most part). Windows collations with no version number in the name are version 80 (meaning SQL Server 2000 as that is version 8.0). Not all versions of SQL Server come with new collations, so there are gaps in the version numbers. There are some that are 90 (for SQL Server 2005, which is version 9.0), most are 100 (for SQL Server 2008, version 10.0), and a small set has 140 (for SQL Server 2017, version 14.0).

      I said "for the most part" because the collations ending in _SC were introduced in SQL Server 2012 (version 11.0), but the underlying data wasn't new, they merely added support for supplementary characters for the built-in functions. So, those endings exist for version 90 and 100 collations, but only starting in SQL Server 2012.

  • Next you have the sensitivities, that can be in any combination of the following, but always specified in this order:
    • CS = case-sensitive or CI = case-insensitive
    • AS = accent-sensitive or AI = accent-insensitive
    • KS = Kana type-sensitive or missing = Kana type-insensitive
    • WS = width-sensitive or missing = width insensitive
    • VSS = variation selector sensitive (only available in the version 140 collations) or missing = variation selector insensitive
  • Optional last piece:

    • _SC at the end means "Supplementary Character support". The "support" only affects how the built-in functions interpret surrogate pairs (which are how supplementary characters are encoded in UTF-16). Without _SC at the end (or _140_ in the middle), built-in functions don't see a single supplementary character, but instead see two meaningless code points that make up the surrogate pair. This ending can be added to any non-binary, version 90 or 100 collation.
    • _BIN or _BIN2 at the end means "binary" sorting and comparison. Data is still stored the same, but there are no linguistic rules. This ending is never combined with any of the 5 sensitivities or _SC. _BIN is the older style, and _BIN2 is the newer, more accurate style. If using SQL Server 2005 or newer, use _BIN2. For details on the differences between _BIN and _BIN2, please see: Differences Between the Various Binary Collations (Cultures, Versions, and BIN vs BIN2).
    • _UTF8 is a new option as of SQL Server 2019. It's an 8-bit encoding that allows for Unicode data to be stored in VARCHAR and CHAR datatypes (but not the deprecated TEXT datatype). This option can only be used on collations that support supplementary characters (i.e. version 90 or 100 collations with _SC in their name, and version 140 collations). There is also a single binary _UTF8 collation (_BIN2, not _BIN).

      PLEASE NOTE: UTF-8 was designed / created for compatibility with environments / code that are set up for 8-bit encodings yet want to support Unicode. Even though there are a few scenarios where UTF-8 can provide up to 50% space savings as compared to NVARCHAR, that is a side-effect and has a cost of a slight hit to performance in many / most operations. If you need this for compatibility, then the cost is acceptable. If you want this for space-savings, you had better test, and TEST AGAIN. Testing includes all functionality, and more than just a few rows of data. Be warned that UTF-8 collations work best when ALL columns, and the database itself, are using VARCHAR data (columns, variables, string literals) with a _UTF8 collation. This is the natural state for anyone using this for compatibility, but not for those hoping to use it for space-savings. Be careful when mixing VARCHAR data using a _UTF8 collation with either VARCHAR data using non-_UTF8 collations or NVARCHAR data, as you might experience odd behavior / data loss. For more details on the new UTF-8 collations, please see: Native UTF-8 Support in SQL Server 2019: Savior or False Prophet?

How to convert from Hex to ASCII in JavaScript?

You can use this..

_x000D_
_x000D_
var asciiVal = "32343630".match(/.{1,2}/g).map(function(v){_x000D_
      return String.fromCharCode(parseInt(v, 16));_x000D_
    }).join('');_x000D_
    _x000D_
document.write(asciiVal);
_x000D_
_x000D_
_x000D_

SSL Proxy/Charles and Android trouble

For the newer emulator it might be helpful to launch from command line using:

emulator -netdelay none -netspeed full -avd <emulator_name> -http-proxy http://<ip-address>:8888

Make sure you follow @User9527's advice above as well for the rest of the setup

What is the difference between `git merge` and `git merge --no-ff`?

Merge Strategies

Explicit Merge: Creates a new merge commit. (This is what you will get if you used --no-ff.)

enter image description here

Fast Forward Merge: Forward rapidly, without creating a new commit:

enter image description here

Rebase: Establish a new base level:

enter image description here

Squash: Crush or squeeze (something) with force so that it becomes flat:

enter image description here

What is the difference between print and puts?

puts call the to_s of each argument and adds a new line to each string, if it does not end with new line. print just output each argument by calling their to_s.

for example: puts "one two": one two

{new line}

puts "one two\n": one two

{new line} #puts will not add a new line to the result, since the string ends with a new line

print "one two": one two

print "one two\n": one two

{new line}

And there is another way to output: p

For each object, directly writes obj.inspect followed by a newline to the program’s standard output.

It is helpful to output debugging message. p "aa\n\t": aa\n\t

'Linker command failed with exit code 1' when using Google Analytics via CocoaPods

Some times appeared if you declare a constant in the header file without static notation. like this

const int k = 10;

it should be:

static const int k = 10;

iOS UIImagePickerController result image orientation after upload

I achieve this by writing below a few lines of code

extension UIImage {

    public func correctlyOrientedImage() -> UIImage {
        guard imageOrientation != .up else { return self }

        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        draw(in: CGRect(origin: .zero, size: size))
        let normalizedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()

        return normalizedImage
    }
}

Saving and Reading Bitmaps/Images from Internal memory in Android

if you want to follow Android 10 practices to write in storage, check here and if you only want the images to be app specific, here for example if you want to store an image just to be used by your app:

viewModelScope.launch(Dispatchers.IO) {
            getApplication<Application>().openFileOutput(filename, Context.MODE_PRIVATE).use {
                bitmap.compress(Bitmap.CompressFormat.PNG, 50, it)
            }
        }

getApplication is a method to give you context for ViewModel and it's part of AndroidViewModel later if you want to read it:

viewModelScope.launch(Dispatchers.IO) {
            val savedBitmap = BitmapFactory.decodeStream(
                getApplication<App>().openFileInput(filename).readBytes().inputStream()
            )
        }

Difference between id and name attributes in HTML

The ID of a form input element has nothing to do with the data contained within the element. IDs are for hooking the element with JavaScript and CSS. The name attribute, however, is used in the HTTP request sent by your browser to the server as a variable name associated with the data contained in the value attribute.

For instance:

<form>
    <input type="text" name="user" value="bob">
    <input type="password" name="password" value="abcd1234">
</form>

When the form is submitted, the form data will be included in the HTTP header like this:

If you add an ID attribute, it will not change anything in the HTTP header. It will just make it easier to hook it with CSS and JavaScript.

How to get the GL library/headers?

Debian Linux (e.g. Ubuntu)

sudo apt-get update
OpenGL: sudo apt-get install libglu1-mesa-dev freeglut3-dev mesa-common-dev

Windows

Locate your Visual Studio folder for where it puts libraries and also header files, download and copy lib files to lib folder and header files to header. Then copy dll files to system32. Then your code will 100% run.

Also Windows: For all of those includes you just need to download glut32.lib, glut.h, glut32.dll.

Tools for creating Class Diagrams

I have used both Poseidon UML and Enterprise Architect and must say that I prefer Poseidon but wasn't fully satisfied with any of them.

Difference between except: and except Exception as e: in Python

Using the second form gives you a variable (named based upon the as clause, in your example e) in the except block scope with the exception object bound to it so you can use the infomration in the exception (type, message, stack trace, etc) to handle the exception in a more specially tailored manor.

Call to undefined function mysql_query() with Login

You are mixing the deprecated mysql extension with mysqli.

Try something like:

$sql = mysqli_query($success, "SELECT * FROM login WHERE username = '".$_POST['username']."' and password = '".md5($_POST['password'])."'");
$row = mysqli_num_rows($sql);

Adding padding to a tkinter widget only on one side

There are multiple ways of doing that you can use either place or grid or even the packmethod.

Sample code:

from tkinter import *
root = Tk()

l = Label(root, text="hello" )
l.pack(padx=6, pady=4) # where padx and pady represent the x and y axis respectively
# well you can also use side=LEFT inside the pack method of the label widget.

To place a widget to on basis of columns and rows , use the grid method:

but = Button(root, text="hello" )
but.grid(row=0, column=1)

Specify an SSH key for git push for a given domain

You might need to remove (or comment out) default Host configuration .ssh/config

Multi-gradient shapes

You can layer gradient shapes in the xml using a layer-list. Imagine a button with the default state as below, where the second item is semi-transparent. It adds a sort of vignetting. (Please excuse the custom-defined colours.)

<!-- Normal state. -->
<item>
    <layer-list>
        <item>  
            <shape>
                <gradient 
                    android:startColor="@color/grey_light"
                    android:endColor="@color/grey_dark"
                    android:type="linear"
                    android:angle="270"
                    android:centerColor="@color/grey_mediumtodark" />
                <stroke
                    android:width="1dp"
                    android:color="@color/grey_dark" />
                <corners
                    android:radius="5dp" />
            </shape>
        </item>
        <item>  
            <shape>
                <gradient 
                    android:startColor="#00666666"
                    android:endColor="#77666666"
                    android:type="radial"
                    android:gradientRadius="200"
                    android:centerColor="#00666666"
                    android:centerX="0.5"
                    android:centerY="0" />
                <stroke
                    android:width="1dp"
                    android:color="@color/grey_dark" />
                <corners
                    android:radius="5dp" />
            </shape>
        </item>
    </layer-list>
</item>

assign headers based on existing row in dataframe in R

Very similar to Vishnu's answer but uses the lapply to map all the data to characters then to assign them as the headers. This is really helpful if your data is imported as factors.

DF[] <- lapply(DF, as.character)
colnames(DF) <- DF[1, ]
DF <- DF[-1 ,]

note that that if you have a lot of numeric data or factors you want you'll need to convert them back. In this case it may make sense to store the character data frame, extract the row you want, and then apply it to the original data frame

tempDF <- DF
tempDF[] <- lapply(DF, as.character)
colnames(DF) <- tempDF[1, ]
DF <- DF[-1 ,]
tempDF <- NULL

Determine project root from a running node.js application

the easiest way to get the global root (assuming you use NPM to run your node.js app 'npm start', etc)

var appRoot = process.env.PWD;

If you want to cross-verify the above

Say you want to cross-check process.env.PWD with the settings of you node.js application. if you want some runtime tests to check the validity of process.env.PWD, you can cross-check it with this code (that I wrote which seems to work well). You can cross-check the name of the last folder in appRoot with the npm_package_name in your package.json file, for example:

    var path = require('path');

    var globalRoot = __dirname; //(you may have to do some substring processing if the first script you run is not in the project root, since __dirname refers to the directory that the file is in for which __dirname is called in.)

    //compare the last directory in the globalRoot path to the name of the project in your package.json file
    var folders = globalRoot.split(path.sep);
    var packageName = folders[folders.length-1];
    var pwd = process.env.PWD;
    var npmPackageName = process.env.npm_package_name;
    if(packageName !== npmPackageName){
        throw new Error('Failed check for runtime string equality between globalRoot-bottommost directory and npm_package_name.');
    }
    if(globalRoot !== pwd){
        throw new Error('Failed check for runtime string equality between globalRoot and process.env.PWD.');
    }

you can also use this NPM module: require('app-root-path') which works very well for this purpose

How do I find duplicates across multiple columns?

A little late to the game on this post, but I found this way to be pretty flexible / efficient

select 
    s1.id
    ,s1.name
    ,s1.city 
from 
    stuff s1
    ,stuff s2
Where
    s1.id <> s2.id
    and s1.name = s2.name
    and s1.city = s2.city

How to remove a column from an existing table?

If you are using C# and the Identity column is int, create a new instance of int without providing any value to it.It worked for me.

[identity_column] = new int()

Why does JSHint throw a warning if I am using const?

You can add a file named .jshintrc in your app's root with the following content to apply this setting for the whole solution:

{
    "esversion": 6
}

James' answer suggests that you can add a comment /*jshint esversion: 6 */ for each file, but it is more work than necessary if you need to control many files.

Add a column to a table, if it does not already exist

Here's another variation that worked for me.

IF NOT EXISTS (SELECT 1
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE upper(TABLE_NAME) = 'TABLENAME'
        AND upper(COLUMN_NAME) = 'COLUMNNAME')
BEGIN
    ALTER TABLE [dbo].[Person] ADD Column
END
GO

EDIT: Note that INFORMATION_SCHEMA views may not always be updated, use SYS.COLUMNS instead:

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS....

Close Current Tab

You can only close windows/tabs that you create yourself. That is, you cannot programmatically close a window/tab that the user creates.

For example, if you create a window with window.open() you can close it with window.close().

C# code to validate email address

A simple one without using Regex (which I don't like for its poor readability):

bool IsValidEmail(string email)
{
    string emailTrimed = email.Trim();

    if (!string.IsNullOrEmpty(emailTrimed))
    {
        bool hasWhitespace = emailTrimed.Contains(" ");

        int indexOfAtSign = emailTrimed.LastIndexOf('@');

        if (indexOfAtSign > 0 && !hasWhitespace)
        {
            string afterAtSign = emailTrimed.Substring(indexOfAtSign + 1);

            int indexOfDotAfterAtSign = afterAtSign.LastIndexOf('.');

            if (indexOfDotAfterAtSign > 0 && afterAtSign.Substring(indexOfDotAfterAtSign).Length > 1)
                return true;
        }
    }

    return false;
}

Examples:

It is meant to be simple and therefore it doesn't deal with rare cases like emails with bracketed domains that contain spaces (typically allowed), emails with IPv6 addresses, etc.

How do I make a PHP form that submits to self?

That will only work if register_globals is on, and it should never be on (unless of course you are defining that variable somewhere else).

Try setting the form's action attribute to ?...

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

You can also set it to be blank (""), but older WebKit versions had a bug.

Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails

try this

SET foreign_key_checks = 0;

ALTER TABLE sourcecodes_tags ADD FOREIGN KEY (sourcecode_id) REFERENCES sourcecodes (id) ON DELETE CASCADE ON UPDATE CASCADE

SET foreign_key_checks = 1;

What does the NS prefix mean?

It is the NextStep (= NS) heritage. NeXT was the computer company that Steve Jobs formed after he quit Apple in 1985, and NextStep was it's operating system (UNIX based) together with the Obj-C language and runtime. Together with it's libraries and tools, NextStep was later renamed OpenStep (which was also the name on an API that NeXT developed together with Sun), which in turn later became Cocoa.

These different names are actually quite confusing (especially since some of the names differs only in which characters are upper or lower case..), try this for an explanation:

TheMerger OpenstepConfusion

How to get controls in WPF to fill available space?

There are also some properties you can set to force a control to fill its available space when it would otherwise not do so. For example, you can say:

HorizontalContentAlignment="Stretch"

... to force the contents of a control to stretch horizontally. Or you can say:

HorizontalAlignment="Stretch"

... to force the control itself to stretch horizontally to fill its parent.

How do I get 'date-1' formatted as mm-dd-yyyy using PowerShell?

I think this is only partially true. Changing the format seems to switch the date to a string object which then has no methods like AddDays to manipulate it. So to make this work, you have to switch it back to a date. For example:

Get-Date (Get-Date).AddDays(-1) -format D

How do you specify the Java compiler version in a pom.xml file?

<project>
  [...]
  <build>
    [...]
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>(whatever version is current)</version>
        <configuration>
          <!-- or whatever version you use -->
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
    [...]
  </build>
  [...]
</project>

See the config page for the maven compiler plugin:

http://maven.apache.org/plugins/maven-compiler-plugin/examples/set-compiler-source-and-target.html

Oh, and: don't use Java 1.3.x, current versions are Java 1.7.x or 1.8.x

How can I toggle word wrap in Visual Studio?

For Visual Studio 2017 do the following:

Tools > Options > All Languages, then check or uncheck the checkbox based on your preference. As you can see in below image :

When to use std::size_t?

size_t is a very readable way to specify the size dimension of an item - length of a string, amount of bytes a pointer takes, etc. It's also portable across platforms - you'll find that 64bit and 32bit both behave nicely with system functions and size_t - something that unsigned int might not do (e.g. when should you use unsigned long

What are the advantages of Sublime Text over Notepad++ and vice-versa?

One thing that should be considered is licensing.

Notepad++ is free (as in speech and as in beer) for perpetual use, released under the GPL license, whereas Sublime Text 2 requires a license.

To quote the Sublime Text 2 website:

..a license must be purchased for continued use. There is currently no enforced time limit for the evaluation.

The same is now true of Sublime Text 3, and a paid upgrade will be needed for future versions.

Upgrade Policy A license is valid for Sublime Text 3, and includes all point updates, as well as access to prior versions (e.g., Sublime Text 2). Future major versions, such as Sublime Text 4, will be a paid upgrade.

This licensing requirement is still correct as of Dec 2019.

How to put labels over geom_bar for each bar in R with ggplot2

To add to rcs' answer, if you want to use position_dodge() with geom_bar() when x is a POSIX.ct date, you must multiply the width by 86400, e.g.,

ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) + 
 geom_bar(position = "dodge", stat = 'identity') +
 geom_text(aes(label=Number), position=position_dodge(width=0.9*86400), vjust=-0.25)

Which programming languages can be used to develop in Android?

Here's a list of languages that can be used to develop on android:

  • Java - primary android development language

  • Kotlin, language from JetBrains which received first-party support from Google, announced in Google I/O 2017

  • C++ - NDK for libraries, not apps

  • Python, bash, et. al. - Via the Scripting Environment

  • Corona- One is to use the Corona SDK . Corona is a high level SDK built on the Lua programming language. Lua is much simpler to learn than Java and the SDK takes away a lot of the pain in developing Android app.

  • Cordova - which uses HTML5, JavaScript, CSS, and can be extended with Java

  • Xamarin technology - that uses c# and in which mono is used for that. Here MonoTouch and Mono for Android are cross-platform implementations of the Common Language Infrastructure (CLI) and Common Language Specifications.

As for your second question: android is highly dependent on it's java architecture, I find it unlikely that there will be other primary development languages available any time soon. However, there's no particular reason why someone couldn't implement another language in Java (something like Jython) and use that. However, that surely won't be easier or as performant as just writing the code in Java.

correct way to use super (argument passing)

As explained in Python's super() considered super, one way is to have class eat the arguments it requires, and pass the rest on. Thus, when the call-chain reaches object, all arguments have been eaten, and object.__init__ will be called without arguments (as it expects). So your code should look like this:

class A(object):
    def __init__(self, *args, **kwargs):
        print "A"
        super(A, self).__init__(*args, **kwargs)

class B(object):
    def __init__(self, *args, **kwargs):
        print "B"
        super(B, self).__init__(*args, **kwargs)

class C(A):
    def __init__(self, arg, *args, **kwargs):
        print "C","arg=",arg
        super(C, self).__init__(*args, **kwargs)

class D(B):
    def __init__(self, arg, *args, **kwargs):
        print "D", "arg=",arg
        super(D, self).__init__(*args, **kwargs)

class E(C,D):
    def __init__(self, arg, *args, **kwargs):
        print "E", "arg=",arg
        super(E, self).__init__(*args, **kwargs)

print "MRO:", [x.__name__ for x in E.__mro__]
E(10, 20, 30)

YAML mapping values are not allowed in this context

The elements of a sequence need to be indented at the same level. Assuming you want two jobs (A and B) each with an ordered list of key value pairs, you should use:

jobs:
 - - name: A
   - schedule: "0 0/5 * 1/1 * ? *"
   - - type: mongodb.cluster
     - config:
       - host: mongodb://localhost:27017/admin?replicaSet=rs
       - minSecondaries: 2
       - minOplogHours: 100
       - maxSecondaryDelay: 120
 - - name: B
   - schedule: "0 0/5 * 1/1 * ? *"
   - - type: mongodb.cluster
     - config:
       - host: mongodb://localhost:27017/admin?replicaSet=rs
       - minSecondaries: 2
       - minOplogHours: 100
       - maxSecondaryDelay: 120

Converting the sequences of (single entry) mappings to a mapping as @Tsyvarrev does is also possible, but makes you lose the ordering.

Authenticate Jenkins CI for Github private repository

I had a similar problem with gitlab. It turns out I had restricted the users that are allowed to login via ssh. This won't affect github users, but in case people end up here for gitlab (and the like) issues, ensure you add git to the AllowUsers setting in /etc/ssh/sshd_config:

# Authentication:
LoginGraceTime 120
PermitRootLogin no
StrictModes yes
AllowUsers batman git

How to pass the password to su/sudo/ssh without overriding the TTY?

The usual solution to this problem is setuiding a helper app that performs the task requiring superuser access: http://en.wikipedia.org/wiki/Setuid

Sudo is not meant to be used offline.

Later edit: SSH can be used with private-public key authentication. If the private key does not have a passphrase, ssh can be used without prompting for a password.

How can I comment a single line in XML?

No, there is no way to comment a line in XML and have the comment end automatically on a linebreak.

XML has only one definition for a comment:

'<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'

XML forbids -- in comments to maintain compatibility with SGML.

Nested attributes unpermitted parameters

From the docs

To whitelist an entire hash of parameters, the permit! method can be used

params.require(:log_entry).permit!

Nested attributes are in the form of a hash. In my app, I have a Question.rb model accept nested attributes for an Answer.rb model (where the user creates answer choices for a question he creates). In the questions_controller, I do this

  def question_params

      params.require(:question).permit!

  end

Everything in the question hash is permitted, including the nested answer attributes. This also works if the nested attributes are in the form of an array.

Having said that, I wonder if there's a security concern with this approach because it basically permits anything that's inside the hash without specifying exactly what it is, which seems contrary to the purpose of strong parameters.

How to display the value of the bar on each bar with pyplot.barh()?

Use plt.text() to put text in the plot.

Example:

import matplotlib.pyplot as plt
N = 5
menMeans = (20, 35, 30, 35, 27)
ind = np.arange(N)

#Creating a figure with some fig size
fig, ax = plt.subplots(figsize = (10,5))
ax.bar(ind,menMeans,width=0.4)
#Now the trick is here.
#plt.text() , you need to give (x,y) location , where you want to put the numbers,
#So here index will give you x pos and data+1 will provide a little gap in y axis.
for index,data in enumerate(menMeans):
    plt.text(x=index , y =data+1 , s=f"{data}" , fontdict=dict(fontsize=20))
plt.tight_layout()
plt.show()

This will show the figure as:

bar chart with values at the top

typeof !== "undefined" vs. != null

good way:

if(typeof neverDeclared == "undefined") //no errors

But the best looking way is to check via :

if(typeof neverDeclared === typeof undefined) //also no errors and no strings

Printing a 2D array in C

...
for(int i=0;i<3;i++){ //Rows
for(int j=0;j<5;j++){ //Cols
 printf("%<...>\t",var);
}
printf("\n");
}
...

considering that <...> would be d,e,f,s,c... etc datatype... X)

Is there a command to refresh environment variables from the command prompt in Windows?

By design there isn't a built in mechanism for Windows to propagate an environment variable add/change/remove to an already running cmd.exe, either from another cmd.exe or from "My Computer -> Properties ->Advanced Settings -> Environment Variables".

If you modify or add a new environment variable outside of the scope of an existing open command prompt you either need to restart the command prompt, or, manually add using SET in the existing command prompt.

The latest accepted answer shows a partial work-around by manually refreshing all the environment variables in a script. The script handles the use case of changing environment variables globally in "My Computer...Environment Variables", but if an environment variable is changed in one cmd.exe the script will not propagate it to another running cmd.exe.

Spring Boot application.properties value not populating

Actually, For me below works fine.

@Component
public class MyBean {

   public static String prop;

   @Value("${some.prop}")
   public void setProp(String prop) {
      this.prop= prop;
   }

   public MyBean() {

   }

   @PostConstruct
   public void init() {
      System.out.println("================== " + prop + "================== ");
   }

}

Now whereever i want, just invoke

MyBean.prop

it will return value.

Which HTTP methods match up to which CRUD methods?

Create = PUT with a new URI
         POST to a base URI returning a newly created URI
Read   = GET
Update = PUT with an existing URI
Delete = DELETE

PUT can map to both Create and Update depending on the existence of the URI used with the PUT.

POST maps to Create.

Correction: POST can also map to Update although it's typically used for Create. POST can also be a partial update so we don't need the proposed PATCH method.

Is there a way to view two blocks of code from the same file simultaneously in Sublime Text?

In the nav go View => Layout => Columns:2 (alt+shift+2) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py)

It appears you can also reopen the file using the command File -> New View into File which will open the current file in a new tab

Int division: Why is the result of 1/3 == 0?

1 and 3 are integer contants and so Java does an integer division which's result is 0. If you want to write double constants you have to write 1.0 and 3.0.

ERROR in ./node_modules/css-loader?

Run this command:

npm install --save node-sass

This does the same as above. Similarly to the answer above.

HTML5 best practices; section/header/aside/article elements

I'd suggest reading the W3 wiki page about structuring HTML5:

<header> Used to contain the header content of a site. <footer> Contains the footer content of a site. <nav> Contains the navigation menu, or other navigation functionality for the page.

<article> Contains a standalone piece of content that would make
sense if syndicated as an RSS item, for example a news item.

<section> Used to either group different articles into different
purposes or subjects, or to define the different sections of a single article.

<aside> Defines a block of content that is related to the main content around it, but not central to the flow of it.

They include an image that I've cleaned up here:

html5

In code, this looks like so:

<body>
  <header></header>    
  <nav></nav>    
  <section id="sidebar"></section>    
  <section id="content"></section>    
  <aside></aside>    
  <footer></footer>
</body>

Let's explore some of the HTML5 elements in more detail.

<section>

The <section> element is for containing distinct different areas of functionality or subjects area, or breaking an article or story up into different sections. So in this case: "sidebar1" contains various useful links that will persist on every page of the site, such as "subscribe to RSS" and "Buy music from store". "main" contains the main content of this page, which is blog posts. On other pages of the site, this content will change. It is a fairly generic element, but still has way more semantic meaning than the plain old <div>.

<article>

<article> is related to <section>, but is distinctly different. Whereas <section> is for grouping distinct sections of content or functionality, <article> is for containing related individual standalone pieces of content, such as individual blog posts, videos, images or news items. Think of it this way - if you have a number of items of content, each of which would be suitable for reading on their own, and would make sense to syndicate as separate items in an RSS feed, then <article> is suitable for marking them up. In our example, <section id="main"> contains blog entries. Each blog entry would be suitable for syndicating as an item in an RSS feed, and would make sense when read on its own, out of context, therefore <article> is perfect for them:

<section id="main">
    <article><!-- first blog post --></article>        
    <article><!-- second blog post --></article>        
    <article><!-- third blog post --></article>
</section>

Simple huh? Be aware though that you can also nest sections inside articles, where it makes sense to do so. For example, if each one of these blog posts has a consistent structure of distinct sections, then you could put sections inside your articles as well. It could look something like this:

<article>
  <section id="introduction"></section>      
  <section id="content"></section>
  <section id="summary"></section>
</article>

<header> and <footer>

as we already mentioned above, the purpose of the <header> and <footer> elements is to wrap header and footer content, respectively. In our particular example the <header> element contains a logo image, and the <footer> element contains a copyright notice, but you could add more elaborate content if you wished. Also note that you can have more than one header and footer on each page - as well as the top level header and footer we have just discussed, you could also have a <header> and <footer> element nested inside each <article>, in which case they would just apply to that particular article. Adding to our above example:

<article>
  <header></header>    
  <section id="introduction"></section>      
  <section id="content"></section>      
  <section id="summary"></section>      
  <footer></footer>
</article>

<nav>

The <nav> element is for marking up the navigation links or other constructs (eg a search form) that will take you to different pages of the current site, or different areas of the current page. Other links, such as sponsored links, do not count. You can of course include headings and other structuring elements inside the <nav>, but it's not compulsory.

<aside>

you may have noticed that we used an <aside> element to markup the 2nd sidebar: the one containing latest gigs and contact details. This is perfectly appropriate, as <aside> is for marking up pieces of information that are related to the main flow, but don't fit in to it directly. And the main content in this case is all about the band! Other good choices for an <aside> would be information about the author of the blog post(s), a band biography, or a band discography with links to buy their albums.

Where does that leave <div>?

So, with all these great new elements to use on our pages, the days of the humble <div> are numbered, surely? NO. In fact, the <div> still has a perfectly valid use. You should use it when there is no other more suitable element available for grouping an area of content, which will often be when you are purely using an element to group content together for styling/visual purposes. A common example is using a <div> to wrap all of the content on the page, and then using CSS to centre all the content in the browser window, or apply a specific background image to the whole content.

java.lang.NoClassDefFoundError in junit

This error also comes if 2 versions of hamcrest-library or hamcrest-core is present in the classpath.

In the pom file, you can exclude the extra version and it works.

How to test abstract class in Java with JUnit?

My way of testing this is quite simple, within each abstractUnitTest.java. I simply create a class in the abstractUnitTest.java that extend the abstract class. And test it that way.

System.Timers.Timer vs System.Threading.Timer

System.Threading.Timer is a plain timer. It calls you back on a thread pool thread (from the worker pool).

System.Timers.Timer is a System.ComponentModel.Component that wraps a System.Threading.Timer, and provides some additional features used for dispatching on a particular thread.

System.Windows.Forms.Timer instead wraps a native message-only-HWND and uses Window Timers to raise events in that HWNDs message loop.

If your app has no UI, and you want the most light-weight and general-purpose .Net timer possible, (because you are happy figuring out your own threading/dispatching) then System.Threading.Timer is as good as it gets in the framework.

I'm not fully clear what the supposed 'not thread safe' issues with System.Threading.Timer are. Perhaps it is just same as asked in this question: Thread-safety of System.Timers.Timer vs System.Threading.Timer, or perhaps everyone just means that:

  1. it's easy to write race conditions when you're using timers. E.g. see this question: Timer (System.Threading) thread safety

  2. re-entrancy of timer notifications, where your timer event can trigger and call you back a second time before you finish processing the first event. E.g. see this question: Thread-safe execution using System.Threading.Timer and Monitor