Programs & Examples On #Drupal templates

Theme templates are part of Drupal's theming system and allow for the customization of Drupal sites.

How to output to the console and file?

Use logging module (http://docs.python.org/library/logging.html):

import logging

logger = logging.getLogger('scope.name')

file_log_handler = logging.FileHandler('logfile.log')
logger.addHandler(file_log_handler)

stderr_log_handler = logging.StreamHandler()
logger.addHandler(stderr_log_handler)

# nice output format
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_log_handler.setFormatter(formatter)
stderr_log_handler.setFormatter(formatter)

logger.info('Info message')
logger.error('Error message')

Is there shorthand for returning a default value if None in Python?

return "default" if x is None else x

try the above.

linking jquery in html

<script
 src="CDN">
</script>

for change the CDN check this website.

the first one is JQuery

Are iframes considered 'bad practice'?

It's worth noting that iframes will, regardless of the speed of your users' internet connection or the contents of the iframe, cause a small (0.3s or so) but noticeable slowdown in the speed your page downloads. This is not something you'll see when testing it locally. Actually, this is true for any element added to a page, but iframes seem to be worse.

How to access to the parent object in c#

I would give the parent an ID, and store the parentID in the child object, so that you can pull information about the parent as needed without creating a parent-owns-child/child-owns-parent loop.

How do I solve the "server DNS address could not be found" error on Windows 10?

There might be a problem with your DNS servers of the ISP. A computer by default uses the ISP's DNS servers. You can manually configure your DNS servers. It is free and usually better than your ISP.

  1. Go to Control Panel ? Network and Internet ? Network and Sharing Centre
  2. Click on Change Adapter settings.
  3. Right click on your connection icon (Wireless Network Connection or Local Area Connection) and select properties.
  4. Select Internet protocol version 4.
  5. Click on "Use the following DNS server address" and type either of the two DNS given below.

Google Public DNS

Preferred DNS server : 8.8.8.8
Alternate DNS server : 8.8.4.4

OpenDNS

Preferred DNS server : 208.67.222.222
Alternate DNS server : 208.67.220.220

How do I convert an existing callback API to promises?

Below is the implementation of how a function (callback API) can be converted to a promise.

function promisify(functionToExec) {
  return function() {
    var array = Object.values(arguments);
    return new Promise((resolve, reject) => {
      array.push(resolve)
      try {
         functionToExec.apply(null, array);
      } catch (error) {
         reject(error)
      }
    })
  }
}

// USE SCENARIO

function apiFunction (path, callback) { // Not a promise
  // Logic
}

var promisedFunction = promisify(apiFunction);

promisedFunction('path').then(()=>{
  // Receive the result here (callback)
})

// Or use it with await like this
let result = await promisedFunction('path');

Best way to do Version Control for MS Excel

It depends whether you are talking about data, or the code contained within a spreadsheet. While I have a strong dislike of Microsoft's Visual Sourcesafe and normally would not recommended it, it does integrate easily with both Access and Excel, and provides source control of modules.

[In fact the integration with Access, includes queries, reports and modules as individual objects that can be versioned]

The MSDN link is here.

write multiple lines in a file in python

It can be done like this as well:

target.write(line1 + "\n" + line2 + "\n" + line3 + "\n")

Double array initialization in Java

This is array initializer syntax, and it can only be used on the right-hand-side when declaring a variable of array type. Example:

int[] x = {1,2,3,4};
String y = {"a","b","c"};

If you're not on the RHS of a variable declaration, use an array constructor instead:

int[] x;
x = new int[]{1,2,3,4};
String y;
y = new String[]{"a","b","c"};

These declarations have the exact same effect: a new array is allocated and constructed with the specified contents.

In your case, it might actually be clearer (less repetitive, but a bit less concise) to specify the table programmatically:

double[][] m = new double[4][4];

for(int i=0; i<4; i++) {
    for(int j=0; j<4; j++) {
        m[i][j] = i*j;
    }
}

What does status=canceled for a resource mean in Chrome Developer Tools?

For anyone coming from LoopbackJS and attempting to use the custom stream method like provided in their chart example. I was getting this error using a PersistedModel, switching to a basic Model fixed my issue of the eventsource status cancelling out.

Again, this is specifically for the loopback api. And since this is a top answer and top on google i figured i'de throw this in the mix of answers.

Split files using tar, gz, zip, or bzip2

If you are splitting from Linux, you can still reassemble in Windows.

copy /b file1 + file2 + file3 + file4 filetogether

How to locate the Path of the current project directory in Java (IDE)?

What about System.getProperty("user.dir")? It'll give you the working directory from where your program was launched.

See System Properties from the Java Tutorial for an overview of Java's System Properties.

What does the M stand for in C# Decimal literal notation?

From C# specifications:

var f = 0f; // float
var d = 0d; // double
var m = 0m; // decimal (money)
var u = 0u; // unsigned int
var l = 0l; // long
var ul = 0ul; // unsigned long

Note that you can use an uppercase or lowercase notation.

Evenly distributing n points on a sphere

Healpix solves a closely related problem (pixelating the sphere with equal area pixels):

http://healpix.sourceforge.net/

It's probably overkill, but maybe after looking at it you'll realize some of it's other nice properties are interesting to you. It's way more than just a function that outputs a point cloud.

I landed here trying to find it again; the name "healpix" doesn't exactly evoke spheres...

Clearing localStorage in javascript?

This code here you give a list of strings of keys that you don't want to delete, then it filters those from all the keys in local storage then deletes the others.

const allKeys = Object.keys(localStorage);

const toBeDeleted = allKeys.filter(value => {
  return !this.doNotDeleteList.includes(value);
});

toBeDeleted.forEach(value => {
  localStorage.removeItem(value);
});

Disable form auto submit on button click

You could just try using return false (return false overrides default behaviour on every DOM element) like that :

myform.onsubmit = function ()
{ 
  // do what you want
  return false
}

and then submit your form using myform.submit()

or alternatively :

mybutton.onclick = function () 
{
   // do what you want
   return false
}

Also, if you use type="button" your form will not be submitted.

int value under 10 convert to string two digit number

The accepted answer is good and fast:

i.ToString("00")

or

i.ToString("000")

If you need more complexity, String.Format is worth a try:

var str1 = "";
var str2 = "";
for (int i = 1; i < 100; i++)
{
    str1 = String.Format("{0:00}", i);
    str2 = String.Format("{0:000}", i);
}

For the i = 10 case:

str1: "10"
str2: "010"

I use this, for example, to clear the text on particular Label Controls on my form by name:

private void EmptyLabelArray()
{
    var fmt = "Label_Row{0:00}_Col{0:00}";
    for (var rowIndex = 0; rowIndex < 100; rowIndex++)
    {
        for (var colIndex = 0; colIndex < 100; colIndex++)
        {
            var lblName = String.Format(fmt, rowIndex, colIndex);
            foreach (var ctrl in this.Controls)
            {
                var lbl = ctrl as Label;
                if ((lbl != null) && (lbl.Name == lblName))
                {
                    lbl.Text = null;
                }
            }
        }
    }
}

Execution failed for task ':app:compileDebugAidl': aidl is missing

I am working with sdk 23.1.0 and gradle 1.3.1. I created a new project edited nothing and got the aidl error. I went into my project gradle file and changed tool to 22.0.1 instead of 23.1.0 and it worked:

   compileSdkVersion 23
   buildToolsVersion "22.0.1" //"23.1.0"

Should I test private methods or only public ones?

You should not. If your private methods have enough complexity that must be tested, you should put them on another class. Keep high cohesion, a class should have only one purpose. The class public interface should be enough.

Can I specify multiple users for myself in .gitconfig?

There is a simple solution that seems to work well for avoiding mistakes.

Simply remove the [user] section from your ~/.gitconfig, which will prevent you from making any commits without setting user.name for each repository.

In your ~/.bashrc, add some simple aliases for the user and email:

alias ggmail='git config user.name "My Name";git config user.email [email protected]'
alias gwork='git config user.name "My Name";git config user.email [email protected]'

How to replace spaces in file names using a bash script

A find/rename solution. rename is part of util-linux.

You need to descend depth first, because a whitespace filename can be part of a whitespace directory:

find /tmp/ -depth -name "* *" -execdir rename " " "_" "{}" ";"

How to make a phone call programmatically?

Tried this on my phone and it works perfectly.

Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:900..." ));
startActivity(intent);

Add this permission in manifest file.

<uses-permission android:name="android.permission.CALL_PHONE" />

Remove Top Line of Text File with PowerShell

skip` didn't work, so my workaround is

$LinesCount = $(get-content $file).Count
get-content $file |
    select -Last $($LinesCount-1) | 
    set-content "$file-temp"
move "$file-temp" $file -Force

How to display my application's errors in JSF?

Found this while Googling. The second post makes a point about the different phases of JSF, which might be causing your error message to become lost. Also, try null in place of "newPassword" because you do not have any object with the id newPassword.

Rounded table corners CSS only

The selected answer is terrible. I would implement this by targeting the corner table cells and applying the corresponding border radius.

To get the top corners, set the border radius on the first and last of type of the th elements, then finish by setting the border radius on the last and first of td type on the last of type tr to get the bottom corners.

th:first-of-type {
  border-top-left-radius: 10px;
}
th:last-of-type {
  border-top-right-radius: 10px;
}
tr:last-of-type td:first-of-type {
  border-bottom-left-radius: 10px;
}
tr:last-of-type td:last-of-type {
  border-bottom-right-radius: 10px;
}

Expand a random range from 1–5 to 1–7

int ans = 0;
while (ans == 0) 
{
     for (int i=0; i<3; i++) 
     {
          while ((r = rand5()) == 3){};
          ans += (r < 3) >> i
     }
}

keyCode values for numeric keypad?

******************* Don't use KEYCODE !!!! ******************

The problem with keyCode is to avoid the combined keys with the numbers on top of keyboard, we must add a check on the key "Shift" and "Alt" to avoid special characters such as e @ & " { } ...

A simplest solution is to convert e.key to a number and check if the conversion gives NaN!

let key = Number(e.key)
if (isNaN(key) || e.key === null || e.key === ' ') {
  console.log("is not numeric")
}
else {
  console.log("is numeric")
}

Be careful if e.key is null or a space, it gives 0 !

Number(5)         // => 5
Number('5')       // => 5
Number(null)      // => 0 
Number(' ')       // => 0
Number('chars')   // => NaN
Number(undefined) // => NaN

Uploading files to file server using webclient class

namespace FileUpload
{
public partial class Form1 : Form
{
    string fileName = "";
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

        string path = "";
        OpenFileDialog fDialog = new OpenFileDialog();
        fDialog.Title = "Attach customer proposal document";
        fDialog.Filter = "Doc Files|*.doc|Docx File|*.docx|PDF doc|*.pdf";
        fDialog.InitialDirectory = @"C:\";
        if (fDialog.ShowDialog() == DialogResult.OK)
        {
            fileName = System.IO.Path.GetFileName(fDialog.FileName);
            path = Path.GetDirectoryName(fDialog.FileName);
            textBox1.Text = path + "\\" + fileName;

        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        try
        {
            WebClient client = new WebClient();

            NetworkCredential nc = new NetworkCredential("erandika1986", "123");

            Uri addy = new Uri(@"\\192.168.2.4\UploadDocs\"+fileName);

            client.Credentials = nc;
            byte[] arrReturn = client.UploadFile(addy, textBox1.Text);
            MessageBox.Show(arrReturn.ToString());

        }
        catch (Exception ex1)
        {
            MessageBox.Show(ex1.Message);
        }
    }
}
}

how to extract only the year from the date in sql server 2008?

year(@date)
year(getdate())
year('20120101')

update table
set column = year(date_column)
whre ....

or if you need it in another table

 update t
   set column = year(t1.date_column)
     from table_source t1
     join table_target t on (join condition)
    where ....

Is there a way to view past mysql queries with phpmyadmin?

you can run your past mysql with run /PATH_PAST_MYSQL/bin/mysqld.exe

it run your last mysql and you can see it in phpmyadmin and other section of your system.

notice: stop your current mysql version.

S F My English.

How to remove unwanted space between rows and columns in table?

For standards compliant HTML5 add all this css to remove all space between images in tables:

table { 
    border-spacing: 0;
    border-collapse: collapse;
}
td {
    padding:0px;
}
td img {
    display:block;
}

git add, commit and push commands in one?

Set as an alias in bash:

$ alias lazygit="git add .; git commit -a -m '...'; git push;";

Call it:

$ lazygit

(To make this alias permanent, you'd have to include it in your .bashrc or .bash_profile)

How do I set the value property in AngularJS' ng-options?

The ng-options directive does not set the value attribute on the <options> elements for arrays:

Using limit.value as limit.text for limit in limits means:

set the <option>'s label as limit.text
save the limit.value value into the select's ng-model

See Stack Overflow question AngularJS ng-options not rendering values.

Android: Access child views from a ListView

listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
        View v;
        int count = parent.getChildCount();
        v = parent.getChildAt(position);
        parent.requestChildFocus(v, view);
        v.setBackground(res.getDrawable(R.drawable.transparent_button));
        for (int i = 0; i < count; i++) {
            if (i != position) {
                v = parent.getChildAt(i);
                v.setBackground(res.getDrawable(R.drawable.not_clicked));
            }
        }
    }
});

Basically, create two Drawables - one that is transparent, and another that is the desired color. Request focus at the clicked position (int position as defined) and change the color of the said row. Then walk through the parent ListView, and change all other rows accordingly. This accounts for when a user clicks on the listview multiple times. This is done with a custom layout for each row in the ListView. (Very simple, just create a new layout file with a TextView - do not set focusable or clickable!).

No custom adapter required - use ArrayAdapter

What is the best way to return different types of ResponseEntity in Spring MVC or Spring-Boot

Its possible to return ResponseEntity without using generics, such as follows,

public ResponseEntity method() {
    boolean isValid = // some logic
    if (isValid){
        return new ResponseEntity(new Success(), HttpStatus.OK);
    }
    else{
        return new ResponseEntity(new Error(), HttpStatus.BAD_REQUEST);
    }
}

Plotting in a non-blocking way with Matplotlib

Iggy's answer was the easiest for me to follow, but I got the following error when doing a subsequent subplot command that was not there when I was just doing show:

MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.

In order to avoid this error, it helps to close (or clear) the plot after the user hits enter.

Here's the code that worked for me:

def plt_show():
    '''Text-blocking version of plt.show()
    Use this instead of plt.show()'''
    plt.draw()
    plt.pause(0.001)
    input("Press enter to continue...")
    plt.close()

How to Call a JS function using OnClick event

Using the onclick attribute or applying a function to your JS onclick properties will erase your onclick initialization in <head>.

What you need to do is add click events on your button. To do that you’ll need the addEventListener or attachEvent (IE) method.

<!DOCTYPE html>
<html>
<head>
    <script>
        function addEvent(obj, event, func) {
            if (obj.addEventListener) {
                obj.addEventListener(event, func, false);
                return true;
            } else if (obj.attachEvent) {
                obj.attachEvent('on' + event, func);
            } else {
                var f = obj['on' + event];
                obj['on' + event] = typeof f === 'function' ? function() {
                    f();
                    func();
                } : func
            }
        }

        function f1()
        {
            alert("f1 called");
            //form validation that recalls the page showing with supplied inputs.    
        }
    </script>
</head>
<body>
    <form name="form1" id="form1" method="post">
        State: <select id="state ID">
        <option></option>
        <option value="ap">ap</option>
        <option value="bp">bp</option>
        </select>
    </form>

    <table><tr><td id="Save" onclick="f1()">click</td></tr></table>

    <script>
        addEvent(document.getElementById('Save'), 'click', function() {
            alert('hello');
        });
    </script>
</body>
</html>

Populate unique values into a VBA array from Excel

one more way ...

Sub get_unique()
Dim unique_string As String
    lr = Sheets("data").Cells(Sheets("data").Rows.Count, 1).End(xlUp).Row
    Set range1 = Sheets("data").Range("A2:A" & lr)
    For Each cel In range1
       If Not InStr(output, cel.Value) > 0 Then
           unique_string = unique_string & cel.Value & ","
       End If
    Next
End Sub

Controlling fps with requestAnimationFrame?

How to easily throttle to a specific FPS:

// timestamps are ms passed since document creation.
// lastTimestamp can be initialized to 0, if main loop is executed immediately
var lastTimestamp = 0,
    maxFPS = 30,
    timestep = 1000 / maxFPS; // ms for each frame

function main(timestamp) {
    window.requestAnimationFrame(main);

    // skip if timestep ms hasn't passed since last frame
    if (timestamp - lastTimestamp < timestep) return;

    lastTimestamp = timestamp;

    // draw frame here
}

window.requestAnimationFrame(main);

Source: A Detailed Explanation of JavaScript Game Loops and Timing by Isaac Sukin

how to use a like with a join in sql?

When writing queries with our server LIKE or INSTR (or CHARINDEX in T-SQL) takes too long, so we use LEFT like in the following structure:

select *
from little
left join big
on left( big.key, len(little.key) ) = little.key

I understand that might only work with varying endings to the query, unlike other suggestions with '%' + b + '%', but is enough and much faster if you only need b+'%'.

Another way to optimize it for speed (but not memory) is to create a column in "little" that is "len(little.key)" as "lenkey" and user that instead in the query above.

Import JSON file in React

With json-loader installed, you can use

import customData from '../customData.json';

or also, even more simply

import customData from '../customData';

To install json-loader

npm install --save-dev json-loader

How to validate a url in Python? (Malformed or not)

All of the above solutions recognize a string like "http://www.google.com/path,www.yahoo.com/path" as valid. This solution always works as it should

import re

# URL-link validation
ip_middle_octet = u"(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5]))"
ip_last_octet = u"(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))"

URL_PATTERN = re.compile(
                        u"^"
                        # protocol identifier
                        u"(?:(?:https?|ftp|rtsp|rtp|mmp)://)"
                        # user:pass authentication
                        u"(?:\S+(?::\S*)?@)?"
                        u"(?:"
                        u"(?P<private_ip>"
                        # IP address exclusion
                        # private & local networks
                        u"(?:localhost)|"
                        u"(?:(?:10|127)" + ip_middle_octet + u"{2}" + ip_last_octet + u")|"
                        u"(?:(?:169\.254|192\.168)" + ip_middle_octet + ip_last_octet + u")|"
                        u"(?:172\.(?:1[6-9]|2\d|3[0-1])" + ip_middle_octet + ip_last_octet + u"))"
                        u"|"
                        # IP address dotted notation octets
                        # excludes loopback network 0.0.0.0
                        # excludes reserved space >= 224.0.0.0
                        # excludes network & broadcast addresses
                        # (first & last IP address of each class)
                        u"(?P<public_ip>"
                        u"(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])"
                        u"" + ip_middle_octet + u"{2}"
                        u"" + ip_last_octet + u")"
                        u"|"
                        # host name
                        u"(?:(?:[a-z\u00a1-\uffff0-9_-]-?)*[a-z\u00a1-\uffff0-9_-]+)"
                        # domain name
                        u"(?:\.(?:[a-z\u00a1-\uffff0-9_-]-?)*[a-z\u00a1-\uffff0-9_-]+)*"
                        # TLD identifier
                        u"(?:\.(?:[a-z\u00a1-\uffff]{2,}))"
                        u")"
                        # port number
                        u"(?::\d{2,5})?"
                        # resource path
                        u"(?:/\S*)?"
                        # query string
                        u"(?:\?\S*)?"
                        u"$",
                        re.UNICODE | re.IGNORECASE
                       )
def url_validate(url):   
    """ URL string validation
    """                                                                                                                                                      
    return re.compile(URL_PATTERN).match(url)

How do you monitor network traffic on the iPhone?

I use Charles Web Debugging Proxy it costs but they have a trial version.

It is very simple to set up if your iPhone/iPad share the same Wifi network as your Mac.

  1. Install Charles on your Mac
  2. Get the IP address for your Mac - use the Mac "Network utility"
  3. On your iPhone/iPad open the Wifi settings and under the "HTTP Proxy" change to manual and enter the IP from step (2) and then Port to 8888 (Charles default Port)
  4. Open Charles and under the Proxy Settings dialogmake sure the “Enable Mac OS X Proxy” and “Use HTTP Proxy” are ticked
  5. You should now see the traffic appearing within Charles
  6. If you want to look at HTTPS traffic you need to do the additional 2 steps download the Charles Certificate Bundle and then email the .crt file to your iPhone/iPad and install.
  7. In the Proxy Settings Dialog SSL tab, add the specific https top level domains you want to sniff with port 443.

If your Mac and iOS device are not on the same Wifi network you can set up your Mac as a Wifi router using the "Internet Sharing" option under Sharing in the System Preferences. You then connect your device to that "Wifi" network and follow the steps above.

How to delete a localStorage item when the browser window/tab is closed?

use sessionStorage

The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the browser window.

The following example counts the number of times a user has clicked a button, in the current session:

Example

if (sessionStorage.clickcount) {
    sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
    sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
sessionStorage.clickcount + " time(s) in this session.";

CS0120: An object reference is required for the nonstatic field, method, or property 'foo'

Credit to @COOLGAMETUBE for tipping me off to what ended up working for me. His idea was good but I had a problem when Application.SetCompatibleTextRenderingDefault was called after the form was already created. So with a little change, this is working for me:


static class Program
{
    public static Form1 form1; // = new Form1(); // Place this var out of the constructor

/// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(form1 = new Form1()); } }

How to read strings from a Scanner in a Java console application?

You are entering a null value to nextInt, it will fail if you give a null value...

i have added a null check to the piece of code

Try this code:

import java.util.Scanner;
class MyClass
{
     public static void main(String args[]){

                Scanner scanner = new Scanner(System.in);
                int eid,sid;
                String ename;
                System.out.println("Enter Employeeid:");
                     eid=(scanner.nextInt());
                System.out.println("Enter EmployeeName:");
                     ename=(scanner.next());
                System.out.println("Enter SupervisiorId:");
                    if(scanner.nextLine()!=null&&scanner.nextLine()!=""){//null check
                     sid=scanner.nextInt();
                     }//null check
        }
}

SSRS chart does not show all labels on Horizontal axis

The problem here is that if there are too many data bars the labels will not show.

To fix this, under the "Chart Axis" properties set the Interval value to "=1". Then all the labels will be shown.

Javascript: formatting a rounded number to N decimals

There's always a better way for doing things.

var number = 51.93999999999761;

I would like to get four digits precision: 51.94

just do:

number.toPrecision(4);

the result will be: 51.94

How do I find the install time and date of Windows?

Press WindowsKey + R and enter cmd

In the command window type:

systeminfo | find /i "Original"

(for older versions of windows, type "ORIGINAL" in all capital letters).

Node.js - EJS - including a partial

In oficial documentation https://github.com/mde/ejs#includes show that includes works like that:

<%- include('../partials/head') %>

How to use a parameter in ExecStart command line?

To attempt command line arguments directly is not possible.

One alternative might be environment variables (https://superuser.com/questions/728951/systemd-giving-my-service-multiple-arguments).

This is where I found the answer: http://www.freedesktop.org/software/systemd/man/systemctl.html

so sudo systemctl restart myprog -v -- systemctl will think you're trying to set one of its flags, not myprog's flag.

sudo systemctl restart myprog someotheroption -- systemctl will restart myprog and the someotheroption service, if it exists.

Subset a dataframe by multiple factor levels

Try this:

> data[match(as.character(data$Code), selected, nomatch = FALSE), ]
    Code Value
1      A     1
2      B     2
1.1    A     1
1.2    A     1

What should a JSON service return on failure / error

I would definitely return a 500 error with a JSON object describing the error condition, similar to how an ASP.NET AJAX "ScriptService" error returns. I believe this is fairly standard. It's definitely nice to have that consistency when handling potentially unexpected error conditions.

Aside, why not just use the built in functionality in .NET, if you're writing it in C#? WCF and ASMX services make it easy to serialize data as JSON, without reinventing the wheel.

List(of String) or Array or ArrayList

You can use IList(Of String) in the function :

Private Function getWriteBits() As IList(Of String)


Dim temp1 As String
Dim temp2 As Boolean
Dim temp3 As Boolean


'Pallet Destination Unique
Dim temp4 As Boolean
Dim temp5 As Boolean
Dim temp6 As Boolean

Dim lstWriteBits As Ilist = {temp1, temp2, temp3, temp4, temp5, temp6}

Return lstWriteBits
End Function

use list1.AddRange(list2) to add lists

Hope it helps.

adb command not found in linux environment

Make sure you installed sudo apt-get install android-tools-adb Now check sudo adb It will show help of adb

Now please kill/start adb use following commands -

sudo adb kill-server sudo adb start-server

Lastly, sudo adb devices

Hopefully this will work !!!

How to call a stored procedure from Java and JPA

To call stored procedure we can use Callable Statement in java.sql package.

jQuery callback on image load (even when the image is cached)

A solution I found https://bugs.chromium.org/p/chromium/issues/detail?id=7731#c12 (This code taken directly from the comment)

var photo = document.getElementById('image_id');
var img = new Image();
img.addEventListener('load', myFunction, false);
img.src = 'http://newimgsource.jpg';
photo.src = img.src;

Convert Month Number to Month Name Function in SQL

This one worked for me:

@MetricMonthNumber (some number)

SELECT 
(DateName( month , DateAdd( month , @MetricMonthNumber - 1 , '1900-01-01' ) )) AS MetricMonthName
FROM TableName

From a post above from @leoinfo and @Valentino Vranken. Just did a quick select and it works.

Django: Calling .update() on a single model instance retrieved by .get()?

I don't know how good or bad this is, but you can try something like this:

try:
    obj = Model.objects.get(id=some_id)
except Model.DoesNotExist:
    obj = Model.objects.create()
obj.__dict__.update(your_fields_dict) 
obj.save()

The EXECUTE permission was denied on the object 'xxxxxxx', database 'zzzzzzz', schema 'dbo'

Best solution that i found is create a new database role i.e.

CREATE ROLE db_executor;

and then grant that role exec permission.

GRANT EXECUTE TO db_executor;

Now when you go to the properties of the user and go to User Mapping and select the database where you have added new role,now new role will be visible in the Database role membership for: section

For more detail read full article

Java - ignore exception and continue

You could catch the NullPointerException explicitly and ignore it - though its generally not recommended. You should not, however, ignore all exceptions as you're currently doing.

UserInfo ui = new UserInfo();
try {
    DirectoryUser du = LDAPService.findUser(username);
    if (du!=null) {
       ui.setUserInfo(du.getUserInfo());
    }
} catch (NullPointerException npe) {
    // Lulz @ your NPE
    Logger.log("No user info for " +username+ ", will find some way to cope");
}

A simple scenario using wait() and notify() in java

Example for wait() and notifyall() in Threading.

A synchronized static array list is used as resource and wait() method is called if the array list is empty. notify() method is invoked once a element is added for the array list.

public class PrinterResource extends Thread{

//resource
public static List<String> arrayList = new ArrayList<String>();

public void addElement(String a){
    //System.out.println("Add element method "+this.getName());
    synchronized (arrayList) {
        arrayList.add(a);
        arrayList.notifyAll();
    }
}

public void removeElement(){
    //System.out.println("Remove element method  "+this.getName());
    synchronized (arrayList) {
        if(arrayList.size() == 0){
            try {
                arrayList.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else{
            arrayList.remove(0);
        }
    }
}

public void run(){
    System.out.println("Thread name -- "+this.getName());
    if(!this.getName().equalsIgnoreCase("p4")){
        this.removeElement();
    }
    this.addElement("threads");

}

public static void main(String[] args) {
    PrinterResource p1 = new PrinterResource();
    p1.setName("p1");
    p1.start();

    PrinterResource p2 = new PrinterResource();
    p2.setName("p2");
    p2.start();


    PrinterResource p3 = new PrinterResource();
    p3.setName("p3");
    p3.start();


    PrinterResource p4 = new PrinterResource();
    p4.setName("p4");
    p4.start();     

    try{
        p1.join();
        p2.join();
        p3.join();
        p4.join();
    }catch(InterruptedException e){
        e.printStackTrace();
    }
    System.out.println("Final size of arraylist  "+arrayList.size());
   }
}

How can I convert a series of images to a PDF from the command line on linux?

Use convert from http://www.imagemagick.org. (Readily supplied as a package in most Linux distributions.)

jQuery vs. javascript?

Jquery like any other good JavaScript frameworks supplies you with functionality independent of browser platform wrapping all the intricacies, which you may not care about or don't want to care about.

I think using a framework is better instead of using pure JavaScript and doing all the stuff from scratch, unless you usage is very limited.

I definitely recommend JQuery!

Thanks

How to use CMAKE_INSTALL_PREFIX

But do remember to place it BEFORE PROJECT(< project_name>) command, otherwise it will not work!

My first week of using cmake - after some years of GNU autotools - so I am still learning (better then writing m4 macros), but I think modifying CMAKE_INSTALL_PREFIX after setting project is the better place.

CMakeLists.txt

cmake_minimum_required (VERSION 2.8)

set (CMAKE_INSTALL_PREFIX /foo/bar/bubba)
message("CIP = ${CMAKE_INSTALL_PREFIX} (should be /foo/bar/bubba")
project (BarkBark)
message("CIP = ${CMAKE_INSTALL_PREFIX} (should be /foo/bar/bubba")
set (CMAKE_INSTALL_PREFIX /foo/bar/bubba)
message("CIP = ${CMAKE_INSTALL_PREFIX} (should be /foo/bar/bubba")

First run (no cache)

CIP = /foo/bar/bubba (should be /foo/bar/bubba
-- The C compiler identification is GNU 4.4.7
-- etc, etc,...
CIP = /usr/local (should be /foo/bar/bubba
CIP = /foo/bar/bubba (should be /foo/bar/bubba
-- Configuring done
-- Generating done

Second run

CIP = /foo/bar/bubba (should be /foo/bar/bubba
CIP = /foo/bar/bubba (should be /foo/bar/bubba
CIP = /foo/bar/bubba (should be /foo/bar/bubba
-- Configuring done
-- Generating done

Let me know if I am mistaken, I have a lot of learning to do. It's fun.

Excel VBA - How to Redim a 2D array?

A small update to what @control freak and @skatun wrote previously (sorry I don't have enough reputation to just make a comment). I used skatun's code and it worked well for me except that it was creating a larger array than what I needed. Therefore, I changed:

ReDim aPreservedArray(nNewFirstUBound, nNewLastUBound)

to:

ReDim aPreservedArray(LBound(aArrayToPreserve, 1) To nNewFirstUBound, LBound(aArrayToPreserve, 2) To nNewLastUBound)

This will maintain whatever the original array's lower bounds were (either 0, 1, or whatever; the original code assumes 0) for both dimensions.

How to make g++ search for header files in a specific directory?

A/code.cpp

#include <B/file.hpp>

A/a/code2.cpp

#include <B/file.hpp>

Compile using:

g++ -I /your/source/root /your/source/root/A/code.cpp
g++ -I /your/source/root /your/source/root/A/a/code2.cpp

Edit:

You can use environment variables to change the path g++ looks for header files. From man page:

Some additional environments variables affect the behavior of the preprocessor.

   CPATH
   C_INCLUDE_PATH
   CPLUS_INCLUDE_PATH
   OBJC_INCLUDE_PATH

Each variable's value is a list of directories separated by a special character, much like PATH, in which to look for header files. The special character, "PATH_SEPARATOR", is target-dependent and determined at GCC build time. For Microsoft Windows-based targets it is a semicolon, and for almost all other targets it is a colon.

CPATH specifies a list of directories to be searched as if specified with -I, but after any paths given with -I options on the command line. This environment variable is used regardless of which language is being preprocessed.

The remaining environment variables apply only when preprocessing the particular language indicated. Each specifies a list of directories to be searched as if specified with -isystem, but after any paths given with -isystem options on the command line.

In all these variables, an empty element instructs the compiler to search its current working directory. Empty elements can appear at the beginning or end of a path. For instance, if the value of CPATH is ":/special/include", that has the same effect as -I. -I/special/include.

There are many ways you can change an environment variable. On bash prompt you can do this:

$ export CPATH=/your/source/root
$ g++ /your/source/root/A/code.cpp
$ g++ /your/source/root/A/a/code2.cpp

You can of course add this in your Makefile etc.

How do I detect a click outside an element?

As another poster said there are a lot of gotchas, especially if the element you are displaying (in this case a menu) has interactive elements. I've found the following method to be fairly robust:

$('#menuscontainer').click(function(event) {
    //your code that shows the menus fully

    //now set up an event listener so that clicking anywhere outside will close the menu
    $('html').click(function(event) {
        //check up the tree of the click target to check whether user has clicked outside of menu
        if ($(event.target).parents('#menuscontainer').length==0) {
            // your code to hide menu

            //this event listener has done its job so we can unbind it.
            $(this).unbind(event);
        }

    })
});

C - error: storage size of ‘a’ isn’t known

In this case the user has done mistake in definition and its usage. If someone has done a typedef to a structure the same should be used without using struct following is the example.

typedef struct
{
   int a;
}studyT;

When using in a function

int main()
{
   struct studyT study; // This will give above error.
   studyT stud; // This will eliminate the above error.
   return 0;
}

Getting java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory exception

I have also faced the same issues, to fix, download the jar files from the below url

http://commons.apache.org/logging/download_logging.cgi

and copy to your lib folder, will resolve your issue.

Convert Data URI to File then append to FormData

The original answer by Stoive is easily fixable by changing the last line to accommodate Blob:

function dataURItoBlob (dataURI) {
    // convert base64 to raw binary data held in a string
    // doesn't handle URLEncoded DataURIs
    var byteString;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(dataURI.split(',')[1]);
    else
        byteString = unescape(dataURI.split(',')[1]);
    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to an ArrayBuffer
    var ab = new ArrayBuffer(byteString.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    // write the ArrayBuffer to a blob, and you're done
    return new Blob([ab],{type: mimeString});
}

How do I collapse sections of code in Visual Studio Code for Windows?

This feature is available in the standard build now. To make the collapse/expand controls appears, you need to mouse over the area just to the right of the line numbers as shown in this screenshot:

Enter image description here

Running Google Maps v2 on the Android emulator

I have already replied to this question in an answer to Stack Overflow question Trouble using Google sign-in button in emulator. It only works for Android 4.2.2, but lets you use the "Intel Atom (x86)" in AVD.

I think that it is easy to make it work for other versions of Android. Just find the correct files.

$(this).attr("id") not working

I recommend you to read more about the this keyword.

You cannot expect "this" to select the "select" tag in this case.

What you want to do in this case is use obj.id to get the id of select tag.

Stacking DIVs on top of each other?

All the answers seem pretty old :) I'd prefer CSS grid for a better page layout (absolute divs can be overridden by other divs in the page.)

<div class="container">
  <div class="inner" style="background-color: white;"></div>
  <div class="inner" style="background-color: red;"></div>
  <div class="inner" style="background-color: green;"></div>
  <div class="inner" style="background-color: blue;"></div>
  <div class="inner" style="background-color: purple;"></div>
  <div class="inner no-display" style="background-color: black;"></div>
</div>

<style>
.container {
  width: 300px;
  height: 300px;
  margin: 0 auto;
  background-color: yellow;
  display: grid;
  place-items: center;
  grid-template-areas:
                  "inners";
}

.inner {
  grid-area: inners;
  height: 100px;
  width: 100px;
}

.no-display {
  display: none;
}
</style>

Here's a working link

What is the GAC in .NET?

Centralized DLL library.

How to read Data from Excel sheet in selenium webdriver

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

String FilePath = "/home/lahiru/Desktop/Sample.xls";
FileInputStream fs = new FileInputStream(FilePath);
Workbook wb = Workbook.getWorkbook(fs);

String <variable> = sh.getCell("A2").getContents();

The maximum recursion 100 has been exhausted before statement completion

Specify the maxrecursion option at the end of the query:

...
from EmployeeTree
option (maxrecursion 0)

That allows you to specify how often the CTE can recurse before generating an error. Maxrecursion 0 allows infinite recursion.

String comparison - Android

You can use, contentEquals() function. It may help you..

Sending email in .NET through Gmail

I had the same issue, but it was resolved by going to gmail's security settings and Allowing Less Secure apps. The Code from Domenic & Donny works, but only if you enabled that setting

If you are signed in (to Google) you can follow this link and toggle "Turn on" for "Access for less secure apps"

How do I add a project as a dependency of another project?

Assuming the MyEjbProject is not another Maven Project you own or want to build with maven, you could use system dependencies to link to the existing jar file of the project like so

<project>
   ...
   <dependencies>
      <dependency>
         <groupId>yourgroup</groupId>
         <artifactId>myejbproject</artifactId>
         <version>2.0</version>
         <scope>system</scope>
         <systemPath>path/to/myejbproject.jar</systemPath>
      </dependency>
   </dependencies>
   ...
</project>

That said it is usually the better (and preferred way) to install the package to the repository either by making it a maven project and building it or installing it the way you already seem to do.


If they are, however, dependent on each other, you can always create a separate parent project (has to be a "pom" project) declaring the two other projects as its "modules". (The child projects would not have to declare the third project as their parent). As a consequence you'd get a new directory for the new parent project, where you'd also quite probably put the two independent projects like this:

parent
|- pom.xml
|- MyEJBProject
|   `- pom.xml
`- MyWarProject
    `- pom.xml

The parent project would get a "modules" section to name all the child modules. The aggregator would then use the dependencies in the child modules to actually find out the order in which the projects are to be built)

<project>
   ...
   <artifactId>myparentproject</artifactId>
   <groupId>...</groupId>
   <version>...</version>

   <packaging>pom</packaging>
   ...
   <modules>
     <module>MyEJBModule</module>
     <module>MyWarModule</module>
   </modules>
   ...
</project>

That way the projects can relate to each other but (once they are installed in the local repository) still be used independently as artifacts in other projects


Finally, if your projects are not in related directories, you might try to give them as relative modules:

filesystem
 |- mywarproject
 |   `pom.xml
 |- myejbproject
 |   `pom.xml
 `- parent
     `pom.xml

now you could just do this (worked in maven 2, just tried it):

<!--parent-->
<project>
  <modules>
    <module>../mywarproject</module>
    <module>../myejbproject</module>
  </modules>
</project>

Use table name in MySQL SELECT "AS"

SELECT field1, field2, 'Test' AS field3 FROM Test; // replace with simple quote '

Mergesort with Python

    def merge(a,low,mid,high):
        l=a[low:mid+1]
        r=a[mid+1:high+1]
        #print(l,r)
        k=0;i=0;j=0;
        c=[0 for i in range(low,high+1)]
        while(i<len(l) and j<len(r)):
            if(l[i]<=r[j]):

                c[k]=(l[i])
                k+=1

                i+=1
            else:
                c[k]=(r[j])
                j+=1
                k+=1
        while(i<len(l)):
            c[k]=(l[i])
            k+=1
            i+=1

        while(j<len(r)):
            c[k]=(r[j])
            k+=1
            j+=1
        #print(c)  
        a[low:high+1]=c  

    def mergesort(a,low,high):
        if(high>low):
            mid=(low+high)//2


            mergesort(a,low,mid)
            mergesort(a,mid+1,high)
            merge(a,low,mid,high)

    a=[12,8,3,2,9,0]
    mergesort(a,0,len(a)-1)
    print(a)

Which Protocols are used for PING?

Ping can be used with a variety of protocols. The protocol value can be appletalk, clns, ip (the default), novell, apollo, vines, decnet, or xns. Some protocols require another Cisco router at the remote end to answer ping packets. ... (Cisco field manual: router configuration, By Dave Hucaby, Steve McQuerry. Page 64)

... For IP. ping uses ICMP type 8 requests and ICMP type 0 replies. The traceroute (by using UDP) command can be used to discover the routers along the path that packets are taking to a destination. ... (Page 63)

u'\ufeff' in Python string

I ran into this on Python 3 and found this question (and solution). When opening a file, Python 3 supports the encoding keyword to automatically handle the encoding.

Without it, the BOM is included in the read result:

>>> f = open('file', mode='r')
>>> f.read()
'\ufefftest'

Giving the correct encoding, the BOM is omitted in the result:

>>> f = open('file', mode='r', encoding='utf-8-sig')
>>> f.read()
'test'

Just my 2 cents.

Setting the Textbox read only property to true using JavaScript

document.getElementById('textbox-id').readOnly=true should work

Android SharedPreferences in Fragment

Maybe this is helpfull to someone after few years. New way, on Androidx, of getting SharedPreferences() inside fragment is to implement into gradle dependencies

implementation "androidx.preference:preference:1.1.1"

and then, inside fragment call

SharedPreferences preferences;
preferences = androidx.preference.PreferenceManager.getDefaultSharedPreferences(getActivity());

Read a zipped file as a pandas DataFrame

It seems you don't even have to specify the compression any more. The following snippet loads the data from filename.zip into df.

import pandas as pd
df = pd.read_csv('filename.zip')

(Of course you will need to specify separator, header, etc. if they are different from the defaults.)

Math.random() versus Random.nextInt(int)

another important point is that Random.nextInt(n) is repeatable since you can create two Random object with the same seed. This is not possible with Math.random().

NUnit Unit tests not showing in Test Explorer with Test Adapter installed

If you are using VS 2017 and .net core ,as said here, you should add references to the test framework NUnit 3.6.1, to the test runner NUnit3TestAdapter 3.8.0-alpha1 and to the test SDK Microsoft.NET.Test.Sdk 15.0.0.

HTML Form: Select-Option vs Datalist-Option

Think of it as the difference between a requirement and a suggestion. For the select element, the user is required to select one of the options you've given. For the datalist element, it is suggested that the user select one of the options you've given, but he can actually enter anything he wants in the input.

Edit 1: So which one you use depends upon your requirements. If the user must enter one of your choices, use the select element. If the use can enter whatever, use the datalist element.

Edit 2: Found this tidbit in the HTML Living Standard: "Each option element that is a descendant of the datalist element...represents a suggestion."

What is the difference between null=True and blank=True in Django?

null is for database and blank is for fields validation that you want to show on user interface like textfield to get the last name of person. If lastname=models.charfield (blank=true) it didnot ask user to enter last name as this is the optional field now. If lastname=models.charfield (null=true) then it means that if this field doesnot get any value from user then it will store in database as an empty string " ".

How to convert a column number (e.g. 127) into an Excel column (e.g. AA)

Microsoft Excel Miniature, Quick-and-Dirty formula.

Hi,

Here's one way to get the Excel character-column-header from a number....

I created a formula for an Excel cell.

(i.e. I took the approach of not using VBA programming.)

The formula looks at a cell that has a number in it and tells you what the column is -- in letters.

In the attached image:

  • I put 1,2,3 etc in the top row all the way out to column ABS.
  • I pasted my formula in the second row all the way out to ABS.
  • My formula looks at row 1 and converts the number to Excel's column header id.
  • My formula works for all numbers out to 702 (zz).
  • I did it in this manner to prove that the formula works so you can look at the output from the formula and look at the column header above and easily visually verify that the formula works. :-)

    =CONCATENATE(MID("_abcdefghijklmnopqrstuvwxyz",(IF(MOD(K1,26)>0,INT(K1/26)+1,(INT(K1/26)))),1),MID("abcdefghijklmnopqrstuvwxyz",IF(MOD(K1,26)=0,26,MOD(K1,26)),1))

The underscore was there for debugging purposes - to let you know there was an actual space and that it was working correctly.

With this formula above -- whatever you put in K1 - the formula will tell you what the column header will be.

The formula, in its current form, only goes out to 2 digits (ZZ) but could be modified to add the 3rd letter (ZZZ).

enter image description here

Can't find file executable in your configured search path for gnc gcc compiler

Just open your setting->compiler and click on the reset defaults and it will start work.

Redeploy alternatives to JRebel

I have been working on an open source project that allows you to hot replace classes over and above what hot swap allows: https://github.com/fakereplace/fakereplace

It may or may not work for you, but any feedback is appreciated

Linq where clause compare only date value without time value

In similar case I used the following code:

DateTime upperBound = DateTime.Today.AddDays(1); // If today is October 9, then upperBound is set to 2012-10-10 00:00:00
return var _My_ResetSet_Array = _DB
    .tbl_MyTable
    .Where(x => x.Active == true
        && x.DateTimeValueColumn < upperBound) // Accepts all dates earlier than October 10, time of day doesn't matter here
    .Select(x => x);

Getting XML Node text value with Java DOM

I'd print out the result of an2.getNodeName() as well for debugging purposes. My guess is that your tree crawling code isn't crawling to the nodes that you think it is. That suspicion is enhanced by the lack of checking for node names in your code.

Other than that, the javadoc for Node defines "getNodeValue()" to return null for Nodes of type Element. Therefore, you really should be using getTextContent(). I'm not sure why that wouldn't give you the text that you want.

Perhaps iterate the children of your tag node and see what types are there?

Tried this code and it works for me:

String xml = "<add job=\"351\">\n" +
             "    <tag>foobar</tag>\n" +
             "    <tag>foobar2</tag>\n" +
             "</add>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
Document doc = db.parse(bis);
Node n = doc.getFirstChild();
NodeList nl = n.getChildNodes();
Node an,an2;

for (int i=0; i < nl.getLength(); i++) {
    an = nl.item(i);
    if(an.getNodeType()==Node.ELEMENT_NODE) {
        NodeList nl2 = an.getChildNodes();

        for(int i2=0; i2<nl2.getLength(); i2++) {
            an2 = nl2.item(i2);
            // DEBUG PRINTS
            System.out.println(an2.getNodeName() + ": type (" + an2.getNodeType() + "):");
            if(an2.hasChildNodes()) System.out.println(an2.getFirstChild().getTextContent());
            if(an2.hasChildNodes()) System.out.println(an2.getFirstChild().getNodeValue());
            System.out.println(an2.getTextContent());
            System.out.println(an2.getNodeValue());
        }
    }
}

Output was:

#text: type (3): foobar foobar
#text: type (3): foobar2 foobar2

Finding height in Binary Search Tree

public int height(){

    if(this.root== null) return 0;

    int leftDepth = nodeDepth(this.root.left, 1);
    int rightDepth = nodeDepth(this.root.right, 1);

    int height = leftDepth > rightDepth? leftDepth: rightDepth;

    return height;
}


private int nodeDepth(Node node, int startValue){

    int nodeDepth = 0;

    if(node.left == null && node.right == null) return startValue;
    else{
        startValue++;
        if(node.left!= null){
            nodeDepth = nodeDepth(node.left, startValue);
        }

        if(node.right!= null){
            nodeDepth = nodeDepth(node.right, startValue);
        }
    }

    return nodeDepth;
}

nodejs - How to read and output jpg image?

Two things to keep in mind Content-Type and the Encoding

1) What if the file is css

if (/.(css)$/.test(path)) {
  res.writeHead(200, {'Content-Type': 'text/css'}); 
  res.write(data, 'utf8');
} 

2) What if the file is jpg/png

if (/.(jpg)$/.test(path)) {
  res.writeHead(200, {'Content-Type': 'image/jpg'});
  res.end(data,'Base64');
}

Above one is just a sample code to explain the answer and not the exact code pattern.

In bash, how to store a return value in a variable?

The return value (aka exit code) is a value in the range 0 to 255 inclusive. It's used to indicate success or failure, not to return information. Any value outside this range will be wrapped.

To return information, like your number, use

echo "$value"

To print additional information that you don't want captured, use

echo "my irrelevant info" >&2 

Finally, to capture it, use what you did:

 result=$(password_formula)

In other words:

echo "enter: "
        read input

password_formula()
{
        length=${#input}
        last_two=${input:length-2:length}
        first=`echo $last_two| sed -e 's/\(.\)/\1 /g'|awk '{print $2}'`
        second=`echo $last_two| sed -e 's/\(.\)/\1 /g'|awk '{print $1}'`
        let sum=$first+$second
        sum_len=${#sum}
        echo $second >&2
        echo $sum >&2

        if [ $sum -gt 9 ]
        then
               sum=${sum:1}
        fi

        value=$second$sum$first
        echo $value
}
result=$(password_formula)
echo "The value is $result"

Which header file do you include to use bool type in c in linux?

#include <stdbool.h>

For someone like me here to copy and paste.

How to 'foreach' a column in a DataTable using C#?

This should work:

DataTable dtTable;

MySQLProcessor.DTTable(mysqlCommand, out dtTable);

// On all tables' rows
foreach (DataRow dtRow in dtTable.Rows)
{
    // On all tables' columns
    foreach(DataColumn dc in dtTable.Columns)
    {
      var field1 = dtRow[dc].ToString();
    }
}

How to convert an Stream into a byte[] in C#?

Byte[] Content = new BinaryReader(file.InputStream).ReadBytes(file.ContentLength);

One DbContext per web request... why?

Another understated reason for not using a singleton DbContext, even in a single threaded single user application, is because of the identity map pattern it uses. It means that every time you retrieve data using query or by id, it will keep the retrieved entity instances in cache. The next time you retrieve the same entity, it will give you the cached instance of the entity, if available, with any modifications you have done in the same session. This is necessary so the SaveChanges method does not end up with multiple different entity instances of the same database record(s); otherwise, the context would have to somehow merge the data from all those entity instances.

The reason that is a problem is a singleton DbContext can become a time bomb that could eventually cache the whole database + the overhead of .NET objects in memory.

There are ways around this behavior by only using Linq queries with the .NoTracking() extension method. Also these days PCs have a lot of RAM. But usually that is not the desired behavior.

Meaning of "[: too many arguments" error from if [] (square brackets)

I have had same problem with my scripts. But when I did some modifications it worked for me. I did like this :-

export k=$(date "+%k");
if [ $k -ge 16 ] 
    then exit 0; 
else 
    echo "good job for nothing"; 
fi;

that way I resolved my problem. Hope that will help for you too.

CSS to set A4 paper size

CSS

body {
  background: rgb(204,204,204); 
}
page[size="A4"] {
  background: white;
  width: 21cm;
  height: 29.7cm;
  display: block;
  margin: 0 auto;
  margin-bottom: 0.5cm;
  box-shadow: 0 0 0.5cm rgba(0,0,0,0.5);
}
@media print {
  body, page[size="A4"] {
    margin: 0;
    box-shadow: 0;
  }
}

HTML

<page size="A4"></page>
<page size="A4"></page>
<page size="A4"></page>

DEMO

How to create/make rounded corner buttons in WPF?

You can try this...........

 <Border BorderBrush="Black" Name="MyBorder"  
            Height="78" 
            Background="Red" 
            Width="74" 
            CornerRadius="3">
        <Button Width="{Binding MyBorder.Width}" 
                Height="{Binding MyBorder.Height}" 
                Content="Hi" Background="Red"/>
    </Border>

Select count(*) from multiple tables

select @count = sum(data) from
(
select count(*)  as data from #tempregion
union 
select count(*)  as data from #tempmetro
union
select count(*)  as data from #tempcity
union
select count(*)  as data from #tempzips
) a

How to Convert date into MM/DD/YY format in C#

Have you tried the following?:

textbox1.text = System.DateTime.Today.ToString("MM/dd/yy");

Be aware that 2 digit years could be bad in the future...

How do you extract a column from a multi-dimensional array?

I think you want to extract a column from an array such as an array below

import numpy as np
A = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])

Now if you want to get the third column in the format

D=array[[3],
[7],
[11]]

Then you need to first make the array a matrix

B=np.asmatrix(A)
C=B[:,2]
D=asarray(C)

And now you can do element wise calculations much like you would do in excel.

Should switch statements always contain a default clause?

I would always use a default clause, no matter what language you are working in.

Things can and do go wrong. Values will not be what you expect, and so on.

Not wanting to include a default clause implies you are confident that you know the set of possible values. If you believe you know the set of possible values then, if the value is outside this set of possible values, you'd want to be informed of it - it's certainly an error.

That's the reason why you should always use a default clause and throw an error, for example in Java:

switch (myVar) {
   case 1: ......; break;
   case 2: ......; break;
   default: throw new RuntimeException("unreachable");
}

There's no reason to include more information than just the "unreachable" string; if it actually happens, you're going to need to look at the source and the values of the variables etc anyway, and the exception stacktrace will include that line number, so no need to waste your time writing more text into the exception message.

CertPathValidatorException : Trust anchor for certificate path not found - Retrofit Android

You are converting cert into BKS Keystore, why aren't you using .cert directly, from https://developer.android.com/training/articles/security-ssl.html:

CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream instream = context.getResources().openRawResource(R.raw.gtux_cert);
Certificate ca;
try {
    ca = cf.generateCertificate(instream);
} finally {
    caInput.close();
}

KeyStore kStore = KeyStore.getInstance(KeyStore.getDefaultType());
kStore.load(null, null);
kStore.setCertificateEntry("ca", ca);

TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm(););
tmf.init(kStore);

SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);

okHttpClient.setSslSocketFactory(context.getSocketFactory());

including parameters in OPENQUERY

Simple example based off of @Tuan Zaidi's example above which seemed the easiest. Didn't know you can do the filter on the outside of OPENQUERY... so much easier!

However in my case I needed to stuff it in a variable so I created an additional Sub Query Level to return a single value.

SET @SFID = (SELECT T.Id FROM (SELECT Id,  Contact_ID_SQL__c  FROM OPENQUERY([TR-SF-PROD], 'SELECT Id,  Contact_ID_SQL__c FROM Contact') WHERE Contact_ID_SQL__c = @ContactID) T)

Why should the static field be accessed in a static way?

There's actually a good reason:
The non-static access does not always work, for reasons of ambiguity.

Suppose we have two classes, A and B, the latter being a subclass of A, with static fields with the same name:

public class A {
    public static String VALUE = "Aaa";
}

public class B extends A {
    public static String VALUE = "Bbb";
}

Direct access to the static variable:

A.VALUE (="Aaa")
B.VALUE (="Bbb")

Indirect access using an instance (gives a compiler warning that VALUE should be statically accessed):

new B().VALUE (="Bbb")

So far, so good, the compiler can guess which static variable to use, the one on the superclass is somehow farther away, seems somehow logical.

Now to the point where it gets tricky: Interfaces can also have static variables.

public interface C {
    public static String VALUE = "Ccc";
}

public interface D {
    public static String VALUE = "Ddd";
}

Let's remove the static variable from B, and observe following situations:

  • B implements C, D
  • B extends A implements C
  • B extends A implements C, D
  • B extends A implements C where A implements D
  • B extends A implements C where C extends D
  • ...

The statement new B().VALUE is now ambiguous, as the compiler cannot decide which static variable was meant, and will report it as an error:

error: reference to VALUE is ambiguous
both variable VALUE in C and variable VALUE in D match

And that's exactly the reason why static variables should be accessed in a static way.

python max function using 'key' and lambda expression

lambda is an anonymous function, it is equivalent to:

def func(p):
   return p.totalScore     

Now max becomes:

max(players, key=func)

But as def statements are compound statements they can't be used where an expression is required, that's why sometimes lambda's are used.

Note that lambda is equivalent to what you'd put in a return statement of a def. Thus, you can't use statements inside a lambda, only expressions are allowed.


What does max do?

max(a, b, c, ...[, key=func]) -> value

With a single iterable argument, return its largest item. With two or more arguments, return the largest argument.

So, it simply returns the object that is the largest.


How does key work?

By default in Python 2 key compares items based on a set of rules based on the type of the objects (for example a string is always greater than an integer).

To modify the object before comparison, or to compare based on a particular attribute/index, you've to use the key argument.

Example 1:

A simple example, suppose you have a list of numbers in string form, but you want to compare those items by their integer value.

>>> lis = ['1', '100', '111', '2']

Here max compares the items using their original values (strings are compared lexicographically so you'd get '2' as output) :

>>> max(lis)
'2'

To compare the items by their integer value use key with a simple lambda:

>>> max(lis, key=lambda x:int(x))  # compare `int` version of each item
'111'

Example 2: Applying max to a list of tuples.

>>> lis = [(1,'a'), (3,'c'), (4,'e'), (-1,'z')]

By default max will compare the items by the first index. If the first index is the same then it'll compare the second index. As in my example, all items have a unique first index, so you'd get this as the answer:

>>> max(lis)
(4, 'e')

But, what if you wanted to compare each item by the value at index 1? Simple: use lambda:

>>> max(lis, key = lambda x: x[1])
(-1, 'z')

Comparing items in an iterable that contains objects of different type:

List with mixed items:

lis = ['1','100','111','2', 2, 2.57]

In Python 2 it is possible to compare items of two different types:

>>> max(lis)  # works in Python 2
'2'
>>> max(lis, key=lambda x: int(x))  # compare integer version of each item
'111'

But in Python 3 you can't do that any more:

>>> lis = ['1', '100', '111', '2', 2, 2.57]
>>> max(lis)
Traceback (most recent call last):
  File "<ipython-input-2-0ce0a02693e4>", line 1, in <module>
    max(lis)
TypeError: unorderable types: int() > str()

But this works, as we are comparing integer version of each object:

>>> max(lis, key=lambda x: int(x))  # or simply `max(lis, key=int)`
'111'

nginx: how to create an alias url route?

server {
  server_name example.com;
  root /path/to/root;
  location / {
    # bla bla
  }
  location /demo {
    alias /path/to/root/production/folder/here;
  }
}

If you need to use try_files inside /demo you'll need to replace alias with a root and do a rewrite because of the bug explained here

PHP remove all characters before specific string

You can use strstr to do this.

echo strstr($str, 'www/audio');

How to use awk sort by column 3

try this -

awk '{print $0|"sort -t',' -nk3 "}' user.csv

OR

sort -t',' -nk3 user.csv

How to change color and font on ListView

You can select a child like

TextView tv = (TextView)lv.getChildAt(0);
tv.setTextColor(Color.RED);
tv.setTextSize(12);    

Add Favicon with React and Webpack

Browsers look for your favicon in /favicon.ico, so that's where it needs to be. You can double check if you've positioned it in the correct place by navigating to [address:port]/favicon.ico and seeing if your icon appears.

In dev mode, you are using historyApiFallback, so will need to configure webpack to explicitly return your icon for that route:

historyApiFallback: {
    index: '[path/to/index]',
    rewrites: [
        // shows favicon
        { from: /favicon.ico/, to: '[path/to/favicon]' }
    ]
}

In your server.js file, try explicitly rewriting the url:

app.configure(function() {
    app.use('/favicon.ico', express.static(__dirname + '[route/to/favicon]'));
});

(or however your setup prefers to rewrite urls)

I suggest generating a true .ico file rather than using a .png, since I've found that to be more reliable across browsers.

POST JSON fails with 415 Unsupported media type, Spring 3 mvc

I've had this happen before with Spring @ResponseBody and it was because there was no accept header sent with the request. Accept header can be a pain to set with jQuery, but this worked for me source

$.postJSON = function(url, data, callback) {
    return jQuery.ajax({
    headers: { 
        'Accept': 'application/json',
        'Content-Type': 'application/json' 
    },
    'type': 'POST',
    'url': url,
    'data': JSON.stringify(data),
    'dataType': 'json',
    'success': callback
    });
};

The Content-Type header is used by @RequestBody to determine what format the data being sent from the client in the request is. The accept header is used by @ResponseBody to determine what format to sent the data back to the client in the response. That's why you need both headers.

More elegant way of declaring multiple variables at the same time

Like JavaScript you can also use multiple statements on one line in python a = 1; b = "Hello World"; c += 3

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

I ran into this problem and inspired by @Jeremy Cook's answer, I bit the bullet to find out what the heck caused IIS 7 Integrated mode to not like my web.config. Here's my scenario:

  1. Web API (version 4.0.030506.0 aka the old one)
  2. .NET 4.0
  3. Attribute Routing 3.5.6 for Web API [spoiler alert: it was this guy!]

I wanted to use attribute routing in a project that (unfortunately) had to use .NET 4 and hence could not use Web API 2.2 (which needs .NET 4.5). The well meaning NuGet package added this section under the <system.web> section:

<system.web>
<httpHandlers>
      <add verb="*" path="routes.axd" type="AttributeRouting.Web.Logging.LogRoutesHandler, AttributeRouting.Web" />
    </httpHandlers>
</system.web>

[I say well meaning, because this part is required on older versions of IIS]

Removing this section got me past the HTTP 500.23!!

Summary: I second Jeremy's words that it is important to understand why things don't work rather than just "masking the symptom". Even if you have to mask the symptom, you know what you are doing (and why) :-)

Read HttpContent in WebApi controller

You can keep your CONTACT parameter with the following approach:

using (var stream = new MemoryStream())
{
    var context = (HttpContextBase)Request.Properties["MS_HttpContext"];
    context.Request.InputStream.Seek(0, SeekOrigin.Begin);
    context.Request.InputStream.CopyTo(stream);
    string requestBody = Encoding.UTF8.GetString(stream.ToArray());
}

Returned for me the json representation of my parameter object, so I could use it for exception handling and logging.

Found as accepted answer here

How does the compilation/linking process work?

The compilation of a C++ program involves three steps:

  1. Preprocessing: the preprocessor takes a C++ source code file and deals with the #includes, #defines and other preprocessor directives. The output of this step is a "pure" C++ file without pre-processor directives.

  2. Compilation: the compiler takes the pre-processor's output and produces an object file from it.

  3. Linking: the linker takes the object files produced by the compiler and produces either a library or an executable file.

Preprocessing

The preprocessor handles the preprocessor directives, like #include and #define. It is agnostic of the syntax of C++, which is why it must be used with care.

It works on one C++ source file at a time by replacing #include directives with the content of the respective files (which is usually just declarations), doing replacement of macros (#define), and selecting different portions of text depending of #if, #ifdef and #ifndef directives.

The preprocessor works on a stream of preprocessing tokens. Macro substitution is defined as replacing tokens with other tokens (the operator ## enables merging two tokens when it makes sense).

After all this, the preprocessor produces a single output that is a stream of tokens resulting from the transformations described above. It also adds some special markers that tell the compiler where each line came from so that it can use those to produce sensible error messages.

Some errors can be produced at this stage with clever use of the #if and #error directives.

Compilation

The compilation step is performed on each output of the preprocessor. The compiler parses the pure C++ source code (now without any preprocessor directives) and converts it into assembly code. Then invokes underlying back-end(assembler in toolchain) that assembles that code into machine code producing actual binary file in some format(ELF, COFF, a.out, ...). This object file contains the compiled code (in binary form) of the symbols defined in the input. Symbols in object files are referred to by name.

Object files can refer to symbols that are not defined. This is the case when you use a declaration, and don't provide a definition for it. The compiler doesn't mind this, and will happily produce the object file as long as the source code is well-formed.

Compilers usually let you stop compilation at this point. This is very useful because with it you can compile each source code file separately. The advantage this provides is that you don't need to recompile everything if you only change a single file.

The produced object files can be put in special archives called static libraries, for easier reusing later on.

It's at this stage that "regular" compiler errors, like syntax errors or failed overload resolution errors, are reported.

Linking

The linker is what produces the final compilation output from the object files the compiler produced. This output can be either a shared (or dynamic) library (and while the name is similar, they haven't got much in common with static libraries mentioned earlier) or an executable.

It links all the object files by replacing the references to undefined symbols with the correct addresses. Each of these symbols can be defined in other object files or in libraries. If they are defined in libraries other than the standard library, you need to tell the linker about them.

At this stage the most common errors are missing definitions or duplicate definitions. The former means that either the definitions don't exist (i.e. they are not written), or that the object files or libraries where they reside were not given to the linker. The latter is obvious: the same symbol was defined in two different object files or libraries.

How to delete mysql database through shell command

In general, you can pass any query to mysql from shell with -e option.

mysql -u username -p -D dbname -e "DROP DATABASE dbname"

How do I create a comma-separated list using a SQL query?

There is no way to do it in a DB-agnostic way. So you need to get the whole data-set like this:

select 
  r.name as ResName, 
  a.name as AppName
from 
  Resouces as r, 
  Applications as a, 
  ApplicationsResources as ar
where
  ar.app_id = a.id 
  and ar.resource_id = r.id

And then concat the AppName programmatically while grouping by ResName.

How to add more than one machine to the trusted hosts list using winrm

Same as @Altered-Ego but with txt.file:

Get-Content "C:\ServerList.txt"
machineA,machineB,machineC,machineD


$ServerList = Get-Content "C:\ServerList.txt"
    $currentTrustHost=(get-item WSMan:\localhost\Client\TrustedHosts).value
    if ( ($currentTrustHost).Length -gt "0" ) {
        $currentTrustHost+= ,$ServerList
        set-item WSMan:\localhost\Client\TrustedHosts –value $currentTrustHost -Force -ErrorAction SilentlyContinue
        }
    else {
        $currentTrustHost+= $ServerList
        set-item WSMan:\localhost\Client\TrustedHosts –value $currentTrustHost -Force -ErrorAction SilentlyContinue
    }

The "-ErrorAction SilentlyContinue" is required in old PS version to avoid fake error message:

PS C:\Windows\system32> get-item WSMan:\localhost\Client\TrustedHosts


   WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Client

Type            Name                           SourceOfValue   Value
----            ----                           -------------   -----
System.String   TrustedHosts                                   machineA,machineB,machineC,machineD

Sending Windows key using SendKeys

Alt+F4 is working only in brackets

SendKeys.SendWait("(%{F4})");

Initializing default values in a struct

You don't even need to define a constructor

struct foo {
    bool a = true;
    bool b = true;
    bool c;
 } bar;

To clarify: these are called brace-or-equal-initializers (because you may also use brace initialization instead of equal sign). This is not only for aggregates: you can use this in normal class definitions. This was added in C++11.

How to convert C# nullable int to int

All you need is..

v2= v1.GetValueOrDefault();

ModelState.AddModelError - How can I add an error that isn't for a property?

Putting the model dot property in strings worked for me: ModelState.AddModelError("Item1.Month", "This is not a valid date");

How to test if JSON object is empty in Java

I have added isEmpty() methods on JSONObject and JSONArray()

 //on JSONObject 
 public Boolean isEmpty(){         
     return !this.keys().hasNext();
 }

...

//on JSONArray
public Boolean isEmpty(){
    return this.length()==0;        
}

you can get it here https://github.com/kommradHomer/JSON-java

Javascript Date Validation ( DD/MM/YYYY) & Age Checking

To get the values use pattern.exec() instead of pattern.test() (the .test() returns a boolean value).

Eclipse - Failed to create the java virtual machine

Reduce the memory size to Xmx512m and it works.

Bash integer comparison

Easier solution;

#/bin/bash
if (( ${1:-2} >= 2 )); then
    echo "First parameter must be 0 or 1"
fi
# rest of script...

Output

$ ./test 
First parameter must be 0 or 1
$ ./test 0
$ ./test 1
$ ./test 4
First parameter must be 0 or 1
$ ./test 2
First parameter must be 0 or 1

Explanation

  • (( )) - Evaluates the expression using integers.
  • ${1:-2} - Uses parameter expansion to set a value of 2 if undefined.
  • >= 2 - True if the integer is greater than or equal to two 2.

R Error in x$ed : $ operator is invalid for atomic vectors

Because $ does not work on atomic vectors. Use [ or [[ instead. From the help file for $:

The default methods work somewhat differently for atomic vectors, matrices/arrays and for recursive (list-like, see is.recursive) objects. $ is only valid for recursive objects, and is only discussed in the section below on recursive objects.

x[["ed"]] will work.

On duplicate key ignore?

Would suggest NOT using INSERT IGNORE as it ignores ALL errors (ie its a sloppy global ignore). Instead, since in your example tag is the unique key, use:

INSERT INTO table_tags (tag) VALUES ('tag_a'),('tab_b'),('tag_c') ON DUPLICATE KEY UPDATE tag=tag;

on duplicate key produces:

Query OK, 0 rows affected (0.07 sec)

Kotlin - Property initialization using "by lazy" vs. "lateinit"

Additionnally to hotkey's good answer, here is how I choose among the two in practice:

lateinit is for external initialisation: when you need external stuff to initialise your value by calling a method.

e.g. by calling:

private lateinit var value: MyClass

fun init(externalProperties: Any) {
   value = somethingThatDependsOn(externalProperties)
}

While lazy is when it only uses dependencies internal to your object.

How to resolve "local edit, incoming delete upon update" message

So you can just revert the file that you deleted but remember, If you are working on any type of project with a set project file (like iOS), reverting the file will add it to your system folder structure but not your project file structure. additional steps may be required if you are in this case

How to read integer values from text file

You might want to do something like this (if you're using java 5 and more)

Scanner scanner = new Scanner(new File("tall.txt"));
int [] tall = new int [100];
int i = 0;
while(scanner.hasNextInt())
{
     tall[i++] = scanner.nextInt();
}

Via Julian Grenier from Reading Integers From A File In An Array

What is the simplest method of inter-process communication between 2 C# processes?

necromancing

it's just way more easy to make a shared file if possible!

//out
File.AppendAllText("sharedFile.txt", "payload text here");
// in
File.ReadAllText("sharedFile.txt");

How to pull remote branch from somebody else's repo

GitHub has a new option relative to the preceding answers, just copy/paste the command lines from the PR:

  1. Scroll to the bottom of the PR to see the Merge or Squash and merge button
  2. Click the link on the right: view command line instructions
  3. Press the Copy icon to the right of Step 1
  4. Paste the commands in your terminal

How to check if variable is array?... or something array-like

You can check instance of Traversable with a simple function. This would work for all this of Iterator because Iterator extends Traversable

function canLoop($mixed) {
    return is_array($mixed) || $mixed instanceof Traversable ? true : false;
}

Where is Android Studio layout preview?

Go to File->Invalidate Caches / Restart.

This will solve the issue.

How to use Angular2 templates with *ngFor to create a table out of nested arrays?

it's not exact output that you wanted but maybe something like this will do. Parent cmp:

<table>
  <item *ngFor="#i of items" [data]="i"></item>
</table>

Child cmp

import {Component} from 'angular2/core';

@Component({
  selector: `item`,
  inputs: ['data'],
  template: `
    <tr><td>{{data.name}}</td></tr>
    <tr *ngFor="#i of data.items">
      <td><h1>{{i}}</h1></td>
    </tr>
  `
})
export default class Item {


}

Pure Javascript listen to input value change

This is what events are for.

HTMLInputElementObject.addEventListener('input', function (evt) {
    something(this.value);
});

What is the default maximum heap size for Sun's JVM from Java SE 6?

To answer this question it's critical whether the Java VM is in CLIENT or SERVER mode. You can specify "-client" or "-server" options. Otherwise java uses internal rules; basically win32 is always client and Linux is always server, but see the table here:

http://docs.oracle.com/javase/6/docs/technotes/guides/vm/server-class.html

Sun/Oracle jre6u18 doc says re client: the VM gets 1/2 of physical memory if machine has <= 192MB; 1/4 of memory if machine has <= 1Gb; max 256Mb. In my test on a 32bit WindowsXP system with 2Gb phys mem, Java allocated 256Mb, which agrees with the doc.

Sun/Oracle jre6u18 doc says re server: same as client, then adds confusing language: for 32bit JVM the default max is 1Gb, and for 64 bit JVM the default is 32Gb. In my test on a 64bit linux machine with 8Gb physical, Java allocates 2Gb, which is 1/4 of physical; on a 64bit linux machine with 128Gb physical Java allocates 32Gb, again 1/4 of physical.

Thanks to this SO post for guiding me:

Definition of server-class machine changed recently?

Change project name on Android Studio

UPDATE:

This answer is better.

OLD ANSWER: 1. Right click your

ackage name and Refactor -> Rename...

enter image description here

  1. When asked if you want to Rename directory or Rename package, choose Rename package

enter image description here

  1. Now in Finder, manually rename your root folder (the parent folder of your /app folder)

enter image description here

  1. Reopen project in Android Studio with new folder name

  2. Cmd + Shift + f for any instances of your old name in Android Studio, and change all of them to the new name.

  3. Change the applicationId in your build.gradle

BONUS ROUND:

  • You might need to update a .gitignore file if it was at the root of your project. Note that when swapping branches after doing this, you'll potentially see a bunch of files showing up in working changes, but don't worry they should go away after you merge in your renamed branch with updated .gitignore. Don't manually remove these as it can cause issues in Android Studio.
  • Delete your old root folder in Finder

Request Monitoring in Chrome

don't know as of which chrome version this is available, but i found a setting 'Console - Log XMLHttpRequests' (clicking on the icon in the bottom right corner of developer tools in chrome on mac)

In PHP how can you clear a WSDL cache?

if you already deployed the code or can't change any configuration, you could remove all temp files from wsdl:

rm /tmp/wsdl-*

What is Parse/parsing?

Parsing is the division of text in to a set of parts or tokens.

How to update a value, given a key in a hashmap?

One line solution:

map.put(key, map.containsKey(key) ? map.get(key) + 1 : 1);

How to repeat a char using printf?

You can use the following technique:

printf("%.*s", 5, "=================");

This will print "=====" It works for me on Visual Studio, no reason it shouldn't work on all C compilers.

LocalDate to java.util.Date and vice versa simplest conversion?

Converting LocalDateTime to java.util.Date

    LocalDateTime localDateTime = LocalDateTime.now();

    ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneOffset.systemDefault());

    Instant instant = zonedDateTime.toInstant();

    Date date = Date.from(instant);

System.out.println("Result Date is : "+date);

INSTALL_FAILED_USER_RESTRICTED : android studio using redmi 4 device

Failure [INSTALL_FAILED_USER_RESTRICTED: Install canceled by user]:

Go to Settings->Additional Settings->Developer options->Developer Option(Need to enable)->USB debugging(Need to enable)->Install via USB (Need to enable)->USB debugging (Security settings)(Need to enable)

Perfectly working in the above steps.

Enjoy your coding...

How to display errors on laravel 4?

Following the good advice by @The Shift Exchange I looked at the error_log and indeed managed to solve to problem. it was simply a permissions issue:

Tue Feb 26 11:22:20 2013] [error] [client 127.0.0.1] PHP Fatal error:  Uncaught exception 'UnexpectedValueException' with message 'The stream or file "/Users/matanya/Sites/indgo/app/start/../storage/logs/log-apache2handler-2013-02-26.txt" could not be opened: failed to open stream: Permission denied' in /Users/matanya/Sites/indgo/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php:71\nStack trace:\n#0 /Users/matanya/Sites/indgo/vendor/monolog/monolog/src/Monolog/Handler/RotatingFileHandler.php(77): Monolog\\Handler\\StreamHandler->write(Array)\n#1 /Users/matanya/Sites/indgo/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php(37): Monolog\\Handler\\RotatingFileHandler->write(Array)\n#2 /Users/matanya/Sites/indgo/vendor/monolog/monolog/src/Monolog/Logger.php(217): Monolog\\Handler\\AbstractProcessingHandler->handle(Array)\n#3 /Users/matanya/Sites/indgo/vendor/monolog/monolog/src/Monolog/Logger.php(281): Monolog\\Logger->addRecord(400, Object(ErrorException), Array)\n#4 [internal function]: Monolog\\Logger->addError(Object(ErrorException))\n#5 /Users/matanya/Sites/in in /Users/matanya/Sites/indgo/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php on line 71

Once I used chmod to apply less stringent permissions, all went back to normal.

However, I'm not sure that it answers the OP's question, as he was getting a blank screen rather than a server error.

Changing the image source using jQuery

IF there is not only jQuery or other resource killing frameworks - many kb to download each time by each user just for a simple trick - but also native JavaScript(!):

<img src="img1_on.jpg" 
    onclick="this.src=this.src.match(/_on/)?'img1_off.jpg':'img1_on.jpg';">
<img src="img2_on.jpg" 
    onclick="this.src=this.src.match(/_on/)?'img2_off.jpg':'img2_on.jpg';">

This can be written general and more elegant:

<html>
<head>
<script>
function switchImg(img){
    img.src = img.src.match(/_on/) ? 
        img.src.replace(/_on/, "_off") : 
        img.src.replace(/_off/, "_on");
}
</script>
</head>
<body>
    <img src="img1_on.jpg" onclick="switchImg(this)">
    <img src="img2_on.jpg" onclick="switchImg(this)">
</body>
</html>

How do I convert a String to an InputStream in Java?

You could use a StringReader and convert the reader to an input stream using the solution in this other stackoverflow post.

Angular 2.0 and Modal Dialog

Here is my full implementation of modal bootstrap angular2 component:

I assume that in your main index.html file (with <html> and <body> tags) at the bottom of <body> tag you have:

  <script src="assets/js/jquery-2.1.1.js"></script>
  <script src="assets/js/bootstrap.min.js"></script>

modal.component.ts:

import { Component, Input, Output, ElementRef, EventEmitter, AfterViewInit } from '@angular/core';

declare var $: any;// this is very importnant (to work this line: this.modalEl.modal('show')) - don't do this (becouse this owerride jQuery which was changed by bootstrap, included in main html-body template): let $ = require('../../../../../node_modules/jquery/dist/jquery.min.js');

@Component({
  selector: 'modal',
  templateUrl: './modal.html',
})
export class Modal implements AfterViewInit {

    @Input() title:string;
    @Input() showClose:boolean = true;
    @Output() onClose: EventEmitter<any> = new EventEmitter();

    modalEl = null;
    id: string = uniqueId('modal_');

    constructor(private _rootNode: ElementRef) {}

    open() {
        this.modalEl.modal('show');
    }

    close() {
        this.modalEl.modal('hide');
    }

    closeInternal() { // close modal when click on times button in up-right corner
        this.onClose.next(null); // emit event
        this.close();
    }

    ngAfterViewInit() {
        this.modalEl = $(this._rootNode.nativeElement).find('div.modal');
    }

    has(selector) {
        return $(this._rootNode.nativeElement).find(selector).length;
    }
}

let modal_id: number = 0;
export function uniqueId(prefix: string): string {
    return prefix + ++modal_id;
}

modal.html:

<div class="modal inmodal fade" id="{{modal_id}}" tabindex="-1" role="dialog"  aria-hidden="true" #thisModal>
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header" [ngClass]="{'hide': !(has('mhead') || title) }">
                <button *ngIf="showClose" type="button" class="close" (click)="closeInternal()"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <ng-content select="mhead"></ng-content>
                <h4 *ngIf='title' class="modal-title">{{ title }}</h4>
            </div>
            <div class="modal-body">
                <ng-content></ng-content>
            </div>

            <div class="modal-footer" [ngClass]="{'hide': !has('mfoot') }" >
                <ng-content select="mfoot"></ng-content>
            </div>
        </div>
    </div>
</div>

And example of usage in client Editor component: client-edit-component.ts:

import { Component } from '@angular/core';
import { ClientService } from './client.service';
import { Modal } from '../common';

@Component({
  selector: 'client-edit',
  directives: [ Modal ],
  templateUrl: './client-edit.html',
  providers: [ ClientService ]
})
export class ClientEdit {

    _modal = null;

    constructor(private _ClientService: ClientService) {}

    bindModal(modal) {this._modal=modal;}

    open(client) {
        this._modal.open();
        console.log({client});
    }

    close() {
        this._modal.close();
    }

}

client-edit.html:

<modal [title]='"Some standard title"' [showClose]='true' (onClose)="close()" #editModal>{{ bindModal(editModal) }}
    <mhead>Som non-standart title</mhead>
    Some contents
    <mfoot><button calss='btn' (click)="close()">Close</button></mfoot>
</modal>

Ofcourse title, showClose, <mhead> and <mfoot> ar optional parameters/tags.

What is the difference between a database and a data warehouse?

A data warehouse is a TYPE of database.

In addition to what folks have already said, data warehouses tend to be OLAP, with indexes, etc. tuned for reading, not writing, and the data is de-normalized / transformed into forms that are easier to read & analyze.

Some folks have said "databases" are the same as OLTP -- this isn't true. OLTP, again, is a TYPE of database.

Other types of "databases": Text files, XML, Excel, CSV..., Flat Files :-)

How do I schedule a task to run at periodic intervals?

public void schedule(TimerTask task,long delay)

Schedules the specified task for execution after the specified delay.

you want:

public void schedule(TimerTask task, long delay, long period)

Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals separated by the specified period.

cannot call member function without object

If you want to call them like that, you should declare them static.

CUDA incompatible with my gcc version

I had to install the older versions of gcc, g++.

    sudo apt-get install gcc-4.4
    sudo apt-get install g++-4.4

Check that gcc-4.4 is in /usr/bin/, and same for g++ Then I could use the solution above:

    sudo ln -s /usr/bin/gcc-4.4 /opt/cuda/bin/gcc
    sudo ln -s /usr/bin/g++-4.4 /opt/cuda/bin/g++

How do you display code snippets in MS Word preserving format and syntax highlighting?

If you are using Android Studio, you can simply copy and paste, and the code aspect is going to be preserved and the colors as well. Simple enough!

Change class on mouseover in directive

This is my solution for my scenario:

<div class="btn-group btn-group-justified">
    <a class="btn btn-default" ng-class="{'btn-success': hover.left, 'btn-danger': hover.right}" ng-click="setMatch(-1)" role="button" ng-mouseenter="hover.left = true;" ng-mouseleave="hover.left = false;">
        <i class="fa fa-thumbs-o-up fa-5x pull-left" ng-class="{'fa-rotate-90': !hover.left && !hover.right, 'fa-flip-vertical': hover.right}"></i>
        {{ song.name }}
    </a>
    <a class="btn btn-default" ng-class="{'btn-success': hover.right, 'btn-danger': hover.left}" ng-click="setMatch(1)" role="button" ng-mouseenter="hover.right = true;" ng-mouseleave="hover.right = false;">
        <i class="fa fa-thumbs-o-up fa-5x pull-right" ng-class="{'fa-rotate-270': !hover.left && !hover.right, 'fa-flip-vertical': hover.left}"></i>
        {{ match.name }}
    </a>
</div>

default state: enter image description here

on hover: enter image description here

How to return a value from __init__ in Python?

Sample Usage of the matter in question can be like:

class SampleObject(object):

    def __new__(cls, item):
        if cls.IsValid(item):
            return super(SampleObject, cls).__new__(cls)
        else:
            return None

    def __init__(self, item):
        self.InitData(item) #large amount of data and very complex calculations

...

ValidObjects = []
for i in data:
    item = SampleObject(i)
    if item:             # in case the i data is valid for the sample object
        ValidObjects.append(item)

I do not have enough reputation so I can not write a comment, it is crazy! I wish I could post it as a comment to weronika

"Server Tomcat v7.0 Server at localhost failed to start" without stack trace while it works in terminal

The problem could be annotations in your servlet(s), see if you are using annotations for URL patterns for your servlets.

Try to change the project facet (Dynamic web project ) version to 2.5 and define all your servlet entries in web.xml this should solve the issue.

you can change project facet version in eclipse by changing it in project properties-->search for "facet" in the search box change the Dynamic web project facet version to 2.5

Is there an easy way to convert jquery code to javascript?

This will get you 90% of the way there ; )

window.$ = document.querySelectorAll.bind(document)

For Ajax, the Fetch API is now supported on the current version of every major browser. For $.ready(), DOMContentLoaded has near universal support. You Might Not Need jQuery gives equivalent native methods for other common jQuery functions.

Zepto offers similar functionality but weighs in at 10K zipped. There are custom Ajax builds for jQuery and Zepto as well as some micro frameworks, but jQuery/Zepto have solid support and 10KB is only ~1 second on a 56K modem.

Is there a way to get colored text in GitHubflavored Markdown?

You cannot include style directives in GFM.

The most complete documentation/example is "Markdown Cheatsheet", and it illustrates that this element <style> is missing.

If you manage to include your text in one of the GFM elements, then you can play with a github.css stylesheet in order to colors that way, meaning to color using inline CSS style directives, referring to said css stylesheet.

Making Maven run all tests, even when some fail

A quick answer:

mvn -fn test

Works with nested project builds.

xsd:boolean element type accept "true" but not "True". How can I make it accept it?

xs:boolean is predefined with regard to what kind of input it accepts. If you need something different, you have to define your own enumeration:

 <xs:simpleType name="my:boolean">
    <xs:restriction base="xs:string">
      <xs:enumeration value="True"/>
      <xs:enumeration value="False"/>
    </xs:restriction>
  </xs:simpleType>

PostgreSQL "DESCRIBE TABLE"

You can also check using below query

Select * from schema_name.table_name limit 0;

Expmple : My table has 2 columns name and pwd. Giving screenshot below.

Adding image

*Using PG admin3

SQL Server Management Studio – tips for improving the TSQL coding process

If you need to write a lot of sprocs for an API of some sort. You may like this tools I wrote when I was a programmer. Say you have a 200 columns table that need to have a sproc written to insert/update and another one to delete. Because you don't want your application to directly access the tables. Just the declaration part will be a tedious task but not if a part of the code is written for you. Here's an example...

CREATE PROC upsert_Table1(@col1 int, @col2 varchar(200), @col3 float, etc.)
AS
BEGIN
  UPDATE table1 SET col1 = @col1, col2 = @col2, col3 = @col3, etc.
  IF @@error <> 0
    INSERT Table1 (col1, col2, col3, etc.)
    VALUES(@col1, @col2, @col3, etc.)
END
GO
CREATE PROC delete_Table1(@col1)
AS DELETE FROM Table1 WHERE col1 = @col1

http://snipplr.com/view/13451/spcoldefinition-or-writing-upsert-sp-in-a-snap/

Note : You can also get to the original code and article written in 2002 (I feel old now!)
http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=549&lngWId=5

if (select count(column) from table) > 0 then

not so elegant but you dont need to declare any variable:

for k in (select max(1) from table where 1 = 1) loop
    update x where column = value;
end loop;

How to make an image center (vertically & horizontally) inside a bigger div

https://www.w3.org/Style/Examples/007/center.en.html

IMG.displayed {
  display: block;
  margin-left: auto;
  margin-right: auto 
}

<IMG class="displayed" src="..." alt="...">

Why does .NET foreach loop throw NullRefException when collection is null?

A foreach loop calls the GetEnumerator method.
If the collection is null, this method call results in a NullReferenceException.

It is bad practice to return a null collection; your methods should return an empty collection instead.

set div height using jquery (stretch div height)

Off the top of my head:

$('#content').height(
    $(window).height() - $('#header').height() - $('#footer').height()
);

Is that what you mean?

How do you count the elements of an array in java

Java doesn't have the concept of a "count" of the used elements in an array.

To get this, Java uses an ArrayList. The List is implemented on top of an array which gets resized whenever the JVM decides it's not big enough (or sometimes when it is too big).

To get the count, you use mylist.size() to ensure a capacity (the underlying array backing) you use mylist.ensureCapacity(20). To get rid of the extra capacity, you use mylist.trimToSize().

How is a JavaScript hash map implemented?

JavaScript objects cannot be implemented purely on top of hash maps.

Try this in your browser console:

var foo = {
    a: true,
    b: true,
    z: true,
    c: true
}

for (var i in foo) {
    console.log(i);
}

...and you'll recieve them back in insertion order, which is de facto standard behaviour.

Hash maps inherently do not maintain ordering, so JavaScript implementations may use hash maps somehow, but if they do, it'll require at least a separate index and some extra book-keeping for insertions.

Here's a video of Lars Bak explaining why v8 doesn't use hash maps to implement objects.

Regex match text between tags

Use match instead, and the g flag.

str.match(/<b>(.*?)<\/b>/g);

How should I edit an Entity Framework connection string?

Open .edmx file any text editor change the Schema="your required schema" and also open the app.config/web.config, change the user id and password from the connection string. you are done.

How can I show data using a modal when clicking a table row (using bootstrap)?

One thing you can do is get rid of all those onclick attributes and do it the right way with bootstrap. You don't need to open them manually; you can specify the trigger and even subscribe to events before the modal opens so that you can do your operations and populate data in it.

I am just going to show as a static example which you can accommodate in your real world.

On each of your <tr>'s add a data attribute for id (i.e. data-id) with the corresponding id value and specify a data-target, which is a selector you specify, so that when clicked, bootstrap will select that element as modal dialog and show it. And then you need to add another attribute data-toggle=modal to make this a trigger for modal.

  <tr data-toggle="modal" data-id="1" data-target="#orderModal">
            <td>1</td>
            <td>24234234</td>
            <td>A</td>
  </tr>
  <tr data-toggle="modal" data-id="2" data-target="#orderModal">
            <td>2</td>
            <td>24234234</td>
            <td>A</td>
        </tr>
  <tr data-toggle="modal" data-id="3" data-target="#orderModal">
            <td>3</td>
            <td>24234234</td>
            <td>A</td>
  </tr>

And now in the javascript just set up the modal just once and event listen to its events so you can do your work.

$(function(){
    $('#orderModal').modal({
        keyboard: true,
        backdrop: "static",
        show:false,

    }).on('show', function(){ //subscribe to show method
          var getIdFromRow = $(event.target).closest('tr').data('id'); //get the id from tr
        //make your ajax call populate items or what even you need
        $(this).find('#orderDetails').html($('<b> Order Id selected: ' + getIdFromRow  + '</b>'))
    });
});

Demo

Do not use inline click attributes any more. Use event bindings instead with vanilla js or using jquery.

Alternative ways here:

Demo2 or Demo3

jQuery Validate - Enable validation for hidden fields

So I'm going to go a bit deeper in to why this doesn't work because I'm the kind of person that can't sleep at night without knowing haha. I'm using jQuery validate 1.10 and Microsoft jQuery Unobtrusive Validation 2.0.20710.0 which was published on 1/29/2013.

I started by searching for the setDefaults method in jQuery Validate and found it on line 261 of the unminified file. All this function really does is merge your json settings in to the existing $.validator.defaults which are initialized with the ignore property being set to ":hidden" along with the other defaults defined in jQuery Validate. So at this point we've overridden ignore. Now let's see where this defaults property is being referenced at.

When I traced through the code to see where $.validator.defaults is being referenced. I noticed that is was only being used by the constructor for a form validator, line 170 in jQuery validate unminified file.

// constructor for validator
$.validator = function( options, form ) {
    this.settings = $.extend( true, {}, $.validator.defaults, options );
    this.currentForm = form;
    this.init();
};

At this point a validator will merge any default settings that were set and attach it to the form validator. When you look at the code that is doing the validating, highlighting, unhighlighting, etc they all use the validator.settings object to pull the ignore property. So we need to make sure if we are to set the ignore with the setDefaults method then it has to occur before the $("form").validate() is called.

If you're using Asp.net MVC and the unobtrusive plugin, then you'll realize after looking at the javascript that validate is called in document.ready. I've also called my setDefaults in the document.ready block which is going to execute after the scripts, jquery validate and unobtrusive because I've defined those scripts in the html before the one that has the call in it. So my call obviously had no impact on the default functionality of skipping hidden elements during validation. There is a couple of options here.

Option 1 - You could as Juan Mellado pointed out have the call outside of the document.ready which would execute as soon as the script has been loaded. I'm not sure about the timing of this since browsers are now capable of doing parallel script loading. If I'm just being over cautious then please correct me. Also, there's probably ways around this but for my needs I did not go down this path.

Option 2a - The safe bet in my eyes is to just replace the $.validator.setDefaults({ ignore: '' }); inside of the document.ready event with $("form").data("validator").settings.ignore = "";. This will modify the ignore property that is actually used by jQuery validate when doing each validation on your elements for the given form.

Options 2b - After looking in to the code a bit more you could also use $("form").validate().settings.ignore = ""; as a way of setting the ignore property. The reason is that when looking at the validate function it checks to see if a validator object has already been stored for the form element via the $.data() function. If it finds a validator object stored with the form element then it just returns the validator object instead of creating another one.

JQuery .hasClass for multiple values in an if statement

Here is a slight variation on answer offered by jfriend00:

$.fn.hasAnyClass = function() {
    var classes = arguments[0].split(" ");
    for (var i = 0; i < classes.length; i++) {
        if (this.hasClass(classes[i])) {
            return true;
        }
    }
    return false;
}

Allows use of same syntax as .addClass() and .removeClass(). e.g., .hasAnyClass('m320 m768') Needs bulletproofing, of course, as it assumes at least one argument.

error: No resource identifier found for attribute 'adSize' in package 'com.google.example' main.xml

You can also use http://schemas.android.com/apk/res-auto that would take care of it automatically. Use it like this:

xmlns:ads="http://schemas.android.com/apk/res-auto"

CSS text-decoration underline color

You can do it if you wrap your text into a span like:

_x000D_
_x000D_
a {_x000D_
  color: red;_x000D_
  text-decoration: underline;_x000D_
}_x000D_
span {_x000D_
  color: blue;_x000D_
  text-decoration: none;_x000D_
}
_x000D_
<a href="#">_x000D_
  <span>Text</span>_x000D_
</a>
_x000D_
_x000D_
_x000D_

How to import an existing X.509 certificate and private key in Java keystore to use in SSL?

And one more:

#!/bin/bash

# We have:
#
# 1) $KEY : Secret key in PEM format ("-----BEGIN RSA PRIVATE KEY-----") 
# 2) $LEAFCERT : Certificate for secret key obtained from some
#    certification outfit, also in PEM format ("-----BEGIN CERTIFICATE-----")   
# 3) $CHAINCERT : Intermediate certificate linking $LEAFCERT to a trusted
#    Self-Signed Root CA Certificate 
#
# We want to create a fresh Java "keystore" $TARGET_KEYSTORE with the
# password $TARGET_STOREPW, to be used by Tomcat for HTTPS Connector.
#
# The keystore must contain: $KEY, $LEAFCERT, $CHAINCERT
# The Self-Signed Root CA Certificate is obtained by Tomcat from the
# JDK's truststore in /etc/pki/java/cacerts

# The non-APR HTTPS connector (APR uses OpenSSL-like configuration, much
# easier than this) in server.xml looks like this 
# (See: https://tomcat.apache.org/tomcat-6.0-doc/ssl-howto.html):
#
#  <Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol"
#                SSLEnabled="true"
#                maxThreads="150" scheme="https" secure="true"
#                clientAuth="false" sslProtocol="TLS"
#                keystoreFile="/etc/tomcat6/etl-web.keystore.jks"
#                keystorePass="changeit" />
#

# Let's roll:    

TARGET_KEYSTORE=/etc/tomcat6/foo-server.keystore.jks
TARGET_STOREPW=changeit

TLS=/etc/pki/tls

KEY=$TLS/private/httpd/foo-server.example.com.key
LEAFCERT=$TLS/certs/httpd/foo-server.example.com.pem
CHAINCERT=$TLS/certs/httpd/chain.cert.pem

# ----
# Create PKCS#12 file to import using keytool later
# ----

# From https://www.sslshopper.com/ssl-converter.html:
# The PKCS#12 or PFX format is a binary format for storing the server certificate,
# any intermediate certificates, and the private key in one encryptable file. PFX
# files usually have extensions such as .pfx and .p12. PFX files are typically used 
# on Windows machines to import and export certificates and private keys.

TMPPW=$$ # Some random password

PKCS12FILE=`mktemp`

if [[ $? != 0 ]]; then
  echo "Creation of temporary PKCS12 file failed -- exiting" >&2; exit 1
fi

TRANSITFILE=`mktemp`

if [[ $? != 0 ]]; then
  echo "Creation of temporary transit file failed -- exiting" >&2; exit 1
fi

cat "$KEY" "$LEAFCERT" > "$TRANSITFILE"

openssl pkcs12 -export -passout "pass:$TMPPW" -in "$TRANSITFILE" -name etl-web > "$PKCS12FILE"

/bin/rm "$TRANSITFILE"

# Print out result for fun! Bug in doc (I think): "-pass " arg does not work, need "-passin"

openssl pkcs12 -passin "pass:$TMPPW" -passout "pass:$TMPPW" -in "$PKCS12FILE" -info

# ----
# Import contents of PKCS12FILE into a Java keystore. WTF, Sun, what were you thinking?
# ----

if [[ -f "$TARGET_KEYSTORE" ]]; then
  /bin/rm "$TARGET_KEYSTORE"
fi

keytool -importkeystore \
   -deststorepass  "$TARGET_STOREPW" \
   -destkeypass    "$TARGET_STOREPW" \
   -destkeystore   "$TARGET_KEYSTORE" \
   -srckeystore    "$PKCS12FILE" \
   -srcstoretype  PKCS12 \
   -srcstorepass  "$TMPPW" \
   -alias foo-the-server

/bin/rm "$PKCS12FILE"

# ----
# Import the chain certificate. This works empirically, it is not at all clear from the doc whether this is correct
# ----

echo "Importing chain"

TT=-trustcacerts

keytool -import $TT -storepass "$TARGET_STOREPW" -file "$CHAINCERT" -keystore "$TARGET_KEYSTORE" -alias chain

# ----
# Print contents
# ----

echo "Listing result"

keytool -list -storepass "$TARGET_STOREPW" -keystore "$TARGET_KEYSTORE"

Apache VirtualHost 403 Forbidden

Apache 2.4.3 (or maybe slightly earlier) added a new security feature that often results in this error. You would also see a log message of the form "client denied by server configuration". The feature is requiring a user identity to access a directory. It is turned on by DEFAULT in the httpd.conf that ships with Apache. You can see the enabling of the feature with the directive

Require all denied

This basically says to deny access to all users. To fix this problem, either remove the denied directive (or much better) add the following directive to the directories you want to grant access to:

Require all granted

as in

<Directory "your directory here">
   Order allow,deny
   Allow from all
   # New directive needed in Apache 2.4.3: 
   Require all granted
</Directory>

Node.js, can't open files. Error: ENOENT, stat './path/to/file'

Paths specified with a . are relative to the current working directory, not relative to the script file. So the file might be found if you run node app.js but not if you run node folder/app.js. The only exception to this is require('./file') and that is only possible because require exists per-module and thus knows what module it is being called from.

To make a path relative to the script, you must use the __dirname variable.

var path = require('path');

path.join(__dirname, 'path/to/file')

or potentially

path.join(__dirname, 'path', 'to', 'file')

Make a VStack fill the width of the screen in SwiftUI

 var body: some View {
      VStack {
           CarouselView().edgesIgnoringSafeArea(.all)           
           List {
                ForEach(viewModel.parents) { k in
                    VideosRowView(parent: k)
                }
           }
    }
 }

How to use std::sort to sort an array in C++

sorting method without std::sort:

// sorting myArray ascending
int iTemp = 0;
for (int i = 0; i < ARRAYSIZE; i++)
{
    for (int j = i + 1; j <= ARRAYSIZE; j++)
    {
        // for descending sort change '<' with '>'
        if (myArray[j] < myArray[i])
        {
            iTemp = myArray[i];
            myArray[i] = myArray[j];
            myArray[j] = iTemp;
        }
    }
}

Run complete example:

#include <iostream> // std::cout, std::endl /* http://en.cppreference.com/w/cpp/header/iostream */
#include <cstdlib>  // srand(), rand()      /* http://en.cppreference.com/w/cpp/header/cstdlib */
#include <ctime>    // time()               /* http://en.cppreference.com/w/cpp/header/ctime */


int main()
{
    const int ARRAYSIZE = 10;
    int myArray[ARRAYSIZE];

    // populate myArray with random numbers from 1 to 1000
    srand(time(0));
    for (int i = 0; i < ARRAYSIZE; i++)
    {
        myArray[i] = rand()% 1000 + 1;
    }

    // print unsorted myArray
    std::cout << "unsorted myArray: " << std::endl;
    for (int i = 0; i < ARRAYSIZE; i++)
    {
        std::cout << "[" << i << "] -> " << myArray[i] << std::endl;
    }
    std::cout << std::endl;

    // sorting myArray ascending
    int iTemp = 0;
    for (int i = 0; i < ARRAYSIZE; i++)
    {
        for (int j = i + 1; j <= ARRAYSIZE; j++)
        {
            // for descending sort change '<' with '>'
            if (myArray[j] < myArray[i])
            {
                iTemp = myArray[i];
                myArray[i] = myArray[j];
                myArray[j] = iTemp;
            }
        }
    }

    // print sorted myArray
    std::cout << "sorted myArray: " << std::endl;
    for (int i = 0; i < ARRAYSIZE; i++)
    {
        std::cout << "[" << i << "] -> " << myArray[i] << std::endl;
    }
    std::cout << std::endl;

    return 0;
}

How to create large PDF files (10MB, 50MB, 100MB, 200MB, 500MB, 1GB, etc.) for testing purposes?

For those using macOS mkfile might be a good alternative to fallocate or dd

mkfile 100m some100mfile.pdf

reference - https://stackoverflow.com/a/33478049/711401

XDocument or XmlDocument

XDocument is from the LINQ to XML API, and XmlDocument is the standard DOM-style API for XML. If you know DOM well, and don't want to learn LINQ to XML, go with XmlDocument. If you're new to both, check out this page that compares the two, and pick which one you like the looks of better.

I've just started using LINQ to XML, and I love the way you create an XML document using functional construction. It's really nice. DOM is clunky in comparison.

Fitting a Normal distribution to 1D data

You can use matplotlib to plot the histogram and the PDF (as in the link in @MrE's answer). For fitting and for computing the PDF, you can use scipy.stats.norm, as follows.

import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt


# Generate some data for this demonstration.
data = norm.rvs(10.0, 2.5, size=500)

# Fit a normal distribution to the data:
mu, std = norm.fit(data)

# Plot the histogram.
plt.hist(data, bins=25, density=True, alpha=0.6, color='g')

# Plot the PDF.
xmin, xmax = plt.xlim()
x = np.linspace(xmin, xmax, 100)
p = norm.pdf(x, mu, std)
plt.plot(x, p, 'k', linewidth=2)
title = "Fit results: mu = %.2f,  std = %.2f" % (mu, std)
plt.title(title)

plt.show()

Here's the plot generated by the script:

Plot

Importing files from different folder

The code below imports the Python script given by it's path, no matter where it is located, in a Python version-save way:

def import_module_by_path(path):
    name = os.path.splitext(os.path.basename(path))[0]
    if sys.version_info[0] == 2:   
        # Python 2
        import imp
        return imp.load_source(name, path)
    elif sys.version_info[:2] <= (3, 4):  
        # Python 3, version <= 3.4
        from importlib.machinery import SourceFileLoader
        return SourceFileLoader(name, path).load_module()
    else:                            
        # Python 3, after 3.4
        import importlib.util
        spec = importlib.util.spec_from_file_location(name, path)
        mod = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(mod)
        return mod

This code is not written by me; I found it in the codebase of psutils, in psutils.test.__init__.py (line 1042; permalink to most recent commit as of 09.10.2020).

Usage example:

script = "/home/username/Documents/some_script.py"
some_module = import_module_by_path(script)
print(some_module.foo())

Caveat: The module will be treated as top-level. If it's a submodule of some bigger project, then relative imports from parent packages will fail.

IE8 issue with Twitter Bootstrap 3

I faced the same problem, tried the first answer but something was missing.

If you guys are using Webpack, your css will be loaded as a style tag which is not supported by respond.js, it needs a file, so make sure bootstrap is loaded as a css file

Personally I used extract-text-webpack-plugin

const webpack = require("webpack")
const ExtractTextPlugin = require("extract-text-webpack-plugin")
const path = require("path")

module.exports = {
    context: __dirname+"/src",
    entry: "./index.js",
    output: {
        filename: "./dist/bundle.js",
        path: __dirname
    },
    plugins: [
        ...,
        new ExtractTextPlugin("./dist/bootstrap.css", {
            allChunks: true
        })
    ],
    module: {
        loaders: [
            ...,
            // your css loader excluding bootstrap
            {
                test: /\.css$/,
                loader: "style!css",
                exclude: [
                    path.resolve(__dirname, "node_modules/bootstrap/dist/css/bootstrap.css")
                ]
            },

            {
                // loads bootstrap as a file, change path accordingly if needs be, path needs to be absolute
                include: [
                    path.resolve(__dirname, "node_modules/bootstrap/dist/css/bootstrap.css")
                ],
                loader: ExtractTextPlugin.extract("style-loader", "css-loader?minimize")
            }
        ]
    }
}

Hope it will help you

WPF Button with Image

You can create a custom control that inherits from the Button class. This code will be more reusable, please look at the following blog post for more details: WPF - create custom button with image (ImageButton)

Using this control:

<local:ImageButton Width="200" Height="50" Content="Click Me!"
    ImageSource="ok.png" ImageLocation="Left" ImageWidth="20" ImageHeight="25" />

ImageButton.cs file:

public class ImageButton : Button
{
   static ImageButton()
   {
       DefaultStyleKeyProperty.OverrideMetadata(typeof(ImageButton), new FrameworkPropertyMetadata(typeof(ImageButton)));
   }

   public ImageButton()
   {
       this.SetCurrentValue(ImageButton.ImageLocationProperty, WpfImageButton.ImageLocation.Left);
   }

   public int ImageWidth
   {
       get { return (int)GetValue(ImageWidthProperty); }
       set { SetValue(ImageWidthProperty, value); }
   }

   public static readonly DependencyProperty ImageWidthProperty =
       DependencyProperty.Register("ImageWidth", typeof(int), typeof(ImageButton), new PropertyMetadata(30));

   public int ImageHeight
   {
       get { return (int)GetValue(ImageHeightProperty); }
       set { SetValue(ImageHeightProperty, value); }
   }

   public static readonly DependencyProperty ImageHeightProperty =
       DependencyProperty.Register("ImageHeight", typeof(int), typeof(ImageButton), new PropertyMetadata(30));

   public ImageLocation? ImageLocation
   {
       get { return (ImageLocation)GetValue(ImageLocationProperty); }
       set { SetValue(ImageLocationProperty, value); }
   }

   public static readonly DependencyProperty ImageLocationProperty =
       DependencyProperty.Register("ImageLocation", typeof(ImageLocation?), typeof(ImageButton), new PropertyMetadata(null, PropertyChangedCallback));

   private static void PropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
   {
       var imageButton = (ImageButton)d;
       var newLocation = (ImageLocation?) e.NewValue ?? WpfImageButton.ImageLocation.Left;

       switch (newLocation)
       {
           case WpfImageButton.ImageLocation.Left:
               imageButton.SetCurrentValue(ImageButton.RowIndexProperty, 1);
               imageButton.SetCurrentValue(ImageButton.ColumnIndexProperty, 0);
               break;
           case WpfImageButton.ImageLocation.Top:
               imageButton.SetCurrentValue(ImageButton.RowIndexProperty, 0);
               imageButton.SetCurrentValue(ImageButton.ColumnIndexProperty, 1);
               break;
           case WpfImageButton.ImageLocation.Right:
               imageButton.SetCurrentValue(ImageButton.RowIndexProperty, 1);
               imageButton.SetCurrentValue(ImageButton.ColumnIndexProperty, 2);
               break;
           case WpfImageButton.ImageLocation.Bottom:
               imageButton.SetCurrentValue(ImageButton.RowIndexProperty, 2);
               imageButton.SetCurrentValue(ImageButton.ColumnIndexProperty, 1);
               break;
           case WpfImageButton.ImageLocation.Center:
               imageButton.SetCurrentValue(ImageButton.RowIndexProperty, 1);
               imageButton.SetCurrentValue(ImageButton.ColumnIndexProperty, 1);
               break;
           default:
               throw new ArgumentOutOfRangeException();
       }
   }

   public ImageSource ImageSource
   {
       get { return (ImageSource)GetValue(ImageSourceProperty); }
       set { SetValue(ImageSourceProperty, value); }
   }

   public static readonly DependencyProperty ImageSourceProperty =
       DependencyProperty.Register("ImageSource", typeof(ImageSource), typeof(ImageButton), new PropertyMetadata(null));

   public int RowIndex
   {
       get { return (int)GetValue(RowIndexProperty); }
       set { SetValue(RowIndexProperty, value); }
   }

   public static readonly DependencyProperty RowIndexProperty =
       DependencyProperty.Register("RowIndex", typeof(int), typeof(ImageButton), new PropertyMetadata(0));

   public int ColumnIndex
   {
       get { return (int)GetValue(ColumnIndexProperty); }
       set { SetValue(ColumnIndexProperty, value); }
   }

   public static readonly DependencyProperty ColumnIndexProperty =
       DependencyProperty.Register("ColumnIndex", typeof(int), typeof(ImageButton), new PropertyMetadata(0));
}

public enum ImageLocation
{
   Left,
   Top,
   Right,
   Bottom,
   Center
}

Generic.xaml file:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfImageButton">
    <Style TargetType="{x:Type local:ImageButton}" BasedOn="{StaticResource {x:Type Button}}">
        <Setter Property="ContentTemplate">
            <Setter.Value>
                <DataTemplate>
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition Height="*"/>
                            <RowDefinition Height="Auto"/>
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="Auto"/>
                        </Grid.ColumnDefinitions>
                        <Image Source="{Binding ImageSource, RelativeSource={RelativeSource AncestorType=local:ImageButton}}"
                               Width="{Binding ImageWidth, RelativeSource={RelativeSource AncestorType=local:ImageButton}}"
                               Height="{Binding ImageHeight, RelativeSource={RelativeSource AncestorType=local:ImageButton}}"
                               Grid.Row="{Binding RowIndex, RelativeSource={RelativeSource AncestorType=local:ImageButton}}"
                               Grid.Column="{Binding ColumnIndex, RelativeSource={RelativeSource AncestorType=local:ImageButton}}"
                               VerticalAlignment="Center" HorizontalAlignment="Center"></Image>
                        <ContentPresenter Grid.Row="1" Grid.Column="1" Content="{TemplateBinding Content}"
                                          VerticalAlignment="Center" HorizontalAlignment="Center"></ContentPresenter>
                    </Grid>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>