Programs & Examples On #Ribbon

A ribbon is an interface wherein a set of toolbars are organized using tabs. Don't use this tag for questions related to the Netflix Ribbon component, use [netflix-ribbon] instead.

Make just one slide different size in Powerpoint

True you can't have different sized slides. NOT true the size of you slide doesn't matter. It will size it to your resolution, but you can click on the magnifying icon(at least on PP 2013) and you can then scroll in all directions of your slide in original resolution.

Exception from HRESULT: 0x800A03EC Error

We had the same problem and found for us the solution :

Please make this folder. C:\Windows\SysWOW64\config\systemprofile\Desktop ·Windows 2008 Server x86
Please make this folder. C:\Windows\System32\config\systemprofile\Desktop

Targeting .NET Framework 4.5 via Visual Studio 2010

FYI, if you want to create an Installer package in VS2010, unfortunately it only targets .NET 4. To work around this, you have to add NET 4.5 as a launch condition.

Add the following in to the Launch Conditions of the installer (Right click, View, Launch Conditions).

In "Search Target Machine", right click and select "Add Registry Search".

Property: REGISTRYVALUE1
RegKey: Software\Microsoft\NET Framework Setup\NDP\v4\Full
Root: vsdrrHKLM
Value: Release

Add new "Launch Condition":

Condition: REGISTRYVALUE1>="#378389"
InstallUrl: http://www.microsoft.com/en-gb/download/details.aspx?id=30653
Message: Setup requires .NET Framework 4.5 to be installed.

Where:

378389 = .NET Framework 4.5

378675 = .NET Framework 4.5.1 installed with Windows 8.1

378758 = .NET Framework 4.5.1 installed on Windows 8, Windows 7 SP1, or Windows Vista SP2

379893 = .NET Framework 4.5.2

Launch condition reference: http://msdn.microsoft.com/en-us/library/vstudio/xxyh2e6a(v=vs.100).aspx

ggplot legends - change labels, order and title

You need to do two things:

  1. Rename and re-order the factor levels before the plot
  2. Rename the title of each legend to the same title

The code:

dtt$model <- factor(dtt$model, levels=c("mb", "ma", "mc"), labels=c("MBB", "MAA", "MCC"))

library(ggplot2)
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha = 0.35, linetype=0)+ 
  geom_line(aes(linetype=model), size = 1) +       
  geom_point(aes(shape=model), size=4)  +      
  theme(legend.position=c(.6,0.8)) +
  theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid')) +
  scale_linetype_discrete("Model 1") +
  scale_shape_discrete("Model 1") +
  scale_colour_discrete("Model 1")

enter image description here

However, I think this is really ugly as well as difficult to interpret. It's far better to use facets:

ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha=0.2, colour=NA)+ 
  geom_line() +       
  geom_point()  +      
  facet_wrap(~model)

enter image description here

How to add a custom Ribbon tab using VBA?

AFAIK you cannot use VBA Excel to create custom tab in the Excel ribbon. You can however hide/make visible a ribbon component using VBA. Additionally, the link that you mentioned above is for MS Project and not MS Excel.

I create tabs for my Excel Applications/Add-Ins using this free utility called Custom UI Editor.


Edit: To accommodate new request by OP

Tutorial

Here is a short tutorial as promised:

  1. After you have installed the Custom UI Editor (CUIE), open it and then click on File | Open and select the relevant Excel File. Please ensure that the Excel File is closed before you open it via CUIE. I am using a brand new worksheet as an example.

    enter image description here

  2. Right click as shown in the image below and click on "Office 2007 Custom UI Part". It will insert the "customUI.xml"

    enter image description here

  3. Next Click on menu Insert | Sample XML | Custom Tab. You will notice that the basic code is automatically generated. Now you are all set to edit it as per your requirements.

    enter image description here

  4. Let's inspect the code

    enter image description here

    label="Custom Tab": Replace "Custom Tab" with the name which you want to give your tab. For the time being let's call it "Jerome".

    The below part adds a custom button.

    <button id="customButton" label="Custom Button" imageMso="HappyFace" size="large" onAction="Callback" />
    

    imageMso: This is the image that will display on the button. "HappyFace" is what you will see at the moment. You can download more image ID's here.

    onAction="Callback": "Callback" is the name of the procedure which runs when you click on the button.

Demo

With that, let's create 2 buttons and call them "JG Button 1" and "JG Button 2". Let's keep happy face as the image of the first one and let's keep the "Sun" for the second. The amended code now looks like this:

<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui">
<ribbon startFromScratch="false">
<tabs>
<tab id="MyCustomTab" label="Jerome" insertAfterMso="TabView">
<group id="customGroup1" label="First Tab">
<button id="customButton1" label="JG Button 1" imageMso="HappyFace" size="large" onAction="Callback1" />
<button id="customButton2" label="JG Button 2" imageMso="PictureBrightnessGallery" size="large" onAction="Callback2" />
</group>
</tab>
</tabs>
</ribbon>
</customUI>

Delete all the code which was generated in CUIE and then paste the above code in lieu of that. Save and close CUIE. Now when you open the Excel File it will look like this:

enter image description here

Now the code part. Open VBA Editor, insert a module, and paste this code:

Public Sub Callback1(control As IRibbonControl)

    MsgBox "You pressed Happy Face"

End Sub

Public Sub Callback2(control As IRibbonControl)

    MsgBox "You pressed the Sun"

End Sub

Save the Excel file as a macro enabled file. Now when you click on the Smiley or the Sun you will see the relevant message box:

enter image description here

Hope this helps!

When should the xlsm or xlsb formats be used?

One could think that xlsb has only advantages over xlsm. The fact that xlsm is XML-based and xlsb is binary is that when workbook corruption occurs, you have better chances to repair a xlsm than a xlsb.

Placing an image to the top right corner - CSS

While looking at the same problem, I found an example

<style type="text/css">
#topright {
    position: absolute;
    right: 0;
    top: 0;
    display: block;
    height: 125px;
    width: 125px;
    background: url(TRbanner.gif) no-repeat;
    text-indent: -999em;
    text-decoration: none;
}
</style>

<a id="topright" href="#" title="TopRight">Top Right Link Text</a>

The trick here is to create a small, (I used GIMP) a PNG (or GIF) that has a transparent background, (and then just delete the opposite bottom corner.)

How to name an object within a PowerPoint slide?

Click Insert ->Object->Create from file ->Browse.

Once the file is selected choose the "Change icon" option and you will be able to rename the file and change the icon if you wish.

Hope this helps!

Component based game engine design

While not a complete tutorial on the subject of game engine design, I have found that this page has some good detail and examples on use of the component architecture for games.

Oracle Not Equals Operator

The difference is :

"If you use !=, it returns sub-second. If you use <>, it takes 7 seconds to return. Both return the right answer."

Oracle not equals (!=) SQL operator

Regards

How to extract base URL from a string in JavaScript?

function getBaseURL() {
    var url = location.href;  // entire url including querystring - also: window.location.href;
    var baseURL = url.substring(0, url.indexOf('/', 14));


    if (baseURL.indexOf('http://localhost') != -1) {
        // Base Url for localhost
        var url = location.href;  // window.location.href;
        var pathname = location.pathname;  // window.location.pathname;
        var index1 = url.indexOf(pathname);
        var index2 = url.indexOf("/", index1 + 1);
        var baseLocalUrl = url.substr(0, index2);

        return baseLocalUrl + "/";
    }
    else {
        // Root Url for domain name
        return baseURL + "/";
    }

}

You then can use it like this...

var str = 'http://en.wikipedia.org/wiki/Knopf?q=1&t=2';
var url = str.toUrl();

The value of url will be...

{
"original":"http://en.wikipedia.org/wiki/Knopf?q=1&t=2",<br/>"protocol":"http:",
"domain":"wikipedia.org",<br/>"host":"en.wikipedia.org",<br/>"relativePath":"wiki"
}

The "var url" also contains two methods.

var paramQ = url.getParameter('q');

In this case the value of paramQ will be 1.

var allParameters = url.getParameters();

The value of allParameters will be the parameter names only.

["q","t"]

Tested on IE,chrome and firefox.

How to assign execute permission to a .sh file in windows to be executed in linux

As far as I know the permission system in Linux is set up in such a way to prevent exactly what you are trying to accomplish.

I think the best you can do is to give your Linux user a custom unzip one-liner to run on the prompt:

unzip zip_name.zip && chmod +x script_name.sh

If there are multiple scripts that you need to give execute permission to, write a grant_perms.sh as follows:

#!/bin/bash
# file: grant_perms.sh

chmod +x script_1.sh
chmod +x script_2.sh
...
chmod +x script_n.sh

(You can put the scripts all on one line for chmod, but I found separate lines easier to work with in vim and with shell script commands.)

And now your unzip one-liner becomes:

unzip zip_name.zip && source grant_perms.sh

Note that since you are using source to run grant_perms.sh, it doesn't need execute permission

How can I increment a date by one day in Java?

java.time

On Java 8 and later, the java.time package makes this pretty much automatic. (Tutorial)

Assuming String input and output:

import java.time.LocalDate;

public class DateIncrementer {
  static public String addOneDay(String date) {
    return LocalDate.parse(date).plusDays(1).toString();
  }
}

Sort Dictionary by keys

Swift 5

Input your dictionary that you want to sort alphabetically by keys.

// Sort inputted dictionary with keys alphabetically.
func sortWithKeys(_ dict: [String: Any]) -> [String: Any] {
    let sorted = dict.sorted(by: { $0.key < $1.key })
    var newDict: [String: Any] = [:]
    for sortedDict in sorted {
        newDict[sortedDict.key] = sortedDict.value
    }
    return newDict
}

dict.sorted(by: { $0.key < $1.key }) by it self returns a tuple (value, value) instead of a dictionary [value: value]. Thus, the for loop parses the tuple to return as a dictionary. That way, you put in a dictionary & get a dictionary back.

Any reason not to use '+' to concatenate two strings?

Plus operator is perfectly fine solution to concatenate two Python strings. But if you keep adding more than two strings (n > 25) , you might want to think something else.

''.join([a, b, c]) trick is a performance optimization.

HTML5 - mp4 video does not play in IE9

Internet Explorer 9 support MPEG4 using H.264 codec. But it also required that the file can start to play as soon as it starts downloading.

Here are the very basic steps on how to make a MPEG file that works in IE9 (using avconv on Ubuntu). I spent many hours to figure that out, so I hope that it can help someone else.

  1. Convert the video to MPEG4 using H.264 codec. You don't need anything fancy, just let avconv do the job for you:

    avconv -i video.mp4 -vcodec libx264 pre_out.mp4
    
  2. This video will works on all browsers that support MPEG4, except IE9. To add support for IE9, you have to move the file info to the file header, so the browser can start playing it as soon as it starts to download it. THIS IS THE KEY FOR IE9!!!

    qt-faststart pre_out.mp4 out.mp4
    

qt-faststart is a Quicktime utilities that also support H.264/ACC file format. It is part of libav-tools package.

Using Caps Lock as Esc in Mac OS X

You can also use DoubleCommand to remap this, and other keys.

IIRC, it will map Caps Lock to Esc.

Listview Scroll to the end of the list after updating the list

I use

setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);

to add entries at the bottom, and older entries scroll off the top, like a chat transcript

substring index range

0: U

1: n

2: i

3: v

4: e

5: r

6: s

7: i

8: t

9: y

Start index is inclusive

End index is exclusive

Javadoc link

android edittext onchange listener

I have done it using AutotextView:

AutotextView textView = (AutotextView) findViewById(R.id.autotextview);
textView.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
        seq = cs;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int arg1, int arg2, int arg3) {

    }

    @Override
    public void afterTextChanged(Editable arg0) {
        new SearchTask().execute(seq.toString().trim());
    }

});

get one item from an array of name,value JSON

I don't know anything about jquery so can't help you with that, but as far as Javascript is concerned you have an array of objects, so what you will only be able to access the names & values through each array element. E.g arr[0].name will give you 'k1', arr[1].value will give you 'hi'.

Maybe you want to do something like:

var obj = {};

obj.k1 = "abc";
obj.k2 = "hi";
obj.k3 = "oa";

alert ("obj.k2:" + obj.k2);

Get a DataTable Columns DataType

What you want to use is this property:

dt.Columns[0].DataType

The DataType property will set to one of the following:

Boolean
Byte
Char
DateTime
Decimal
Double
Int16
Int32
Int64
SByte
Single
String
TimeSpan
UInt16
UInt32
UInt64

DataColumn.DataType Property MSDN Reference

Why is it important to override GetHashCode when Equals method is overridden?

You should always guarantee that if two objects are equal, as defined by Equals(), they should return the same hash code. As some of the other comments state, in theory this is not mandatory if the object will never be used in a hash based container like HashSet or Dictionary. I would advice you to always follow this rule though. The reason is simply because it is way too easy for someone to change a collection from one type to another with the good intention of actually improving the performance or just conveying the code semantics in a better way.

For example, suppose we keep some objects in a List. Sometime later someone actually realizes that a HashSet is a much better alternative because of the better search characteristics for example. This is when we can get into trouble. List would internally use the default equality comparer for the type which means Equals in your case while HashSet makes use of GetHashCode(). If the two behave differently, so will your program. And bear in mind that such issues are not the easiest to troubleshoot.

I've summarized this behavior with some other GetHashCode() pitfalls in a blog post where you can find further examples and explanations.

How to increase maximum execution time in php

Use the PHP function

void set_time_limit ( int $seconds )

The maximum execution time, in seconds. If set to zero, no time limit is imposed.

This function has no effect when PHP is running in safe mode. There is no workaround other than turning off safe mode or changing the time limit in the php.ini.

Bootstrap 3: Text overlay on image

try the following example. Image overlay with text on image. demo

<div class="thumbnail">
  <img src="https://s3.amazonaws.com/discount_now_staging/uploads/ed964a11-e089-4c61-b927-9623a3fe9dcb/direct_uploader_2F50cc1daf-465f-48f0-8417-b04ac68a999d_2FN_19_jewelry.jpg" alt="..."   />
  <div class="caption post-content">  
  </div> 
  <div class="details">
    <h3>Robots!</h3>
    <p>Lorem ipsum dolor sit amet</p>   
  </div>  
</div>

css

.post-content {
    background: rgba(0, 0, 0, 0.7) none repeat scroll 0 0;
    opacity: 0.5;
    top:0;
    left:0;
    min-width: 500px;
    min-height: 500px; 
    position: absolute;
    color: #ffffff; 
}

.thumbnail{
    position:relative;

}
.details {
    position: absolute; 
    z-index: 2; 
    top: 0;
    color: #ffffff; 
}

Permission denied error on Github Push

I had this problem too but managed to solve it, the error is that ur computer has saved a git username and password so if you shift to another account the error 403 will appear. Below is the solution For Windows you can find the keys here:

control panel > user accounts > credential manager > Windows credentials > Generic credentials

Next remove the Github keys.

libclntsh.so.11.1: cannot open shared object file.

For the benefit of anyone else coming here by far the best thing to do is to update cx_Oracle to the latest version (6+). This version does not need LD_LIBRARY_PATH set at all.

How to wrap text using CSS?

This will work everywhere.

<body>
  <table style="table-layout:fixed;">
  <tr>
    <td><div style="word-wrap: break-word; width: 100px" > gdfggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg</div></td>
  </tr>
  </table>
 </body>

set date in input type date

to me the shortest way to solve this problem is to use moment.js and solve this problem in just 2 lines.

var today = moment().format('YYYY-MM-DD');
$('#datePicker').val(today);

moment.js, how to get day of week number

You can get this in 2 way using moment and also using Javascript

_x000D_
_x000D_
const date = moment("2015-07-02"); // Thursday Feb 2015_x000D_
const usingMoment_1 = date.day();_x000D_
const usingMoment_2 = date.isoWeekday();_x000D_
_x000D_
console.log('usingMoment: date.day() ==> ',usingMoment_1);_x000D_
console.log('usingMoment: date.isoWeekday() ==> ',usingMoment_2);_x000D_
_x000D_
_x000D_
const usingJS= new Date("2015-07-02").getDay();_x000D_
console.log('usingJavaSript: new Date("2015-07-02").getDay() ===> ',usingJS);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

How do I use NSTimer?

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(timerCalled) userInfo:nil repeats:NO];

-(void)timerCalled
{
     NSLog(@"Timer Called");
     // Your Code
}

Remove all values within one list from another list?

>>> a = range(1, 10)
>>> [x for x in a if x not in [2, 3, 7]]
[1, 4, 5, 6, 8, 9]

Dropdown using javascript onchange

easy

<script>
jQuery.noConflict()(document).ready(function() {
    $('#hide').css('display','none');
    $('#plano').change(function(){

        if(document.getElementById('plano').value == 1){
            $('#hide').show('slow');    

        }else 
            if(document.getElementById('plano').value == 0){

             $('#hide').hide('slow'); 
        }else
            if(document.getElementById('plano').value == 0){
             $('#hide').css('display','none');  

            }

    });
    $('#plano').change();
});
</script>

this example shows and hides the div if selected in combobox some specific value

Cannot find vcvarsall.bat when running a Python script

In 2015, if you still getting this confusing error, blame python default setuptools that PIP uses.

  1. Download and install minimal Microsoft Visual C++ Compiler for Python 2.7 required to compile python 2.7 modules from http://www.microsoft.com/en-in/download/details.aspx?id=44266
  2. Update your setuptools - pip install -U setuptools
  3. Install whatever python package you want that require C compilation. pip install blahblah

It will work fine.

UPDATE: It won't work fine for all libraries. I still get some error with few modules, that require lib-headers. They only thing that work flawlessly is Linux platform

Python PDF library

There is also http://appyframework.org/pod.html which takes a LibreOffice or OpenOffice document as template and can generate pdf, rtf, odt ... To generate pdf it requires a headless OOo on some server. Documentation is concise but relatively complete. http://appyframework.org/podWritingTemplates.html If you need advice, the author is rather helpful.

Vba macro to copy row from table if value in table meets condition

Try it like this:

Sub testIt()
Dim r As Long, endRow as Long, pasteRowIndex As Long

endRow = 10 ' of course it's best to retrieve the last used row number via a function
pasteRowIndex = 1

For r = 1 To endRow 'Loop through sheet1 and search for your criteria

    If Cells(r, Columns("B").Column).Value = "YourCriteria" Then 'Found

            'Copy the current row
            Rows(r).Select 
            Selection.Copy

            'Switch to the sheet where you want to paste it & paste
            Sheets("Sheet2").Select
            Rows(pasteRowIndex).Select
            ActiveSheet.Paste

            'Next time you find a match, it will be pasted in a new row
            pasteRowIndex = pasteRowIndex + 1


           'Switch back to your table & continue to search for your criteria
            Sheets("Sheet1").Select  
    End If
Next r
End Sub

Git submodule head 'reference is not a tree' error

Possible cause

This can happens when:

  1. Submodule(s) have been edited in place
  2. Submodule(s) committed, which updates the hash of the submodule being pointed to
  3. Submodule(s) not pushed.

e.g. something like this happened:

$ cd submodule
$ emacs my_source_file  # edit some file(s)
$ git commit -am "Making some changes but will forget to push!"

Should have submodule pushed at this point.

$ cd .. # back to parent repository
$ git commit -am "updates to parent repository"
$ git push origin master

As a result, the missing commits could not possibly be found by the remote user because they are still on the local disk.

Solution

Informa the person who modified the submodule to push, i.e.

$ cd submodule
$ git push

AngularJS event on window innerWidth size change

If Khanh TO's solution caused UI issues for you (like it did for me) try using $timeout to not update the attribute until it has been unchanged for 500ms.

var oldWidth = window.innerWidth;
$(window).on('resize.doResize', function () {
    var newWidth = window.innerWidth,
        updateStuffTimer;

    if (newWidth !== oldWidth) {
        $timeout.cancel(updateStuffTimer);
    }

    updateStuffTimer = $timeout(function() {
         updateStuff(newWidth); // Update the attribute based on window.innerWidth
    }, 500);
});

$scope.$on('$destroy',function (){
    $(window).off('resize.doResize'); // remove the handler added earlier
});

Reference: https://gist.github.com/tommaitland/7579618

TypeError: unhashable type: 'dict'

A possible solution might be to use the JSON dumps() method, so you can convert the dictionary to a string ---

import json

a={"a":10, "b":20}
b={"b":20, "a":10}
c = [json.dumps(a), json.dumps(b)]


set(c)
json.dumps(a) in c

Output -

set(['{"a": 10, "b": 20}'])
True

Pycharm: run only part of my Python file

You can select a code snippet and use right click menu to choose the action "Execute Selection in console".

Read from file or stdin

You may want to look at how this is done in the cat utility, for example.

See code here. If there is no filename as argument, or it is "-", then stdin is used for input. stdin will be there, even if no data is pushed to it (but then, your read call may wait forever).

"Eliminate render-blocking CSS in above-the-fold content"

The 2019 optimal solution for this is HTTP/2 Server Push.

You do not need any hacky javascript solutions or inline styles. However, you do need a server that supports HTTP 2.0 (any modern server version will), which itself requires your server to run SSL. However, with Let's Encrypt there's no reason not to be using SSL anyway.

My site https://r.je/ has a 100/100 score for both mobile and desktop.

The reason for these errors is that the browser gets the HTML, then has to wait for the CSS to be downloaded before the page can be rendered. Using HTTP2 you can send both the HTML and the CSS at the same time.

You can use HTTP/2 push by setting the Link header.

Apache example (.htaccess):

Header add Link "</style.css>; as=style; rel=preload, </font.css>; as=style; rel=preload"

For NGINX you can add the header to your location tag in the server configuration:

location = / {
    add_header Link "</style.css>; as=style; rel=preload, </font.css>; as=style; rel=preload";
}

With this header set, the browser receives the HTML and CSS at the same time which stops the CSS from blocking rendering.

You will want to tweak it so that the CSS is only sent on the first request, but the Link header is the most complete and least hacky solution to "Eliminate Render Blocking Javascript and CSS"

For a detailed discussion, take a look at my post here: Eliminate Render Blocking CSS using HTTP/2 Push

ERROR 1064 (42000): You have an error in your SQL syntax; Want to configure a password as root being the user

Try this one. It may be helpful:

mysql> UPDATE mysql.user SET Password = PASSWORD('pwd') WHERE User='root';

I hope it helps.

Why is a "GRANT USAGE" created the first time I grant a user privileges?

In addition mysql passwords when not using the IDENTIFIED BY clause, may be blank values, if non-blank, they may be encrypted. But yes USAGE is used to modify an account by granting simple resource limiters such as MAX_QUERIES_PER_HOUR, again this can be specified by also using the WITH clause, in conjuction with GRANT USAGE(no privileges added) or GRANT ALL, you can also specify GRANT USAGE at the global level, database level, table level,etc....

Why doesn't "System.out.println" work in Android?

System.out.println("...") is displayed on the Android Monitor in Android Studio

Is there a way to specify how many characters of a string to print out using printf()?

In addition to specify a fixed amount of characters, you can also use * which means that printf takes the number of characters from an argument:

#include <stdio.h>

int main(int argc, char *argv[])
{
        const char hello[] = "Hello world";
        printf("message: '%.3s'\n", hello);
        printf("message: '%.*s'\n", 3, hello);
        printf("message: '%.*s'\n", 5, hello);
        return 0;
}

Prints:

message: 'Hel'
message: 'Hel'
message: 'Hello'

What is the difference between Integrated Security = True and Integrated Security = SSPI?

In my point of view,

If you dont use Integrated security=SSPI,then you need to hardcode the username and password in the connection string which means "relatively insecure" why because, all the employees have the access even ex-employee could use the information maliciously.

cpp / c++ get pointer value or depointerize pointer

To get the value of a pointer, just de-reference the pointer.

int *ptr;
int value;
*ptr = 9;

value = *ptr;

value is now 9.

I suggest you read more about pointers, this is their base functionality.

Simple GUI Java calculator

This is the working code...

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

public class JavaCalculator extends JFrame {

    private JButton jbtNum1;
    private JButton jbtNum2;
    private JButton jbtNum3;
    private JButton jbtNum4;
    private JButton jbtNum5;
    private JButton jbtNum6;
    private JButton jbtNum7;
    private JButton jbtNum8;
    private JButton jbtNum9;
    private JButton jbtNum0;
    private JButton jbtEqual;
    private JButton jbtAdd;
    private JButton jbtSubtract;
    private JButton jbtMultiply;
    private JButton jbtDivide;
    private JButton jbtSolve;
    private JButton jbtClear;
    private double TEMP;
    private double SolveTEMP;
    private JTextField jtfResult;

    Boolean addBool = false;
    Boolean subBool = false;
    Boolean divBool = false;
    Boolean mulBool = false;

    String display = "";

    public JavaCalculator() {

        JPanel p1 = new JPanel();
        p1.setLayout(new GridLayout(4, 3));
        p1.add(jbtNum1 = new JButton("1"));
        p1.add(jbtNum2 = new JButton("2"));
        p1.add(jbtNum3 = new JButton("3"));
        p1.add(jbtNum4 = new JButton("4"));
        p1.add(jbtNum5 = new JButton("5"));
        p1.add(jbtNum6 = new JButton("6"));
        p1.add(jbtNum7 = new JButton("7"));
        p1.add(jbtNum8 = new JButton("8"));
        p1.add(jbtNum9 = new JButton("9"));
        p1.add(jbtNum0 = new JButton("0"));
        p1.add(jbtClear = new JButton("C"));

        JPanel p2 = new JPanel();
        p2.setLayout(new FlowLayout());
        p2.add(jtfResult = new JTextField(20));
        jtfResult.setHorizontalAlignment(JTextField.RIGHT);
        jtfResult.setEditable(false);

        JPanel p3 = new JPanel();
        p3.setLayout(new GridLayout(5, 1));
        p3.add(jbtAdd = new JButton("+"));
        p3.add(jbtSubtract = new JButton("-"));
        p3.add(jbtMultiply = new JButton("*"));
        p3.add(jbtDivide = new JButton("/"));
        p3.add(jbtSolve = new JButton("="));

        JPanel p = new JPanel();
        p.setLayout(new GridLayout());
        p.add(p2, BorderLayout.NORTH);
        p.add(p1, BorderLayout.SOUTH);
        p.add(p3, BorderLayout.EAST);

        add(p);

        jbtNum1.addActionListener(new ListenToOne());
        jbtNum2.addActionListener(new ListenToTwo());
        jbtNum3.addActionListener(new ListenToThree());
        jbtNum4.addActionListener(new ListenToFour());
        jbtNum5.addActionListener(new ListenToFive());
        jbtNum6.addActionListener(new ListenToSix());
        jbtNum7.addActionListener(new ListenToSeven());
        jbtNum8.addActionListener(new ListenToEight());
        jbtNum9.addActionListener(new ListenToNine());
        jbtNum0.addActionListener(new ListenToZero());

        jbtAdd.addActionListener(new ListenToAdd());
        jbtSubtract.addActionListener(new ListenToSubtract());
        jbtMultiply.addActionListener(new ListenToMultiply());
        jbtDivide.addActionListener(new ListenToDivide());
        jbtSolve.addActionListener(new ListenToSolve());
        jbtClear.addActionListener(new ListenToClear());
    } //JavaCaluclator()

    class ListenToClear implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            //display = jtfResult.getText();
            jtfResult.setText("");
            addBool = false;
            subBool = false;
            mulBool = false;
            divBool = false;

            TEMP = 0;
            SolveTEMP = 0;
        }
    }

    class ListenToOne implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "1");
        }
    }

    class ListenToTwo implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "2");
        }
    }

    class ListenToThree implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "3");
        }
    }

    class ListenToFour implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "4");
        }
    }

    class ListenToFive implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "5");
        }
    }

    class ListenToSix implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "6");
        }
    }

    class ListenToSeven implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "7");
        }
    }

    class ListenToEight implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "8");
        }
    }

    class ListenToNine implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "9");
        }
    }

    class ListenToZero implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "0");
        }
    }

    class ListenToAdd implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            TEMP = Double.parseDouble(jtfResult.getText());
            jtfResult.setText("");
            addBool = true;
        }
    }

    class ListenToSubtract implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            TEMP = Double.parseDouble(jtfResult.getText());
            jtfResult.setText("");
            subBool = true;
        }
    }

    class ListenToMultiply implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            TEMP = Double.parseDouble(jtfResult.getText());
            jtfResult.setText("");
            mulBool = true;
        }
    }

    class ListenToDivide implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            TEMP = Double.parseDouble(jtfResult.getText());
            jtfResult.setText("");
            divBool = true;
        }
    }

    class ListenToSolve implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            SolveTEMP = Double.parseDouble(jtfResult.getText());
            if (addBool == true)
                SolveTEMP = SolveTEMP + TEMP;
            else if ( subBool == true)
                SolveTEMP = SolveTEMP - TEMP;
            else if ( mulBool == true)
                SolveTEMP = SolveTEMP * TEMP;
            else if ( divBool == true)
                            SolveTEMP = SolveTEMP / TEMP;
            jtfResult.setText(  Double.toString(SolveTEMP));

            addBool = false;
            subBool = false;
            mulBool = false;
            divBool = false;
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JavaCalculator calc = new JavaCalculator();
        calc.pack();
        calc.setLocationRelativeTo(null);
                calc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        calc.setVisible(true);
    }

} //JavaCalculator

Stashing only staged changes in git - is it possible?

Another approach to this is to create a temporary commit with files you don't want to be stashed, then stash remaining files and gently remove last commit, keeping the files intact:

git add *files that you don't want to be stashed*
git commit -m "temp"
git stash --include-untracked
git reset --soft HEAD~1

That way you only touch files that you want to be touched.

Note, "--include-untracked" is used here to also stash new files (which is probably what you really want).

Is it possible to set a custom font for entire of application?

A brilliant solution can be found here: https://coderwall.com/p/qxxmaa/android-use-a-custom-font-everywhere.

Simply extend activities from BaseActivity and write those methods. Also you should better cache fonts as described here: https://stackoverflow.com/a/16902532/2914140.


After some research I wrote code that works at Samsung Galaxy Tab A (Android 5.0). Used code of weston and Roger Huang as well as https://stackoverflow.com/a/33236102/2914140. Also tested on Lenovo TAB 2 A10-70L, where it doesn't work. I inserted a font 'Comic Sans' here in order to see a difference.

import android.content.Context;
import android.graphics.Typeface;
import android.os.Build;
import android.util.Log;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class FontsOverride {
    private static final int BOLD = 1;
    private static final int BOLD_ITALIC = 2;
    private static final int ITALIC = 3;
    private static final int LIGHT = 4;
    private static final int CONDENSED = 5;
    private static final int THIN = 6;
    private static final int MEDIUM = 7;
    private static final int REGULAR = 8;

    private Context context;

    public FontsOverride(Context context) {
        this.context = context;
    }

    public void loadFonts() {
        Map<String, Typeface> fontsMap = new HashMap<>();
        fontsMap.put("sans-serif", getTypeface("comic.ttf", REGULAR));
        fontsMap.put("sans-serif-bold", getTypeface("comic.ttf", BOLD));
        fontsMap.put("sans-serif-italic", getTypeface("comic.ttf", ITALIC));
        fontsMap.put("sans-serif-light", getTypeface("comic.ttf", LIGHT));
        fontsMap.put("sans-serif-condensed", getTypeface("comic.ttf", CONDENSED));
        fontsMap.put("sans-serif-thin", getTypeface("comic.ttf", THIN));
        fontsMap.put("sans-serif-medium", getTypeface("comic.ttf", MEDIUM));
        overrideFonts(fontsMap);
    }

    private void overrideFonts(Map<String, Typeface> typefaces) {
        if (Build.VERSION.SDK_INT == 21) {
            try {
                final Field field = Typeface.class.getDeclaredField("sSystemFontMap");
                field.setAccessible(true);
                Map<String, Typeface> oldFonts = (Map<String, Typeface>) field.get(null);
                if (oldFonts != null) {
                    oldFonts.putAll(typefaces);
                } else {
                    oldFonts = typefaces;
                }
                field.set(null, oldFonts);
                field.setAccessible(false);
            } catch (Exception e) {
                Log.e("TypefaceUtil", "Cannot set custom fonts");
            }
        } else {
            try {
                for (Map.Entry<String, Typeface> entry : typefaces.entrySet()) {
                    final Field staticField = Typeface.class.getDeclaredField(entry.getKey());
                    staticField.setAccessible(true);
                    staticField.set(null, entry.getValue());
                }
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    private Typeface getTypeface(String fontFileName, int fontType) {
        final Typeface tf = Typeface.createFromAsset(context.getAssets(), "fonts/" + fontFileName);
        return Typeface.create(tf, fontType);
    }
}

To run the code in entire application you should write in some class like Application the following:

    new FontsOverride(this).loadFonts();

Create a folder 'fonts' inside 'assets' and put needed fonts there. A simple instruction may be found here: https://stackoverflow.com/a/31697103/2914140.

The Lenovo device also incorrectly gets a value of a typeface. In most times it returns Typeface.NORMAL, sometimes null. Even if a TextView is bold (in xml-file layout). See here: TextView isBold always returns NORMAL. This way a text on a screen is always in a regural font, not bold or italic. So I think it's a bug of a producer.

How to specify the download location with wget?

man wget: -O file --output-document=file

wget "url" -O /tmp/cron_test/<file>

Docker-Compose with multiple services

The thing is that you are using the option -t when running your container.

Could you check if enabling the tty option (see reference) in your docker-compose.yml file the container keeps running?

version: '2'
services:
  ubuntu:
        build: .
        container_name: ubuntu
        volumes:
            - ~/sph/laravel52:/www/laravel
        ports:
          - "80:80"
        tty: true

PostgreSQL: How to change PostgreSQL user password?

Configuration that I've got on my server was customized a lot and I managed to change password only after I set trust authentication in the pg_hba.conf file:

local   all   all   trust

Don't forget to change this back to password or md5

Concatenate a list of pandas dataframes together

If the dataframes DO NOT all have the same columns try the following:

df = pd.DataFrame.from_dict(map(dict,df_list))

How to replace a character by a newline in Vim

\r can do the work here for you.

How to programmatically send SMS on the iPhone?

One of the systems of inter-process communication in MacOS is XPC. This system layer has been developed for inter-process communication based on the transfer of plist structures using libSystem and launchd. In fact, it is an interface that allows managing processes via the exchange of such structures as dictionaries. Due to heredity, iOS 5 possesses this mechanism as well.

You might already understand what I mean by this introduction. Yep, there are system services in iOS that include tools for XPC communication. And I want to exemplify the work with a daemon for SMS sending. However, it should be mentioned that this ability is fixed in iOS 6, but is relevant for iOS 5.0—5.1.1. Jailbreak, Private Framework, and other illegal tools are not required for its exploitation. Only the set of header files from the directory /usr/include/xpc/* are needed.

One of the elements for SMS sending in iOS is the system service com.apple.chatkit, the tasks of which include generation, management, and sending of short text messages. For the ease of control, it has the publicly available communication port com.apple.chatkit.clientcomposeserver.xpc. Using the XPC subsystem, you can generate and send messages without user's approval.

Well, let's try to create a connection.

xpc_connection_t myConnection;

dispatch_queue_t queue = dispatch_queue_create("com.apple.chatkit.clientcomposeserver.xpc", DISPATCH_QUEUE_CONCURRENT);

myConnection = xpc_connection_create_mach_service("com.apple.chatkit.clientcomposeserver.xpc", queue, XPC_CONNECTION_MACH_SERVICE_PRIVILEGED);

Now we have the XPC connection myConnection set to the service of SMS sending. However, XPC configuration provides for creation of suspended connections —we need to take one more step for the activation.

xpc_connection_set_event_handler(myConnection, ^(xpc_object_t event){
xpc_type_t xtype = xpc_get_type(event);
if(XPC_TYPE_ERROR == xtype)
{
NSLog(@"XPC sandbox connection error: %s\n", xpc_dictionary_get_string(event, XPC_ERROR_KEY_DESCRIPTION));
}
// Always set an event handler. More on this later.

NSLog(@"Received a message event!");

});

xpc_connection_resume(myConnection);

The connection is activated. Right at this moment iOS 6 will display a message in the telephone log that this type of communication is forbidden. Now we need to generate a dictionary similar to xpc_dictionary with the data required for the message sending.

NSArray *recipient = [NSArray arrayWithObjects:@"+7 (90*) 000-00-00", nil];

NSData *ser_rec = [NSPropertyListSerialization dataWithPropertyList:recipient format:200 options:0 error:NULL];

xpc_object_t mydict = xpc_dictionary_create(0, 0, 0);
xpc_dictionary_set_int64(mydict, "message-type", 0);
xpc_dictionary_set_data(mydict, "recipients", [ser_rec bytes], [ser_rec length]);
xpc_dictionary_set_string(mydict, "text", "hello from your application!");

Little is left: send the message to the XPC port and make sure it is delivered.

xpc_connection_send_message(myConnection, mydict);
xpc_connection_send_barrier(myConnection, ^{
NSLog(@"The message has been successfully delivered");
});

That's all. SMS sent.

How to define unidirectional OneToMany relationship in JPA

My bible for JPA work is the Java Persistence wikibook. It has a section on unidirectional OneToMany which explains how to do this with a @JoinColumn annotation. In your case, i think you would want:

@OneToMany
@JoinColumn(name="TXTHEAD_CODE")
private Set<Text> text;

I've used a Set rather than a List, because the data itself is not ordered.

The above is using a defaulted referencedColumnName, unlike the example in the wikibook. If that doesn't work, try an explicit one:

@OneToMany
@JoinColumn(name="TXTHEAD_CODE", referencedColumnName="DATREG_META_CODE")
private Set<Text> text;

Change Button color onClick

Every time setColor gets hit, you are setting count = 1. You would need to define count outside of the scope of the function. Example:

var count=1;
function setColor(btn, color){
    var property = document.getElementById(btn);
    if (count == 0){
        property.style.backgroundColor = "#FFFFFF"
        count=1;        
    }
    else{
        property.style.backgroundColor = "#7FFF00"
        count=0;
    }

}

Logical operator in a handlebars.js {{#if}} conditional

You can use the following code:

{{#if selection1}}
    doSomething1
{{else}}
   {{#if selection2}}
       doSomething2
   {{/if}}
{{/if}}

WCF change endpoint address at runtime

We store our URLs in a database and load them at runtime.

public class ServiceClientFactory<TChannel> : ClientBase<TChannel> where TChannel : class
{
    public TChannel Create(string url)
    {
        this.Endpoint.Address = new EndpointAddress(new Uri(url));
        return this.Channel;
    }
}

Implementation

var client = new ServiceClientFactory<yourServiceChannelInterface>().Create(newUrl);

How to solve WAMP and Skype conflict on Windows 7?

I know this posting is old, but I had the same problem, WAMP would not go online (green) while SKYPE was running. I simply closed SKYPE, ran WAMP and then reloaded SKYPE. I have not verified this, but I think SKYPE port corrected to allow for WAMP settings. At least I have not experienced any problems doing it this way

Get Excel sheet name and use as variable in macro

in a Visual Basic Macro you would use

pName = ActiveWorkbook.Path      ' the path of the currently active file
wbName = ActiveWorkbook.Name     ' the file name of the currently active file
shtName = ActiveSheet.Name       ' the name of the currently selected worksheet

The first sheet in a workbook can be referenced by

ActiveWorkbook.Worksheets(1)

so after deleting the [Report] tab you would use

ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name

to "work on that sheet later on" you can create a range object like

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]

and continue working on MySheet(rowNum, colNum) etc. ...

shortcut creation of a range object without defining shtName:

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]

what does "error : a nonstatic member reference must be relative to a specific object" mean?

CPMSifDlg::EncodeAndSend() method is declared as non-static and thus it must be called using an object of CPMSifDlg. e.g.

CPMSifDlg obj;
return obj.EncodeAndSend(firstName, lastName, roomNumber, userId, userFirstName, userLastName);

If EncodeAndSend doesn't use/relate any specifics of an object (i.e. this) but general for the class CPMSifDlg then declare it as static:

class CPMSifDlg {
...
  static int EncodeAndSend(...);
  ^^^^^^
};

Getting the closest string match

A sample using C# is here.

public static void Main()
{
    Console.WriteLine("Hello World " + LevenshteinDistance("Hello","World"));
    Console.WriteLine("Choice A " + LevenshteinDistance("THE BROWN FOX JUMPED OVER THE RED COW","THE RED COW JUMPED OVER THE GREEN CHICKEN"));
    Console.WriteLine("Choice B " + LevenshteinDistance("THE BROWN FOX JUMPED OVER THE RED COW","THE RED COW JUMPED OVER THE RED COW"));
    Console.WriteLine("Choice C " + LevenshteinDistance("THE BROWN FOX JUMPED OVER THE RED COW","THE RED FOX JUMPED OVER THE BROWN COW"));
}

public static float LevenshteinDistance(string a, string b)
{
    var rowLen = a.Length;
    var colLen = b.Length;
    var maxLen = Math.Max(rowLen, colLen);

    // Step 1
    if (rowLen == 0 || colLen == 0)
    {
        return maxLen;
    }

    /// Create the two vectors
    var v0 = new int[rowLen + 1];
    var v1 = new int[rowLen + 1];

    /// Step 2
    /// Initialize the first vector
    for (var i = 1; i <= rowLen; i++)
    {
        v0[i] = i;
    }

    // Step 3
    /// For each column
    for (var j = 1; j <= colLen; j++)
    {
        /// Set the 0'th element to the column number
        v1[0] = j;

        // Step 4
        /// For each row
        for (var i = 1; i <= rowLen; i++)
        {
            // Step 5
            var cost = (a[i - 1] == b[j - 1]) ? 0 : 1;

            // Step 6
            /// Find minimum
            v1[i] = Math.Min(v0[i] + 1, Math.Min(v1[i - 1] + 1, v0[i - 1] + cost));
        }

        /// Swap the vectors
        var vTmp = v0;
        v0 = v1;
        v1 = vTmp;
    }

    // Step 7
    /// The vectors were swapped one last time at the end of the last loop,
    /// that is why the result is now in v0 rather than in v1
    return v0[rowLen];
}

The output is:

Hello World 4
Choice A 15
Choice B 6
Choice C 8

Difference between null and empty ("") Java String

What your statements are telling you is just that "" isn't the same as null - which is true. "" is an empty string; null means that no value has been assigned.

It might be more enlightening to try:

System.out.println(a.length()); // 0
System.out.println(b.length()); // error; b is not an object

"" is still a string, meaning you can call its methods and get meaningful information. null is an empty variable - there's literally nothing there.

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

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

Here is a decent tutorial article.

Convert file to byte array and vice versa

Apache FileUtil gives very handy methods to do the conversion

try {
    File file = new File(imagefilePath);
    byte[] byteArray = new byte[file.length()]();
    byteArray = FileUtils.readFileToByteArray(file);  
 }catch(Exception e){
     e.printStackTrace();

 }

Overflow:hidden dots at the end

<style>
    .dots
    {
        display: inline-block;
        width: 325px;
        white-space: nowrap;
        overflow: hidden !important;
        text-overflow: ellipsis;
    }

    .dot
    {
        display: inline-block;
        width: 185px;
        white-space: nowrap;
        overflow: hidden !important;
        text-overflow: ellipsis;
    }
</style>

Can I change the Android startActivity() transition animation?

You can simply create a context and do something like below:-

private Context context = this;

And your animation:-

((Activity) context).overridePendingTransition(R.anim.abc_slide_in_bottom,R.anim.abc_slide_out_bottom);

You can use any animation you want.

How do I float a div to the center?

You can do it inline like this

<div style="margin:0px auto"></div>

or you can do it via class

<div class="x"><div>

in your css file or between <style></style> add this .x{margin:0px auto}

or you can simply use the center tag

  <center>
    <div></div>
  </center>

or if you using absolute position, you can do

.x{
   width: 140px;
   position: absolute;
   top: 0px;
   left: 50%;
   margin-left: -70px; /*half the size of width*/
}

Difference between IsNullOrEmpty and IsNullOrWhiteSpace in C#

IsNullOrWhiteSpace is a convenience method that is similar to the following code, except that it offers superior performance:

return String.IsNullOrEmpty(value) || value.Trim().Length == 0;

White-space characters are defined by the Unicode standard. The IsNullOrWhiteSpace method interprets any character that returns a value of true when it is passed to the Char.IsWhiteSpace method as a white-space character.

angular.element vs document.getElementById or jQuery selector with spin (busy) control

You should inject $document in your controller, and use it instead of original document object.

var myElement = angular.element($document[0].querySelector('#MyID'))

If you don't need the jquery style element wrap, $document[0].querySelector('#MyID') will give you the DOM object.

How to check if a user is logged in (how to properly use user.is_authenticated)?

Following block should work:

    {% if user.is_authenticated %}
        <p>Welcome {{ user.username }} !!!</p>       
    {% endif %}

How to get first object out from List<Object> using Linq

You also can use this:

var firstOrDefault = lstComp.FirstOrDefault();
if(firstOrDefault != null) 
{
    //doSmth
}

How to install a specific version of a package with pip?

Use ==:

pip install django_modeltranslation==0.4.0-beta2

Show/hide forms using buttons and JavaScript

There's something I bet you already heard about this! It's called jQuery.

$("#button1").click(function() {
    $("#form1").show();
};

It's really easy and you can use CSS-like selectors and you can add animations. It's really easy to learn.

month name to month number and vice versa in python

def month_num2abbr(month):
    month = int(month)
    import calendar
    months_abbr = {month: index for index, month in enumerate(calendar.month_abbr) if month}
    for abbr, month_num in months_abbr.items():
        if month_num==month:
            return abbr
    return False

print(month_num2abbr(7))

Node.js/Express routing with get params

For Query parameters like domain.com/test?format=json&type=mini format, then you can easily receive it via - req.query.

app.get('/test', function(req, res){
  var format = req.query.format,
      type = req.query.type;
});

How to Automatically Start a Download in PHP?

Send the following headers before outputting the file:

header("Content-Disposition: attachment; filename=\"" . basename($File) . "\"");
header("Content-Type: application/octet-stream");
header("Content-Length: " . filesize($File));
header("Connection: close");

@grom: Interesting about the 'application/octet-stream' MIME type. I wasn't aware of that, have always just used 'application/force-download' :)

Add Bootstrap Glyphicon to Input Box

If you are using Fontawesome you can do this :

<input type="text" style="font-family:Arial, FontAwesome"  placeholder="&#xf007;" />

Result

enter image description here

The complete list of unicode can be found in the The complete Font Awesome 4.6.3 icon reference

Add SUM of values of two LISTS into new LIST

From docs

import operator
list(map(operator.add, first,second))

Select default option value from typescript angular 6

For reactive form, I managed to make it work by using the following example (47 can be replaced with other value or variable):

<div [formGroup]="form">
  <select formControlName="fieldName">
    <option
        *ngFor="let option of options; index as i"
        [selected]="option === 47"
    >
        {{ option }}
    </option>
  </select>
</div>

javascript - replace dash (hyphen) with a space

var str = "This-is-a-news-item-";
while (str.contains("-")) {
  str = str.replace("-", ' ');
}
alert(str);

I found that one use of str.replace() would only replace the first hyphen, so I looped thru while the input string still contained any hyphens, and replaced them all.

http://jsfiddle.net/LGCYF/

Can't import org.apache.http.HttpResponse in Android Studio

Use This:-

compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'

How to read GET data from a URL using JavaScript?

It’s 2019 and there is no need for any hand-written solution or third-party library. If you want to parse the URL of current page in browser:

# running on https://www.example.com?name=n1&name=n2
let params = new URLSearchParams(location.search);
params.get('name') # => "n1"
params.getAll('name') # => ["n1", "n2"]

If you want to parse a random URL, either in browser or in Node.js:

let url = 'https://www.example.com?name=n1&name=n2';
let params = (new URL(url)).searchParams;
params.get('name') # => "n1"
params.getAll('name') # => ["n1", "n2"]

It’s making use of the URLSearchParams interface that comes with modern browsers.

How can I find the latitude and longitude from address?

The following code will work for google apiv2:

public void convertAddress() {
    if (address != null && !address.isEmpty()) {
        try {
            List<Address> addressList = geoCoder.getFromLocationName(address, 1);
            if (addressList != null && addressList.size() > 0) {
                double lat = addressList.get(0).getLatitude();
                double lng = addressList.get(0).getLongitude();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } // end catch
    } // end if
} // end convertAddress

Where address is the String (123 Testing Rd City State zip) you want to convert to LatLng.

Android setOnClickListener method - How does it work?

This is the best way to implement Onclicklistener for many buttons in a row implement View.onclicklistener.

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

This is a button in the MainActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    bt_submit = (Button) findViewById(R.id.submit);

    bt_submit.setOnClickListener(this);
}

This is an override method

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.submit:
                //action

                break;

            case R.id.secondbutton:
                //action
                break;
        }
    }

What is the difference between declarative and imperative paradigm in programming?

Declarative programming is when you say what you want, and imperative language is when you say how to get what you want.

A simple example in Python:

# Declarative
small_nums = [x for x in range(20) if x < 5]

# Imperative
small_nums = []
for i in range(20):
    if i < 5:
        small_nums.append(i)

The first example is declarative because we do not specify any "implementation details" of building the list.

To tie in a C# example, generally, using LINQ results in a declarative style, because you aren't saying how to obtain what you want; you are only saying what you want. You could say the same about SQL.

One benefit of declarative programming is that it allows the compiler to make decisions that might result in better code than what you might make by hand. Running with the SQL example, if you had a query like

SELECT score FROM games WHERE id < 100;

the SQL "compiler" can "optimize" this query because it knows that id is an indexed field -- or maybe it isn't indexed, in which case it will have to iterate over the entire data set anyway. Or maybe the SQL engine knows that this is the perfect time to utilize all 8 cores for a speedy parallel search. You, as a programmer, aren't concerned with any of those conditions, and you don't have to write your code to handle any special case in that way.

Create a .txt file if doesn't exist, and if it does append a new line

You don't actually have to check if the file exists, as StreamWriter will do that for you. If you open it in append-mode, the file will be created if it does not exists, then you will always append and never over write. So your initial check is redundant.

TextWriter tw = new StreamWriter(path, true);
tw.WriteLine("The next line!");
tw.Close(); 

How to set javascript variables using MVC4 with Razor

I use a very simple function to solve syntax errors in body of JavaScript codes that mixed with Razor codes ;)

function n(num){return num;}

var nonID = n(@nonProID);
var proID= n(@proID);

What is the best way to insert source code examples into a Microsoft Word document?

I absolutely hate and despise working for free for Microsoft, given how after all those billions of dollars they STILL do not to have proper guides about stuff like this with screenshots on their damn website.

Anyways, here is a quick guide in Word 2010, using Notepad++ for syntax coloring, and a TextBox which can be captioned:

  1. Choose Insert / Text Box / Simple Text Box
    01word
  2. A default text box is inserted
    02word
  3. Switch to NPP, choose the language for syntax coloring of your code, go to Plugins / NPPExport / Copy RTF to clipboard
    03npp
  4. Switch back to word, and paste into the text box - it may be too small ...
    04word
  5. ... so you may have to change its size
    05word
  6. Having selected the text box, right-click on it, then choose Insert Caption ...
    06word
  7. In the Caption menu, if you don't have one already, click New Label, and set the new label to "Code", click OK ...
    07word
  8. ... then in the Caption dialog, switch the label to Code, and hit OK
    08word
  9. Finally, type your caption in the newly created caption box
    09word

Spring: @Component versus @Bean

1. About @Component
@Component functs similarily to @Configuration.

They both indicate that the annotated class has one or more beans need to be registered to Spring-IOC-Container.

The class annotated by @Component, we call it Component of Spring. It is a concept that contains several beans.

Component class needs to be auto-scanned by Spring for registering those beans of the component class.

2. About @Bean
@Bean is used to annotate the method of component-class(as mentioned above). It indicate the instance retured by the annotated method needs to be registered to Spring-IOC-Container.

3. Conclusion
The difference between them two is relatively obivious, they are used in different circumstances. The general usage is:

    // @Configuration is implemented by @Component
    @Configuration
    public ComponentClass {

      @Bean
      public FirstBean FirstBeanMethod() {
        return new FirstBean();
      }

      @Bean
      public SecondBean SecondBeanMethod() {
        return new SecondBean();
      }
    }

Reading a registry key in C#

If you want it casted to a specific type you can use this method. Most non primitive types won't by default support direct casting so you will have to handle those accordingly.

  public T GetValue<T>(string registryKeyPath, string value, T defaultValue = default(T))
  {
    T retVal = default(T);

      retVal = (T)Registry.GetValue(registryKeyPath, value, defaultValue);

      return retVal;
  }

Less aggressive compilation with CSS3 calc

There's a tidier way to include variables inside the escaped calc, as explained in this post: CSS3 calc() function doesn't work with Less #974

@variable: 2em;

body{ width: calc(~"100% - @{variable} * 2");}

By using the curly brackets you don't need to close and reopen the escaping quotes.

How to make tesseract to recognize only numbers, when they are mixed with letters?

What I do is to recognize everything, and when I have the text, I take out all the characters except numbers

//This replaces all except numbers from 0 to 9
recognizedText = recognizedText.replaceAll("[^0-9]+", " ");

This works pretty well for me.

Assigning the return value of new by reference is deprecated

It happened because of PHP 5.3 , which comes in WAMP 2.0i package and not Joomla.

You have two choices to fix it,

either use WAMP 2h (previous version) or download PHP 5.2.9-2 addon from WAMP website.

How do you make a LinearLayout scrollable?

Wrap the linear layout with a <ScrollView>

See here for an example:

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout 
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       xmlns:android="http://schemas.android.com/apk/res/android">
       <ScrollView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">
            <LinearLayout 
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:orientation="vertical">
                  <!-- Content here -->
            </LinearLayout>
      </ScrollView>
 </LinearLayout>

Note: fill_parent is deprecated and renamed to match_parent in API Level 8 and higher.

\r\n, \r and \n what is the difference between them?

They are normal symbols as 'a' or '?' or any other. Just (invisible) entries in a string. \r moves cursor to the beginning of the line. \n goes one line down.

As for your replacement, you haven't specified what language you're using, so here's the sketch:

someString.replace("\r\n", "\n").replace("\r", "\n")

VSCode cannot find module '@angular/core' or any other modules

In my case, when i upgrade vs project to angular 10, I had this errors.

Angular cli creates tsconfig.json, tsconfig.base.json and tsconfig.app.json when i delete tsconfig.json and rename tsconfig.base.json to tsconfig.ts all things will Ok. you must also change extends inside tsconfig.app.json to tsconfig.json

How to set ObjectId as a data type in mongoose

My solution on using ObjectId

// usermodel.js

const mongoose = require('mongoose')
const Schema = mongoose.Schema
const ObjectId = Schema.Types.ObjectId


let UserSchema = new Schema({
   username: {
     type: String
   },
   events: [{
     type: ObjectId,
     ref: 'Event' // Reference to some EventSchema
   }]
})

UserSchema.set('autoIndex', true)

module.exports = mongoose.model('User', UserSchema)

Using mongoose's populate method

// controller.js

const mongoose = require('mongoose')
const User = require('./usermodel.js')

let query = User.findOne({ name: "Person" })

query.exec((err, user) => {
  if (err) {
     console.log(err)
  }

  user.events = events
  // user.events is now an array of events
})

Load dimension value from res/values/dimension.xml from source code

Use a Kotlin Extension

You can add an extension to simplify this process. It enables you to just call context.dp(R.dimen. tutorial_cross_marginTop) to get the Float value

fun Context.px(@DimenRes dimen: Int): Int = resources.getDimension(dimen).toInt()

fun Context.dp(@DimenRes dimen: Int): Float = px(dimen) / resources.displayMetrics.density

If you want to handle it without context, you can use Resources.getSystem():

val Int.dp get() = this / Resources.getSystem().displayMetrics.density // Float

val Int.px get() = (this * Resources.getSystem().displayMetrics.density).toInt()

For example, on an xhdpi device, use 24.dp to get 12.0 or 12.px to get 24

Private properties in JavaScript ES6 classes

I have a workaround that works woo and it pretty simple... although performance is prob not the pest... but it works and works well.

The trick is that until private properties and functions are established and standardized/adopted work arounds are required and this is another workaround...

class ClassPrivateProperties {
    constructor(instance) {
        const $this = instance;
        let properties = {};
        this.prop = (key, value = undefined) => {
            if (!value) {
                return properties[key];
            } else {
                properties[key] = value;
            }
        };
        this.clear = instance => {
            if ($this === instance) {
                properties = {};
                return true;
            } else {
                return false;
            }
        }
    }
}

This is a sample usage that can be what ever (also if you use the above feel free to make it better)

class Test {
    constructor() {
        this._privateProps = new ClassPrivateProperties(this);
    }
    property(key, value = undefined) {
        if (!value) {
            return this._privateProps.prop(key);
        } else {
            this._privateProps.prop(key, value);
        }
    }
    clear() { return this._privateProps.clear(this); }
}
const test = new test;
test.property('myKey','some value here');
console.log(test.property('myKey'));

Like I mentioned that this prob not the best of the best but it works and makes properties truly private.

How to properly compare two Integers in Java?

== will still test object equality. It is easy to be fooled, however:

Integer a = 10;
Integer b = 10;

System.out.println(a == b); //prints true

Integer c = new Integer(10);
Integer d = new Integer(10);

System.out.println(c == d); //prints false

Your examples with inequalities will work since they are not defined on Objects. However, with the == comparison, object equality will still be checked. In this case, when you initialize the objects from a boxed primitive, the same object is used (for both a and b). This is an okay optimization since the primitive box classes are immutable.

Rails: Adding an index after adding column

Add in the generated migration after creating the column the following (example)

add_index :photographers, :email, :unique => true

How do I read a response from Python Requests?

Requests doesn't have an equivalent to Urlib2's read().

>>> import requests
>>> response = requests.get("http://www.google.com")
>>> print response.content
'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage"><head>....'
>>> print response.content == response.text
True

It looks like the POST request you are making is returning no content. Which is often the case with a POST request. Perhaps it set a cookie? The status code is telling you that the POST succeeded after all.

Edit for Python 3:

Python now handles data types differently. response.content returns a sequence of bytes (integers that represent ASCII) while response.text is a string (sequence of chars).

Thus,

>>> print response.content == response.text
False

>>> print str(response.content) == response.text
True

How to retrieve SQL result column value using column name in Python?

You didn't provide many details, but you could try something like this:

# conn is an ODBC connection to the DB
dbCursor = conn.cursor()
sql = ('select field1, field2 from table') 
dbCursor = conn.cursor()
dbCursor.execute(sql)
for row in dbCursor:
    # Now you should be able to access the fields as properties of "row"
    myVar1 = row.field1
    myVar2 = row.field2
conn.close()

C# - Fill a combo box with a DataTable

You need to set the binding context of the ToolStripComboBox.ComboBox.

Here is a slightly modified version of the code that I have just recreated using Visual Studio. The menu item combo box is called toolStripComboBox1 in my case. Note the last line of code to set the binding context.

I noticed that if the combo is in the visible are of the toolstrip, the binding works without this but not when it is in a drop-down. Do you get the same problem?

If you can't get this working, drop me a line via my contact page and I will send you the project. You won't be able to load it using SharpDevelop but will with C# Express.

var languages = new string[2];
languages[0] = "English";
languages[1] = "German";

DataSet myDataSet = new DataSet();

// --- Preparation
DataTable lTable = new DataTable("Lang");
DataColumn lName = new DataColumn("Language", typeof(string));
lTable.Columns.Add(lName);

for (int i = 0; i < languages.Length; i++)
{
    DataRow lLang = lTable.NewRow();
    lLang["Language"] = languages[i];
    lTable.Rows.Add(lLang);
}
myDataSet.Tables.Add(lTable);

toolStripComboBox1.ComboBox.DataSource = myDataSet.Tables["Lang"].DefaultView;
toolStripComboBox1.ComboBox.DisplayMember = "Language";

toolStripComboBox1.ComboBox.BindingContext = this.BindingContext;

How to recover Git objects damaged by hard disk failure?

The solution by Daniel Fanjul looked promissing. I was able to find that blob file and extracted it ("git fsck --full --no-dangling", "git cat-file -t {hash}", "git show {hash} > file.tmp") but when I tried to update pack file with "git hash-object -w file.tmp", it displayed correct hash BUT the error remained.

So I decided to try different approach. I could simply delete local repository and download everything from remote but some branches in local repository were 8 commits ahead and I did not want to lose those changes. Since that tiny, 6kb mp3 file, I decided to delete it completely. I tried many ways but the best was from here: https://itextpdf.com/en/blog/technical-notes/how-completely-remove-file-git-repository

I got the file name by running this command "git rev-list --objects --all | grep {hash}". Then I did a backup (strongly recommend to do so because I failed 3 times) and then run the command:

"java -jar bfg.jar --delete-files {filename} --no-blob-protection ."

You can get bfg.jar file from here https://rtyley.github.io/bfg-repo-cleaner/ so according to documentation I should run this command next:

"git reflog expire --expire=now --all && git gc --prune=now --aggressive"

When I did so, I got errors on last step. So I recovered everything from backup and this time, after removing file, I checkout to the branch (which was causing that error), then check out back to main and only after run the command one after each other:

"git reflog expire --expire=now --all" "git gc --prune=now --aggressive"

Then I added my file back to its location and comit. However, since many local commits were changed, I was not able to push anything to server. So I backup everything on server (in case I screw it), check out to the branch which was affected and run the command "git push --force".

What I understood from this case? GIT is great but so senstive... I should have an option to simply disregard one f... 6kb file I know what I am doing. I have no clude why "git hash-object -w" did not work either =( Lessons learnt, push all commits, do not wait, do backup of repository time to time. Also I know how to remove files from repository, if I ever need =)

I hope this saves someone's time

PHP salt and hash SHA256 for login password

These examples are from php.net. Thanks to you, I also just learned about the new php hashing functions.

Read the php documentation to find out about the possibilities and best practices: http://www.php.net/manual/en/function.password-hash.php

Save a password hash:

$options = [
    'cost' => 11,
];
// Get the password from post
$passwordFromPost = $_POST['password'];

$hash = password_hash($passwordFromPost, PASSWORD_BCRYPT, $options);

// Now insert it (with login or whatever) into your database, use mysqli or pdo!

Get the password hash:

// Get the password from the database and compare it to a variable (for example post)
$passwordFromPost = $_POST['password'];
$hashedPasswordFromDB = ...;

if (password_verify($passwordFromPost, $hashedPasswordFromDB)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}

Python DNS module import error

One possible reason here might be your script have wrong shebang (so it is not using python from your virtualenv). I just did this change and it works:

-#!/bin/python
+#!/usr/bin/env python

Or ignore shebang and just run the script with python in your venv:

$ python your_script.py

How to make a transparent border using CSS?

Using the :before pseudo-element,
CSS3's border-radius,
and some transparency is quite easy:

LIVE DEMO

enter image description here

<div class="circle"></div>

CSS:

.circle, .circle:before{
  position:absolute;
  border-radius:150px;  
}
.circle{  
  width:200px;
  height:200px;
  z-index:0;
  margin:11%;
  padding:40px;
  background: hsla(0, 100%, 100%, 0.6);   
}
.circle:before{
  content:'';
  display:block;
  z-index:-1;  
  width:200px;
  height:200px;

  padding:44px;
  border: 6px solid hsla(0, 100%, 100%, 0.6);
  /* 4px more padding + 6px border = 10 so... */  
  top:-10px;
  left:-10px; 
}

The :before attaches to our .circle another element which you only need to make (ok, block, absolute, etc...) transparent and play with the border opacity.

WCF Service , how to increase the timeout?

The best way is to change any setting you want in your code.

Check out the below example:

using(WCFServiceClient client = new WCFServiceClient ())
{ 
    client.Endpoint.Binding.SendTimeout = new TimeSpan(0, 1, 30);
}

How do I delete rows in a data frame?

You can also work with a so called boolean vector, aka logical:

row_to_keep = c(TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE)
myData = myData[row_to_keep,]

Note that the ! operator acts as a NOT, i.e. !TRUE == FALSE:

myData = myData[!row_to_keep,]

This seems a bit cumbersome in comparison to @mrwab's answer (+1 btw :)), but a logical vector can be generated on the fly, e.g. where a column value exceeds a certain value:

myData = myData[myData$A > 4,]
myData = myData[!myData$A > 4,] # equal to myData[myData$A <= 4,]

You can transform a boolean vector to a vector of indices:

row_to_keep = which(myData$A > 4)

Finally, a very neat trick is that you can use this kind of subsetting not only for extraction, but also for assignment:

myData$A[myData$A > 4,] <- NA

where column A is assigned NA (not a number) where A exceeds 4.

Can I calculate z-score with R?

if x is a vector with raw scores then scale(x) is a vector with standardized scores.

Or manually: (x-mean(x))/sd(x)

Resize image with javascript canvas (smoothly)

I created a library that allows you to downstep any percentage while keeping all the color data.

https://github.com/danschumann/limby-resize/blob/master/lib/canvas_resize.js

That file you can include in the browser. The results will look like photoshop or image magick, preserving all the color data, averaging pixels, rather than taking nearby ones and dropping others. It doesn't use a formula to guess the averages, it takes the exact average.

How to create a laravel hashed password

Hashing A Password Using Bcrypt in Laravel:

$password = Hash::make('yourpassword');

This will create a hashed password. You may use it in your controller or even in a model, for example, if a user submits a password using a form to your controller using POST method then you may hash it using something like this:

$password = Input::get('passwordformfield'); // password is form field
$hashed = Hash::make($password);

Here, $hashed will contain the hashed password. Basically, you'll do it when creating/registering a new user, so, for example, if a user submits details such as, name, email, username and password etc using a form, then before you insert the data into database, you'll hash the password after validating the data. For more information, read the documentation.

Update:

$password = 'JohnDoe';
$hashedPassword = Hash::make($password);
echo $hashedPassword; // $2y$10$jSAr/RwmjhwioDlJErOk9OQEO7huLz9O6Iuf/udyGbHPiTNuB3Iuy

So, you'll insert the $hashedPassword into database. Hope, it's clear now and if still you are confused then i suggest you to read some tutorials, watch some screen casts on laracasts.com and tutsplus.com and also read a book on Laravel, this is a free ebook, you may download it.

Update: Since OP wants to manually encrypt password using Laravel Hash without any class or form so this is an alternative way using artisan tinker from command prompt:

  1. Go to your command prompt/terminal
  2. Navigate to the Laravel installation (your project's root directory)
  3. Use cd <directory name> and press enter from command prompt/terminal
  4. Then write php artisan tinker and press enter
  5. Then write echo Hash::make('somestring');
  6. You'll get a hashed password on the console, copy it and then do whatever you want to do.

Update (Laravel 5.x):

// Also one can use bcrypt
$password = bcrypt('JohnDoe');

C: convert double to float, preserving decimal point precision

float and double don't store decimal places. They store binary places: float is (assuming IEEE 754) 24 significant bits (7.22 decimal digits) and double is 53 significant bits (15.95 significant digits).

Converting from double to float will give you the closest possible float, so rounding won't help you. Goining the other way may give you "noise" digits in the decimal representation.

#include <stdio.h>

int main(void) {
    double orig = 12345.67;
    float f = (float) orig;
    printf("%.17g\n", f); // prints 12345.669921875
    return 0;
}

To get a double approximation to the nice decimal value you intended, you can write something like:

double round_to_decimal(float f) {
    char buf[42];
    sprintf(buf, "%.7g", f); // round to 7 decimal digits
    return atof(buf);
}

Convert string to nullable type (int, double, etc...)

You could try using the below extension method:

public static T? GetValueOrNull<T>(this string valueAsString)
    where T : struct 
{
    if (string.IsNullOrEmpty(valueAsString))
        return null;
    return (T) Convert.ChangeType(valueAsString, typeof(T));
}

This way you can do this:

double? amount = strAmount.GetValueOrNull<double>();
int? amount = strAmount.GetValueOrNull<int>();
decimal? amount = strAmount.GetValueOrNull<decimal>();

Reference to a non-shared member requires an object reference occurs when calling public sub

You either have to make the method Shared or use an instance of the class General:

Dim gen = New General()
gen.updateDynamics(get_prospect.dynamicsID)

or

General.updateDynamics(get_prospect.dynamicsID)

Public Shared Sub updateDynamics(dynID As Int32)
    ' ... '
End Sub

Shared(VB.NET)

Setting background images in JFrame

Try this :

import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;


public class Test {

    public static void main(String[] args) {
        JFrame f = new JFrame();
        try {
            f.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("test.jpg")))));
        } catch (IOException e) {
            e.printStackTrace();
        }
        f.pack();
        f.setVisible(true);
    }

}

By the way, this will result in the content pane not being a container. If you want to add things to it you have to subclass a JPanel and override the paintComponent method.

CURL to access a page that requires a login from a different page

Also you might want to log in via browser and get the command with all headers including cookies:

Open the Network tab of Developer Tools, log in, navigate to the needed page, use "Copy as cURL".

screenshot

ggplot2 plot without axes, legends, etc

Late to the party, but might be of interest...

I find a combination of labs and guides specification useful in many cases:

You want nothing but a grid and a background:

ggplot(diamonds, mapping = aes(x = clarity)) + 
  geom_bar(aes(fill = cut)) + 
  labs(x = NULL, y = NULL) + 
  guides(x = "none", y = "none")

enter image description here

You want to only suppress the tick-mark label of one or both axes:

ggplot(diamonds, mapping = aes(x = clarity)) + 
  geom_bar(aes(fill = cut)) + 
  guides(x = "none", y = "none")

enter image description here

How to dynamically change the color of the selected menu item of a web page?

I use PHP to find the URL and match the page name (without the extension of .php, also I can add multiple pages that all have the same word in common like contact, contactform, etc. All will have that class added) and add a class with PHP to change the color, etc. For that you would have to save your pages with file extension .php.

Here is a demo. Change your links and pages as required. The CSS class for all the links is .tab and for the active link there is also another class of .currentpage (as is the PHP function) so that is where you will overwrite your CSS rules. You could name them whatever you like.

<?php # Using REQUEST_URI
    $currentpage = $_SERVER['REQUEST_URI'];?>
    <div class="nav">
        <div class="tab
             <?php
                 if(preg_match("/index/i", $currentpage)||($currentpage=="/"))
                     echo " currentpage";
             ?>"><a href="index.php">Home</a>
         </div>
         <div class="tab
             <?php
                 if(preg_match("/services/i", $currentpage))
                     echo " currentpage";
             ?>"><a href="services.php">Services</a>
         </div>
         <div class="tab
             <?php
                 if(preg_match("/about/i", $currentpage))
                     echo " currentpage";
             ?>"><a href="about.php">About</a>
         </div>
         <div class="tab
             <?php
                 if(preg_match("/contact/i", $currentpage))
                     echo " currentpage";
             ?>"><a href="contact.php">Contact</a>
         </div>
     </div> <!--nav-->

How to implement onBackPressed() in Fragments?

You should add interface to your project like below;

public interface OnBackPressed {

     void onBackPressed();
}

And then, you should implement this interface on your fragment;

public class SampleFragment extends Fragment implements OnBackPressed {

    @Override
    public void onBackPressed() {
        //on Back Pressed
    }

}

And you can trigger this onBackPressed event under your activities onBackPressed event like below;

public class MainActivity extends AppCompatActivity {
       @Override
        public void onBackPressed() {
                Fragment currentFragment = getSupportFragmentManager().getFragments().get(getSupportFragmentManager().getBackStackEntryCount() - 1);
                if (currentFragment instanceof OnBackPressed) {  
                    ((OnBackPressed) currentFragment).onBackPressed();
                }
                super.onBackPressed();
        }
}

How to remove old Docker containers

I'm using:

docker rm -v $(docker ps -a -q -f status=exited)

to delete exited containers and:

docker rmi -f $(docker images | grep "<none>" | awk "{print \$3}")

in order to get rid of all untagged images.

Need to list all triggers in SQL Server database with table name and table's schema

I had the same task recently and I used the following for sql server 2012 db. Use management studio and connect to the database you want to search. Then execute the following script.

Select 
[tgr].[name] as [trigger name], 
[tbl].[name] as [table name]

from sysobjects tgr 

join sysobjects tbl
on tgr.parent_obj = tbl.id

WHERE tgr.xtype = 'TR'

Measuring text height to be drawn on Canvas ( Android )

There are different ways to measure the height depending on what you need.

getTextBounds

If you are doing something like precisely centering a small amount of fixed text, you probably want getTextBounds. You can get the bounding rectangle like this

Rect bounds = new Rect();
mTextPaint.getTextBounds(mText, 0, mText.length(), bounds);
int height = bounds.height();

As you can see for the following images, different strings will give different heights (shown in red).

enter image description here

These differing heights could be a disadvantage in some situations when you just need a constant height no matter what the text is. See the next section.

Paint.FontMetrics

You can calculate the hight of the font from the font metrics. The height is always the same because it is obtained from the font, not any particular text string.

Paint.FontMetrics fm = mTextPaint.getFontMetrics();
float height = fm.descent - fm.ascent;

The baseline is the line that the text sits on. The descent is generally the furthest a character will go below the line and the ascent is generally the furthest a character will go above the line. To get the height you have to subtract ascent because it is a negative value. (The baseline is y=0 and y descreases up the screen.)

Look at the following image. The heights for both of the strings are 234.375.

enter image description here

If you want the line height rather than just the text height, you could do the following:

float height = fm.bottom - fm.top + fm.leading; // 265.4297

These are the bottom and top of the line. The leading (interline spacing) is usually zero, but you should add it anyway.

The images above come from this project. You can play around with it to see how Font Metrics work.

StaticLayout

For measuring the height of multi-line text you should use a StaticLayout. I talked about it in some detail in this answer, but the basic way to get this height is like this:

String text = "This is some text. This is some text. This is some text. This is some text. This is some text. This is some text.";

TextPaint myTextPaint = new TextPaint();
myTextPaint.setAntiAlias(true);
myTextPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
myTextPaint.setColor(0xFF000000);

int width = 200;
Layout.Alignment alignment = Layout.Alignment.ALIGN_NORMAL;
float spacingMultiplier = 1;
float spacingAddition = 0;
boolean includePadding = false;

StaticLayout myStaticLayout = new StaticLayout(text, myTextPaint, width, alignment, spacingMultiplier, spacingAddition, includePadding);

float height = myStaticLayout.getHeight(); 

TypeScript getting error TS2304: cannot find name ' require'

In my case, it was a super stupid problem, where the src/tsconfig.app.json was overriding the tsconfig.json setting.

So, I had this in tsconfig.json:

    "types": [
      "node"
    ]

And this one in src/tsconfig.app.json:

    "types": []

I hope someone finds this helpful, as this error was causing me gray hairs.

Maximum and Minimum values for ints

You may use 'inf' like this:

import math
bool_true = 0 < math.inf
bool_false = 0 < -math.inf

Refer: math — Mathematical functions

Regex pattern to match at least 1 number and 1 character in a string

And an idea with a negative check.

/^(?!\d*$|[a-z]*$)[a-z\d]+$/i
  • ^(?! at start look ahead if string does not
  • \d*$ contain only digits | or
  • [a-z]*$ contain only letters
  • [a-z\d]+$ matches one or more letters or digits until $ end.

Have a look at this regex101 demo

(the i flag turns on caseless matching: a-z matches a-zA-Z)

Bash ignoring error for a particular command

No solutions worked for me from here, so I found another one:

set +e
find "./csharp/Platform.$REPOSITORY_NAME/obj" -type f -iname "*.cs" -delete
find "./csharp/Platform.$REPOSITORY_NAME.Tests/obj" -type f -iname "*.cs" -delete
set -e

This is useful for CI & CD. This way the error messages are printed but the whole script continues to execute.

Change mysql user password using command line

Your login root should be /usr/local/directadmin/conf/mysql.conf. Then try following

UPDATE mysql.user SET password=PASSWORD('$w0rdf1sh') WHERE user='tate256' AND Host='10.10.2.30';
FLUSH PRIVILEGES;

Host is your mysql host.

xlsxwriter: is there a way to open an existing worksheet in my workbook?

You can use the workbook.get_worksheet_by_name() feature: https://xlsxwriter.readthedocs.io/workbook.html#get_worksheet_by_name

According to https://xlsxwriter.readthedocs.io/changes.html the feature has been added on May 13, 2016.

"Release 0.8.7 - May 13 2016

-Fix for issue when inserting read-only images on Windows. Issue #352.

-Added get_worksheet_by_name() method to allow the retrieval of a worksheet from a workbook via its name.

-Fixed issue where internal file creation and modification dates were in the local timezone instead of UTC."

Display HTML snippets in HTML

There are a few ways to escape everything in HTML, none of them nice.

Or you could put in an iframe that loads a plain old text file.

Close/kill the session when the browser or tab is closed

For browser close you can put below code into your web.config :

<system.web>
    <sessionState mode="InProc"></sessionState>
 </system.web>

It will destroy your session when browser is closed, but it will not work for tab close.

MySQL DISTINCT on a GROUP_CONCAT()

You can simply add DISTINCT in front.

SELECT GROUP_CONCAT(DISTINCT categories SEPARATOR ' ')

if you want to sort,

SELECT GROUP_CONCAT(DISTINCT categories ORDER BY categories ASC SEPARATOR ' ')

Is a Python dictionary an example of a hash table?

Yes, it is a hash mapping or hash table. You can read a description of python's dict implementation, as written by Tim Peters, here.

That's why you can't use something 'not hashable' as a dict key, like a list:

>>> a = {}
>>> b = ['some', 'list']
>>> hash(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable
>>> a[b] = 'some'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable

You can read more about hash tables or check how it has been implemented in python and why it is implemented that way.

Sort array by value alphabetically php

You want the php function "asort":

http://php.net/manual/en/function.asort.php

it sorts the array, maintaining the index associations.

Edit: I've just noticed you're using a standard array (non-associative). if you're not fussed about preserving index associations, use sort():

http://php.net/manual/en/function.sort.php

what is this value means 1.845E-07 in excel?

Highlight the cells, format cells, select Custom then select zero.

How to correctly implement custom iterators and const_iterators?

I'm going to show you how you can easily define iterators for your custom containers, but just in case I have created a c++11 library that allows you to easily create custom iterators with custom behavior for any type of container, contiguous or non-contiguous.

You can find it on Github

Here are the simple steps to creating and using custom iterators:

  1. Create your "custom iterator" class.
  2. Define typedefs in your "custom container" class.
    • e.g. typedef blRawIterator< Type > iterator;
    • e.g. typedef blRawIterator< const Type > const_iterator;
  3. Define "begin" and "end" functions
    • e.g. iterator begin(){return iterator(&m_data[0]);};
    • e.g. const_iterator cbegin()const{return const_iterator(&m_data[0]);};
  4. We're Done!!!

Finally, onto defining our custom iterator classes:

NOTE: When defining custom iterators, we derive from the standard iterator categories to let STL algorithms know the type of iterator we've made.

In this example, I define a random access iterator and a reverse random access iterator:

  1. //-------------------------------------------------------------------
    // Raw iterator with random access
    //-------------------------------------------------------------------
    template<typename blDataType>
    class blRawIterator
    {
    public:
    
        using iterator_category = std::random_access_iterator_tag;
        using value_type = blDataType;
        using difference_type = std::ptrdiff_t;
        using pointer = blDataType*;
        using reference = blDataType&;
    
    public:
    
        blRawIterator(blDataType* ptr = nullptr){m_ptr = ptr;}
        blRawIterator(const blRawIterator<blDataType>& rawIterator) = default;
        ~blRawIterator(){}
    
        blRawIterator<blDataType>&                  operator=(const blRawIterator<blDataType>& rawIterator) = default;
        blRawIterator<blDataType>&                  operator=(blDataType* ptr){m_ptr = ptr;return (*this);}
    
        operator                                    bool()const
        {
            if(m_ptr)
                return true;
            else
                return false;
        }
    
        bool                                        operator==(const blRawIterator<blDataType>& rawIterator)const{return (m_ptr == rawIterator.getConstPtr());}
        bool                                        operator!=(const blRawIterator<blDataType>& rawIterator)const{return (m_ptr != rawIterator.getConstPtr());}
    
        blRawIterator<blDataType>&                  operator+=(const difference_type& movement){m_ptr += movement;return (*this);}
        blRawIterator<blDataType>&                  operator-=(const difference_type& movement){m_ptr -= movement;return (*this);}
        blRawIterator<blDataType>&                  operator++(){++m_ptr;return (*this);}
        blRawIterator<blDataType>&                  operator--(){--m_ptr;return (*this);}
        blRawIterator<blDataType>                   operator++(int){auto temp(*this);++m_ptr;return temp;}
        blRawIterator<blDataType>                   operator--(int){auto temp(*this);--m_ptr;return temp;}
        blRawIterator<blDataType>                   operator+(const difference_type& movement){auto oldPtr = m_ptr;m_ptr+=movement;auto temp(*this);m_ptr = oldPtr;return temp;}
        blRawIterator<blDataType>                   operator-(const difference_type& movement){auto oldPtr = m_ptr;m_ptr-=movement;auto temp(*this);m_ptr = oldPtr;return temp;}
    
        difference_type                             operator-(const blRawIterator<blDataType>& rawIterator){return std::distance(rawIterator.getPtr(),this->getPtr());}
    
        blDataType&                                 operator*(){return *m_ptr;}
        const blDataType&                           operator*()const{return *m_ptr;}
        blDataType*                                 operator->(){return m_ptr;}
    
        blDataType*                                 getPtr()const{return m_ptr;}
        const blDataType*                           getConstPtr()const{return m_ptr;}
    
    protected:
    
        blDataType*                                 m_ptr;
    };
    //-------------------------------------------------------------------
    
  2. //-------------------------------------------------------------------
    // Raw reverse iterator with random access
    //-------------------------------------------------------------------
    template<typename blDataType>
    class blRawReverseIterator : public blRawIterator<blDataType>
    {
    public:
    
        blRawReverseIterator(blDataType* ptr = nullptr):blRawIterator<blDataType>(ptr){}
        blRawReverseIterator(const blRawIterator<blDataType>& rawIterator){this->m_ptr = rawIterator.getPtr();}
        blRawReverseIterator(const blRawReverseIterator<blDataType>& rawReverseIterator) = default;
        ~blRawReverseIterator(){}
    
        blRawReverseIterator<blDataType>&           operator=(const blRawReverseIterator<blDataType>& rawReverseIterator) = default;
        blRawReverseIterator<blDataType>&           operator=(const blRawIterator<blDataType>& rawIterator){this->m_ptr = rawIterator.getPtr();return (*this);}
        blRawReverseIterator<blDataType>&           operator=(blDataType* ptr){this->setPtr(ptr);return (*this);}
    
        blRawReverseIterator<blDataType>&           operator+=(const difference_type& movement){this->m_ptr -= movement;return (*this);}
        blRawReverseIterator<blDataType>&           operator-=(const difference_type& movement){this->m_ptr += movement;return (*this);}
        blRawReverseIterator<blDataType>&           operator++(){--this->m_ptr;return (*this);}
        blRawReverseIterator<blDataType>&           operator--(){++this->m_ptr;return (*this);}
        blRawReverseIterator<blDataType>            operator++(int){auto temp(*this);--this->m_ptr;return temp;}
        blRawReverseIterator<blDataType>            operator--(int){auto temp(*this);++this->m_ptr;return temp;}
        blRawReverseIterator<blDataType>            operator+(const int& movement){auto oldPtr = this->m_ptr;this->m_ptr-=movement;auto temp(*this);this->m_ptr = oldPtr;return temp;}
        blRawReverseIterator<blDataType>            operator-(const int& movement){auto oldPtr = this->m_ptr;this->m_ptr+=movement;auto temp(*this);this->m_ptr = oldPtr;return temp;}
    
        difference_type                             operator-(const blRawReverseIterator<blDataType>& rawReverseIterator){return std::distance(this->getPtr(),rawReverseIterator.getPtr());}
    
        blRawIterator<blDataType>                   base(){blRawIterator<blDataType> forwardIterator(this->m_ptr); ++forwardIterator; return forwardIterator;}
    };
    //-------------------------------------------------------------------
    

Now somewhere in your custom container class:

template<typename blDataType>
class blCustomContainer
{
public: // The typedefs

    typedef blRawIterator<blDataType>              iterator;
    typedef blRawIterator<const blDataType>        const_iterator;

    typedef blRawReverseIterator<blDataType>       reverse_iterator;
    typedef blRawReverseIterator<const blDataType> const_reverse_iterator;

                            .
                            .
                            .

public:  // The begin/end functions

    iterator                                       begin(){return iterator(&m_data[0]);}
    iterator                                       end(){return iterator(&m_data[m_size]);}

    const_iterator                                 cbegin(){return const_iterator(&m_data[0]);}
    const_iterator                                 cend(){return const_iterator(&m_data[m_size]);}

    reverse_iterator                               rbegin(){return reverse_iterator(&m_data[m_size - 1]);}
    reverse_iterator                               rend(){return reverse_iterator(&m_data[-1]);}

    const_reverse_iterator                         crbegin(){return const_reverse_iterator(&m_data[m_size - 1]);}
    const_reverse_iterator                         crend(){return const_reverse_iterator(&m_data[-1]);}

                            .
                            .
                            .
    // This is the pointer to the
    // beginning of the data
    // This allows the container
    // to either "view" data owned
    // by other containers or to
    // own its own data
    // You would implement a "create"
    // method for owning the data
    // and a "wrap" method for viewing
    // data owned by other containers

    blDataType*                                    m_data;
};

IPython/Jupyter Problems saving notebook as PDF

For Ubuntu users, an answer can be found here. I also quote it:

The most probable cause, is that you have not installed the appropriate dependencies. Your Ubuntu system has to have some packages installed regarding conversion of LaTeX and XeTeX files, in order to save your notebook as PDF. You can install them by:

sudo apt-get install texlive texlive-xetex texlive-generic-extra texlive-generic-recommended pandoc

Also, nbconvert is another dependency that is usually automatically installed with jupyter. But you can install it just to be sure, while having your virtual environment activated:

pip install -U nbconvert

Linux find file names with given string recursively

use ack its simple. just type ack <string to be searched>

Good Free Alternative To MS Access

In the context of a programming forum, we don't usually think of the programmer also needing the application portion of the database. Normally a programmer wants to use their own development environment for the business logic and front end, and just use the store, query, retrieval, and data processing capabilities of the database.

If you really want all those other things, then you're talking about a much larger and more complicated run time environment. You're not going to find anything that's 'lightweight' any more. Even MS Access itself no longer qualifies, because it's hardly light weight. It's just lucky in that a lot of users might already have it, making it appear to be light weight.

This doesn't mean you won't find anything. Just that it's not likely to have the same level of maturity or distribution as Access, especially since the underlying access engine is already baked into Windows.

automating telnet session using bash scripts

Write an expect script.

Here is an example:

#!/usr/bin/expect

#If it all goes pear shaped the script will timeout after 20 seconds.
set timeout 20
#First argument is assigned to the variable name
set name [lindex $argv 0]
#Second argument is assigned to the variable user
set user [lindex $argv 1]
#Third argument is assigned to the variable password
set password [lindex $argv 2]
#This spawns the telnet program and connects it to the variable name
spawn telnet $name 
#The script expects login
expect "login:" 
#The script sends the user variable
send "$user "
#The script expects Password
expect "Password:"
#The script sends the password variable
send "$password "
#This hands control of the keyboard over to you (Nice expect feature!)
interact

To run:

./myscript.expect name user password

java.sql.SQLException: - ORA-01000: maximum open cursors exceeded

In our case, we were using Hibernate and we had many variables referencing the same Hibernate mapped entity. We were creating and saving these references in a loop. Each reference opened a cursor and kept it open.

We discovered this by using a query to check the number of open cursors while running our code, stepping through with a debugger and selectively commenting things out.

As to why each new reference opened another cursor - the entity in question had collections of other entities mapped to it and I think this had something to do with it (perhaps not just this alone but in combination with how we had configured the fetch mode and cache settings). Hibernate itself has had bugs around failing to close open cursors, though it looks like these have been fixed in later versions.

Since we didn't really need to have so many duplicate references to the same entity anyway, the solution was to stop creating and holding onto all those redundant references. Once we did that the problem when away.

How to add message box with 'OK' button?

@Override
protected Dialog onCreateDialog(int id)
{
    switch(id)
    {
    case 0:
    {               
        return new AlertDialog.Builder(this)
        .setMessage("text here")
        .setPositiveButton("OK", new DialogInterface.OnClickListener() 
        {                   
            @Override
            public void onClick(DialogInterface arg0, int arg1) 
            {
                try
                {

                }//end try
                catch(Exception e)
                {
                    Toast.makeText(getBaseContext(),  "", Toast.LENGTH_LONG).show();
                }//end catch
            }//end onClick()
        }).create();                
    }//end case
  }//end switch
    return null;
}//end onCreateDialog

Getting the source HTML of the current page from chrome extension

Inject a script into the page you want to get the source from and message it back to the popup....

manifest.json

{
  "name": "Get pages source",
  "version": "1.0",
  "manifest_version": 2,
  "description": "Get pages source from a popup",
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": ["tabs", "<all_urls>"]
}

popup.html

<!DOCTYPE html>
<html style=''>
<head>
<script src='popup.js'></script>
</head>
<body style="width:400px;">
<div id='message'>Injecting Script....</div>
</body>
</html>

popup.js

chrome.runtime.onMessage.addListener(function(request, sender) {
  if (request.action == "getSource") {
    message.innerText = request.source;
  }
});

function onWindowLoad() {

  var message = document.querySelector('#message');

  chrome.tabs.executeScript(null, {
    file: "getPagesSource.js"
  }, function() {
    // If you try and inject into an extensions page or the webstore/NTP you'll get an error
    if (chrome.runtime.lastError) {
      message.innerText = 'There was an error injecting script : \n' + chrome.runtime.lastError.message;
    }
  });

}

window.onload = onWindowLoad;

getPagesSource.js

// @author Rob W <http://stackoverflow.com/users/938089/rob-w>
// Demo: var serialized_html = DOMtoString(document);

function DOMtoString(document_root) {
    var html = '',
        node = document_root.firstChild;
    while (node) {
        switch (node.nodeType) {
        case Node.ELEMENT_NODE:
            html += node.outerHTML;
            break;
        case Node.TEXT_NODE:
            html += node.nodeValue;
            break;
        case Node.CDATA_SECTION_NODE:
            html += '<![CDATA[' + node.nodeValue + ']]>';
            break;
        case Node.COMMENT_NODE:
            html += '<!--' + node.nodeValue + '-->';
            break;
        case Node.DOCUMENT_TYPE_NODE:
            // (X)HTML documents are identified by public identifiers
            html += "<!DOCTYPE " + node.name + (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '') + (!node.publicId && node.systemId ? ' SYSTEM' : '') + (node.systemId ? ' "' + node.systemId + '"' : '') + '>\n';
            break;
        }
        node = node.nextSibling;
    }
    return html;
}

chrome.runtime.sendMessage({
    action: "getSource",
    source: DOMtoString(document)
});

Open a workbook using FileDialog and manipulate it in Excel VBA

Thankyou Frank.i got the idea. Here is the working code.

Option Explicit
Private Sub CommandButton1_Click()

  Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
  Dim fd As Office.FileDialog

  Set fd = Application.FileDialog(msoFileDialogFilePicker)

  With fd
    .AllowMultiSelect = False
    .Title = "Please select the file."
    .Filters.Clear
    .Filters.Add "Excel 2003", "*.xls?"

    If .Show = True Then
      fileName = Dir(.SelectedItems(1))

    End If
  End With

  Application.ScreenUpdating = False
  Application.DisplayAlerts = False

  Workbooks.Open (fileName)

  For Each sheet In Workbooks(fileName).Worksheets
    total = Workbooks("import-sheets.xlsm").Worksheets.Count
    Workbooks(fileName).Worksheets(sheet.Name).Copy _
        after:=Workbooks("import-sheets.xlsm").Worksheets(total)
  Next sheet

  Workbooks(fileName).Close

  Application.ScreenUpdating = True
  Application.DisplayAlerts = True

End Sub

What does enctype='multipart/form-data' mean?

  • enctype(ENCode TYPE) attribute specifies how the form-data should be encoded when submitting it to the server.
  • multipart/form-data is one of the value of enctype attribute, which is used in form element that have a file upload. multi-part means form data divides into multiple parts and send to server.

DbEntityValidationException - How can I easily tell what caused the error?

As Martin indicated, there is more information in the DbEntityValidationResult. I found it useful to get both my POCO class name and property name in each message, and wanted to avoid having to write custom ErrorMessage attributes on all my [Required] tags just for this.

The following tweak to Martin's code took care of these details for me:

// Retrieve the error messages as a list of strings.
List<string> errorMessages = new List<string>();
foreach (DbEntityValidationResult validationResult in ex.EntityValidationErrors)
{
    string entityName = validationResult.Entry.Entity.GetType().Name;
    foreach (DbValidationError error in validationResult.ValidationErrors)
    {
        errorMessages.Add(entityName + "." + error.PropertyName + ": " + error.ErrorMessage);
    }
}

Iterating a JavaScript object's properties using jQuery

Late, but can be done by using Object.keys like,

_x000D_
_x000D_
var a={key1:'value1',key2:'value2',key3:'value3',key4:'value4'},_x000D_
  ulkeys=document.getElementById('object-keys'),str='';_x000D_
var keys = Object.keys(a);_x000D_
for(i=0,l=keys.length;i<l;i++){_x000D_
   str+= '<li>'+keys[i]+' : '+a[keys[i]]+'</li>';_x000D_
}_x000D_
ulkeys.innerHTML=str;
_x000D_
<ul id="object-keys"></ul>
_x000D_
_x000D_
_x000D_

CSS table layout: why does table-row not accept a margin?

Have you tried setting the bottom margin to .row div, i.e. to your "cells"? When you work with actual HTML tables, you cannot set margins to rows, too - only to cells.

Hibernate: get entity by id

Using EntityManager em;

public User getUserById(Long id) {
     return em.getReference(User.class, id);
}

Determining if an Object is of primitive type

commons-lang ClassUtils has relevant methods.

The new version has:

boolean isPrimitiveOrWrapped = 
    ClassUtils.isPrimitiveOrWrapper(object.getClass());

The old versions have wrapperToPrimitive(clazz) method, which will return the primitive correspondence.

boolean isPrimitiveOrWrapped = 
    clazz.isPrimitive() || ClassUtils.wrapperToPrimitive(clazz) != null;

Checking if output of a command contains a certain string in a shell script

Testing $? is an anti-pattern.

if ./somecommand | grep -q 'string'; then
  echo "matched"
fi

How could I put a border on my grid control in WPF?

This is a later answer that works for me, if it may be of use to anyone in the future. I wanted a simple border around all four sides of the grid and I achieved it like so...

<DataGrid x:Name="dgDisplay" Margin="5" BorderBrush="#1266a7" BorderThickness="1"...

tr:hover not working

Also try thistr:hover td {color: aqua;} `

Transmitting newline character "\n"

late to the party, but if anyone comes across this, javascript has a encodeURI method

OpenSSL: unable to verify the first certificate for Experian URL

I came across the same issue installing my signed certificate on an Amazon Elastic Load Balancer instance.

All seemed find via a browser (Chrome) but accessing the site via my java client produced the exception javax.net.ssl.SSLPeerUnverifiedException

What I had not done was provide a "certificate chain" file when installing my certificate on my ELB instance (see https://serverfault.com/questions/419432/install-ssl-on-amazon-elastic-load-balancer-with-godaddy-wildcard-certificate)

We were only sent our signed public key from the signing authority so I had to create my own certificate chain file. Using my browser's certificate viewer panel I exported each certificate in the signing chain. (The order of the certificate chain in important, see https://forums.aws.amazon.com/message.jspa?messageID=222086)

Why in C++ do we use DWORD rather than unsigned int?

For myself, I would assume unsigned int is platform specific. Integer could be 8 bits, 16 bits, 32 bits or even 64 bits.

DWORD in the other hand, specifies its own size, which is Double Word. Word are 16 bits so DWORD will be known as 32 bit across all platform

How do I increase the RAM and set up host-only networking in Vagrant?

You can modify various VM properties by adding the following configuration (see the Vagrant docs for a bit more info):

  # Configure VM Ram usage
  config.vm.customize [
                        "modifyvm", :id,
                        "--name", "Test_Environment",
                        "--memory", "1024"
                      ]

You can obtain the properties that you want to change from the documents for VirtualBox command-line options:

The vagrant documentation has the section on how to change IP address:

Vagrant::Config.run do |config|
  config.vm.network :hostonly, "192.168.50.4"
end

Also you can restructure the configuration like this, ending is do with end without nesting it. This is simpler.

config.vm.define :web do |web_config|
    web_config.vm.box = "lucid32"
    web_config.vm.forward_port 80, 8080
end
web_config.vm.provision :puppet do |puppet|
    puppet.manifests_path = "manifests"
    puppet.manifest_file = "lucid32.pp"
end

Copy data from one column to other column (which is in a different table)

Table2.Column2 => Table1.Column1

I realize this question is old but the accepted answer did not work for me. For future googlers, this is what worked for me:

UPDATE table1 
    SET column1 = (
        SELECT column2
        FROM table2
        WHERE table2.id = table1.id
    );

Whereby:

  • table1 = table that has the column that needs to be updated
  • table2 = table that has the column with the data
  • column1 = blank column that needs the data from column2 (this is in table1)
  • column2 = column that has the data (that is in table2)

How to print binary number via printf

printf() doesn't directly support that. Instead you have to make your own function.

Something like:

while (n) {
    if (n & 1)
        printf("1");
    else
        printf("0");

    n >>= 1;
}
printf("\n");

Easiest way to rotate by 90 degrees an image using OpenCV?

Here is my python cv2 implementation:

import cv2

img=cv2.imread("path_to_image.jpg")

# rotate ccw
out=cv2.transpose(img)
out=cv2.flip(out,flipCode=0)

# rotate cw
out=cv2.transpose(img)
out=cv2.flip(out,flipCode=1)

cv2.imwrite("rotated.jpg", out)

How to remove rows with any zero value

As dplyr 1.0.0 deprecated the scoped variants which @Feng Mai nicely showed, here is an update with the new syntax. This might be useful because in this case, across() doesn't work, and it took me some time to figure out the solution as follows.

The goal was to extract all rows that contain at least one 0 in a column.

df %>% 
  rowwise() %>% 
  filter(any(c_across(everything(.)) == 0))

with the data

df <- data.frame(a = 1:4, b= 1:0, c=0:3)
df <- rbind(df, c(0,0,0))
df <- rbind(df, c(9,9,9))

# A tibble: 4 x 3
# Rowwise: 
      a     b     c
  <dbl> <dbl> <dbl>
1     1     1     0
2     2     0     1
3     4     0     3
4     0     0     0

So it correctly doesn't return the last row containing all 9s.

TypeError: sequence item 0: expected string, int found

String interpolation is a nice way to pass in a formatted string.

values = ', '.join('$%s' % v for v in value_list)

How to index an element of a list object in R

Indexing a list is done using double bracket, i.e. hypo_list[[1]] (e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table does not return a table but a dataframe (see value section in ?read.table). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.

Note: In R, the index for the first entry is a 1 (not 0 like in some other languages).

Dataframes

l <- list(anscombe, iris)   # put dfs in list
l[[1]]             # returns anscombe dataframe

anscombe[1:2, 2]   # access first two rows and second column of dataset
[1] 10  8

l[[1]][1:2, 2]     # the same but selecting the dataframe from the list first
[1] 10  8

Table objects

tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2)  # put tables in a list

tbl1[1:2]              # access first two elements of table 1 

Now with the list

l[[1]]                 # access first table from the list

1  2  3  4  5 
9 11 12  9  9 

l[[1]][1:2]            # access first two elements in first table

1  2 
9 11 

[Ljava.lang.Object; cannot be cast to

Your query execution will return list of Object[].

List result_source = LoadSource.list();
for(Object[] objA : result_source) {
    // read it all
}

'0000-00-00 00:00:00' can not be represented as java.sql.Timestamp error

you can try like This

ArrayList<String> dtlst = new ArrayList<String>();
String qry1 = "select dt_tracker from gs";

Statement prepst = conn.createStatement();
ResultSet rst = prepst.executeQuery(qry1);
while(rst.next())
{
    String dt = "";
    try
    {
        dt = rst.getDate("dt_tracker")+" "+rst.getTime("dt_tracker");
    }
    catch(Exception e)
    {
        dt = "0000-00-00 00:00:00";
    }

    dtlst.add(dt);
}

In Python, how do I read the exif data for an image?

I usually use pyexiv2 to set exif information in JPG files, but when I import the library in a script QGIS script crash.

I found a solution using the library exif:

https://pypi.org/project/exif/

It's so easy to use, and with Qgis I don,'t have any problem.

In this code I insert GPS coordinates to a snapshot of screen:

from exif import Image
with open(file_name, 'rb') as image_file:
    my_image = Image(image_file)

my_image.make = "Python"
my_image.gps_latitude_ref=exif_lat_ref
my_image.gps_latitude=exif_lat
my_image.gps_longitude_ref= exif_lon_ref
my_image.gps_longitude= exif_lon

with open(file_name, 'wb') as new_image_file:
    new_image_file.write(my_image.get_file())

How to replace innerHTML of a div using jQuery?

jQuery's .html() can be used for setting and getting the contents of matched non empty elements (innerHTML).

var contents = $(element).html();
$(element).html("insert content into element");

jquery find closest previous sibling with class

Try

$('li.current_sub').prev('.par_cat').[do stuff];

Press any key to continue

I've created a little Powershell function to emulate MSDOS pause. This handles whether running Powershell ISE or non ISE. (ReadKey does not work in powershell ISE). When running Powershell ISE, this function opens a Windows MessageBox. This can sometimes be confusing, because the MessageBox does not always come to the forefront. Anyway, here it goes:

Usage: pause "Press any key to continue"

Function definition:

Function pause ($message)
{
    # Check if running Powershell ISE
    if ($psISE)
    {
        Add-Type -AssemblyName System.Windows.Forms
        [System.Windows.Forms.MessageBox]::Show("$message")
    }
    else
    {
        Write-Host "$message" -ForegroundColor Yellow
        $x = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    }
}

Does IE9 support console.log, and is it a real function?

console.log is only defined when the console is open. If you want to check for it in your code make sure you check for for it within the window property

if (window.console)
    console.log(msg)

this throws an exception in IE9 and will not work correctly. Do not do this

if (console) 
    console.log(msg)

Which is better: <script type="text/javascript">...</script> or <script>...</script>

Both will work but xhtml standard requires you to specify the type too:

<script type="text/javascript">..</script> 

<!ELEMENT SCRIPT - - %Script;          -- script statements -->
<!ATTLIST SCRIPT
  charset     %Charset;      #IMPLIED  -- char encoding of linked resource --
  type        %ContentType;  #REQUIRED -- content type of script language --
  src         %URI;          #IMPLIED  -- URI for an external script --
  defer       (defer)        #IMPLIED  -- UA may defer execution of script --
  >

type = content-type [CI] This attribute specifies the scripting language of the element's contents and overrides the default scripting language. The scripting language is specified as a content type (e.g., "text/javascript"). Authors must supply a value for this attribute. There is no default value for this attribute.

Notices the emphasis above.

http://www.w3.org/TR/html4/interact/scripts.html

Note: As of HTML5 (far away), the type attribute is not required and is default.

How do AX, AH, AL map onto EAX?

The below snippet examines EAX using GDB.

    (gdb) info register eax
    eax            0xaa55   43605
    (gdb) info register ax
    ax             0xaa55   -21931
    (gdb) info register ah
    ah             0xaa -86
    (gdb) info register al
    al             0x55 85
  1. EAX - Full 32 bit value
  2. AX - lower 16 bit value
  3. AH - Bits from 8 to 15
  4. AL - lower 8 bits of EAX/AX

What is git tag, How to create tags & How to checkout git remote tag(s)

Let's start by explaining what a tag in git is

enter image description here

A tag is used to label and mark a specific commit in the history.
It is usually used to mark release points (eg. v1.0, etc.).

Although a tag may appear similar to a branch, a tag, however, does not change. It points directly to a specific commit in the history and will not change unless explicitly updated.

enter image description here


You will not be able to checkout the tags if it's not locally in your repository so first, you have to fetch the tags to your local repository.

First, make sure that the tag exists locally by doing

# --all will fetch all the remotes.
# --tags will fetch all tags as well
$ git fetch --all --tags --prune

Then check out the tag by running

$ git checkout tags/<tag_name> -b <branch_name>

Instead of origin use the tags/ prefix.


In this sample you have 2 tags version 1.0 & version 1.1 you can check them out with any of the following:

$ git checkout A  ...
$ git checkout version 1.0  ...
$ git checkout tags/version 1.0  ...

All of the above will do the same since the tag is only a pointer to a given commit.

enter image description here
origin: https://backlog.com/git-tutorial/img/post/stepup/capture_stepup4_1_1.png


How to see the list of all tags?

# list all tags
$ git tag

# list all tags with given pattern ex: v-
$ git tag --list 'v-*'

How to create tags?

There are 2 ways to create a tag:

# lightweight tag 
$ git tag 

# annotated tag
$ git tag -a

The difference between the 2 is that when creating an annotated tag you can add metadata as you have in a git commit:
name, e-mail, date, comment & signature

enter image description here

How to delete tags?

Delete a local tag

$ git tag -d <tag_name>
Deleted tag <tag_name> (was 000000)

Note: If you try to delete a non existig Git tag, there will be see the following error:

$ git tag -d <tag_name>
error: tag '<tag_name>' not found.

Delete remote tags

# Delete a tag from the server with push tags
$ git push --delete origin <tag name>

How to clone a specific tag?

In order to grab the content of a given tag, you can use the checkout command. As explained above tags are like any other commits so we can use checkout and instead of using the SHA-1 simply replacing it with the tag_name

Option 1:

# Update the local git repo with the latest tags from all remotes
$ git fetch --all

# checkout the specific tag
$ git checkout tags/<tag> -b <branch>

Option 2:

Using the clone command

Since git supports shallow clone by adding the --branch to the clone command we can use the tag name instead of the branch name. Git knows how to "translate" the given SHA-1 to the relevant commit

# Clone a specific tag name using git clone 
$ git clone <url> --branch=<tag_name>

git clone --branch=

--branch can also take tags and detaches the HEAD at that commit in the resulting repository.


How to push tags?

git push --tags

To push all tags:

# Push all tags
$ git push --tags 

Using the refs/tags instead of just specifying the <tagname>.

Why?

  • It's recommended to use refs/tags since sometimes tags can have the same name as your branches and a simple git push will push the branch instead of the tag

To push annotated tags and current history chain tags use:

git push --follow-tags

This flag --follow-tags pushes both commits and only tags that are both:

  • Annotated tags (so you can skip local/temp build tags)
  • Reachable tags (an ancestor) from the current branch (located on the history)

enter image description here

From Git 2.4 you can set it using configuration

$ git config --global push.followTags true

Cheatsheet: enter image description here


C - Convert an uppercase letter to lowercase

#include <stdio.h>
#include <string.h>

int main()
{
    char string[] = "Strlwr in C";

    printf("%s\n",strlwr(string));

    return  0;
}

use strlwr for lowering the case

How to Calculate Execution Time of a Code Snippet in C++

boost::timer will probably give you as much accuracy as you'll need. It's nowhere near accurate enough to tell you how long a = a+1; will take, but I what reason would you have to time something that takes a couple nanoseconds?

Align inline-block DIVs to top of container element

You need to add a vertical-align property to your two child div's.

If .small is always shorter, you need only apply the property to .small. However, if either could be tallest then you should apply the property to both .small and .big.

.container{ 
    border: 1px black solid;
    width: 320px;
    height: 120px;    
}

.small{
    display: inline-block;
    width: 40%;
    height: 30%;
    border: 1px black solid;
    background: aliceblue; 
    vertical-align: top;   
}

.big {
    display: inline-block;
    border: 1px black solid;
    width: 40%;
    height: 50%;
    background: beige; 
    vertical-align: top;   
}

Vertical align affects inline or table-cell box's, and there are a large nubmer of different values for this property. Please see https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align for more details.

Replace String in all files in Eclipse

Strange but it is a two step task:

  1. Search what you want
  2. In the search tab right click and select replace , or replace all:

A demo at:

http://www.avajava.com/tutorials/lessons/how-do-i-do-a-find-and-replace-in-multiple-files-in-eclipse.html

How to make a DIV not wrap?

The min-width property does not work correctly in Internet Explorer, which is most likely the cause of your problems.

Read info and a brilliant script that fixes many IE CSS problems.

How create Date Object with values in java

import java.io.*;
import java.util.*;
import java.util.HashMap;

public class Solution 
{

    public static void main(String[] args)
    {
        HashMap<Integer,String> hm = new HashMap<Integer,String>();
        hm.put(1,"SUNDAY");
        hm.put(2,"MONDAY");
        hm.put(3,"TUESDAY");
        hm.put(4,"WEDNESDAY");
        hm.put(5,"THURSDAY");
        hm.put(6,"FRIDAY");
        hm.put(7,"SATURDAY");
        Scanner in = new Scanner(System.in);
        String month = in.next();
        String day = in.next();
        String year = in.next();

        String format = year + "/" + month + "/" + day;
        Date date = null;
        try
        {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
            date = formatter.parse(format);
        }
        catch(Exception e){
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
        System.out.println(hm.get(dayOfWeek));
    }
}

How to change FontSize By JavaScript?

try this:

var span = document.getElementById("span");
span.style.fontSize = "25px";
span.innerHTML = "String";

How do I hide a menu item in the actionbar?

You can use toolbar.getMenu().clear(); to hide all the menu items at once

Make Vim show ALL white spaces as a character

Keep those hacks in the .vimrc as comments, so in the shell, simply :

echo '
  " how-to see the non-visible while spaces
  " :set listchars=eol:¬,tab:>·,trail:~,extends:>,precedes:<,space:?
  " set listchars=eol:$,tab:>-,trail:~,extends:>,precedes:<
  " :set list
  " but hei how-to unset the visible tabs ?!
  " :set nolist
  ' >> ~/.vimrc

Regex not operator

No, there's no direct not operator. At least not the way you hope for.

You can use a zero-width negative lookahead, however:

\((?!2001)[0-9a-zA-z _\.\-:]*\)

The (?!...) part means "only match if the text following (hence: lookahead) this doesn't (hence: negative) match this. But it doesn't actually consume the characters it matches (hence: zero-width).

There are actually 4 combinations of lookarounds with 2 axes:

  • lookbehind / lookahead : specifies if the characters before or after the point are considered
  • positive / negative : specifies if the characters must match or must not match.

Android Studio Gradle Already disposed Module

Sometimes gradlew clean or Invalidate Cache and Restart does not help, because these methods do not clean Android Studio specific files by themselves.

In this case, close AS and remove .idea directory and .iml file in a root project where settings.gradle file exists. This will make AS rebuild from the fresh ground.

Android: how to get the current day of the week (Monday, etc...) in the user's language?

I just use this solution in Kotlin:

 var date : String = DateFormat.format("EEEE dd-MMM-yyyy HH:mm a" , Date()) as String

git ahead/behind info between master and branch?

You can also use awk to make it a little bit prettier:

git rev-list --left-right --count  origin/develop...feature-branch | awk '{print "Behind "$1" - Ahead "$2""}'

You can even make an alias that always fetches origin first and then compares the branches

commit-diff = !"git fetch &> /dev/null && git rev-list --left-right --count"

How to run python script on terminal (ubuntu)?

This error:

python: can't open file 'test.py': [Errno 2] No such file or directory

Means that the file "test.py" doesn't exist. (Or, it does, but it isn't in the current working directory.)

I must save the file in any specific folder to make it run on terminal?

No, it can be where ever you want. However, if you just say, "test.py", you'll need to be in the directory containing test.py.

Your terminal (actually, the shell in the terminal) has a concept of "Current working directory", which is what directory (folder) it is currently "in".

Thus, if you type something like:

python test.py

test.py needs to be in the current working directory. In Linux, you can change the current working directory with cd. You might want a tutorial if you're new. (Note that the first hit on that search for me is this YouTube video. The author in the video is using a Mac, but both Mac and Linux use bash for a shell, so it should apply to you.)

Use of var keyword in C#

From the discussion on this topic, the outcome appears to be:

Good: var customers = new List<Customer>();

Controversial: var customers = dataAccess.GetCustomers();

Ignoring the misguided opinion that "var" magically helps with refactoring, the biggest issue for me is people's insistence that they don't care what the return type is, "so long as they can enumerate the collection".

Consider:

IList<Customer> customers = dataAccess.GetCustomers();

var dummyCustomer = new Customer();
customers.Add(dummyCustomer);

Now consider:

var customers = dataAccess.GetCustomers();

var dummyCustomer = new Customer();
customers.Add(dummyCustomer);

Now, go and refactor the data access class, so that GetCustomers returns IEnumerable<Customer>, and see what happens...

The problem here is that in the first example you're making your expectations of the GetCustomers method explicit - you're saying that you expect it to return something that behaves like a list. In the second example, this expectation is implicit, and not immediately obvious from the code.

It's interesting (to me) that a lot of pro-var arguments say "i don't care what type it returns", but go on to say "i just need to iterate over it...". (so it needs to implement the IEnumerable interface, implying the type does matter).

How to start MySQL with --skip-grant-tables?

If you use mysql 5.6 server and have problems with C:\Program Files\MySQL\MySQL Server 5.6\my.ini:

You should go to C:\ProgramData\MySQL\MySQL Server 5.6\my.ini.

You should add skip-grant-tables and then you do not need a password.

# SERVER SECTION
# ----------------------------------------------------------------------
#
# The following options will be read by the MySQL Server. Make sure that
# you have installed the server correctly (see above) so it reads this 
# file.
#
# server_type=3
[mysqld]
skip-grant-tables

Note: after you are done with your work on skip-grant-tables, you should restore your file of C:\ProgramData\MySQL\MySQL Server 5.6\my.ini.

How to detect chrome and safari browser (webkit)

you can use this minified jQuery snippet to detect if your user is viewing using a mobile device. If you need to test for a specific device I’ve included a collection of JavaScript snippets below which can be used to detect various mobile handheld devices such as iPad, iPhone, iPod, iDevice, Andriod, Blackberry, WebOs and Windows Phone.

/**
 * jQuery.browser.mobile (http://detectmobilebrowser.com/)
 * jQuery.browser.mobile will be true if the browser is a mobile device
 **/

    (function(a){jQuery.browser.mobile=/android.+mobile|avantgo|bada/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)/|plucker|pocket|psp|symbian|treo|up.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|/(k|l|u)|50|54|e-|e/|-[a-w])|libw|lynx|m1-w|m3ga|m50/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(-|2|g)|yas-|your|zeto|zte-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera);

Example Usage:

if(jQuery.browser.mobile)
{
console.log(‘You are using a mobile device!’);
}
else
{
console.log(‘You are not using a mobile device!’);
}

Detect iPad

var isiPad = /ipad/i.test(navigator.userAgent.toLowerCase());
if (isiPad)
{
…
}

Detect iPhone

var isiPhone = /iphone/i.test(navigator.userAgent.toLowerCase());
if (isiPhone)
{
…
}

Detect iPod

var isiPod = /ipod/i.test(navigator.userAgent.toLowerCase());
if (isiPod)
{
…
}

Detect iDevice

var isiDevice = /ipad|iphone|ipod/i.test(navigator.userAgent.toLowerCase());

if (isiDevice)
{
…
}

Detect Andriod

var isAndroid = /android/i.test(navigator.userAgent.toLowerCase());

if (isAndroid)
{
…
}

Detect Blackberry

var isBlackBerry = /blackberry/i.test(navigator.userAgent.toLowerCase());

if (isBlackBerry)
{
…
}

Detect WebOs

var isWebOS = /webos/i.test(navigator.userAgent.toLowerCase());

if (isWebOS)
{
…
}

Detect Windows Phone

var isWindowsPhone = /windows phone/i.test(navigator.userAgent.toLowerCase());

if (isWindowsPhone)
{
…
}

Find difference between timestamps in seconds in PostgreSQL

SELECT (cast(timestamp_1 as bigint) - cast(timestamp_2 as bigint)) FROM table;

In case if someone is having an issue using extract.

Why shouldn't I use "Hungarian Notation"?

Joel is wrong, and here is why.

That "application" information he's talking about should be encoded in the type system. You should not depend on flipping variable names to make sure you don't pass unsafe data to functions requiring safe data. You should make it a type error, so that it is impossible to do so. Any unsafe data should have a type that is marked unsafe, so that it simply cannot be passed to a safe function. To convert from unsafe to safe should require processing with some kind of a sanitize function.

A lot of the things that Joel talks of as "kinds" are not kinds; they are, in fact, types.

What most languages lack, however, is a type system that's expressive enough to enforce these kind of distinctions. For example, if C had a kind of "strong typedef" (where the typedef name had all the operations of the base type, but was not convertible to it) then a lot of these problems would go away. For example, if you could say, strong typedef std::string unsafe_string; to introduce a new type unsafe_string that could not be converted to a std::string (and so could participate in overload resolution etc. etc.) then we would not need silly prefixes.

So, the central claim that Hungarian is for things that are not types is wrong. It's being used for type information. Richer type information than the traditional C type information, certainly; it's type information that encodes some kind of semantic detail to indicate the purpose of the objects. But it's still type information, and the proper solution has always been to encode it into the type system. Encoding it into the type system is far and away the best way to obtain proper validation and enforcement of the rules. Variables names simply do not cut the mustard.

In other words, the aim should not be "make wrong code look wrong to the developer". It should be "make wrong code look wrong to the compiler".

Kendo grid date column not formatting

I found this piece of information and got it to work correctly. The data given to me was in string format so I needed to parse the string using kendo.parseDate before formatting it with kendo.toString.

columns: [
    {
        field: "FirstName",
        title: "FIRST NAME"
    },
    {
        field: "LastName",
        title: "LAST NAME"
    },
    {
        field: "DateOfBirth",
        title: "DATE OF BIRTH",
        template: "#= kendo.toString(kendo.parseDate(DateOfBirth, 'yyyy-MM-dd'), 'MM/dd/yyyy') #"
    },
...


References:

  1. format-date-in-grid
  2. jsfiddle
  3. kendo ui date formatting

Android: Color To Int conversion

Any color parse into int simplest two way here:

1) Get System Color

int redColorValue = Color.RED;

2) Any Color Hex Code as a String Argument

int greenColorValue = Color.parseColor("#00ff00")

MUST REMEMBER in above code Color class must be android.graphics...!

Want to upgrade project from Angular v5 to Angular v6

Just use the official upgrade guide which will tell you what you need to do for your own particular needs:

Upgrade angular

https://update.angular.io/

How to calculate age (in years) based on Date of Birth and getDate()

How about this:

SET @Age = CAST(DATEDIFF(Year, @DOB, @Stamp) as int)
IF (CAST(DATEDIFF(DAY, DATEADD(Year, @Age, @DOB), @Stamp) as int) < 0) 
    SET @Age = @Age - 1

What is difference between functional and imperative programming languages?

There seem to be many opinions about what functional programs and what imperative programs are.

I think functional programs can most easily be described as "lazy evaluation" oriented. Instead of having a program counter iterate through instructions, the language by design takes a recursive approach.

In a functional language, the evaluation of a function would start at the return statement and backtrack, until it eventually reaches a value. This has far reaching consequences with regards to the language syntax.

Imperative: Shipping the computer around

Below, I've tried to illustrate it by using a post office analogy. The imperative language would be mailing the computer around to different algorithms, and then have the computer returned with a result.

Functional: Shipping recipes around

The functional language would be sending recipes around, and when you need a result - the computer would start processing the recipes.

This way, you ensure that you don't waste too many CPU cycles doing work that is never used to calculate the result.

When you call a function in a functional language, the return value is a recipe that is built up of recipes which in turn is built of recipes. These recipes are actually what's known as closures.

// helper function, to illustrate the point
function unwrap(val) {
  while (typeof val === "function") val = val();
  return val;
}

function inc(val) {
  return function() { unwrap(val) + 1 };
}

function dec(val) {
  return function() { unwrap(val) - 1 };
}

function add(val1, val2) {
  return function() { unwrap(val1) + unwrap(val2) }
}

// lets "calculate" something

let thirteen = inc(inc(inc(10)))
let twentyFive = dec(add(thirteen, thirteen))

// MAGIC! The computer still has not calculated anything.
// 'thirteen' is simply a recipe that will provide us with the value 13

// lets compose a new function

let doubler = function(val) {
  return add(val, val);
}

// more modern syntax, but it's the same:
let alternativeDoubler = (val) => add(val, val)

// another function
let doublerMinusOne = (val) => dec(add(val, val));

// Will this be calculating anything?

let twentyFive = doubler(thirteen)

// no, nothing has been calculated. If we need the value, we have to unwrap it:
console.log(unwrap(thirteen)); // 26

The unwrap function will evaluate all the functions to the point of having a scalar value.

Language Design Consequences

Some nice features in imperative languages, are impossible in functional languages. For example the value++ expression, which in functional languages would be difficult to evaluate. Functional languages make constraints on how the syntax must be, because of the way they are evaluated.

On the other hand, with imperative languages can borrow great ideas from functional languages and become hybrids.

Functional languages have great difficulty with unary operators like for example ++ to increment a value. The reason for this difficulty is not obvious, unless you understand that functional languages are evaluated "in reverse".

Implementing a unary operator would have to be implemented something like this:

let value = 10;

function increment_operator(value) {
  return function() {
    unwrap(value) + 1;
  }
}

value++ // would "under the hood" become value = increment_operator(value)

Note that the unwrap function I used above, is because javascript is not a functional language, so when needed we have to manually unwrap the value.

It is now apparent that applying increment a thousand times would cause us to wrap the value with 10000 closures, which is worthless.

The more obvious approach, is to actually directly change the value in place - but voila: you have introduced modifiable values a.k.a mutable values which makes the language imperative - or actually a hybrid.

Under the hood, it boils down to two different approaches to come up with an output when provided with an input.

Below, I'll try to make an illustration of a city with the following items:

  1. The Computer
  2. Your Home
  3. The Fibonaccis

Imperative Languages

Task: Calculate the 3rd fibonacci number. Steps:

  1. Put The Computer into a box and mark it with a sticky note:

    Field Value
    Mail Address The Fibonaccis
    Return Address Your Home
    Parameters 3
    Return Value undefined

    and send off the computer.

  2. The Fibonaccis will upon receiving the box do as they always do:

    • Is the parameter < 2?

      • Yes: Change the sticky note, and return the computer to the post office:

        Field Value
        Mail Address The Fibonaccis
        Return Address Your Home
        Parameters 3
        Return Value 0 or 1 (returning the parameter)

        and return to sender.

      • Otherwise:

        1. Put a new sticky note on top of the old one:

          Field Value
          Mail Address The Fibonaccis
          Return Address Otherwise, step 2, c/oThe Fibonaccis
          Parameters 2 (passing parameter-1)
          Return Value undefined

          and send it.

        2. Take off the returned sticky note. Put a new sticky note on top of the initial one and send The Computer again:

          Field Value
          Mail Address The Fibonaccis
          Return Address Otherwise, done, c/o The Fibonaccis
          Parameters 2 (passing parameter-2)
          Return Value undefined
        3. By now, we should have the initial sticky note from the requester, and two used sticky notes, each having their Return Value field filled. We summarize the return values and put it in the Return Value field of the final sticky note.

          Field Value
          Mail Address The Fibonaccis
          Return Address Your Home
          Parameters 3
          Return Value 2 (returnValue1 + returnValue2)

          and return to sender.

As you can imagine, quite a lot of work starts immediately after you send your computer off to the functions you call.

The entire programming logic is recursive, but in truth the algorithm happens sequentially as the computer moves from algorithm to algorithm with the help of a stack of sticky notes.

Functional Languages

Task: Calculate the 3rd fibonacci number. Steps:

  1. Write the following down on a sticky note:

    Field Value
    Instructions The Fibonaccis
    Parameters 3

That's essentially it. That sticky note now represents the computation result of fib(3).

We have attached the parameter 3 to the recipe named The Fibonaccis. The computer does not have to perform any calculations, unless somebody needs the scalar value.

Functional Javascript Example

I've been working on designing a programming language named Charm, and this is how fibonacci would look in that language.

fib: (n) => if (                         
  n < 2               // test
  n                   // when true
  fib(n-1) + fib(n-2) // when false
)
print(fib(4));

This code can be compiled both into imperative and functional "bytecode".

The imperative javascript version would be:

let fib = (n) => 
  n < 2 ?
  n : 
  fib(n-1) + fib(n-2);

The HALF functional javascript version would be:

let fib = (n) => () =>
  n < 2 ?
  n :
  fib(n-1) + fib(n-2);

The PURE functional javascript version would be much more involved, because javascript doesn't have functional equivalents.

let unwrap = ($) =>
  typeof $ !== "function" ? $ : unwrap($());

let $if = ($test, $whenTrue, $whenFalse) => () =>
  unwrap($test) ? $whenTrue : $whenFalse;

let $lessThen = (a, b) => () =>
  unwrap(a) < unwrap(b);

let $add = ($value, $amount) => () =>
  unwrap($value) + unwrap($amount);

let $sub = ($value, $amount) => () =>
  unwrap($value) - unwrap($amount);

let $fib = ($n) => () =>
  $if(
    $lessThen($n, 2),
    $n,
    $add( $fib( $sub($n, 1) ), $fib( $sub($n, 2) ) )
  );

I'll manually "compile" it into javascript code:

"use strict";

// Library of functions:
  /**
   * Function that resolves the output of a function.
   */
  let $$ = (val) => {
    while (typeof val === "function") {
      val = val();
    }
    return val;
  }

  /**
   * Functional if
   *
   * The $ suffix is a convention I use to show that it is "functional"
   * style, and I need to use $$() to "unwrap" the value when I need it.
   */
  let if$ = (test, whenTrue, otherwise) => () =>
    $$(test) ? whenTrue : otherwise;

  /**
   * Functional lt (less then)
   */
  let lt$ = (leftSide, rightSide)   => () => 
    $$(leftSide) < $$(rightSide)


  /**
   * Functional add (+)
   */
  let add$ = (leftSide, rightSide) => () => 
    $$(leftSide) + $$(rightSide)

// My hand compiled Charm script:

  /**
   * Functional fib compiled
   */
  let fib$ = (n) => if$(                 // fib: (n) => if(
    lt$(n, 2),                           //   n < 2
    () => n,                             //   n
    () => add$(fib$(n-2), fib$(n-1))     //   fib(n-1) + fib(n-2)
  )                                      // )

// This takes a microsecond or so, because nothing is calculated
console.log(fib$(30));

// When you need the value, just unwrap it with $$( fib$(30) )
console.log( $$( fib$(5) ))

// The only problem that makes this not truly functional, is that
console.log(fib$(5) === fib$(5)) // is false, while it should be true
// but that should be solveable

https://jsfiddle.net/819Lgwtz/42/

The entity type <type> is not part of the model for the current context

Put this in your custom DbContext class:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Estate>().ToTable("Estate");
}

If your tables are not created on startup, this is why. You need to tell the DbContext about them in the OnModelCreating method override.

You can either do custom per-entity mappings here, or separate them out into separate EntityTypeConfiguration<T> classes.

Append an object to a list in R in amortized constant time, O(1)?

There is also list.append from the rlist (link to the documentation)

require(rlist)
LL <- list(a="Tom", b="Dick")
list.append(LL,d="Pam",f=c("Joe","Ann"))

It's very simple and efficient.