Programs & Examples On #Downsize

Bootstrap Carousel Full Screen

This is how I did it. This makes the images in the slideshow take up the full screen if it´s aspect ratio allows it, othervice it scales down.

.carousel {
    height: 100vh;
    width: 100%;
    overflow:hidden;
}
.carousel .carousel-inner {
    height:100%;    
}

To allways get a full screen slideshow, no matter screen aspect ratio, you can also use object-fit: (doesn´t work in IE or Edge)

.carousel .carousel-inner img {
    display:block;
    object-fit: cover;
}

Resizing an image in an HTML5 canvas

So something interesting that I found a while ago while working with canvas that might be helpful:

To resize the canvas control on its own, you need to use the height="" and width="" attributes (or canvas.width/canvas.height elements). If you use CSS to resize the canvas, it will actually stretch (i.e.: resize) the content of the canvas to fit the full canvas (rather than simply increasing or decreasing the area of the canvas.

It'd be worth a shot to try drawing the image into a canvas control with the height and width attributes set to the size of the image and then using CSS to resize the canvas to the size you're looking for. Perhaps this would use a different resizing algorithm.

It should also be noted that canvas has different effects in different browsers (and even different versions of different browsers). The algorithms and techniques used in the browsers is likely to change over time (especially with Firefox 4 and Chrome 6 coming out so soon, which will place heavy emphasis on canvas rendering performance).

In addition, you may want to give SVG a shot, too, as it likely uses a different algorithm as well.

Best of luck!

Where to get this Java.exe file for a SQL Developer installation

If you are asked to enter the full pathname for the JDK, click Browse and find it. For example, on a Windows system the path might have a name similar to C:\Program Files\Java\jdk1.7.0_51.

How to read and write excel file

String path="C:\\Book2.xlsx";
try {

        File f = new File( path );
        Workbook wb = WorkbookFactory.create(f);
        Sheet mySheet = wb.getSheetAt(0);
        Iterator<Row> rowIter = mySheet.rowIterator();
        for ( Iterator<Row> rowIterator = mySheet.rowIterator() ;rowIterator.hasNext(); )
        {
            for (  Iterator<Cell> cellIterator = ((Row)rowIterator.next()).cellIterator() ; cellIterator.hasNext() ;  ) 
            {
                System.out.println ( ( (Cell)cellIterator.next() ).toString() );
            }
            System.out.println( " **************************************************************** ");
        }
    } catch ( Exception e )
    {
        System.out.println( "exception" );
        e.printStackTrace();
    }

and make sure to have added the jars poi and poi-ooxml (org.apache.poi) to your project

How to use OUTPUT parameter in Stored Procedure

SqlCommand yourCommand = new SqlCommand();
yourCommand.Connection = yourSqlConn;
yourCommand.Parameters.Add("@yourParam");
yourCommand.Parameters["@yourParam"].Direction = ParameterDirection.Output;

// execute your query successfully

int yourResult = yourCommand.Parameters["@yourParam"].Value;

How do I keep jQuery UI Accordion collapsed by default?

Add the active: false option (documentation)..

$("#accordion").accordion({ header: "h3", collapsible: true, active: false });

Get IFrame's document, from JavaScript in main document

You should be able to access the document in the IFRAME using the following code:

document.getElementById('myframe').contentWindow.document

However, you will not be able to do this if the page in the frame is loaded from a different domain (such as google.com). THis is because of the browser's Same Origin Policy.

How can I check if a background image is loaded?

I've located a solution that worked better for me, and which has the advantage of being usable with several images (case not illustrated in this example).

From @adeneo's answer on this question :

If you have an element with a background image, like this

<div id="test" style="background-image: url(link/to/image.png)"><div>

You can wait for the background to load by getting the image URL and using it for an image object in javascript with an onload handler

var src = $('#test').css('background-image');
var url = src.match(/\((.*?)\)/)[1].replace(/('|")/g,'');

var img = new Image();
img.onload = function() {
    alert('image loaded');
}
img.src = url;
if (img.complete) img.onload();

Create hyperlink to another sheet

I recorded a macro making a hiperlink. This resulted.

ActiveCell.FormulaR1C1 = "=HYPERLINK(""[Workbook.xlsx]Sheet1!A1"",""CLICK HERE"")"

How to use MySQL DECIMAL?

MySQL 5.x specification for decimal datatype is: DECIMAL[(M[,D])] [UNSIGNED] [ZEROFILL]. The answer above is wrong (now corrected) in saying that unsigned decimals are not possible.

To define a field allowing only unsigned decimals, with a total length of 6 digits, 4 of which are decimals, you would use: DECIMAL (6,4) UNSIGNED.

You can likewise create unsigned (ie. not negative) FLOAT and DOUBLE datatypes.


Update on MySQL 8.0.17+, as in MySQL 8 Manual: 11.1.1 Numeric Data Type Syntax:

"Numeric data types that permit the UNSIGNED attribute also permit SIGNED. However, these data types are signed by default, so the SIGNED attribute has no effect.*

As of MySQL 8.0.17, the UNSIGNED attribute is deprecated for columns of type FLOAT, DOUBLE, and DECIMAL (and any synonyms); you should expect support for it to be removed in a future version of MySQL. Consider using a simple CHECK constraint instead for such columns.

Switch android x86 screen resolution

In VirtualBox you should add custom resolution via the command:

VBoxManage setextradata "VM name" "CustomVideoMode1" "800x480x16"

instead of editing a .vbox file.

This solution works fine for me!

How do I get cURL to not show the progress bar?

this could help..

curl 'http://example.com' > /dev/null

php delete a single file in directory

<?php 
    if(isset($_GET['delete'])){
        $delurl=$_GET['delete'];
        unlink($delurl);
    }
?>
<?php
if ($handle = opendir('.')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            echo "<a href=\"$entry\">$entry</a> | <a href=\"?delete=$entry\">Delete</a><br>";
        }
    }
    closedir($handle);
}
?>

This is It

multi line comment vb.net in Visual studio 2010

multi comment in vb.net

VB.NET doesn't support for multi line comment.

The only way to do multi-line comments in VB.NET is to do a lot of single line comments(').

Or just highlight the whole code and just use (Ctrl+E,C), (Ctrl+E,U) to comment or uncomment.

Only in c# /* */

Or in ASP.NET html source using <!-- -->.

Video streaming over websockets using JavaScript

It's definitely conceivable but I am not sure we're there yet. In the meantime, I'd recommend using something like Silverlight with IIS Smooth Streaming. Silverlight is plugin-based, but it works on Windows/OSX/Linux. Some day the HTML5 <video> element will be the way to go, but that will lack support for a little while.

Using filesystem in node.js with async / await

Node.js 8.0.0

Native async / await

Promisify

From this version, you can use native Node.js function from util library.

const fs = require('fs')
const { promisify } = require('util')

const readFileAsync = promisify(fs.readFile)
const writeFileAsync = promisify(fs.writeFile)

const run = async () => {
  const res = await readFileAsync('./data.json')
  console.log(res)
}

run()


Promise Wrapping

const fs = require('fs')

const readFile = (path, opts = 'utf8') =>
  new Promise((resolve, reject) => {
    fs.readFile(path, opts, (err, data) => {
      if (err) reject(err)
      else resolve(data)
    })
  })

const writeFile = (path, data, opts = 'utf8') =>
  new Promise((resolve, reject) => {
    fs.writeFile(path, data, opts, (err) => {
      if (err) reject(err)
      else resolve()
    })
  })

module.exports = {
  readFile,
  writeFile
}

...


// in some file, with imported functions above
// in async block
const run = async () => {
  const res = await readFile('./data.json')
  console.log(res)
}

run()

Advice

Always use try..catch for await blocks, if you don't want to rethrow exception upper.

jquery $('.class').each() how many items?

If you're using chained syntax:

$(".class").each(function() {
    // ...
});

...I don't think there's any (reasonable) way for the code within the each function to know how many items there are. (Unreasonable ways would involve repeating the selector and using index.)

But it's easy enough to make the collection available to the function that you're calling in each. Here's one way to do that:

var collection = $(".class");
collection.each(function() {
    // You can access `collection.length` here.
});

As a somewhat convoluted option, you could convert your jQuery object to an array and then use the array's forEach. The arguments that get passed to forEach's callback are the entry being visited (what jQuery gives you as this and as the second argument), the index of that entry, and the array you called it on:

$(".class").get().forEach(function(entry, index, array) {
    // Here, array.length is the total number of items
});

That assumes an at least vaguely modern JavaScript engine and/or a shim for Array#forEach.

Or for that matter, give yourself a new tool:

// Loop through the jQuery set calling the callback:
//    loop(callback, thisArg);
// Callback gets called with `this` set to `thisArg` unless `thisArg`
// is falsey, in which case `this` will be the element being visited.
// Arguments to callback are `element`, `index`, and `set`, where
// `element` is the element being visited, `index` is its index in the
// set, and `set` is the jQuery set `loop` was called on.
// Callback's return value is ignored unless it's `=== false`, in which case
// it stops the loop.
$.fn.loop = function(callback, thisArg) {
    var me = this;
    return this.each(function(index, element) {
        return callback.call(thisArg || element, element, index, me);
    });
};

Usage:

$(".class").loop(function(element, index, set) {
    // Here, set.length is the length of the set
});

Configuration System Failed to Initialize

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="xyz" value="123" />    
  </appSettings>
</configuration>

Getting ssh to execute a command in the background on target machine

YOUR-COMMAND &> YOUR-LOG.log &    

This should run the command and assign a process id you can simply tail -f YOUR-LOG.log to see results written to it as they happen. you can log out anytime and the process will carry on

How to put sshpass command inside a bash script?

Try the "-o StrictHostKeyChecking=no" option to ssh("-o" being the flag that tells ssh that your are going to use an option). This accepts any incoming RSA key from your ssh connection, even if the key is not in the "known host" list.

sshpass -p 'password' ssh -o StrictHostKeyChecking=no user@host 'command'

How to read data from excel file using c#

Convert the excel file to .csv file (comma separated value file) and now you can easily be able to read it.

Dealing with commas in a CSV file

If you feel like reinventing the wheel, the following may work for you:

public static IEnumerable<string> SplitCSV(string line)
{
    var s = new StringBuilder();
    bool escaped = false, inQuotes = false;
    foreach (char c in line)
    {
        if (c == ',' && !inQuotes)
        {
            yield return s.ToString();
            s.Clear();
        }
        else if (c == '\\' && !escaped)
        {
            escaped = true;
        }
        else if (c == '"' && !escaped)
        {
            inQuotes = !inQuotes;
        }
        else
        {
            escaped = false;
            s.Append(c);
        }
    }
    yield return s.ToString();
}

Errors in pom.xml with dependencies (Missing artifact...)

This is a very late answer,but this might help.I went to this link and searched for ojdbc8(I was trying to add jdbc oracle driver) When clicked on the result , a note was displayed like this:

enter image description here

I clicked the link in the note and the correct dependency was mentioned like below enter image description here

Get the (last part of) current directory name in C#

Try this:

String newString = "";
Sting oldString = "/Users/smcho/filegen_from_directory/AIRPassthrough";

int indexOfLastSlash = oldString.LastIndexOf('/', 0, oldString.length());

newString = oldString.subString(indexOfLastSlash, oldString.length());

Code may be off (I haven't tested it) but the idea should work

Combine two pandas Data Frames (join on a common column)

In case anyone needs to try and merge two dataframes together on the index (instead of another column), this also works!

T1 and T2 are dataframes that have the same indices

import pandas as pd
T1 = pd.merge(T1, T2, on=T1.index, how='outer')

P.S. I had to use merge because append would fill NaNs in unnecessarily.

How do I skip a header from CSV files in Spark?

It's an option that you pass to the read() command:

context = new org.apache.spark.sql.SQLContext(sc)

var data = context.read.option("header","true").csv("<path>")

How can I debug git/git-shell related problems?

Debugging

Git has a fairly complete set of traces embedded which you can use to debug your git problems.

To turn them on, you can define the following variables:

  • GIT_TRACE for general traces,
  • GIT_TRACE_PACK_ACCESS for tracing of packfile access,
  • GIT_TRACE_PACKET for packet-level tracing for network operations,
  • GIT_TRACE_PERFORMANCE for logging the performance data,
  • GIT_TRACE_SETUP for information about discovering the repository and environment it’s interacting with,
  • GIT_MERGE_VERBOSITY for debugging recursive merge strategy (values: 0-5),
  • GIT_CURL_VERBOSE for logging all curl messages (equivalent to curl -v),
  • GIT_TRACE_SHALLOW for debugging fetching/cloning of shallow repositories.

Possible values can include:

  • true, 1 or 2 to write to stderr,
  • an absolute path starting with / to trace output to the specified file.

For more details, see: Git Internals - Environment Variables


SSH

For SSH issues, try the following commands:

echo 'ssh -vvv "$*"' > ssh && chmod +x ssh
GIT_SSH="$PWD/ssh" git pull origin master

or use ssh to validate your credentials, e.g.

ssh -vvvT [email protected]

or over HTTPS port:

ssh -vvvT -p 443 [email protected]

Note: Reduce number of -v to reduce the verbosity level.


Examples

$ GIT_TRACE=1 git status
20:11:39.565701 git.c:350               trace: built-in: git 'status'

$ GIT_TRACE_PERFORMANCE=$PWD/gc.log git gc
Counting objects: 143760, done.
...
$ head gc.log 
20:12:37.214410 trace.c:420             performance: 0.090286000 s: git command: 'git' 'pack-refs' '--all' '--prune'
20:12:37.378101 trace.c:420             performance: 0.156971000 s: git command: 'git' 'reflog' 'expire' '--all'
...

$ GIT_TRACE_PACKET=true git pull origin master
20:16:53.062183 pkt-line.c:80           packet:        fetch< 93eb028c6b2f8b1d694d1173a4ddf32b48e371ce HEAD\0multi_ack thin-pack side-band side-band-64k ofs-delta shallow no-progress include-tag multi_ack_detailed symref=HEAD:refs/heads/master agent=git/2:2.6.5~update-ref-initial-update-1494-g76b680d
...

How do I concatenate strings with variables in PowerShell?

You could use the PowerShell equivalent of String.Format - it's usually the easiest way to build up a string. Place {0}, {1}, etc. where you want the variables in the string, put a -f immediately after the string and then the list of variables separated by commas.

Get-ChildItem c:\code|%{'{0}\{1}\{2}.dll' -f $_.fullname,$buildconfig,$_.name}

(I've also taken the dash out of the $buildconfig variable name as I have seen that causes issues before too.)

Get all table names of a particular database by SQL query?

In order if someone would like to list all tables within specific database without using the "use" keyword:

SELECT TABLE_NAME FROM databasename.INFORMATION_SCHEMA.TABLES

How to analyze information from a Java core dump?

Okay if you've created the core dump with gcore or gdb then you'll need to convert it to something called a HPROF file. These can be used by VisualVM, Netbeans or Eclipse's Memory Analyzer Tool (formerly SAP Memory Analyzer). I'd recommend Eclipse MAT.

To convert the file use the commandline tool jmap.

# jmap -dump:format=b,file=dump.hprof /usr/bin/java core.1234

where:

dump.hprof is the name of the hprof file you wish to create

/usr/bin/java is the path to the version of the java binary that generated the core dump

core.1234 is your regular core file.

Getting assembly name

I use the Assembly to set the form's title as such:

private String BuildFormTitle()
{
    String AppName = System.Reflection.Assembly.GetEntryAssembly().GetName().Name;
    String FormTitle = String.Format("{0} {1} ({2})", 
                                     AppName, 
                                     Application.ProductName, 
                                     Application.ProductVersion);
    return FormTitle;
}

Password encryption/decryption code in .NET

First create a class like:

public class Encryption
    { 
        public static string Encrypt(string clearText)
        {
            string EncryptionKey = "MAKV2SPBNI99212";
            byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
            using (Aes encryptor = Aes.Create())
            {
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV = pdb.GetBytes(16);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(clearBytes, 0, clearBytes.Length);
                        cs.Close();
                    }
                    clearText = Convert.ToBase64String(ms.ToArray());
                }
            }
            return clearText;
        }

        public static string Decrypt(string cipherText)
        {
            string EncryptionKey = "MAKV2SPBNI99212";
            byte[] cipherBytes = Convert.FromBase64String(cipherText);
            using (Aes encryptor = Aes.Create())
            {
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV = pdb.GetBytes(16);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(cipherBytes, 0, cipherBytes.Length);
                        cs.Close();
                    }
                    cipherText = Encoding.Unicode.GetString(ms.ToArray());
                }
            }
            return cipherText;
        }
    }

**In Controller **

add reference for this encryption class:

using testdemo.Models

public ActionResult Index() {
            return View();
        }
        [HttpPost]
        public ActionResult Index(string text)
        {
            if (Request["txtEncrypt"] != null)
            {
                string getEncryptionCode = Request["txtEncrypt"];
                string DecryptCode = Encryption.Decrypt(HttpUtility.UrlDecode(getEncryptionCode));
                ViewBag.GetDecryptCode = DecryptCode;
                return View();
            }
            else {
                string getDecryptCode = Request["txtDecrypt"];
                string EncryptionCode = HttpUtility.UrlEncode(Encryption.Encrypt(getDecryptCode));
                ViewBag.GetEncryptionCode = EncryptionCode;
                return View();
            }

        }

In View

<h2>Decryption Code</h2>
@using (Html.BeginForm())
{
    <table class="table-bordered table">
        <tr>
            <th>Encryption Code</th>
            <td><input type="text" id="txtEncrypt" name="txtEncrypt" placeholder="Enter Encryption Code" /></td>
        </tr>
        <tr>
            <td colspan="2">
                <span style="color:red">@ViewBag.GetDecryptCode</span>
            </td>
        </tr>
        <tr>
                <td colspan="2">
                    <input type="submit" id="btnEncrypt" name="btnEncrypt"value="Decrypt to Encrypt code" />
                </td>
            </tr>
    </table>
}
    <br />
    <br />
    <br />
    <h2>Encryption Code</h2>
@using (Html.BeginForm())
{
    <table class="table-bordered table">
        <tr>
            <th>Decryption Code</th>
            <td><input type="text" id="txtDecrypt" name="txtDecrypt" placeholder="Enter Decryption Code" /></td>
        </tr>

        <tr>
            <td colspan="2">
                <span style="color:red">@ViewBag.GetEncryptionCode</span>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" id="btnDecryt" name="btnDecryt" value="Encrypt to Decrypt code" />
            </td>
        </tr>
    </table>
}

How to perform a real time search and filter on a HTML table

Pure Javascript Solution :

Works for ALL columns and Case Insensitive :

function search_table(){
  // Declare variables 
  var input, filter, table, tr, td, i;
  input = document.getElementById("search_field_input");
  filter = input.value.toUpperCase();
  table = document.getElementById("table_id");
  tr = table.getElementsByTagName("tr");

  // Loop through all table rows, and hide those who don't match the search query
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td") ; 
    for(j=0 ; j<td.length ; j++)
    {
      let tdata = td[j] ;
      if (tdata) {
        if (tdata.innerHTML.toUpperCase().indexOf(filter) > -1) {
          tr[i].style.display = "";
          break ; 
        } else {
          tr[i].style.display = "none";
        }
      } 
    }
  }
}

Convert pyspark string to date format

The strptime() approach does not work for me. I get another cleaner solution, using cast:

from pyspark.sql.types import DateType
spark_df1 = spark_df.withColumn("record_date",spark_df['order_submitted_date'].cast(DateType()))
#below is the result
spark_df1.select('order_submitted_date','record_date').show(10,False)

+---------------------+-----------+
|order_submitted_date |record_date|
+---------------------+-----------+
|2015-08-19 12:54:16.0|2015-08-19 |
|2016-04-14 13:55:50.0|2016-04-14 |
|2013-10-11 18:23:36.0|2013-10-11 |
|2015-08-19 20:18:55.0|2015-08-19 |
|2015-08-20 12:07:40.0|2015-08-20 |
|2013-10-11 21:24:12.0|2013-10-11 |
|2013-10-11 23:29:28.0|2013-10-11 |
|2015-08-20 16:59:35.0|2015-08-20 |
|2015-08-20 17:32:03.0|2015-08-20 |
|2016-04-13 16:56:21.0|2016-04-13 |

What is the best way to add a value to an array in state

Both of the options you provided are the same. Both of them will still point to the same object in memory and have the same array values. You should treat the state object as immutable as you said, however you need to re-create the array so its pointing to a new object, set the new item, then reset the state. Example:

onChange(event){
    var newArray = this.state.arr.slice();    
    newArray.push("new value");   
    this.setState({arr:newArray})
}

How to change color of ListView items on focus and on click

Declare list item components as final outside your setOnClickListener or whatever you want to apply on your list item like this:

final View yourView;
final TextView yourTextView;

And in overriding onClick or whatever method you use, just set colors as needed like this:

yourView.setBackgroundColor(Color.WHITE/*or whatever RGB suites good contrast*/);
yourTextView.setTextColor(Color.BLACK/*or whatever RGB suites good contrast*/);

Or without the final declaration, if let's say you implement an onClick() for a custom adapter to populate a list, this is what I used in getView() for my setOnClickListener/onClick():

//reset color for all list items in case any item was previously selected
for(int i = 0; i < parent.getChildCount(); i++)
{
  parent.getChildAt(i).setBackgroundColor(Color.BLACK);
  TextView text=(TextView) parent.getChildAt(i).findViewById(R.id.item);
  text.setTextColor(Color.rgb(0,178,178));
}
//highlight currently selected item
 parent.getChildAt(position).setBackgroundColor(Color.rgb(0,178,178));
 TextView text=(TextView) parent.getChildAt(position).findViewById(R.id.item);
 text.setTextColor(Color.rgb(0,178,178));

Setting device orientation in Swift iOS

Swift 4:

The simplest answer, in my case needing to ensure one onboarding tutorial view was portrait-only:

extension myViewController {
    //manage rotation for this viewcontroller
    override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
}

Eezy-peezy.

Android toolbar center title and custom font

Solution that I used for this problem:

 public static void applyFontForToolbarTitle(Activity a){
        Toolbar toolbar = (Toolbar) a.findViewById(R.id.app_bar);
        for(int i = 0; i < toolbar.getChildCount(); i++){
            View view = toolbar.getChildAt(i);
            if(view instanceof TextView){
                TextView tv = (TextView) view;
                if(tv.getText().equals(a.getTitle())){
                    tv.setTypeface(getRuneTypefaceBold(a));
                    break;
                }
            }
        }
    }

For center gravity I think it would be necessary to change layout params to match_parent horizontally and then:

tv.setGravity(Gravity.CENTER);

Passing 'this' to an onclick event

You can always call funciton differently: foo.call(this); in this way you will be able to use this context inside the function.

Example:

<button onclick="foo.call(this)" id="bar">Button</button>?

var foo = function()
{
    this.innerHTML = "Not a button";
};

Why am I getting "Thread was being aborted" in ASP.NET?

Nope, ThreadAbortException is thrown by a simple Response.Redirect

Replace all elements of Python NumPy Array that are greater than some value

Lets us assume you have a numpy array that has contains the value from 0 all the way up to 20 and you want to replace numbers greater than 10 with 0

_x000D_
_x000D_
import numpy as np

my_arr = np.arange(0,21) # creates an array
my_arr[my_arr > 10] = 0 # modifies the value
_x000D_
_x000D_
_x000D_

Note this will however modify the original array to avoid overwriting the original array try using arr.copy() to create a new detached copy of the original array and modify that instead.

_x000D_
_x000D_
import numpy as np

my_arr = np.arange(0,21)
my_arr_copy = my_arr.copy() # creates copy of the orignal array

my_arr_copy[my_arr_copy > 10] = 0 
_x000D_
_x000D_
_x000D_

MySQL DELETE FROM with subquery as condition

I approached this in a slightly different way and it worked for me;

I needed to remove secure_links from my table that referenced the conditions table where there were no longer any condition rows left. A housekeeping script basically. This gave me the error - You cannot specify target table for delete.

So looking here for inspiration I came up with the below query and it works just fine. This is because it creates a temporary table sl1 that is used as the reference for the DELETE.

DELETE FROM `secure_links` WHERE `secure_links`.`link_id` IN 
            (
            SELECT
                `sl1`.`link_id` 
            FROM 
                (
                SELECT 

                    `sl2`.`link_id` 

                FROM 
                    `secure_links` AS `sl2` 
                    LEFT JOIN `conditions` ON `conditions`.`job` = `sl2`.`job` 

                WHERE 

                    `sl2`.`action` = 'something' AND 
                    `conditions`.`ref` IS NULL 
                ) AS `sl1`
            )

Works for me.

How to get an isoformat datetime string including the default timezone?

To get the current time in UTC in Python 3.2+:

>>> from datetime import datetime, timezone
>>> datetime.now(timezone.utc).isoformat()
'2015-01-27T05:57:31.399861+00:00'

To get local time in Python 3.3+:

>>> from datetime import datetime, timezone
>>> datetime.now(timezone.utc).astimezone().isoformat()
'2015-01-27T06:59:17.125448+01:00'

Explanation: datetime.now(timezone.utc) produces a timezone aware datetime object in UTC time. astimezone() then changes the timezone of the datetime object, to the system's locale timezone if called with no arguments. Timezone aware datetime objects then produce the correct ISO format automatically.

How to define custom configuration variables in rails

This works in rails 3.1:

in config/environment.rb (or in config/environments/.. to target a specific environment) :

YourApp::Application.config.yourKey = 'foo'

This will be accessible in controller or views like this:

YourApp::Application.config.yourKey

(YourApp should be replaced by your application name.)

Note: It's Ruby code, so if you have a lot of config keys, you can do this :

in config/environment.rb :

YourApp::Application.configure do
  config.something = foo
  config.....
  config....
  .
  config....
end

push multiple elements to array

When using most functions of objects with apply or call, the context parameter MUST be the object you are working on.

In this case, you need a.push.apply(a, [1,2]) (or more correctly Array.prototype.push.apply(a, [1,2]))

C# Telnet Library

I ended up finding MinimalistTelnet and adapted it to my uses. I ended up needing to be able to heavily modify the code due to the unique** device that I am attempting to attach to.

** Unique in this instance can be validly interpreted as brain-dead.

How to switch from the default ConstraintLayout to RelativeLayout in Android Studio

Android 3.0

In activity_main.xml

Replace in this tag i.e <android.support.constraint.ConstraintLayout>

android.support.constraint.ConstraintLayout

with

RelativeLayout

How to trigger a click on a link using jQuery

You should call the element's native .click() method or use the createEvent API.

For more info, please visit: https://learn.jquery.com/events/triggering-event-handlers/

How can I get npm start at a different directory?

This one-liner should work:

npm start --prefix path/to/your/app

Corresponding doc

How to apply two CSS classes to a single element

This is very clear that to add two classes in single div, first you have to generate the classes and then combine them. This process is used to make changes and reduce the no. of classes. Those who make the website from scratch mostly used this type of methods. they make two classes first class is for color and second class is for setting width, height, font-style, etc. When we combine both the classes then the first class and second class both are in effect.

_x000D_
_x000D_
.color_x000D_
{background-color:#21B286;}_x000D_
.box_x000D_
{_x000D_
  width:"100%";_x000D_
  height:"100px";_x000D_
  font-size: 16px;_x000D_
  text-align:center;_x000D_
  line-height:1.19em;_x000D_
}_x000D_
.box.color_x000D_
{_x000D_
width:"100%";_x000D_
height:"100px";_x000D_
font-size:16px;_x000D_
color:#000000;_x000D_
text-align:center;_x000D_
}
_x000D_
<div class="box color">orderlist</div>
_x000D_
_x000D_
_x000D_

How to strip comma in Python string

You want to replace it, not strip it:

s = s.replace(',', '')

Clone private git repo with dockerfile

My key was password protected which was causing the problem, a working file is now listed below (for help of future googlers)

FROM ubuntu

MAINTAINER Luke Crooks "[email protected]"

# Update aptitude with new repo
RUN apt-get update

# Install software 
RUN apt-get install -y git
# Make ssh dir
RUN mkdir /root/.ssh/

# Copy over private key, and set permissions
# Warning! Anyone who gets their hands on this image will be able
# to retrieve this private key file from the corresponding image layer
ADD id_rsa /root/.ssh/id_rsa

# Create known_hosts
RUN touch /root/.ssh/known_hosts
# Add bitbuckets key
RUN ssh-keyscan bitbucket.org >> /root/.ssh/known_hosts

# Clone the conf files into the docker container
RUN git clone [email protected]:User/repo.git

How to safely call an async method in C# without await

I end up with this solution :

public async Task MyAsyncMethod()
{
    // do some stuff async, don't return any data
}

public string GetStringData()
{
    // Run async, no warning, exception are catched
    RunAsync(MyAsyncMethod()); 
    return "hello world";
}

private void RunAsync(Task task)
{
    task.ContinueWith(t =>
    {
        ILog log = ServiceLocator.Current.GetInstance<ILog>();
        log.Error("Unexpected Error", t.Exception);

    }, TaskContinuationOptions.OnlyOnFaulted);
}

Check file size before upload

I created a jQuery version of PhpMyCoder's answer:

$('form').submit(function( e ) {    
    if(!($('#file')[0].files[0].size < 10485760 && get_extension($('#file').val()) == 'jpg')) { // 10 MB (this size is in bytes)
        //Prevent default and display error
        alert("File is wrong type or over 10Mb in size!");
        e.preventDefault();
    }
});

function get_extension(filename) {
    return filename.split('.').pop().toLowerCase();
}

Convert string with comma to integer

I would do using String#tr :

"1,112".tr(',','').to_i # => 1112

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

shape is a tuple that gives dimensions of the array..

>>> c = arange(20).reshape(5,4)
>>> c
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19]])

c.shape[0] 
5

Gives the number of rows

c.shape[1] 
4

Gives number of columns

Option to ignore case with .contains method?

With a null check on the dvdList and your searchString

    if (!StringUtils.isEmpty(searchString)) {
        return Optional.ofNullable(dvdList)
                       .map(Collection::stream)
                       .orElse(Stream.empty())
                       .anyMatch(dvd >searchString.equalsIgnoreCase(dvd.getTitle()));
      }

vertical-align: middle doesn't work

The answer given by Matt K works perfectly fine.

However it is important to note one thing - If the div you are applying it to has absolute positioning, it wont work. For it to work, do this -

<div style="position:absolute; hei...">
   <div style="position:relative; display: table-cell; vertical-align:middle; hei..."> 
      <!-- here position MUST be relative, this div acts as a wrapper-->
      ...
   </div>
</div>

How to get height and width of device display in angular2 using typescript?

I found the solution. The answer is very simple. write the below code in your constructor.

import { Component, OnInit, OnDestroy, Input } from "@angular/core";
// Import this, and write at the top of your .ts file
import { HostListener } from "@angular/core";

@Component({
  selector: "app-login",
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})

export class LoginComponent implements OnInit, OnDestroy {
    // Declare height and width variables
    scrHeight:any;
    scrWidth:any;

    @HostListener('window:resize', ['$event'])
    getScreenSize(event?) {
          this.scrHeight = window.innerHeight;
          this.scrWidth = window.innerWidth;
          console.log(this.scrHeight, this.scrWidth);
    }

    // Constructor
    constructor() {
        this.getScreenSize();
    }


}

====== Working Code (Another) ======

export class Dashboard  {
 mobHeight: any;
 mobWidth: any;
     constructor(private router:Router, private http: Http){
        this.mobHeight = (window.screen.height) + "px";
        this.mobWidth = (window.screen.width) + "px";
          console.log(this.mobHeight);
          console.log(this.mobWidth)
     }
}

"Android library projects cannot be launched"?

It says “Android library projects cannot be launched” because Android library projects cannot be launched. That simple. You cannot run a library. If you want to test a library, create an Android project that uses the library, and execute it.

In Java 8 how do I transform a Map<K,V> to another Map<K,V> using a lambda?

Map<String, Integer> map = new HashMap<>();
map.put("test1", 1);
map.put("test2", 2);

Map<String, Integer> map2 = new HashMap<>();
map.forEach(map2::put);

System.out.println("map: " + map);
System.out.println("map2: " + map2);
// Output:
// map:  {test2=2, test1=1}
// map2: {test2=2, test1=1}

You can use the forEach method to do what you want.

What you're doing there is:

map.forEach(new BiConsumer<String, Integer>() {
    @Override
    public void accept(String s, Integer integer) {
        map2.put(s, integer);     
    }
});

Which we can simplify into a lambda:

map.forEach((s, integer) ->  map2.put(s, integer));

And because we're just calling an existing method we can use a method reference, which gives us:

map.forEach(map2::put);

Where does error CS0433 "Type 'X' already exists in both A.dll and B.dll " come from?

This happened to me because of an error in my Web.Config

<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.WebPages, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

The Sytem.Web.Helpers was pointed at 1.0.0.0 instead of 3.0.0.0 (MVC 3 is being used on this project).

Because IIS couldn't find the reference in the local folder it looked in the GAC and found two different versions. After pointing it at the correct reference IIS found the local dll and used that instead of searching the GAC.

Error: Selection does not contain a main type

I had this problem in two projects. Maven and command line worked as expected for both. The problems were Eclipse specific. Two different solutions: Project 1): Move the main method declaration to the top within the class, above all other declarations like fields and constructors. Crazy, but it worked. Project 2): The solution for Project 1) did not remedy the problem. However, removing lombok imports and explicitly writing a getter method solved the problem

Conclusion: Eclipse and/or the lombok plugin have/has a bug.

Animate element to auto height with jQuery

You can always wrap the child elements of #first and save height height of the wrapper as a variable. This might not be the prettiest or most efficient answer, but it does the trick.

Here's a fiddle where I included a reset.

but for your purposes, here's the meat & potatoes:

$(function(){
//wrap everything inside #first
$('#first').children().wrapAll('<div class="wrapper"></div>');
//get the height of the wrapper 
var expandedHeight = $('.wrapper').height();
//get the height of first (set to 200px however you choose)
var collapsedHeight = $('#first').height();
//when you click the element of your choice (a button in my case) #first will animate to height auto
$('button').click(function(){
    $("#first").animate({
        height: expandedHeight            
    })
});
});?

Dynamic Web Module 3.0 -- 3.1

I had the same problem and fixed this by editing org.eclipse.wst.common.project.facet.core.xml.

In this file, I was able to change the following line

<installed facet="jst.web" version="3.1"/>

back to

<installed facet="jst.web" version="3.0"/>

That seemed to fix the problem for me.

difference between @size(max = value ) and @min(value) @max(value)

package com.mycompany;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class Car {

    @NotNull
    private String manufacturer;

    @NotNull
    @Size(min = 2, max = 14)
    private String licensePlate;

    @Min(2)
    private int seatCount;

    public Car(String manufacturer, String licencePlate, int seatCount) {
        this.manufacturer = manufacturer;
        this.licensePlate = licencePlate;
        this.seatCount = seatCount;
    }

    //getters and setters ...
}

@NotNull, @Size and @Min are so-called constraint annotations, that we use to declare constraints, which shall be applied to the fields of a Car instance:

manufacturer shall never be null

licensePlate shall never be null and must be between 2 and 14 characters long

seatCount shall be at least 2.

DOS: find a string, if found then run another script

It's been awhile since I've done anything with batch files but I think that the following works:

find /c "string" file
if %errorlevel% equ 1 goto notfound
echo found
goto done
:notfound
echo notfound
goto done
:done

This is really a proof of concept; clean up as it suits your needs. The key is that find returns an errorlevel of 1 if string is not in file. We branch to notfound in this case otherwise we handle the found case.

Django: How can I call a view function from template?

How about this:

<a class="btn btn-primary" href="{% url 'url-name'%}">Button-Text</a>

The class is including bootstrap styles for primary button.

How to set lifetime of session

Prior to PHP 7, the session_start() function did not directly accept any configuration options. Now you can do it this way

<?php
// This sends a persistent cookie that lasts a day.
session_start([
    'cookie_lifetime' => 86400,
]);
?>

Reference: https://php.net/manual/en/function.session-start.php#example-5976

List of installed gems?

A more modern version would be to use something akin to the following...

require 'rubygems'
puts Gem::Specification.all().map{|g| [g.name, g.version.to_s].join('-') }

NOTE: very similar the first part of an answer by Evgeny... but due to page formatting, it's easy to miss.

How to get all elements inside "div" that starts with a known text

i have tested a sample and i would like to share this sample and i am sure it's quite help full. I have done all thing in body, first creating an structure there on click of button you will call a function selectallelement(); on mouse click which will pass the id of that div about which you want to know the childrens. I have given alerts here on different level so u can test where r u now in the coding .

    <body>
    <h1>javascript to count the number of children of given child</h1>

    <div id="count">
    <span>a</span>
    <span>s</span>
    <span>d</span>
    <span>ff</span>
    <div>fsds</div>
    <p>fffff</p>
    </div>
   <button type="button" onclick="selectallelement('count')">click</button>
   <p>total element no.</p>
    <p id="sho">here</p>
  <script>

  function selectallelement(divid)
  {
 alert(divid);
 var ele = document.getElementById(divid).children;
 var match = new Array();
  var i = fillArray(ele,match);
  alert(i);
   document.getElementById('sho').innerHTML = i;
  }
 function fillArray(e1,a1)
  {
 alert("we are here");
   for(var i =0;i<e1.length;i++)
{
  if(e1[i].id.indexOf('count') == 0)
    a1.push(e1[i]);
}
return i;
   }
   </script>

 </body>

  USE THIS I AM SURE U WILL GET YOUR ANSWER ...THANKS 

jQuery UI Dialog with ASP.NET button postback

I didn't want to have to work around this problem for every dialog in my project, so I created a simple jQuery plugin. This plugin is merely for opening new dialogs and placing them within the ASP.NET form:

(function($) {
    /**
     * This is a simple jQuery plugin that works with the jQuery UI
     * dialog. This plugin makes the jQuery UI dialog append to the
     * first form on the page (i.e. the asp.net form) so that
     * forms in the dialog will post back to the server.
     *
     * This plugin is merely used to open dialogs. Use the normal
     * $.fn.dialog() function to close dialogs programatically.
     */
    $.fn.aspdialog = function() {
        if (typeof $.fn.dialog !== "function")
            return;

        var dlg = {};

        if ( (arguments.length == 0)
                || (arguments[0] instanceof String) ) {
            // If we just want to open it without any options
            // we do it this way.
            dlg = this.dialog({ "autoOpen": false });
            dlg.parent().appendTo('form:first');
            dlg.dialog('open');
        }
        else {
            var options = arguments[0];
            options.autoOpen = false;
            options.bgiframe = true;

            dlg = this.dialog(options);
            dlg.parent().appendTo('form:first');
            dlg.dialog('open');
        }
    };
})(jQuery);</code></pre>

So to use the plugin, you first load jQuery UI and then the plugin. Then you can do something like the following:

$('#myDialog1').aspdialog(); // Simple
$('#myDialog2').aspdialog('open'); // The same thing
$('#myDialog3').aspdialog({title: "My Dialog", width: 320, height: 240}); // With options!

To be clear, this plugin assumes you are ready to show the dialog when you call it.

Changing the selected option of an HTML Select element

Excellent answers - here's the D3 version for anyone looking:

<select id="sel">
    <option>Cat</option>
    <option>Dog</option>
    <option>Fish</option>
</select>
<script>
    d3.select('#sel').property('value', 'Fish');
</script>

Remove category & tag base from WordPress url - without a plugin

Whilst you dismiss it as a solution, the plugin is by far the easiest and most consistent method and they don't change any WordPress default files.

http://wordpress.org/plugins/wp-no-category-base/

It hasn't needed to be updated for a year, so it is not exactly creating any problems with updates.

There is no simple hand rolled solution that will do all of this that does not just replicate what the plugin does from within your own functions.php

  • Better and logical permalinks like myblog.com/my-category/ and myblog.com/my-category/my-post/.
  • Simple plugin - barely adds any overhead.
  • Works out of the box - no setup needed. No need to modify WordPress files.
  • Doesn't require other plugins to work.
  • Compatible with sitemap plugins.
  • Works with multiple sub-categories.
  • Works with WordPress Multisite.
  • Redirects old category permalinks to the new ones (301 redirect, good for SEO).

Plus you get the benefit that if WordPress does change, then the plugin will be updated to work whilst you would then have to figure out how to fix your own code on your own.

Xcode "Build and Archive" from command line

We developed an iPad app with XCode 4.2.1 and wanted to integrate the build into our continuous integration (Jenkins) for OTA distribution. Here's the solution I came up with:

# Unlock keychain
security unlock-keychain -p jenkins /Users/jenkins/Library/Keychains/login.keychain

# Build and sign app
xcodebuild -configuration Distribution clean build

# Set variables
APP_PATH="$PWD/build/Distribution-iphoneos/iPadApp.app"
VERSION=`defaults read $APP_PATH/Info CFBundleShortVersionString`
REVISION=`defaults read $APP_PATH/Info CFBundleVersion`
DATE=`date +"%Y%m%d-%H%M%S"`
ITUNES_LINK="<a href=\"itms-services:\/\/?action=download-manifest\&url=https:\/\/xxx.xxx.xxx\/iPadApp-$VERSION.$REVISION-$DATE.plist\">Download iPad2-App v$VERSION.$REVISION-$DATE<\/a>"

# Package and verify app
xcrun -sdk iphoneos PackageApplication -v build/Distribution-iphoneos/iPadApp.app -o $PWD/iPadApp-$VERSION.$REVISION-$DATE.ipa

# Create plist
cat iPadApp.plist.template | sed -e "s/\${VERSION}/$VERSION/" -e "s/\${DATE}/$DATE/" -e "s/\${REVISION}/$REVISION/" > iPadApp-$VERSION.$REVISION-$DATE.plist

# Update index.html
curl https://xxx.xxx.xxx/index.html -o index.html.$DATE
cat index.html.$DATE | sed -n '1h;1!H;${;g;s/\(<h3>Aktuelle Version<\/h3>\)\(.*\)\(<h3>&Auml;ltere Versionen<\/h3>.<ul>.<li>\)/\1\
${ITUNES_LINK}\
\3\2<\/li>\
<li>/g;p;}' | sed -e "s/\${ITUNES_LINK}/$ITUNES_LINK/" > index.html

Then Jenkins uploads the ipa, plist and html files to our webserver.

This is the plist template:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>items</key>
    <array>
        <dict>
            <key>assets</key>
            <array>
                <dict>
                    <key>kind</key>
                    <string>software-package</string>
                    <key>url</key>
                    <string>https://xxx.xxx.xxx/iPadApp-${VERSION}.${REVISION}-${DATE}.ipa</string>
                </dict>
                <dict>
                    <key>kind</key>
                    <string>full-size-image</string>
                    <key>needs-shine</key>
                    <true/>
                    <key>url</key>
                    <string>https://xxx.xxx.xxx/iPadApp.png</string>
                </dict>
                <dict>
                    <key>kind</key>
                    <string>display-image</string>
                    <key>needs-shine</key>
                    <true/>
                    <key>url</key>
                    <string>https://xxx.xxx.xxx/iPadApp_sm.png</string>
                </dict>
            </array>
            <key>metadata</key>
            <dict>
                <key>bundle-identifier</key>
                <string>xxx.xxx.xxx.iPadApp</string>
                <key>bundle-version</key>
                <string>${VERSION}</string>
                <key>kind</key>
                <string>software</string>
                <key>subtitle</key>
                <string>iPad2-App</string>
                <key>title</key>
                <string>iPadApp</string>
            </dict>
        </dict>
    </array>
</dict>
</plist>

To set this up, you have to import the distribution certificate and provisioning profile into the designated user's keychain.

How to request Administrator access inside a batch file

@echo off 
Net session >nul 2>&1 || (PowerShell start -verb runas '%~0' &exit /b)
Echo Administrative privileges have been got. & pause

The above works on my Windows 10 Version 1903

Place a button right aligned

In my case the

<p align="right"/>

worked fine

Android XXHDPI resources

xxhdpi was not specified before but now new devices S4, HTC one are surely comes inside xxhdpi .These device dpi are around 440. I do not know exact limit for xxhdpi See how to develop android application for xxhdpi device Samsung S4 I know this is late answer but as thing had change since the question asked

Note Google Nexus 10 need to add a 144*144px icon in the drawable-xxhdpi or drawable-480dpi folder.

JQuery show/hide when hover

Since you're using jQuery, you just need to attach to some specific events and some pre defined animations:

$('#cat').hover(function()
{
     // Mouse Over Callback
}, function()
{ 
     // Mouse Leave callback
});

Then, to do the animation, you simply need to call the fadeOut / fadeIn animations:

$('#dog').fadeOut(750 /* Animation Time */, function()
{
    // animation complete callback
     $('#cat').fadeIn(750);
});

Combining the two together, you would simply insert the animations in the hover callbacks (something like so, use this as a reference point):

$('#cat').hover(function()
{
     if($('#dog').is(':visible'))
        $('#dog').fadeOut(750 /* Animation Time */, function()
     {
        // animation complete callback
         $('#cat').fadeIn(750);
     });
}, function()
{ 
     // Mouse Leave callback
});

Can't use WAMP , port 80 is used by IIS 7.5

If you're using Windows 10, as I am, and the port is occupied by Microsoft-IIS/10.0, change the lines 62 and 63, of the httpd.conf, from:

Listen 0.0.0.0:80
Listen [::0]:80

To:

Listen 0.0.0.0:8080
Listen [::0]:8080

As the people here suggested.

And also, change the line 221, from:

ServerName localhost:80

To:

ServerName localhost:8080

Now, your host will be available at http://localhost:8080/.

Telegram Bot - how to get a group chat id?

You can get Chat ID in this way.

On private chat with your bot, send a random message. You will search this message later.

Get Your API-token from bot_father : XXXXXXXXX:YYYYYYY-YYYYYYYYYYYYYYYYY_YY

Then, on your browser make a request with that url :

https://api.telegram.org/botXXXXXXXXX:YYYYYYY-YYYYYYYYYYYYYYYYY_YY/getUpdates

The request returns a json response, in json text search your random message and get chat id in that object.

MVC 4 - how do I pass model data to a partial view?

Also, this could make it works:

@{
Html.RenderPartial("your view", your_model, ViewData);
}

or

@{
Html.RenderPartial("your view", your_model);
}

For more information on RenderPartial and similar HTML helpers in MVC see this popular StackOverflow thread

Open images? Python

Open any file

import os
os.startfile(<filepath>)

How can I put the current running linux process in background?

Suspend the process with CTRL+Z then use the command bg to resume it in background. For example:

sleep 60
^Z  #Suspend character shown after hitting CTRL+Z
[1]+  Stopped  sleep 60  #Message showing stopped process info
bg  #Resume current job (last job stopped)

More about job control and bg usage in bash manual page:

JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.

bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.

EDIT

To start a process where you can even kill the terminal and it still carries on running

nohup [command] [-args] > [filename] 2>&1 &

e.g.

nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &

To just ignore the output (not very wise) change the filename to /dev/null

To get the error message set to a different file change the &1 to a filename.

In addition: You can use the jobs command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1 or kill %2 with the number being the index of the process.

jquery : focus to div is not working

a <div> can be focused if it has a tabindex attribute. (the value can be set to -1)

For example:

$("#focus_point").attr("tabindex",-1).focus();

In addition, consider setting outline: none !important; so it displayed without a focus rectangle.

var element = $("#focus_point");
element.css('outline', 'none !important')
       .attr("tabindex", -1)
       .focus();

How to make a GridLayout fit screen size

I archive this using LinearLayout

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

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:height="166dp"
            android:text="Tile1"
            android:gravity="center"
            android:background="#6f19e5"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:text="Tile2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:height="126dp"
            android:gravity="center"
            android:layout_weight=".50"
            android:background="#f1d600"/>

        <TextView
            android:text="Tile3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:height="126dp"
            android:gravity="center"
            android:layout_weight=".50"
            android:background="#e75548"/>

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:text="Tile4"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:height="126dp"
            android:gravity="center"
            android:layout_weight=".50"
            android:background="#29d217"/>

        <TextView
            android:text="Tile5"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:height="126dp"
            android:gravity="center"
            android:layout_weight=".50"
            android:background="#e519cb"/>

    </LinearLayout>
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:height="176dp"
            android:text="Tile6"
            android:gravity="center"
            android:background="#09eadd"/>
    </LinearLayout>
</LinearLayout>

Here the modal

yii2 hidden input value

Like This:

<?= $form->field($model, 'hidden')->hiddenInput(['class' => 'form-control', 'maxlength' => true,])->label(false) ?>

How to expire a cookie in 30 minutes using jQuery?

30 minutes is 30 * 60 * 1000 miliseconds. Add that to the current date to specify an expiration date 30 minutes in the future.

 var date = new Date();
 var minutes = 30;
 date.setTime(date.getTime() + (minutes * 60 * 1000));
 $.cookie("example", "foo", { expires: date });

What is the Java equivalent of PHP var_dump?

Your alternatives are to override the toString() method of your object to output its contents in a way that you like, or to use reflection to inspect the object (in a way similar to what debuggers do).

The advantage of using reflection is that you won't need to modify your individual objects to be "analysable", but there is added complexity and if you need nested object support you'll have to write that.

This code will list the fields and their values for an Object "o"

Field[] fields = o.getClass().getDeclaredFields();
for (int i=0; i<fields.length; i++)
{
    System.out.println(fields[i].getName() + " - " + fields[i].get(o));
}

Using Tkinter in python to edit the title bar

I found this works:

window = Tk()
window.title('Window')

Maybe this helps?

How to force Hibernate to return dates as java.util.Date instead of Timestamp?

Approaches 1 and 2 obviously don't work, because you get java.sql.Date objects, per JPA/Hibernate spec, and not java.util.Date. From approaches 3 and 4, I would rather choose the latter one, because it's more declarative, and will work with both field and getter annotations.

You have already laid out the solution 4 in your referenced blog post, as @tscho was kind to point out. Maybe defaultForType (see below) should give you the centralized solution you were looking for. Of course will will still need to differentiate between date (without time) and timestamp fields.

For future reference I will leave the summary of using your own Hibernate UserType here:

To make Hibernate give you java.util.Date instances, you can use the @Type and @TypeDef annotations to define a different mapping of your java.util.Date java types to and from the database.

See the examples in the core reference manual here.

  1. Implement a UserType to do the actual plumbing (conversion to/from java.util.Date), named e.g. TimestampAsJavaUtilDateType
  2. Add a @TypeDef annotation on one entity or in a package-info.java - both will be available globally for the session factory (see manual link above). You can use defaultForType to apply the type conversion on all mapped fields of type java.util.Date.

    @TypeDef
      name = "timestampAsJavaUtilDate",
      defaultForType = java.util.Date.class, /* applied globally */
      typeClass = TimestampAsJavaUtilDateType.class
    )
    
  3. Optionally, instead of defaultForType, you can annotate your fields/getters with @Type individually:

    @Entity
    public class MyEntity {
       [...]
       @Type(type="timestampAsJavaUtilDate")
       private java.util.Date myDate;
       [...]
    }
    

P.S. To suggest a totally different approach: we usually just don't compare Date objects using equals() anyway. Instead we use a utility class with methods to compare e.g. only the calendar date of two Date instances (or another resolution such as seconds), regardless of the exact implementation type. That as worked well for us.

Return Boolean Value on SQL Select Statement

Use 'Exists' which returns either 0 or 1.

The query will be like:

SELECT EXISTS(SELECT * FROM USER WHERE UserID = 20070022)

Android Google Maps v2 - set zoom level for myLocation

you have to write only one line in maps_activity.xml

map:cameraZoom="13"

I hope this will solve your problem...

How can I install a .ipa file to my iPhone simulator

Step to run in different simulator without any code repo :-

First create a .app by building your project(under project folder in Xcode) and paste it in a appropriate location (See pic for more clarity)

enter image description here

  1. Download Xcode
  2. Create a demo project and Start simulator in which you want to run the app.
  3. Copy the .app file in particular location(ex :- Desktop).
  4. cd Desktop and Run the command (xcrun simctl install booted appName.app),
  5. App will be installed in the particular booted simulator.

How to set the current working directory?

import os
print os.getcwd()  # Prints the current working directory

To set the working directory:

os.chdir('c:\\Users\\uname\\desktop\\python')  # Provide the new path here

AngularJS: ng-model not binding to ng-checked for checkboxes

What you could do is use ng-repeat passing in the value of whatever you're iterating on to the ng-checked and from there utilising ng-class to apply your styles depending on the result.

I did something similar recently and it worked for me.

How to select data of a table from another database in SQL Server?

I've used this before to setup a query against another server and db via linked server:

EXEC sp_addlinkedserver @server='PWA_ProjectServer', @srvproduct='',
@provider='SQLOLEDB', @datasrc='SERVERNAME\PWA_ProjectServer'

per the comment above:

select * from [server].[database].[schema].[table]

e.g.

select top 6 * from [PWA_ProjectServer].[PWA_ProjectServer_Reporting].[dbo].[MSP_AdminStatus]

Allow scroll but hide scrollbar

Try this:

HTML:

<div id="container">
    <div id="content">
        // Content here
    </div>
</div>

CSS:

#container{
    height: 100%;
    width: 100%;
    overflow: hidden;
}

#content{
    width: 100%;
    height: 99%;
    overflow: auto;
    padding-right: 15px;
}

html, body{
    height: 99%;
    overflow:hidden;
}

JSFiddle Demo

Tested on FF and Safari.

How does OAuth 2 protect against things like replay attacks using the Security Token?

Figure 1, lifted from RFC6750:

     +--------+                               +---------------+
     |        |--(A)- Authorization Request ->|   Resource    |
     |        |                               |     Owner     |
     |        |<-(B)-- Authorization Grant ---|               |
     |        |                               +---------------+
     |        |
     |        |                               +---------------+
     |        |--(C)-- Authorization Grant -->| Authorization |
     | Client |                               |     Server    |
     |        |<-(D)----- Access Token -------|               |
     |        |                               +---------------+
     |        |
     |        |                               +---------------+
     |        |--(E)----- Access Token ------>|    Resource   |
     |        |                               |     Server    |
     |        |<-(F)--- Protected Resource ---|               |
     +--------+                               +---------------+

Breaking out of a nested loop

The easiest way to end a double loop would be directly ending the first loop

string TestStr = "The frog jumped over the hill";
char[] KillChar = {'w', 'l'};

for(int i = 0; i < TestStr.Length; i++)
{
    for(int E = 0; E < KillChar.Length; E++)
    {
        if(KillChar[E] == TestStr[i])
        {
            i = TestStr.Length; //Ends First Loop
            break; //Ends Second Loop
        }
    }
}

Difference between jar and war in Java

A .war file has a specific structure in terms of where certain files will be. Other than that, yes, it's just a .jar.

How to terminate a python subprocess launched with shell=True

None of these answers worked for me so Im leaving the code that did work. In my case even after killing the process with .kill() and getting a .poll() return code the process didn't terminate.

Following the subprocess.Popen documentation:

"...in order to cleanup properly a well-behaved application should kill the child process and finish communication..."

proc = subprocess.Popen(...)
try:
    outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()

In my case I was missing the proc.communicate() after calling proc.kill(). This cleans the process stdin, stdout ... and does terminate the process.

What does it mean with bug report captured in android tablet?

It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.

Edit: This is what the forums say:

By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.

To disable:

/system/bin/bugmailer.sh must be deleted/renamed.

There should be a folder on your SD card called "bug reports".

Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948

And this one: http://forum.xda-developers.com/showthread.php?t=1405639

what is the use of "response.setContentType("text/html")" in servlet

From JavaEE docs ServletResponse#setContentType

  • Sets the content type of the response being sent to the client, if the response has not been committed yet.

  • The given content type may include a character encoding specification, for example,

response.setContentType("text/html;charset=UTF-8");

  • The response's character encoding is only set from the given content type if this method is called before getWriter is called.

  • This method may be called repeatedly to change content type and character encoding.

  • This method has no effect if called after the response has been committed. It does not set the response's character encoding if it is called after getWriter has been called or after the response has been committed.

  • Containers must communicate the content type and the character encoding used for the servlet response's writer to the client if the protocol provides a way for doing so. In the case of HTTP, the Content-Type header is used.

need to add a class to an element

Try using setAttribute on the result:

result.setAttribute("class","red"); 

Bash Templating: How to build configuration files from templates with Bash?

Here is another solution: generate a bash script with all the variables and the contents of the template file, that script would look like this:

word=dog           
i=1                
cat << EOF         
the number is ${i} 
the word is ${word}

EOF                

If we feed this script into bash it would produce the desired output:

the number is 1
the word is dog

Here is how to generate that script and feed that script into bash:

(
    # Variables
    echo word=dog
    echo i=1

    # add the template
    echo "cat << EOF"
    cat template.txt
    echo EOF
) | bash

Discussion

  • The parentheses opens a sub shell, its purpose is to group together all the output generated
  • Within the sub shell, we generate all the variable declarations
  • Also in the sub shell, we generate the cat command with HEREDOC
  • Finally, we feed the sub shell output to bash and produce the desired output
  • If you want to redirect this output into a file, replace the last line with:

    ) | bash > output.txt
    

How to add an empty column to a dataframe?

if you want to add column name from a list

df=pd.DataFrame()
a=['col1','col2','col3','col4']
for i in a:
    df[i]=np.nan

Delete empty lines using sed

I am missing the awk solution:

awk 'NF' file

Which would return:

xxxxxx
yyyyyy
zzzzzz

How does this work? Since NF stands for "number of fields", those lines being empty have 0 fiedls, so that awk evaluates 0 to False and no line is printed; however, if there is at least one field, the evaluation is True and makes awk perform its default action: print the current line.

Get Number of Rows returned by ResultSet in Java

You may think JDBC is a rich API and ResultSet has got so many methods then why not just a getCount() method? Well, For many databases e.g. Oracle, MySQL and SQL Server, ResultSet is a streaming API, this means that it does not load (or maybe even fetch) all the rows from the database server. By iterating to the end of the ResultSet you may add significantly to the time taken to execute in certain cases.

Btw, if you have to there are a couple of ways to do it e.g. by using ResultSet.last() and ResultSet.getRow() method, that's not the best way to do it but it works if you absolutely need it.

Though, getting the column count from a ResultSet is easy in Java. The JDBC API provides a ResultSetMetaData class which contains methods to return the number of columns returned by a query and hold by ResultSet.

Change auto increment starting number?

Procedure to auto fix AUTO_INCREMENT value of table

DROP PROCEDURE IF EXISTS update_auto_increment;
DELIMITER //
CREATE PROCEDURE update_auto_increment (_table VARCHAR(64))
BEGIN
    DECLARE _max_stmt VARCHAR(1024);
    DECLARE _stmt VARCHAR(1024);    
    SET @inc := 0;

    SET @MAX_SQL := CONCAT('SELECT IFNULL(MAX(`id`), 0) + 1 INTO @inc FROM ', _table);
    PREPARE _max_stmt FROM @MAX_SQL;
    EXECUTE _max_stmt;
    DEALLOCATE PREPARE _max_stmt;

    SET @SQL := CONCAT('ALTER TABLE ', _table, ' AUTO_INCREMENT =  ', @inc);
    PREPARE _stmt FROM @SQL;
    EXECUTE _stmt;
    DEALLOCATE PREPARE _stmt;
END//
DELIMITER ;

CALL update_auto_increment('your_table_name')

How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

I encountered a similar error with while attempting to play an audio file. At first, it was working, then it stopped working when I started using ChangeDetector's markForCheck method in the same function to trigger a re-render when a promise resolves (I had an issue with view rendering).

When I changed the markForCheck to detectChanges it started working again. I really can't explain what happened, I just thought of dropping this here, perhaps it would help someone.

Case vs If Else If: Which is more efficient?

I believe because cases must be constant values, the switch statement does the equivelent of a goto, so based on the value of the variable it jumps to the right case, whereas in the if/then statement it must evaluate each expression.

PHP expects T_PAAMAYIM_NEKUDOTAYIM?

From Wikipedia:

In PHP, the scope resolution operator is also called Paamayim Nekudotayim (Hebrew: ?????? ?????????), which means “double colon” in Hebrew.

The name "Paamayim Nekudotayim" was introduced in the Israeli-developed Zend Engine 0.5 used in PHP 3. Although it has been confusing to many developers who do not speak Hebrew, it is still being used in PHP 5, as in this sample error message:

$ php -r :: Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM

As of PHP 5.4, error messages concerning the scope resolution operator still include this name, but have clarified its meaning somewhat:

$ php -r :: Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)

From the official PHP documentation:

The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.

When referencing these items from outside the class definition, use the name of the class.

As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static).

Paamayim Nekudotayim would, at first, seem like a strange choice for naming a double-colon. However, while writing the Zend Engine 0.5 (which powers PHP 3), that's what the Zend team decided to call it. It actually does mean double-colon - in Hebrew!

Is there a way to style a TextView to uppercase all of its letters?

By using AppCompat textAllCaps in Android Apps supporting older API's (less than 14)

There is one UI widgets that ships with AppCompat named CompatTextView is a Custom TextView extension that adds support for textAllCaps

For newer android API > 14 you can use :

android:textAllCaps="true"

A simple example:

<android.support.v7.internal.widget.CompatTextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:textAllCaps="true"/>

Source:developer.android

Update:

As it so happens CompatTextView was replaced by AppCompatTextView in latest appcompat-v7 library ~ Eugen Pechanec

PHP: How to get referrer URL?

If $_SERVER['HTTP_REFERER'] variable doesn't seems to work, then you can either use Google Analytics or AddThis Analytics.

TypeError: 'function' object is not subscriptable - Python

You have two objects both named bank_holiday -- one a list and one a function. Disambiguate the two.

bank_holiday[month] is raising an error because Python thinks bank_holiday refers to the function (the last object bound to the name bank_holiday), whereas you probably intend it to mean the list.

How do I fix a NoSuchMethodError?

In my case I had a multi module project and scenario was like com.xyz.TestClass was in module A and as well as in module B and module A was dependent on module B. So while creating a assembly jar I think only one version of class was retained if that doesn't have the invoked method then I was getting NoSuchMethodError runtime exception, but compilation was fine.

Related : https://reflectoring.io/nosuchmethod/

How to strip HTML tags from string in JavaScript?

cleanText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");

Distilled from this website (web.achive).

This regex looks for <, an optional slash /, one or more characters that are not >, then either > or $ (the end of the line)

Examples:

'<div>Hello</div>' ==> 'Hello'
 ^^^^^     ^^^^^^
'Unterminated Tag <b' ==> 'Unterminated Tag '
                  ^^

But it is not bulletproof:

'If you are < 13 you cannot register' ==> 'If you are '
            ^^^^^^^^^^^^^^^^^^^^^^^^
'<div data="score > 42">Hello</div>' ==> ' 42">Hello'
 ^^^^^^^^^^^^^^^^^^          ^^^^^^

If someone is trying to break your application, this regex will not protect you. It should only be used if you already know the format of your input. As other knowledgable and mostly sane people have pointed out, to safely strip tags, you must use a parser.

If you do not have acccess to a convenient parser like the DOM, and you cannot trust your input to be in the right format, you may be better off using a package like sanitize-html, and also other sanitizers are available.

How to make a cross-module variable?

I could achieve cross-module modifiable (or mutable) variables by using a dictionary:

# in myapp.__init__
Timeouts = {} # cross-modules global mutable variables for testing purpose
Timeouts['WAIT_APP_UP_IN_SECONDS'] = 60

# in myapp.mod1
from myapp import Timeouts

def wait_app_up(project_name, port):
    # wait for app until Timeouts['WAIT_APP_UP_IN_SECONDS']
    # ...

# in myapp.test.test_mod1
from myapp import Timeouts

def test_wait_app_up_fail(self):
    timeout_bak = Timeouts['WAIT_APP_UP_IN_SECONDS']
    Timeouts['WAIT_APP_UP_IN_SECONDS'] = 3
    with self.assertRaises(hlp.TimeoutException) as cm:
        wait_app_up(PROJECT_NAME, PROJECT_PORT)
    self.assertEqual("Timeout while waiting for App to start", str(cm.exception))
    Timeouts['WAIT_JENKINS_UP_TIMEOUT_IN_SECONDS'] = timeout_bak

When launching test_wait_app_up_fail, the actual timeout duration is 3 seconds.

Select row on click react-table

I am not familiar with, react-table, so I do not know it has direct support for selecting and deselecting (it would be nice if it had).

If it does not, with the piece of code you already have you can install the onCLick handler. Now instead of trying to attach style directly to row, you can modify state, by for instance adding selected: true to row data. That would trigger rerender. Now you only have to override how are rows with selected === true rendered. Something along lines of:

// Any Tr element will be green if its (row.age > 20) 
<ReactTable
  getTrProps={(state, rowInfo, column) => {
    return {
      style: {
        background: rowInfo.row.selected ? 'green' : 'red'
      }
    }
  }}
/>

Custom ImageView with drop shadow

Here the Implementation of Paul Burkes answer:

public class ShadowImageView extends ImageView {

    public ShadowImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

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

    public ShadowImageView(Context context) {
        super(context);
    }

    private Paint createShadow() {
        Paint mShadow = new Paint();

        float radius = 10.0f;
        float xOffset = 0.0f;
        float yOffset = 2.0f;

        // color=black
        int color = 0xFF000000;
        mShadow.setShadowLayer(radius, xOffset, yOffset, color);


        return mShadow;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Paint mShadow = createShadow();
        Drawable d = getDrawable();
        if (d != null){
            setLayerType(LAYER_TYPE_SOFTWARE, mShadow);
            Bitmap bitmap = ((BitmapDrawable) getDrawable()).getBitmap();
            canvas.drawBitmap(bitmap, 0.0f, 0.0f, mShadow);
        } else {
            super.onDraw(canvas);
        }

    };

}

TODO: execute setLayerType(LAYER_TYPE_SOFTWARE, mShadow); only if API Level is > 10

File URL "Not allowed to load local resource" in the Internet Browser

Now we know what the actual error is can formulate an answer.

Not allowed to load local resource

is a Security exception built into Chrome and other modern browsers. The wording may be different but in some way shape or form they all have security exceptions in place to deal with this scenario.

In the past you could override certain settings or apply certain flags such as

--disable-web-security --allow-file-access-from-files --allow-file-access

in Chrome (See https://stackoverflow.com/a/22027002/692942)

It's there for a reason

At this point though it's worth pointing out that these security exceptions exist for good reason and trying to circumvent them isn't the best idea.

There is another way

As you have access to Classic ASP already you could always build a intermediary page that serves the network based files. You do this using a combination of the ADODB.Stream object and the Response.BinaryWrite() method. Doing this ensures your network file locations are never exposed to the client and due to the flexibility of the script it can be used to load resources from multiple locations and multiple file types.

Here is a basic example (getfile.asp);

<%
Option Explicit

Dim s, id, bin, file, filename, mime

id = Request.QueryString("id")

'id can be anything just use it as a key to identify the 
'file to return. It could be a simple Case statement like this
'or even pulled from a database.
Select Case id
Case "TESTFILE1"
  'The file, mime and filename can be built-up anyway they don't 
  'have to be hard coded.
  file = "\\server\share\Projecten\Protocollen\346\Uitvoeringsoverzicht.xls"     
  mime = "application/vnd.ms-excel"
  'Filename you want to display when downloading the resource.
  filename = "Uitvoeringsoverzicht.xls"

'Assuming other files 
Case ...
End Select

If Len(file & "") > 0 Then
  Set s = Server.CreateObject("ADODB.Stream")
  s.Type = adTypeBinary 'adTypeBinary = 1 See "Useful Links"
  Call s.Open()
  Call s.LoadFromFile(file)
  bin = s.Read()

  'Clean-up the stream and free memory
  Call s.Close()
  Set s = Nothing

  'Set content type header based on mime variable
  Response.ContentType = mime
  'Control how the content is returned using the 
  'Content-Disposition HTTP Header. Using "attachment" forces the resource
  'to prompt the client to download while "inline" allows the resource to
  'download and display in the client (useful for returning images
  'as the "src" of a <img> tag).
  Call Response.AddHeader("Content-Disposition", "attachment;filename=" & filename)
  Call Response.BinaryWrite(bin)
Else
  'Return a 404 if there's no file.
  Response.Status = "404 Not Found"
End If
%>

This example is pseudo coded and as such is untested.

This script can then be used in <a> like this to return the resource;

<a href="/getfile.asp?id=TESTFILE1">Click Here</a>

The could take this approach further and consider (especially for larger files) reading the file in chunks using Response.IsConnected to check whether the client is still there and s.EOS property to check for the end of the stream while the chunks are being read. You could also add to the querystring parameters to set whether you want the file to return in-line or prompt to be downloaded.


Useful Links

PersistenceContext EntityManager injection NullPointerException

If you have any NamedQueries in your entity classes, then check the stack trace for compilation errors. A malformed query which cannot be compiled can cause failure to load the persistence context.

Pretty graphs and charts in Python

Please look at the Open Flash Chart embedding for WHIFF http://aaron.oirt.rutgers.edu/myapp/docs/W1100_1600.openFlashCharts and the amCharts embedding for WHIFF too http://aaron.oirt.rutgers.edu/myapp/amcharts/doc. Thanks.

How do I undo 'git add' before commit?

An addition to the accepted answer, if your mistakenly-added file was huge, you'll probably notice that, even after removing it from the index with 'git reset', it still seems to occupy space in the .git directory.

This is nothing to be worried about; the file is indeed still in the repository, but only as a "loose object". It will not be copied to other repositories (via clone, push), and the space will be eventually reclaimed - though perhaps not very soon. If you are anxious, you can run:

git gc --prune=now

Update (what follows is my attempt to clear some confusion that can arise from the most upvoted answers):

So, which is the real undo of git add?

git reset HEAD <file> ?

or

git rm --cached <file>?

Strictly speaking, and if I'm not mistaken: none.

git add cannot be undone - safely, in general.

Let's recall first what git add <file> actually does:

  1. If <file> was not previously tracked, git add adds it to the cache, with its current content.

  2. If <file> was already tracked, git add saves the current content (snapshot, version) to the cache. In Git, this action is still called add, (not mere update it), because two different versions (snapshots) of a file are regarded as two different items: hence, we are indeed adding a new item to the cache, to be eventually committed later.

In light of this, the question is slightly ambiguous:

I mistakenly added files using the command...

The OP's scenario seems to be the first one (untracked file), we want the "undo" to remove the file (not just the current contents) from the tracked items. If this is the case, then it's ok to run git rm --cached <file>.

And we could also run git reset HEAD <file>. This is in general preferable, because it works in both scenarios: it also does the undo when we wrongly added a version of an already tracked item.

But there are two caveats.

First: There is (as pointed out in the answer) only one scenario in which git reset HEAD doesn't work, but git rm --cached does: a new repository (no commits). But, really, this a practically irrelevant case.

Second: Be aware that git reset HEAD can't magically recover the previously cached file contents, it just resynchronises it from the HEAD. If our misguided git add overwrote a previous staged uncommitted version, we can't recover it. That's why, strictly speaking, we cannot undo [*].

Example:

$ git init
$ echo "version 1" > file.txt
$ git add file.txt   # First add of file.txt
$ git commit -m 'first commit'
$ echo "version 2" > file.txt
$ git add  file.txt   # Stage (don't commit) "version 2" of file.txt
$ git diff --cached file.txt
-version 1
+version 2
$ echo "version 3" > file.txt
$ git diff  file.txt
-version 2
+version 3
$ git add  file.txt    # Oops we didn't mean this
$ git reset HEAD file.txt  # Undo?
$ git diff --cached file.txt  # No dif, of course. stage == HEAD
$ git diff file.txt   # We have irrevocably lost "version 2"
-version 1
+version 3

Of course, this is not very critical if we just follow the usual lazy workflow of doing 'git add' only for adding new files (case 1), and we update new contents via the commit, git commit -a command.


* (Edit: the above is practically correct, but still there can be some slightly hackish/convoluted ways for recovering changes that were staged, but not committed and then overwritten - see the comments by Johannes Matokic and iolsmit)

Starting a node.js server

Run cmd and then run node server.js. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)

Ant: How to execute a command for each file in directory?

ant-contrib is evil; write a custom ant task.

ant-contrib is evil because it tries to convert ant from a declarative style to an imperative style. But xml makes a crap programming language.

By contrast a custom ant task allows you to write in a real language (Java), with a real IDE, where you can write unit tests to make sure you have the behavior you want, and then make a clean declaration in your build script about the behavior you want.

This rant only matters if you care about writing maintainable ant scripts. If you don't care about maintainability by all means do whatever works. :)

Jtf

Rails find_or_create_by more than one attribute?

You can do:

User.find_or_create_by(first_name: 'Penélope', last_name: 'Lopez')
User.where(first_name: 'Penélope', last_name: 'Lopez').first_or_create

Or to just initialize:

User.find_or_initialize_by(first_name: 'Penélope', last_name: 'Lopez')
User.where(first_name: 'Penélope', last_name: 'Lopez').first_or_initialize

This Row already belongs to another table error when trying to add rows?

Why don't you just use CopyToDataTable

DataTable dt = (DataTable)Session["dtAllOrders"];
DataTable dtSpecificOrders = new DataTable();

DataTable orderRows = dt.Select("CustomerID = 2").CopyToDataTable();

Add Class to Object on Page Load

I would recommend using jQuery with this function:

$(document).ready(function(){
 $('#about').addClass('expand');
});

This will add the expand class to an element with id of about when the dom is ready on page load.

Best way to handle list.index(might-not-exist) in python?

Comparison of implementations

Simple comparison on Python 3.8

TL;DR maybeidx2 is faster in general except for arrays (n<100) with lots of misses

def maybeidx1(l, v):
    return l.index(v) if v in l else None

def maybeidx2(l, v):
    try:
        return l.index(v)
    except ValueError:
        return None

Test cases:

a = [*range(100_000)]
# Case 1: index in list
maybeidx1(a, 50_000)
Out[20]: 50000
maybeidx2(a, 50_000)
Out[21]: 50000
# Case 2: index not in list
maybeidx1(a, 100_000) is None
Out[23]: True
maybeidx2(a, 100_000) is None
Out[24]: True

Timing case 1

%timeit maybeidx1(a, 50_000)
1.06 ms ± 15.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit maybeidx2(a, 50_000)
530 µs ± 8.47 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Timing case 2

%timeit maybeidx1(a, 100_000)
1.07 ms ± 21 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit maybeidx2(a, 100_000)
1.07 ms ± 16.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Result

Use the maybeidx2 method for larger arrays. This is faster due to maybeidx1 having two scans of the array in search of the value - this is still O(n) time but has a constant multiplier of 2 and thus slower in practice. This holds in the case of the value being present in the list. When the value is not present, these times will be roughly equal; they both have to scan the full array exactly once, then return None. The overhead of the try-except is negligible, even with an array size of 10 - unless case two occurs. Then the try-except overhead is noticeable. Example:

a = [*range(10)]
%timeit maybeidx1(a, 10)
191 ns ± 2.61 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
%timeit maybeidx2(a, 10)
566 ns ± 5.93 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

This overhead becomes negligible (on my machine) when a has above 100 elements.

UUID max character length

Section 3 of RFC4122 provides the formal definition of UUID string representations. It's 36 characters (32 hex digits + 4 dashes).

Sounds like you need to figure out where the invalid 60-char IDs are coming from and decide 1) if you want to accept them, and 2) what the max length of those IDs might be based on whatever API is used to generate them.

Set selected item of spinner programmatically

In my case, this code saved my day:

public static void selectSpinnerItemByValue(Spinner spnr, long value) {
    SpinnerAdapter adapter = spnr.getAdapter();
    for (int position = 0; position < adapter.getCount(); position++) {
        if(adapter.getItemId(position) == value) {
            spnr.setSelection(position);
            return;
        }
    }
}

Add element to a list In Scala

I will try to explain the results of all the commands you tried.

scala> val l = 1.0 :: 5.5 :: Nil
l: List[Double] = List(1.0, 5.5)

First of all, List is a type alias to scala.collection.immutable.List (defined in Predef.scala).

Using the List companion object is more straightforward way to instantiate a List. Ex: List(1.0,5.5)

scala> l
res0: List[Double] = List(1.0, 5.5)

scala> l ::: List(2.2, 3.7)
res1: List[Double] = List(1.0, 5.5, 2.2, 3.7)

::: returns a list resulting from the concatenation of the given list prefix and this list

The original List is NOT modified

scala> List(l) :+ 2.2
res2: List[Any] = List(List(1.0, 5.5), 2.2)

List(l) is a List[List[Double]] Definitely not what you want.

:+ returns a new list consisting of all elements of this list followed by elem.

The type is List[Any] because it is the common superclass between List[Double] and Double

scala> l
res3: List[Double] = List(1.0, 5.5)

l is left unmodified because no method on immutable.List modified the List.

HTTP Get with 204 No Content: Is that normal

The POST/GET with 204 seems fine in the first sight and will also work.

Documentation says, 2xx -- This class of status codes indicates the action requested by the client was received, understood, accepted, and processed successfully. whereas 4xx -- The 4xx class of status code is intended for situations in which the client seems to have erred.

Since, the request was successfully received, understood and processed on server. The result was that the resource was not found. So, in this case this was not an error on the client side or the client has not erred.

Hence this should be a series 2xx code and not 4xx. Sending 204 (No Content) in this case will be better than a 404 or 410 response.

What is the difference between 'protected' and 'protected internal'?

public - The members (Functions & Variables) declared as public can be accessed from anywhere.

private - Private members cannot be accessed from outside the class. This is the default access specifier for a member, i.e if you do not specify an access specifier for a member (variable or function), it will be considered as private. Therefore, string PhoneNumber; is equivalent to private string PhoneNumber.

protected - Protected members can be accessed only from the child classes.

internal - It can be accessed only within the same assembly.

protected internal - It can be accessed within the same assembly as well as in derived class.

How to compare pointers?

The == operator on pointers will compare their numeric address and hence determine if they point to the same object.

using favicon with css

You don't need to - if the favicon is place in the root at favicon.ico, browsers will automatically pick it up.

If you don't see it working, clear your cache etc, it does work without the markup. You only need to use the code if you want to call it something else, or put it on a CDN for instance.

IntelliJ does not show project folders

OS:Mac && IDE: IntelliJ && Project: Maven build

  1. Navigate to File>Project Structure>Modules.
  2. In right-hand area; list of modules would be present.
  3. Delete the default one selected and close IntelliJ.
  4. Next Open again; IntelliJ will ask if you want to treat the project as Maven project.
  5. Accept that popup and you are good to go.

How to drop a PostgreSQL database if there are active connections to it?

In Linux command Prompt, I would first stop all postgresql processes that are running by tying this command sudo /etc/init.d/postgresql restart

type the command bg to check if other postgresql processes are still running

then followed by dropdb dbname to drop the database

sudo /etc/init.d/postgresql restart
bg
dropdb dbname

This works for me on linux command prompt

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

Use ==:

pip install django_modeltranslation==0.4.0-beta2

Why are hexadecimal numbers prefixed with 0x?

The preceding 0 is used to indicate a number in base 2, 8, or 16.

In my opinion, 0x was chosen to indicate hex because 'x' sounds like hex.

Just my opinion, but I think it makes sense.

Good Day!

How to center canvas in html5

Give the canvas the following css style properties:

canvas {
    padding-left: 0;
    padding-right: 0;
    margin-left: auto;
    margin-right: auto;
    display: block;
    width: 800px;
}

Edit

Since this answer is quite popular, let me add a little bit more details.

The above properties will horizontally center the canvas, div or whatever other node you have relative to it's parent. There is no need to change the top or bottom margins and paddings. You specify a width and let the browser fill the remaining space with the auto margins.

However, if you want to type less, you could use whatever css shorthand properties you wish, such as

canvas {
    padding: 0;
    margin: auto;
    display: block;
    width: 800px;
}

Centering the canvas vertically requires a different approach however. You need to use absolute positioning, and specify both the width and the height. Then set the left, right, top and bottom properties to 0 and let the browser fill the remaining space with the auto margins.

canvas {
    padding: 0;
    margin: auto;
    display: block;
    width: 800px;
    height: 600px;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}

The canvas will center itself based on the first parent element that has position set to relative or absolute, or the body if none is found.

Another approach would be to use display: flex, that is available in IE11

Also, make sure you use a recent doctype such as xhtml or html 5.

Python: Finding differences between elements of a list

>>> t
[1, 3, 6]
>>> [j-i for i, j in zip(t[:-1], t[1:])]  # or use itertools.izip in py2k
[2, 3]

Data binding for TextBox

We can use following code

textBox1.DataBindings.Add("Text", model, "Name", false, DataSourceUpdateMode.OnPropertyChanged);

Where

  • "Text" – the property of textbox
  • model – the model object enter code here
  • "Name" – the value of model which to bind the textbox.

Add target="_blank" in CSS

Another way to use target="_blank" is:

onclick="this.target='_blank'"

Example:

<a href="http://www.url.com" onclick="this.target='_blank'">Your Text<a>

How to use filesaver.js

For people who want to load it in the console :

var s = document.createElement('script');
s.type = 'text/javascript';
s.src = 'https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js';
document.body.appendChild(s);

Then :

saveAs(new Blob([data], {type: "application/octet-stream ;charset=utf-8"}), "video.ts")

File will be save when you're out of a breakpoint (at least on Chrome)

What's the best UI for entering date of birth?

As mentioned in this Jakob Nielsen article, drop down lists should be avoided for data that is well known to the user:

Menus of data well known to users, such as the month and year of their birth. Such information is often hardwired into users' fingers, and having to select such options from a menu breaks the standard paradigm for entering information and can even create more work for users.

The ideal solution is likely something like follows:

  • Provide 3 separate text boxes for day, month, and year (labeled appropriately)
  • Sort the text boxes according to the user's culture.
  • Day and Month text boxes should be sized so that a 2 digit input is assumed.
  • Year text box should be sized so that a 4 digit year is assumed.
  • Allow the user to enter a 2 or 4 digit year. Assume a 2 digit year is 1900, and update the textbox to reflect this onBlur (or on a following confirmation step).
  • Allow the user to enter either a month number OR month name.

EDIT: Here is how we implemented our DOB picker: Masked text input field with HTML5 regex to force the numeric keyboard on iOS devices.

http://www.huntercourse.com/usa/texas/

JUnit Testing Exceptions

If your constructor is similar to this one:

public Example(String example) {
    if (example == null) {
        throw new NullPointerException();
    }
    //do fun things with valid example here
}

Then, when you run this JUnit test you will get a green bar:

@Test(expected = NullPointerException.class)
public void constructorShouldThrowNullPointerException() {
    Example example = new Example(null);
}

Can't load IA 32-bit .dll on a AMD 64-bit platform

Go to

Project properties >> Run >> VM options

and put this address:

-Djava.library.path="C:\opencv\build\java\x64"

Gradients in Internet Explorer 9

As of version 11, Opera supports linear gradients with the -o- vendor prefix. Chris Mills wrote a Dev.Opera article about it: http://dev.opera.com/articles/view/css3-linear-gradients/

Radial gradients are still in the works (both in the spec, and within Opera).

How can I get Maven to stop attempting to check for updates for artifacts from a certain group from maven-central-repo?

Something that is now available in maven as well is

mvn goal --no-snapshot-updates

or in short

mvn goal -nsu

jQuery send string as POST parameters

I was facing the problem in passing string value to string parameters in Ajax. After so much googling, i have come up with a custom solution as below.

var bar = 'xyz';
var calibri = 'no$libri';

$.ajax({
   type: "POST",
   dataType: "json",
   contentType: "application/json; charset=utf-8",
   url: "http://nakolesah.ru/",
   data: '{ foo: \'' + bar + '\', zoo: \'' + calibri + '\'}',
   success: function(msg){
       alert('wow'+msg);
   },
});

Here, bar and calibri are two string variables and you can pass whatever string value to respective string parameters in web method.

Persistent invalid graphics state error when using ggplot2

The solution is to simply reinstall ggplot2. Maybe there is an incompatibility between the R version you are using, and your installed version of ggplot2. Alternatively, something might have gone wrong while installing ggplot2 earlier, causing the issue you see.

Multi-key dictionary in c#?

I wrote and have used this with success.

public class MultiKeyDictionary<K1, K2, V> : Dictionary<K1, Dictionary<K2, V>>  {

    public V this[K1 key1, K2 key2] {
        get {
            if (!ContainsKey(key1) || !this[key1].ContainsKey(key2))
                throw new ArgumentOutOfRangeException();
            return base[key1][key2];
        }
        set {
            if (!ContainsKey(key1))
                this[key1] = new Dictionary<K2, V>();
            this[key1][key2] = value;
        }
    }

    public void Add(K1 key1, K2 key2, V value) {
            if (!ContainsKey(key1))
                this[key1] = new Dictionary<K2, V>();
            this[key1][key2] = value;
    }

    public bool ContainsKey(K1 key1, K2 key2) {
        return base.ContainsKey(key1) && this[key1].ContainsKey(key2);
    }

    public new IEnumerable<V> Values {
        get {
            return from baseDict in base.Values
                   from baseKey in baseDict.Keys
                   select baseDict[baseKey];
        }
    } 

}


public class MultiKeyDictionary<K1, K2, K3, V> : Dictionary<K1, MultiKeyDictionary<K2, K3, V>> {
    public V this[K1 key1, K2 key2, K3 key3] {
        get {
            return ContainsKey(key1) ? this[key1][key2, key3] : default(V);
        }
        set {
            if (!ContainsKey(key1))
                this[key1] = new MultiKeyDictionary<K2, K3, V>();
            this[key1][key2, key3] = value;
        }
    }

    public bool ContainsKey(K1 key1, K2 key2, K3 key3) {
        return base.ContainsKey(key1) && this[key1].ContainsKey(key2, key3);
    }
}

public class MultiKeyDictionary<K1, K2, K3, K4, V> : Dictionary<K1, MultiKeyDictionary<K2, K3, K4, V>> {
    public V this[K1 key1, K2 key2, K3 key3, K4 key4] {
        get {
            return ContainsKey(key1) ? this[key1][key2, key3, key4] : default(V);
        }
        set {
            if (!ContainsKey(key1))
                this[key1] = new MultiKeyDictionary<K2, K3, K4, V>();
            this[key1][key2, key3, key4] = value;
        }
    }

    public bool ContainsKey(K1 key1, K2 key2, K3 key3, K4 key4) {
        return base.ContainsKey(key1) && this[key1].ContainsKey(key2, key3, key4);
    }
}

public class MultiKeyDictionary<K1, K2, K3, K4, K5, V> : Dictionary<K1, MultiKeyDictionary<K2, K3, K4, K5, V>> {
    public V this[K1 key1, K2 key2, K3 key3, K4 key4, K5 key5] {
        get {
            return ContainsKey(key1) ? this[key1][key2, key3, key4, key5] : default(V);
        }
        set {
            if (!ContainsKey(key1))
                this[key1] = new MultiKeyDictionary<K2, K3, K4, K5, V>();
            this[key1][key2, key3, key4, key5] = value;
        }
    }

    public bool ContainsKey(K1 key1, K2 key2, K3 key3, K4 key4, K5 key5) {
        return base.ContainsKey(key1) && this[key1].ContainsKey(key2, key3, key4, key5);
    }
}

public class MultiKeyDictionary<K1, K2, K3, K4, K5, K6, V> : Dictionary<K1, MultiKeyDictionary<K2, K3, K4, K5, K6, V>> {
    public V this[K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6] {
        get {
            return ContainsKey(key1) ? this[key1][key2, key3, key4, key5, key6] : default(V);
        }
        set {
            if (!ContainsKey(key1))
                this[key1] = new MultiKeyDictionary<K2, K3, K4, K5, K6, V>();
            this[key1][key2, key3, key4, key5, key6] = value;
        }
    }
    public bool ContainsKey(K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6) {
        return base.ContainsKey(key1) && this[key1].ContainsKey(key2, key3, key4, key5, key6);
    }
}

public class MultiKeyDictionary<K1, K2, K3, K4, K5, K6, K7, V> : Dictionary<K1, MultiKeyDictionary<K2, K3, K4, K5, K6, K7, V>> {
    public V this[K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6, K7 key7] {
        get {
            return ContainsKey(key1) ? this[key1][key2, key3, key4, key5, key6, key7] : default(V);
        }
        set {
            if (!ContainsKey(key1))
                this[key1] = new MultiKeyDictionary<K2, K3, K4, K5, K6, K7, V>();
            this[key1][key2, key3, key4, key5, key6, key7] = value;
        }
    }
    public bool ContainsKey(K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6, K7 key7) {
        return base.ContainsKey(key1) && this[key1].ContainsKey(key2, key3, key4, key5, key6, key7);
    }
}

public class MultiKeyDictionary<K1, K2, K3, K4, K5, K6, K7, K8, V> : Dictionary<K1, MultiKeyDictionary<K2, K3, K4, K5, K6, K7, K8, V>> {
    public V this[K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6, K7 key7, K8 key8] {
        get {
            return ContainsKey(key1) ? this[key1][key2, key3, key4, key5, key6, key7, key8] : default(V);
        }
        set {
            if (!ContainsKey(key1))
                this[key1] = new MultiKeyDictionary<K2, K3, K4, K5, K6, K7, K8, V>();
            this[key1][key2, key3, key4, key5, key6, key7, key8] = value;
        }
    }
    public bool ContainsKey(K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6, K7 key7, K8 key8) {
        return base.ContainsKey(key1) && this[key1].ContainsKey(key2, key3, key4, key5, key6, key7, key8);
    }
}

public class MultiKeyDictionary<K1, K2, K3, K4, K5, K6, K7, K8, K9, V> : Dictionary<K1, MultiKeyDictionary<K2, K3, K4, K5, K6, K7, K8, K9, V>> {
    public V this[K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6, K7 key7, K8 key8, K9 key9] {
        get {
            return ContainsKey(key1) ? this[key1][key2, key3, key4, key5, key6, key7, key8, key9] : default(V);
        }
        set {
            if (!ContainsKey(key1))
                this[key1] = new MultiKeyDictionary<K2, K3, K4, K5, K6, K7, K8, K9, V>();
            this[key1][key2, key3, key4, key5, key6, key7, key8, key9] = value;
        }
    }
    public bool ContainsKey(K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6, K7 key7, K8 key8, K9 key9) {
        return base.ContainsKey(key1) && this[key1].ContainsKey(key2, key3, key4, key5, key6, key7, key8, key9);
    }
}

public class MultiKeyDictionary<K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, V> : Dictionary<K1, MultiKeyDictionary<K2, K3, K4, K5, K6, K7, K8, K9, K10, V>> {
    public V this[K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6, K7 key7, K8 key8, K9 key9, K10 key10] {
        get {
            return ContainsKey(key1) ? this[key1][key2, key3, key4, key5, key6, key7, key8, key9, key10] : default(V);
        }
        set {
            if (!ContainsKey(key1))
                this[key1] = new MultiKeyDictionary<K2, K3, K4, K5, K6, K7, K8, K9, K10, V>();
            this[key1][key2, key3, key4, key5, key6, key7, key8, key9, key10] = value;
        }
    }
    public bool ContainsKey(K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6, K7 key7, K8 key8, K9 key9, K10 key10) {
        return base.ContainsKey(key1) && this[key1].ContainsKey(key2, key3, key4, key5, key6, key7, key8, key9, key10);
    }
}

public class MultiKeyDictionary<K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, V> : Dictionary<K1, MultiKeyDictionary<K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, V>> {
    public V this[K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6, K7 key7, K8 key8, K9 key9, K10 key10, K11 key11] {
        get {
            return ContainsKey(key1) ? this[key1][key2, key3, key4, key5, key6, key7, key8, key9, key10, key11] : default(V);
        }
        set {
            if (!ContainsKey(key1))
                this[key1] = new MultiKeyDictionary<K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, V>();
            this[key1][key2, key3, key4, key5, key6, key7, key8, key9, key10, key11] = value;
        }
    }
    public bool ContainsKey(K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6, K7 key7, K8 key8, K9 key9, K10 key10, K11 key11) {
        return base.ContainsKey(key1) && this[key1].ContainsKey(key2, key3, key4, key5, key6, key7, key8, key9, key10, key11);
    }
}

Eclipse memory settings when getting "Java Heap Space" and "Out of Memory"

My FLashBuilder is crashing all the time when I try to release a new version or I abuse of the "Mark Occurrences" and "Link with editor" features.

I have improved significantly my flash performance by following this steps http://www.redcodelabs.com/2012/03/eclipse-speed-up-flashbuilder/

Especially by setting the FlashBuilder.ini to the following configuration

-vm
C:/jdk1.6.0_25/bin
-startup
plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar
–launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.100.v20110502
-product
org.eclipse.epp.package.jee.product
–launcher.defaultAction
openFile
–launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
–launcher.XXMaxPermSize
256m
–launcher.defaultAction
openFile
-vmargs
-server
-Dosgi.requiredJavaVersion=1.5
-Xmn128m
-Xms1024m
-Xmx1024m
-Xss2m
-XX:PermSize=128m
-XX:MaxPermSize=128m
-XX:+UseParallelGC

My hardware configuration is intel i3 cpu, 4gb DDR3, windows 7 64Bit.

CSS container div not getting height

Try inserting this clearing div before the last </div>

<div style="clear: both; line-height: 0;">&nbsp;</div>

How to control size of list-style-type disc in CSS?

Since I don't know how to control only the list marker size with CSS and no one's offered this yet, you can use :before content to generate the bullets:

li {
    list-style: none;
    font-size: 20px;
}

li:before {
    content:"·";
    font-size:120px;
    vertical-align:middle;
    line-height:20px;
}

Demo: http://jsfiddle.net/4wDL5/

The markers are limited to appearing "inside" with this particular CSS, although you could change it. It's definitely not the best option (browser must support generated content, so no IE6 or 7), but it might be the easiest - plus you can choose any character you want for the marker.

If you go the image route, see list-style-image.

How to import cv2 in python3?

Your screenshot shows you doing a pip install from the python terminal which is wrong. Do that outside the python terminal. Also the package I believe you want is:

pip install opencv-python

Since you're running on Windows, I might look at the official install manual: https://breakthrough.github.io/Installing-OpenCV

opencv2 is ONLY compatible with Python3 if you do so by compiling the source code. See the section under opencv supported python versions: https://pypi.org/project/opencv-python

Make Error 127 when running trying to compile code

Error 127 means one of two things:

  1. file not found: the path you're using is incorrect. double check that the program is actually in your $PATH, or in this case, the relative path is correct -- remember that the current working directory for a random terminal might not be the same for the IDE you're using. it might be better to just use an absolute path instead.
  2. ldso is not found: you're using a pre-compiled binary and it wants an interpreter that isn't on your system. maybe you're using an x86_64 (64-bit) distro, but the prebuilt is for x86 (32-bit). you can determine whether this is the answer by opening a terminal and attempting to execute it directly. or by running file -L on /bin/sh (to get your default/native format) and on the compiler itself (to see what format it is).

if the problem is (2), then you can solve it in a few diff ways:

  1. get a better binary. talk to the vendor that gave you the toolchain and ask them for one that doesn't suck.
  2. see if your distro can install the multilib set of files. most x86_64 64-bit distros allow you to install x86 32-bit libraries in parallel.
  3. build your own cross-compiler using something like crosstool-ng.
  4. you could switch between an x86_64 & x86 install, but that seems a bit drastic ;).

How to detect scroll position of page using jQuery

You are looking for the window.scrollTop() function.

$(window).scroll(function() {
    var height = $(window).scrollTop();

    if(height  > some_number) {
        // do something
    }
});

How to send a Post body in the HttpClient request in Windows Phone 8?

This depends on what content do you have. You need to initialize your requestMessage.Content property with new HttpContent. For example:

...
// Add request body
if (isPostRequest)
{
    requestMessage.Content = new ByteArrayContent(content);
}
...

where content is your encoded content. You also should include correct Content-type header.

UPDATE:

Oh, it can be even nicer (from this answer):

requestMessage.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}", Encoding.UTF8, "application/json");

Oracle Add 1 hour in SQL

The calculation is simple

if you want to add 1 hour in the date .

every day have 24 hour , you can add .

select sysdate + 1/24 from dual; 

if you want 1 day to add

select sysdate + 24/24 from dual; 

or 

select sysdate + 1 from dual; 

same as for 2, 3 , 4 day

For static date you have the answer below.

How can I split this comma-delimited string in Python?

Question is a little vague.

list_of_lines = multiple_lines.split("\n")
for line in list_of_lines:
    list_of_items_in_line = line.split(",")
    first_int = int(list_of_items_in_line[0])

etc.

How to create JNDI context in Spring Boot with Embedded Tomcat Container

Please note instead of

public TomcatEmbeddedServletContainerFactory tomcatFactory()

I had to use the following method signature

public EmbeddedServletContainerFactory embeddedServletContainerFactory() 

Redirecting to a certain route based on condition

After some diving through some documentation and source code, I think I got it working. Perhaps this will be useful for someone else?

I added the following to my module configuration:

angular.module(...)
 .config( ['$routeProvider', function($routeProvider) {...}] )
 .run( function($rootScope, $location) {

    // register listener to watch route changes
    $rootScope.$on( "$routeChangeStart", function(event, next, current) {
      if ( $rootScope.loggedUser == null ) {
        // no logged user, we should be going to #login
        if ( next.templateUrl != "partials/login.html" ) {
          // not going to #login, we should redirect now
          $location.path( "/login" );
        }
      }         
    });
 })

The one thing that seems odd is that I had to test the partial name (login.html) because the "next" Route object did not have a url or something else. Maybe there's a better way?

How do I print a datetime in the local timezone?

I believe the best way to do this is to use the LocalTimezone class defined in the datetime.tzinfo documentation (goto http://docs.python.org/library/datetime.html#tzinfo-objects and scroll down to the "Example tzinfo classes" section):

Assuming Local is an instance of LocalTimezone

t = datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=utc)
local_t = t.astimezone(Local)

then str(local_t) gives:

'2009-07-11 04:44:59.193982+10:00'

which is what you want.

(Note: this may look weird to you because I'm in New South Wales, Australia which is 10 or 11 hours ahead of UTC)

How to Apply global font to whole HTML document

Use the following css:

* {
    font: Verdana, Arial, 'sans-serif' !important;/* <-- fonts */
}

The *-selector means any/all elements, but will obviously be on the bottom of the food chain when it comes to overriding more specific selectors.

Note that the !important-flag will render the font-style for * to be absolute, even if other selectors have been used to set the text (for example, the body or maybe a p).

Understanding the Linux oom-killer's logs

This webpage have an explanation and a solution.

The solution is:

To fix this problem the behavior of the kernel has to be changed, so it will no longer overcommit the memory for application requests. Finally I have included those mentioned values into the /etc/sysctl.conf file, so they get automatically applied on start-up:

vm.overcommit_memory = 2

vm.overcommit_ratio = 80

What is the best way to declare global variable in Vue.js?

a vue3 replacement of this answer:

// Vue3

const app = Vue.createApp({})
app.config.globalProperties.$hostname = 'http://localhost:3000'


app.component('a-child-component', {
  mounted() {
    console.log(this.$hostname) // 'http://localhost:3000'
  }
})

How to replace comma (,) with a dot (.) using java

For the current information you are giving, it will be enought with this simple regex to do the replacement:

str.replaceAll(",", ".");

Python: Get HTTP headers from urllib2.urlopen call?

One-liner:

$ python -c "import urllib2; print urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1)).open(urllib2.Request('http://google.com'))"

Gradle: Could not determine java version from '11.0.2'

tl;dr: downgrade java by running update-alternatives


My system gradle version was 4.4.1, and the gradle wrapper version was 4.0. After running the command given by several other answers:

gradle wrapper --gradle-version 4.4.1

I still had the same error:

FAILURE: Build failed with an exception.

* What went wrong:
Could not determine java version from '11.0.4'.

It turns out java 11 wasn't supported until gradle 4.8, and my software repositories only had 4.4.1. (Also, upgrading to newer gradle version might have been incompatible with the package I was trying to compile.)

The answer was to downgrade java. My system actually had java8 already installed, and it was easy to switch between java versions by running this command and following the instructions:

sudo update-alternatives --config java

How to install toolbox for MATLAB

Use ver it will list all the installed toolboxes and versions of the toolbox.

Created Button Click Event c#

You need an event handler which will fire when the button is clicked. Here is a quick way -

  var button = new Button();
  button.Text = "my button";

  this.Controls.Add(button);

  button.Click += (sender, args) =>
                       {
                           MessageBox.Show("Some stuff");
                           Close();
                       };

But it would be better to understand a bit more about buttons, events, etc.

If you use the visual studio UI to create a button and double click the button in design mode, this will create your event and hook it up for you. You can then go to the designer code (the default will be Form1.Designer.cs) where you will find the event:

 this.button1.Click += new System.EventHandler(this.button1_Click);

You will also see a LOT of other information setup for the button, such as location, etc. - which will help you create one the way you want and will improve your understanding of creating UI elements. E.g. a default button gives this on my 2012 machine:

        this.button1.Location = new System.Drawing.Point(128, 214);
        this.button1.Name = "button1";
        this.button1.Size = new System.Drawing.Size(75, 23);
        this.button1.TabIndex = 1;
        this.button1.Text = "button1";
        this.button1.UseVisualStyleBackColor = true;

As for closing the Form, it is as easy as putting Close(); within your event handler:

private void button1_Click(object sender, EventArgs e)
    {
       MessageBox.Show("some text");
       Close();
    }

How to make Java work with SQL Server?

The driver you are using is the MS SQL server 2008 driver (sqljdbc4.jar). As stated in the MSDN page it requires Java 6+ to work.

http://msdn.microsoft.com/en-us/library/ms378526.aspx

sqljdbc4.jar class library requires a Java Runtime Environment (JRE) of version 6.0 or later.

I'd suggest using the 2005 driver which I beleive is in (sqljdbc.jar) or as Oxbow_Lakes says try the jTDS driver (http://jtds.sourceforge.net/).

To draw an Underline below the TextView in Android

In Kotlin you can create extension property:

inline var TextView.underline: Boolean
    set(visible) {
        paintFlags = if (visible) paintFlags or Paint.UNDERLINE_TEXT_FLAG
        else paintFlags and Paint.UNDERLINE_TEXT_FLAG.inv()
    }
    get() = paintFlags and Paint.UNDERLINE_TEXT_FLAG == Paint.UNDERLINE_TEXT_FLAG

And use:

textView.underline = true

Are PostgreSQL column names case-sensitive?

The column names which are mixed case or uppercase have to be double quoted in PostgresQL. So best convention will be to follow all small case with underscore.

read input separated by whitespace(s) or newline...?

Use 'q' as the the optional argument to getline.

#include <iostream>
#include <sstream>

int main() {
    std::string numbers_str;
    getline( std::cin, numbers_str, 'q' );

    int number;
    for ( std::istringstream numbers_iss( numbers_str );
          numbers_iss >> number; ) {
        std::cout << number << ' ';
    }
}

http://ideone.com/I2vWl

add elements to object array

I know this is old, but came across it looking for a simpler way, and this is how i do it, just create a new list of the same object and add it to the one you want to use e.g.

Subject[] subjectsList = {new Subject1{....}, new Subject2{....}, new Subject3{....}} 
univStudent.subjects = subjectsList ;

Convert string to hex-string in C#

According to this snippet here, this approach should be good for long strings:

private string StringToHex(string hexstring)
{
    StringBuilder sb = new StringBuilder();
    foreach (char t in hexstring)
    { 
        //Note: X for upper, x for lower case letters
        sb.Append(Convert.ToInt32(t).ToString("x")); 
    }
    return sb.ToString();
}

usage:

string result = StringToHex("Hello world"); //returns "48656c6c6f20776f726c64"

Another approach in one line

string input = "Hello world";
string result = String.Concat(input.Select(x => ((int)x).ToString("x")));

Trigger change event of dropdown

For some reason, the other jQuery solutions provided here worked when running the script from console, however, it did not work for me when triggered from Chrome Bookmarklets.

Luckily, this Vanilla JS solution (the triggerChangeEvent function) did work:

_x000D_
_x000D_
/**_x000D_
  * Trigger a `change` event on given drop down option element._x000D_
  * WARNING: only works if not already selected._x000D_
  * @see https://stackoverflow.com/questions/902212/trigger-change-event-of-dropdown/58579258#58579258_x000D_
  */_x000D_
function triggerChangeEvent(option) {_x000D_
  // set selected property_x000D_
  option.selected = true;_x000D_
  _x000D_
  // raise event on parent <select> element_x000D_
  if ("createEvent" in document) {_x000D_
    var evt = document.createEvent("HTMLEvents");_x000D_
    evt.initEvent("change", false, true);_x000D_
    option.parentNode.dispatchEvent(evt);_x000D_
  }_x000D_
  else {_x000D_
    option.parentNode.fireEvent("onchange");_x000D_
  }_x000D_
}_x000D_
_x000D_
// ################################################_x000D_
// Setup our test case_x000D_
// ################################################_x000D_
_x000D_
(function setup() {_x000D_
  const sel = document.querySelector('#fruit');_x000D_
  sel.onchange = () => {_x000D_
    document.querySelector('#result').textContent = sel.value;_x000D_
  };_x000D_
})();_x000D_
_x000D_
function runTest() {_x000D_
  const sel = document.querySelector('#selector').value;_x000D_
  const optionEl = document.querySelector(sel);_x000D_
  triggerChangeEvent(optionEl);_x000D_
}
_x000D_
<select id="fruit">_x000D_
  <option value="">(select a fruit)</option>_x000D_
  <option value="apple">Apple</option>_x000D_
  <option value="banana">Banana</option>_x000D_
  <option value="pineapple">Pineapple</option>_x000D_
</select>_x000D_
_x000D_
<p>_x000D_
  You have selected: <b id="result"></b>_x000D_
</p>_x000D_
<p>_x000D_
  <input id="selector" placeholder="selector" value="option[value='banana']">_x000D_
  <button onclick="runTest()">Trigger select!</button>_x000D_
</p>
_x000D_
_x000D_
_x000D_

Chrome hangs after certain amount of data transfered - waiting for available socket

simple and correct solution is put off preload your audio and video file from setting and recheck your page your problem of waiting for available socket will resolved ...

if you use jplayer then replace preload:"metadata" to preload:"none" from jplayer JS file ...

preload:"metadata" is the default value which play your audio/video file on page load thats why google chrome showing "waiting for available socket" error

Sass Nesting for :hover does not work

For concatenating selectors together when nesting, you need to use the parent selector (&):

.class {
    margin:20px;
    &:hover {
        color:yellow;
    }
}

How to tell if browser/tab is active

You would use the focus and blur events of the window:

var interval_id;
$(window).focus(function() {
    if (!interval_id)
        interval_id = setInterval(hard_work, 1000);
});

$(window).blur(function() {
    clearInterval(interval_id);
    interval_id = 0;
});

To Answer the Commented Issue of "Double Fire" and stay within jQuery ease of use:

$(window).on("blur focus", function(e) {
    var prevType = $(this).data("prevType");

    if (prevType != e.type) {   //  reduce double fire issues
        switch (e.type) {
            case "blur":
                // do work
                break;
            case "focus":
                // do work
                break;
        }
    }

    $(this).data("prevType", e.type);
})

Click to view Example Code Showing it working (JSFiddle)

VBA: Counting rows in a table (list object)

You can use this:

    Range("MyTable[#Data]").Rows.Count

You have to distinguish between a table which has either one row of data or no data, as the previous code will return "1" for both cases. Use this to test for an empty table:

    If WorksheetFunction.CountA(Range("MyTable[#Data]"))

How to redirect the output of the time command to a file in Linux?

Try

{ time sleep 1 ; } 2> time.txt

which combines the STDERR of "time" and your command into time.txt

Or use

{ time sleep 1 2> sleep.stderr ; } 2> time.txt

which puts STDERR from "sleep" into the file "sleep.stderr" and only STDERR from "time" goes into "time.txt"

Adding an image to a project in Visual Studio

If you're having an issue where the Resources added are images and are not getting copied to your build folder on compiling. You need to change the "Build Action" to None from Resource ( which is the default) and change the Copy to "If Newer" or "Always" as shown below :

enter image description here

javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25

This should not happen. Can you try doing this? Use the system properties and set the property as below:

Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", "10.101.3.229");

And if you have a port associated, then set this as well.

properties.setProperty("mail.smtp.port", "8080");

How to debug (only) JavaScript in Visual Studio?

First open Visual studio ..select your project in solution explorer..Right click and choose option "browse with" then set IE as default browser.

enter image description here Now open IE ..go to
Tools >> Internet option >> Advance>> uncheck the checkbox having "Disable Script Debugging (Internet Explorer). and then click Apply and OK and you are done ..

Now you can set breakpoints in your JS file and then hit the debug button in VS..

enter image description here

EDIT:- For asp.net web application right click on the page which is your startup page(say default.aspx) and perform the same steps. :)

Get the Id of current table row with Jquery

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
    <title>Untitled</title>

<script type="text/javascript"><!--

function getVal(e) {
    var targ;
    if (!e) var e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;

    alert(targ.innerHTML);
}

onload = function() {
    var t = document.getElementById("main").getElementsByTagName("td");
    for ( var i = 0; i < t.length; i++ )
        t[i].onclick = getVal;
}

</script>



<body>

<table id="main"><tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
</tr><tr>
    <td>5</td>
    <td>6</td>
    <td>7</td>
    <td>8</td>
</tr><tr>
    <td>9</td>
    <td>10</td>
    <td>11</td>
    <td>12</td>
</tr></table>

</body>
</html>

How to make zsh run as a login shell on Mac OS X (in iTerm)?

The command to change the shell at startup is chsh -s <path_to_shell>. The default shells in mac OS X are installed inside the bin directory so if you want to change to the default zsh then you would use the following

chsh -s /bin/zsh

If you're using different version of zsh then you might have to add that version to /etc/shells to avoid the nonstandard shell message. For example if you want home-brew's version of zsh then you have to add /usr/local/bin/zsh to the aforementioned file which you can do in one command sudo sh -c "echo '/usr/local/bin/zsh' >> /etc/shells" and then run

chsh -s /usr/local/bin/zsh

Or if you want to do the whole thing in one command just copy and paste this if you have zsh already installed

sudo sh -c "echo '/usr/local/bin/zsh' >> /etc/shells" && chsh -s /usr/local/bin/zsh

What causes imported Maven project in Eclipse to use Java 1.5 instead of Java 1.6 by default and how can I ensure it doesn't?

To change JDK's version, you can do:

1- Project > Properties
2- Go to Java Build Path
3- In Libraries, select JRE System ... and click on Edit
4- Choose your appropriate version and validate

Search input with an icon Bootstrap 4

Update 2019

Why not use an input-group?

<div class="input-group col-md-4">
      <input class="form-control py-2" type="search" value="search" id="example-search-input">
      <span class="input-group-append">
        <button class="btn btn-outline-secondary" type="button">
            <i class="fa fa-search"></i>
        </button>
      </span>
</div>

And, you can make it appear inside the input using the border utils...

        <div class="input-group col-md-4">
            <input class="form-control py-2 border-right-0 border" type="search" value="search" id="example-search-input">
            <span class="input-group-append">
              <button class="btn btn-outline-secondary border-left-0 border" type="button">
                    <i class="fa fa-search"></i>
              </button>
            </span>
        </div>

Or, using a input-group-text w/o the gray background so the icon appears inside the input...

        <div class="input-group">
            <input class="form-control py-2 border-right-0 border" type="search" value="search" id="example-search-input">
            <span class="input-group-append">
                <div class="input-group-text bg-transparent"><i class="fa fa-search"></i></div>
            </span>
        </div>

Alternately, you can use the grid (row>col-) with no gutter spacing:

<div class="row no-gutters">
     <div class="col">
          <input class="form-control border-secondary border-right-0 rounded-0" type="search" value="search" id="example-search-input4">
     </div>
     <div class="col-auto">
          <button class="btn btn-outline-secondary border-left-0 rounded-0 rounded-right" type="button">
             <i class="fa fa-search"></i>
          </button>
     </div>
</div>

Or, prepend the icon like this...

<div class="input-group">
  <span class="input-group-prepend">
    <div class="input-group-text bg-transparent border-right-0">
      <i class="fa fa-search"></i>
    </div>
  </span>
  <input class="form-control py-2 border-left-0 border" type="search" value="..." id="example-search-input" />
  <span class="input-group-append">
    <button class="btn btn-outline-secondary border-left-0 border" type="button">
     Search
    </button>
  </span>
</div>

Demo of all Bootstrap 4 icon input options


enter image description here


Example with validation icons

req.query and req.param in ExpressJS

req.query will return a JS object after the query string is parsed.

/user?name=tom&age=55 - req.query would yield {name:"tom", age: "55"}

req.params will return parameters in the matched route. If your route is /user/:id and you make a request to /user/5 - req.params would yield {id: "5"}

req.param is a function that peels parameters out of the request. All of this can be found here.

UPDATE

If the verb is a POST and you are using bodyParser, then you should be able to get the form body in you function with req.body. That will be the parsed JS version of the POSTed form.

How to convert a JSON string to a dictionary?

Details

  • Xcode Version 10.3 (10G8), Swift 5

Solution

import Foundation

// MARK: - CastingError

struct CastingError: Error {
    let fromType: Any.Type
    let toType: Any.Type
    init<FromType, ToType>(fromType: FromType.Type, toType: ToType.Type) {
        self.fromType = fromType
        self.toType = toType
    }
}

extension CastingError: LocalizedError {
    var localizedDescription: String { return "Can not cast from \(fromType) to \(toType)" }
}

extension CastingError: CustomStringConvertible { var description: String { return localizedDescription } }

// MARK: - Data cast extensions

extension Data {
    func toDictionary(options: JSONSerialization.ReadingOptions = []) throws -> [String: Any] {
        return try to(type: [String: Any].self, options: options)
    }

    func to<T>(type: T.Type, options: JSONSerialization.ReadingOptions = []) throws -> T {
        guard let result = try JSONSerialization.jsonObject(with: self, options: options) as? T else {
            throw CastingError(fromType: type, toType: T.self)
        }
        return result
    }
}

// MARK: - String cast extensions

extension String {
    func asJSON<T>(to type: T.Type, using encoding: String.Encoding = .utf8) throws -> T {
        guard let data = data(using: encoding) else { throw CastingError(fromType: type, toType: T.self) }
        return try data.to(type: T.self)
    }

    func asJSONToDictionary(using encoding: String.Encoding = .utf8) throws -> [String: Any] {
        return try asJSON(to: [String: Any].self, using: encoding)
    }
}

// MARK: - Dictionary cast extensions

extension Dictionary {
    func toData(options: JSONSerialization.WritingOptions = []) throws -> Data {
        return try JSONSerialization.data(withJSONObject: self, options: options)
    }
}

Usage

let value1 = try? data.toDictionary()
let value2 = try? data.to(type: [String: Any].self)
let value3 = try? data.to(type: [String: String].self)
let value4 = try? string.asJSONToDictionary()
let value5 = try? string.asJSON(to: [String: String].self)

Test sample

Do not forget to paste the solution code here

func testDescriber(text: String, value: Any) {
    print("\n//////////////////////////////////////////")
    print("-- \(text)\n\n  type: \(type(of: value))\n  value: \(value)")
}

let json1: [String: Any] = ["key1" : 1, "key2": true, "key3" : ["a": 1, "b": 2], "key4": [1,2,3]]
var jsonData = try? json1.toData()
testDescriber(text: "Sample test of func toDictionary()", value: json1)
if let data = jsonData {
    print("  Result: \(String(describing: try? data.toDictionary()))")
}

testDescriber(text: "Sample test of func to<T>() -> [String: Any]", value: json1)
if let data = jsonData {
    print("  Result: \(String(describing: try? data.to(type: [String: Any].self)))")
}

testDescriber(text: "Sample test of func to<T>() -> [String] with cast error", value: json1)
if let data = jsonData {
    do {
        print("  Result: \(String(describing: try data.to(type: [String].self)))")
    } catch {
        print("  ERROR: \(error)")
    }
}

let array = [1,4,5,6]
testDescriber(text: "Sample test of func to<T>() -> [Int]", value: array)
if let data = try? JSONSerialization.data(withJSONObject: array) {
    print("  Result: \(String(describing: try? data.to(type: [Int].self)))")
}

let json2 = ["key1": "a", "key2": "b"]
testDescriber(text: "Sample test of func to<T>() -> [String: String]", value: json2)
if let data = try? JSONSerialization.data(withJSONObject: json2) {
    print("  Result: \(String(describing: try? data.to(type: [String: String].self)))")
}

let jsonString = "{\"key1\": \"a\", \"key2\": \"b\"}"
testDescriber(text: "Sample test of func to<T>() -> [String: String]", value: jsonString)
print("  Result: \(String(describing: try? jsonString.asJSON(to: [String: String].self)))")

testDescriber(text: "Sample test of func to<T>() -> [String: String]", value: jsonString)
print("  Result: \(String(describing: try? jsonString.asJSONToDictionary()))")

let wrongJsonString = "{\"key1\": \"a\", \"key2\":}"
testDescriber(text: "Sample test of func to<T>() -> [String: String] with JSONSerialization error", value: jsonString)
do {
    let json = try wrongJsonString.asJSON(to: [String: String].self)
    print("  Result: \(String(describing: json))")
} catch {
    print("  ERROR: \(error)")
}

Test log

//////////////////////////////////////////
-- Sample test of func toDictionary()

  type: Dictionary<String, Any>
  value: ["key4": [1, 2, 3], "key2": true, "key3": ["a": 1, "b": 2], "key1": 1]
  Result: Optional(["key4": <__NSArrayI 0x600002a35380>(
1,
2,
3
)
, "key2": 1, "key3": {
    a = 1;
    b = 2;
}, "key1": 1])

//////////////////////////////////////////
-- Sample test of func to<T>() -> [String: Any]

  type: Dictionary<String, Any>
  value: ["key4": [1, 2, 3], "key2": true, "key3": ["a": 1, "b": 2], "key1": 1]
  Result: Optional(["key4": <__NSArrayI 0x600002a254d0>(
1,
2,
3
)
, "key2": 1, "key1": 1, "key3": {
    a = 1;
    b = 2;
}])

//////////////////////////////////////////
-- Sample test of func to<T>() -> [String] with cast error

  type: Dictionary<String, Any>
  value: ["key4": [1, 2, 3], "key2": true, "key3": ["a": 1, "b": 2], "key1": 1]
  ERROR: Can not cast from Array<String> to Array<String>

//////////////////////////////////////////
-- Sample test of func to<T>() -> [Int]

  type: Array<Int>
  value: [1, 4, 5, 6]
  Result: Optional([1, 4, 5, 6])

//////////////////////////////////////////
-- Sample test of func to<T>() -> [String: String]

  type: Dictionary<String, String>
  value: ["key1": "a", "key2": "b"]
  Result: Optional(["key1": "a", "key2": "b"])

//////////////////////////////////////////
-- Sample test of func to<T>() -> [String: String]

  type: String
  value: {"key1": "a", "key2": "b"}
  Result: Optional(["key1": "a", "key2": "b"])

//////////////////////////////////////////
-- Sample test of func to<T>() -> [String: String]

  type: String
  value: {"key1": "a", "key2": "b"}
  Result: Optional(["key1": a, "key2": b])

//////////////////////////////////////////
-- Sample test of func to<T>() -> [String: String] with JSONSerialization error

  type: String
  value: {"key1": "a", "key2": "b"}
  ERROR: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 21." UserInfo={NSDebugDescription=Invalid value around character 21.}

How to draw text using only OpenGL methods?

Load an image with characters as texture and draw the part of that texture depending on what character you want. You can create that texture using a paint program, hardcode it or use a window component to draw to an image and retrieve that image for an exact copy of system fonts.

No need to use Glut or any other extension, just basic OpenGL operability. It gets the job done, not to mention that its been done like this for decades by professional programmers in very succesfull games and other applications.

ANTLR: Is there a simple example?

For Antlr 4 the java code generation process is below:-

java -cp antlr-4.5.3-complete.jar org.antlr.v4.Tool Exp.g

Update your jar name in classpath accordingly.