Programs & Examples On #Dynamic forms

Dynamic PDF forms can re-render on the client depending on user interaction (adding or deleting controls, changing layout and colors). They were first introduced in Adobe Reader 7.0 and can be interactive or non-interactive.

How to uncheck a radio button?

either (plain js)

this.checked = false;

or (jQuery)

$(this).prop('checked', false);
// Note that the pre-jQuery 1.6 idiom was
// $(this).attr('checked', false);

See jQuery prop() help page for an explanation on the difference between attr() and prop() and why prop() is now preferable.
prop() was introduced with jQuery 1.6 in May 2011.

PHP order array by date?

I recommend using DateTime objects instead of strings, because you cannot easily compare strings, which is required for sorting. You also get additional advantages for working with dates.

Once you have the DateTime objects, sorting is quite easy:

usort($array, function($a, $b) {
  return ($a['date'] < $b['date']) ? -1 : 1;
});

Syntax error: Illegal return statement in JavaScript

where are you trying to return the value? to console in dev tools is better for debugging

<script type = 'text/javascript'>
var ask = confirm('".$message."');
function answer(){
  if(ask==false){
    return false;     
  } else {
    return true;
  }
}
console.log("ask : ", ask);
console.log("answer : ", answer());
</script>

github: server certificate verification failed

I also was having this error when trying to clone a repository from Github on a Windows Subsystem from Linux console:

fatal: unable to access 'http://github.com/docker/getting-started.git/': server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none

The solution from @VonC on this thread didn't work for me.

The solution from this Fabian Lee's article solved it for me:

openssl s_client -showcerts -servername github.com -connect github.com:443 </dev/null 2>/dev/null | sed -n -e '/BEGIN\ CERTIFICATE/,/END\ CERTIFICATE/ p'  > github-com.pem
cat github-com.pem | sudo tee -a /etc/ssl/certs/ca-certificates.crt

npm WARN ... requires a peer of ... but none is installed. You must install peer dependencies yourself

npm install -g npm-install-peers

it will add all the missing peers and remove all the error

#1146 - Table 'phpmyadmin.pma_recent' doesn't exist

I shear the point made by user2237829. The table names in the create_tables script used a double underscore while the table names in the xampp example uses a single underscore.

Getting "type or namespace name could not be found" but everything seems ok?

In my case, adding the dll as a reference gave the type or namespace name could not be found error. However, copying and pasting the dll file directly in bin folder resolved the error.

No idea why this worked.

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

You may have your answer however till this day it's difficult to judge whether to put null=True or blank=True or both to a field. I personally think it's pretty useless and confusing to provide so many options to developers. Let the handle the nulls or blanks however they want.

I follow this table, from Two Scoops of Django: enter image description here

Table showing when to use null or blank for each field type

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0

For me the cause was incorrect url for jcenter. To solve it I simply changed url for app and proect level build.gradle

from

jcenter { url "http://jcenter.bintray.com/"}

to

jcenter()

What is the easiest way to parse an INI file in Java?

I personally prefer Confucious.

It is nice, as it doesn't require any external dependencies, it's tiny - only 16K, and automatically loads your ini file on initialization. E.g.

Configurable config = Configuration.getInstance();  
String host = config.getStringValue("host");   
int port = config.getIntValue("port"); 
new Connection(host, port);

Node.js request CERT_HAS_EXPIRED

I think the strictSSL: false should (should have worked, even in 2013) work. So in short are three possible ways:

  1. (obvious) Get your CA to renew the certificate, and put it on your server!
  2. Change the default settings of your request object:

    const myRequest = require('request').defaults({strictSSL: false})

    Many modules that use node-request internally also allow a request-object to be injected, so you can make them use your modified instance.
  3. (not recommended) Override all certificate checks for all HTTP(S) agent connections by setting the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 for the Node.js process.

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

This can also happen if data model is out of date.

Hopefully this will save someone else frustration :)

javascript : sending custom parameters with window.open() but its not working

You can use this but there remains a security issue

<script type="text/javascript">
function fnc1()
{
    var a=window.location.href;

    username="p";
    password=1234;
    window.open(a+'?username='+username+'&password='+password,"");

}   
</script>
<input type="button" onclick="fnc1()" />
<input type="text" id="atext"  />

Getting All Variables In Scope

If you just want to inspect the variables manually to help debug, just fire up the debugger:

debugger;

Straight into the browser console.

ASP.NET GridView RowIndex As CommandArgument

Here is Microsoft Suggestion for this http://msdn.microsoft.com/en-us/library/bb907626.aspx#Y800

On the gridview add a command button and convert it into a template, then give it a commandname in this case "AddToCart" and also add CommandArgument "<%# ((GridViewRow) Container).RowIndex %>"

<asp:TemplateField>
  <ItemTemplate>
    <asp:Button ID="AddButton" runat="server" 
      CommandName="AddToCart" 
      CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
      Text="Add to Cart" />
  </ItemTemplate> 
</asp:TemplateField>

Then for create on the RowCommand event of the gridview identify when the "AddToCart" command is triggered, and do whatever you want from there

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
  if (e.CommandName == "AddToCart")
  {
    // Retrieve the row index stored in the 
    // CommandArgument property.
    int index = Convert.ToInt32(e.CommandArgument);

    // Retrieve the row that contains the button 
    // from the Rows collection.
    GridViewRow row = GridView1.Rows[index];

    // Add code here to add the item to the shopping cart.
  }
}

**One mistake I was making is that I wanted to add the actions on my template button instead of doing it directly on the RowCommand Event.

Android: View.setID(int id) programmatically - how to avoid ID conflicts?

Also you can define ids.xml in res/values. You can see an exact example in android's sample code.

samples/ApiDemos/src/com/example/android/apis/RadioGroup1.java
samples/ApiDemp/res/values/ids.xml

json_encode/json_decode - returns stdClass instead of Array in PHP

tl;dr: JavaScript doesn't support associative arrays, therefore neither does JSON.

After all, it's JSON, not JSAAN. :)

So PHP has to convert your array into an object in order to encode into JSON.

How do I POST JSON data with cURL?

HTTPie is a recommended alternative to curl because you can do just

$ http POST http://example.com/some/endpoint name=value name1=value1

It speaks JSON by default and will handle both setting the necessary header for you as well encoding data as valid JSON. There is also:

Some-Header:value

for headers, and

name==value

for query string parameters. If you have a large chunk of data, you can also read it from a file have it be JSON encoded:

 [email protected]

Why does my favicon not show up?

Try adding the profile attribute to your head tag and use "image/x-icon" for the type attribute:

<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon" type="image/x-icon" href="img/favicon.ico">

If the above code doesn't work, try using the full icon path for the href attribute:

<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon" type="image/x-icon" href="http://example.com/img/favicon.ico">

How to vertically center a "div" element for all browsers using CSS?

Not answering for browser compatibility but to also mention the new Grid and the not so new Flexbox feature.

Grid

From: Mozilla - Grid Documentation - Align Div Vertically

Browser Support: Grid Browser Support

CSS:

.wrapper {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-gap: 10px;
  grid-auto-rows: 200px;
  grid-template-areas: 
    ". a a ."
    ". a a .";
}
.item1 {
  grid-area: a;
  align-self: center;
  justify-self: center;
}

HTML:

<div class="wrapper">
 <div class="item1">Item 1</div>
</div>

Flexbox

Browser Support: Flexbox Browser Support

CSS:

display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
align-items: center;
justify-content: center;

write newline into a file

Change the lines

if(nodeValue!=null)
    fop.write(nodeValue.getBytes());

fop.flush();

to

if(nodeValue!=null) {
    fop.write(nodeValue.getBytes());
    fop.write(System.getProperty("line.separator").getBytes());
}

fop.flush();

Update to address your edit:

In order to write each word on a different line, you need to split up your input string and then write each word separately.

private static void GetText(String nodeValue) throws IOException {

    if(!file3.exists()) {
        file3.createNewFile();
    }

    FileOutputStream fop=new FileOutputStream(file3,true);
    if(nodeValue!=null)
        for(final String s : nodeValue.split(" ")){
            fop.write(s.getBytes());
            fop.write(System.getProperty("line.separator").getBytes());
        }
    }

    fop.flush();
    fop.close();

}

Using an if statement to check if a div is empty

In my case I had multiple elements to hide on document.ready. This is the function (filter) that worked for me so far:

$('[name="_invisibleIfEmpty"]').filter(function () {
    return $.trim($(this).html()).length == 0;
}).hide();

or .remove() rather than .hide(), whatever you prefer.

FYI: This, in particular, is the solution I am using to hide annoying empty table cells in SharePoint (in addition with this condition "|| $(this).children("menu").length".

Should you always favor xrange() over range()?

For performance, especially when you're iterating over a large range, xrange() is usually better. However, there are still a few cases why you might prefer range():

  • In python 3, range() does what xrange() used to do and xrange() does not exist. If you want to write code that will run on both Python 2 and Python 3, you can't use xrange().

  • range() can actually be faster in some cases - eg. if iterating over the same sequence multiple times. xrange() has to reconstruct the integer object every time, but range() will have real integer objects. (It will always perform worse in terms of memory however)

  • xrange() isn't usable in all cases where a real list is needed. For instance, it doesn't support slices, or any list methods.

[Edit] There are a couple of posts mentioning how range() will be upgraded by the 2to3 tool. For the record, here's the output of running the tool on some sample usages of range() and xrange()

RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: ws_comma
--- range_test.py (original)
+++ range_test.py (refactored)
@@ -1,7 +1,7 @@

 for x in range(20):
-    a=range(20)
+    a=list(range(20))
     b=list(range(20))
     c=[x for x in range(20)]
     d=(x for x in range(20))
-    e=xrange(20)
+    e=range(20)

As you can see, when used in a for loop or comprehension, or where already wrapped with list(), range is left unchanged.

What's the name for hyphen-separated case?

There is no standardized name.

Libraries like jquery and lodash refer it as kebab-case. So does Vuejs javascript framework. However, I am not sure whether it's safe to declare that it's referred as kebab-case in javascript world.

How to pass params with history.push/Link/Redirect in react-router v4?

  • For the earlier versions:

    history.push('/path', yourData);
    

    And get the data in the related component just like below:

    this.props.location.state // it is equal to yourData
    
  • For the newer versions the above way works well but there is a new way:

    history.push({
      pathname: '/path',
      customNameData: yourData,
    });
    

    And get the data in the related component just like below:

    this.props.location.customNameData // it is equal to yourData
    

Hint: the state key name was used in the earlier versions and for newer versions, you can use your custom name to pass data and using state name is not essential.

php stdClass to array

Use the built in type cast functionality, simply type

$realArray = (array)$stdClass;

Write to Windows Application Event Log

Yes, there is a way to write to the event log you are looking for. You don't need to create a new source, just simply use the existent one, which often has the same name as the EventLog's name and also, in some cases like the event log Application, can be accessible without administrative privileges*.

*Other cases, where you cannot access it directly, are the Security EventLog, for example, which is only accessed by the operating system.

I used this code to write directly to the event log Application:

using (EventLog eventLog = new EventLog("Application")) 
{
    eventLog.Source = "Application"; 
    eventLog.WriteEntry("Log message example", EventLogEntryType.Information, 101, 1); 
}

As you can see, the EventLog source is the same as the EventLog's name. The reason of this can be found in Event Sources @ Windows Dev Center (I bolded the part which refers to source name):

Each log in the Eventlog key contains subkeys called event sources. The event source is the name of the software that logs the event. It is often the name of the application or the name of a subcomponent of the application if the application is large. You can add a maximum of 16,384 event sources to the registry.

mysqli_select_db() expects parameter 1 to be mysqli, string given

// 2. Select a database to use 
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
    die("Database selection failed: " . mysqli_error($connection));
}

You got the order of the arguments to mysqli_select_db() backwards. And mysqli_error() requires you to provide a connection argument. mysqli_XXX is not like mysql_XXX, these arguments are no longer optional.

Note also that with mysqli you can specify the DB in mysqli_connect():

$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if (!$connection) {
  die("Database connection failed: " . mysqli_connect_error();
}

You must use mysqli_connect_error(), not mysqli_error(), to get the error from mysqli_connect(), since the latter requires you to supply a valid connection.

Disabling submit button until all fields have values

Check out this jsfiddle.

HTML

// note the change... I set the disabled property right away
<input type="submit" id="register" value="Register" disabled="disabled" />

JavaScript

(function() {
    $('form > input').keyup(function() {

        var empty = false;
        $('form > input').each(function() {
            if ($(this).val() == '') {
                empty = true;
            }
        });

        if (empty) {
            $('#register').attr('disabled', 'disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
        } else {
            $('#register').removeAttr('disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
        }
    });
})()

The nice thing about this is that it doesn't matter how many input fields you have in your form, it will always keep the button disabled if there is at least 1 that is empty. It also checks emptiness on the .keyup() which I think makes it more convenient for usability.

Notepad++ incrementally replace


Solutions suggested above will work only if data is aligned..
See solution in the link using PythonScript Notepad++ plugin, It Works great!

stackoverflow Find/Replace but Increment Value

How do you represent a JSON array of strings?

String strJson="{\"Employee\":
[{\"id\":\"101\",\"name\":\"Pushkar\",\"salary\":\"5000\"},
{\"id\":\"102\",\"name\":\"Rahul\",\"salary\":\"4000\"},
{\"id\":\"103\",\"name\":\"tanveer\",\"salary\":\"56678\"}]}";

This is an example of a JSON string with Employee as object, then multiple strings and values in an array as a reference to @cregox...

A bit complicated but can explain a lot in a single JSON string.

Binding a WPF ComboBox to a custom list

To bind the data to ComboBox

List<ComboData> ListData = new List<ComboData>();
ListData.Add(new ComboData { Id = "1", Value = "One" });
ListData.Add(new ComboData { Id = "2", Value = "Two" });
ListData.Add(new ComboData { Id = "3", Value = "Three" });
ListData.Add(new ComboData { Id = "4", Value = "Four" });
ListData.Add(new ComboData { Id = "5", Value = "Five" });

cbotest.ItemsSource = ListData;
cbotest.DisplayMemberPath = "Value";
cbotest.SelectedValuePath = "Id";

cbotest.SelectedValue = "2";

ComboData looks like:

public class ComboData
{ 
  public int Id { get; set; } 
  public string Value { get; set; } 
}

(note that Id and Value have to be properties, not class fields)

Email Address Validation in Android on EditText

I did this way:

Add this method to check whether email address is valid or not:

private boolean isValidEmailId(String email){

    return Pattern.compile("^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))@"
              + "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
              + "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
              + "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
              + "[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
              + "([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$").matcher(email).matches();
     }

Now check with String of EditText:

if(isValidEmailId(edtEmailId.getText().toString().trim())){
  Toast.makeText(getApplicationContext(), "Valid Email Address.", Toast.LENGTH_SHORT).show();
}else{       
  Toast.makeText(getApplicationContext(), "InValid Email Address.", Toast.LENGTH_SHORT).show();
}

Done

How to get child element by class name?

Use doc.childNodes to iterate through each span, and then filter the one whose className equals 4:

var doc = document.getElementById("test");
var notes = null;
for (var i = 0; i < doc.childNodes.length; i++) {
    if (doc.childNodes[i].className == "4") {
      notes = doc.childNodes[i];
      break;
    }        
}

?

Why are interface variables static and final by default?

Because anything else is part of the implementation, and interfaces cannot contain any implementation.

How to programmatically move, copy and delete files and directories on SD?

File from = new File(Environment.getExternalStorageDirectory().getAbsolutePath().getAbsolutePath()+"/kaic1/imagem.jpg");
File to = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/kaic2/imagem.jpg");
from.renameTo(to);

How to read the Stock CPU Usage data

As other answers have pointed, on UNIX systems the numbers represent CPU load averages over 1/5/15 minute periods. But on Linux (and consequently Android), what it represents is something different.

After a kernel patch dating back to 1993 (a great in-depth article on the subject), in Linux the load average numbers no longer strictly represent the CPU load: as the calculation accounts not only for CPU bound processes, but also for processes in uninterruptible wait state - the original goal was to account for I/O bound processes this way, to represent more of a "system load" than just CPU load. The issue is that since 1993 the usage of uninterruptible state has grown in Linux kernel, and it no longer typically represents an I/O bound process. The problem is further exacerbated by some Linux devs using uninterruptible waits as an easy wait to avoid accommodating signals in their implementations. As a result, in Linux (and Android) we can see skewed high load average numbers that do not objectively represent the real load. There are Android user reports about unreasonable high load averages contrasting low CPU utilization. For example, my old Android phone (with 2 CPU cores) normally shown average load of ~12 even when the system and CPUs were idle. Hence, average load numbers in Linux (Android) does not turn out to be a reliable performance metric.

How can I switch word wrap on and off in Visual Studio Code?

If you want to use text word wrap in your Visual Studio Code editor, you have to press button Alt + Z for text word wrap. Its word wrap is toggled between text wrap or unwrap.

How to get rid of blank pages in PDF exported from SSRS

It is better to do this on the design surface (Visual Studio 2012 is shown but can be done in other versions) first before calculating any maths when editing an SSRS document.

Below the following numbers in red circles that map to these following steps:

  1. In the design surface, sometimes the editor will create a page which is larger than the actual controls; hence the ghost area being printed.
  2. Resize to the controls. Visually look at the width/height and see if you can't bring in the page on the design surface to size it to the space actually needed by the controls and no more.
  3. Then try to create a PDF and see if that fixes it.
  4. If #3 does not resolve the issue, then there are controls requiring too much of the actual page size and going over in either length/width. So one will need to make the size of the controls smaller to accommodate a smaller page size.

Steps to manually remediate


Also in some circumstances one can just change a property of the report page by setting ConsumeContainerWhitespace to true to automatically consume the spaces.

Mongodb service won't start

After running the repair I was able to start the mongod proccessor but as root, which meant that service mongod start would not work. To repair this issue, I needed to make sure that all the files inside the database folder were owned and grouped to mongod. I did this by the following:

  1. Check the file permissions inside your database folder
    1. note you need to be in your dbpath folder mine was /var/lib/mongo I went to cd /var/lib
    2. I ran ls -l mongo
  2. This showed me that databases were owned by root, which is wrong. I ran the following to fix this: chown -R mongod:mongod mongo. This changed the owner and group of every file in the folder to mongod. (If using the mongodb package, chown -R mongodb:mongodb mongodb)

I hope this helps someone else in the future.

How to add browse file button to Windows Form using C#

var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
    string fileToOpen = FD.FileName;

    System.IO.FileInfo File = new System.IO.FileInfo(FD.FileName);

    //OR

    System.IO.StreamReader reader = new System.IO.StreamReader(fileToOpen);
    //etc
}

Run jQuery function onclick

There's several things you can improve upon here. To start, there's no reason to use an <a> (anchor) tag since you don't have a link.

Every element can be bound to click and hover events... divs, spans, labels, inputs, etc.

I can't really identify what it is you're trying to do, though. You're mixing the goal with your own implementation and, from what I've seen so far, you're not really sure how to do it. Could you better illustrate what it is you're trying to accomplish?

== EDIT ==

The requirements are still very vague. I've implemented a very quick version of what I'm imagining you're saying ... or something close that illustrates how you might be able to do it. Left me know if I'm on the right track.

http://jsfiddle.net/THEtheChad/j9Ump/

div inside table

It is allow as TD can contain inline- AND block-elements.

Here you can find it in the reference: http://xhtml.com/en/xhtml/reference/td/#td-contains

Lightweight Javascript DB for use in Node.js

I'm only familiar with Mongo and Couch, but there's also one named Persistence.

How can I get the key value in a JSON object?

You can simply traverse through the object and return if a match is found.

Here is the code:

returnKeyforValue : function() {
    var JsonObj= { "one":1, "two":2, "three":3, "four":4, "five":5 };
        for (key in JsonObj) {
        if(JsonObj[key] === "Keyvalue") {
            return key;
        }
    }
}

How to determine the Schemas inside an Oracle Data Pump Export file

You need to search for OWNER_NAME.

cat -v dumpfile.dmp | grep -o '<OWNER_NAME>.*</OWNER_NAME>' | uniq -u

cat -v turn the dumpfile into visible text.

grep -o shows only the match so we don't see really long lines

uniq -u removes duplicate lines so you see less output.

This works pretty well, even on large dump files, and could be tweaked for usage in a script.

Why, Fatal error: Class 'PHPUnit_Framework_TestCase' not found in ...?

For those arriving here after updating phpunit to version 6 or greater released on 2017-02-03 (e.g. with composer), you may be getting this error because phpunit code is now namespaced (check changelog).

You will need to refactor things like \PHPUnit_Framework_TestCase to \PHPUnit\Framework\TestCase

How to set iPhone UIView z index?

Within the view you want to bring to the top... (in swift)

superview?.bringSubviewToFront(self)

Create table with jQuery - append


i prefer the most readable and extensible way using jquery.
Also, you can build fully dynamic content on the fly.
Since jquery version 1.4 you can pass attributes to elements which is,
imho, a killer feature. Also the code can be kept cleaner.

$(function(){

        var tablerows = new Array();

        $.each(['result1', 'result2', 'result3'], function( index, value ) {
            tablerows.push('<tr><td>' + value + '</td></tr>');
        });

        var table =  $('<table/>', {
           html:  tablerows
       });

        var div = $('<div/>', {
            id: 'here_table',
            html: table
        });

        $('body').append(div);

    });

Addon: passing more than one "html" tag you've to use array notation like: e.g.

var div = $('<div/>', {
            id: 'here_table',
            html: [ div1, div2, table ]
        });

best Rgds.
Franz

Try catch statements in C

You use goto in C for similar error handling situations.
That is the closest equivalent of exceptions you can get in C.

How do I get the name of the current executable in C#?

Why nobody suggested this, its simple.

Path.GetFileName(Application.ExecutablePath)

How to format a string as a telephone number in C#

I prefer to use regular expressions:

Regex.Replace("1112224444", @"(\d{3})(\d{3})(\d{4})", "$1-$2-$3");

MySQL Workbench Edit Table Data is read only

According to this bug, the issue was fixed in Workbench 5.2.38 for some people and perhaps 5.2.39 for others—can you upgrade to the latest version (5.2.40)?

Alternatively, it is possible to workaround with:

SELECT *,'' FROM my_table

How do I create an HTML table with a fixed/frozen left column and a scrollable body?

A little late but I did run across this thread when trying out solutions for myself. Assuming you're using modern browsers nowadays, I came up with a solution using CSS calc() to help guarantee widths met up.

_x000D_
_x000D_
.table-fixed-left table,_x000D_
.table-fixed-right table {_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
.table-fixed-right td,_x000D_
.table-fixed-right th,_x000D_
.table-fixed-left td,_x000D_
.table-fixed-left th {_x000D_
  border: 1px solid #ddd;_x000D_
  padding: 5px 5px;_x000D_
}_x000D_
.table-fixed-left {_x000D_
  width: 120px;_x000D_
  float: left;_x000D_
  position: fixed;_x000D_
  overflow-x: scroll;_x000D_
  white-space: nowrap;_x000D_
  text-align: left;_x000D_
  border: 1px solid #ddd;_x000D_
  z-index: 2;_x000D_
}_x000D_
.table-fixed-right {_x000D_
  width: calc(100% - 145px);_x000D_
  right: 15px;_x000D_
  position: fixed;_x000D_
  overflow-x: scroll;_x000D_
  border: 1px solid #ddd;_x000D_
  white-space: nowrap;_x000D_
}_x000D_
.table-fixed-right td,_x000D_
.table-fixed-right th {_x000D_
  padding: 5px 10px;_x000D_
}
_x000D_
<div class="table-fixed-left">_x000D_
  <table>_x000D_
    <tr>_x000D_
      <th>Normal Header</th>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <th>Header with extra line_x000D_
        <br/>&nbsp;</th>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <th>Normal Header</th>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <th>Normal with extra line_x000D_
        <br/>&nbsp;</th>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <th>Normal Header</th>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <th>Normal Header</th>_x000D_
    </tr>_x000D_
  </table>_x000D_
</div>_x000D_
<div class="table-fixed-right">_x000D_
  <table>_x000D_
    <tr>_x000D_
      <th>Header</th>_x000D_
      <th>Another header</th>_x000D_
      <th>Header</th>_x000D_
      <th>Header really really really really long</th>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Info Long</td>_x000D_
      <td>Info_x000D_
        <br/>with second line</td>_x000D_
      <td>Info_x000D_
        <br/>with second line</td>_x000D_
      <td>Info Long</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Info Long</td>_x000D_
      <td>Info Long</td>_x000D_
      <td>Info Long</td>_x000D_
      <td>Info Long</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Info_x000D_
        <br/>with second line</td>_x000D_
      <td>Info_x000D_
        <br/>with second line</td>_x000D_
      <td>Info_x000D_
        <br/>with second line</td>_x000D_
      <td>Info</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Info</td>_x000D_
      <td>Info</td>_x000D_
      <td>Info</td>_x000D_
      <td>Info</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Info</td>_x000D_
      <td>Info</td>_x000D_
      <td>Info</td>_x000D_
      <td>Info</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Hope this helps someone!

How to copy multiple files in one layer using a Dockerfile?

It might be worth mentioning that you can also create a .dockerignore file, to exclude the files that you don't want to copy:

https://docs.docker.com/engine/reference/builder/#dockerignore-file

Before the docker CLI sends the context to the docker daemon, it looks for a file named .dockerignore in the root directory of the context. If this file exists, the CLI modifies the context to exclude files and directories that match patterns in it. This helps to avoid unnecessarily sending large or sensitive files and directories to the daemon and potentially adding them to images using ADD or COPY.

Best Practice: Access form elements by HTML id or name attribute?

It’s not really answering your question, but just on this part:

[3] requires both an id and a name... having both is somewhat redundant

You’ll most likely need to have an id attribute on each form field anyway, so that you can associate its <label> element with it, like this:

<label for="foo">Foo:</label>
<input type="text" name="foo" id="foo" />

This is required for accessibility (i.e. if you don’t associate form labels and controls, why do you hate blind people so much?).

It is somewhat redundant, although less so when you have checkboxes/radio buttons, where several of them can share a name. Ultimately, id and name are for different purposes, even if both are often set to the same value.

Add custom icons to font awesome

Depends on what you have. If your svg icon is just a path, then it's easy enough to add that glyph by just copying the 'd' attribute to a new <glyph> element. However, the path needs to be scaled to the font's coordinate system (the EM-square, which typically is [0,0,2048,2048] - the standard for Truetype fonts) and aligned with the baseline you want.

Not all browsers support svg fonts however, so you're going to have to convert it to other formats too if you want it to work everywhere.

Fontforge can import svg files (select a glyph slot, File > Import and then select your svg image), and you can then convert to all the relevant font formats (svg, truetype, woff etc).

inherit from two classes in C#

Do you mean you want Class C to be the base class for A & B in that case.

public abstract class C
{
    public abstract void Method1();

    public abstract void Method2();
}

public class A : C
{
    public override void Method1()
    {
        throw new NotImplementedException();
    }

    public override void Method2()
    {
        throw new NotImplementedException();
    }
}


public class B : C
{
    public override void Method1()
    {
        throw new NotImplementedException();
    }

    public override void Method2()
    {
        throw new NotImplementedException();
    }
}

Simple PHP form: Attachment to email (code golf)

I haven't tested the email part of this (my test box does not send email) but I think it will work.

<?php
if ($_POST) {
$s = md5(rand());
mail('[email protected]', 'attachment', "--$s

{$_POST['m']}
--$s
Content-Type: application/octet-stream; name=\"f\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment

".chunk_split(base64_encode(join(file($_FILES['f']['tmp_name']))))."
--$s--", "MIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"$s\"");
exit;
}
?>
<form method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'] ?>">
<textarea name="m"></textarea><br>
<input type="file" name="f"/><br>
<input type="submit">
</form>

How to access model hasMany Relation with where condition?

I think that this is the correct way:

class Game extends Eloquent {
    // many more stuff here

    // relation without any constraints ...works fine 
    public function videos() {
        return $this->hasMany('Video');
    }

    // results in a "problem", se examples below
    public function available_videos() {
        return $this->videos()->where('available','=', 1);
    }
}

And then you'll have to

$game = Game::find(1);
var_dump( $game->available_videos()->get() );

What is the difference between Python's list methods append and extend?

You can use "+" for returning extend, instead of extending in place.

l1=range(10)

l1+[11]

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11]

l2=range(10,1,-1)

l1+l2

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2]

Similarly += for in place behavior, but with slight differences from append & extend. One of the biggest differences of += from append and extend is when it is used in function scopes, see this blog post.

How to Delete a directory from Hadoop cluster which is having comma(,) in its name?

Or you can: hadoop fs -rm -r PATH

Hint: if you enter: hadoop fs -rmr PATH you would mostly get:Please use 'rm -r' instead.

rails 3.1.0 ActionView::Template::Error (application.css isn't precompiled)

For all those who are reading this but do not have problem with application.css and instead with their custom CSS classes e.g. admin.css, base.css etc.

Solution is to use as mentioned

bundle exec rake assets:precompile

And in stylesheets references just reference application.css

<%= stylesheet_link_tag    "application", :media => "all" %>

Since assets pipeline will precompile all of your stylesheets in application.css. This also happens in development so using any other references is wrong when using assets pipeline.

How to round each item in a list of floats to 2 decimal places?

Another option which doesn't require numpy is:

precision = 2  
myRoundedList = [int(elem*(10**precision)+delta)/(10.0**precision) for elem in myList]

# delta=0 for floor
# delta = 0.5 for round
# delta = 1 for ceil

linux shell script: split string, put them in an array then loop through them

If you don't wish to mess with IFS (perhaps for the code within the loop) this might help.

If know that your string will not have whitespace, you can substitute the ';' with a space and use the for/in construct:

#local str
for str in ${STR//;/ } ; do 
   echo "+ \"$str\""
done

But if you might have whitespace, then for this approach you will need to use a temp variable to hold the "rest" like this:

#local str rest
rest=$STR
while [ -n "$rest" ] ; do
   str=${rest%%;*}  # Everything up to the first ';'
   # Trim up to the first ';' -- and handle final case, too.
   [ "$rest" = "${rest/;/}" ] && rest= || rest=${rest#*;}
   echo "+ \"$str\""
done

JSON.net: how to deserialize without using the default constructor?

Based on some of the answers here, I have written a CustomConstructorResolver for use in a current project, and I thought it might help somebody else.

It supports the following resolution mechanisms, all configurable:

  • Select a single private constructor so you can define one private constructor without having to mark it with an attribute.
  • Select the most specific private constructor so you can have multiple overloads, still without having to use attributes.
  • Select the constructor marked with an attribute of a specific name - like the default resolver, but without a dependency on the Json.Net package because you need to reference Newtonsoft.Json.JsonConstructorAttribute.
public class CustomConstructorResolver : DefaultContractResolver
{
    public string ConstructorAttributeName { get; set; } = "JsonConstructorAttribute";
    public bool IgnoreAttributeConstructor { get; set; } = false;
    public bool IgnoreSinglePrivateConstructor { get; set; } = false;
    public bool IgnoreMostSpecificConstructor { get; set; } = false;

    protected override JsonObjectContract CreateObjectContract(Type objectType)
    {
        var contract = base.CreateObjectContract(objectType);

        // Use default contract for non-object types.
        if (objectType.IsPrimitive || objectType.IsEnum) return contract;

        // Look for constructor with attribute first, then single private, then most specific.
        var overrideConstructor = 
               (this.IgnoreAttributeConstructor ? null : GetAttributeConstructor(objectType)) 
            ?? (this.IgnoreSinglePrivateConstructor ? null : GetSinglePrivateConstructor(objectType)) 
            ?? (this.IgnoreMostSpecificConstructor ? null : GetMostSpecificConstructor(objectType));

        // Set override constructor if found, otherwise use default contract.
        if (overrideConstructor != null)
        {
            SetOverrideCreator(contract, overrideConstructor);
        }

        return contract;
    }

    private void SetOverrideCreator(JsonObjectContract contract, ConstructorInfo attributeConstructor)
    {
        contract.OverrideCreator = CreateParameterizedConstructor(attributeConstructor);
        contract.CreatorParameters.Clear();
        foreach (var constructorParameter in base.CreateConstructorParameters(attributeConstructor, contract.Properties))
        {
            contract.CreatorParameters.Add(constructorParameter);
        }
    }

    private ObjectConstructor<object> CreateParameterizedConstructor(MethodBase method)
    {
        var c = method as ConstructorInfo;
        if (c != null)
            return a => c.Invoke(a);
        return a => method.Invoke(null, a);
    }

    protected virtual ConstructorInfo GetAttributeConstructor(Type objectType)
    {
        var constructors = objectType
            .GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
            .Where(c => c.GetCustomAttributes().Any(a => a.GetType().Name == this.ConstructorAttributeName)).ToList();

        if (constructors.Count == 1) return constructors[0];
        if (constructors.Count > 1)
            throw new JsonException($"Multiple constructors with a {this.ConstructorAttributeName}.");

        return null;
    }

    protected virtual ConstructorInfo GetSinglePrivateConstructor(Type objectType)
    {
        var constructors = objectType
            .GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic);

        return constructors.Length == 1 ? constructors[0] : null;
    }

    protected virtual ConstructorInfo GetMostSpecificConstructor(Type objectType)
    {
        var constructors = objectType
            .GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
            .OrderBy(e => e.GetParameters().Length);

        var mostSpecific = constructors.LastOrDefault();
        return mostSpecific;
    }
}

Here is the complete version with XML documentation as a gist: https://gist.github.com/maverickelementalch/80f77f4b6bdce3b434b0f7a1d06baa95

Feedback appreciated.

Android: Proper Way to use onBackPressed() with Toast

This is the best way, because if user not back more than two seconds then reset backpressed value.

declare one global variable.

 private boolean backPressToExit = false;

Override onBackPressed Method.

@Override
public void onBackPressed() {

    if (backPressToExit) {
        super.onBackPressed();
        return;
    }
    this.backPressToExit = true;
    Snackbar.make(findViewById(R.id.yourview), getString(R.string.exit_msg), Snackbar.LENGTH_SHORT).show();
    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            backPressToExit = false;
        }
    }, 2000);
}

Run a vbscript from another vbscript

See if the following works

Dim objShell
Set objShell = Wscript.CreateObject("WScript.Shell")

objShell.Run "TestScript.vbs" 

' Using Set is mandatory
Set objShell = Nothing

Calculate AUC in R?

You can learn more about AUROC in this blog post by Miron Kursa:

https://mbq.me/blog/augh-roc/

He provides a fast function for AUROC:

# By Miron Kursa https://mbq.me
auroc <- function(score, bool) {
  n1 <- sum(!bool)
  n2 <- sum(bool)
  U  <- sum(rank(score)[!bool]) - n1 * (n1 + 1) / 2
  return(1 - U / n1 / n2)
}

Let's test it:

set.seed(42)
score <- rnorm(1e3)
bool  <- sample(c(TRUE, FALSE), 1e3, replace = TRUE)

pROC::auc(bool, score)
mltools::auc_roc(score, bool)
ROCR::performance(ROCR::prediction(score, bool), "auc")@y.values[[1]]
auroc(score, bool)

0.51371668847094
0.51371668847094
0.51371668847094
0.51371668847094

auroc() is 100 times faster than pROC::auc() and computeAUC().

auroc() is 10 times faster than mltools::auc_roc() and ROCR::performance().

print(microbenchmark(
  pROC::auc(bool, score),
  computeAUC(score[bool], score[!bool]),
  mltools::auc_roc(score, bool),
  ROCR::performance(ROCR::prediction(score, bool), "auc")@y.values,
  auroc(score, bool)
))

Unit: microseconds
                                                             expr       min
                                           pROC::auc(bool, score) 21000.146
                            computeAUC(score[bool], score[!bool]) 11878.605
                                    mltools::auc_roc(score, bool)  5750.651
 ROCR::performance(ROCR::prediction(score, bool), "auc")@y.values  2899.573
                                               auroc(score, bool)   236.531
         lq       mean     median        uq        max neval  cld
 22005.3350 23738.3447 22206.5730 22710.853  32628.347   100    d
 12323.0305 16173.0645 12378.5540 12624.981 233701.511   100   c 
  6186.0245  6495.5158  6325.3955  6573.993  14698.244   100  b  
  3019.6310  3300.1961  3068.0240  3237.534  11995.667   100 ab  
   245.4755   253.1109   251.8505   257.578    300.506   100 a   

How to Sort a List<T> by a property in the object

var obj = db.Items.Where...

var orderBYItemId = obj.OrderByDescending(c => Convert.ToInt32(c.ID));

How to check for a JSON response using RSpec?

Another approach to test just for a JSON response (not that the content within contains an expected value), is to parse the response using ActiveSupport:

ActiveSupport::JSON.decode(response.body).should_not be_nil

If the response is not parsable JSON an exception will be thrown and the test will fail.

Is there a way to call a stored procedure with Dapper?

Here is code for getting value return from Store procedure

Stored procedure:

alter proc [dbo].[UserlogincheckMVC]    
@username nvarchar(max),    
@password nvarchar(max)
as    
begin    
    if exists(select Username from Adminlogin where Username =@username and Password=@password)    
        begin        
            return 1  
        end    
    else    
        begin     
            return 0  
        end    
end 

Code:

var parameters = new DynamicParameters();
string pass = EncrytDecry.Encrypt(objUL.Password);
conx.Open();
parameters.Add("@username", objUL.Username);
parameters.Add("@password", pass);
parameters.Add("@RESULT", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);
var RS = conx.Execute("UserlogincheckMVC", parameters, null, null, commandType: CommandType.StoredProcedure);
int result = parameters.Get<int>("@RESULT");

What is best tool to compare two SQL Server databases (schema and data)?

I like Open DBDiff.

While not the most complete tool, it works great, it's free, and it's very easy to use.

CSS Select box arrow style

Try to replace the

padding: 2px 30px 2px 2px;

with

padding: 2px 2px 2px 2px;

It should work.

How do I manually create a file with a . (dot) prefix in Windows? For example, .htaccess

It seems that Microsoft finally is addressing this problem. Current versions in the Insider Editions of Explorer allows creating files with a dot at the front.

Tested with Build 19541

Getting the screen resolution using PHP

Fully Working Example

I couldn't find an actual working PHP example to "invisibly" (without URL parameters) return client screen size, and other properties, to server-side PHP, so I put this example together.

JS populates and submits a hidden form (scripted by PHP from an array of JS properties), POSTing to itself (the data now available in PHP) and returns the data in a table.

(Tested in "several" browsers.)

<!DOCTYPE html>
<html>
<head>
    <title>*Client Info*</title>
    <style>table,tr{border:2px solid gold;border-collapse:collapse;}td{padding:5px;}</style>
</head>

<body>
<?php
  $clientProps=array('screen.width','screen.height','window.innerWidth','window.innerHeight', 
    'window.outerWidth','window.outerHeight','screen.colorDepth','screen.pixelDepth');

  if(! isset($_POST['screenheight'])){

    echo "Loading...<form method='POST' id='data' style='display:none'>";
    foreach($clientProps as $p) {  //create hidden form
      echo "<input type='text' id='".str_replace('.','',$p)."' name='".str_replace('.','',$p)."'>";
    }
    echo "<input type='submit'></form>";

    echo "<script>";
    foreach($clientProps as $p) {  //populate hidden form with screen/window info
      echo "document.getElementById('" . str_replace('.','',$p) . "').value = $p;";
    }
    echo "document.forms.namedItem('data').submit();"; //submit form
    echo "</script>";

  }else{

    echo "<table>";
    foreach($clientProps as $p) {   //create output table
      echo "<tr><td>".ucwords(str_replace('.',' ',$p)).":</td><td>".$_POST[str_replace('.','',$p)]."</td></tr>";
    }
    echo "</table>";
  }
?>
<script>
    window.history.replaceState(null,null); //avoid form warning if user clicks refresh
</script>
</body>
</html>

The returned data is extract'd into variables. For example:

  • window.innerWidth is returned in $windowinnerWidth

How to move from one fragment to another fragment on click of an ImageView in Android?

When you are inside an activity and need to go to a fragment use below

getFragmentManager().beginTransaction().replace(R.id.*TO_BE_REPLACED_LAYOUT_ID*, new tasks()).commit();

But when you are inside a fragment and need to go to a fragment then just add a getActivity(). before, so it would become

getActivity().getFragmentManager().beginTransaction().replace(R.id.*TO_BE_REPLACED_LAYOUT_ID*, new tasks()).commit();

as simple as that.

The *TO_BE_REPLACED_LAYOUT_ID* can be the entire page of activity or a part of it, just make sure to put an id to the layout to be replaced. It is general practice to put the replaceable layout in a FrameLayout .

need to add a class to an element

You can use result.className = 'red';, but you can also use result.classList.add('red');. The .classList.add(str) way is usually easier if you need to add a class in general, and don't want to check if the class is already in the list of classes.

Jackson and generic type reference

'JavaType' works !! I was trying to unmarshall (deserialize) a List in json String to ArrayList java Objects and was struggling to find a solution since days.
Below is the code that finally gave me solution. Code:

JsonMarshallerUnmarshaller<T> {
    T targetClass;

    public ArrayList<T> unmarshal(String jsonString) {
        ObjectMapper mapper = new ObjectMapper();

        AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();
        mapper.getDeserializationConfig()
            .withAnnotationIntrospector(introspector);

        mapper.getSerializationConfig()
            .withAnnotationIntrospector(introspector);
        JavaType type = mapper.getTypeFactory().
            constructCollectionType(
                ArrayList.class, 
                targetclass.getClass());

        try {
            Class c1 = this.targetclass.getClass();
            Class c2 = this.targetclass1.getClass();
            ArrayList<T> temp = (ArrayList<T>) 
                mapper.readValue(jsonString,  type);
            return temp ;
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null ;
    }  
}

Passing HTML to template using Flask/Jinja2

From the jinja docs section HTML Escaping:

When automatic escaping is enabled everything is escaped by default except for values explicitly marked as safe. Those can either be marked by the application or in the template by using the |safe filter.

Example:

 <div class="info">
   {{data.email_content|safe}}
 </div>

How to fill Matrix with zeros in OpenCV?

If You are more into programming with templates, You may also do it this way...

template<typename _Tp>
... some algo ...
cv::Mat mat = cv::Mat_<_Tp>::zeros(rows, cols);
mat.at<_Tp>(i, j) = val;

Best way to reverse a string

Since I like a couple of the answers - one for using string.Create and therefore high performance and low allocation and another for correctness - using the StringInfo class, I decided a combined approach is needed. This is the ultimate string reversal method :)

private static string ReverseString(string str)
    {
        return string.Create(str.Length, str, (chars, state) =>
        {
            var enumerator = StringInfo.GetTextElementEnumerator(state);
            var position = state.Length;
            while (enumerator.MoveNext())
            {
                var cluster = ((string)enumerator.Current).AsSpan();
                cluster.CopyTo(chars.Slice(position - cluster.Length));
                position -= cluster.Length;
            }
        });
    }

There's an even better way using a method of the StringInfo class which skips a lot of string allocations by the Enumerator by returning just the indexes.

private static string ReverseString(string str)
    {
        return string.Create(str.Length, str, (chars, state) =>
        {
            var position = 0;
            var indexes = StringInfo.ParseCombiningCharacters(state); // skips string creation
            var stateSpan = state.AsSpan();
            for (int len = indexes.Length, i = len - 1; i >= 0; i--)
            {
                var index = indexes[i];
                var spanLength = i == len - 1 ? state.Length - index : indexes[i + 1] - index;
                stateSpan.Slice(index, spanLength).CopyTo(chars.Slice(position));
                position += spanLength;
            }
        });
    }

Some benchmarks compared to the LINQ solution:

String length 20:

LINQ                       Mean: 2,355.5 ns   Allocated: 1440 B
string.Create              Mean:   851.0 ns   Allocated:  720 B
string.Create with indexes Mean:   466.4 ns   Allocated:  168 B

String length 450:

LINQ                          Mean: 34.33 us   Allocated: 22.98 KB
string.Create                 Mean:   19.13 us   Allocated: 14.98 KB
string.Create with indexes    Mean:   10.32 us   Allocated: 2.69 KB

req.body empty on posts

I didn't have the name in my Input ... my request was empty... glad that is finished and I can keep coding. Thanks everyone!

Answer I used by Jason Kim:

So instead of

<input type="password" class="form-control" id="password">

I have this

<input type="password" class="form-control" id="password" name="password">

Anonymous method in Invoke call

I like to use Action in place of MethodInvoker, it is shorter and looks cleaner.

Invoke((Action)(() => {
    DoSomething();
}));

// OR

Invoke((Action)delegate {
    DoSomething();
});

Eg.

// Thread-safe update on a form control
public void DisplayResult(string text){
    if (txtResult.InvokeRequired){
        txtResult.Invoke((Action)delegate {
            DisplayResult(text);
        });
        return;
    }

    txtResult.Text += text + "\r\n";
}

Upload files with HTTPWebrequest (multipart/form-data)

Client use convert File to ToBase64String, after use Xml to promulgate to Server call, this server use File.WriteAllBytes(path,Convert.FromBase64String(dataFile_Client_sent)).

Good lucky!

Custom Date/Time formatting in SQL Server

If dt is your datetime column, then

For 1:

SUBSTRING(CONVERT(varchar, dt, 13), 1, 2)
    + UPPER(SUBSTRING(CONVERT(varchar, dt, 13), 4, 3))

For 2:

SUBSTRING(CONVERT(varchar, dt, 100), 13, 2)
    + SUBSTRING(CONVERT(varchar, dt, 100), 16, 3)

How to export and import environment variables in windows?

You can get access to the environment variables in either the command line or in the registry.

Command Line

If you want a specific environment variable, then just type the name of it (e.g. PATH), followed by a >, and the filename to write to. The following will dump the PATH environment variable to a file named path.txt.

C:\> PATH > path.txt

Registry Method

The Windows Registry holds all the environment variables, in different places depending on which set you are after. You can use the registry Import/Export commands to shift them into the other PC.

For System Variables:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

For User Variables:

HKEY_CURRENT_USER\Environment

How to Generate Unique ID in Java (Integer)?

Just generate ID and check whether it is already present or not in your list of generated IDs.

Debugging with command-line parameters in Visual Studio

In Visual Studio 2010, right click the project, choose Properties, click the configuring properties section on the left pane, then click Debugging, then on the right pane there is a box for command arguments.

In that enter the command line arguments. You are good to go. Now debug and see the result. If you are tired of changing in the properties then temporarily give the input directly in the program.

How can I get form data with JavaScript/jQuery?

For those of you who would prefer an Object as opposed to a serialized string (like the one returned by $(form).serialize(), and a slight improvement on $(form).serializeArray()), feel free to use the code below:

var Form = {
    _form: null,
    _validate: function(){
        if(!this._form || this._form.tagName.toLowerCase() !== "form") return false;
        if(!this._form.elements.length) return false;
    }, _loopFields: function(callback){
        var elements = this._form.elements;
        for(var i = 0; i < elements.length; i++){
            var element = form.elements[i];
            if(name !== ""){
                callback(this._valueOfField(element));
            }
        }
    }, _valueOfField: function(element){
        var type = element.type;
        var name = element.name.trim();
        var nodeName = element.nodeName.toLowerCase();
        switch(nodeName){
            case "input":
                if(type === "radio" || type === "checkbox"){
                    if(element.checked){
                        return element.value;
                    }
                }
                return element.value;
                break;
            case "select":
                if(type === "select-multiple"){
                    for(var i = 0; i < element.options.length; i++){
                        if(options[i].selected){
                            return element.value;
                        }
                    }
                }
                return element.value;
                break;
            case "button":
                switch(type){
                    case "reset": 
                    case "submit": 
                    case "button":
                        return element.value;
                        break;
                }
                break;
        } 
    }, serialize: function(form){
        var data = {};
        this._form = form;

        if(this._validate()){
            this._loopFields(function(value){
                if(value !== null) data[name] = value;
            });
        }
        return data;
    }
};

To execute it, just use Form.serialize(form) and the function will return an Object similar to this:

<!-- { username: "username", password: "password" } !-->
<input type="text" value="username">
<input type="password" value="password">

As a bonus, it means you don't have to install the entire bundle of jQuery just for one serialize function.

How to set a selected option of a dropdown list control using angular JS

Simple way

If you have a Users as response or a Array/JSON you defined, First You need to set the selected value in controller, then you put the same model name in html. This example i wrote to explain in easiest way.
Simple example
Inside Controller:

$scope.Users = ["Suresh","Mahesh","Ramesh"]; 
$scope.selectedUser = $scope.Users[0];

Your HTML

<select data-ng-options="usr for usr in Users" data-ng-model="selectedUser">
</select>

complex example
Inside Controller:

$scope.JSON = {
       "ResponseObject":
           [{
               "Name": "Suresh",
               "userID": 1
           },
           {
               "Name": "Mahesh",
               "userID": 2
           }]
   };
   $scope.selectedUser = $scope.JSON.ResponseObject[0];

Your HTML

<select data-ng-options="usr.Name for usr in JSON.ResponseObject" data-ng-model="selectedUser"></select>
<h3>You selected: {{selectedUser.Name}}</h3>    

HashMap to return default value for non-found keys?

Can't you just create a static method that does exactly this?

private static <K, V> V getOrDefault(Map<K,V> map, K key, V defaultValue) {
    return map.containsKey(key) ? map.get(key) : defaultValue;
}

Set attribute without value

You can do it without jQuery!

Example:

_x000D_
_x000D_
document.querySelector('button').setAttribute('disabled', '');
_x000D_
<button>My disabled button!</button>
_x000D_
_x000D_
_x000D_

To set the value of a Boolean attribute, such as disabled, you can specify any value. An empty string or the name of the attribute are recommended values. All that matters is that if the attribute is present at all, regardless of its actual value, its value is considered to be true. The absence of the attribute means its value is false. By setting the value of the disabled attribute to the empty string (""), we are setting disabled to true, which results in the button being disabled.

From MDN Element.setAttribute()

What is secret key for JWT based authentication and how to generate it?

What is the secret key does, you may have already known till now. It is basically HMAC SH256 (Secure Hash). The Secret is a symmetrical key.

Using the same key you can generate, & reverify, edit, etc.

For more secure, you can go with private, public key (asymmetric way). Private key to create token, public key to verify at client level.

Coming to secret key what to give You can give anything, "sudsif", "sdfn2173", any length

you can use online generator, or manually write

I prefer using openssl

C:\Users\xyz\Desktop>openssl rand -base64 12
65JymYzDDqqLW8Eg

generate, then encode with base 64

C:\Users\xyz\Desktop>openssl rand -out openssl-secret.txt -hex 20

The generated value is saved inside the file named "openssl-secret.txt"

generate, & store into a file.

One thing is giving 12 will generate, 12 characters only, but since it is base 64 encoded, it will be (4/3*n) ceiling value.

I recommend reading this article

https://auth0.com/blog/brute-forcing-hs256-is-possible-the-importance-of-using-strong-keys-to-sign-jwts/

Applying function with multiple arguments to create a new pandas column

This solves the problem:

df['newcolumn'] = df.A * df.B

You could also do:

def fab(row):
  return row['A'] * row['B']

df['newcolumn'] = df.apply(fab, axis=1)

How can I set / change DNS using the command-prompt at windows 8

There are little difference in command of adding AND changing DNS-IPs:

To Add:

Syntax:
   netsh interface ipv4 add dnsserver "Network Interface Name" dns.server.ip index=1(for primary)2(for secondary)
Eg:
   netsh interface ipv4 add dnsserver "Ethernet" 8.8.8.8 index=1
  • Here, to know "Network Interface Name", type command netsh interface show interface
  • 8.8.8.8 is Google's recursive DNS server, use it, if your's not working

To Set/Change: (as OP asked this)

Syntax:
   netsh interface ipv4 set dnsservers "Network Interface Name" static dns.server.ip primary
Eg:
   netsh interface ipv4 set dnsservers "Wi-Fi" static 8.8.4.4 primary
   netsh interface ipv4 set dnsservers "Wi-Fi" dhcp
  • Last parameter can be none:disable DNS, both:set for primary and secondary DNS both, primary: for primary DNS only. You can notice here we are not using index-parameter as we did in adding DNS.

  • In the place of static you can type dhcp to make DNS setting automatic, but further parameter will not be required.


Note: Tested in windows 8,8.1 & 10.

Thin Black Border for a Table

Style the td and th instead

td, th {
    border: 1px solid black;
}

And also to make it so there is no spacing between cells use:

table {
    border-collapse: collapse;
}

(also note, you have border-style: none; which should be border-style: solid;)

See an example here: http://jsfiddle.net/KbjNr/

Difference between onStart() and onResume()

A particularly feisty example is when you decide to show a managed Dialog from an Activity using showDialog(). If the user rotates the screen while the dialog is still open (we call this a "configuration change"), then the main Activity will go through all the ending lifecycle calls up untill onDestroy(), will be recreated, and go back up through the lifecycles. What you might not expect however, is that onCreateDialog() and onPrepareDialog() (the methods that are called when you do showDialog() and now again automatically to recreate the dialog - automatically since it is a managed dialog) are called between onStart() and onResume(). The pointe here is that the dialog does not cover the full screen and therefore leaves part of the main activity visible. It's a detail but it does matter!

Error: unexpected symbol/input/string constant/numeric constant/SPECIAL in my code

If you are copy-pasting code into R, it sometimes won't accept some special characters such as "~" and will appear instead as a "?". So if a certain character is giving an error, make sure to use your keyboard to enter the character, or find another website to copy-paste from if that doesn't work.

Easiest way to copy a single file from host to Vagrant guest?

Vagrant provides a way to execute a command over ssh instead of logging in, so for Linux host and guest you can use:

  • from host to guest:

cat ~/file_on_host.txt | vagrant ssh -c 'cat - > ~/file_on_guest.txt'

  • from guest to host:

vagrant ssh -c 'cat ~/file_on_guest.txt' > ~/file_on_host.txt

No need for plugins or guest reloads. Just make sure to provide vagrant box ID to 'vagrant ssh' if you are not in the same dir as the Vagrantfile. Tested on Vagrant v1.8.1.

Securely storing passwords for use in python script

Know the master key yourself. Don't hard code it.

Use py-bcrypt (bcrypt), powerful hashing technique to generate a password yourself.

Basically you can do this (an idea...)

import bcrypt
from getpass import getpass
master_secret_key = getpass('tell me the master secret key you are going to use')
salt = bcrypt.gensalt()
combo_password = raw_password + salt + master_secret_key
hashed_password = bcrypt.hashpw(combo_password, salt)

save salt and hashed password somewhere so whenever you need to use the password, you are reading the encrypted password, and test against the raw password you are entering again.

This is basically how login should work these days.

AddTransient, AddScoped and AddSingleton Services Differences

  • Singleton is a single instance for the lifetime of the application domain.
  • Scoped is a single instance for the duration of the scoped request, which means per HTTP request in ASP.NET.
  • Transient is a single instance per code request.

Normally the code request should be made through a constructor parameter, as in

public MyConsumingClass(IDependency dependency)

I wanted to point out in @akazemis's answer that "services" in the context of DI does not imply RESTful services; services are implementations of dependencies that provide functionality.

How to stop mysqld

I did it with next command:

sudo killall mysqld

Google Maps API 3 - Custom marker color for default (dot) marker

Well the closest thing I've been able to get with the StyledMarker is this.

The bullet in the middle isn't quite a big as the default one though. The StyledMarker class simply builds this url and asks the google api to create the marker.

From the class use example use "%E2%80%A2" as your text, as in:

var styleMaker2 = new StyledMarker({styleIcon:new StyledIcon(StyledIconTypes.MARKER,{text:"%E2%80%A2"},styleIconClass),position:new google.maps.LatLng(37.263477473067, -121.880502070713),map:map});

You will need to modifiy StyledMarker.js to comment out the lines:

  if (text_) {
    text_ = text_.substr(0,2);
  }

as this will trim the text string to 2 characters.

Alternatively you could create custom marker images based on the default one with the colors you desire and override the default marker with code such as this:

marker = new google.maps.Marker({
  map:map,
  position: latlng,
  icon: new google.maps.MarkerImage(
    'http://www.gettyicons.com/free-icons/108/gis-gps/png/24/needle_left_yellow_2_24.png',
    new google.maps.Size(24, 24),
    new google.maps.Point(0, 0),
    new google.maps.Point(0, 24)
  )
});

Fix columns in horizontal scrolling

Demo: http://www.jqueryscript.net/demo/jQuery-Plugin-For-Fixed-Table-Header-Footer-Columns-TableHeadFixer/

HTML

<h2>TableHeadFixer Fix Left Column</h2>

<div id="parent">
    <table id="fixTable" class="table">
        <thead>
            <tr>
                <th>Ano</th>
                <th>Jan</th>
                <th>Fev</th>
                <th>Mar</th>
                <th>Abr</th>
                <th>Maio</th>
                <th>Total</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
        </tbody>
    </table>
</div>

JS

    $(document).ready(function() {
        $("#fixTable").tableHeadFixer({"head" : false, "right" : 1}); 
    });

CSS

    #parent {
        height: 300px;
    }

    #fixTable {
        width: 1800px !important;
    }

https://jsfiddle.net/5gfuqqc4/

Creating a new ArrayList in Java

You are looking for Java generics

List<MyClass> list = new ArrayList<MyClass>();

Here's a tutorial http://docs.oracle.com/javase/tutorial/java/generics/index.html

What is the C++ function to raise a number to a power?

You should be able to use normal C methods in math.

#include <cmath>

pow(2,3)

if you're on a unix-like system, man cmath

Is that what you're asking?

Sujal

java.io.FileNotFoundException: the system cannot find the file specified

Try to create a file using the code, so you will get to know the path of the file where the system create

File test=new File("check.txt");
if (test.createNewFile()) {
    System.out.println("File created: " + test.getName());
  }

How to break out or exit a method in Java?

If you are deeply in recursion inside recursive method, throwing and catching exception may be an option.

Unlike Return that returns only one level up, exception would break out of recursive method as well into the code that initially called it, where it can be catched.

Java Constructor Inheritance

I don't know any language where subclasses inherit constructors (but then, I am not much of a programming polyglott).

Here's a discussion about the same question concerning C#. The general consensus seems to be that it would complicate the language, introduce the potential for nasty side effects to changes in a base class, and generally shouldn't be necessary in a good design.

A child container failed during start java.util.concurrent.ExecutionException

I have observed a similar issue in my project. The issue was solved when the jar with the missing class definition was pasted into the lib directory of tomcat.

How to convert text column to datetime in SQL

Use convert with style 101.

select convert(datetime, Remarks, 101)

If your column is really text you need to convert to varchar before converting to datetime

select convert(datetime, convert(varchar(30), Remarks), 101)

Set a form's action attribute when submitting?

<input type='submit' value='Submit' onclick='this.form.action="somethingelse";' />

Or you can modify it from outside the form, with javascript the normal way:

 document.getElementById('form_id').action = 'somethingelse';

Compare two files report difference in python

import difflib

lines1 = '''
dog
cat
bird
buffalo
gophers
hound
horse
'''.strip().splitlines()

lines2 = '''
cat
dog
bird
buffalo
gopher
horse
mouse
'''.strip().splitlines()

# Changes:
# swapped positions of cat and dog
# changed gophers to gopher
# removed hound
# added mouse

for line in difflib.unified_diff(lines1, lines2, fromfile='file1', tofile='file2', lineterm=''):
    print line

Outputs the following:

--- file1
+++ file2
@@ -1,7 +1,7 @@
+cat
 dog
-cat
 bird
 buffalo
-gophers
-hound
+gopher
 horse
+mouse

This diff gives you context -- surrounding lines to help make it clear how the file is different. You can see "cat" here twice, because it was removed from below "dog" and added above it.

You can use n=0 to remove the context.

for line in difflib.unified_diff(lines1, lines2, fromfile='file1', tofile='file2', lineterm='', n=0):
    print line

Outputting this:

--- file1
+++ file2
@@ -0,0 +1 @@
+cat
@@ -2 +2,0 @@
-cat
@@ -5,2 +5 @@
-gophers
-hound
+gopher
@@ -7,0 +7 @@
+mouse

But now it's full of the "@@" lines telling you the position in the file that has changed. Let's remove the extra lines to make it more readable.

for line in difflib.unified_diff(lines1, lines2, fromfile='file1', tofile='file2', lineterm='', n=0):
    for prefix in ('---', '+++', '@@'):
        if line.startswith(prefix):
            break
    else:
        print line

Giving us this output:

+cat
-cat
-gophers
-hound
+gopher
+mouse

Now what do you want it to do? If you ignore all removed lines, then you won't see that "hound" was removed. If you're happy just showing the additions to the file, then you could do this:

diff = difflib.unified_diff(lines1, lines2, fromfile='file1', tofile='file2', lineterm='', n=0)
lines = list(diff)[2:]
added = [line[1:] for line in lines if line[0] == '+']
removed = [line[1:] for line in lines if line[0] == '-']

print 'additions:'
for line in added:
    print line
print
print 'additions, ignoring position'
for line in added:
    if line not in removed:
        print line

Outputting:

additions:
cat
gopher
mouse

additions, ignoring position:
gopher
mouse

You can probably tell by now that there are various ways to "print the differences" of two files, so you will need to be very specific if you want more help.

How do I wrap text in a span?

I've got a solution that should work in IE6 (and definitely works in 7+ & FireFox/Chrome).
You were on the right track using a span, but the use of a ul was wrong and the css wasn't right.

Try this

<a class="htooltip" href="#">
    Notes

    <span>
        Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin pharetra nonummy pede. Mauris et orci.
    </span>
</a>
.htooltip, .htooltip:visited, .tooltip:active {
    color: #0077AA;
    text-decoration: none;
}

.htooltip:hover {
    color: #0099CC;
}

.htooltip span {
    display : none;
    position: absolute;
    background-color: black;
    color: #fff;
    padding: 5px 10px 5px 40px;
    text-decoration: none;
    width: 350px;
    z-index: 10;
}

.htooltip:hover span {
    display: block;
}

Everyone was going about this the wrong way. The code isn't valid, ul's cant go in a's, p's can't go in a's, div's cant go in a's, just use a span (remembering to make it display as a block so it will wrap as if it were a div/p etc).

Git on Bitbucket: Always asked for password, even after uploading my public SSH key

Hello Googlers from the future.

On MacOS >= High Sierra, the SSH key is no longer saved to the KeyChain because of reasons.

Using ssh-add -K no longer survives restarts as well.

Here are 3 possible solutions.

I've used the first method successfully. I've created a file called config in ~/.ssh:

Host *
  AddKeysToAgent yes
  UseKeychain yes
  IdentityFile ~/.ssh/id_rsa

addEventListener in Internet Explorer

I'm using this solution and works in IE8 or greater.

if (typeof Element.prototype.addEventListener === 'undefined') {
    Element.prototype.addEventListener = function (e, callback) {
      e = 'on' + e;
      return this.attachEvent(e, callback);
    };
  }

And then:

<button class="click-me">Say Hello</button>

<script>
  document.querySelectorAll('.click-me')[0].addEventListener('click', function () {
    console.log('Hello');
  });
</script>

This will work both IE8 and Chrome, Firefox, etc.

Remove accents/diacritics in a string in JavaScript

I used string.js's latinise() method, which lets you do it like this:

var output = S(input).latinise().toString();

Pass path with spaces as parameter to bat file

Interesting one. I love collecting quotes about quotes handling in cmd/command.

Your particular scripts gets fixed by using %1 instead of "%1" !!!

By adding an 'echo on' ( or getting rid of an echo off ), you could have easily found that out.

How to get the device's IMEI/ESN programmatically in android?

For Android 10 Following code is working for me.

val uid: String = Settings.Secure.getString(ctx.applicationContext.contentResolver, Settings.Secure.ANDROID_ID)
if (ContextCompat.checkSelfPermission(ctx, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
            imei = when {
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> {
                    uid
                }
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> {
                    telephonyManager.imei
                }
                else -> {
                    telephonyManager.deviceId
                }
            }
        }

Easiest way to compare arrays in C#

elementwise compare ? what about

public void Linq78a()
{
 int[] numbers1 = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
 int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
 bool bb = numbers.Zip(numbers1, (a, b) => (a == b)).Any(p => !p);
 if (!bb) Console.WriteLine("Lists are equal (bb)");
   else Console.WriteLine("Lists are not equal (bb)");
}

Replace the (a==b) condition by anything you'd like to compare in a and b.

(this combines two examples from MSDN developer Linq samples)

Is there a naming convention for MySQL?

as @fabrizio-valencia said use lower case. in windows if you export mysql database (phpmyadmin) the tables name will converted to lower case and this lead to all sort of problems. see Are table names in MySQL case sensitive?

Formatting PowerShell Get-Date inside string

"This is my string with date in specified format $($theDate.ToString('u'))"

or

"This is my string with date in specified format $(Get-Date -format 'u')"

The sub-expression ($(...)) can include arbitrary expressions calls.

MSDN Documents both standard and custom DateTime format strings.

PHP multidimensional array search by value

Try this

<?php
 function recursive_array_search($needle,$haystack) {
    foreach($haystack as $key=>$value) {
        $current_key=$key;
        if($needle===$value OR (is_array($value) && 
            recursive_array_search($needle,$value) !== false)) {
             return $current_key;
        }
    }
    return false;
 }
 ?>

Dynamically generating a QR code with PHP

I know the question is how to generate QR codes using PHP, but for others who are looking for a way to generate codes for websites doing this in pure javascript is a good way to do it. The jquery-qrcode jquery plugin does it well.

SQL Server database backup restore on lower version

you can use BCP in and out for small tables.

BCP OUT command:-

BCP "SELECT *  FROM [Dinesh].[dbo].[Invoices]" QUERYOUT C:\av\Invoices1.txt -S MC0XENTC -T -c -r c:\error.csv

BCP IN command:- Create table structure for Invoicescopy1.

BCP [Dinesh].[dbo].[Invoicescopy1] IN C:\av\Invoices.txt -S MC0XENTC -T -c

How to set placeholder value using CSS?

AFAIK, you can't do it with CSS alone. CSS has content rule but even that can be used to insert content before or after an element using pseudo selectors. You need to resort to javascript for that OR use placeholder attribute if you are using HTML5 as pointed out by @Blender.

I get a "An attempt was made to load a program with an incorrect format" error on a SQL Server replication project

We recently had the issue when trying to run the code from Visual Studio. In that case you need to do
TOOLS > OPTIONS > Projects and Solutions > WEB PROJECTS and check the "Use the 64 bit version of IIS Express for web sites and projects".

GnuPG: "decryption failed: secret key not available" error from gpg on Windows

One more cause for the "secret key not available" message: GPG version mismatch.

Practical example: I had been using GPG v1.4. Switching packaging systems, the MacPorts supplied gpg was removed, and revealed another gpg binary in the path, this one version 2.0. For decryption, it was unable to locate the secret key and gave this very error. For encryption, it complained about an unusable public key. However, gpg -k and -K both listed valid keys, which was the cause of major confusion.

Render partial view with dynamic model in Razor view engine and ASP.NET MVC 3

Can also be called as

@Html.Partial("_PartialView", (ModelClass)View.Data)

On a CSS hover event, can I change another div's styling?

The following example is based on jQuery but it can be achieved using any JS tool kit or even plain old JS

$(document).ready(function(){
     $("#a").mouseover(function(){
         $("#b").css("background-color", "red");
     });
});

Shortcut for creating single item list in C#

var list = new List<string>(1) { "hello" };

Very similar to what others have posted, except that it makes sure to only allocate space for the single item initially.

Of course, if you know you'll be adding a bunch of stuff later it may not be a good idea, but still worth mentioning once.

Android WebView not loading an HTTPS URL

Remove the below code it will work

 super.onReceivedSslError(view, handler, error);

Git adding files to repo

I had an issue with connected repository. What's how I fixed:

I deleted manually .git folder under my project folder, run git init and then it all worked.

How to set xampp open localhost:8080 instead of just localhost

Steps using XAMPP GUI:

Step-1: Click on Config button

enter image description here

Step-2: Click on Service and Port Settings button

enter image description here

Final step: Change your port and Save

enter image description here

Read url to string in few lines of java code

This answer refers to an older version of Java. You may want to look at ccleve's answer.


Here is the traditional way to do this:

import java.net.*;
import java.io.*;

public class URLConnectionReader {
    public static String getText(String url) throws Exception {
        URL website = new URL(url);
        URLConnection connection = website.openConnection();
        BufferedReader in = new BufferedReader(
                                new InputStreamReader(
                                    connection.getInputStream()));

        StringBuilder response = new StringBuilder();
        String inputLine;

        while ((inputLine = in.readLine()) != null) 
            response.append(inputLine);

        in.close();

        return response.toString();
    }

    public static void main(String[] args) throws Exception {
        String content = URLConnectionReader.getText(args[0]);
        System.out.println(content);
    }
}

As @extraneon has suggested, ioutils allows you to do this in a very eloquent way that's still in the Java spirit:

 InputStream in = new URL( "http://jakarta.apache.org" ).openStream();

 try {
   System.out.println( IOUtils.toString( in ) );
 } finally {
   IOUtils.closeQuietly(in);
 }

How to get the anchor from the URL using jQuery?

If you just have a plain url string (and therefore don't have a hash attribute) you can also use a regular expression:

var url = "www.example.com/task1/1.3.html#a_1"  
var anchor = url.match(/#(.*)/)[1] 

How to set Python's default version to 3.x on OS X?

Go to terminal type:

alias python=python3.x

This will setup default python as python3.x

Deleting queues in RabbitMQ

You assert that a queue exists (and create it if it does not) by using queue.declare. If you originally set auto-delete to false, calling queue.declare again with autodelete true will result in a soft error and the broker will close the channel.

You need to use queue.delete now in order to delete it.

See the API documentation for details:

If you use another client, you'll need to find the equivalent method. Since it's part of the protocol, it should be there, and it's probably part of Channel or the equivalent.

You might also want to have a look at the rest of the documentation, in particular the Geting Started section which covers a lot of common use cases.

Finally, if you have a question and can't find the answer elsewhere, you should try posting on the RabbitMQ Discuss mailing list. The developers do their best to answer all questions asked there.

Change Name of Import in Java, or import two classes with the same name

There is no import aliasing mechanism in Java. You cannot import two classes with the same name and use both of them unqualified.

Import one class and use the fully qualified name for the other one, i.e.

import com.text.Formatter;

private Formatter textFormatter;
private com.json.Formatter jsonFormatter;

Call parent method from child class c#

To follow up on the comment by suhendri to Rory McCrossan answer. Here is an Action delegate example:

In child add:

public Action UpdateProgress;  // In place of event handler declaration
                               // declare an Action delegate
.
.
.
private LoadData() {
    this.UpdateProgress();    // call to Action delegate - MyMethod in
                              // parent
}

In parent add:

// The 3 lines in the parent becomes:
ChildClass child = new ChildClass();
child.UpdateProgress = this.MyMethod;  // assigns MyMethod to child delegate

Is it a good practice to use try-except-else in Python?

Just because no-one else has posted this opinion, I would say

avoid else clauses in try/excepts because they're unfamiliar to most people

Unlike the keywords try, except, and finally, the meaning of the else clause isn't self-evident; it's less readable. Because it's not used very often, it'll cause people that read your code to want to double-check the docs to be sure they understand what's going on.

(I'm writing this answer precisely because I found a try/except/else in my codebase and it caused a wtf moment and forced me to do some googling).

So, wherever I see code like the OP example:

try:
    try_this(whatever)
except SomeException as the_exception:
    handle(the_exception)
else:
    # do some more processing in non-exception case
    return something

I would prefer to refactor to

try:
    try_this(whatever)
except SomeException as the_exception:
    handle(the_exception)
    return  # <1>
# do some more processing in non-exception case  <2>
return something
  • <1> explicit return, clearly shows that, in the exception case, we are finished working

  • <2> as a nice minor side-effect, the code that used to be in the else block is dedented by one level.

How do I install Python OpenCV through Conda?

You can install OpenCV by running these commands in the Anaconda command prompt:

conda config --add channels conda-forge

conda install libopencv opencv py-opencv

Source:

https://github.com/conda-forge/opencv-feedstock

Vibrate and Sound defaults on notification

I m using the followung code and its working fine for me .

private void sendNotification(String msg) {
    Log.d(TAG, "Preparing to send notification...: " + msg);
    mNotificationManager = (NotificationManager) this
            .getSystemService(Context.NOTIFICATION_SERVICE);

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, MainActivity.class), 0);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            this).setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("GCM Notification")
            .setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_ALL)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
            .setContentText(msg);

    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    Log.d(TAG, "Notification sent successfully.");
}

How to edit log message already committed in Subversion?

svnadmin setlog /path/to/repository -r revision_number --bypass-hooks message_file.txt

./configure : /bin/sh^M : bad interpreter

To fix, open your script with vi or vim and enter in vi command mode (key Esc), then type this:

:set fileformat=unix

Finally save it

:x! or :wq!

Escaping special characters in Java Regular Expressions

The Pattern.quote(String s) sort of does what you want. However it leaves a little left to be desired; it doesn't actually escape the individual characters, just wraps the string with \Q...\E.

There is not a method that does exactly what you are looking for, but the good news is that it is actually fairly simple to escape all of the special characters in a Java regular expression:

regex.replaceAll("[\\W]", "\\\\$0")

Why does this work? Well, the documentation for Pattern specifically says that its permissible to escape non-alphabetic characters that don't necessarily have to be escaped:

It is an error to use a backslash prior to any alphabetic character that does not denote an escaped construct; these are reserved for future extensions to the regular-expression language. A backslash may be used prior to a non-alphabetic character regardless of whether that character is part of an unescaped construct.

For example, ; is not a special character in a regular expression. However, if you escape it, Pattern will still interpret \; as ;. Here are a few more examples:

  • > becomes \> which is equivalent to >
  • [ becomes \[ which is the escaped form of [
  • 8 is still 8.
  • \) becomes \\\) which is the escaped forms of \ and ( concatenated.

Note: The key is is the definition of "non-alphabetic", which in the documentation really means "non-word" characters, or characters outside the character set [a-zA-Z_0-9].

How to set margin with jquery?

try

el.css('margin-left',mrg+'px');

Execute raw SQL using Doctrine 2

I had the same problem. You want to look the connection object supplied by the entity manager:

$conn = $em->getConnection();

You can then query/execute directly against it:

$statement = $conn->query('select foo from bar');
$num_rows_effected = $conn->exec('update bar set foo=1');

See the docs for the connection object at http://www.doctrine-project.org/api/dbal/2.0/doctrine/dbal/connection.html

print highest value in dict with key

You could use use max and min with dict.get:

maximum = max(mydict, key=mydict.get)  # Just use 'min' instead of 'max' for minimum.
print(maximum, mydict[maximum])
# D 87

Remove empty strings from a list of strings

Depending on the size of your list, it may be most efficient if you use list.remove() rather than create a new list:

l = ["1", "", "3", ""]

while True:
  try:
    l.remove("")
  except ValueError:
    break

This has the advantage of not creating a new list, but the disadvantage of having to search from the beginning each time, although unlike using while '' in l as proposed above, it only requires searching once per occurrence of '' (there is certainly a way to keep the best of both methods, but it is more complicated).

Split string with delimiters in C

String tokenizer this code should put you in the right direction.

int main(void) {
  char st[] ="Where there is will, there is a way.";
  char *ch;
  ch = strtok(st, " ");
  while (ch != NULL) {
  printf("%s\n", ch);
  ch = strtok(NULL, " ,");
  }
  getch();
  return 0;
}

Get 2 Digit Number For The Month

For me the quickest solution was

DATE_FORMAT(CURDATE(),'%m')

Random number from a range in a Bash Script

shuf -i 2000-65000 -n 1

Enjoy!

Edit: The range is inclusive.

$(document).on('click', '#id', function() {}) vs $('#id').on('click', function(){})

The first example demonstrates event delegation. The event handler is bound to an element higher up the DOM tree (in this case, the document) and will be executed when an event reaches that element having originated on an element matching the selector.

This is possible because most DOM events bubble up the tree from the point of origin. If you click on the #id element, a click event is generated that will bubble up through all of the ancestor elements (side note: there is actually a phase before this, called the 'capture phase', when the event comes down the tree to the target). You can capture the event on any of those ancestors.

The second example binds the event handler directly to the element. The event will still bubble (unless you prevent that in the handler) but since the handler is bound to the target, you won't see the effects of this process.

By delegating an event handler, you can ensure it is executed for elements that did not exist in the DOM at the time of binding. If your #id element was created after your second example, your handler would never execute. By binding to an element that you know is definitely in the DOM at the time of execution, you ensure that your handler will actually be attached to something and can be executed as appropriate later on.

Java 8 stream map to list of keys sorted by values

You have to sort with a custom comparator based on the value of the entry. Then select all the keys before collecting

countByType.entrySet()
           .stream()
           .sorted((e1, e2) -> e1.getValue().compareTo(e2.getValue())) // custom Comparator
           .map(e -> e.getKey())
           .collect(Collectors.toList());

How to Detect Browser Window /Tab Close Event?

to make the difference between a refresh and a closed tab or navigator, here is how I fixed it :

_x000D_
_x000D_
<script>_x000D_
    function endSession() {_x000D_
         // Browser or Broswer tab is closed_x000D_
         // Write code here_x000D_
    }_x000D_
</script>_x000D_
_x000D_
<body onpagehide="endSession();">_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_

#1025 - Error on rename of './database/#sql-2e0f_1254ba7' to './database/table' (errno: 150)

For those who are getting to this question via google... this error can also happen if you try to rename a field that is acting as a foreign key.

Git command to show which specific files are ignored by .gitignore

(extending the other answers)

Note, git check-ignore uses the committed .gitignore and not the one in your working tree! To play with it without polluting your git history, you might freely try to edit it, and then commit with a git commit --amend.

This problem happens mainly if you need a workaround of the problem, that git doesn't follow directories. Enter in the .gitignore:

dirtokeep/**
!dirtokeep/.keep

.keep should be a zero-length file in dirtokeep.

The result will be that everything in dirtokeep will be ignored, except dirtokeep/.keep, which will result that also the dirtokeep directory will be constructed on clone/checkout.

When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?

Try this

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String userName = authentication.getName();

jQuery: get the file name selected from <input type="file" />

Add a hidden reset button :

<input id="Reset1" type="reset" value="reset" class="hidden" />

Click the reset button to clear the input.

$("#Reset1").click();

Status bar and navigation bar appear over my view's bounds in iOS 7

If you want the view to have the translucent nav bar (which is kind of nice) you have to setup a contentInset or similar.

Here is how I do it:

// Check if we are running on ios7
if([[[[UIDevice currentDevice] systemVersion] componentsSeparatedByString:@"."][0] intValue] >= 7) {
      CGRect statusBarViewRect = [[UIApplication sharedApplication] statusBarFrame];
      float heightPadding = statusBarViewRect.size.height+self.navigationController.navigationBar.frame.size.height;

      myContentView.contentInset = UIEdgeInsetsMake(heightPadding, 0.0, 0.0, 0.0);
}

Import Python Script Into Another?

It's worth mentioning that (at least in python 3), in order for this to work, you must have a file named __init__.py in the same directory.

How to set character limit on the_content() and the_excerpt() in wordpress

wp_trim_words This function trims text to a certain number of words and returns the trimmed text.

Example:-

echo wp_trim_words( get_the_content(), 40, '...' );

Specified argument was out of the range of valid values. Parameter name: site

If you are okay with using the built in Visual Studio Development server or you don't want to or cannot install IIS, you can change the web server the project uses by going into

  1. Project Properties (right click project in solution explorer and select properties)

  2. select Web tab

  3. select "Use Visual Studio Development Server".

I don't know how it happened to me, but somehow this option was changed to "Use Local IIS Web Server" for one of my projects.

Undefined index with $_POST

When you say:

$user = $_POST["username"];

You're asking the PHP interpreter to assign $user the value of the $_POST array that has a key (or index) of username. If it doesn't exist, PHP throws a fit.

Use isset($_POST['user']) to check for the existence of that variable:

if (isset($_POST['user'])) {
  $user = $_POST["username"];
  ...

Regular Expression to match only alphabetic characters

In Ruby and other languages that support POSIX character classes in bracket expressions, you can do simply:

/\A[[:alpha:]]+\z/i

That will match alpha-chars in all Unicode alphabet languages. Easy peasy.

More info: http://en.wikipedia.org/wiki/Regular_expression#Character_classes http://ruby-doc.org/core-2.0/Regexp.html

How to exclude 0 from MIN formula Excel

All you have to do is to delete the "0" in the cells that contain just that and try again. That should work.

Best way to encode text data for XML in Java?

Just replace

 & with &amp;

And for other characters:

> with &gt;
< with &lt;
\" with &quot;
' with &apos;

How to parse month full form string using DateFormat in Java?

val currentTime = Calendar.getInstance().time
SimpleDateFormat("MMMM", Locale.getDefault()).format(date.time)

How can I send and receive WebSocket messages on the server side?

Thank you for the answer, i would like to add onto hfern's(above) Python version to include the Sending function if any one is interested.

def DecodedWebsockRecieve(stringStreamIn):
    byteArray =  stringStreamIn 
    datalength = byteArray[1] & 127
    indexFirstMask = 2 
    if datalength == 126:
        indexFirstMask = 4
    elif datalength == 127:
        indexFirstMask = 10
    masks = [m for m in byteArray[indexFirstMask : indexFirstMask+4]]
    indexFirstDataByte = indexFirstMask + 4
    decodedChars = []
    i = indexFirstDataByte
    j = 0
    while i < len(byteArray):
        decodedChars.append( chr(byteArray[i] ^ masks[j % 4]) )
        i += 1
        j += 1
    return ''.join(decodedChars)

def EncodeWebSockSend(socket,data):
    bytesFormatted = []
    bytesFormatted.append(129)

    bytesRaw = data.encode()
    bytesLength = len(bytesRaw)
    if bytesLength <= 125 :
        bytesFormatted.append(bytesLength)
    elif bytesLength >= 126 and bytesLength <= 65535 :
        bytesFormatted.append(126)
        bytesFormatted.append( ( bytesLength >> 8 ) & 255 )
        bytesFormatted.append( bytesLength & 255 )
    else :
        bytesFormatted.append( 127 )
        bytesFormatted.append( ( bytesLength >> 56 ) & 255 )
        bytesFormatted.append( ( bytesLength >> 48 ) & 255 )
        bytesFormatted.append( ( bytesLength >> 40 ) & 255 )
        bytesFormatted.append( ( bytesLength >> 32 ) & 255 )
        bytesFormatted.append( ( bytesLength >> 24 ) & 255 )
        bytesFormatted.append( ( bytesLength >> 16 ) & 255 )
        bytesFormatted.append( ( bytesLength >>  8 ) & 255 )
        bytesFormatted.append( bytesLength & 255 )

    bytesFormatted = bytes(bytesFormatted)
    bytesFormatted = bytesFormatted + bytesRaw
    socket.send(bytesFormatted) 

Usage for reading:

bufSize = 1024     
read = DecodedWebsockRecieve(socket.recv(bufSize))

Usage for writing:

EncodeWebSockSend(sock,"hellooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo")

What is the best way to implement constants in Java?

A good object oriented design should not need many publicly available constants. Most constants should be encapsulated in the class that needs them to do its job.

CSS background-image - What is the correct usage?

you really don't need quotes if let say use are using the image from your css file it can be

{background-image: url(your image.png/jpg etc);}

How to calculate DATE Difference in PostgreSQL?

a simple way would be to cast the dates into timestamps and take their difference and then extract the DAY part.

if you want real difference

select extract(day from 'DATE_A'::timestamp - 'DATE_B':timestamp);

if you want absolute difference

select abs(extract(day from 'DATE_A'::timestamp - 'DATE_B':timestamp));

How do I check if a directory exists? "is_dir", "file_exists" or both?

I had the same doubt, but see the PHP docu:

https://www.php.net/manual/en/function.file-exists.php

https://www.php.net/manual/en/function.is-dir.php

You will see that is_dir() has both properties.

Return Values is_dir Returns TRUE if the filename exists and is a directory, FALSE otherwise.

Best C++ IDE or Editor for Windows

I have used Netbeans for java, and it works great. Not sure how it works with C++, though.

100% Min Height CSS layout

I agree with Levik as the parent container is set to 100% if you have sidebars and want them to fill the space to meet up with the footer you cannot set them to 100% because they will be 100 percent of the parent height as well which means that the footer ends up getting pushed down when using the clear function.

Think of it this way if your header is say 50px height and your footer is 50px height and the content is just autofitted to the remaining space say 100px for example and the page container is 100% of this value its height will be 200px. Then when you set the sidebar height to 100% it is then 200px even though it is supposed to fit snug in between the header and footer. Instead it ends up being 50px + 200px + 50px so the page is now 300px because the sidebars are set to the same height as the page container. There will be a big white space in the contents of the page.

I am using internet Explorer 9 and this is what I am getting as the effect when using this 100% method. I havent tried it in other browsers and I assume that it may work in some of the other options. but it will not be universal.

convert string to specific datetime format?

More formats:

 require 'date'

 date = "01/07/2016 09:17AM"
 DateTime.parse(date).strftime("%A, %b %d")
 #=> Friday, Jul 01

 DateTime.parse(date).strftime("%m/%d/%Y")
 #=> 07/01/2016

 DateTime.parse(date).strftime("%m-%e-%y %H:%M")
 #=> 07- 1-16 09:17

 DateTime.parse(date).strftime("%b %e")
 #=> Jul  1

 DateTime.parse(date).strftime("%l:%M %p")
 #=>  9:17 AM

 DateTime.parse(date).strftime("%B %Y")
 #=> July 2016
 DateTime.parse(date).strftime("%b %d, %Y")
 #=> Jul 01, 2016
 DateTime.parse(date).strftime("%a, %e %b %Y %H:%M:%S %z")
 #=> Fri,  1 Jul 2016 09:17:00 +0200
 DateTime.parse(date).strftime("%Y-%m-%dT%l:%M:%S%z")
 #=> 2016-07-01T 9:17:00+0200
 DateTime.parse(date).strftime("%I:%M:%S %p")
 #=> 09:17:00 AM
 DateTime.parse(date).strftime("%H:%M:%S")
 #=> 09:17:00
 DateTime.parse(date).strftime("%e %b %Y %H:%M:%S%p")
 #=>  1 Jul 2016 09:17:00AM
 DateTime.parse(date).strftime("%d.%m.%y")
 #=> 01.07.16
 DateTime.parse(date).strftime("%A, %d %b %Y %l:%M %p")
 #=> Friday, 01 Jul 2016  9:17 AM

How can I override Bootstrap CSS styles?

I found out that (bootstrap 4) putting your own CSS behind bootstrap.css and .js is the best solution.

Find the item you want to change (inspect element) and use the exact same declaration then it will override.

It took me some little time to figure this out.

Fade In Fade Out Android Animation in Java

AnimationSets don't appear to work as expected at all. In the end I gave up and used the Handler class's postDelayed() to sequence animations.

How do I get an animated gif to work in WPF?

Basically the same PictureBox solution above, but this time with the code-behind to use an Embedded Resource in your project:

In XAML:

<WindowsFormsHost x:Name="_loadingHost">
  <Forms:PictureBox x:Name="_loadingPictureBox"/>
</WindowsFormsHost>

In Code-Behind:

public partial class ProgressIcon
{
    public ProgressIcon()
    {
        InitializeComponent();
        var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("My.Namespace.ProgressIcon.gif");
        var image = System.Drawing.Image.FromStream(stream);
        Loaded += (s, e) => _loadingPictureBox.Image = image;
    }
}

Get first day of week in SQL Server

For those who need the answer at work and creating function is forbidden by your DBA, the following solution will work:

select *,
cast(DATEADD(day, -1*(DATEPART(WEEKDAY, YouDate)-1), YourDate) as DATE) as WeekStart
From.....

This gives the start of that week. Here I assume that Sundays are the start of weeks. If you think that Monday is the start, you should use:

select *,
cast(DATEADD(day, -1*(DATEPART(WEEKDAY, YouDate)-2), YourDate) as DATE) as WeekStart
From.....

Right way to convert data.frame to a numeric matrix, when df also contains strings?

Edit 2: See @flodel's answer. Much better.

Try:

# assuming SFI is your data.frame
as.matrix(sapply(SFI, as.numeric))  

Edit: or as @ CarlWitthoft suggested in the comments:

matrix(as.numeric(unlist(SFI)),nrow=nrow(SFI))

Is `shouldOverrideUrlLoading` really deprecated? What can I use instead?

Use

public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
    return shouldOverrideUrlLoading(view, request.getUrl().toString());
}

How to iterate over a TreeMap?

    //create TreeMap instance
    TreeMap treeMap = new TreeMap();

    //add key value pairs to TreeMap
    treeMap.put("1","One");
    treeMap.put("2","Two");
    treeMap.put("3","Three");

    /*
      get Collection of values contained in TreeMap using
      Collection values()        
    */
    Collection c = treeMap.values();

    //obtain an Iterator for Collection
    Iterator itr = c.iterator();

    //iterate through TreeMap values iterator
    while(itr.hasNext())
      System.out.println(itr.next());

or:

   for (Map.Entry<K,V> entry : treeMap.entrySet()) {
        V value = entry.getValue();
        K key = entry.getKey();
   }

or:

   // Use iterator to display the keys and associated values
   System.out.println("Map Values Before: ");
   Set keys = map.keySet();
   for (Iterator i = keys.iterator(); i.hasNext();) {
     Integer key = (Integer) i.next();
     String value = (String) map.get(key);
     System.out.println(key + " = " + value);
   }

Python: How exactly can you take a string, split it, reverse it and join it back together again?

You mean this?

from string import punctuation, digits

takeout = punctuation + digits

turnthis = "(fjskl) 234 = -345 089 abcdef"
turnthis = turnthis.translate(None, takeout)[::-1]
print turnthis

How to parse JSON string in Typescript

TS has a JavaScript runtime

Typescript has a JavaScript runtime because it gets compiled to JS. This means JS objects which are built in as part of the language such as JSON, Object, and Math are also available in TS. Therefore we can just use the JSON.parse method to parse the JSON string.

Example:

const JSONStr = '{"name": "Bob", "error": false}'

// The JSON object is part of the runtime
const parsedObj = JSON.parse(JSONStr);

console.log(parsedObj);
// [LOG]: {
//   "name": "Bob",
//   "error": false
// } 

// The Object object is also part of the runtime so we can use it in TS
const objKeys = Object.keys(parsedObj);

console.log(objKeys);
// [LOG]: ["name", "error"] 

The only thing now is that parsedObj is type any which is generally a bad practice in TS. We can type the object if we are using type guards. Here is an example:

const JSONStr = '{"name": "Bob", "error": false}'
const parsedObj = JSON.parse(JSONStr);

interface nameErr {
  name: string;
  error: boolean;
}

function isNameErr(arg: any): arg is nameErr {
  if (typeof arg.name === 'string' && typeof arg.error === 'boolean') {
    return true;
  } else {
    return false;
  }
}

if (isNameErr(parsedObj)) {
  // Within this if statement parsedObj is type nameErr;
  parsedObj
}

How can you run a command in bash over and over until success?

You need to test $? instead, which is the exit status of the previous command. passwd exits with 0 if everything worked ok, and non-zero if the passwd change failed (wrong password, password mismatch, etc...)

passwd
while [ $? -ne 0 ]; do
    passwd
done

With your backtick version, you're comparing passwd's output, which would be stuff like Enter password and confirm password and the like.

How to replace all spaces in a string

    $('#title').keyup(function () {
        var replaceSpace = $(this).val();

        var result = replaceSpace.replace(/\s/g, ";");

        $("#keyword").val(result);

    });

Since the javascript replace function do not replace 'all', we can make use the regular expression for replacement. As per your need we have to replace all space ie the \s in your string globally. The g character after the regular expressions represents the global replacement. The seond parameter will be the replacement character ie the semicolon.

JavaScript file upload size validation

Works for Dynamic and Static File Element

Javascript Only Solution

_x000D_
_x000D_
function ValidateSize(file) {
        var FileSize = file.files[0].size / 1024 / 1024; // in MiB
        if (FileSize > 2) {
            alert('File size exceeds 2 MiB');
           // $(file).val(''); //for clearing with Jquery
        } else {

        }
    }
_x000D_
 <input onchange="ValidateSize(this)" type="file">
_x000D_
_x000D_
_x000D_

Export P7b file with all the certificate chain into CER file

If you add -chain to your command line, it will export any chained certificates.

http://www.openssl.org/docs/apps/pkcs12.html

Date Difference in php on days?

I would recommend to use date->diff function, as in example below:

   $dStart = new DateTime('2012-07-26');
   $dEnd  = new DateTime('2012-08-26');
   $dDiff = $dStart->diff($dEnd);
   echo $dDiff->format('%r%a'); // use for point out relation: smaller/greater

see http://www.php.net/manual/en/datetime.diff.php

Making a mocked method return an argument that was passed to it

This is a bit old, but I came here because I had the same issue. I'm using JUnit but this time in a Kotlin app with mockk. I'm posting a sample here for reference and comparison with the Java counterpart:

@Test
fun demo() {
  // mock a sample function
  val aMock: (String) -> (String) = mockk()

  // make it return the same as the argument on every invocation
  every {
    aMock.invoke(any())
  } answers {
    firstArg()
  }

  // test it
  assertEquals("senko", aMock.invoke("senko"))
  assertEquals("senko1", aMock.invoke("senko1"))
  assertNotEquals("not a senko", aMock.invoke("senko"))
}

PHP Checking if the current date is before or after a set date

if (strtotime($date) > mktime(0,0,0)) should do the job.

How to compare numbers in bash?

I solved this by using a small function to convert version strings to plain integer values that can be compared:

function versionToInt() {
  local IFS=.
  parts=($1)
  let val=1000000*parts[0]+1000*parts[1]+parts[2]
  echo $val
}

This makes two important assumptions:

  1. Input is a "normal SemVer string"
  2. Each part is between 0-999

For example

versionToInt 12.34.56  # --> 12034056
versionToInt 1.2.3     # -->  1002003

Example testing whether npm command meets minimum requirement ...

NPM_ACTUAL=$(versionToInt $(npm --version))  # Capture npm version
NPM_REQUIRED=$(versionToInt 4.3.0)           # Desired version
if [ $NPM_ACTUAL \< $NPM_REQUIRED ]; then
  echo "Please update to npm@latest"
  exit 1
fi

How to normalize a histogram in MATLAB?

My answer to this is the same as in an answer to your earlier question. For a probability density function, the integral over the entire space is 1. Dividing by the sum will not give you the correct density. To get the right density, you must divide by the area. To illustrate my point, try the following example.

[f, x] = hist(randn(10000, 1), 50); % Create histogram from a normal distribution.
g = 1 / sqrt(2 * pi) * exp(-0.5 * x .^ 2); % pdf of the normal distribution

% METHOD 1: DIVIDE BY SUM
figure(1)
bar(x, f / sum(f)); hold on
plot(x, g, 'r'); hold off

% METHOD 2: DIVIDE BY AREA
figure(2)
bar(x, f / trapz(x, f)); hold on
plot(x, g, 'r'); hold off

You can see for yourself which method agrees with the correct answer (red curve).

enter image description here

Another method (more straightforward than method 2) to normalize the histogram is to divide by sum(f * dx) which expresses the integral of the probability density function, i.e.

% METHOD 3: DIVIDE BY AREA USING sum()
figure(3)
dx = diff(x(1:2))
bar(x, f / sum(f * dx)); hold on
plot(x, g, 'r'); hold off