Programs & Examples On #Correspondence

'Incorrect SET Options' Error When Building Database Project

I found the solution for this problem:

  1. Go to the Server Properties.
  2. Select the Connections tab.
  3. Check if the ansi_padding option is unchecked.

Are Git forks actually Git clones?

Forking is done when you decide to contribute to some project. You would make a copy of the entire project along with its history logs. This copy is made entirely in your repository and once you make these changes, you issue a pull request. Now its up-to the owner of the source to accept your pull request and incorporate the changes into the original code.

Git clone is an actual command that allows users to get a copy of the source. git clone [URL] This should create a copy of [URL] in your own local repository.

Import SQL dump into PostgreSQL database

Postgresql12

from sql file: pg_restore -d database < file.sql

from custom format file: pg_restore -Fc database < file.dump

Wireshark vs Firebug vs Fiddler - pros and cons?

Wireshark, Firebug, Fiddler all do similar things - capture network traffic.

  • Wireshark captures any kind of network packet. It can capture packet details below TCP/IP (HTTP is at the top). It does have filters to reduce the noise it captures.

  • Firebug tracks each request the browser page makes and captures the associated headers and the time taken for each stage of the request (DNS, receiving, sending, ...).

  • Fiddler works as an HTTP/HTTPS proxy. It captures every HTTP request the computer makes and records everything associated with it. It does allow things like converting post variables to a table form and editing/replaying requests. It doesn't, by default, capture localhost traffic in IE, see the FAQ for the workaround.

How to deal with "data of class uneval" error from ggplot2?

This could also occur if you refer to a variable in the data.frame that doesn't exist. For example, recently I forgot to tell ddply to summarize by one of my variables that I used in geom_line to specify line color. Then, ggplot didn't know where to find the variable I hadn't created in the summary table, and I got this error.

Nginx - Customizing 404 page

These answers are no longer recommended since try_files works faster than if in this context. Simply add try_files in your php location block to test if the file exists, otherwise return a 404.

location ~ \.php {
    try_files $uri =404;
    ...
}

Checking if an object is a number in C#

If your requirement is really

.ToString() would result in a string containing digits and +,-,.

and you want to use double.TryParse then you need to use the overload that takes a NumberStyles parameter, and make sure you are using the invariant culture.

For example for a number which may have a leading sign, no leading or trailing whitespace, no thousands separator and a period decimal separator, use:

NumberStyles style = 
   NumberStyles.AllowLeadingSign | 
   NumberStyles.AllowDecimalPoint | 
double.TryParse(input, style, CultureInfo.InvariantCulture, out result);

Running Selenium Webdriver with a proxy in Python

How about something like this

PROXY = "149.215.113.110:70"

webdriver.DesiredCapabilities.FIREFOX['proxy'] = {
    "httpProxy":PROXY,
    "ftpProxy":PROXY,
    "sslProxy":PROXY,
    "noProxy":None,
    "proxyType":"MANUAL",
    "class":"org.openqa.selenium.Proxy",
    "autodetect":False
}

# you have to use remote, otherwise you'll have to code it yourself in python to 
driver = webdriver.Remote("http://localhost:4444/wd/hub", webdriver.DesiredCapabilities.FIREFOX)

You can read more about it here.

How do I loop through or enumerate a JavaScript object?

A good way for looping on an enumerable JavaScript object which could be awesome and common for ReactJS is using Object.keys or Object.entries with using map function. like below:

// assume items:

const items = {
  first: { name: 'phone', price: 400 },
  second: { name: 'tv', price: 300 },
  third: { name: 'sofa', price: 250 },
};

For looping and show some UI on ReactJS act like below:

~~~
<div>
  {Object.entries(items).map(([key, ({ name, price })]) => (
    <div key={key}>
     <span>name: {name}</span>
     <span>price: {price}</span>
    </div>
  ))}
</div>

Actually, I use the destructuring assignment twice, once for getting key once for getting name and price.

Add borders to cells in POI generated Excel File

From Version 4.0.0 on RegionUtil-methods have a new signature. For example:

RegionUtil.setBorderBottom(BorderStyle.DOUBLE,
            CellRangeAddress.valueOf("A1:B7"), sheet);

How do I handle Database Connections with Dapper in .NET?

I wrap connection with the helper class:

public class ConnectionFactory
{
    private readonly string _connectionName;

    public ConnectionFactory(string connectionName)
    {
        _connectionName = connectionName;
    }

    public IDbConnection NewConnection() => new SqlConnection(_connectionName);

    #region Connection Scopes

    public TResult Scope<TResult>(Func<IDbConnection, TResult> func)
    {
        using (var connection = NewConnection())
        {
            connection.Open();
            return func(connection);
        }
    }

    public async Task<TResult> ScopeAsync<TResult>(Func<IDbConnection, Task<TResult>> funcAsync)
    {
        using (var connection = NewConnection())
        {
            connection.Open();
            return await funcAsync(connection);
        }
    }

    public void Scope(Action<IDbConnection> func)
    {
        using (var connection = NewConnection())
        {
            connection.Open();
            func(connection);
        }
    }

    public async Task ScopeAsync<TResult>(Func<IDbConnection, Task> funcAsync)
    {
        using (var connection = NewConnection())
        {
            connection.Open();
            await funcAsync(connection);
        }
    }

    #endregion Connection Scopes
}

Examples of usage:

public class PostsService
{
    protected IConnectionFactory Connection;

    // Initialization here ..

    public async Task TestPosts_Async()
    {
        // Normal way..
        var posts = Connection.Scope(cnn =>
        {
            var state = PostState.Active;
            return cnn.Query<Post>("SELECT * FROM [Posts] WHERE [State] = @state;", new { state });
        });

        // Async way..
        posts = await Connection.ScopeAsync(cnn =>
        {
            var state = PostState.Active;
            return cnn.QueryAsync<Post>("SELECT * FROM [Posts] WHERE [State] = @state;", new { state });
        });
    }
}

So I don't have to explicitly open the connection every time. Additionally, you can use it this way for the convenience' sake of the future refactoring:

var posts = Connection.Scope(cnn =>
{
    var state = PostState.Active;
    return cnn.Query<Post>($"SELECT * FROM [{TableName<Post>()}] WHERE [{nameof(Post.State)}] = @{nameof(state)};", new { state });
});

What is TableName<T>() can be found in this answer.

Why do you need to put #!/bin/bash at the beginning of a script file?

It is called a shebang. It consists of a number sign and an exclamation point character (#!), followed by the full path to the interpreter such as /bin/bash. All scripts under UNIX and Linux execute using the interpreter specified on a first line.

Remove "whitespace" between div element

You need this

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<-- I absolutely don't know why, but go ahead, and add this code snippet to your CSS -->

*{
    margin:0;
    padding:0;
}

That's it, have fun removing all those white-spaces problems.

How to add a file to the last commit in git?

If you didn't push the update in remote then the simple solution is remove last local commit using following command: git reset HEAD^. Then add all files and commit again.

Automatically running a batch file as an administrator

Use

runas /savecred /profile /user:Administrator whateveryouwanttorun.cmd

It will ask for the password the first time only. It will not ask for password again, unless the password is changed, etc.

Assigning a function to a variable

lambda should be useful for this case. For example,

  1. create function y=x+1 y=lambda x:x+1

  2. call the function y(1) then return 2.

Getting IPV4 address from a sockaddr structure

inet_ntoa() works for IPv4; inet_ntop() works for both IPv4 and IPv6.

Given an input struct sockaddr *res, here are two snippets of code (tested on macOS):

Using inet_ntoa()

#include <arpa/inet.h>

struct sockaddr_in *addr_in = (struct sockaddr_in *)res;
char *s = inet_ntoa(addr_in->sin_addr);
printf("IP address: %s\n", s);

Using inet_ntop()

#include <arpa/inet.h>
#include <stdlib.h>

char *s = NULL;
switch(res->sa_family) {
    case AF_INET: {
        struct sockaddr_in *addr_in = (struct sockaddr_in *)res;
        s = malloc(INET_ADDRSTRLEN);
        inet_ntop(AF_INET, &(addr_in->sin_addr), s, INET_ADDRSTRLEN);
        break;
    }
    case AF_INET6: {
        struct sockaddr_in6 *addr_in6 = (struct sockaddr_in6 *)res;
        s = malloc(INET6_ADDRSTRLEN);
        inet_ntop(AF_INET6, &(addr_in6->sin6_addr), s, INET6_ADDRSTRLEN);
        break;
    }
    default:
        break;
}
printf("IP address: %s\n", s);
free(s);

DataTables fixed headers misaligned with columns in wide tables

try this

this works for me... i added the css for my solution and it works... although i didnt change anything in datatable css except { border-collapse: separate;}

.dataTables_scrollHeadInner {    /*for positioning header when scrolling is applied*/
padding:0% ! important
}

How to get subarray from array?

The question is actually asking for a New array, so I believe a better solution would be to combine Abdennour TOUMI's answer with a clone function:

_x000D_
_x000D_
function clone(obj) {_x000D_
  if (null == obj || "object" != typeof obj) return obj;_x000D_
  const copy = obj.constructor();_x000D_
  for (const attr in obj) {_x000D_
    if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];_x000D_
  }_x000D_
  return copy;_x000D_
}_x000D_
_x000D_
// With the `clone()` function, you can now do the following:_x000D_
_x000D_
Array.prototype.subarray = function(start, end) {_x000D_
  if (!end) {_x000D_
    end = this.length;_x000D_
  } _x000D_
  const newArray = clone(this);_x000D_
  return newArray.slice(start, end);_x000D_
};_x000D_
_x000D_
// Without a copy you will lose your original array._x000D_
_x000D_
// **Example:**_x000D_
_x000D_
const array = [1, 2, 3, 4, 5];_x000D_
console.log(array.subarray(2)); // print the subarray [3, 4, 5, subarray: function]_x000D_
_x000D_
console.log(array); // print the original array [1, 2, 3, 4, 5, subarray: function]
_x000D_
_x000D_
_x000D_

[http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object]

Cannot access wamp server on local network

I had the same problem but mine worked fine. Turn off your firewall, antivirus. Make sure your port 80 is enabled and both pcs are set to be remotely accessed. In each pc under users, add new user using the host ip address of the other pc. Restart all services. Put your wampserver online. It should connect

How to get names of enum entries?

For me an easier, practical and direct way to understand what is going on, is that the following enumeration:

enum colors { red, green, blue };

Will be converted essentially to this:

var colors = { red: 0, green: 1, blue: 2,
               [0]: "red", [1]: "green", [2]: "blue" }

Because of this, the following will be true:

colors.red === 0
colors[colors.red] === "red"
colors["red"] === 0

This creates a easy way to get the name of an enumerated as follows:

var color: colors = colors.red;
console.log("The color selected is " + colors[color]);

It also creates a nice way to convert a string to an enumerated value.

var colorName: string = "green";
var color: colors = colors.red;
if (colorName in colors) color = colors[colorName];

The two situations above are far more common situation, because usually you are far more interested in the name of a specific value and serializing values in a generic way.

css3 transition animation on load?

start it with hover of body than It will start when the mouse first moves on the screen, which is mostly within a second after arrival, the problem here is that it will reverse when out of the screen.

html:hover #animateelementid, body:hover #animateelementid {rotate ....}

thats the best thing I can think of: http://jsfiddle.net/faVLX/

fullscreen: http://jsfiddle.net/faVLX/embedded/result/

Edit see comments below:
This will not work on any touchscreen device because there is no hover, so the user won't see the content unless they tap it. – Rich Bradshaw

CSS Input field text color of inputted text

If you want the placeholder text to be red you need to target it specifically in CSS.

Write:

input::placeholder{
  color: #f00;
}

How to remove underline from a name on hover

You can assign an id to the specific link and add CSS. See the steps below:

1.Add an id of your choice (must be a unique name; can only start with text, not a number):

<a href="/abc/xyz" id="smallLinkButton">def</a>
  1. Then add the necessary CSS as follows:

    #smallLinkButton:hover,active,visited{
    
          text-decoration: none;
          }
    

Git push results in "Authentication Failed"

I'm not really sure what I did to get this error, but doing:

git remote set-url origin https://...

didn't work for me. However:

git remote set-url origin [email protected]:user/repo

somehow worked.

How to list containers in Docker

The Docker command set is simple and holds together well:

docker stack ls
docker service ls
docker image ls
docker container ls

Teaching the aliases first is confusing. Once you understand what's going on, they can save some keystrokes:

docker images -> docker image ls
docker ps -> docker container ls
docker rmi -> docker image rm
docker rm -> docker container rm

There are several aliases in Docker. For instance:

docker rmi
docker image rm
docker image rmi
docker image remove

are all the same command (see for your self using docker help image rm).

SHA1 vs md5 vs SHA256: which to use for a PHP login?

I think using md5 or sha256 or any hash optimized for speed is perfectly fine and am very curious to hear any rebuttle other users might have. Here are my reasons

  1. If you allow users to use weak passwords such as God, love, war, peace then no matter the encryption you will still be allowing the user to type in the password not the hash and these passwords are often used first, thus this is NOT going to have anything to do with encryption.

  2. If your not using SSL or do not have a certificate then attackers listening to the traffic will be able to pull the password and any attempts at encrypting with javascript or the like is client side and easily cracked and overcome. Again this is NOT going to have anything to do with data encryption on server side.

  3. Brute force attacks will take advantage weak passwords and again because you allow the user to enter the data if you do not have the login limitation of 3 or even a little more then the problem will again NOT have anything to do with data encryption.

  4. If your database becomes compromised then most likely everything has been compromised including your hashing techniques no matter how cryptic you've made it. Again this could be a disgruntled employee XSS attack or sql injection or some other attack that has nothing to do with your password encryption.

I do believe you should still encrypt but the only thing I can see the encryption does is prevent people that already have or somehow gained access to the database from just reading out loud the password. If it is someone unauthorized to on the database then you have bigger issues to worry about that's why Sony got took because they thought an encrypted password protected everything including credit card numbers all it does is protect that one field that's it.

The only pure benefit I can see to complex encryptions of passwords in a database is to delay employees or other people that have access to the database from just reading out the passwords. So if it's a small project or something I wouldn't worry to much about security on the server side instead I would worry more about securing anything a client might send to the server such as sql injection, XSS attacks or the plethora of other ways you could be compromised. If someone disagrees I look forward to reading a way that a super encrypted password is a must from the client side.

The reason I wanted to try and make this clear is because too often people believe an encrypted password means they don't have to worry about it being compromised and they quit worrying about securing the website.

How to reset form body in bootstrap modal box?

Just find your form and clear before it opens!

    $modal = $('#modal');
    $modal.find('form')[0].reset();

Asynchronous Function Call in PHP

I dont have a direct answer, but you might want to look into these things:

Firefox "ssl_error_no_cypher_overlap" error

If you review the process of SSL negotiation at Wikipedia, you will know that at the beginning ClientHello and ServerHello messages are sent between the browser and the server.

Only if the cyphers provided in ClientHello have overlapping items on the server, ServerHello message will contain a cypher that both sides support. Otherwise, SSL connection will not be initiated as there is no common cypher.

To resolve the problem, you need to install cyphers (usually at OS level), instead of trying hard on the browser (usually the browser relies on the OS). I am familiar with Windows and IE, but I know little about Linux and Firefox, so I can only point out what's wrong but cannot deliver you a solution.

Switch tabs using Selenium WebDriver with Java

driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL,Keys.SHIFT,Keys.TAB);

This method helps in switching between multiple windows. The restricting problem with this method is that it can only be used so many times until the required window is reached. Hope it helps.

Function not defined javascript

I just went through the same problem. And found out once you have a syntax or any type of error in you javascript, the whole file don't get loaded so you cannot use any of the other functions at all.

How to modify STYLE attribute of element with known ID using JQuery

Use the CSS function from jQuery to set styles to your items :

$('#buttonId').css({ "background-color": 'brown'});

Using LIKE operator with stored procedure parameters

Your datatype for @location nchar(20) should be @location nvarchar(20), since nChar has a fixed length (filled with Spaces).
If Location is nchar too you will have to convert it:

 ... Cast(Location as nVarchar(200)) like '%'+@location+'%' ...   

To enable nullable parameters with and AND condition just use IsNull or Coalesce for comparison, which is not needed in your example using OR.

e.g. if you would like to compare for Location AND Date and Time.

@location nchar(20),
@time time,
@date date
as
select DonationsTruck.VechileId, Phone, Location, [Date], [Time]
from Vechile, DonationsTruck
where Vechile.VechileId = DonationsTruck.VechileId
and (((Location like '%'+IsNull(@location,Location)+'%')) and [Date]=IsNUll(@date,date) and [Time] = IsNull(@time,Time))

How can I update a single row in a ListView?

I used the code that provided Erik, works great, but i have a complex custom adapter for my listview and i was confronted with twice implementation of the code that updates the UI. I've tried to get the new view from my adapters getView method(the arraylist that holds the listview data has allready been updated/changed):

View cell = lvOptim.getChildAt(index - lvOptim.getFirstVisiblePosition());
if(cell!=null){
    cell = adapter.getView(index, cell, lvOptim); //public View getView(final int position, View convertView, ViewGroup parent)
    cell.startAnimation(animationLeftIn());
}

It's working well, but i dont know if this is a good practice. So i don't need to implement the code that updates the list item two times.

Is there a Newline constant defined in Java like Environment.Newline in C#?

Be aware that this property isn't as useful as many people think it is. Just because your app is running on a Windows machine, for example, doesn't mean the file it's reading will be using Windows-style line separators. Many web pages contain a mixture of "\n" and "\r\n", having been cobbled together from disparate sources. When you're reading text as a series of logical lines, you should always look for all three of the major line-separator styles: Windows ("\r\n"), Unix/Linux/OSX ("\n") and pre-OSX Mac ("\r").

When you're writing text, you should be more concerned with how the file will be used than what platform you're running on. For example, if you expect people to read the file in Windows Notepad, you should use "\r\n" because it only recognizes the one kind of separator.

Undefined Reference to

Another way to get this error is by accidentally writing the definition of something in an anonymous namespace:

foo.h:

namespace foo {
    void bar();
}

foo.cc:

namespace foo {
    namespace {  // wrong
        void bar() { cout << "hello"; };
    }
}

other.cc file:

#include "foo.h"

void baz() {
    foo::bar();
}

How do you make a deep copy of an object?

A few people have mentioned using or overriding Object.clone(). Don't do it. Object.clone() has some major problems, and its use is discouraged in most cases. Please see Item 11, from "Effective Java" by Joshua Bloch for a complete answer. I believe you can safely use Object.clone() on primitive type arrays, but apart from that you need to be judicious about properly using and overriding clone.

The schemes that rely on serialization (XML or otherwise) are kludgy.

There is no easy answer here. If you want to deep copy an object you will have to traverse the object graph and copy each child object explicitly via the object's copy constructor or a static factory method that in turn deep copies the child object. Immutables (e.g. Strings) do not need to be copied. As an aside, you should favor immutability for this reason.

How to get the response of XMLHttpRequest?

You can get it by XMLHttpRequest.responseText in XMLHttpRequest.onreadystatechange when XMLHttpRequest.readyState equals to XMLHttpRequest.DONE.

Here's an example (not compatible with IE6/7).

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        alert(xhr.responseText);
    }
}
xhr.open('GET', 'http://example.com', true);
xhr.send(null);

For better crossbrowser compatibility, not only with IE6/7, but also to cover some browser-specific memory leaks or bugs, and also for less verbosity with firing ajaxical requests, you could use jQuery.

$.get('http://example.com', function(responseText) {
    alert(responseText);
});

Note that you've to take the Same origin policy for JavaScript into account when not running at localhost. You may want to consider to create a proxy script at your domain.

getting the reason why websockets closed with close code 1006

This may be your websocket URL you are using in device are not same(You are hitting different websocket URL from android/iphonedevice )

Python script to do something at the same time every day

I spent quite a bit of time also looking to launch a simple Python program at 01:00. For some reason, I couldn't get cron to launch it and APScheduler seemed rather complex for something that should be simple. Schedule (https://pypi.python.org/pypi/schedule) seemed about right.

You will have to install their Python library:

pip install schedule

This is modified from their sample program:

import schedule
import time

def job(t):
    print "I'm working...", t
    return

schedule.every().day.at("01:00").do(job,'It is 01:00')

while True:
    schedule.run_pending()
    time.sleep(60) # wait one minute

You will need to put your own function in place of job and run it with nohup, e.g.:

nohup python2.7 MyScheduledProgram.py &

Don't forget to start it again if you reboot.

Can't create project on Netbeans 8.2

I had the same problem I installed NetBeans 8.2 on macOS High Sierra, and by default settings, NetBeans will work with the latest JDK release (currently JDK 9).

NetBeans Problem

What I did was forcing NetBeans to use JDK 8, you must config your netbeans.conf file, you can find it on:

/Applications/NetBeans/NetBeans 8.2.app/Contents/Resources/NetBeans/etc/netbeans.conf

enter image description here

You need to uncomment and update your path to JDK, you will find yours at:

/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home

enter image description here

Just save it, restart NetBeans and you are done!

How do I copy to the clipboard in JavaScript?

function copytoclipboard(element) {

    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val('0' + element).select();
    document.execCommand("copy");
    $temp.remove();
}

JavaScript array to CSV

General form is:

var ids = []; <= this is your array/collection
var csv = ids.join(",");

For your case you will have to adapt a little bit

Deploying just HTML, CSS webpage to Tomcat

There is no real need to create a war to run it from Tomcat. You can follow these steps

  1. Create a folder in webapps folder e.g. MyApp

  2. Put your html and css in that folder and name the html file, which you want to be the starting page for your application, index.html

  3. Start tomcat and point your browser to url "http://localhost:8080/MyApp". Your index.html page will pop up in the browser

Importing CommonCrypto in a Swift framework

I'm not sure if something's changed with Xcode 9.2 but it's now much simpler to achieve this. The only things I had to do are create a folder called "CommonCrypto" in my framework project directory and create two files inside it, one called "cc.h" as follows:

#include <CommonCrypto/CommonCrypto.h>
#include <CommonCrypto/CommonRandom.h>

And another called module.modulemap:

module CommonCrypto {
    export *
    header "cc.h"
}

(I don't know why you can't reference header files from the SDKROOT area directly in a modulemap file but I couldn't get it to work)

The third thing is to find the "Import Paths" setting and set to $(SRCROOT). In fact you can set it to whatever folder you want the CommonCrypto folder to be under, if you don't want it at the root level.

After this you should be able to use

import CommonCrypto

In any swift file and all the types/functions/etc. are available.

A word of warning though - if your app uses libCommonCrypto (or libcoreCrypto) it's exceptionally easy for a not-too-sophisticated hacker to attach a debugger to your app and find out what keys are being passed to these functions.

YouTube embedded video: set different thumbnail

There's a nice workaround for this in the sitepoint forums:

<div onclick="this.nextElementSibling.style.display='block'; this.style.display='none'">
   <img src="my_thumbnail.png" style="cursor:pointer" />
</div>
<div style="display:none">
    <!-- Embed code here -->
</div>

Note: To prevent having to click twice to make the video play, use autoplay=1 in the video embed code. It will start playing when the second div is displayed.

Algorithm to return all combinations of k elements from n

All said and and done here comes the O'caml code for that. Algorithm is evident from the code..

let combi n lst =
    let rec comb l c =
        if( List.length c = n) then [c] else
        match l with
        [] -> []
        | (h::t) -> (combi t (h::c))@(combi t c)
    in
        combi lst []
;;

Single Form Hide on Startup

I'm coming at this from C#, but should be very similar in vb.net.

In your main program file, in the Main method, you will have something like:

Application.Run(new MainForm());

This creates a new main form and limits the lifetime of the application to the lifetime of the main form.

However, if you remove the parameter to Application.Run(), then the application will be started with no form shown and you will be free to show and hide forms as much as you like.

Rather than hiding the form in the Load method, initialize the form before calling Application.Run(). I'm assuming the form will have a NotifyIcon on it to display an icon in the task bar - this can be displayed even if the form itself is not yet visible. Calling Form.Show() or Form.Hide() from handlers of NotifyIcon events will show and hide the form respectively.

Changing default startup directory for command prompt in Windows 7

This doesn't work for me. I've tried this both under Win7 64bit and Vista 32.

I'm using the below commandline to add this capability.

reg add "HKEY_CURRENT_USER\Software\Microsoft\Command Processor" /v AutoRun /t REG_SZ /d "IF x"%COMSPEC%"==x%CMDCMDLINE% (cd /D c:)"

Is it possible to make Font Awesome icons larger than 'fa-5x'?

Easy — just use Font Awesome 5's default fa-[size]x classes. You can scale icons up to 10x of the parent element's font-size Read the docs about icon sizing.

Examples:

<span class="fas fa-info-circle fa-6x"></span>
<span class="fas fa-info-circle fa-7x"></span>
<span class="fas fa-info-circle fa-8x"></span>
<span class="fas fa-info-circle fa-9x"></span>
<span class="fas fa-info-circle fa-10x"></span>

super() raises "TypeError: must be type, not classobj" for new-style class

You can also use class TextParser(HTMLParser, object):. This makes TextParser a new-style class, and super() can be used.

How to copy Outlook mail message into excel using VBA or Macros

New introduction 2

In the previous version of macro "SaveEmailDetails" I used this statement to find Inbox:

Set FolderTgt = CreateObject("Outlook.Application"). _
              GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)

I have since installed a newer version of Outlook and I have discovered that it does not use the default Inbox. For each of my email accounts, it created a separate store (named for the email address) each with its own Inbox. None of those Inboxes is the default.

This macro, outputs the name of the store holding the default Inbox to the Immediate Window:

Sub DsplUsernameOfDefaultStore()

  Dim NS As Outlook.NameSpace
  Dim DefaultInboxFldr As MAPIFolder

  Set NS = CreateObject("Outlook.Application").GetNamespace("MAPI")
  Set DefaultInboxFldr = NS.GetDefaultFolder(olFolderInbox)

  Debug.Print DefaultInboxFldr.Parent.Name

End Sub

On my installation, this outputs: "Outlook Data File".

I have added an extra statement to macro "SaveEmailDetails" that shows how to access the Inbox of any store.

New introduction 1

A number of people have picked up the macro below, found it useful and have contacted me directly for further advice. Following these contacts I have made a few improvements to the macro so I have posted the revised version below. I have also added a pair of macros which together will return the MAPIFolder object for any folder with the Outlook hierarchy. These are useful if you wish to access other than a default folder.

The original text referenced one question by date which linked to an earlier question. The first question has been deleted so the link has been lost. That link was to Update excel sheet based on outlook mail (closed)

Original text

There are a surprising number of variations of the question: "How do I extract data from Outlook emails to Excel workbooks?" For example, two questions up on [outlook-vba] the same question was asked on 13 August. That question references a variation from December that I attempted to answer.

For the December question, I went overboard with a two part answer. The first part was a series of teaching macros that explored the Outlook folder structure and wrote data to text files or Excel workbooks. The second part discussed how to design the extraction process. For this question Siddarth has provided an excellent, succinct answer and then a follow-up to help with the next stage.

What the questioner of every variation appears unable to understand is that showing us what the data looks like on the screen does not tell us what the text or html body looks like. This answer is an attempt to get past that problem.

The macro below is more complicated than Siddarth’s but a lot simpler that those I included in my December answer. There is more that could be added but I think this is enough to start with.

The macro creates a new Excel workbook and outputs selected properties of every email in Inbox to create this worksheet:

Example of worksheet created by macro

Near the top of the macro there is a comment containing eight hashes (#). The statement below that comment must be changed because it identifies the folder in which the Excel workbook will be created.

All other comments containing hashes suggest amendments to adapt the macro to your requirements.

How are the emails from which data is to be extracted identified? Is it the sender, the subject, a string within the body or all of these? The comments provide some help in eliminating uninteresting emails. If I understand the question correctly, an interesting email will have Subject = "Task Completed".

The comments provide no help in extracting data from interesting emails but the worksheet shows both the text and html versions of the email body if they are present. My idea is that you can see what the macro will see and start designing the extraction process.

This is not shown in the screen image above but the macro outputs two versions on the text body. The first version is unchanged which means tab, carriage return, line feed are obeyed and any non-break spaces look like spaces. In the second version, I have replaced these codes with the strings [TB], [CR], [LF] and [NBSP] so they are visible. If my understanding is correct, I would expect to see the following within the second text body:

Activity[TAB]Count[CR][LF]Open[TAB]35[CR][LF]HCQA[TAB]42[CR][LF]HCQC[TAB]60[CR][LF]HAbst[TAB]50 45 5 2 2 1[CR][LF] and so on

Extracting the values from the original of this string should not be difficult.

I would try amending my macro to output the extracted values in addition to the email’s properties. Only when I have successfully achieved this change would I attempt to write the extracted data to an existing workbook. I would also move processed emails to a different folder. I have shown where these changes must be made but give no further help. I will respond to a supplementary question if you get to the point where you need this information.

Good luck.

Latest version of macro included within the original text

Option Explicit
Public Sub SaveEmailDetails()

  ' This macro creates a new Excel workbook and writes to it details
  ' of every email in the Inbox.

  ' Lines starting with hashes either MUST be changed before running the
  ' macro or suggest changes you might consider appropriate.

  Dim AttachCount As Long
  Dim AttachDtl() As String
  Dim ExcelWkBk As Excel.Workbook
  Dim FileName As String
  Dim FolderTgt As MAPIFolder
  Dim HtmlBody As String
  Dim InterestingItem As Boolean
  Dim InxAttach As Long
  Dim InxItemCrnt As Long
  Dim PathName As String
  Dim ReceivedTime As Date
  Dim RowCrnt As Long
  Dim SenderEmailAddress As String
  Dim SenderName As String
  Dim Subject As String
  Dim TextBody As String
  Dim xlApp As Excel.Application

  ' The Excel workbook will be created in this folder.
  ' ######## Replace "C:\DataArea\SO" with the name of a folder on your disc.
  PathName = "C:\DataArea\SO"

  ' This creates a unique filename.
  ' #### If you use a version of Excel 2003, change the extension to "xls".
  FileName = Format(Now(), "yymmdd hhmmss") & ".xlsx"

  ' Open own copy of Excel
  Set xlApp = Application.CreateObject("Excel.Application")
  With xlApp
    ' .Visible = True         ' This slows your macro but helps during debugging
    .ScreenUpdating = False ' Reduces flash and increases speed
    ' Create a new workbook
    ' #### If updating an existing workbook, replace with an
    ' #### Open workbook statement.
    Set ExcelWkBk = xlApp.Workbooks.Add
    With ExcelWkBk
      ' #### None of this code will be useful if you are adding
      ' #### to an existing workbook.  However, it demonstrates a
      ' #### variety of useful statements.
      .Worksheets("Sheet1").Name = "Inbox"    ' Rename first worksheet
      With .Worksheets("Inbox")
        ' Create header line
        With .Cells(1, "A")
          .Value = "Field"
          .Font.Bold = True
        End With
        With .Cells(1, "B")
          .Value = "Value"
          .Font.Bold = True
        End With
        .Columns("A").ColumnWidth = 18
        .Columns("B").ColumnWidth = 150
      End With
    End With
    RowCrnt = 2
  End With

  ' FolderTgt is the folder I am going to search.  This statement says
  ' I want to seach the Inbox.  The value "olFolderInbox" can be replaced
  ' to allow any of the standard folders to be searched.
  ' See FindSelectedFolder() for a routine that will search for any folder.
  Set FolderTgt = CreateObject("Outlook.Application"). _
              GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
  ' #### Use the following the access a non-default Inbox.
  ' #### Change "Xxxx" to name of one of your store you want to access.
  Set FolderTgt = Session.Folders("Xxxx").Folders("Inbox")

  ' This examines the emails in reverse order. I will explain why later.
  For InxItemCrnt = FolderTgt.Items.Count To 1 Step -1
    With FolderTgt.Items.Item(InxItemCrnt)
      ' A folder can contain several types of item: mail items, meeting items,
      ' contacts, etc.  I am only interested in mail items.
      If .Class = olMail Then
        ' Save selected properties to variables
        ReceivedTime = .ReceivedTime
        Subject = .Subject
        SenderName = .SenderName
        SenderEmailAddress = .SenderEmailAddress
        TextBody = .Body
        HtmlBody = .HtmlBody
        AttachCount = .Attachments.Count
        If AttachCount > 0 Then
          ReDim AttachDtl(1 To 7, 1 To AttachCount)
          For InxAttach = 1 To AttachCount
            ' There are four types of attachment:
            '  *   olByValue       1
            '  *   olByReference   4
            '  *   olEmbeddedItem  5
            '  *   olOLE           6
            Select Case .Attachments(InxAttach).Type
              Case olByValue
            AttachDtl(1, InxAttach) = "Val"
              Case olEmbeddeditem
            AttachDtl(1, InxAttach) = "Ebd"
              Case olByReference
            AttachDtl(1, InxAttach) = "Ref"
              Case olOLE
            AttachDtl(1, InxAttach) = "OLE"
              Case Else
            AttachDtl(1, InxAttach) = "Unk"
            End Select
            ' Not all types have all properties.  This code handles
            ' those missing properties of which I am aware.  However,
            ' I have never found an attachment of type Reference or OLE.
            ' Additional code may be required for them.
            Select Case .Attachments(InxAttach).Type
              Case olEmbeddeditem
                AttachDtl(2, InxAttach) = ""
              Case Else
                AttachDtl(2, InxAttach) = .Attachments(InxAttach).PathName
            End Select
            AttachDtl(3, InxAttach) = .Attachments(InxAttach).FileName
            AttachDtl(4, InxAttach) = .Attachments(InxAttach).DisplayName
            AttachDtl(5, InxAttach) = "--"
            ' I suspect Attachment had a parent property in early versions
            ' of Outlook. It is missing from Outlook 2016.
            On Error Resume Next
            AttachDtl(5, InxAttach) = .Attachments(InxAttach).Parent
            On Error GoTo 0
            AttachDtl(6, InxAttach) = .Attachments(InxAttach).Position
            ' Class 5 is attachment.  I have never seen an attachment with
            ' a different class and do not see the purpose of this property.
            ' The code will stop here if a different class is found.
            Debug.Assert .Attachments(InxAttach).Class = 5
            AttachDtl(7, InxAttach) = .Attachments(InxAttach).Class
          Next
        End If
        InterestingItem = True
      Else
        InterestingItem = False
      End If
    End With
    ' The most used properties of the email have been loaded to variables but
    ' there are many more properies.  Press F2.  Scroll down classes until
    ' you find MailItem.  Look through the members and note the name of
    ' any properties that look useful.  Look them up using VB Help.

    ' #### You need to add code here to eliminate uninteresting items.
    ' #### For example:
    'If SenderEmailAddress <> "[email protected]" Then
    '  InterestingItem = False
    'End If
    'If InStr(Subject, "Accounts payable") = 0 Then
    '  InterestingItem = False
    'End If
    'If AttachCount = 0 Then
    '  InterestingItem = False
    'End If

    ' #### If the item is still thought to be interesting I
    ' #### suggest extracting the required data to variables here.

    ' #### You should consider moving processed emails to another
    ' #### folder.  The emails are being processed in reverse order
    ' #### to allow this removal of an email from the Inbox without
    ' #### effecting the index numbers of unprocessed emails.

    If InterestingItem Then
      With ExcelWkBk
        With .Worksheets("Inbox")
          ' #### This code creates a dividing row and then
          ' #### outputs a property per row.  Again it demonstrates
          ' #### statements that are likely to be useful in the final
          ' #### version
          ' Create dividing row between emails
          .Rows(RowCrnt).RowHeight = 5
          .Range(.Cells(RowCrnt, "A"), .Cells(RowCrnt, "B")) _
                                      .Interior.Color = RGB(0, 255, 0)
          RowCrnt = RowCrnt + 1
          .Cells(RowCrnt, "A").Value = "Sender name"
          .Cells(RowCrnt, "B").Value = SenderName
          RowCrnt = RowCrnt + 1
          .Cells(RowCrnt, "A").Value = "Sender email address"
          .Cells(RowCrnt, "B").Value = SenderEmailAddress
          RowCrnt = RowCrnt + 1
          .Cells(RowCrnt, "A").Value = "Received time"
          With .Cells(RowCrnt, "B")
            .NumberFormat = "@"
            .Value = Format(ReceivedTime, "mmmm d, yyyy h:mm")
          End With
          RowCrnt = RowCrnt + 1
          .Cells(RowCrnt, "A").Value = "Subject"
          .Cells(RowCrnt, "B").Value = Subject
          RowCrnt = RowCrnt + 1
          If AttachCount > 0 Then
            .Cells(RowCrnt, "A").Value = "Attachments"
            .Cells(RowCrnt, "B").Value = "Inx|Type|Path name|File name|Display name|Parent|Position|Class"
            RowCrnt = RowCrnt + 1
            For InxAttach = 1 To AttachCount
              .Cells(RowCrnt, "B").Value = InxAttach & "|" & _
                                           AttachDtl(1, InxAttach) & "|" & _
                                           AttachDtl(2, InxAttach) & "|" & _
                                           AttachDtl(3, InxAttach) & "|" & _
                                           AttachDtl(4, InxAttach) & "|" & _
                                           AttachDtl(5, InxAttach) & "|" & _
                                           AttachDtl(6, InxAttach) & "|" & _
                                           AttachDtl(7, InxAttach)
              RowCrnt = RowCrnt + 1
            Next
          End If
          If TextBody <> "" Then

            ' ##### This code was in the original version of the macro
            ' ##### but I did not find it as useful as the other version of
            ' ##### the text body.  See below
            ' This outputs the text body with CR, LF and TB obeyed
            'With .Cells(RowCrnt, "A")
            '  .Value = "text body"
            '  .VerticalAlignment = xlTop
            'End With
            'With .Cells(RowCrnt, "B")
            '  ' The maximum size of a cell 32,767
            '  .Value = Mid(TextBody, 1, 32700)
            '  .WrapText = True
            'End With
            'RowCrnt = RowCrnt + 1

            ' This outputs the text body with NBSP, CR, LF and TB
            ' replaced by strings.
            With .Cells(RowCrnt, "A")
              .Value = "text body"
              .VerticalAlignment = xlTop
            End With
            TextBody = Replace(TextBody, Chr(160), "[NBSP]")
            TextBody = Replace(TextBody, vbCr, "[CR]")
            TextBody = Replace(TextBody, vbLf, "[LF]")
            TextBody = Replace(TextBody, vbTab, "[TB]")
            With .Cells(RowCrnt, "B")
              ' The maximum size of a cell 32,767
              .Value = Mid(TextBody, 1, 32700)
              .WrapText = True
            End With
            RowCrnt = RowCrnt + 1
          End If

          If HtmlBody <> "" Then

            ' ##### This code was in the original version of the macro
            ' ##### but I did not find it as useful as the other version of
            ' ##### the html body.  See below
            ' This outputs the html body with CR, LF and TB obeyed
            'With .Cells(RowCrnt, "A")
            '  .Value = "Html body"
            '  .VerticalAlignment = xlTop
            'End With
            'With .Cells(RowCrnt, "B")
            '  .Value = Mid(HtmlBody, 1, 32700)
            '  .WrapText = True
            'End With
            'RowCrnt = RowCrnt + 1

            ' This outputs the html body with NBSP, CR, LF and TB
            ' replaced by strings.
            With .Cells(RowCrnt, "A")
              .Value = "Html body"
              .VerticalAlignment = xlTop
            End With
            HtmlBody = Replace(HtmlBody, Chr(160), "[NBSP]")
            HtmlBody = Replace(HtmlBody, vbCr, "[CR]")
            HtmlBody = Replace(HtmlBody, vbLf, "[LF]")
            HtmlBody = Replace(HtmlBody, vbTab, "[TB]")
            With .Cells(RowCrnt, "B")
              .Value = Mid(HtmlBody, 1, 32700)
              .WrapText = True
            End With
            RowCrnt = RowCrnt + 1

          End If
        End With
      End With
    End If
  Next

  With xlApp
    With ExcelWkBk
      ' Write new workbook to disc
      If Right(PathName, 1) <> "\" Then
        PathName = PathName & "\"
      End If
      .SaveAs FileName:=PathName & FileName
      .Close
    End With
    .Quit   ' Close our copy of Excel
  End With

  Set xlApp = Nothing       ' Clear reference to Excel

End Sub

Macros not included in original post but which some users of above macro have found useful.

Public Sub FindSelectedFolder(ByRef FolderTgt As MAPIFolder, _
                              ByVal NameTgt As String, ByVal NameSep As String)

  ' This routine (and its sub-routine) locate a folder within the hierarchy and
  ' returns it as an object of type MAPIFolder

  ' NameTgt   The name of the required folder in the format:
  '              FolderName1 NameSep FolderName2 [ NameSep FolderName3 ] ...
  '           If NameSep is "|", an example value is "Personal Folders|Inbox"
  '           FolderName1 must be an outer folder name such as
  '           "Personal Folders". The outer folder names are typically the names
  '           of PST files.  FolderName2 must be the name of a folder within
  '           Folder1; in the example "Inbox".  FolderName2 is compulsory.  This
  '           routine cannot return a PST file; only a folder within a PST file.
  '           FolderName3, FolderName4 and so on are optional and allow a folder
  '           at any depth with the hierarchy to be specified.
  ' NameSep   A character or string used to separate the folder names within
  '           NameTgt.
  ' FolderTgt On exit, the required folder.  Set to Nothing if not found.

  ' This routine initialises the search and finds the top level folder.
  ' FindSelectedSubFolder() is used to find the target folder within the
  ' top level folder.

  Dim InxFolderCrnt As Long
  Dim NameChild As String
  Dim NameCrnt As String
  Dim Pos As Long
  Dim TopLvlFolderList As Folders

  Set FolderTgt = Nothing   ' Target folder not found

  Set TopLvlFolderList = _
          CreateObject("Outlook.Application").GetNamespace("MAPI").Folders

  ' Split NameTgt into the name of folder at current level
  ' and the name of its children
  Pos = InStr(NameTgt, NameSep)
  If Pos = 0 Then
    ' I need at least a level 2 name
    Exit Sub
  End If
  NameCrnt = Mid(NameTgt, 1, Pos - 1)
  NameChild = Mid(NameTgt, Pos + 1)

  ' Look for current name.  Drop through and return nothing if name not found.
  For InxFolderCrnt = 1 To TopLvlFolderList.Count
    If NameCrnt = TopLvlFolderList(InxFolderCrnt).Name Then
      ' Have found current name. Call FindSelectedSubFolder() to
      ' look for its children
      Call FindSelectedSubFolder(TopLvlFolderList.Item(InxFolderCrnt), _
                                            FolderTgt, NameChild, NameSep)
      Exit For
    End If
  Next

End Sub
Public Sub FindSelectedSubFolder(FolderCrnt As MAPIFolder, _
                      ByRef FolderTgt As MAPIFolder, _
                      ByVal NameTgt As String, ByVal NameSep As String)

  ' See FindSelectedFolder() for an introduction to the purpose of this routine.
  ' This routine finds all folders below the top level

  ' FolderCrnt The folder to be seached for the target folder.
  ' NameTgt    The NameTgt passed to FindSelectedFolder will be of the form:
  '               A|B|C|D|E
  '            A is the name of outer folder which represents a PST file.
  '            FindSelectedFolder() removes "A|" from NameTgt and calls this
  '            routine with FolderCrnt set to folder A to search for B.
  '            When this routine finds B, it calls itself with FolderCrnt set to
  '            folder B to search for C.  Calls are nested to whatever depth are
  '            necessary.
  ' NameSep    As for FindSelectedSubFolder
  ' FolderTgt  As for FindSelectedSubFolder

  Dim InxFolderCrnt As Long
  Dim NameChild As String
  Dim NameCrnt As String
  Dim Pos As Long

  ' Split NameTgt into the name of folder at current level
  ' and the name of its children
  Pos = InStr(NameTgt, NameSep)
  If Pos = 0 Then
    NameCrnt = NameTgt
    NameChild = ""
  Else
    NameCrnt = Mid(NameTgt, 1, Pos - 1)
    NameChild = Mid(NameTgt, Pos + 1)
  End If

  ' Look for current name.  Drop through and return nothing if name not found.
  For InxFolderCrnt = 1 To FolderCrnt.Folders.Count
    If NameCrnt = FolderCrnt.Folders(InxFolderCrnt).Name Then
      ' Have found current name.
      If NameChild = "" Then
        ' Have found target folder
        Set FolderTgt = FolderCrnt.Folders(InxFolderCrnt)
      Else
        'Recurse to look for children
        Call FindSelectedSubFolder(FolderCrnt.Folders(InxFolderCrnt), _
                                            FolderTgt, NameChild, NameSep)
      End If
      Exit For
    End If
  Next

  ' If NameCrnt not found, FolderTgt will be returned unchanged.  Since it is
  ' initialised to Nothing at the beginning, that will be the returned value.

End Sub

Rails: Missing host to link to! Please provide :host parameter or set default_url_options[:host]

You can always pass host as a parameter to the URL helper:

listing_url(listing, host: request.host)

python filter list of dictionaries based on key value

You can try a list comp

>>> exampleSet = [{'type':'type1'},{'type':'type2'},{'type':'type2'}, {'type':'type3'}]
>>> keyValList = ['type2','type3']
>>> expectedResult = [d for d in exampleSet if d['type'] in keyValList]
>>> expectedResult
[{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]

Another way is by using filter

>>> list(filter(lambda d: d['type'] in keyValList, exampleSet))
[{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]

MySQL Error: : 'Access denied for user 'root'@'localhost'

Ugh- nothing worked for me! I have a CentOS 7.4 machine running mariadb 5.5.64.

What I had to do was this, right after installation of mariadb from yum;

# systemctl restart mariadb
# mysql_secure_installation

The mysql_secure_installation will take you through a number of steps, including "Set root password? [Y/n]". Just say "y" and give it a password. Answer the other questions as you wish.

Then you can get in with your password, using

# mysql -u root -p

It will survive

# systemctl restart mariadb

The Key

Then, I checked the /bin/mysql_secure_installation source code to find out how it was magically able to change the root password and none of the other answers here could. The import bit is:

do_query "UPDATE mysql.user SET Password=PASSWORD('$esc_pass') WHERE User='root';"

...It says SET Password=... and not SET authentication_string = PASSWORD.... So, the proper procedure for this version (5.5.64) is:

login using mysql -u root -p , using the password you already set.
Or, stop the database and start it with:
mysql_safe --skip-grant-tables --skip-networking &

From the mysql> prompt:

use mysql;
select host,user,password from user where user = 'root';
(observe your existing passwords for root).
UPDATE mysql.user set Password = PASSWORD('your_new_cleartext_password') where user = 'root' AND host = 'localhost';
select host,user,password from user where user = 'root';
flush privileges;
quit;

kill the running mysqld_safe. restart mariadb. Login as root: mysql -u -p. Use your new password.

If you want, you can set all the root passwords at once. I think this is wise:

mysql -u root -p
(login)
use mysql;
select host,user,password from user where user = 'root';
UPDATE mysql.user set Password = PASSWORD('your_new_cleartext_password') where user = 'root';
select host,user,password from user where user = 'root';
flush privileges;
quit;

This will perform updates on all the root passwords: ie, for "localhost", "127.0.0.1", and "::1"

In the future, when I go to RHEL8 or what have you, I will try to remember to check the /bin/mysql_secure_installation and see how the guys did it, who were the ones that configured mariadb for this OS.

How to ensure that there is a delay before a service is started in systemd?

You can create a .timer systemd unit file to control the execution of your .service unit file.

So for example, to wait for 1 minute after boot-up before starting your foo.service, create a foo.timer file in the same directory with the contents:

[Timer]
OnBootSec=1min

It is important that the service is disabled (so it doesn't start at boot), and the timer enabled, for all this to work (thanks to user tride for this):

systemctl disable foo.service
systemctl enable foo.timer

You can find quite a few more options and all information needed here: https://wiki.archlinux.org/index.php/Systemd/Timers

Get the position of a spinner in Android

The way to get the selection of the spinner is:

  spinner1.getSelectedItemPosition();

Documentation reference: http://developer.android.com/reference/android/widget/AdapterView.html#getSelectedItemPosition()

However, in your code, the one place you are referencing it is within your setOnItemSelectedListener(). It is not necessary to poll the spinner, because the onItemSelected method gets passed the position as the "position" variable.

So you could change that line to:

TestProjectActivity.this.number = position + 1;

If that does not fix the problem, please post the error message generated when your app crashes.

maxReceivedMessageSize and maxBufferSize in app.config

You need to do that on your binding, but you'll need to do it on both Client and Server. Something like:

<system.serviceModel>
    <bindings>
        <basicHttpBinding>
            <binding maxBufferSize="64000000" maxReceivedMessageSize="64000000" />
        </basicHttpBinding>
    </bindings>
</system.serviceModel>

Formatting a field using ToText in a Crystal Reports formula field

I think you are looking for ToText(CCur(@Price}/{ValuationReport.YestPrice}*100-100))

You can use CCur to convert numbers or string to Curency formats. CCur(number) or CCur(string)


I think this may be what you are looking for,

Replace (ToText(CCur({field})),"$" , "") that will give the parentheses for negative numbers

It is a little hacky, but I'm not sure CR is very kind in the ways of formatting

No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

As message shows that we need to add provider System.Data.SqlClient that's why we need to install nuget package of EntityFramework that has two dll but if we are developing only console application then we just need to add reference of EntityFramework.SqlServer.dll

Eclipse error "ADB server didn't ACK, failed to start daemon"

I had a similar issue. Killing an existing instance of the ADB process from Task Manager did not work for me.

Just few days back, I had tried to install MIPS SDK and ADT-17 earlier and Eclipse gave me the error, and I did not fix that issue.

So, now, when I got this ADB server didn't ACK, failed to start daemon... issue, I executed 'Check for Updates' in the Eclipse Help menu item. There were no updates available, but at least 'ADB server did not ACK' error disappeared.

I hope this might help in a few cases.

What SOAP client libraries exist for Python, and where is the documentation for them?

Im using SOAPpy with Python 2.5.3 in a production setting.

I had to manually edit a couple of files in SOAPpy (something about header code being in the wrong place) but other than that it worked and continues to do so very reliably.

How are environment variables used in Jenkins with Windows Batch Command?

I know nothing about Jenkins, but it looks like you are trying to access environment variables using some form of unix syntax - that won't work.

If the name of the variable is WORKSPACE, then the value is expanded in Windows batch using
%WORKSPACE%. That form of expansion is performed at parse time. For example, this will print to screen the value of WORKSPACE

echo %WORKSPACE%

If you need the value at execution time, then you need to use delayed expansion !WORKSPACE!. Delayed expansion is not normally enabled by default. Use SETLOCAL EnableDelayedExpansion to enable it. Delayed expansion is often needed because blocks of code within parentheses and/or multiple commands concatenated by &, &&, or || are parsed all at once, so a value assigned within the block cannot be read later within the same block unless you use delayed expansion.

setlocal enableDelayedExpansion
set WORKSPACE=BEFORE
(
  set WORKSPACE=AFTER
  echo Normal Expansion = %WORKSPACE%
  echo Delayed Expansion = !WORKSPACE!
)

The output of the above is

Normal Expansion = BEFORE
Delayed Expansion = AFTER

Use HELP SET or SET /? from the command line to get more information about Windows environment variables and the various expansion options. For example, it explains how to do search/replace and substring operations.

How to configure log4j to only keep log files for the last seven days?

My script based on @dogbane's answer

/etc/cron.daily/hbase

#!/bin/sh
find /var/log/hbase -type f -name "phoenix-hbase-server.log.[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]" -exec bzip2 {} ";"
find /var/log/hbase -type f -regex ".*.out.[0-9][0-9]?" -exec bzip2 {} ";"
find /var/log/hbase -type f -mtime +7 -name "*.bz2" -exec rm -f {} ";"

/etc/cron.daily/tomcat

#!/bin/sh
find /opt/tomcat/log/ -type f -mtime +1 -name "*.[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9].*log" -exec bzip2 {} ";"
find /opt/tomcat/log/ -type f -mtime +1 -name "*.[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9].txt" -exec bzip2 {} ";"
find /opt/tomcat/log/ -type f -mtime +7 -name "*.bz2" -exec rm -f {} ";"

because Tomcat rotate needs one day delay.

How do I use reflection to invoke a private method?

Could you not just have a different Draw method for each type that you want to Draw? Then call the overloaded Draw method passing in the object of type itemType to be drawn.

Your question does not make it clear whether itemType genuinely refers to objects of differing types.

Refused to load the font 'data:font/woff.....'it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src'

I was facing similar issue.

  1. You need to remove all the CSP parameter which are picked up by default and understand why each attribute is required.

font-src - is to tell the browser to load the font's from src which is specified after that. font-src: 'self' - this tells to load font family within the same origin or system. font-src: 'self' data: - this tells load font-family within the same origin and the calls made to get data:

You might also get warning "** Failed to decode downloaded font, OTS parsing error: invalid version tag **" Add the following entry in CSP.

font-src: 'self' font

This should now load with no errors.

Start thread with member function

Here is a complete example

#include <thread>
#include <iostream>

class Wrapper {
   public:
      void member1() {
          std::cout << "i am member1" << std::endl;
      }
      void member2(const char *arg1, unsigned arg2) {
          std::cout << "i am member2 and my first arg is (" << arg1 << ") and second arg is (" << arg2 << ")" << std::endl;
      }
      std::thread member1Thread() {
          return std::thread([=] { member1(); });
      }
      std::thread member2Thread(const char *arg1, unsigned arg2) {
          return std::thread([=] { member2(arg1, arg2); });
      }
};
int main(int argc, char **argv) {
   Wrapper *w = new Wrapper();
   std::thread tw1 = w->member1Thread();
   std::thread tw2 = w->member2Thread("hello", 100);
   tw1.join();
   tw2.join();
   return 0;
}

Compiling with g++ produces the following result

g++ -Wall -std=c++11 hello.cc -o hello -pthread

i am member1
i am member2 and my first arg is (hello) and second arg is (100)

Is there a difference between using a dict literal and a dict constructor?

the dict() literal is nice when you are copy pasting values from something else (none python) For example a list of environment variables. if you had a bash file, say

FOO='bar'
CABBAGE='good'

you can easily paste then into a dict() literal and add comments. It also makes it easier to do the opposite, copy into something else. Whereas the {'FOO': 'bar'} syntax is pretty unique to python and json. So if you use json a lot, you might want to use {} literals with double quotes.

add onclick function to a submit button

  1. Create a hidden button with id="hiddenBtn" and type="submit" that do the submit
  2. Change current button to type="button"
  3. set onclick of the current button call a function look like below:

    function foo() { // do something before submit ... // trigger click event of the hidden button $('#hinddenBtn').trigger("click"); }

How can I sort generic list DESC and ASC?

With Linq

var ascendingOrder = li.OrderBy(i => i);
var descendingOrder = li.OrderByDescending(i => i);

Without Linq

li.Sort((a, b) => a.CompareTo(b)); // ascending sort
li.Sort((a, b) => b.CompareTo(a)); // descending sort

Note that without Linq, the list itself is being sorted. With Linq, you're getting an ordered enumerable of the list but the list itself hasn't changed. If you want to mutate the list, you would change the Linq methods to something like

li = li.OrderBy(i => i).ToList();

Check if a key exists inside a json object

(I wanted to point this out even though I'm late to the party)
The original question you were trying to find a 'Not IN' essentially. It looks like is not supported from the research (2 links below) that I was doing.

So if you wanted to do a 'Not In':

("merchant_id" in x)
true
("merchant_id_NotInObject" in x)
false 

I'd recommend just setting that expression == to what you're looking for

if (("merchant_id" in thisSession)==false)
{
    // do nothing.
}
else 
{
    alert("yeah");
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in http://www.w3schools.com/jsref/jsref_operators.asp

How to check encoding of a CSV file

Use chardet https://github.com/chardet/chardet (documentation is short and easy to read).

Install python, then pip install chardet, at last use the command line command.

I tested under GB2312 and it's pretty accurate. (Make sure you have at least a few characters, sample with only 1 character may fail easily).

file is not reliable as you can see.

enter image description here

Angular2 - Radio Button Binding

Simplest solution and workaround:

<input name="toRent" type="radio" (click)="setToRentControl(false)">
<input name="toRent" type="radio" (click)="setToRentControl(true)">

setToRentControl(value){
    this.vm.toRent.updateValue(value);
    alert(value); //true/false
}

On postback, how can I check which control cause postback in Page_Init event

if (Request.Params["__EVENTTARGET"] != null)
{
  if (Request.Params["__EVENTTARGET"].ToString().Contains("myControlID"))
  {
    DoWhateverYouWant();
  }
}

docker entrypoint running bash script gets "permission denied"

This is a bit stupid maybe but the error message I got was Permission denied and it sent me spiralling down in a very wrong direction to attempt to solve it. (Here for example)

I haven't even added any bash script myself, I think one is added by nodejs image which I use.

FROM node:14.9.0

I was wrongly running to expose/connect the port on my local:

docker run -p 80:80 [name] . # this is wrong!

which gives

/usr/local/bin/docker-entrypoint.sh: 8: exec: .: Permission denied

But you shouldn't even have a dot in the end, it was added to documentation of another projects docker image by misstake. You should simply run:

docker run -p 80:80 [name]

I like Docker a lot but it's sad it has so many gotchas like this and not always very clear error messages...

How to create a byte array in C++?

Byte is not a standard type in C/C++, so it is represented by char.

An advantage of this is that you can treat a basic_string as a byte array allowing for safe storage and function passing. This will help you avoid the memory leaks and segmentation faults you might encounter when using the various forms of char[] and char*.

For example, this creates a string as a byte array of null values:

typedef basic_string<unsigned char> u_string;

u_string bytes = u_string(16,'\0');

This allows for standard bitwise operations with other char values, including those stored in other string variables. For example, to XOR the char values of another u_string across bytes:

u_string otherBytes = "some more chars, which are just bytes";
for(int i = 0; i < otherBytes.length(); i++)
    bytes[i%16] ^= (int)otherBytes[i];

Can I have two JavaScript onclick events in one element?

The HTML

<a href="#" id="btn">click</a>

And the javascript

// get a cross-browser function for adding events, place this in [global] or somewhere you can access it
var on = (function(){
    if (window.addEventListener) {
        return function(target, type, listener){
            target.addEventListener(type, listener, false);
        };
    }
    else {
        return function(object, sEvent, fpNotify){
            object.attachEvent("on" + sEvent, fpNotify);
        };
    }
}());

// find the element
var el = document.getElementById("btn");

// add the first listener
on(el, "click", function(){
    alert("foo");
});

// add the second listener
on(el, "click", function(){
    alert("bar");
});

This will alert both 'foo' and 'bar' when clicked.

Removing html5 required attribute with jQuery

Just:

$('#edit-submitted-first-name').removeAttr('required');?????

If you're interested in further reading take a look here.

How to check if a variable is set in Bash?

For those that are looking to check for unset or empty when in a script with set -u:

if [ -z "${var-}" ]; then
   echo "Must provide var environment variable. Exiting...."
   exit 1
fi

The regular [ -z "$var" ] check will fail with var; unbound variable if set -u but [ -z "${var-}" ] expands to empty string if var is unset without failing.

Use underscore inside Angular controllers

you can use this module -> https://github.com/jiahut/ng.lodash

this is for lodash so does underscore

How can I strip first and last double quotes?

If string is always as you show:

string[1:-1]

MySQL: What's the difference between float and double?

Perhaps this example could explain.

CREATE TABLE `test`(`fla` FLOAT,`flb` FLOAT,`dba` DOUBLE(10,2),`dbb` DOUBLE(10,2)); 

We have a table like this:

+-------+-------------+
| Field | Type        |
+-------+-------------+
| fla   | float       |
| flb   | float       |
| dba   | double(10,2)|
| dbb   | double(10,2)|
+-------+-------------+

For first difference, we try to insert a record with '1.2' to each field:

INSERT INTO `test` values (1.2,1.2,1.2,1.2);

The table showing like this:

SELECT * FROM `test`;

+------+------+------+------+
| fla  | flb  | dba  | dbb  |
+------+------+------+------+
|  1.2 |  1.2 | 1.20 | 1.20 |
+------+------+------+------+

See the difference?

We try to next example:

SELECT fla+flb, dba+dbb FROM `test`;

Hola! We can find the difference like this:

+--------------------+---------+
| fla+flb            | dba+dbb |
+--------------------+---------+
| 2.4000000953674316 |    2.40 |
+--------------------+---------+

Can I run CUDA on Intel's integrated graphics processor?

At the present time, Intel graphics chips do not support CUDA. It is possible that, in the nearest future, these chips will support OpenCL (which is a standard that is very similar to CUDA), but this is not guaranteed and their current drivers do not support OpenCL either. (There is an Intel OpenCL SDK available, but, at the present time, it does not give you access to the GPU.)

Newest Intel processors (Sandy Bridge) have a GPU integrated into the CPU core. Your processor may be a previous-generation version, in which case "Intel(HD) graphics" is an independent chip.

PHP and MySQL Select a Single Value

mysql_* extension has been deprecated in 2013 and removed completely from PHP in 2018. You have two alternatives PDO or MySQLi.

PDO

The simpler option is PDO which has a neat helper function fetchColumn():

$stmt = $pdo->prepare("SELECT id FROM Users WHERE username=?");
$stmt->execute([ $_GET["username"] ]);
$value = $stmt->fetchColumn();

Proper PDO tutorial

MySQLi

You can do the same with MySQLi, but it is more complicated:

$stmt = $mysqliConn->prepare('SELECT id FROM Users WHERE username=?');
$stmt->bind_param("s", $_GET["username"]);
$stmt->execute();
$data = $stmt->get_result()->fetch_assoc();
$value = $data ? $data['id'] : null;

fetch_assoc() could return NULL if there are no rows returned from the DB, which is why I check with ternary if there was any data returned.

The program can’t start because MSVCR71.dll is missing from your computer. Try reinstalling the program to fix this program

MY SOLUTION!!!!!!! I fixed this problem when I was trying to install business objects. When the installer failed to register .dll's I inputted the MSVCR71.dll into both system32 and sysWOW64 then clicked retry. Installation finished. I did try adding this in before and after install but, install still failed.

How to define Singleton in TypeScript

This is probably the longest process to make a singleton in typescript, but in larger applications is the one that has worked better for me.

First you need a Singleton class in, let's say, "./utils/Singleton.ts":

module utils {
    export class Singleton {
        private _initialized: boolean;

        private _setSingleton(): void {
            if (this._initialized) throw Error('Singleton is already initialized.');
            this._initialized = true;
        }

        get setSingleton() { return this._setSingleton; }
    }
}

Now imagine you need a Router singleton "./navigation/Router.ts":

/// <reference path="../utils/Singleton.ts" />

module navigation {
    class RouterClass extends utils.Singleton {
        // NOTICE RouterClass extends from utils.Singleton
        // and that it isn't exportable.

        private _init(): void {
            // This method will be your "construtor" now,
            // to avoid double initialization, don't forget
            // the parent class setSingleton method!.
            this.setSingleton();

            // Initialization stuff.
        }

        // Expose _init method.
        get init { return this.init; }
    }

    // THIS IS IT!! Export a new RouterClass, that no
    // one can instantiate ever again!.
    export var Router: RouterClass = new RouterClass();
}

Nice!, now initialize or import wherever you need:

/// <reference path="./navigation/Router.ts" />

import router = navigation.Router;

router.init();
router.init(); // Throws error!.

The nice thing about doing singletons this way is that you still use all the beauty of typescript classes, it gives you nice intellisense, the singleton logic keeps someway separated and it's easy to remove if needed.

jQuery .load() call doesn't execute JavaScript in loaded HTML file

Well I had the same problem that only seemed to happen for Firefox, and I couldn't use another JQuery command except for .load() since I was modifying the front-end on exisitng PHP files...

Anyways, after using the .load() command, I embedded my JQuery script within the external HTML that was getting loaded in, and it seemed to work. I don't understand why the JS that I loaded at the top of the main document didn't work for the new content however...

WooCommerce: Finding the products in database

The following tables are store WooCommerce products database :

  • wp_posts -

    The core of the WordPress data is the posts. It is stored a post_type like product or variable_product.

  • wp_postmeta-

    Each post features information called the meta data and it is stored in the wp_postmeta. Some plugins may add their own information to this table like WooCommerce plugin store product_id of product in wp_postmeta table.

Product categories, subcategories stored in this table :

  • wp_terms
  • wp_termmeta
  • wp_term_taxonomy
  • wp_term_relationships
  • wp_woocommerce_termmeta

following Query Return a list of product categories

SELECT wp_terms.* 
    FROM wp_terms 
    LEFT JOIN wp_term_taxonomy ON wp_terms.term_id = wp_term_taxonomy.term_id
    WHERE wp_term_taxonomy.taxonomy = 'product_cat';

for more reference -

Declare variable MySQL trigger

Agree with neubert about the DECLARE statements, this will fix syntax error. But I would suggest you to avoid using openning cursors, they may be slow.

For your task: use INSERT...SELECT statement which will help you to copy data from one table to another using only one query.

INSERT ... SELECT Syntax.

Android: TextView: Remove spacing and padding on top and bottom

I remove the spacing in my custom view -- NoPaddingTextView.

https://github.com/SenhLinsh/NoPaddingTextView

enter image description here

package com.linsh.nopaddingtextview;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.widget.TextView;

/**
 * Created by Senh Linsh on 17/3/27.
 */

public class NoPaddingTextView extends TextView {

    private int mAdditionalPadding;

    public NoPaddingTextView(Context context) {
        super(context);
        init();
    }


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

    private void init() {
        setIncludeFontPadding(false);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int yOff = -mAdditionalPadding / 6;
        canvas.translate(0, yOff);
        super.onDraw(canvas);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        getAdditionalPadding();

        int mode = MeasureSpec.getMode(heightMeasureSpec);
        if (mode != MeasureSpec.EXACTLY) {
            int measureHeight = measureHeight(getText().toString(), widthMeasureSpec);

            int height = measureHeight - mAdditionalPadding;
            height += getPaddingTop() + getPaddingBottom();
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    private int measureHeight(String text, int widthMeasureSpec) {
        float textSize = getTextSize();

        TextView textView = new TextView(getContext());
        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
        textView.setText(text);
        textView.measure(widthMeasureSpec, 0);
        return textView.getMeasuredHeight();
    }

    private int getAdditionalPadding() {
        float textSize = getTextSize();

        TextView textView = new TextView(getContext());
        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
        textView.setLines(1);
        textView.measure(0, 0);
        int measuredHeight = textView.getMeasuredHeight();
        if (measuredHeight - textSize > 0) {
            mAdditionalPadding = (int) (measuredHeight - textSize);
            Log.v("NoPaddingTextView", "onMeasure: height=" + measuredHeight + " textSize=" + textSize + " mAdditionalPadding=" + mAdditionalPadding);
        }
        return mAdditionalPadding;
    }
}

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

Explicitly cast it as a double

double g = 1.0/3.0

This happens because Java uses the integer division operation for 1 and 3 since you entered them as integer constants.

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens on line 102

You didn't bind all your bindings here

$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate     FROM comments WHERE articleid = :art 
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";

$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );

You've declared a binding called :numRows but you never actually bind anything to it.

UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion

Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.

In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)

Find files and tar them (with spaces)

If you have multiple files or directories and you want to zip them into independent *.gz file you can do this. Optional -type f -atime

find -name "httpd-log*.txt" -type f -mtime +1 -exec tar -vzcf {}.gz {} \;

This will compress

httpd-log01.txt
httpd-log02.txt

to

httpd-log01.txt.gz
httpd-log02.txt.gz

join on multiple columns

Below is the structure of SQL that you may write. You can do multiple joins by using "AND" or "OR".

Select TableA.Col1, TableA.Col2, TableB.Val
FROM TableA, 
INNER JOIN TableB
 ON TableA.Col1 = TableB.Col1 OR TableA.Col2 = TableB.Col2

Android: why setVisibility(View.GONE); or setVisibility(View.INVISIBLE); do not work

In my case I found that simply clearing the animation on the view before setting the visibility to GONE works.

dp2.clearAnimation();
dp2.setVisibility(View.GONE);

I had a similar issue where I toggle between two views, one of which must always start off as GONE - But when I displayed the views again, it was displaying over the first view even if setVisibility(GONE) was called. Clearing the animation before setting the view to GONE worked.

How do I choose the URL for my Spring Boot webapp?

In your src/main/resources put an application.properties or application.yml and put a server.contextPath in there.

server.contextPath=/your/context/here

When starting your application the application will be available at http://localhost:8080/your/context/here.

For a comprehensive list of properties to set see Appendix A. of the Spring Boot reference guide.

Instead of putting it in the application.properties you can also pass it as a system property when starting your application

java -jar yourapp.jar -Dserver.contextPath=/your/path/here

Set cursor position on contentEditable <div>

You can leverage selectNodeContents which is supported by modern browsers.

var el = document.getElementById('idOfYoursContentEditable');
var selection = window.getSelection();
var range = document.createRange();
selection.removeAllRanges();
range.selectNodeContents(el);
range.collapse(false);
selection.addRange(range);
el.focus();

80-characters / right margin line in Sublime Text 3

Yes, it is possible both in Sublime Text 2 and 3 (which you should really upgrade to if you haven't already). Select View ? Ruler ? 80 (there are several other options there as well). If you like to actually wrap your text at 80 columns, select View ? Word Wrap Column ? 80. Make sure that View ? Word Wrap is selected.

To make your selections permanent (the default for all opened files or views), open Preferences ? Settings—User and use any of the following rules:

{
    // set vertical rulers in specified columns.
    // Use "rulers": [80] for just one ruler
    // default value is []
    "rulers": [80, 100, 120],

    // turn on word wrap for source and text
    // default value is "auto", which means off for source and on for text
    "word_wrap": true,

    // set word wrapping at this column
    // default value is 0, meaning wrapping occurs at window width
    "wrap_width": 80
}

These settings can also be used in a .sublime-project file to set defaults on a per-project basis, or in a syntax-specific .sublime-settings file if you only want them to apply to files written in a certain language (Python.sublime-settings vs. JavaScript.sublime-settings, for example). Access these settings files by opening a file with the desired syntax, then selecting Preferences ? Settings—More ? Syntax Specific—User.

As always, if you have multiple entries in your settings file, separate them with commas , except for after the last one. The entire content should be enclosed in curly braces { }. Basically, make sure it's valid JSON.

If you'd like a key combo to automatically set the ruler at 80 for a particular view/file, or you are interested in learning how to set the value without using the mouse, please see my answer here.

Finally, as mentioned in another answer, you really should be using a monospace font in order for your code to line up correctly. Other types of fonts have variable-width letters, which means one 80-character line may not appear to be the same length as another 80-character line with different content, and your indentations will look all messed up. Sublime has monospace fonts set by default, but you can of course choose any one you want. Personally, I really like Liberation Mono. It has glyphs to support many different languages and Unicode characters, looks good at a variety of different sizes, and (most importantly for a programming font) clearly differentiates between 0 and O (digit zero and capital letter oh) and 1 and l (digit one and lowercase letter ell), which not all monospace fonts do, unfortunately. Version 2.0 and later of the font are licensed under the open-source SIL Open Font License 1.1 (here is the FAQ).

What is the difference between the kernel space and the user space?

Memory get's divided into two distinct areas:

  • The user space, which is a set of locations where normal user processes run (i.e everything other than the kernel). The role of the kernel is to manage applications running in this space from messing with each other, and the machine.
  • The kernel space, which is the location where the code of the kernel is stored, and executes under.

Processes running under the user space have access only to a limited part of memory, whereas the kernel has access to all of the memory. Processes running in user space also don't have access to the kernel space. User space processes can only access a small part of the kernel via an interface exposed by the kernel - the system calls.If a process performs a system call, a software interrupt is sent to the kernel, which then dispatches the appropriate interrupt handler and continues its work after the handler has finished.

Transparent ARGB hex value

If you have your hex value, and your just wondering what the value for the alpha would be, this snippet may help:

_x000D_
_x000D_
const alphaToHex = (alpha => {_x000D_
  if (alpha > 1 || alpha < 0 || isNaN(alpha)) {_x000D_
    throw new Error('The argument must be a number between 0 and 1');_x000D_
  }_x000D_
  return Math.ceil(255 * alpha).toString(16).toUpperCase();_x000D_
})_x000D_
_x000D_
console.log(alphaToHex(0.45));
_x000D_
_x000D_
_x000D_

How to bind an enum to a combobox control in WPF?

I like for all objects that I'm binding to be defined in my ViewModel, so I try to avoid using <ObjectDataProvider> in the xaml when possible.

My solution uses no data defined in the View and no code-behind. Only a DataBinding, a reusable ValueConverter, a method to get a collection of descriptions for any Enum type, and a single property in the ViewModel to bind to.

When I want to bind an Enum to a ComboBox the text I want to display never matches the values of the Enum, so I use the [Description()] attribute to give it the text that I actually want to see in the ComboBox. If I had an enum of days of the week, it would look something like this:

public enum DayOfWeek
{
  // add an optional blank value for default/no selection
  [Description("")]
  NOT_SET = 0,
  [Description("Sunday")]
  SUNDAY,
  [Description("Monday")]
  MONDAY,
  ...
}

First I created helper class with a couple methods to deal with enums. One method gets a description for a specific value, the other method gets all values and their descriptions for a type.

public static class EnumHelper
{
  public static string Description(this Enum value)
  {
    var attributes = value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
    if (attributes.Any())
      return (attributes.First() as DescriptionAttribute).Description;

    // If no description is found, the least we can do is replace underscores with spaces
    // You can add your own custom default formatting logic here
    TextInfo ti = CultureInfo.CurrentCulture.TextInfo;
    return ti.ToTitleCase(ti.ToLower(value.ToString().Replace("_", " ")));
  }

  public static IEnumerable<ValueDescription> GetAllValuesAndDescriptions(Type t)
  {
    if (!t.IsEnum)
      throw new ArgumentException($"{nameof(t)} must be an enum type");

    return Enum.GetValues(t).Cast<Enum>().Select((e) => new ValueDescription() { Value = e, Description = e.Description() }).ToList();
  }
}

Next, we create a ValueConverter. Inheriting from MarkupExtension makes it easier to use in XAML so we don't have to declare it as a resource.

[ValueConversion(typeof(Enum), typeof(IEnumerable<ValueDescription>))]
public class EnumToCollectionConverter : MarkupExtension, IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
    return EnumHelper.GetAllValuesAndDescriptions(value.GetType());
  }
  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
    return null;
  }
  public override object ProvideValue(IServiceProvider serviceProvider)
  {
    return this;
  }
}

My ViewModel only needs 1 property that my View can bind to for both the SelectedValue and ItemsSource of the combobox:

private DayOfWeek dayOfWeek;

public DayOfWeek SelectedDay
{
  get { return dayOfWeek; }
  set
  {
    if (dayOfWeek != value)
    {
      dayOfWeek = value;
      OnPropertyChanged(nameof(SelectedDay));
    }
  }
}

And finally to bind the ComboBox view (using the ValueConverter in the ItemsSource binding)...

<ComboBox ItemsSource="{Binding Path=SelectedDay, Converter={x:EnumToCollectionConverter}, Mode=OneTime}"
          SelectedValuePath="Value"
          DisplayMemberPath="Description"
          SelectedValue="{Binding Path=SelectedDay}" />

To implement this solution you only need to copy my EnumHelper class and EnumToCollectionConverter class. They will work with any enums. Also, I didn't include it here, but the ValueDescription class is just a simple class with 2 public object properties, one called Value, one called Description. You can create that yourself or you can change the code to use a Tuple<object, object> or KeyValuePair<object, object>

How do I order my SQLITE database in descending order, for an android app?

public List getExpensesList(){
    SQLiteDatabase db = this.getWritableDatabase();

    List<String> expenses_list = new ArrayList<String>();
    String selectQuery = "SELECT * FROM " + TABLE_NAME ;

    Cursor cursor = db.rawQuery(selectQuery, null);
    try{
        if (cursor.moveToLast()) {

            do{
                String info = cursor.getString(cursor.getColumnIndex(KEY_DESCRIPTION));
                expenses_list.add(info);
            }while (cursor.moveToPrevious());
        }
    }finally{
        cursor.close();
    }
    return expenses_list;
}

This is my way of reading the record from database for list view in descending order. Move the cursor to last and move to previous record after each record is fetched. Hope this helps~

Constants in Objective-C

I use a singleton class, so that I can mock the class and change the constants if necessary for testing. The constants class looks like this:

#import <Foundation/Foundation.h>

@interface iCode_Framework : NSObject

@property (readonly, nonatomic) unsigned int iBufCapacity;
@property (readonly, nonatomic) unsigned int iPort;
@property (readonly, nonatomic) NSString * urlStr;

@end

#import "iCode_Framework.h"

static iCode_Framework * instance;

@implementation iCode_Framework

@dynamic iBufCapacity;
@dynamic iPort;
@dynamic urlStr;

- (unsigned int)iBufCapacity
{
    return 1024u;
};

- (unsigned int)iPort
{
    return 1978u;
};

- (NSString *)urlStr
{
    return @"localhost";
};

+ (void)initialize
{
    if (!instance) {
        instance = [[super allocWithZone:NULL] init];
    }
}

+ (id)allocWithZone:(NSZone * const)notUsed
{
    return instance;
}

@end

And it is used like this (note the use of a shorthand for the constants c - it saves typing [[Constants alloc] init] every time):

#import "iCode_FrameworkTests.h"
#import "iCode_Framework.h"

static iCode_Framework * c; // Shorthand

@implementation iCode_FrameworkTests

+ (void)initialize
{
    c  = [[iCode_Framework alloc] init]; // Used like normal class; easy to mock!
}

- (void)testSingleton
{
    STAssertNotNil(c, nil);
    STAssertEqualObjects(c, [iCode_Framework alloc], nil);
    STAssertEquals(c.iBufCapacity, 1024u, nil);
}

@end

C++ style cast from unsigned char * to const char *

char * and const unsigned char * are considered unrelated types. So you want to use reinterpret_cast.

But if you were going from const unsigned char* to a non const type you'd need to use const_cast first. reinterpret_cast cannot cast away a const or volatile qualification.

how to create Socket connection in Android?

Simple socket server app example

I've already posted a client example at: https://stackoverflow.com/a/35971718/895245 , so here goes a server example.

This example app runs a server that returns a ROT-1 cypher of the input.

You would then need to add an Exit button + some sleep delays, but this should get you started.

To play with it:

Android sockets are the same as Java's, except we have to deal with some permission issues.

src/com/cirosantilli/android_cheat/socket/Main.java

package com.cirosantilli.android_cheat.socket;

import android.app.Activity;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Main extends Activity {
    static final String TAG = "AndroidCheatSocket";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(Main.TAG, "onCreate");
        Main.this.startService(new Intent(Main.this, MyService.class));
    }

    public static class MyService extends IntentService {
        public MyService() {
            super("MyService");
        }
        @Override
        protected void onHandleIntent(Intent intent) {
            Log.d(Main.TAG, "onHandleIntent");
            final int port = 12345;
            ServerSocket listener = null;
            try {
                listener = new ServerSocket(port);
                Log.d(Main.TAG, String.format("listening on port = %d", port));
                while (true) {
                    Log.d(Main.TAG, "waiting for client");
                    Socket socket = listener.accept();
                    Log.d(Main.TAG, String.format("client connected from: %s", socket.getRemoteSocketAddress().toString()));
                    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    PrintStream out = new PrintStream(socket.getOutputStream());
                    for (String inputLine; (inputLine = in.readLine()) != null;) {
                        Log.d(Main.TAG, "received");
                        Log.d(Main.TAG, inputLine);
                        StringBuilder outputStringBuilder = new StringBuilder("");
                        char inputLineChars[] = inputLine.toCharArray();
                        for (char c : inputLineChars)
                            outputStringBuilder.append(Character.toChars(c + 1));
                        out.println(outputStringBuilder);
                    }
                }
            } catch(IOException e) {
                Log.d(Main.TAG, e.toString());
            }
        }
    }
}

We need a Service or other background method or else: How do I fix android.os.NetworkOnMainThreadException?

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.cirosantilli.android_cheat.socket"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="22" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:label="AndroidCheatsocket">
        <activity android:name="Main">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".Main$MyService" />
    </application>
</manifest>

We must add: <uses-permission android:name="android.permission.INTERNET" /> or else: Java socket IOException - permission denied

On GitHub with a build.xml: https://github.com/cirosantilli/android-cheat/tree/92de020d0b708549a444ebd9f881de7b240b3fbc/socket

In C#, why is String a reference type that behaves like a value type?

Isn't just as simple as Strings are made up of characters arrays. I look at strings as character arrays[]. Therefore they are on the heap because the reference memory location is stored on the stack and points to the beginning of the array's memory location on the heap. The string size is not known before it is allocated ...perfect for the heap.

That is why a string is really immutable because when you change it even if it is of the same size the compiler doesn't know that and has to allocate a new array and assign characters to the positions in the array. It makes sense if you think of strings as a way that languages protect you from having to allocate memory on the fly (read C like programming)

Force download a pdf link using javascript/ajax/jquery

Here is the perfect example of downloading a file using javaScript.

Usage: download_file(fileURL, fileName);

How to read barcodes with the camera on Android?

Here is a sample code: my app uses ZXing Barcode Scanner.

  1. You need these 2 classes: IntentIntegrator and IntentResult

  2. Call scanner (e.g. OnClickListener, OnMenuItemSelected...), "PRODUCT_MODE" - it scans standard 1D barcodes (you can add more).:

    IntentIntegrator.initiateScan(this, 
               "Warning", 
               "ZXing Barcode Scanner is not installed, download?",
               "Yes", "No",
               "PRODUCT_MODE");
    
  3. Get barcode as a result:

    public void onActivityResult(int requestCode, int resultCode, Intent intent) {  
      switch (requestCode) {
      case IntentIntegrator.REQUEST_CODE:
         if (resultCode == Activity.RESULT_OK) {
    
            IntentResult intentResult = 
               IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
    
            if (intentResult != null) {
    
               String contents = intentResult.getContents();
               String format = intentResult.getFormatName();
    
               this.elemQuery.setText(contents);
               this.resume = false;
               Log.d("SEARCH_EAN", "OK, EAN: " + contents + ", FORMAT: " + format);
            } else {
               Log.e("SEARCH_EAN", "IntentResult je NULL!");
            }
         } else if (resultCode == Activity.RESULT_CANCELED) {
            Log.e("SEARCH_EAN", "CANCEL");
         }
      }
    }
    

contents holds barcode number

Removing whitespace from strings in Java

The easiest way to do this is by using the org.apache.commons.lang3.StringUtils class of commons-lang3 library such as "commons-lang3-3.1.jar" for example.

Use the static method "StringUtils.deleteWhitespace(String str)" on your input string & it will return you a string after removing all the white spaces from it. I tried your example string "name=john age=13 year=2001" & it returned me exactly the string that you wanted - "name=johnage=13year=2001". Hope this helps.

What is HTML5 ARIA?

ARIA stands for Accessible Rich Internet Applications.

WAI-ARIA is an incredibly powerful technology that allows developers to easily describe the purpose, state and other functionality of visually rich user interfaces - in a way that can be understood by Assistive Technology. WAI-ARIA has finally been integrated into the current working draft of the HTML 5 specification.

And if you are wondering what WAI-ARIA is, its the same thing.

Please note the terms WAI-ARIA and ARIA refer to the same thing. However, it is more correct to use WAI-ARIA to acknowledge its origins in WAI.

WAI = Web Accessibility Initiative

From the looks of it, ARIA is used for assistive technologies and mostly screen reading.

Most of your doubts will be cleared if you read this article

http://www.w3.org/TR/aria-in-html/

Vue is not defined

I found two main problems with that implementation. First, when you import the vue.js script you use type="JavaScript" as content-type which is wrong. You should remove this type parameter because by default script tags have text/javascript as default content-type. Or, just replace the type parameter with the correct content-type which is type="text/javascript".

The second problem is that your script is embedded in the same HTML file means that it may be triggered first and probably the vue.js file was not loaded yet. You can fix this using a jQuery snippet $(function(){ /* ... */ }); or adding a javascript function as shown in this example:

_x000D_
_x000D_
// Verifies if the document is ready_x000D_
function ready(f) {_x000D_
  /in/.test(document.readyState) ? setTimeout('ready(' + f + ')', 9) : f();_x000D_
}_x000D_
_x000D_
ready(function() {_x000D_
  var demo = new Vue({_x000D_
    el: '#demo',_x000D_
    data: {_x000D_
      message: 'Hello Vue.js!'_x000D_
    }_x000D_
  })_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
<div id="demo">_x000D_
  <p>{{message}}</p>_x000D_
  <input v-model="message">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Manage toolbar's navigation and back button from fragment in android

First you add the Navigation back button

   getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);

Then, add the Method in your HostActivity.

 @Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId()==android.R.id.home)
    {
        super.onBackPressed();
        Toast.makeText(this, "OnBAckPressed Works", Toast.LENGTH_SHORT).show();
    }

    return super.onOptionsItemSelected(item);
}

Try this, definitely work.

How do I hide anchor text without hiding the anchor?

Mini tip:

I had the following scenario:

<a href="/page/">My link text
:after
</a>

I hided the text with font-size: 0, so I could use a FontAwesome icon for it. This worked on Chrome 36, Firefox 31 and IE9+.

I wouldn't recommend color: transparent because the text stil exists and is selectable. Using line-height: 0px didn't allow me to use :after. Maybe because my element was a inline-block.

Visibility: hidden: Didn't allow me to use :after.

text-indent: -9999px;: Also moved the :after element

What does .shape[] do in "for i in range(Y.shape[0])"?

In python, Suppose you have loaded up the data in some variable train:

train = pandas.read_csv('file_name')
>>> train
train([[ 1.,  2.,  3.],
        [ 5.,  1.,  2.]],)

I want to check what are the dimensions of the 'file_name'. I have stored the file in train

>>>train.shape
(2,3)
>>>train.shape[0]              # will display number of rows
2
>>>train.shape[1]              # will display number of columns
3

How to set ID using javascript?

Do you mean like this?

var hello1 = document.getElementById('hello1');
hello1.id = btoa(hello1.id);

To further the example, say you wanted to get all elements with the class 'abc'. We can use querySelectorAll() to accomplish this:

HTML

<div class="abc"></div>
<div class="abc"></div>

JS

var abcElements = document.querySelectorAll('.abc');

// Set their ids
for (var i = 0; i < abcElements.length; i++)
    abcElements[i].id = 'abc-' + i;

This will assign the ID 'abc-<index number>' to each element. So it would come out like this:

<div class="abc" id="abc-0"></div>
<div class="abc" id="abc-1"></div>

To create an element and assign an id we can use document.createElement() and then appendChild().

var div = document.createElement('div');
div.id = 'hello1';

var body = document.querySelector('body');
body.appendChild(div);

Update

You can set the id on your element like this if your script is in your HTML file.

<input id="{{str(product["avt"]["fto"])}}" >
<span>New price :</span>
<span class="assign-me">

<script type="text/javascript">
    var s = document.getElementsByClassName('assign-me')[0];
    s.id = btoa({{str(produit["avt"]["fto"])}});
</script>

Your requirements still aren't 100% clear though.

Installing packages in Sublime Text 2

Try using Sublime Package Control to install your packages.

Also take a look at these tips

How do I prevent Conda from activating the base environment by default?

So in the end I found that if I commented out the Conda initialisation block like so:

# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
# __conda_setup="$('/Users/geoff/anaconda2/bin/conda' 'shell.bash' 'hook' 2> /dev/null)"
# if [ $? -eq 0 ]; then
    # eval "$__conda_setup"
# else
if [ -f "/Users/geoff/anaconda2/etc/profile.d/conda.sh" ]; then
    . "/Users/geoff/anaconda2/etc/profile.d/conda.sh"
else
    export PATH="/Users/geoff/anaconda2/bin:$PATH"
fi
# fi
# unset __conda_setup
# <<< conda initialize <<<

It works exactly how I want. That is, Conda is available to activate an environment if I want, but doesn't activate by default.

Facebook user url by id

As of now (NOV-2019), graph.api V5.0

graph API says, refer graph api

A link to the person's Timeline. The link will only resolve if the person clicking the link is logged into Facebook and is a friend of the person whose profile is being viewed.

doc

Java: How to convert a File object to a String object in java?

Use a library like Guava or Commons / IO. They have oneliner methods.

Guava:

Files.toString(file, charset);

Commons / IO:

FileUtils.readFileToString(file, charset);

Without such a library, I'd write a helper method, something like this:

public String readFile(File file, Charset charset) throws IOException {
    return new String(Files.readAllBytes(file.toPath()), charset);
}

bootstrap responsive table content wrapping

EDIT

I think the reason that your table is not responsive to start with was you did not wrap in .container, .row and .col-md-x classes like this one

<div class="container">
   <div class="row">
     <div class="col-md-12">
     <!-- or use any other number .col-md- -->
         <div class="table-responsive">
             <div class="table">
             </div>
         </div>
     </div>
   </div>
</div>

With this, you can still use <p> tags and even make it responsive.

Please see the Bootply example here

Jquery Date picker Default Date

While the defaultDate does not set the widget. What is needed is something like:

$(".datepicker").datepicker({
    showButtonPanel: true,
    numberOfMonths: 2

});

$(".datepicker[value='']").datepicker("setDate", "-0d"); 

When to use static classes in C#

For C# 3.0, extension methods may only exist in top-level static classes.

making matplotlib scatter plots from dataframes in Python's pandas

I will recommend to use an alternative method using seaborn which more powerful tool for data plotting. You can use seaborn scatterplot and define colum 3 as hue and size.

Working code:

import pandas as pd
import seaborn as sns
import numpy as np

#creating sample data 
sample_data={'col_name_1':np.random.rand(20),
      'col_name_2': np.random.rand(20),'col_name_3': np.arange(20)*100}
df= pd.DataFrame(sample_data)
sns.scatterplot(x="col_name_1", y="col_name_2", data=df, hue="col_name_3",size="col_name_3")

enter image description here

Remove specific rows from a data frame

 X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
  Variable1 Variable2
1        11         2
2        14         3
3        12         1
4        15         4
> X[X$Variable1!=11 & X$Variable1!=12, ]
  Variable1 Variable2
2        14         3
4        15         4
> X[ ! X$Variable1 %in% c(11,12), ]
  Variable1 Variable2
2        14         3
4        15         4

You can functionalize this however you like.

Android ADB devices unauthorized

I suppose you have enabled On-device Developer Options in your smartphone? If not you can take a look at the steps provided by Android, http://developer.android.com/tools/device.html#developer-device-options

Relative path to absolute path in C#?

This worked for me.

//used in an ASP.NET MVC app
private const string BatchFilePath = "/MyBatchFileDirectory/Mybatchfiles.bat"; 
var batchFile = HttpContext.Current.Server.MapPath(BatchFilePath);

Passing a variable from one php include file to another: global vs. not

When including files in PHP, it acts like the code exists within the file they are being included from. Imagine copy and pasting the code from within each of your included files directly into your index.php. That is how PHP works with includes.

So, in your example, since you've set a variable called $name in your front.inc file, and then included both front.inc and end.inc in your index.php, you will be able to echo the variable $name anywhere after the include of front.inc within your index.php. Again, PHP processes your index.php as if the code from the two files you are including are part of the file.

When you place an echo within an included file, to a variable that is not defined within itself, you're not going to get a result because it is treated separately then any other included file.

In other words, to do the behavior you're expecting, you will need to define it as a global.

Why is "cursor:pointer" effect in CSS not working

Just happened to me, and in my case it was due to a CSS rule pointer-events: none; which was set on a parent element and I forgot about it.

This caused any pointer events to be just ignored, which includes the cursor.

To fix this, you can just set the style to allow pointer events:

.about>span{
    cursor:pointer;
    pointer-events: auto;
}

Or directly in the element:

<span style="pointer-events: auto;">...</span>

Refused to execute script, strict MIME type checking is enabled?

Python flask

On Windows, it uses data from the registry, so if the "Content Type" value in HKCR/.js is not set to the proper MIME type it can cause your problem.

Open regedit and go to the HKEY_CLASSES_ROOT make sure the key .js/Content Type has the value text/javascript

C:\>reg query HKCR\.js /v "Content Type"

HKEY_CLASSES_ROOT\.js
    Content Type    REG_SZ    text/javascript

How to define servlet filter order of execution using annotations in WAR

  1. Make the servlet filter implement the spring Ordered interface.
  2. Declare the servlet filter bean manually in configuration class.
    import org.springframework.core.Ordered;
    
    public class MyFilter implements Filter, Ordered {

        @Override
        public void init(FilterConfig filterConfig) {
            // do something
        }

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            // do something
        }

        @Override
        public void destroy() {
            // do something
        }

        @Override
        public int getOrder() {
            return -100;
        }
    }


    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;

    @Configuration
    @ComponentScan
    public class MyAutoConfiguration {

        @Bean
        public MyFilter myFilter() {
            return new MyFilter();
        }
    }

Finding duplicate values in MySQL

Select column_name, column_name1,column_name2, count(1) as temp from table_name group by column_name having temp > 1

MongoDb shuts down with Code 100

In my case, I got a similar error and it was happening because I had run mongod with the root user and that had created a log file only accessible by the root. I could fix this by changing the ownership from root to the user you normally run mongod from. The log file was in /var/lib/mongodb/journal/

Traits vs. interfaces

Public Service Announcement:

I want to state for the record that I believe traits are almost always a code smell and should be avoided in favor of composition. It's my opinion that single inheritance is frequently abused to the point of being an anti-pattern and multiple inheritance only compounds this problem. You'll be much better served in most cases by favoring composition over inheritance (be it single or multiple). If you're still interested in traits and their relationship to interfaces, read on ...


Let's start by saying this:

Object-Oriented Programming (OOP) can be a difficult paradigm to grasp. Just because you're using classes doesn't mean your code is Object-Oriented (OO).

To write OO code you need to understand that OOP is really about the capabilities of your objects. You've got to think about classes in terms of what they can do instead of what they actually do. This is in stark contrast to traditional procedural programming where the focus is on making a bit of code "do something."

If OOP code is about planning and design, an interface is the blueprint and an object is the fully constructed house. Meanwhile, traits are simply a way to help build the house laid out by the blueprint (the interface).

Interfaces

So, why should we use interfaces? Quite simply, interfaces make our code less brittle. If you doubt this statement, ask anyone who's been forced to maintain legacy code that wasn't written against interfaces.

The interface is a contract between the programmer and his/her code. The interface says, "As long as you play by my rules you can implement me however you like and I promise I won't break your other code."

So as an example, consider a real-world scenario (no cars or widgets):

You want to implement a caching system for a web application to cut down on server load

You start out by writing a class to cache request responses using APC:

class ApcCacher
{
  public function fetch($key) {
    return apc_fetch($key);
  }
  public function store($key, $data) {
    return apc_store($key, $data);
  }
  public function delete($key) {
    return apc_delete($key);
  }
}

Then, in your HTTP response object, you check for a cache hit before doing all the work to generate the actual response:

class Controller
{
  protected $req;
  protected $resp;
  protected $cacher;

  public function __construct(Request $req, Response $resp, ApcCacher $cacher=NULL) {
    $this->req    = $req;
    $this->resp   = $resp;
    $this->cacher = $cacher;

    $this->buildResponse();
  }

  public function buildResponse() {
    if (NULL !== $this->cacher && $response = $this->cacher->fetch($this->req->uri()) {
      $this->resp = $response;
    } else {
      // Build the response manually
    }
  }

  public function getResponse() {
    return $this->resp;
  }
}

This approach works great. But maybe a few weeks later you decide you want to use a file-based cache system instead of APC. Now you have to change your controller code because you've programmed your controller to work with the functionality of the ApcCacher class rather than to an interface that expresses the capabilities of the ApcCacher class. Let's say instead of the above you had made the Controller class reliant on a CacherInterface instead of the concrete ApcCacher like so:

// Your controller's constructor using the interface as a dependency
public function __construct(Request $req, Response $resp, CacherInterface $cacher=NULL)

To go along with that you define your interface like so:

interface CacherInterface
{
  public function fetch($key);
  public function store($key, $data);
  public function delete($key);
}

In turn you have both your ApcCacher and your new FileCacher classes implement the CacherInterface and you program your Controller class to use the capabilities required by the interface.

This example (hopefully) demonstrates how programming to an interface allows you to change the internal implementation of your classes without worrying if the changes will break your other code.

Traits

Traits, on the other hand, are simply a method for re-using code. Interfaces should not be thought of as a mutually exclusive alternative to traits. In fact, creating traits that fulfill the capabilities required by an interface is the ideal use case.

You should only use traits when multiple classes share the same functionality (likely dictated by the same interface). There's no sense in using a trait to provide functionality for a single class: that only obfuscates what the class does and a better design would move the trait's functionality into the relevant class.

Consider the following trait implementation:

interface Person
{
    public function greet();
    public function eat($food);
}

trait EatingTrait
{
    public function eat($food)
    {
        $this->putInMouth($food);
    }

    private function putInMouth($food)
    {
        // Digest delicious food
    }
}

class NicePerson implements Person
{
    use EatingTrait;

    public function greet()
    {
        echo 'Good day, good sir!';
    }
}

class MeanPerson implements Person
{
    use EatingTrait;

    public function greet()
    {
        echo 'Your mother was a hamster!';
    }
}

A more concrete example: imagine both your FileCacher and your ApcCacher from the interface discussion use the same method to determine whether a cache entry is stale and should be deleted (obviously this isn't the case in real life, but go with it). You could write a trait and allow both classes to use it to for the common interface requirement.

One final word of caution: be careful not to go overboard with traits. Often traits are used as a crutch for poor design when unique class implementations would suffice. You should limit traits to fulfilling interface requirements for best code design.

Offset a background image from the right using CSS

!! Outdated answer, since CSS3 brought this feature

Is there a way to position a background image a certain number of pixels from the right of its element?

Nope.

Popular workarounds include

  • setting a margin-right on the element instead
  • adding transparent pixels to the image itself and positioning it top right
  • or calculating the position using jQuery after the element's width is known.

Vertical Tabs with JQuery?

//o_O\\  (Poker Face) i know its late

just add beloww css style

<style type="text/css">

   /* Vertical Tabs ----------------------------------*/
 .ui-tabs-vertical { width: 55em; }
 .ui-tabs-vertical .ui-tabs-nav { padding: .2em .1em .2em .2em; float: left; width: 12em; }
 .ui-tabs-vertical .ui-tabs-nav li { clear: left; width: 100%; border-bottom-width: 1px !important; border-right-width: 0 !important; margin: 0 -1px .2em 0; }
 .ui-tabs-vertical .ui-tabs-nav li a { display:block; }
 .ui-tabs-vertical .ui-tabs-nav li.ui-tabs-selected { padding-bottom: 0; padding-right: .1em; border-right-width: 1px; border-right-width: 1px; }
 .ui-tabs-vertical .ui-tabs-panel { padding: 1em; float: right; width: 40em;}

</style>

UPDATED ! http://jqueryui.com/tabs/#vertical

Practical uses of git reset --soft?

Use Case - Combine a series of local commits

"Oops. Those three commits could be just one."

So, undo the last 3 (or whatever) commits (without affecting the index nor working directory). Then commit all the changes as one.

E.g.

> git add -A; git commit -m "Start here."
> git add -A; git commit -m "One"
> git add -A; git commit -m "Two"
> git add -A' git commit -m "Three"
> git log --oneline --graph -4 --decorate

> * da883dc (HEAD, master) Three
> * 92d3eb7 Two
> * c6e82d3 One
> * e1e8042 Start here.

> git reset --soft HEAD~3
> git log --oneline --graph -1 --decorate

> * e1e8042 Start here.

Now all your changes are preserved and ready to be committed as one.

Short answers to your questions

Are these two commands really the same (reset --soft vs commit --amend)?

  • No.

Any reason to use one or the other in practical terms?

  • commit --amend to add/rm files from the very last commit or to change its message.
  • reset --soft <commit> to combine several sequential commits into a new one.

And more importantly, are there any other uses for reset --soft apart from amending a commit?

  • See other answers :)

How to install SimpleJson Package for Python

You can import json as simplejson like this:

import json as simplejson

and keep backward compatibility.

Superscript in markdown (Github flavored)?

<sup> and <sub> tags work and are your only good solution for arbitrary text. Other solutions include:

Unicode

If the superscript (or subscript) you need is of a mathematical nature, Unicode may well have you covered.

I've compiled a list of all the Unicode super and subscript characters I could identify in this gist. Some of the more common/useful ones are:

  • ° SUPERSCRIPT ZERO (U+2070)
  • ¹ SUPERSCRIPT ONE (U+00B9)
  • ² SUPERSCRIPT TWO (U+00B2)
  • ³ SUPERSCRIPT THREE (U+00B3)
  • n SUPERSCRIPT LATIN SMALL LETTER N (U+207F)

People also often reach for <sup> and <sub> tags in an attempt to render specific symbols like these:

  • TRADE MARK SIGN (U+2122)
  • ® REGISTERED SIGN (U+00AE)
  • ? SERVICE MARK (U+2120)

Assuming your editor supports Unicode, you can copy and paste the characters above directly into your document.

Alternatively, you could use the hex values above in an HTML character escape. Eg, &#x00B2; instead of ². This works with GitHub (and should work anywhere else your Markdown is rendered to HTML) but is less readable when presented as raw text/Markdown.

Images

If your requirements are especially unusual, you can always just inline an image. The GitHub supported syntax is:

![Alt text goes here, if you'd like](path/to/image.png) 

You can use a full path (eg. starting with https:// or http://) but it's often easier to use a relative path, which will load the image from the repo, relative to the Markdown document.

If you happen to know LaTeX (or want to learn it) you could do just about any text manipulation imaginable and render it to an image. Sites like Quicklatex make this quite easy.

'adb' is not recognized as an internal or external command, operable program or batch file

In my case it was:

C:\Program Files (x86)\Android\android-sdk\platform-tools

How to check for empty array in vba macro

Auth was closest but his answer throws a type mismatch error.

As for the other answers you should avoid using an error to test for a condition, if you can, because at the very least it complicates debugging (what if something else is causing that error).

Here's a simple, complete solution:

option explicit
Function foo() As Variant

    Dim bar() As String

    If (Not Not bar) Then
        ReDim Preserve bar(0 To UBound(bar) + 1)
    Else
        ReDim Preserve bar(0 To 0)
    End If

    bar(UBound(bar)) = "it works!"

    foo = bar

End Function

Detect enter press in JTextField

public void keyReleased(KeyEvent e)
{
    int key=e.getKeyCode();
    if(e.getSource()==textField)
    {
        if(key==KeyEvent.VK_ENTER)
        { 
            Toolkit.getDefaultToolkit().beep();
            textField_1.requestFocusInWindow();                     
        }
    }

To write logic for 'Enter press' in JTextField, it is better to keep logic inside the keyReleased() block instead of keyTyped() & keyPressed().

Disable button in WPF?

By code:

btn_edit.IsEnabled = true;

By XAML:

<Button Content="Edit data" Grid.Column="1" Name="btn_edit" Grid.Row="1" IsEnabled="False" />

Converting Integer to Long

This is null-safe

Number tmp = getValueByReflection(inv.var1(), classUnderTest, runtimeInstance);
Long value1 = tmp == null ? null : tmp.longValue();

Keeping session alive with Curl and PHP

This is how you do CURL with sessions

//initial request with login data

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/login.php');
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "username=XXXXX&password=XXXXX");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name');  //could be empty, but cause problems on some hosts
curl_setopt($ch, CURLOPT_COOKIEFILE, '/var/www/ip4.x/file/tmp');  //could be empty, but cause problems on some hosts
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch);
}

//another request preserving the session

curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/profile');
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, "");
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch);
}

I've seen this on ImpressPages

Maximize a window programmatically and prevent the user from changing the windows state

Change the property WindowState to System.Windows.Forms.FormWindowState.Maximized, in some cases if the older answers doesn't works.

So the window will be maximized, and the other parts are in the other answers.

Convert JSON String To C# Object

Let's assume you have a class name Student it has following fields and it has a method which will take JSON as a input and return a string Student Object.We can use JavaScriptSerializer here Convert JSON String To C# Object.std is a JSON string here.

  public class Student
{
   public string FirstName {get;set:}
   public string LastName {get;set:}
   public int[] Grades {get;set:}
}

public static Student ConvertToStudent(string std)
{
  var serializer = new JavaScriptSerializer();

  Return serializer.Deserialize<Student>(std);
 }

What is WebKit and how is it related to CSS?

Webkit is a web browser rendering engine used by Safari and Chrome (among others, but these are the popular ones).

The -webkit prefix on CSS selectors are properties that only this engine is intended to process, very similar to -moz properties. Many of us are hoping this goes away, for example -webkit-border-radius will be replaced by the standard border-radius and you won't need multiple rules for the same thing for multiple browsers. This is really the result of "pre-specification" features that are intended to not interfere with the standard version when it comes about.

For your update:...no it's not related to IE really, IE at least before 9 uses a different rendering engine called Trident.

Get div's offsetTop positions in React

  import ReactDOM from 'react-dom';
  //...
  componentDidMount() {
    var n = ReactDOM.findDOMNode(this);
    console.log(n.offsetTop);
  }

You can just grab the offsetTop from the Node.

How to add a new line of text to an existing file in Java?

Try: "\r\n"

Java 7 example:

// append = true
try(PrintWriter output = new PrintWriter(new FileWriter("log.txt",true))) 
{
    output.printf("%s\r\n", "NEWLINE");
} 
catch (Exception e) {}

When do you use Java's @Override annotation and why?

Using the @Override annotation acts as a compile-time safeguard against a common programming mistake. It will throw a compilation error if you have the annotation on a method you're not actually overriding the superclass method.

The most common case where this is useful is when you are changing a method in the base class to have a different parameter list. A method in a subclass that used to override the superclass method will no longer do so due the changed method signature. This can sometimes cause strange and unexpected behavior, especially when dealing with complex inheritance structures. The @Override annotation safeguards against this.

How to get response from S3 getObject in Node.js?

When doing a getObject() from the S3 API, per the docs the contents of your file are located in the Body property, which you can see from your sample output. You should have code that looks something like the following

const aws = require('aws-sdk');
const s3 = new aws.S3(); // Pass in opts to S3 if necessary

var getParams = {
    Bucket: 'abc', // your bucket name,
    Key: 'abc.txt' // path to the object you're looking for
}

s3.getObject(getParams, function(err, data) {
    // Handle any error and exit
    if (err)
        return err;

  // No error happened
  // Convert Body from a Buffer to a String

  let objectData = data.Body.toString('utf-8'); // Use the encoding necessary
});

You may not need to create a new buffer from the data.Body object but if you need you can use the sample above to achieve that.

Force file download with php using header()

the htaccess solution

<filesmatch "\.(?i:doc|odf|pdf|cer|txt)$">
  Header set Content-Disposition attachment
</FilesMatch>

you can read this page: https://www.techmesto.com/force-files-to-download-using-htaccess/

Visual Studio Error: (407: Proxy Authentication Required)

Download and install Fiddler

Open Fiddler and go to Rule menu to tick Automatically authenticate

Now open visual studio and click on sign-in button.

Enter your email and password.

Hopefully it will work

ISO time (ISO 8601) in Python

Correct me if I'm wrong (I'm not), but the offset from UTC changes with daylight saving time. So you should use

tz = str.format('{0:+06.2f}', float(time.altzone) / 3600)

I also believe that the sign should be different:

tz = str.format('{0:+06.2f}', -float(time.altzone) / 3600)

I could be wrong, but I don't think so.

Rails 3 check if attribute changed

Check out ActiveModel::Dirty (available on all models by default). The documentation is really good, but it lets you do things such as:

@user.street1_changed? # => true/false

Google Chrome "window.open" workaround?

This worked for me:

newwindow = window.open(url, "_blank", "resizable=yes, scrollbars=yes, titlebar=yes, width=800, height=900, top=10, left=10");

What are best practices for REST nested resources?

I've tried both design strategies - nested and non-nested endpoints. I've found that:

  1. if the nested resource has a primary key and you don't have its parent primary key, the nested structure requires you to get it, even though the system doesn't actually require it.

  2. nested endpoints typically require redundant endpoints. In other words, you will more often than not, need the additional /employees endpoint so you can get a list of employees across departments. If you have /employees, what exactly does /companies/departments/employees buy you?

  3. nesting endpoints don't evolve as nicely. E.g. you might not need to search for employees now but you might later and if you have a nested structure, you have no choice but to add another endpoint. With a non-nested design, you just add more parameters, which is simpler.

  4. sometimes a resource could have multiple types of parents. Resulting in multiple endpoints all returning the same resource.

  5. redundant endpoints makes the docs harder to write and also makes the api harder to learn.

In short, the non-nested design seems to allow a more flexible and simpler endpoint schema.

How can I add additional PHP versions to MAMP

Maybe easy like this?

Compiled binaries of the PHP interpreter can be found at http://www.mamp.info/en/ downloads/index.html . Drop this downloaded folder into your /Applications/MAMP/bin/php! directory. Close and re-open your MAMP PRO application. Your new PHP version should now appear in the PHP drop down menu. MAMP PRO will only support PHP versions from the downloads page.

How to write unit testing for Angular / TypeScript for private methods with Jasmine

This worked for me:

Instead of:

sut.myPrivateMethod();

This:

sut['myPrivateMethod']();

Compiling C++ on remote Linux machine - "clock skew detected" warning

This is usually simply due to mismatching times between your host and client machines. You can try to synchronize the times on your machines using ntp.

Reading e-mails from Outlook with Python through MAPI

Sorry for my bad English. Checking Mails using Python with MAPI is easier,

outlook =win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders[5]
Subfldr = folder.Folders[5]
messages_REACH = Subfldr.Items
message = messages_REACH.GetFirst()

Here we can get the most first mail into the Mail box, or into any sub folder. Actually, we need to check the Mailbox number & orientation. With the help of this analysis we can check each mailbox & its sub mailbox folders.

Similarly please find the below code, where we can see, the last/ earlier mails. How we need to check.

`outlook =win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders[5]
Subfldr = folder.Folders[5]
messages_REACH = Subfldr.Items
message = messages_REACH.GetLast()`

With this we can get most recent email into the mailbox. According to the above mentioned code, we can check our all mail boxes, & its sub folders.

appending array to FormData and send via AJAX

You can also send an array via FormData this way:

var formData = new FormData;
var arr = ['this', 'is', 'an', 'array'];
for (var i = 0; i < arr.length; i++) {
    formData.append('arr[]', arr[i]);
}

So you can write arr[] the same way as you do it with a simple HTML form. In case of PHP it should work.

You may find this article useful: How to pass an array within a query string?

ReactJS call parent method

Pass the method from Parent component down as a prop to your Child component. ie:

export default class Parent extends Component {
  state = {
    word: ''
  }

  handleCall = () => {
    this.setState({ word: 'bar' })
  }

  render() {
    const { word } = this.state
    return <Child handler={this.handleCall} word={word} />
  }
}

const Child = ({ handler, word }) => (
<span onClick={handler}>Foo{word}</span>
)

How to sum up elements of a C++ vector?

The easiest way is to use std:accumulate of a vector<int> A:

#include <numeric>
cout << accumulate(A.begin(), A.end(), 0);

Launch Minecraft from command line - username and password as prefix

Just create this batch command file in your game directory. Bat file takes one argument %1 as the username.

Also, I use a splash screen to make pretty. You will NOT be able to play online, but who cares.

Adjust your memory usage to fit your machine (-Xmx & -Xmns).

NOTE: this is for version of minecraft as of 2016-06-27

@ECHO OFF
SET DIR=%cd%
SET JAVA_HOME=%DIR%\runtime\jre-x64\1.8.0_25
SET JAVA=%JAVA_HOME%\bin\java.exe
SET LOW_MEM=768M
SET MAX_MEM=2G
SET LIBRARIES=versions\1.10.2\1.10.2-natives-59894925878961
SET MAIN_CLASS=net.minecraft.client.main.Main
SET CLASSPATH=libraries\com\mojang\netty\1.6\netty-1.6.jar;libraries\oshi-project\oshi-core\1.1\oshi-core-1.1.jar;libraries\net\java\dev\jna\jna\3.4.0\jna-3.4.0.jar;libraries\net\java\dev\jna\platform\3.4.0\platform-3.4.0.jar;libraries\com\ibm\icu\icu4j-core-mojang\51.2\icu4j-core-mojang-51.2.jar;libraries\net\sf\jopt-simple\jopt-simple\4.6\jopt-simple-4.6.jar;libraries\com\paulscode\codecjorbis\20101023\codecjorbis-20101023.jar;libraries\com\paulscode\codecwav\20101023\codecwav-20101023.jar;libraries\com\paulscode\libraryjavasound\20101123\libraryjavasound-20101123.jar;libraries\com\paulscode\librarylwjglopenal\20100824\librarylwjglopenal-20100824.jar;libraries\com\paulscode\soundsystem\20120107\soundsystem-20120107.jar;libraries\io\netty\netty-all\4.0.23.Final\netty-all-4.0.23.Final.jar;libraries\com\google\guava\guava\17.0\guava-17.0.jar;libraries\org\apache\commons\commons-lang3\3.3.2\commons-lang3-3.3.2.jar;libraries\commons-io\commons-io\2.4\commons-io-2.4.jar;libraries\commons-codec\commons-codec\1.9\commons-codec-1.9.jar;libraries\net\java\jinput\jinput\2.0.5\jinput-2.0.5.jar;libraries\net\java\jutils\jutils\1.0.0\jutils-1.0.0.jar;libraries\com\google\code\gson\gson\2.2.4\gson-2.2.4.jar;libraries\com\mojang\authlib\1.5.22\authlib-1.5.22.jar;libraries\com\mojang\realms\1.9.3\realms-1.9.3.jar;libraries\org\apache\commons\commons-compress\1.8.1\commons-compress-1.8.1.jar;libraries\org\apache\httpcomponents\httpclient\4.3.3\httpclient-4.3.3.jar;libraries\commons-logging\commons-logging\1.1.3\commons-logging-1.1.3.jar;libraries\org\apache\httpcomponents\httpcore\4.3.2\httpcore-4.3.2.jar;libraries\it\unimi\dsi\fastutil\7.0.12_mojang\fastutil-7.0.12_mojang.jar;libraries\org\apache\logging\log4j\log4j-api\2.0-beta9\log4j-api-2.0-beta9.jar;libraries\org\apache\logging\log4j\log4j-core\2.0-beta9\log4j-core-2.0-beta9.jar;libraries\org\lwjgl\lwjgl\lwjgl\2.9.4-nightly-20150209\lwjgl-2.9.4-nightly-20150209.jar;libraries\org\lwjgl\lwjgl\lwjgl_util\2.9.4-nightly-20150209\lwjgl_util-2.9.4-nightly-20150209.jar;versions\1.10.2\1.10.2.jar
SET JAVA_OPTIONS=-server -splash:splash.png -d64 -da -dsa -Xrs -Xms%LOW_MEM% -Xmx%MAX_MEM% -XX:NewSize=%LOW_MEM% -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode -XX:-UseAdaptiveSizePolicy -XX:+DisableExplicitGC -Djava.library.path=%LIBRARIES% -cp %CLASSPATH%  %MAIN_CLASS%

start /D %DIR% /I /HIGH %JAVA% %JAVA_OPTIONS% --username %1 --version 1.10.2 --gameDir %DIR% --assetsDir assets --assetIndex 1.10 --uuid 2536abce90e8476a871679918164abc5 --accessToken 99abe417230342cb8e9e2168ab46297a --userType legacy --versionType release --nativeLauncherVersion 307


.prop() vs .attr()

I think Tim said it quite well, but let's step back:

A DOM element is an object, a thing in memory. Like most objects in OOP, it has properties. It also, separately, has a map of the attributes defined on the element (usually coming from the markup that the browser read to create the element). Some of the element's properties get their initial values from attributes with the same or similar names (value gets its initial value from the "value" attribute; href gets its initial value from the "href" attribute, but it's not exactly the same value; className from the "class" attribute). Other properties get their initial values in other ways: For instance, the parentNode property gets its value based on what its parent element is; an element always has a style property, whether it has a "style" attribute or not.

Let's consider this anchor in a page at http://example.com/testing.html:

<a href='foo.html' class='test one' name='fooAnchor' id='fooAnchor'>Hi</a>

Some gratuitous ASCII art (and leaving out a lot of stuff):

+-------------------------------------------+
|             HTMLAnchorElement             |
+-------------------------------------------+
| href:       "http://example.com/foo.html" |
| name:       "fooAnchor"                   |
| id:         "fooAnchor"                   |
| className:  "test one"                    |
| attributes:                               |
|    href:  "foo.html"                      |
|    name:  "fooAnchor"                     |
|    id:    "fooAnchor"                     |
|    class: "test one"                      |
+-------------------------------------------+

Note that the properties and attributes are distinct.

Now, although they are distinct, because all of this evolved rather than being designed from the ground up, a number of properties write back to the attribute they derived from if you set them. But not all do, and as you can see from href above, the mapping is not always a straight "pass the value on", sometimes there's interpretation involved.

When I talk about properties being properties of an object, I'm not speaking in the abstract. Here's some non-jQuery code:

var link = document.getElementById('fooAnchor');
alert(link.href);                 // alerts "http://example.com/foo.html"
alert(link.getAttribute("href")); // alerts "foo.html"

(Those values are as per most browsers; there's some variation.)

The link object is a real thing, and you can see there's a real distinction between accessing a property on it, and accessing an attribute.

As Tim said, the vast majority of the time, we want to be working with properties. Partially that's because their values (even their names) tend to be more consistent across browsers. We mostly only want to work with attributes when there is no property related to it (custom attributes), or when we know that for that particular attribute, the attribute and the property are not 1:1 (as with href and "href" above).

The standard properties are laid out in the various DOM specs:

These specs have excellent indexes and I recommend keeping links to them handy; I use them all the time.

Custom attributes would include, for instance, any data-xyz attributes you might put on elements to provide meta-data to your code (now that that's valid as of HTML5, as long as you stick to the data- prefix). (Recent versions of jQuery give you access to data-xyz elements via the data function, but that function is not just an accessor for data-xyz attributes [it does both more and less than that]; unless you actually need its features, I'd use the attr function to interact with data-xyz attribute.)

The attr function used to have some convoluted logic around getting what they thought you wanted, rather than literally getting the attribute. It conflated the concepts. Moving to prop and attr was meant to de-conflate them. Briefly in v1.6.0 jQuery went too far in that regard, but functionality was quickly added back to attr to handle the common situations where people use attr when technically they should use prop.

C# Switch-case string starting with

In addition to substring answer, you can do it as mystring.SubString(0,3) and check in case statement if its "abc".

But before the switch statement you need to ensure that your mystring is atleast 3 in length.

How to select the first row of each group?

The solution below does only one groupBy and extract the rows of your dataframe that contain the maxValue in one shot. No need for further Joins, or Windows.

import org.apache.spark.sql.Row
import org.apache.spark.sql.catalyst.encoders.RowEncoder
import org.apache.spark.sql.DataFrame

//df is the dataframe with Day, Category, TotalValue

implicit val dfEnc = RowEncoder(df.schema)

val res: DataFrame = df.groupByKey{(r) => r.getInt(0)}.mapGroups[Row]{(day: Int, rows: Iterator[Row]) => i.maxBy{(r) => r.getDouble(2)}}

Use SQL Server Management Studio to connect remotely to an SQL Server Express instance hosted on an Azure Virtual Machine

Here are the three web pages on which we found the answer. The most difficult part was setting up static ports for SQLEXPRESS.

Provisioning a SQL Server Virtual Machine on Windows Azure. These initial instructions provided 25% of the answer.

How to Troubleshoot Connecting to the SQL Server Database Engine. Reading this carefully provided another 50% of the answer.

How to configure SQL server to listen on different ports on different IP addresses?. This enabled setting up static ports for named instances (eg SQLEXPRESS.) It took us the final 25% of the way to the answer.

CSS submit button weird rendering on iPad/iPhone

The above answer for webkit appearance worked, but the button still looked kind pale/dull compared to the browser on other devices/desktop. I also had to set opacity to full (ranges from 0 to 1)

-webkit-appearance:none;
opacity: 1

After setting the opacity, the button looked the same on all the different devices/emulator/desktop.

How to return a file using Web API?

Another way to download file is to write the stream content to the response's body directly:

[HttpGet("pdfstream/{id}")]
public async Task  GetFile(long id)
{        
    var stream = GetStream(id);
    Response.StatusCode = (int)HttpStatusCode.OK;
    Response.Headers.Add( HeaderNames.ContentDisposition, $"attachment; filename=\"{Guid.NewGuid()}.pdf\"" );
    Response.Headers.Add( HeaderNames.ContentType, "application/pdf"  );            
    await stream.CopyToAsync(Response.Body);
    await Response.Body.FlushAsync();           
}

Get an object attribute

You can do the following:

class User(object):
    fullName = "John Doe"

    def __init__(self, name):
        self.SName = name

    def print_names(self):
        print "Names: full name: '%s', name: '%s'" % (self.fullName, self.SName)

user = User('Test Name')

user.fullName # "John Doe"
user.SName # 'Test Name'
user.print_names() # will print you Names: full name: 'John Doe', name: 'Test Name'

E.g any object attributes could be retrieved using istance.

Javascript switch vs. if...else if...else

It turns out that if-else if generally faster than switch

http://jsperf.com/switch-if-else/46

How to change btn color in Bootstrap

You have missed one style ".btn-primary:active:focus" which causes that still during btn click default bootstrap color show up for a second. This works in my code:

.btn-primary, .btn-primary:hover, .btn-primary:active, .btn-primary:visited, .btn-primary:focus, .btn-primary:active:focus {
background-color: #8064A2;}

Download files from server php

If the folder is accessible from the browser (not outside the document root of your web server), then you just need to output links to the locations of those files. If they are outside the document root, you will need to have links, buttons, whatever, that point to a PHP script that handles getting the files from their location and streaming to the response.

SQL: How to get the count of each distinct value in a column?

SELECT
  category,
  COUNT(*) AS `num`
FROM
  posts
GROUP BY
  category

Open another application from your own (intent)

Use following:

String packagename = "com.example.app";
startActivity(getPackageManager().getLaunchIntentForPackage(packagename));

Stop MySQL service windows

On windows 10

If you wanna close it open command prompt with work with admin. Write NET STOP MySQL80. Its done. If you wanna open again so you must write NET START MySQL80

If you do not want it to be turned on automatically when not in use, it automatically runs when the computer is turned on and consumes some ram.

Open services.msc find Mysql80 , look at properties and turn start type manuel or otomaticly again as you wish.

Python object deleting itself

I think I've finally got it!
NOTE: You should not use this in normal code, but it is possible. This is only meant as a curiosity, see other answers for real-world solutions to this problem.


Take a look at this code:

# NOTE: This is Python 3 code, it should work with python 2, but I haven't tested it.
import weakref

class InsaneClass(object):
    _alive = []
    def __new__(cls):
        self = super().__new__(cls)
        InsaneClass._alive.append(self)

        return weakref.proxy(self)

    def commit_suicide(self):
        self._alive.remove(self)

instance = InsaneClass()
instance.commit_suicide()
print(instance)

# Raises Error: ReferenceError: weakly-referenced object no longer exists

When the object is created in the __new__ method, the instance is replaced by a weak reference proxy and the only strong reference is kept in the _alive class attribute.

What is a weak-reference?

Weak-reference is a reference which does not count as a reference when the garbage collector collects the object. Consider this example:

>>> class Test(): pass

>>> a = Test()
>>> b = Test()

>>> c = a
>>> d = weakref.proxy(b)
>>> d
<weakproxy at 0x10671ae58 to Test at 0x10670f4e0> 
# The weak reference points to the Test() object

>>> del a
>>> c
<__main__.Test object at 0x10670f390> # c still exists

>>> del b
>>> d
<weakproxy at 0x10671ab38 to NoneType at 0x1002050d0> 
# d is now only a weak-reference to None. The Test() instance was garbage-collected

So the only strong reference to the instance is stored in the _alive class attribute. And when the commit_suicide() method removes the reference the instance is garbage-collected.

Verify a certificate chain using openssl verify

That's one of the few legitimate jobs for cat:

openssl verify -verbose -CAfile <(cat Intermediate.pem RootCert.pem) UserCert.pem

Update:

As Greg Smethells points out in the comments, this command implicitly trusts Intermediate.pem. I recommend reading the first part of the post Greg references (the second part is specifically about pyOpenSSL and not relevant to this question).

In case the post goes away I'll quote the important paragraphs:

Unfortunately, an "intermediate" cert that is actually a root / self-signed will be treated as a trusted CA when using the recommended command given above:

$ openssl verify -CAfile <(cat geotrust_global_ca.pem rogue_ca.pem) fake_sometechcompany_from_rogue_ca.com.pem fake_sometechcompany_from_rogue_ca.com.pem: OK

It seems openssl will stop verifying the chain as soon as a root certificate is encountered, which may also be Intermediate.pem if it is self-signed. In that case RootCert.pem is not considered. So make sure that Intermediate.pem is coming from a trusted source before relying on the command above.

Custom checkbox image android

Copy the btn_check.xml from android-sdk/platforms/android-#/data/res/drawable to your project's drawable folder and change the 'on' and 'off' image states to your custom images.

Then your xml will just need android:button="@drawable/btn_check"

<CheckBox
    android:button="@drawable/btn_check"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="true" />

If you want to use different default android icons, you can use android:button="@android:drawable/..."

Storing Objects in HTML5 localStorage

You cannot store key value without String Format.

LocalStorage only support String format for key/value.

That is why you should convert your data to string whatever it is Array or Object.

To Store data in localStorage first of all stringify it using JSON.stringify() method.

var myObj = [{name:"test", time:"Date 2017-02-03T08:38:04.449Z"}];
localStorage.setItem('item', JSON.stringify(myObj));

Then when you want to retrieve data , you need to parse the String to Object again.

var getObj = JSON.parse(localStorage.getItem('item'));

Hope it helps.

How can I write data in YAML format in a file?

Link to the PyYAML documentation showing the difference for the default_flow_style parameter. To write it to a file in block mode (often more readable):

d = {'A':'a', 'B':{'C':'c', 'D':'d', 'E':'e'}}
with open('result.yml', 'w') as yaml_file:
    yaml.dump(d, yaml_file, default_flow_style=False)

produces:

A: a
B:
  C: c
  D: d
  E: e

JavaScript set object key by variable

You need to make the object first, then use [] to set it.

var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);

UPDATE 2018:

If you're able to use ES6 and Babel, you can use this new feature:

{
    [yourKeyVariable]: someValueArray,
}  

Set NOW() as Default Value for datetime datatype?

As of MySQL 5.6.5, you can use the DATETIME type with a dynamic default value:

CREATE TABLE foo (
    creation_time      DATETIME DEFAULT   CURRENT_TIMESTAMP,
    modification_time  DATETIME ON UPDATE CURRENT_TIMESTAMP
)

Or even combine both rules:

modification_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

Reference:
http://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html
http://optimize-this.blogspot.com/2012/04/datetime-default-now-finally-available.html

Prior to 5.6.5, you need to use the TIMESTAMP data type, which automatically updates whenever the record is modified. Unfortunately, however, only one auto-updated TIMESTAMP field can exist per table.

CREATE TABLE mytable (
  mydate TIMESTAMP
)

See: http://dev.mysql.com/doc/refman/5.1/en/create-table.html

If you want to prevent MySQL from updating the timestamp value on UPDATE (so that it only triggers on INSERT) you can change the definition to:

CREATE TABLE mytable (
  mydate TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)

How to write to an existing excel file without overwriting data (using pandas)?

writer = pd.ExcelWriter('prueba1.xlsx'engine='openpyxl',keep_date_col=True)

The "keep_date_col" hope help you

X11/Xlib.h not found in Ubuntu

Presume he's using the tutorial from http://www.arcsynthesis.org/gltut/ along with premake4.3 :-)

sudo apt-get install libx11-dev ................. for X11/Xlib.h
sudo apt-get install mesa-common-dev........ for GL/glx.h
sudo apt-get install libglu1-mesa-dev ..... for GL/glu.h
sudo apt-get install libxrandr-dev ........... for X11/extensions/Xrandr.h
sudo apt-get install libxi-dev ................... for X11/extensions/XInput.h

After which I could build glsdk_0.4.4 and examples without further issue.

Entity Framework select distinct name

The way that @alliswell showed is completely valid, and there's another way! :)

var result = EFContext.TestAddresses
    .GroupBy(ta => ta.Name)
    .Select(ta => ta.Key);

I hope it'll be useful to someone.

How to fill in proxy information in cntlm config file?

The solution takes two steps!

First, complete the user, domain, and proxy fields in cntlm.ini. The username and domain should probably be whatever you use to log in to Windows at your office, eg.

Username            employee1730
Domain              corporate
Proxy               proxy.infosys.corp:8080

Then test cntlm with a command such as

cntlm.exe -c cntlm.ini -I -M http://www.bbc.co.uk

It will ask for your password (again whatever you use to log in to Windows_). Hopefully it will print 'http 200 ok' somewhere, and print your some cryptic tokens authentication information. Now add these to cntlm.ini, eg:

Auth            NTLM
PassNT          A2A7104B1CE00000000000000007E1E1
PassLM          C66000000000000000000000008060C8

Finally, set the http_proxy environment variable in Windows (assuming you didn't change with the Listen field which by default is set to 3128) to the following

http://localhost:3128

How to format number of decimal places in wpf using style/template?

    void NumericTextBoxInput(object sender, TextCompositionEventArgs e)
    {
        TextBox txt = (TextBox)sender;
        var regex = new Regex(@"^[0-9]*(?:\.[0-9]{0,1})?$");
        string str = txt.Text + e.Text.ToString();
        int cntPrc = 0;
        if (str.Contains('.'))
        {
            string[] tokens = str.Split('.');
            if (tokens.Count() > 0)
            {
                string result = tokens[1];
                char[] prc = result.ToCharArray();
                cntPrc = prc.Count();
            }
        }
        if (regex.IsMatch(e.Text) && !(e.Text == "." && ((TextBox)sender).Text.Contains(e.Text)) && (cntPrc < 3))
        {
            e.Handled = false;
        }
        else
        {
            e.Handled = true;
        }
    }

Getting the error "Java.lang.IllegalStateException Activity has been destroyed" when using tabs with ViewPager

I had this error because I was using LocalBroadcastManager and I did:

unregisterReceiver(intentReloadFragmentReceiver);

instead of:

LocalBroadcastManager.getInstance(this).unregisterReceiver(intentReloadFragmentReceiver);

How do I log a Python error with debug information?

A little bit of decorator treatment (very loosely inspired by the Maybe monad and lifting). You can safely remove Python 3.6 type annotations and use an older message formatting style.

fallible.py

from functools import wraps
from typing import Callable, TypeVar, Optional
import logging


A = TypeVar('A')


def fallible(*exceptions, logger=None) \
        -> Callable[[Callable[..., A]], Callable[..., Optional[A]]]:
    """
    :param exceptions: a list of exceptions to catch
    :param logger: pass a custom logger; None means the default logger, 
                   False disables logging altogether.
    """
    def fwrap(f: Callable[..., A]) -> Callable[..., Optional[A]]:

        @wraps(f)
        def wrapped(*args, **kwargs):
            try:
                return f(*args, **kwargs)
            except exceptions:
                message = f'called {f} with *args={args} and **kwargs={kwargs}'
                if logger:
                    logger.exception(message)
                if logger is None:
                    logging.exception(message)
                return None

        return wrapped

    return fwrap

Demo:

In [1] from fallible import fallible

In [2]: @fallible(ArithmeticError)
    ...: def div(a, b):
    ...:     return a / b
    ...: 
    ...: 

In [3]: div(1, 2)
Out[3]: 0.5

In [4]: res = div(1, 0)
ERROR:root:called <function div at 0x10d3c6ae8> with *args=(1, 0) and **kwargs={}
Traceback (most recent call last):
  File "/Users/user/fallible.py", line 17, in wrapped
    return f(*args, **kwargs)
  File "<ipython-input-17-e056bd886b5c>", line 3, in div
    return a / b

In [5]: repr(res)
'None'

You can also modify this solution to return something a bit more meaningful than None from the except part (or even make the solution generic, by specifying this return value in fallible's arguments).

Error: Could not create the Java Virtual Machine Mac OSX Mavericks

Normally this error occurs when you invoke java by supplying the wrong arguments/options. In this case it should be the version option.

java -version

So to double check you can always do java -help, and see if the option exists. In this case, there is no option such as v.

How to edit binary file on Unix systems

I've had good experience with wxHexEditor... just make sure if you are hex-editing a drive you do it via the menu

Devices -> Open Disk Device -> SCSI Disk Drive Partition #_N_

Python: "TypeError: __str__ returned non-string" but still prints to output?

Just Try this:

def __str__(self):
    return f'Memo={self.memo}, Tag={self.tags}'

How to set image to UIImage

Try this code to 100% work....

UIImageView * imageview = [[UIImageView alloc] initWithFrame:CGRectMake(20,100, 80, 80)];
imageview.image = [UIImage imageNamed:@"myimage.jpg"];
[self.view  addSubview:imageview];

Can I stop 100% Width Text Boxes from extending beyond their containers?

This works:

<div>
    <input type="text" 
        style="margin: 5px; padding: 4px; border: 1px solid; 
        width: 200px; width: calc(100% - 20px);">
</div>

The first 'width' is a fallback rule for older browsers.