Programs & Examples On #Headereditemscontrol

Combining the results of two SQL queries as separate columns

how to club the 4 query's as a single query

show below query

  1. total number of cases pending + 2.cases filed during this month ( base on sysdate) + total number of cases (1+2) + no. cases disposed where nse= disposed + no. of cases pending (other than nse <> disposed)

nsc = nature of case

report is taken on 06th of every month

( monthly report will be counted from 05th previous month to 05th present of present month)

Targeting only Firefox with CSS

First of all, a disclaimer. I don't really advocate for the solution I present below. The only browser specific CSS I write is for IE (especially IE6), although I wish it wasn't the case.

Now, the solution. You asked it to be elegant so I don't know how elegant is it but it's sure going to target Gecko platforms only.

The trick is only working when JavaScript is enabled and makes use of Mozilla bindings (XBL), which are heavily used internally in Firefox and all other Gecko-based products. For a comparison, this is like the behavior CSS property in IE, but much more powerful.

Three files are involved in my solution:

  1. ff.html: the file to style
  2. ff.xml: the file containg the Gecko bindings
  3. ff.css: Firefox specific styling

ff.html

<!DOCTYPE html>

<html>
<head>
<style type="text/css">
body {
 -moz-binding: url(ff.xml#load-mozilla-css);
}
</style>
</head>
<body>

<h1>This should be red in FF</h1>

</body>
</html>

ff.xml

<?xml version="1.0"?>

<bindings xmlns="http://www.mozilla.org/xbl">
    <binding id="load-mozilla-css">
        <implementation>
            <constructor>
            <![CDATA[
                var link = document.createElement("link");
                    link.setAttribute("rel", "stylesheet");
                    link.setAttribute("type", "text/css");
                    link.setAttribute("href", "ff.css");

                document.getElementsByTagName("head")[0]
                        .appendChild(link);
            ]]>
            </constructor>
        </implementation>
    </binding>
</bindings>

ff.css

h1 {
 color: red;
}

Update: The above solution is not that good. It would be better if instead of appending a new LINK element it will add that "firefox" class on the BODY element. And it's possible, just by replacing the above JS with the following:

this.className += " firefox";

The solution is inspired by Dean Edwards' moz-behaviors.

How to extract text from a PDF file?

Use pdfminer.six. Here is the the doc : https://pdfminersix.readthedocs.io/en/latest/index.html

To convert pdf to text :

    def pdf_to_text():
        from pdfminer.high_level import extract_text

        text = extract_text('test.pdf')
        print(text)

How to get jSON response into variable from a jquery script

Look out for this pitfal: http://www.vertstudios.com/blog/avoiding-ajax-newline-pitfall/

Searched several houres before I found there were some linebreaks in the included files.

super() in Java

As stated, inside the default constructor there is an implicit super() called on the first line of the constructor.

This super() automatically calls a chain of constructors starting at the top of the class hierarchy and moves down the hierarchy .

If there were more than two classes in the class hierarchy of the program, the top class default constructor would get called first.

Here is an example of this:

class A {
    A() {
    System.out.println("Constructor A");
    }
}

class B extends A{

    public B() {
    System.out.println("Constructor B");
    }
}

class C extends B{ 

    public C() {
    System.out.println("Constructor C");
    }

    public static void main(String[] args) {
    C c1 = new C();
    }
} 

The above would output:

Constructor A
Constructor B
Constructor C

How can I use a JavaScript variable as a PHP variable?

You can do what you want, but not like that. What you need to do is make an AJAX request from JavaScript back to the server where a separate PHP script can do the database operation.

How to hide 'Back' button on navigation bar on iPhone?

In Swift:

Add this to the controller

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationItem.setHidesBackButton(true, animated: false)
}

What's the console.log() of java?

public class Console {

    public static void Log(Object obj){
        System.out.println(obj);
    }
}

to call and use as JavaScript just do this:

Console.Log (Object)

I think that's what you mean

Powershell v3 Invoke-WebRequest HTTPS error

An alternative implementation in pure (without Add-Type of source):

#requires -Version 5
#requires -PSEdition Desktop

class TrustAllCertsPolicy : System.Net.ICertificatePolicy {
    [bool] CheckValidationResult([System.Net.ServicePoint] $a,
                                 [System.Security.Cryptography.X509Certificates.X509Certificate] $b,
                                 [System.Net.WebRequest] $c,
                                 [int] $d) {
        return $true
    }
}
[System.Net.ServicePointManager]::CertificatePolicy = [TrustAllCertsPolicy]::new()

How to create dynamic href in react render function?

You can use ES6 backtick syntax too

<a href={`/customer/${item._id}`} >{item.get('firstName')} {item.get('lastName')}</a>

More info on es6 template literals

How to add Apache HTTP API (legacy) as compile-time dependency to build.grade for Android M?

Just copied file: org.apache.http.legacy.jar from Android/Sdk/platforms/android-23/optional folder into project folder app/libs.

Worked like charm for 23.1.1.

Rest-assured. Is it possible to extract value from request json?

There are several ways. I personally use the following ones:

extracting single value:

String user_Id =
given().
when().
then().
extract().
        path("user_id");

work with the entire response when you need more than one:

Response response =
given().
when().
then().
extract().
        response();

String userId = response.path("user_id");

extract one using the JsonPath to get the right type:

long userId =
given().
when().
then().
extract().
        jsonPath().getLong("user_id");

Last one is really useful when you want to match against the value and the type i.e.

assertThat(
    when().
    then().
    extract().
            jsonPath().getLong("user_id"), equalTo(USER_ID)
);

The rest-assured documentation is quite descriptive and full. There are many ways to achieve what you are asking: https://github.com/jayway/rest-assured/wiki/Usage

Duplicate keys in .NET dictionaries?

When using the List<KeyValuePair<string, object>> option, you could use LINQ to do the search:

List<KeyValuePair<string, object>> myList = new List<KeyValuePair<string, object>>();
//fill it here
var q = from a in myList Where a.Key.Equals("somevalue") Select a.Value
if(q.Count() > 0){ //you've got your value }

Get statistics for each group (such as count, mean, etc) using pandas GroupBy?

Please try this code

new_column=df[['col1', 'col2', 'col3', 'col4']].groupby(['col1', 'col2']).count()
df['count_it']=new_column
df

I think that code will add a column called 'count it' which count of each group

How can I make a list of lists in R?

Using your example::

list1 <- list()
list1[1] = 1
list1[2] = 2
list2 <- list()
list2[1] = 'a'
list2[2] = 'b'
list_all <- list(list1, list2)

Use '[[' to retrieve an element of a list:

b = list_all[[1]]
 b
[[1]]
[1] 1

[[2]]
[1] 2

class(b)
[1] "list"

Equivalent of varchar(max) in MySQL?

The max length of a varchar is

65535

divided by the max byte length of a character in the character set the column is set to (e.g. utf8=3 bytes, ucs2=2, latin1=1).

minus 2 bytes to store the length

minus the length of all the other columns

minus 1 byte for every 8 columns that are nullable. If your column is null/not null this gets stored as one bit in a byte/bytes called the null mask, 1 bit per column that is nullable.

Set up DNS based URL forwarding in Amazon Route53

If you're still having issues with the simple approach, creating an empty bucket then Redirect all requests to another host name under Static web hosting in properties via the console. Ensure that you have set 2 A records in route53, one for final-destination.com and one for redirect-to.final-destination.com. The settings for each of these will be identical, but the name will be different so it matches the names that you set for your buckets / URLs.

HTML / CSS How to add image icon to input type="button"?

What I would do is do this:

Use a button type

 <button type="submit" style="background-color:rgba(255,255,255,0.0); border:none;" id="resultButton" onclick="showResults();"><img src="images/search.png" /></button>

I used background-color:rgba(255,255,255,0.0); So that the original background color of a button goes away. The same with the border:none; it will take the original border away.

The provided URI scheme 'https' is invalid; expected 'http'. Parameter name: via

Adding this as an answer, just since you can't do much fancy formatting in comments.
I had the same issue, except I was creating and binding my web service client entirely in code.
Reason is the DLL was being uploaded into a system, which prohibited the use of config files.

Here is the code as it needed to be updated to communicate over SSL...

Public Function GetWebserviceClient() As WebWorker.workerSoapClient
    Dim binding = New BasicHttpBinding()
    binding.Name = "WebWorkerSoap"
    binding.CloseTimeout = TimeSpan.FromMinutes(1)
    binding.OpenTimeout = TimeSpan.FromMinutes(1)
    binding.ReceiveTimeout = TimeSpan.FromMinutes(10)
    binding.SendTimeout = TimeSpan.FromMinutes(1)

    '// HERE'S THE IMPORTANT BIT FOR SSL
    binding.Security.Mode = BasicHttpSecurityMode.Transport

    Dim endpoint = New EndpointAddress("https://myurl/worker.asmx")

    Return New WebWorker.workerSoapClient(binding, endpoint)
End Function

Easy way to export multiple data.frame to multiple Excel worksheets

You can write to multiple sheets with the xlsx package. You just need to use a different sheetName for each data frame and you need to add append=TRUE:

library(xlsx)
write.xlsx(dataframe1, file="filename.xlsx", sheetName="sheet1", row.names=FALSE)
write.xlsx(dataframe2, file="filename.xlsx", sheetName="sheet2", append=TRUE, row.names=FALSE)

Another option, one that gives you more control over formatting and where the data frame is placed, is to do everything within R/xlsx code and then save the workbook at the end. For example:

wb = createWorkbook()

sheet = createSheet(wb, "Sheet 1")

addDataFrame(dataframe1, sheet=sheet, startColumn=1, row.names=FALSE)
addDataFrame(dataframe2, sheet=sheet, startColumn=10, row.names=FALSE)

sheet = createSheet(wb, "Sheet 2")

addDataFrame(dataframe3, sheet=sheet, startColumn=1, row.names=FALSE)

saveWorkbook(wb, "My_File.xlsx")

In case you might find it useful, here are some interesting helper functions that make it easier to add formatting, metadata, and other features to spreadsheets using xlsx: http://www.sthda.com/english/wiki/r2excel-read-write-and-format-easily-excel-files-using-r-software

How to cherry-pick from a remote branch?

If you have fetched, yet this still happens, the following might be a reason.

It can happen that the commit you are trying to pick, is no longer belonging to any branch. This may happen when you rebase.

In such case, at the remote repo:

  1. git checkout xxxxx
  2. git checkout -b temp-branch

Then in your repo, fetch again. The new branch will be fetched, including that commit.

correct way to define class variables in Python

I think this sample explains the difference between the styles:

james@bodacious-wired:~$cat test.py 
#!/usr/bin/env python

class MyClass:
    element1 = "Hello"

    def __init__(self):
        self.element2 = "World"

obj = MyClass()

print dir(MyClass)
print "--"
print dir(obj)
print "--"
print obj.element1 
print obj.element2
print MyClass.element1 + " " + MyClass.element2
james@bodacious-wired:~$./test.py 
['__doc__', '__init__', '__module__', 'element1']
--
['__doc__', '__init__', '__module__', 'element1', 'element2']
--
Hello World
Hello
Traceback (most recent call last):
  File "./test.py", line 17, in <module>
    print MyClass.element2
AttributeError: class MyClass has no attribute 'element2'

element1 is bound to the class, element2 is bound to an instance of the class.

mySQL convert varchar to date

As gratitude to the timely help I got from here - a minor update to above.

$query = "UPDATE `db`.`table` SET `fieldname`=  str_to_date(  fieldname, '%d/%m/%Y')";

Remove Blank option from Select Option with AngularJS

Here is an updated fiddle: http://jsfiddle.net/UKySp/

You needed to set your initial model value to the actual object:

$scope.feed.config = $scope.configs[0];

And update your select to look like this:

<select ng-model="feed.config" ng-options="item.name for item in configs">

Java Desktop application: SWT vs. Swing

One thing to consider: Screenreaders

For some reasons, some Swing components do not work well when using a screenreader (and the Java AccessBridge for Windows). Know that different screenreaders result in different behaviour. And in my experience the SWT-Tree performs a lot better than the Swing-Tree in combination with a screenreader. Thus our application ended up in using both SWT and Swing components.

For distributing and loading the proper SWT-library, you might find this link usefull: http://www.chrisnewland.com/select-correct-swt-jar-for-your-os-and-jvm-at-runtime-191

How do you search an amazon s3 bucket?

Given that you are in AWS...I would think you would want to use their CloudSearch tools. Put the data you want to search in their service...have it point to the S3 keys.

http://aws.amazon.com/cloudsearch/

R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph

You can use geom_col() directly. See the differences between geom_bar() and geom_col() in this link https://ggplot2.tidyverse.org/reference/geom_bar.html

geom_bar() makes the height of the bar proportional to the number of cases in each group If you want the heights of the bars to represent values in the data, use geom_col() instead.

ggplot(data_country)+aes(x=country,y = conversion_rate)+geom_col()

Read Post Data submitted to ASP.Net Form

NameValueCollection nvclc = Request.Form;
string   uName= nvclc ["txtUserName"];
string   pswod= nvclc ["txtPassword"];
//try login
CheckLogin(uName, pswod);

Add/delete row from a table

Here's the code JS Bin using jQuery. Tested on all the browsers. Here, we have to click the rows in order to delete it with beautiful effect. Hope it helps.

Dockerfile copy keep subdirectory structure

To merge a local directory into a directory within an image, do this. It will not delete files already present within the image. It will only add files that are present locally, overwriting the files in the image if a file of the same name already exists.

COPY ./files/. /files/

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

I think the answer depends on which features of stored procedures you need to use.

Stored procedures returning a result set can be run using Query; stored procedures which don't return a result set can be run using Execute - in both cases (using EXEC <procname>) as the SQL command (plus input parameters as necessary). See the documentation for more details.

As of revision 2d128ccdc9a2 there doesn't appear to be native support for OUTPUT parameters; you could add this, or alternatively construct a more complex Query command which declared TSQL variables, executed the SP collecting OUTPUT parameters into the local variables and finallyreturned them in a result set:

DECLARE @output int

EXEC <some stored proc> @i = @output OUTPUT

SELECT @output AS output1

Iterator Loop vs index loop

The special thing about iterators is that they provide the glue between algorithms and containers. For generic code, the recommendation would be to use a combination of STL algorithms (e.g. find, sort, remove, copy) etc. that carries out the computation that you have in mind on your data structure (vector, list, map etc.), and to supply that algorithm with iterators into your container.

Your particular example could be written as a combination of the for_each algorithm and the vector container (see option 3) below), but it's only one out of four distinct ways to iterate over a std::vector:

1) index-based iteration

for (std::size_t i = 0; i != v.size(); ++i) {
    // access element as v[i]

    // any code including continue, break, return
}

Advantages: familiar to anyone familiar with C-style code, can loop using different strides (e.g. i += 2).

Disadvantages: only for sequential random access containers (vector, array, deque), doesn't work for list, forward_list or the associative containers. Also the loop control is a little verbose (init, check, increment). People need to be aware of the 0-based indexing in C++.

2) iterator-based iteration

for (auto it = v.begin(); it != v.end(); ++it) {
    // if the current index is needed:
    auto i = std::distance(v.begin(), it); 

    // access element as *it

    // any code including continue, break, return
}

Advantages: more generic, works for all containers (even the new unordered associative containers, can also use different strides (e.g. std::advance(it, 2));

Disadvantages: need extra work to get the index of the current element (could be O(N) for list or forward_list). Again, the loop control is a little verbose (init, check, increment).

3) STL for_each algorithm + lambda

std::for_each(v.begin(), v.end(), [](T const& elem) {
     // if the current index is needed:
     auto i = &elem - &v[0];

     // cannot continue, break or return out of the loop
});

Advantages: same as 2) plus small reduction in loop control (no check and increment), this can greatly reduce your bug rate (wrong init, check or increment, off-by-one errors).

Disadvantages: same as explicit iterator-loop plus restricted possibilities for flow control in the loop (cannot use continue, break or return) and no option for different strides (unless you use an iterator adapter that overloads operator++).

4) range-for loop

for (auto& elem: v) {
     // if the current index is needed:
     auto i = &elem - &v[0];

    // any code including continue, break, return
}

Advantages: very compact loop control, direct access to the current element.

Disadvantages: extra statement to get the index. Cannot use different strides.

What to use?

For your particular example of iterating over std::vector: if you really need the index (e.g. access the previous or next element, printing/logging the index inside the loop etc.) or you need a stride different than 1, then I would go for the explicitly indexed-loop, otherwise I'd go for the range-for loop.

For generic algorithms on generic containers I'd go for the explicit iterator loop unless the code contained no flow control inside the loop and needed stride 1, in which case I'd go for the STL for_each + a lambda.

How can I get the SQL of a PreparedStatement?

I'm using Oralce 11g and couldn't manage to get the final SQL from the PreparedStatement. After reading @Pascal MARTIN answer I understand why.

I just abandonned the idea of using PreparedStatement and used a simple text formatter which fitted my needs. Here's my example:

//I jump to the point after connexion has been made ...
java.sql.Statement stmt = cnx.createStatement();
String sqlTemplate = "SELECT * FROM Users WHERE Id IN ({0})";
String sqlInParam = "21,34,3434,32"; //some random ids
String sqlFinalSql = java.text.MesssageFormat(sqlTemplate,sqlInParam);
System.out.println("SQL : " + sqlFinalSql);
rsRes = stmt.executeQuery(sqlFinalSql);

You figure out the sqlInParam can be built dynamically in a (for,while) loop I just made it plain simple to get to the point of using the MessageFormat class to serve as a string template formater for the SQL query.

Make a float only show two decimal places

You can also try using NSNumberFormatter:

NSNumberFormatter* nf = [[[NSNumberFormatter alloc] init] autorelease];
nf.positiveFormat = @"0.##";
NSString* s = [nf stringFromNumber: [NSNumber numberWithFloat: myFloat]];

You may need to also set the negative format, but I think it's smart enough to figure it out.

How to set the image from drawable dynamically in android?

First of let's your image name is myimage. So what you have to do is that go to Drawable and save the image name myimage.

Now assume you know only image name and you need to access it. Use below snippet to access it,

what you did is correct , ensure you saved image name you are going to use inside coding.

public static int getResourceId(Context context, String name, String resourceType) {
    return context.getResources().getIdentifier(toResourceString(name), resourceType, context.getPackageName());
}

private static String toResourceString(String name) {
    return name.replace("(", "")
               .replace(")", "")
               .replace(" ", "_")
               .replace("-", "_")
               .replace("'", "")
               .replace("&", "")
               .toLowerCase();
}

In addition to it you should ensure that there is no empty spaces and case sensitives

Copying Code from Inspect Element in Google Chrome

you dont have to do that in the Google chrome. Use the Internet explorer it offers the option to copy the css associated and after you copy and paste select the style and put that into another file .css to call into that html which you have created. Hope this will solve you problem than anything else:)

Moment.js - How to convert date string into date?

Sweet and Simple!
moment('2020-12-04T09:52:03.915Z').format('lll');

Dec 4, 2020 4:58 PM

OtherFormats

moment.locale();         // en
moment().format('LT');   // 4:59 PM
moment().format('LTS');  // 4:59:47 PM
moment().format('L');    // 12/08/2020
moment().format('l');    // 12/8/2020
moment().format('LL');   // December 8, 2020
moment().format('ll');   // Dec 8, 2020
moment().format('LLL');  // December 8, 2020 4:59 PM
moment().format('lll');  // Dec 8, 2020 4:59 PM
moment().format('LLLL'); // Tuesday, December 8, 2020 4:59 PM
moment().format('llll'); // Tue, Dec 8, 2020 4:59 PM

Where do I mark a lambda expression async?

And for those of you using an anonymous expression:

await Task.Run(async () =>
{
   SQLLiteUtils slu = new SQLiteUtils();
   await slu.DeleteGroupAsync(groupname);
});

Plot 3D data in R

I think the following code is close to what you want

x    <- c(0.1, 0.2, 0.3, 0.4, 0.5)
y    <- c(1, 2, 3, 4, 5)
zfun <- function(a,b) {a*b * ( 0.9 + 0.2*runif(a*b) )}
z    <- outer(x, y, FUN="zfun")

It gives data like this (note that x and y are both increasing)

> x
[1] 0.1 0.2 0.3 0.4 0.5
> y
[1] 1 2 3 4 5
> z
          [,1]      [,2]      [,3]      [,4]      [,5]
[1,] 0.1037159 0.2123455 0.3244514 0.4106079 0.4777380
[2,] 0.2144338 0.4109414 0.5586709 0.7623481 0.9683732
[3,] 0.3138063 0.6015035 0.8308649 1.2713930 1.5498939
[4,] 0.4023375 0.8500672 1.3052275 1.4541517 1.9398106
[5,] 0.5146506 1.0295172 1.5257186 2.1753611 2.5046223

and a graph like

persp(x, y, z)

persp(x, y, z)

How to change visibility of layout programmatically

You can change layout visibility just in the same way as for regular view. Use setVisibility(View.GONE) etc. All layouts are just Views, they have View as their parent.

Breaking out of a nested loop

I think unless you want to do the "boolean thing" the only solution is actually to throw. Which you obviously shouldn't do..!

"Javac" doesn't work correctly on Windows 10

To be sure about your path, you can use double quotes " to locate the path or if you are in Windows, you can browse to path to select "C:\Program Files\Java\jdk1.8.0_121\bin" folder.

Change the color of cells in one column when they don't match cells in another column

you could try this:

I have these two columns (column "A" and column "B"). I want to color them when the values between cells in the same row mismatch.

Follow these steps:

  1. Select the elements in column "A" (excluding A1);

  2. Click on "Conditional formatting -> New Rule -> Use a formula to determine which cells to format";

  3. Insert the following formula: =IF(A2<>B2;1;0);

  4. Select the format options and click "OK";

  5. Select the elements in column "B" (excluding B1) and repeat the steps from 2 to 4.

Android ADB device offline, can't issue commands

I had the same problem, while trying to install CyanogenMod on Galaxy S III from Ubuntu. In the end, I simply copied the ZIP file to the external SD card, by attaching the SD card directly to the PC. Then I moved the card back to the phone, and when I rebooted the phone, I could install CyanogenMod from the SD card.

How to compare LocalDate instances Java 8

I believe this snippet will also be helpful in a situation where the dates comparison spans more than two entries.

static final int COMPARE_EARLIEST = 0;

static final int COMPARE_MOST_RECENT = 1;


public LocalDate getTargetDate(List<LocalDate> datesList, int comparatorType) { 
   LocalDate refDate = null;
   switch(comparatorType)
   {
       case COMPARE_EARLIEST:         
       //returns the most earliest of the date entries
          refDate = (LocalDate) datesList.stream().min(Comparator.comparing(item -> 
                      item.toDateTimeAtCurrentTime())).get();
          break;

       case COMPARE_MOST_RECENT:
          //returns the most recent of the date entries 
          refDate = (LocalDate) datesList.stream().max(Comparator.comparing(item -> 
                    item.toDateTimeAtCurrentTime())).get();
          break;
   }

   return refDate;
}

How can I set the PATH variable for javac so I can manually compile my .java works?

First thing I wann ans to this imp question: "Why we require PATH To be set?"

Answer : You need to set PATH to compile Java source code, create JAVA CLASS FILES and allow Operating System to load classes at runtime.

Now you will understand why after setting "javac" you can manually compile by just saying "Class_name.java"

Modify the PATH of Windows Environmental Variable by appending the location till bin directory where all exe file(for eg. java,javac) are present.

Example : ;C:\Program Files\Java\jre7\bin.

Compiling an application for use in highly radioactive environments

Given supercat's comments, the tendencies of modern compilers, and other things, I'd be tempted to go back to the ancient days and write the whole code in assembly and static memory allocations everywhere. For this kind of utter reliability I think assembly no longer incurs a large percentage difference of the cost.

Could someone explain this for me - for (int i = 0; i < 8; i++)

The generic view of a loop is

for (initialization; condition; increment-decrement){}

The first part initializes the code. The second part is the condition that will continue to run the loop as long as it is true. The last part is what will be run after each iteration of the loop. The last part is typically used to increment or decrement a counter, but it doesn't have to.

How to add SHA-1 to android application

Alternatively you can use command line to get your SHA-1 fingerprint:

for your debug certificate you should use:

keytool -list -v -keystore C:\Users\user\.android\debug.keystore -alias androiddebugkey -storepass android -keypass android

you should change "c:\Users\user" with the path to your windows user directory

if you want to get the production SHA-1 for your own certificate, replace "C:\Users\user\.android\debug.keystore" with your custom KeyStore path and use your KeystorePass and Keypass instead of android/android.

Than declare the SHA-1 fingerprints you get to your firebase console as Damini said

How to add noise (Gaussian/salt and pepper etc) to image in Python with OpenCV

just look at cv2.randu() or cv.randn(), it's all pretty similar to matlab already, i guess.

let's play a bit ;) :

import cv2
import numpy as np

>>> im = np.empty((5,5), np.uint8) # needs preallocated input image
>>> im
array([[248, 168,  58,   2,   1],  # uninitialized memory counts as random, too ?  fun ;) 
       [  0, 100,   2,   0, 101],
       [  0,   0, 106,   2,   0],
       [131,   2,   0,  90,   3],
       [  0, 100,   1,   0,  83]], dtype=uint8)
>>> im = np.zeros((5,5), np.uint8) # seriously now.
>>> im
array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]], dtype=uint8)
>>> cv2.randn(im,(0),(99))         # normal
array([[  0,  76,   0, 129,   0],
       [  0,   0,   0, 188,  27],
       [  0, 152,   0,   0,   0],
       [  0,   0, 134,  79,   0],
       [  0, 181,  36, 128,   0]], dtype=uint8)
>>> cv2.randu(im,(0),(99))         # uniform
array([[19, 53,  2, 86, 82],
       [86, 73, 40, 64, 78],
       [34, 20, 62, 80,  7],
       [24, 92, 37, 60, 72],
       [40, 12, 27, 33, 18]], dtype=uint8)

to apply it to an existing image, just generate noise in the desired range, and add it:

img = ...
noise = ...

image = img + noise

What does 'killed' mean when a processing of a huge CSV with Python, which suddenly stops?

Most likely, you ran out of memory, so the Kernel killed your process.

Have you heard about OOM Killer?

Here's a log from a script that I developed for processing a huge set of data from CSV files:

Mar 12 18:20:38 server.com kernel: [63802.396693] Out of memory: Kill process 12216 (python3) score 915 or sacrifice child
Mar 12 18:20:38 server.com kernel: [63802.402542] Killed process 12216 (python3) total-vm:9695784kB, anon-rss:7623168kB, file-rss:4kB, shmem-rss:0kB
Mar 12 18:20:38 server.com kernel: [63803.002121] oom_reaper: reaped process 12216 (python3), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB

It was taken from /var/log/syslog.

Basically:

PID 12216 elected as a victim (due to its use of +9Gb of total-vm), so oom_killer reaped it.

Here's a article about OOM behavior.

Convert an array into an ArrayList

List<Card> list = new ArrayList<Card>(Arrays.asList(hand));

Handle spring security authentication exceptions with @ExceptionHandler

Ok, I tried as suggested writing the json myself from the AuthenticationEntryPoint and it works.

Just for testing I changed the AutenticationEntryPoint by removing response.sendError

@Component("restAuthenticationEntryPoint")
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint{

    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException, ServletException {
    
        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getOutputStream().println("{ \"error\": \"" + authenticationException.getMessage() + "\" }");

    }
}

In this way you can send custom json data along with the 401 unauthorized even if you are using Spring Security AuthenticationEntryPoint.

Obviously you would not build the json as I did for testing purposes but you would serialize some class instance.

In Spring Boot, you should add it to http.authenticationEntryPoint() part of SecurityConfiguration file.

Adding a library/JAR to an Eclipse Android project

If you are using the ADT version 22, you need to check the android dependencies and android private libraries in the order&Export tab in the project build path

Get an OutputStream into a String

Here's what I ended up doing:

Obj.writeToStream(toWrite, os);
try {
    String out = new String(os.toByteArray(), "UTF-8");
    assertTrue(out.contains("testString"));
} catch (UnsupportedEncondingException e) {
    fail("Caught exception: " + e.getMessage());
}

Where os is a ByteArrayOutputStream.

What is the difference between `let` and `var` in swift?

The

Declaring Constants and Variables section of The Swift Programming Language documentation specifies the following:

You declare constants with the let keyword and variables with the var keyword.

Make sure to understand how this works for Reference types. Unlike Value Types, the object's underlying properties can change despite an instance of a reference type being declared as a constant. See the Classes are Reference Types section of the documentation, and look at the example where they change the frameRate property.

How to reset the use/password of jenkins on windows?

I created a new user with "admin" and new password on the installation steps. But after sometime, i wanted to sign in again and that password was showing incorrect, so i used the initial password again to login.

The initial password can be found in the below location:-

C:\Program Files(x86)\Jenkins\secrets\initialAdminPassword

try this method

Unable to send email using Gmail SMTP server through PHPMailer, getting error: SMTP AUTH is required for message submission on port 587. How to fix?

Open this Link and select follow the instructions google servers blocks any attempts from unknown servers so once you click on captcha check every thing will be fine

Getting ORA-01031: insufficient privileges while querying a table instead of ORA-00942: table or view does not exist

for ORA-01031: insufficient privileges. Some of the more common causes are:

  1. You tried to change an Oracle username or password without having the appropriate privileges.
  2. You tried to perform an UPDATE to a table, but you only have SELECT access to the table.
  3. You tried to start up an Oracle database using CONNECT INTERNAL.
  4. You tried to install an Oracle database without having the appropriate privileges to the operating-system.

The option(s) to resolve this Oracle error are:

  1. You can have the Oracle DBA grant you the appropriate privileges that you are missing.
  2. You can have the Oracle DBA execute the operation for you.
  3. If you are having trouble starting up Oracle, you may need to add the Oracle user to the dba group.

For ORA-00942: table or view does not exist. You tried to execute a SQL statement that references a table or view that either does not exist, that you do not have access to, or that belongs to another schema and you didn't reference the table by the schema name.

If this error occurred because the table or view does not exist, you will need to create the table or view.

You can check to see if the table exists in Oracle by executing the following SQL statement:

select *
from all_objects
where object_type in ('TABLE','VIEW')
and object_name = 'OBJECT_NAME';

For example, if you are looking for a suppliers table, you would execute:

select *
from all_objects
where object_type in ('TABLE','VIEW')
and object_name = 'SUPPLIERS';

OPTION #2

If this error occurred because you do not have access to the table or view, you will need to have the owner of the table/view, or a DBA grant you the appropriate privileges to this object.

OPTION #3

If this error occurred because the table/view belongs to another schema and you didn't reference the table by the schema name, you will need to rewrite your SQL to include the schema name.

For example, you may have executed the following SQL statement:

select *
from suppliers;

But the suppliers table is not owned by you, but rather, it is owned by a schema called app, you could fix your SQL as follows:

select *
from app.suppliers;

If you do not know what schema the suppliers table/view belongs to, you can execute the following SQL to find out:

select owner
from all_objects
where object_type in ('TABLE','VIEW')
and object_name = 'SUPPLIERS';

This will return the schema name who owns the suppliers table.

How to line-break from css, without using <br />?

Building on what has been said before, this is a pure CSS solution that works.

<style>
  span {
    display: inline;
  }
  span:before {
    content: "\a ";
    white-space: pre;
  }
</style>
<p>
  First line of text. <span>Next line.</span>
</p>

Converting string to integer

The function you need is CInt.

ie CInt(PrinterLabel)

See Type Conversion Functions (Visual Basic) on MSDN

Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!

How to link an input button to a file select window?

If you want to allow the user to browse for a file, you need to have an input type="file" The closest you could get to your requirement would be to place the input type="file" on the page and hide it. Then, trigger the click event of the input when the button is clicked:

#myFileInput {
    display:none;
}

<input type="file" id="myFileInput" />
<input type="button"
       onclick="document.getElementById('myFileInput').click()" 
       value="Select a File" />

Here's a working fiddle.

Note: I would not recommend this approach. The input type="file" is the mechanism that users are accustomed to using for uploading a file.

Best Way to do Columns in HTML/CSS

Bootstrap. Check out their awesome grid system here.

Using Bootstrap, you could make three columns like this:

<div class="container">
  <div class="row">
    <div class="col-md-4">.col-md-4</div>
    <div class="col-md-4">.col-md-4</div>
    <div class="col-md-4">.col-md-4</div>
  </div>
</div>

How to sort a file in-place

sort file | sponge file

This is in the following Fedora package:

moreutils : Additional unix utilities
Repo        : fedora
Matched from:
Filename    : /usr/bin/sponge

How to "properly" create a custom object in JavaScript?

There are two models for implementing classes and instances in JavaScript: the prototyping way, and the closure way. Both have advantages and drawbacks, and there are plenty of extended variations. Many programmers and libraries have different approaches and class-handling utility functions to paper over some of the uglier parts of the language.

The result is that in mixed company you will have a mishmash of metaclasses, all behaving slightly differently. What's worse, most JavaScript tutorial material is terrible and serves up some kind of in-between compromise to cover all bases, leaving you very confused. (Probably the author is also confused. JavaScript's object model is very different to most programming languages, and in many places straight-up badly designed.)

Let's start with the prototype way. This is the most JavaScript-native you can get: there is a minimum of overhead code and instanceof will work with instances of this kind of object.

function Shape(x, y) {
    this.x= x;
    this.y= y;
}

We can add methods to the instance created by new Shape by writing them to the prototype lookup of this constructor function:

Shape.prototype.toString= function() {
    return 'Shape at '+this.x+', '+this.y;
};

Now to subclass it, in as much as you can call what JavaScript does subclassing. We do that by completely replacing that weird magic prototype property:

function Circle(x, y, r) {
    Shape.call(this, x, y); // invoke the base class's constructor function to take co-ords
    this.r= r;
}
Circle.prototype= new Shape();

before adding methods to it:

Circle.prototype.toString= function() {
    return 'Circular '+Shape.prototype.toString.call(this)+' with radius '+this.r;
}

This example will work and you will see code like it in many tutorials. But man, that new Shape() is ugly: we're instantiating the base class even though no actual Shape is to be created. It happens to work in this simple case because JavaScript is so sloppy: it allows zero arguments to be passed in, in which case x and y become undefined and are assigned to the prototype's this.x and this.y. If the constructor function were doing anything more complicated, it would fall flat on its face.

So what we need to do is find a way to create a prototype object which contains the methods and other members we want at a class level, without calling the base class's constructor function. To do this we are going to have to start writing helper code. This is the simplest approach I know of:

function subclassOf(base) {
    _subclassOf.prototype= base.prototype;
    return new _subclassOf();
}
function _subclassOf() {};

This transfers the base class's members in its prototype to a new constructor function which does nothing, then uses that constructor. Now we can write simply:

function Circle(x, y, r) {
    Shape.call(this, x, y);
    this.r= r;
}
Circle.prototype= subclassOf(Shape);

instead of the new Shape() wrongness. We now have an acceptable set of primitives to built classes.

There are a few refinements and extensions we can consider under this model. For example here is a syntactical-sugar version:

Function.prototype.subclass= function(base) {
    var c= Function.prototype.subclass.nonconstructor;
    c.prototype= base.prototype;
    this.prototype= new c();
};
Function.prototype.subclass.nonconstructor= function() {};

...

function Circle(x, y, r) {
    Shape.call(this, x, y);
    this.r= r;
}
Circle.subclass(Shape);

Either version has the drawback that the constructor function cannot be inherited, as it is in many languages. So even if your subclass adds nothing to the construction process, it must remember to call the base constructor with whatever arguments the base wanted. This can be slightly automated using apply, but still you have to write out:

function Point() {
    Shape.apply(this, arguments);
}
Point.subclass(Shape);

So a common extension is to break out the initialisation stuff into its own function rather than the constructor itself. This function can then inherit from the base just fine:

function Shape() { this._init.apply(this, arguments); }
Shape.prototype._init= function(x, y) {
    this.x= x;
    this.y= y;
};

function Point() { this._init.apply(this, arguments); }
Point.subclass(Shape);
// no need to write new initialiser for Point!

Now we've just got the same constructor function boilerplate for each class. Maybe we can move that out into its own helper function so we don't have to keep typing it, for example instead of Function.prototype.subclass, turning it round and letting the base class's Function spit out subclasses:

Function.prototype.makeSubclass= function() {
    function Class() {
        if ('_init' in this)
            this._init.apply(this, arguments);
    }
    Function.prototype.makeSubclass.nonconstructor.prototype= this.prototype;
    Class.prototype= new Function.prototype.makeSubclass.nonconstructor();
    return Class;
};
Function.prototype.makeSubclass.nonconstructor= function() {};

...

Shape= Object.makeSubclass();
Shape.prototype._init= function(x, y) {
    this.x= x;
    this.y= y;
};

Point= Shape.makeSubclass();

Circle= Shape.makeSubclass();
Circle.prototype._init= function(x, y, r) {
    Shape.prototype._init.call(this, x, y);
    this.r= r;
};

...which is starting to look a bit more like other languages, albeit with slightly clumsier syntax. You can sprinkle in a few extra features if you like. Maybe you want makeSubclass to take and remember a class name and provide a default toString using it. Maybe you want to make the constructor detect when it has accidentally been called without the new operator (which would otherwise often result in very annoying debugging):

Function.prototype.makeSubclass= function() {
    function Class() {
        if (!(this instanceof Class))
            throw('Constructor called without "new"');
        ...

Maybe you want to pass in all the new members and have makeSubclass add them to the prototype, to save you having to write Class.prototype... quite so much. A lot of class systems do that, eg:

Circle= Shape.makeSubclass({
    _init: function(x, y, z) {
        Shape.prototype._init.call(this, x, y);
        this.r= r;
    },
    ...
});

There are a lot of potential features you might consider desirable in an object system and no-one really agrees on one particular formula.


The closure way, then. This avoids the problems of JavaScript's prototype-based inheritance, by not using inheritance at all. Instead:

function Shape(x, y) {
    var that= this;

    this.x= x;
    this.y= y;

    this.toString= function() {
        return 'Shape at '+that.x+', '+that.y;
    };
}

function Circle(x, y, r) {
    var that= this;

    Shape.call(this, x, y);
    this.r= r;

    var _baseToString= this.toString;
    this.toString= function() {
        return 'Circular '+_baseToString(that)+' with radius '+that.r;
    };
};

var mycircle= new Circle();

Now every single instance of Shape will have its own copy of the toString method (and any other methods or other class members we add).

The bad thing about every instance having its own copy of each class member is that it's less efficient. If you are dealing with large numbers of subclassed instances, prototypical inheritance may serve you better. Also calling a method of the base class is slightly annoying as you can see: we have to remember what the method was before the subclass constructor overwrote it, or it gets lost.

[Also because there is no inheritance here, the instanceof operator won't work; you would have to provide your own mechanism for class-sniffing if you need it. Whilst you could fiddle the prototype objects in a similar way as with prototype inheritance, it's a bit tricky and not really worth it just to get instanceof working.]

The good thing about every instance having its own method is that the method may then be bound to the specific instance that owns it. This is useful because of JavaScript's weird way of binding this in method calls, which has the upshot that if you detach a method from its owner:

var ts= mycircle.toString;
alert(ts());

then this inside the method won't be the Circle instance as expected (it'll actually be the global window object, causing widespread debugging woe). In reality this typically happens when a method is taken and assigned to a setTimeout, onclick or EventListener in general.

With the prototype way, you have to include a closure for every such assignment:

setTimeout(function() {
    mycircle.move(1, 1);
}, 1000);

or, in the future (or now if you hack Function.prototype) you can also do it with function.bind():

setTimeout(mycircle.move.bind(mycircle, 1, 1), 1000);

if your instances are done the closure way, the binding is done for free by the closure over the instance variable (usually called that or self, though personally I would advise against the latter as self already has another, different meaning in JavaScript). You don't get the arguments 1, 1 in the above snippet for free though, so you would still need another closure or a bind() if you need to do that.

There are lots of variants on the closure method too. You may prefer to omit this completely, creating a new that and returning it instead of using the new operator:

function Shape(x, y) {
    var that= {};

    that.x= x;
    that.y= y;

    that.toString= function() {
        return 'Shape at '+that.x+', '+that.y;
    };

    return that;
}

function Circle(x, y, r) {
    var that= Shape(x, y);

    that.r= r;

    var _baseToString= that.toString;
    that.toString= function() {
        return 'Circular '+_baseToString(that)+' with radius '+r;
    };

    return that;
};

var mycircle= Circle(); // you can include `new` if you want but it won't do anything

Which way is “proper”? Both. Which is “best”? That depends on your situation. FWIW I tend towards prototyping for real JavaScript inheritance when I'm doing strongly OO stuff, and closures for simple throwaway page effects.

But both ways are quite counter-intuitive to most programmers. Both have many potential messy variations. You will meet both (as well as many in-between and generally broken schemes) if you use other people's code/libraries. There is no one generally-accepted answer. Welcome to the wonderful world of JavaScript objects.

[This has been part 94 of Why JavaScript Is Not My Favourite Programming Language.]

How do I do a Date comparison in Javascript?

You could try adding the following script code to implement this:

if(CompareDates(smallDate,largeDate,'-') == 0) {
    alert('Selected date must be current date or previous date!');
return false;
}

function CompareDates(smallDate,largeDate,separator) {
    var smallDateArr = Array();
    var largeDateArr = Array(); 
    smallDateArr = smallDate.split(separator);
    largeDateArr = largeDate.split(separator);  
    var smallDt = smallDateArr[0];
    var smallMt = smallDateArr[1];
    var smallYr = smallDateArr[2];  
    var largeDt = largeDateArr[0];
    var largeMt = largeDateArr[1];
    var largeYr = largeDateArr[2];

    if(smallYr>largeYr) 
        return 0;
else if(smallYr<=largeYr && smallMt>largeMt)
    return 0;
else if(smallYr<=largeYr && smallMt==largeMt && smallDt>largeDt)
    return 0;
else 
    return 1;
}  

How to use querySelectorAll only for elements that have a specific attribute set?

With your example:

<input type="checkbox" id="c2" name="c2" value="DE039230952"/>

Replace $$ with document.querySelectorAll in the examples:

$$('input') //Every input
$$('[id]') //Every element with id
$$('[id="c2"]') //Every element with id="c2"
$$('input,[id]') //Every input + every element with id
$$('input[id]') //Every input including id
$$('input[id="c2"]') //Every input including id="c2"
$$('input#c2') //Every input including id="c2" (same as above)
$$('input#c2[value="DE039230952"]') //Every input including id="c2" and value="DE039230952"
$$('input#c2[value^="DE039"]') //Every input including id="c2" and value has content starting with DE039
$$('input#c2[value$="0952"]') //Every input including id="c2" and value has content ending with 0952
$$('input#c2[value*="39230"]') //Every input including id="c2" and value has content including 39230

Use the examples directly with:

const $$ = document.querySelectorAll.bind(document);

Some additions:

$$(.) //The same as $([class])
$$(div > input) //div is parent tag to input
document.querySelector() //equals to $$()[0] or $()

$(document).on("click"... not working?

Your code should work, but I'm aware that answer doesn't help you. You can see a working example here (jsfiddle).

Jquery:

$(document).on('click','#test-element',function(){
    alert("You clicked the element with and ID of 'test-element'");
});

As someone already pointed out, you are using an ID instead of a class. If you have more that one element on the page with an ID, then jquery will return only the first element with that ID. There won't be any errors because that's how it works. If this is the problem, then you'll notice that the click event works for the first test-element but not for any that follow.

If this does not accurately describe the symptoms of the problem, then perhaps your selector is wrong. Your update leads me to believe this is the case because of inspecting an element then clicking the page again and triggering the click. What could be causing this is if you put the event listener on the actual document instead of test-element. If so, when you click off the document and back on (like from the developer window back to the document) the event will trigger. If this is the case, you'll also notice the click event is triggered if you click between two different tabs (because they are two different documents and therefore you are clicking the document.

If neither of these are the answer, posting HTML will go a long way toward figuring it out.

How do you modify the web.config appSettings at runtime?

I know this question is old, but I wanted to post an answer based on the current state of affairs in the ASP.NET\IIS world combined with my real world experience.

I recently spearheaded a project at my company where I wanted to consolidate and manage all of the appSettings & connectionStrings settings in our web.config files in one central place. I wanted to pursue an approach where our config settings were stored in ZooKeeper due to that projects maturity & stability. Not to mention that fact that ZooKeeper is by design a configuration & cluster managing application.

The project goals were very simple;

  1. get ASP.NET to communicate with ZooKeeper
  2. in Global.asax, Application_Start - pull web.config settings from ZooKeeper.

Upon getting passed the technical piece of getting ASP.NET to talk to ZooKeeper, I quickly found and hit a wall with the following code;

ConfigurationManager.AppSettings.Add(key_name, data_value)

That statement made the most logical sense since I wanted to ADD new settings to the appSettings collection. However, as the original poster (and many others) mentioned, this code call returns an Error stating that the collection is Read-Only.

After doing a bit of research and seeing all the different crazy ways people worked around this problem, I was very discouraged. Instead of giving up or settling for what appeared to be a less than ideal scenario, I decided to dig in and see if I was missing something.

With a little trial and error, I found the following code would do exactly what I wanted;

ConfigurationManager.AppSettings.Set(key_name, data_value)

Using this line of code, I am now able to load all 85 appSettings keys from ZooKeeper in my Application_Start.

In regards to general statements about changes to web.config triggering IIS recycles, I edited the following appPool settings to monitor the situation behind the scenes;

appPool-->Advanced Settings-->Recycling-->Disable Recycling for Configuration Changes = False
appPool-->Advanced Settings-->Recycling-->Generate Recycle Event Log Entry-->[For Each Setting] = True

With that combination of settings, if this process were to cause an appPool recycle, an Event Log entry should have be recorded, which it was not.

This leads me to conclude that it is possible, and indeed safe, to load an applications settings from a centralized storage medium.

I should mention that I am using IIS7.5 on Windows 7. The code will be getting deployed to IIS8 on Win2012. Should anything regarding this answer change, I will update this answer accordingly.

Is there a simple way to remove multiple spaces in a string?

Using regexes with "\s" and doing simple string.split()'s will also remove other whitespace - like newlines, carriage returns, tabs. Unless this is desired, to only do multiple spaces, I present these examples.

I used 11 paragraphs, 1000 words, 6665 bytes of Lorem Ipsum to get realistic time tests and used random-length extra spaces throughout:

original_string = ''.join(word + (' ' * random.randint(1, 10)) for word in lorem_ipsum.split(' '))

The one-liner will essentially do a strip of any leading/trailing spaces, and it preserves a leading/trailing space (but only ONE ;-).

# setup = '''

import re

def while_replace(string):
    while '  ' in string:
        string = string.replace('  ', ' ')

    return string

def re_replace(string):
    return re.sub(r' {2,}' , ' ', string)

def proper_join(string):
    split_string = string.split(' ')

    # To account for leading/trailing spaces that would simply be removed
    beg = ' ' if not split_string[ 0] else ''
    end = ' ' if not split_string[-1] else ''

    # versus simply ' '.join(item for item in string.split(' ') if item)
    return beg + ' '.join(item for item in split_string if item) + end

original_string = """Lorem    ipsum        ... no, really, it kept going...          malesuada enim feugiat.         Integer imperdiet    erat."""

assert while_replace(original_string) == re_replace(original_string) == proper_join(original_string)

#'''

# while_replace_test
new_string = original_string[:]

new_string = while_replace(new_string)

assert new_string != original_string

# re_replace_test
new_string = original_string[:]

new_string = re_replace(new_string)

assert new_string != original_string

# proper_join_test
new_string = original_string[:]

new_string = proper_join(new_string)

assert new_string != original_string

NOTE: The "while version" made a copy of the original_string, as I believe once modified on the first run, successive runs would be faster (if only by a bit). As this adds time, I added this string copy to the other two so that the times showed the difference only in the logic. Keep in mind that the main stmt on timeit instances will only be executed once; the original way I did this, the while loop worked on the same label, original_string, thus the second run, there would be nothing to do. The way it's set up now, calling a function, using two different labels, that isn't a problem. I've added assert statements to all the workers to verify we change something every iteration (for those who may be dubious). E.g., change to this and it breaks:

# while_replace_test
new_string = original_string[:]

new_string = while_replace(new_string)

assert new_string != original_string # will break the 2nd iteration

while '  ' in original_string:
    original_string = original_string.replace('  ', ' ')

Tests run on a laptop with an i5 processor running Windows 7 (64-bit).

timeit.Timer(stmt = test, setup = setup).repeat(7, 1000)

test_string = 'The   fox jumped   over\n\t    the log.' # trivial

Python 2.7.3, 32-bit, Windows
                test |      minum |    maximum |    average |     median
---------------------+------------+------------+------------+-----------
  while_replace_test |   0.001066 |   0.001260 |   0.001128 |   0.001092
     re_replace_test |   0.003074 |   0.003941 |   0.003357 |   0.003349
    proper_join_test |   0.002783 |   0.004829 |   0.003554 |   0.003035

Python 2.7.3, 64-bit, Windows
                test |      minum |    maximum |    average |     median
---------------------+------------+------------+------------+-----------
  while_replace_test |   0.001025 |   0.001079 |   0.001052 |   0.001051
     re_replace_test |   0.003213 |   0.004512 |   0.003656 |   0.003504
    proper_join_test |   0.002760 |   0.006361 |   0.004626 |   0.004600

Python 3.2.3, 32-bit, Windows
                test |      minum |    maximum |    average |     median
---------------------+------------+------------+------------+-----------
  while_replace_test |   0.001350 |   0.002302 |   0.001639 |   0.001357
     re_replace_test |   0.006797 |   0.008107 |   0.007319 |   0.007440
    proper_join_test |   0.002863 |   0.003356 |   0.003026 |   0.002975

Python 3.3.3, 64-bit, Windows
                test |      minum |    maximum |    average |     median
---------------------+------------+------------+------------+-----------
  while_replace_test |   0.001444 |   0.001490 |   0.001460 |   0.001459
     re_replace_test |   0.011771 |   0.012598 |   0.012082 |   0.011910
    proper_join_test |   0.003741 |   0.005933 |   0.004341 |   0.004009

test_string = lorem_ipsum
# Thanks to http://www.lipsum.com/
# "Generated 11 paragraphs, 1000 words, 6665 bytes of Lorem Ipsum"

Python 2.7.3, 32-bit
                test |      minum |    maximum |    average |     median
---------------------+------------+------------+------------+-----------
  while_replace_test |   0.342602 |   0.387803 |   0.359319 |   0.356284
     re_replace_test |   0.337571 |   0.359821 |   0.348876 |   0.348006
    proper_join_test |   0.381654 |   0.395349 |   0.388304 |   0.388193    

Python 2.7.3, 64-bit
                test |      minum |    maximum |    average |     median
---------------------+------------+------------+------------+-----------
  while_replace_test |   0.227471 |   0.268340 |   0.240884 |   0.236776
     re_replace_test |   0.301516 |   0.325730 |   0.308626 |   0.307852
    proper_join_test |   0.358766 |   0.383736 |   0.370958 |   0.371866    

Python 3.2.3, 32-bit
                test |      minum |    maximum |    average |     median
---------------------+------------+------------+------------+-----------
  while_replace_test |   0.438480 |   0.463380 |   0.447953 |   0.446646
     re_replace_test |   0.463729 |   0.490947 |   0.472496 |   0.468778
    proper_join_test |   0.397022 |   0.427817 |   0.406612 |   0.402053    

Python 3.3.3, 64-bit
                test |      minum |    maximum |    average |     median
---------------------+------------+------------+------------+-----------
  while_replace_test |   0.284495 |   0.294025 |   0.288735 |   0.289153
     re_replace_test |   0.501351 |   0.525673 |   0.511347 |   0.508467
    proper_join_test |   0.422011 |   0.448736 |   0.436196 |   0.440318

For the trivial string, it would seem that a while-loop is the fastest, followed by the Pythonic string-split/join, and regex pulling up the rear.

For non-trivial strings, seems there's a bit more to consider. 32-bit 2.7? It's regex to the rescue! 2.7 64-bit? A while loop is best, by a decent margin. 32-bit 3.2, go with the "proper" join. 64-bit 3.3, go for a while loop. Again.

In the end, one can improve performance if/where/when needed, but it's always best to remember the mantra:

  1. Make It Work
  2. Make It Right
  3. Make It Fast

IANAL, YMMV, Caveat Emptor!

What is a predicate in c#?

In C# Predicates are simply delegates that return booleans. They're useful (in my experience) when you're searching through a collection of objects and want something specific.

I've recently run into them in using 3rd party web controls (like treeviews) so when I need to find a node within a tree, I use the .Find() method and pass a predicate that will return the specific node I'm looking for. In your example, if 'a' mod 2 is 0, the delegate will return true. Granted, when I'm looking for a node in a treeview, I compare it's name, text and value properties for a match. When the delegate finds a match, it returns the specific node I was looking for.

Starting with Zend Tutorial - Zend_DB_Adapter throws Exception: "SQLSTATE[HY000] [2002] No such file or directory"

It looks like mysql service is either not working or stopped. you can start it by using below command (in Ubuntu):

service mysql start

It should work! If you are using any other operating system than Ubuntu then use appropriate way to start mysql

How do I get the full path to a Perl script that is executing?

Getting the absolute path to $0 or __FILE__ is what you want. The only trouble is if someone did a chdir() and the $0 was relative -- then you need to get the absolute path in a BEGIN{} to prevent any surprises.

FindBin tries to go one better and grovel around in the $PATH for something matching the basename($0), but there are times when that does far-too-surprising things (specifically: when the file is "right in front of you" in the cwd.)

File::Fu has File::Fu->program_name and File::Fu->program_dir for this.

What is the best way to get the count/length/size of an iterator?

There is no more efficient way, if all you have is the iterator. And if the iterator can only be used once, then getting the count before you get the iterator's contents is ... problematic.

The solution is either to change your application so that it doesn't need the count, or to obtain the count by some other means. (For example, pass a Collection rather than Iterator ...)

Regex number between 1 and 100

between 0 and 100

/^(\d{1,2}|100)$/

or between 1 and 100

/^([1-9]{1,2}|100)$/

OnClick Send To Ajax

<textarea name='Status'> </textarea>
<input type='button' value='Status Update'>

You have few problems with your code like using . for concatenation

Try this -

$(function () {
    $('input').on('click', function () {
        var Status = $(this).val();
        $.ajax({
            url: 'Ajax/StatusUpdate.php',
            data: {
                text: $("textarea[name=Status]").val(),
                Status: Status
            },
            dataType : 'json'
        });
    });
});

How to automatically reload a page after a given period of inactivity

Auto reload with target of your choice. In this case target is _self set to itself,but you could change the reload page by simply changing the window.open('self.location', '_self'); code to something like this examplewindow.top.location="window.open('http://www.YourPageAdress.com', '_self'";.

With a confirmation ALERT message:

<script language="JavaScript">
function set_interval() {
  //the interval 'timer' is set as soon as the page loads  
  var timeoutMins = 1000 * 1 * 15; // 15 seconds
  var timeout1Mins = 1000 * 1 * 13; // 13 seconds
  itimer=setInterval("auto_logout()",timeoutMins);
  atimer=setInterval("alert_idle()",timeout1Mins);

}

function reset_interval() {
  var timeoutMins = 1000 * 1 * 15; // 15 seconds 
  var timeout1Mins = 1000 * 1 * 13; // 13 seconds
  //resets the timer. The timer is reset on each of the below events:
  // 1. mousemove   2. mouseclick   3. key press 4. scrolling
  //first step: clear the existing timer
  clearInterval(itimer);
  clearInterval(atimer);
  //second step: implement the timer again
  itimer=setInterval("auto_logout()",timeoutMins);
  atimer=setInterval("alert_idle()",timeout1Mins);
}

function alert_idle() {
    var answer = confirm("Session About To Timeout\n\n       You will be automatically logged out.\n       Confirm to remain logged in.")
    if (answer){

        reset_interval();
    }
    else{
        auto_logout();
    }
}

function auto_logout() {
  //this function will redirect the user to the logout script
  window.open('self.location', '_self');
}
</script>

Without confirmation alert:

<script language="JavaScript">
function set_interval() {
  //the interval 'timer' is set as soon as the page loads  
  var timeoutMins = 1000 * 1 * 15; // 15 seconds
  var timeout1Mins = 1000 * 1 * 13; // 13 seconds
  itimer=setInterval("auto_logout()",timeoutMins);

}

function reset_interval() {
  var timeoutMins = 1000 * 1 * 15; // 15 seconds 
  var timeout1Mins = 1000 * 1 * 13; // 13 seconds
  //resets the timer. The timer is reset on each of the below events:
  // 1. mousemove   2. mouseclick   3. key press 4. scrolling
  //first step: clear the existing timer
  clearInterval(itimer);
  clearInterval(atimer);
  //second step: implement the timer again
  itimer=setInterval("auto_logout()",timeoutMins);
}


function auto_logout() {
  //this function will redirect the user to the logout script
  window.open('self.location', '_self');
}
</script>

Body code is the SAME for both solutions:

<body onLoad="set_interval(); document.form1.exp_dat.focus();" onKeyPress="reset_interval();" onmousemove="reset_interval();" onclick="reset_interval();" onscroll="reset_interval();">

Android EditText delete(backspace) key event

I have found a really simple solution which works with a soft keyboard.

override fun onTextChanged(text: CharSequence?, start: Int, before: Int, count: Int) {
    text?.let { 
        if(count < before) {
            Toast.makeText(context, "backspace pressed", Toast.LENGTH_SHORT).show()
            // implement your own code
        }
    }
}

Facebook share link without JavaScript

For those that wish to use javascript but do not want to use the Facebook javascript library:

<a id="shareFB" href="https://www.facebook.com/sharer/sharer.php?u=URLENCODED_URL&t=TITLE"
   onclick="javascript:window.open(this.href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600');return false;"   target="_blank" title="Share on Facebook">Share on Facebook</a>
<script type="text/javascript">document.getElementById("shareFB").setAttribute("href", "https://www.facebook.com/sharer/sharer.php?u=" + document.URL);</script>

Works even if javascript is disabled, but gives you a popup window with share preview if javascript is enabled.

Saves one needles click while not using any Facebook js spyware :)

c# - approach for saving user settings in a WPF application?

The long running most typical approach to this question is: Isolated Storage.

Serialize your control state to XML or some other format (especially easily if you're saving Dependency Properties with WPF), then save the file to the user's isolated storage.

If you do want to go the app setting route, I tried something similar at one point myself...though the below approach could easily be adapted to use Isolated Storage:

class SettingsManager
{
    public static void LoadSettings(FrameworkElement sender, Dictionary<FrameworkElement, DependencyProperty> savedElements)
    {
        EnsureProperties(sender, savedElements);
        foreach (FrameworkElement element in savedElements.Keys)
        {
            try
            {
                element.SetValue(savedElements[element], Properties.Settings.Default[sender.Name + "." + element.Name]);
            }
            catch (Exception ex) { }
        }
    }

    public static void SaveSettings(FrameworkElement sender, Dictionary<FrameworkElement, DependencyProperty> savedElements)
    {
        EnsureProperties(sender, savedElements);
        foreach (FrameworkElement element in savedElements.Keys)
        {
            Properties.Settings.Default[sender.Name + "." + element.Name] = element.GetValue(savedElements[element]);
        }
        Properties.Settings.Default.Save();
    }

    public static void EnsureProperties(FrameworkElement sender, Dictionary<FrameworkElement, DependencyProperty> savedElements)
    {
        foreach (FrameworkElement element in savedElements.Keys)
        {
            bool hasProperty =
                Properties.Settings.Default.Properties[sender.Name + "." + element.Name] != null;

            if (!hasProperty)
            {
                SettingsAttributeDictionary attributes = new SettingsAttributeDictionary();
                UserScopedSettingAttribute attribute = new UserScopedSettingAttribute();
                attributes.Add(attribute.GetType(), attribute);

                SettingsProperty property = new SettingsProperty(sender.Name + "." + element.Name,
                    savedElements[element].DefaultMetadata.DefaultValue.GetType(), Properties.Settings.Default.Providers["LocalFileSettingsProvider"], false, null, SettingsSerializeAs.String, attributes, true, true);
                Properties.Settings.Default.Properties.Add(property);
            }
        }
        Properties.Settings.Default.Reload();
    }
}

.....and....

  Dictionary<FrameworkElement, DependencyProperty> savedElements = new Dictionary<FrameworkElement, DependencyProperty>();

public Window_Load(object sender, EventArgs e) {
           savedElements.Add(firstNameText, TextBox.TextProperty);
                savedElements.Add(lastNameText, TextBox.TextProperty);

            SettingsManager.LoadSettings(this, savedElements);
}

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            SettingsManager.SaveSettings(this, savedElements);
        }

SQL : BETWEEN vs <= and >=

See this excellent blog post from Aaron Bertrand about why you should change your string format and how the boundary values are handled in date range queries.

How to install pip for Python 3.6 on Ubuntu 16.10?

This answer assumes that you have python3.6 installed. For python3.7, replace 3.6 with 3.7. For python3.8, replace 3.6 with 3.8, but it may also first require the python3.8-distutils package.

Installation with sudo

With regard to installing pip, using curl (instead of wget) avoids writing the file to disk.

curl https://bootstrap.pypa.io/get-pip.py | sudo -H python3.6

The -H flag is evidently necessary with sudo in order to prevent errors such as the following when installing pip for an updated python interpreter:

The directory '/home/someuser/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.

The directory '/home/someuser/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.

Installation without sudo

curl https://bootstrap.pypa.io/get-pip.py | python3.6 - --user

This may sometimes give a warning such as:

WARNING: The script wheel is installed in '/home/ubuntu/.local/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.

Verification

After this, pip, pip3, and pip3.6 can all be expected to point to the same target:

$ (pip -V && pip3 -V && pip3.6 -V) | uniq
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)

Of course you can alternatively use python3.6 -m pip as well.

$ python3.6 -m pip -V
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)

Display milliseconds in Excel

Right click on Cell B1 and choose Format Cells. In Custom, put the following in the text box labeled Type:

[h]:mm:ss.000 

To set this in code, you can do something like:

Range("A1").NumberFormat = "[h]:mm:ss.000"

That should give you what you're looking for.

NOTE: Specially formatted fields often require that the column width be wide enough for the entire contents of the formatted text. Otherwise, the text will display as ######.

Error: could not find function ... in R

I can usually resolve this problem when a computer is under my control, but it's more of a nuisance when working with a grid. When a grid is not homogenous, not all libraries may be installed, and my experience has often been that a package wasn't installed because a dependency wasn't installed. To address this, I check the following:

  1. Is Fortran installed? (Look for 'gfortran'.) This affects several major packages in R.
  2. Is Java installed? Are the Java class paths correct?
  3. Check that the package was installed by the admin and available for use by the appropriate user. Sometimes users will install packages in the wrong places or run without appropriate access to the right libraries. .libPaths() is a good check.
  4. Check ldd results for R, to be sure about shared libraries
  5. It's good to periodically run a script that just loads every package needed and does some little test. This catches the package issue as early as possible in the workflow. This is akin to build testing or unit testing, except it's more like a smoke test to make sure that the very basic stuff works.
  6. If packages can be stored in a network-accessible location, are they? If they cannot, is there a way to ensure consistent versions across the machines? (This may seem OT, but correct package installation includes availability of the right version.)
  7. Is the package available for the given OS? Unfortunately, not all packages are available across platforms. This goes back to step 5. If possible, try to find a way to handle a different OS by switching to an appropriate flavor of a package or switch off the dependency in certain cases.

Having encountered this quite a bit, some of these steps become fairly routine. Although #7 might seem like a good starting point, these are listed in approximate order of the frequency that I use them.

How to get first two characters of a string in oracle query?

Just use SUBSTR function. It takes 3 parameters: String column name, starting index and length of substring:

select SUBSTR(OrderNo, 1, 2) FROM shipment;

Getting the SQL from a Django QuerySet

Easy:

print my_queryset.query

For example:

from django.contrib.auth.models import User
print User.objects.filter(last_name__icontains = 'ax').query

It should also be mentioned that if you have DEBUG = True, then all of your queries are logged, and you can get them by accessing connection.queries:

from django.db import connections
connections['default'].queries

The django debug toolbar project uses this to present the queries on a page in a neat manner.

SQL Server NOLOCK and joins

I was pretty sure that you need to specify the NOLOCK for each JOIN in the query. But my experience was limited to SQL Server 2005.

When I looked up MSDN just to confirm, I couldn't find anything definite. The below statements do seem to make me think, that for 2008, your two statements above are equivalent though for 2005 it is not the case:

[SQL Server 2008 R2]

All lock hints are propagated to all the tables and views that are accessed by the query plan, including tables and views referenced in a view. Also, SQL Server performs the corresponding lock consistency checks.

[SQL Server 2005]

In SQL Server 2005, all lock hints are propagated to all the tables and views that are referenced in a view. Also, SQL Server performs the corresponding lock consistency checks.

Additionally, point to note - and this applies to both 2005 and 2008:

The table hints are ignored if the table is not accessed by the query plan. This may be caused by the optimizer choosing not to access the table at all, or because an indexed view is accessed instead. In the latter case, accessing an indexed view can be prevented by using the OPTION (EXPAND VIEWS) query hint.

How to find cube root using Python?

def cube(x):
    if 0<=x: return x**(1./3.)
    return -(-x)**(1./3.)
print (cube(8))
print (cube(-8))

Here is the full answer for both negative and positive numbers.

>>> 
2.0
-2.0
>>> 

Or here is a one-liner;

root_cube = lambda x: x**(1./3.) if 0<=x else -(-x)**(1./3.)

Convert string (without any separator) to list

You can use the re module:

import re
re.sub(r'\D', '', '+123-456-7890')

This will replace all non-digits with ''.

Determine Pixel Length of String in Javascript/jQuery?

I don't believe you can do just a string, but if you put the string inside of a <span> with the correct attributes (size, font-weight, etc); you should then be able to use jQuery to get the width of the span.

<span id='string_span' style='font-weight: bold; font-size: 12'>Here is my string</span>
<script>
  $('#string_span').width();
</script>

Why can templates only be implemented in the header file?

The compiler will generate code for each template instantiation when you use a template during the compilation step. In the compilation and linking process .cpp files are converted to pure object or machine code which in them contains references or undefined symbols because the .h files that are included in your main.cpp have no implementation YET. These are ready to be linked with another object file that defines an implementation for your template and thus you have a full a.out executable.

However since templates need to be processed in the compilation step in order to generate code for each template instantiation that you define, so simply compiling a template separate from it's header file won't work because they always go hand and hand, for the very reason that each template instantiation is a whole new class literally. In a regular class you can separate .h and .cpp because .h is a blueprint of that class and the .cpp is the raw implementation so any implementation files can be compiled and linked regularly, however using templates .h is a blueprint of how the class should look not how the object should look meaning a template .cpp file isn't a raw regular implementation of a class, it's simply a blueprint for a class, so any implementation of a .h template file can't be compiled because you need something concrete to compile, templates are abstract in that sense.

Therefore templates are never separately compiled and are only compiled wherever you have a concrete instantiation in some other source file. However, the concrete instantiation needs to know the implementation of the template file, because simply modifying the typename T using a concrete type in the .h file is not going to do the job because what .cpp is there to link, I can't find it later on because remember templates are abstract and can't be compiled, so I'm forced to give the implementation right now so I know what to compile and link, and now that I have the implementation it gets linked into the enclosing source file. Basically, the moment I instantiate a template I need to create a whole new class, and I can't do that if I don't know how that class should look like when using the type I provide unless I make notice to the compiler of the template implementation, so now the compiler can replace T with my type and create a concrete class that's ready to be compiled and linked.

To sum up, templates are blueprints for how classes should look, classes are blueprints for how an object should look. I can't compile templates separate from their concrete instantiation because the compiler only compiles concrete types, in other words, templates at least in C++, is pure language abstraction. We have to de-abstract templates so to speak, and we do so by giving them a concrete type to deal with so that our template abstraction can transform into a regular class file and in turn, it can be compiled normally. Separating the template .h file and the template .cpp file is meaningless. It is nonsensical because the separation of .cpp and .h only is only where the .cpp can be compiled individually and linked individually, with templates since we can't compile them separately, because templates are an abstraction, therefore we are always forced to put the abstraction always together with the concrete instantiation where the concrete instantiation always has to know about the type being used.

Meaning typename T get's replaced during the compilation step not the linking step so if I try to compile a template without T being replaced as a concrete value type that is completely meaningless to the compiler and as a result object code can't be created because it doesn't know what T is.

It is technically possible to create some sort of functionality that will save the template.cpp file and switch out the types when it finds them in other sources, I think that the standard does have a keyword export that will allow you to put templates in a separate cpp file but not that many compilers actually implement this.

Just a side note, when making specializations for a template class, you can separate the header from the implementation because a specialization by definition means that I am specializing for a concrete type that can be compiled and linked individually.

C# - Create SQL Server table programmatically

First, check whether the table exists or not. Accordingly, create table if doesn't exist.

var commandStr= "If not exists (select name from sysobjects where name = 'Customer') CREATE TABLE Customer(First_Name char(50),Last_Name char(50),Address char(50),City char(50),Country char(25),Birth_Date datetime)";

using (SqlCommand command = new SqlCommand(commandStr, con))
command.ExecuteNonQuery();

Finding rows that don't contain numeric data in Oracle

After doing some testing, building upon the suggestions in the previous answers, there seem to be two usable solutions.

Method 1 is fastest, but less powerful in terms of matching more complex patterns.
Method 2 is more flexible, but slower.

Method 1 - fastest
I've tested this method on a table with 1 million rows.
It seems to be 3.8 times faster than the regex solutions.
The 0-replacement solves the issue that 0 is mapped to a space, and does not seem to slow down the query.

SELECT *
FROM <table>
WHERE TRANSLATE(replace(<char_column>,'0',''),'0123456789',' ') IS NOT NULL;

Method 2 - slower, but more flexible
I've compared the speed of putting the negation inside or outside the regex statement. Both are equally slower than the translate-solution. As a result, @ciuly's approach seems most sensible when using regex.

SELECT *
FROM <table>
WHERE NOT REGEXP_LIKE(<char_column>, '^[0-9]+$');

How to remove blank lines from a Unix file

sed -i '/^$/d' foo

This tells sed to delete every line matching the regex ^$ i.e. every empty line. The -i flag edits the file in-place, if your sed doesn't support that you can write the output to a temporary file and replace the original:

sed '/^$/d' foo > foo.tmp
mv foo.tmp foo

If you also want to remove lines consisting only of whitespace (not just empty lines) then use:

sed -i '/^[[:space:]]*$/d' foo

Edit: also remove whitespace at the end of lines, because apparently you've decided you need that too:

sed -i '/^[[:space:]]*$/d;s/[[:space:]]*$//' foo

How can I display a messagebox in ASP.NET?

The best solution is a minimal use of java directly in the visualstudio GUI

here it is: On a button go to the "OnClientClick" property (its not into events*) overthere type:

return confirm('are you sure?')

it will put a dialog with cancel ok buttons transparent over current page if cancel is pressed no postback will ocure. However if you want only ok button type:

alert ('i told you so')

The events like onclick work server side they execute your code, while OnClientClick runs in the browser side. the come most close to a basic dialog

POSTing JSON to URL via WebClient in C#

You need a json serializer to parse your content, probably you already have it, for your initial question on how to make a request, this might be an idea:

var baseAddress = "http://www.example.com/1.0/service/action";

var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
http.Accept = "application/json";
http.ContentType = "application/json";
http.Method = "POST";

string parsedContent = <<PUT HERE YOUR JSON PARSED CONTENT>>;
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(parsedContent);

Stream newStream = http.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();

var response = http.GetResponse();

var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();

hope it helps,

iPad Safari scrolling causes HTML elements to disappear and reappear with a delay

In my case (an iOS Phonegap app), applying translate3d to relative child elements did not resolve the issue. My scrollable element didn't have a set height as it was absolutely positioned and I was defining the top and bottom positions. What fixed it for me was adding a min-height (of 100px).

How can I use an array of function pointers?

You have a good example here (Array of Function pointers), with the syntax detailed.

int sum(int a, int b);
int subtract(int a, int b);
int mul(int a, int b);
int div(int a, int b);

int (*p[4]) (int x, int y);

int main(void)
{
  int result;
  int i, j, op;

  p[0] = sum; /* address of sum() */
  p[1] = subtract; /* address of subtract() */
  p[2] = mul; /* address of mul() */
  p[3] = div; /* address of div() */
[...]

To call one of those function pointers:

result = (*p[op]) (i, j); // op being the index of one of the four functions

How to measure time in milliseconds using ANSI C?

The best precision you can possibly get is through the use of the x86-only "rdtsc" instruction, which can provide clock-level resolution (ne must of course take into account the cost of the rdtsc call itself, which can be measured easily on application startup).

The main catch here is measuring the number of clocks per second, which shouldn't be too hard.

Iterating through a string word by word

s = 'hi how are you'
l = list(map(lambda x: x,s.split()))
print(l)

Output: ['hi', 'how', 'are', 'you']

What is the difference between =Empty and IsEmpty() in VBA (Excel)?

From the Help:
IsEmpty returns True if the variable is uninitialized, or is explicitly set to Empty; otherwise, it returns False. False is always returned if expression contains more than one variable.
IsEmpty only returns meaningful information for variants.

To check if a cell is empty, you can use cell(x,y) = "".
You might eventually save time by using Range("X:Y").SpecialCells(xlCellTypeBlanks) or xlCellTypeConstants or xlCellTypeFormulas

How do I search within an array of hashes by hash values in ruby?

if your array looks like

array = [
 {:name => "Hitesh" , :age => 27 , :place => "xyz"} ,
 {:name => "John" , :age => 26 , :place => "xtz"} ,
 {:name => "Anil" , :age => 26 , :place => "xsz"} 
]

And you Want To know if some value is already present in your array. Use Find Method

array.find {|x| x[:name] == "Hitesh"}

This will return object if Hitesh is present in name otherwise return nil

pull/push from multiple remote locations

You'll need a script to loop through them. Git doesn't a provide a "push all." You could theoretically do a push in multiple threads, but a native method is not available.

Fetch is even more complicated, and I'd recommend doing that linearly.

I think your best answer is to have once machine that everybody does a push / pull to, if that's at all possible.

Javascript : calling function from another file

Yes you can. Just check my fiddle for clarification. For demo purpose i kept the code in fiddle at same location. You can extract that code as shown in two different Javascript files and load them in html file.

https://jsfiddle.net/mvora/mrLmkxmo/

 /******** PUT THIS CODE IN ONE JS FILE *******/

    var secondFileFuntion = function(){
        this.name = 'XYZ';
    }

    secondFileFuntion.prototype.getSurname = function(){
     return 'ABC';
    }


    var secondFileObject = new secondFileFuntion();

    /******** Till Here *******/

    /******** PUT THIS CODE IN SECOND JS FILE *******/

    function firstFileFunction(){
      var name = secondFileObject.name;
      var surname = secondFileObject.getSurname()
      alert(name);
      alert(surname );
    }

    firstFileFunction();

If you make an object using the constructor function and trying access the property or method from it in second file, it will give you the access of properties which are present in another file.

Just take care of sequence of including these files in index.html

How to set up fixed width for <td>?

_x000D_
_x000D_
<div class="row" id="divcashgap" style="display:none">_x000D_
                <div class="col-md-12">_x000D_
                    <div class="table-responsive">_x000D_
                        <table class="table table-default" id="gvcashgapp">_x000D_
                            <thead>_x000D_
                                <tr>_x000D_
                                    <th class="1">BranchCode</th>_x000D_
                                    <th class="2"><a>TC</a></th>_x000D_
                                    <th class="3">VourNo</th>_x000D_
                                    <th class="4"  style="min-width:120px;">VourDate</th>_x000D_
                                    <th class="5" style="min-width:120px;">RCPT Date</th>_x000D_
                                    <th class="6">RCPT No</th>_x000D_
                                    <th class="7"><a>PIS No</a></th>_x000D_
                                    <th class="8" style="min-width:160px;">RCPT Ammount</th>_x000D_
                                    <th class="9">Agging</th>_x000D_
                                    <th class="10" style="min-width:160px;">DesPosition Days</th>_x000D_
                                    <th class="11" style="min-width:150px;">Bank Credit Date</th>_x000D_
                                    <th class="12">Comments</th>_x000D_
                                    <th class="13" style="min-width:150px;">BAC Comment</th>_x000D_
                                    <th class="14">BAC Ramark</th>_x000D_
                                    <th class="15" style="min-width:150px;">RAC Comment</th>_x000D_
                                    <th class="16">RAC Ramark</th>_x000D_
                                    <th class="17" style="min-width:120px;">Update Status</th>_x000D_
                                </tr>_x000D_
                            </thead>_x000D_
                            <tbody id="tbdCashGapp"></tbody>_x000D_
                        </table>_x000D_
                    </div>_x000D_
                </div>_x000D_
            </div>
_x000D_
_x000D_
_x000D_

How to position the div popup dialog to the center of browser screen?

I write a code in jquery. It isnt seen an easy way. But i hope it is useful for you.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<style type="text/css">

.popup{
    border: 4px solid #6b6a63;
    width: 800px;
    border-radius :7px;
    margin : auto;
    padding : 20px;
    position:fixed;
}

</style>

<div id="popup" class="popup">
some lengthy text<br>
some lengthy text<br>
some lengthy text<br>
some lengthy text<br>
some lengthy text<br>
some lengthy text<br>
some lengthy text<br>
some lengthy text<br>
</div>

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
$(document).ready(function(){
    var popup_height = document.getElementById('popup').offsetHeight;
    var popup_width = document.getElementById('popup').offsetWidth;
    $(".popup").css('top',(($(window).height()-popup_height)/2));
    $(".popup").css('left',(($(window).width()-popup_width)/2));
});
</script>

VBA macro that search for file in multiple subfolders

This sub will populate a Collection with all files matching the filename or pattern you pass in.

Sub GetFiles(StartFolder As String, Pattern As String, _
             DoSubfolders As Boolean, ByRef colFiles As Collection)

    Dim f As String, sf As String, subF As New Collection, s
    
    If Right(StartFolder, 1) <> "\" Then StartFolder = StartFolder & "\"
    
    f = Dir(StartFolder & Pattern)
    Do While Len(f) > 0
        colFiles.Add StartFolder & f
        f = Dir()
    Loop
    
    If DoSubfolders then
        sf = Dir(StartFolder, vbDirectory)
        Do While Len(sf) > 0
            If sf <> "." And sf <> ".." Then
                If (GetAttr(StartFolder & sf) And vbDirectory) <> 0 Then
                        subF.Add StartFolder & sf
                End If
            End If
            sf = Dir()
        Loop
    
        For Each s In subF
            GetFiles CStr(s), Pattern, True, colFiles
        Next s
    End If

End Sub

Usage:

Dim colFiles As New Collection

GetFiles "C:\Users\Marek\Desktop\Makro\", FName & ".xls", True, colFiles
If colFiles.Count > 0 Then
    'work with found files
End If

What does "export" do in shell programming?

Exported variables such as $HOME and $PATH are available to (inherited by) other programs run by the shell that exports them (and the programs run by those other programs, and so on) as environment variables. Regular (non-exported) variables are not available to other programs.

$ env | grep '^variable='
$                                 # No environment variable called variable
$ variable=Hello                  # Create local (non-exported) variable with value
$ env | grep '^variable='
$                                 # Still no environment variable called variable
$ export variable                 # Mark variable for export to child processes
$ env | grep '^variable='
variable=Hello
$
$ export other_variable=Goodbye   # create and initialize exported variable
$ env | grep '^other_variable='
other_variable=Goodbye
$

For more information, see the entry for the export builtin in the GNU Bash manual, and also the sections on command execution environment and environment.

Note that non-exported variables will be available to subshells run via ( ... ) and similar notations because those subshells are direct clones of the main shell:

$ othervar=present
$ (echo $othervar; echo $variable; variable=elephant; echo $variable)
present
Hello
elephant
$ echo $variable
Hello
$

The subshell can change its own copy of any variable, exported or not, and may affect the values seen by the processes it runs, but the subshell's changes cannot affect the variable in the parent shell, of course.

Some information about subshells can be found under command grouping and command execution environment in the Bash manual.

Receiving login prompt using integrated windows authentication

If your URL has dots in the domain name, IE will treat it like it's an internet address and not local. You have at least two options:

  1. Get an alias to use in the URL to replace server.domain. For example, myapp.
  2. Follow the steps below on your computer.

Go to the site and cancel the login dialog. Let this happen:

enter image description here

In IE’s settings:

enter image description here

enter image description here

enter image description here

How To Format A Block of Code Within a Presentation?

An on-line syntax highlighter:

http://markup.su/highlighter/

or

http://hilite.me/

Just copy and paste into your document.

Why does Boolean.ToString output "True" and not "true"

How is it not compatible with C#? Boolean.Parse and Boolean.TryParse is case insensitive and the parsing is done by comparing the value to Boolean.TrueString or Boolean.FalseString which are "True" and "False".

EDIT: When looking at the Boolean.ToString method in reflector it turns out that the strings are hard coded so the ToString method is as follows:

public override string ToString()
{
    if (!this)
    {
        return "False";
    }
    return "True";
}

Connect Device to Mac localhost Server?

I had the same problem. I turned off my WI-FI on my Mac and then turned it on again, which solved the problem. Click Settings > Turn WI-FI Off.

I tested it by going to Safari on my iPhone and entering my host name or IP address. For example: http://<name>.local or http://10.0.1.5

How can I avoid running ActiveRecord callbacks?

# for rails 3
  if !ActiveRecord::Base.private_method_defined? :update_without_callbacks
    def update_without_callbacks
      attributes_with_values = arel_attributes_values(false, false, attribute_names)
      return false if attributes_with_values.empty?
      self.class.unscoped.where(self.class.arel_table[self.class.primary_key].eq(id)).arel.update(attributes_with_values)
    end
  end

Parse HTML table to Python list?

You should use some HTML parsing library like lxml:

from lxml import etree
s = """<table>
  <tr><th>Event</th><th>Start Date</th><th>End Date</th></tr>
  <tr><td>a</td><td>b</td><td>c</td></tr>
  <tr><td>d</td><td>e</td><td>f</td></tr>
  <tr><td>g</td><td>h</td><td>i</td></tr>
</table>
"""
table = etree.HTML(s).find("body/table")
rows = iter(table)
headers = [col.text for col in next(rows)]
for row in rows:
    values = [col.text for col in row]
    print dict(zip(headers, values))

prints

{'End Date': 'c', 'Start Date': 'b', 'Event': 'a'}
{'End Date': 'f', 'Start Date': 'e', 'Event': 'd'}
{'End Date': 'i', 'Start Date': 'h', 'Event': 'g'}

Build project into a JAR automatically in Eclipse

Check out Apache Ant

It's possible to use Ant for automatic builds with eclipse, here's how

Jackson: how to prevent field serialization

Illustrating what StaxMan has stated, this works for me

private String password;

@JsonIgnore
public String getPassword() {
    return password;
}

@JsonProperty
public void setPassword(String password) {
    this.password = password;
}

Combine Multiple child rows into one row MYSQL

Here is how you would construct your query for this type of requirement.

select ID,Item_Name,max(Flavor) as Flavor,max(Extra_Cheese) as Extra_Cheese
    from (select i.*,
                    case when o.Option_Number=43 then o.value else null end as Flavor,
                    case when o.Option_Number=44 then o.value else null end as Extra_Cheese
                from Ordered_Item i,Ordered_Options o) a
    group by ID,Item_Name;

You basically "case out" each column using case when, then select the max() for each of those columns using group by for each intended item.

Xcode 6 iPhone Simulator Application Support location

Use Finder-->go to folder and enter given basepath to reach application folders

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;

NSLog(@"%@",basePath);

Difference between "managed" and "unmanaged"

This is more general than .NET and Windows. Managed is an environment where you have automatic memory management, garbage collection, type safety, ... unmanaged is everything else. So for example .NET is a managed environment and C/C++ is unmanaged.

pass **kwargs argument to another function with **kwargs

Expanding on @gecco 's answer, the following is an example that'll show you the difference:

def foo(**kwargs):
    for entry in kwargs.items():
        print("Key: {}, value: {}".format(entry[0], entry[1]))

# call using normal keys:
foo(a=1, b=2, c=3)
# call using an unpacked dictionary:
foo(**{"a": 1, "b":2, "c":3})

# call using a dictionary fails because the function will think you are
# giving it a positional argument
foo({"a": 1, "b": 2, "c": 3})
# this yields the same error as any other positional argument
foo(3)
foo("string")

Here you can see how unpacking a dictionary works, and why sending an actual dictionary fails

Set drawable size programmatically

Use the post method to achieve the desired effect:

{your view}.post(new Runnable()
    {
        @Override
        public void run()
        {
            Drawable image = context.getResources().getDrawable({drawable image resource id});
            image.setBounds(0, 0, {width amount in pixels}, {height amount in pixels});
            {your view}.setCompoundDrawables(image, null, null, null);
        }
    });

Using :: in C++

The :: is called scope resolution operator. Can be used like this:

:: identifier
class-name :: identifier
namespace :: identifier

You can read about it here
https://docs.microsoft.com/en-us/cpp/cpp/scope-resolution-operator?view=vs-2017

python - checking odd/even numbers and changing outputs on number size

The modulo 2 solutions with %2 is good, but that requires a division and a subtraction. Because computers use binary arithmetic, a much more efficient solution is:

# This first solution does not produce a Boolean value. 
is_odd_if_zero = value & 1

# or

is_odd = (value & 1) == 1

# or

is_even = (value & 1) == 0

How to auto adjust the div size for all mobile / tablet display formats?

You question is a bit unclear as to what you want, but judging from your comments, I assume you want each bubble to cover the screen, both vertically and horizontally. In that case, the vertical part is the tricky part.

As many others have answered, you first need to make sure that you are setting the viewport meta tag to trigger mobile devices to use their "ideal" viewport instead of the emulated "desktop width" viewport. The easiest and most fool proof version of this tag is as follows:

<meta name="viewport" content="width=device-width, initial-scale=1">

Source: PPK, probably the leading expert on how this stuff works. (See http://quirksmode.org/presentations/Spring2014/viewports_jqueryeu.pdf).

Essentially, the above makes sure that media queries and CSS measurements correspond to the ideal display of a virtual "point" on any given device — instead of shrinking pages to work with non-optimized desktop layouts. You don't need to understand the details of it, but it's important.

Now that we have a correct (non-faked) mobile viewport to work with, adjusting to the height of the viewport is still a tricky subject. Generally, web pages are fine to expand vertically, but not horizontally. So when you set height: 100% on something, that measurement has to relate to something else. At the topmost level, this is the size of the HTML element. But when the HTML element is taller than the screen (and expands to contain the contents), your measurements in percentages will be screwed up.

Enter the vh unit: it works like percentages, but works in relation to the viewport, not the containing block. MDN info page here: https://developer.mozilla.org/en-US/docs/Web/CSS/length#Viewport-percentage_lengths

Using that unit works just like you'd expect:

.bubble { height: 100vh; } /* be as tall as the viewport height. Done. */

It works on a lot of browsers (IE9 and up, modern Firefox, Safari, Chrome, Opera etc) but not all (support info here: http://caniuse.com/#search=vh). The downside in the browsers where it does work is that there is a massive bug in iOS6-7 that makes this technique unusable for this very case (details here: https://github.com/scottjehl/Device-Bugs/issues/36). It will be fixed in iOS8 though.

Depending on the HTML structure of your project, you may get away with using height: 100% on each element that is supposed to be as tall as the screen, as long as the following conditions are met:

  1. The element is a direct child element of <body>.
  2. Both the html and body elements have a 100% height set.

I have used that technique in the past, but it was long ago and I'm not sure it works on most mobile devices. Try it and see.

The next choice is to use a JavaScript helper to resize your elements to fit the viewport. Either a polyfill fixing the vh issues or something else altogether. Sadly, not every layout is doable in CSS.

How to get an object's properties in JavaScript / jQuery?

You can look up an object's keys and values by either invoking JavaScript's native for in loop:

var obj = {
    foo:    'bar',
    base:   'ball'
};

for(var key in obj) {
    alert('key: ' + key + '\n' + 'value: ' + obj[key]);
}

or using jQuery's .each() method:

$.each(obj, function(key, element) {
    alert('key: ' + key + '\n' + 'value: ' + element);
});

With the exception of six primitive types, everything in ECMA-/JavaScript is an object. Arrays; functions; everything is an object. Even most of those primitives are actually also objects with a limited selection of methods. They are cast into objects under the hood, when required. To know the base class name, you may invoke the Object.prototype.toString method on an object, like this:

alert(Object.prototype.toString.call([]));

The above will output [object Array].

There are several other class names, like [object Object], [object Function], [object Date], [object String], [object Number], [object Array], and [object Regex].

Post parameter is always null

I've just had this occur using Fiddler. The problem was that I hadn't specified Content-Type.

Try including a header for Content-Type in your POST request.

Content-Type: application/x-www-form-urlencoded

Alternatively, as per comments below, you may need to include a JSON header

Content-Type: application/json

Retrieving the first digit of a number

firstDigit = number/((int)(pow(10,(int)log(number))));

This should get your first digit using math instead of strings.

In your example log(543) = 2.73 which casted to an int is 2. pow(10, 2) = 100 543/100 = 5.43 but since it's an int it gets truncated to 5

Get a json via Http Request in NodeJS

Just setting json option to true, the body will contain the parsed json:

request({
  url: 'http://...',
  json: true
}, function(error, response, body) {
  console.log(body);
});

How do I activate C++ 11 in CMake?

As it turns out, SET(CMAKE_CXX_FLAGS "-std=c++0x") does activate many C++11 features. The reason it did not work was that the statement looked like this:

set(CMAKE_CXX_FLAGS "-std=c++0x ${CMAKE_CXX_FLAGS} -g -ftest-coverage -fprofile-arcs")

Following this approach, somehow the -std=c++0x flag was overwritten and it did not work. Setting the flags one by one or using a list method is working.

list( APPEND CMAKE_CXX_FLAGS "-std=c++0x ${CMAKE_CXX_FLAGS} -g -ftest-coverage -fprofile-arcs")

HTML text-overflow ellipsis detection

This sample show tooltip on cell table with text truncated. Is dynamic based on table width:

$.expr[':'].truncated = function (obj) {
    var element = $(obj);

    return (element[0].scrollHeight > (element.innerHeight() + 1)) || (element[0].scrollWidth > (element.innerWidth() + 1));
};

$(document).ready(function () {
    $("td").mouseenter(function () {
        var cella = $(this);
        var isTruncated = cella.filter(":truncated").length > 0;
        if (isTruncated) 
            cella.attr("title", cella.text());
        else 
            cella.attr("title", null);
    });
});

Demo: https://jsfiddle.net/t4qs3tqs/

It works on all version of jQuery

Git: can't undo local changes (error: path ... is unmerged)

git checkout origin/[branch] .
git status

// Note dot (.) at the end. And all will be good

Simple JavaScript problem: onClick confirm not preventing default action

I use this, works like a charm. No need to have any functions, just inline with your link(s)

onclick="javascript:return confirm('Are you sure you want to delete this comment?')"

How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?

java.text (prior to java 8)

public static ThreadLocal<DateFormat> dateFormat = new ThreadLocal<DateFormat>() {
    protected DateFormat initialValue() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    };
};

...
dateFormat.get().format(new Date());

java.time

public static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");

...
dateTimeFormatter.format(LocalDateTime.now());

How can I make a ComboBox non-editable in .NET?

for winforms .NET change DropDownStyle to DropDownList from Combobox property

Disabled form inputs do not appear in the request

I'm updating this answer since is very useful. Just add readonly to the input.

So the form will be:

<form action="/Media/Add">
    <input type="hidden" name="Id" value="123" />
    <input type="textbox" name="Percentage" value="100" readonly/>
</form>

Comparing two .jar files

Extract each jar to it's own directory using the jar command with parameters xvf. i.e. jar xvf myjar.jar for each jar.

Then, use the UNIX command diff to compare the two directories. This will show the differences in the directories. You can use diff -r dir1 dir2 two recurse and show the differences in text files in each directory(.xml, .properties, etc).

This will also show if binary class files differ. To actually compare the class files you will have to decompile them as noted by others.

Is there any use for unique_ptr with array?

unique_ptr<char[]> can be used where you want the performance of C and convenience of C++. Consider you need to operate on millions (ok, billions if you don't trust yet) of strings. Storing each of them in a separate string or vector<char> object would be a disaster for the memory (heap) management routines. Especially if you need to allocate and delete different strings many times.

However, you can allocate a single buffer for storing that many strings. You wouldn't like char* buffer = (char*)malloc(total_size); for obvious reasons (if not obvious, search for "why use smart ptrs"). You would rather like unique_ptr<char[]> buffer(new char[total_size]);

By analogy, the same performance&convenience considerations apply to non-char data (consider millions of vectors/matrices/objects).

Import-Module : The specified module 'activedirectory' was not loaded because no valid module file was found in any module directory

The ActiveDirectory module for powershell can be installed by adding the RSAT-AD-Powershell feature.

In an elevated powershell window:

Add-WindowsFeature RSAT-AD-PowerShell

or

Enable-WindowsOptionalFeature -FeatureName ActiveDirectory-Powershell -Online -All

How to convert java.lang.Object to ArrayList?

I hope this will be help you

import java.util.ArrayList; 
public class Demo {

 public static void main(String[] args) {
    Object obj2 =null;
    ArrayList al1 = (ArrayList) obj2;
    al1 = (ArrayList) obj2;
    System.out.println("List2 Value: " + al1);
    }
 }

obj2 Object is default null before you cast it to ArrayList. That's why print 'al1' as null.

What's the best way to parse a JSON response from the requests library?

You can use json.loads:

import json
import requests

response = requests.get(...)
json_data = json.loads(response.text)

This converts a given string into a dictionary which allows you to access your JSON data easily within your code.

Or you can use @Martijn's helpful suggestion, and the higher voted answer, response.json().

How do I read an image file using Python?

The word "read" is vague, but here is an example which reads a jpeg file using the Image class, and prints information about it.

from PIL import Image
jpgfile = Image.open("picture.jpg")

print(jpgfile.bits, jpgfile.size, jpgfile.format)

Reading json files in C++

Essentially javascript and C++ work on two different principles. Javascript creates an "associative array" or hash table, which matches a string key, which is the field name, to a value. C++ lays out structures in memory, so the first 4 bytes are an integer, which is an age, then maybe we have a fixed-wth 32 byte string which represents the "profession".

So javascript will handle things like "age" being 18 in one record and "nineteen" in another. C++ can't. (However C++ is much faster).

So if we want to handle JSON in C++, we have to build the associative array from the ground up. Then we have to tag the values with their types. Is it an integer, a real value (probably return as "double"), boolean, a string? It follows that a JSON C++ class is quite a large chunk of code. Effectively what we are doing is implementing a bit of the javascript engine in C++. We then pass our JSON parser the JSON as a string, and it tokenises it, and gives us functions to query the JSON from C++.

Remove trailing zeros

how about this:

public static string TrimEnd(this decimal d)
    {
        string str = d.ToString();
        if (str.IndexOf(".") > 0)
        {
            str = System.Text.RegularExpressions.Regex.Replace(str.Trim(), "0+?$", " ");
            str = System.Text.RegularExpressions.Regex.Replace(str.Trim(), "[.]$", " ");
        }
        return str;
    }

Django Template Variables and Javascript

I was facing simillar issue and answer suggested by S.Lott worked for me.

<script type="text/javascript"> 
   var a = "{{someDjangoVariable}}"
</script>

However I would like to point out major implementation limitation here. If you are planning to put your javascript code in different file and include that file in your template. This won't work.

This works only when you main template and javascript code is in same file. Probably django team can address this limitation.

Google Maps: Set Center, Set Center Point and Set more points

Try using this code for v3:

gMap = new google.maps.Map(document.getElementById('map')); 
gMap.setZoom(13);      // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);

Converting a vector<int> to string

I usually do it this way...

#include <string>
#include <vector>

int main( int argc, char* argv[] )
{
    std::vector<char> vec;
    //... do something with vec
    std::string str(vec.begin(), vec.end());
    //... do something with str
    return 0;
}

How to add a browser tab icon (favicon) for a website?

Kindly use below code in header section your index file.

<link rel="icon" href="yourfevicon.ico" />

jQuery iframe load() event?

If possible, you'd be better off handling the load event within the iframe's document and calling out to a function in the containing document. This has the advantage of working in all browsers and only running once.

In the main document:

function iframeLoaded() {
    alert("Iframe loaded!");
}

In the iframe document:

window.onload = function() {
    parent.iframeLoaded();
}

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

It is easy you need to echo the value you need to return and then capture it like below

demofunc(){
    local variable="hellow"
    echo $variable    
}

val=$(demofunc)
echo $val

how to convert a string to an array in php

explode — Split a string by a string

Syntax :

array explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ] )
  • $delimiter : based on which you want to split string
  • $string. : The string you want to split

Example :

// Example 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

In your example :

$str = "this is string"; 
$array = explode(' ', $str);

node.js require() cache - possible to invalidate?

I made a small module to delete module from the cache after loading. This forces reevaluation of the module next time it is required. See https://github.com/bahmutov/require-and-forget

// random.js
module.exports = Math.random()
const forget = require('require-and-forget')
const r1 = forget('./random')
const r2 = forget('./random')
// r1 and r2 will be different
// "random.js" will not be stored in the require.cache

PS: you can also put "self-destruct" into the module itself. See https://github.com/bahmutov/unload-me

PSS: more tricks with Node require in my https://glebbahmutov.com/blog/hacking-node-require/

How to construct a WebSocket URI relative to the page URI?

In typescript:

export class WebsocketUtils {

    public static websocketUrlByPath(path) {
        return this.websocketProtocolByLocation() +
            window.location.hostname +
            this.websocketPortWithColonByLocation() +
            window.location.pathname +
            path;
    }

    private static websocketProtocolByLocation() {
        return window.location.protocol === "https:" ? "wss://" : "ws://";
    }

    private static websocketPortWithColonByLocation() {
        const defaultPort = window.location.protocol === "https:" ? "443" : "80";
        if (window.location.port !== defaultPort) {
            return ":" + window.location.port;
        } else {
            return "";
        }
    }
}

Usage:

alert(WebsocketUtils.websocketUrlByPath("/websocket"));

Dynamically updating css in Angular 2

you can achive this by calling a function also

<div [style.width.px]="getCustomeWidth()"></div>

  getCustomeWidth() {
    //do what ever you want here
    return customeWidth;
  }

Detect WebBrowser complete page loading

If you're using WPF there is a LoadCompleted event.

If it's Windows.Forms, the DocumentCompleted event should be the correct one. If the page you're loading has frames, your WebBrowser control will fire the DocumentCompleted event for each frame (see here for more details). I would suggest checking the IsBusy property each time the event is fired and if it is false then your page is fully done loading.

How do you rename a Git tag?

As an add on to the other answers, I added an alias to do it all in one step, with a more familiar *nix move command feel. Argument 1 is the old tag name, argument 2 is the new tag name.

[alias]
    renameTag = "!sh -c 'set -e;git tag $2 $1; git tag -d $1;git push origin :refs/tags/$1;git push --tags' -"

Usage:

git renametag old new

How to convert date to timestamp in PHP?

<?php echo date('M j Y g:i A', strtotime('2013-11-15 13:01:02')); ?>

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

How do you change the value inside of a textfield flutter?

First Thing

  TextEditingController MyController= new TextEditingController();

Then add it to init State or in any SetState

    MyController.value = TextEditingValue(text: "ANY TEXT");

How to send email from Terminal?

For SMTP hosts and Gmail I like to use Swaks -> https://easyengine.io/tutorials/mail/swaks-smtp-test-tool/

On a Mac:

  1. brew install swaks
  2. swaks --to [email protected] --server smtp.example.com

Build .so file from .c file using gcc command line

To generate a shared library you need first to compile your C code with the -fPIC (position independent code) flag.

gcc -c -fPIC hello.c -o hello.o

This will generate an object file (.o), now you take it and create the .so file:

gcc hello.o -shared -o libhello.so

EDIT: Suggestions from the comments:

You can use

gcc -shared -o libhello.so -fPIC hello.c

to do it in one step. – Jonathan Leffler

I also suggest to add -Wall to get all warnings, and -g to get debugging information, to your gcc commands. – Basile Starynkevitch

What are Java command line options to set to allow JVM to be remotely debugged?

Here is the easiest solution.

There are a lot of environment special configurations needed if you are using Maven. So, if you start your program from maven, just run the mvnDebug command instead of mvn, it will take care of starting your app with remote debugging configurated. Now you can just attach a debugger on port 8000.

It'll take care of all the environment problems for you.

How can I unstage my files again after making a local commit?

git reset --soft is just for that: it is like git reset --hard, but doesn't touch the files.

What is the size of a pointer?

Pointers generally have a fixed size, for ex. on a 32-bit executable they're usually 32-bit. There are some exceptions, like on old 16-bit windows when you had to distinguish between 32-bit pointers and 16-bit... It's usually pretty safe to assume they're going to be uniform within a given executable on modern desktop OS's.

Edit: Even so, I would strongly caution against making this assumption in your code. If you're going to write something that absolutely has to have a pointers of a certain size, you'd better check it!

Function pointers are a different story -- see Jens' answer for more info.

python : list index out of range error while iteratively popping elements

The problem was that you attempted to modify the list you were referencing within the loop that used the list len(). When you remove the item from the list, then the new len() is calculated on the next loop.

For example, after the first run, when you removed (i) using l.pop(i), that happened successfully but on the next loop the length of the list has changed so all index numbers have been shifted. To a certain point the loop attempts to run over a shorted list throwing the error.

Doing this outside the loop works, however it would be better to build and new list by first declaring and empty list before the loop, and later within the loop append everything you want to keep to the new list.

For those of you who may have come to the same problem.

SQL Server 2005 Using CHARINDEX() To split a string

Try the following query:

DECLARE @item VARCHAR(MAX) = 'LD-23DSP-1430'

SELECT
SUBSTRING( @item, 0, CHARINDEX('-', @item)) ,
SUBSTRING(
               SUBSTRING( @item, CHARINDEX('-', @item)+1,LEN(@ITEM)) ,
               0 ,
               CHARINDEX('-', SUBSTRING( @item, CHARINDEX('-', @item)+1,LEN(@ITEM)))
              ),
REVERSE(SUBSTRING( REVERSE(@ITEM), 0, CHARINDEX('-', REVERSE(@ITEM))))

The operation cannot be completed because the DbContext has been disposed error

You need to remember that IQueryable queries are not actually executed against the data store until you enumerate them.

using (var dataContext = new dataContext())
{

This line of code doesn't actually do anything other than build the SQL statement

    users = dataContext.Users.Where(x => x.AccountID == accountId && x.IsAdmin == false);

.Any() is an operation that enumerates the IQueryable, so the SQL is sent to the data source (through dataContext), and then the .Any() operations is executed against it

    if(users.Any() == false)
    {
        return null;
    }
}

Your "problem" line is reusing the sql built above, and then doing an additional operation (.Select()), which just adds to the query. If you left it here, no exception, except your problem line

return users.Select(x => x.ToInfo()).ToList(); // this line is the problem

calls .ToList(), which enumerates the IQueryable, which causes the SQL to be sent to the datasource through the dataContext that was used in the original LINQ query. Since this dataContext has been disposed, it is no longer valid, and .ToList() throws an exception.

That is the "why it doesn't work". The fix is to move this line of code inside the scope of your dataContext.

How to use it properly is another question with a few arguably correct answers that depend on your application (Forms vs. ASP.net vs. MVC, etc.). The pattern that this implements is the Unit of Work pattern. There is almost no cost to creating a new context object, so the general rule is to create one, do your work, and then dispose of it. In web apps, some people will create a Context per request.

Android: Scale a Drawable or background image?

When you set the Drawable of an ImageView by using the setBackgroundDrawable method, the image will always be scaled. Parameters as adjustViewBounds or different ScaleTypes will just be ignored. The only solution to keep the aspect ratio I found, is to resize the ImageView after loading your drawable. Here is the code snippet I used:

// bmp is your Bitmap object
int imgHeight = bmp.getHeight();
int imgWidth = bmp.getWidth();
int containerHeight = imageView.getHeight();
int containerWidth = imageView.getWidth();
boolean ch2cw = containerHeight > containerWidth;
float h2w = (float) imgHeight / (float) imgWidth;
float newContainerHeight, newContainerWidth;

if (h2w > 1) {
    // height is greater than width
    if (ch2cw) {
        newContainerWidth = (float) containerWidth;
        newContainerHeight = newContainerWidth * h2w;
    } else {
        newContainerHeight = (float) containerHeight;
        newContainerWidth = newContainerHeight / h2w;
    }
} else {
    // width is greater than height
    if (ch2cw) {
        newContainerWidth = (float) containerWidth;
        newContainerHeight = newContainerWidth / h2w; 
    } else {
        newContainerWidth = (float) containerHeight;
        newContainerHeight = newContainerWidth * h2w;       
    }
}
Bitmap copy = Bitmap.createScaledBitmap(bmp, (int) newContainerWidth, (int) newContainerHeight, false);
imageView.setBackgroundDrawable(new BitmapDrawable(copy));
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
imageView.setLayoutParams(params);
imageView.setMaxHeight((int) newContainerHeight);
imageView.setMaxWidth((int) newContainerWidth);

In the code snippet above is bmp the Bitmap object that is to be shown and imageView is the ImageView object

An important thing to note is the change of the layout parameters. This is necessary because setMaxHeight and setMaxWidth will only make a difference if the width and height are defined to wrap the content, not to fill the parent. Fill parent on the other hand is the desired setting at the beginning, because otherwise containerWidth and containerHeight will both have values equal to 0. So, in your layout file you will have something like this for your ImageView:

...
<ImageView android:id="@+id/my_image_view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"/>
...

Uploading images using Node.js, Express, and Mongoose

Here's a way to upload your images using the formidable package, which is recommended over bodyParser in later versions of Express. This also includes the ability to resize your images on the fly:

From my website: Uploading and Resizing Images (on the fly) With Node.js and Express.

Here's the gist:

var express = require("express"),
app = express(),
formidable = require('formidable'),
util = require('util')
fs   = require('fs-extra'),
qt   = require('quickthumb');

// Use quickthumb
app.use(qt.static(__dirname + '/'));

app.post('/upload', function (req, res){
  var form = new formidable.IncomingForm();
  form.parse(req, function(err, fields, files) {
    res.writeHead(200, {'content-type': 'text/plain'});
    res.write('received upload:\n\n');
    res.end(util.inspect({fields: fields, files: files}));
  });

  form.on('end', function(fields, files) {
    /* Temporary location of our uploaded file */
    var temp_path = this.openedFiles[0].path;
    /* The file name of the uploaded file */
    var file_name = this.openedFiles[0].name;
    /* Location where we want to copy the uploaded file */
    var new_location = 'uploads/';

    fs.copy(temp_path, new_location + file_name, function(err) {  
      if (err) {
        console.error(err);
      } else {
        console.log("success!")
      }
    });
  });
});

// Show the upload form 
app.get('/', function (req, res){
  res.writeHead(200, {'Content-Type': 'text/html' });
  /* Display the file upload form. */
  form = '<form action="/upload" enctype="multipart/form-data" method="post">'+ '<input name="title" type="text" />
  '+ '<input multiple="multiple" name="upload" type="file" />
  '+ '<input type="submit" value="Upload" />'+ '</form>';
  res.end(form); 
}); 
app.listen(8080);

NOTE: This requires Image Magick for the quick thumb resizing.

Base64: java.lang.IllegalArgumentException: Illegal character

Your encoded text is [B@6499375d. That is not Base64, something went wrong while encoding. That decoding code looks good.

Use this code to convert the byte[] to a String before adding it to the URL:

String encodedEmailString = new String(encodedEmail, "UTF-8");
// ...
String confirmLink = "Complete your registration by clicking on following"
    + "\n<a href='" + confirmationURL + encodedEmailString + "'>link</a>";

How do I loop through items in a list box and then remove those item?

Do you want to remove all items? If so, do the foreach first, then just use Items.Clear() to remove all of them afterwards.

Otherwise, perhaps loop backwards by indexer:

listBox1.BeginUpdate();
try {
  for(int i = listBox1.Items.Count - 1; i >= 0 ; i--) {
    // do with listBox1.Items[i]

    listBox1.Items.RemoveAt(i);
  }
} finally {
  listBox1.EndUpdate();
}

Add column to dataframe with constant value

df['Name']='abc' will add the new column and set all rows to that value:

In [79]:

df
Out[79]:
         Date, Open, High,  Low,  Close
0  01-01-2015,  565,  600,  400,    450
In [80]:

df['Name'] = 'abc'
df
Out[80]:
         Date, Open, High,  Low,  Close Name
0  01-01-2015,  565,  600,  400,    450  abc

How to force reloading a page when using browser back button?

Since performance.navigation is now deprecated, you can try this:

var perfEntries = performance.getEntriesByType("navigation");

if (perfEntries[0].type === "back_forward") {
    location.reload(true);
}

How to write std::string to file?

remove the ios::binary from your modes in your ofstream and use studentPassword.c_str() instead of (char *)&studentPassword in your write.write()

How to access Spring MVC model object in javascript file?

I recently faced the same need. So I tried Aurand's way but it seems the code is missing ${}. So the code inside SomeJsp.jsp <head></head>is:

<script>
  var model=[];
  model.paramOne="${model.paramOne}";
  model.paramTwo="${model.paramTwo}";
  model.paramThree="${model.paramThree}";
</script>

Note that you can't asssign using var model = ${model} as it will assign a java object reference. So to access this in external JS:

$(document).ready(function() {
   alert(model.paramOne);
});

Bash array with spaces in elements

If you aren't stuck on using bash, different handling of spaces in file names is one of the benefits of the fish shell. Consider a directory which contains two files: "a b.txt" and "b c.txt". Here's a reasonable guess at processing a list of files generated from another command with bash, but it fails due to spaces in file names you experienced:

# bash
$ for f in $(ls *.txt); { echo $f; }
a
b.txt
b
c.txt

With fish, the syntax is nearly identical, but the result is what you'd expect:

# fish
for f in (ls *.txt); echo $f; end
a b.txt
b c.txt

It works differently because fish splits the output of commands on newlines, not spaces.

If you have a case where you do want to split on spaces instead of newlines, fish has a very readable syntax for that:

for f in (ls *.txt | string split " "); echo $f; end

How to use git merge --squash?

You want to merge with the squash option. That's if you want to do it one branch at a time.

git merge --squash feature1

If you want to merge all the branches at the same time as single commits, then first rebase interactively and squash each feature then octopus merge:

git checkout feature1
git rebase -i master

Squash into one commit then repeat for the other features.

git checkout master
git merge feature1 feature2 feature3 ...

That last merge is an "octopus merge" because it's merging a lot of branches at once.

Hope this helps

Specifying onClick event type with Typescript and React.Konva

As posted in my update above, a potential solution would be to use Declaration Merging as suggested by @Tyler-sebastion. I was able to define two additional interfaces and add the index property on the EventTarget in this way.

interface KonvaTextEventTarget extends EventTarget {
  index: number
}

interface KonvaMouseEvent extends React.MouseEvent<HTMLElement> {
  target: KonvaTextEventTarget
}

I then can declare the event as KonvaMouseEvent in my onclick MouseEventHandler function.

onClick={(event: KonvaMouseEvent) => {
          makeMove(ownMark, event.target.index)
}}

I'm still not 100% if this is the best approach as it feels a bit Kludgy and overly verbose just to get past the tslint error.

How do I check when a UITextField changes?

You should follow this steps:

  1. Make a Outlet reference to the textfield
  2. AssignUITextFieldDelegate to the controller class
  3. Configure yourTextField.delegate
  4. Implement whatever function you need

Sample code:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet var yourTextFiled : UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        yourTextFiled.delegate = self
    }


    func textFieldDidEndEditing(_ textField: UITextField) {
        // your code
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        // your code
    }

    .
    .
    .
}

Set the default value in dropdownlist using jQuery

$("#dropdownList option[text='it\'s me']").attr("selected","selected"); 

Can a background image be larger than the div itself?

No, you can't.

But as a solid workaround, I would suggest to classify that first div as position:relative and use div::before to create an underlying element containing your image. Classified as position:absolute you can move it anywhere relative to your initial div.

Don't forget to add content to that new element. Here's some example:

div {
  position: relative;
}    

div::before {
  content: ""; /* empty but necessary */
  position: absolute;
  background: ...
}

Note: if you want it to be 'on top' of the parent div, use div::after instead.

Get current date in Swift 3?

You say in a comment you want to get "15.09.2016".

For this, use Date and DateFormatter:

let date = Date()
let formatter = DateFormatter()

Give the format you want to the formatter:

formatter.dateFormat = "dd.MM.yyyy"

Get the result string:

let result = formatter.string(from: date)

Set your label:

label.text = result

Result:

15.09.2016

Arithmetic operation resulted in an overflow. (Adding integers)

The maximum size for an int is 2147483647. You could use an Int64/Long which is far larger.

How to get a variable from a file to another file in Node.js

File FileOne.js:

module.exports = { ClientIDUnsplash : 'SuperSecretKey' };

File FileTwo.js:

var { ClientIDUnsplash } = require('./FileOne');

This example works best for React.

getting the X/Y coordinates of a mouse click on an image with jQuery

Here is a better script:

$('#mainimage').click(function(e)
{   
    var offset_t = $(this).offset().top - $(window).scrollTop();
    var offset_l = $(this).offset().left - $(window).scrollLeft();

    var left = Math.round( (e.clientX - offset_l) );
    var top = Math.round( (e.clientY - offset_t) );

    alert("Left: " + left + " Top: " + top);

});

executing a function in sql plus

One option would be:

SET SERVEROUTPUT ON

EXEC DBMS_OUTPUT.PUT_LINE(your_fn_name(your_fn_arguments));

Get Specific Columns Using “With()” Function in Laravel Eloquent

You can also specify columns on related model at the time of accessing it.

Post::first()->user()->get(['columns....']);

"Parameter" vs "Argument"

A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.

Consider the following code:

void Foo(int i, float f)
{
    // Do things
}

void Bar()
{
    int anInt = 1;
    Foo(anInt, 2.0);
}

Here i and f are the parameters, and anInt and 2.0 are the arguments.

How to install the JDK on Ubuntu Linux

In case you have already downloaded the ZIP file follow these steps.

Run the following command to unzip your file.

tar -xvf ~/Downloads/jdk-7u3-linux-i586.tar.gz
sudo mkdir -p /usr/lib/jvm/jdk1.7.0
sudo mv jdk1.7.0_03/* /usr/lib/jvm/jdk1.7.0/
sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.7.0/bin/java" 1
sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk1.7.0/bin/javac" 1
sudo update-alternatives --install "/usr/bin/javaws" "javaws" "/usr/lib/jvm/jdk1.7.0/bin/javaws" 1

After installation is complete, set environment variables as follows.

Edit the system path in file /etc/profile:

sudo gedit /etc/profile

Add the following lines at the end.

JAVA_HOME=/usr/lib/jvm/jdk1.7.0
PATH=$PATH:$HOME/bin:$JAVA_HOME/bin
export JAVA_HOME
export PATH

Source: http://javaandme.com/

POST request with JSON body

You need to use the cURL library to send this request.

<?php
// Your ID and token
$blogID = '8070105920543249955';
$authToken = 'OAuth 2.0 token here';

// The data to send to the API
$postData = array(
    'kind' => 'blogger#post',
    'blog' => array('id' => $blogID),
    'title' => 'A new post',
    'content' => 'With <b>exciting</b> content...'
);

// Setup cURL
$ch = curl_init('https://www.googleapis.com/blogger/v3/blogs/'.$blogID.'/posts/');
curl_setopt_array($ch, array(
    CURLOPT_POST => TRUE,
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_HTTPHEADER => array(
        'Authorization: '.$authToken,
        'Content-Type: application/json'
    ),
    CURLOPT_POSTFIELDS => json_encode($postData)
));

// Send the request
$response = curl_exec($ch);

// Check for errors
if($response === FALSE){
    die(curl_error($ch));
}

// Decode the response
$responseData = json_decode($response, TRUE);

// Close the cURL handler
curl_close($ch);

// Print the date from the response
echo $responseData['published'];

If, for some reason, you can't/don't want to use cURL, you can do this:

<?php
// Your ID and token
$blogID = '8070105920543249955';
$authToken = 'OAuth 2.0 token here';

// The data to send to the API
$postData = array(
    'kind' => 'blogger#post',
    'blog' => array('id' => $blogID),
    'title' => 'A new post',
    'content' => 'With <b>exciting</b> content...'
);

// Create the context for the request
$context = stream_context_create(array(
    'http' => array(
        // http://www.php.net/manual/en/context.http.php
        'method' => 'POST',
        'header' => "Authorization: {$authToken}\r\n".
            "Content-Type: application/json\r\n",
        'content' => json_encode($postData)
    )
));

// Send the request
$response = file_get_contents('https://www.googleapis.com/blogger/v3/blogs/'.$blogID.'/posts/', FALSE, $context);

// Check for errors
if($response === FALSE){
    die('Error');
}

// Decode the response
$responseData = json_decode($response, TRUE);

// Print the date from the response
echo $responseData['published'];

'and' (boolean) vs '&' (bitwise) - Why difference in behavior with lists vs numpy arrays?

  1. In Python an expression of X and Y returns Y, given that bool(X) == True or any of X or Y evaluate to False, e.g.:

    True and 20 
    >>> 20
    
    False and 20
    >>> False
    
    20 and []
    >>> []
    
  2. Bitwise operator is simply not defined for lists. But it is defined for integers - operating over the binary representation of the numbers. Consider 16 (01000) and 31 (11111):

    16 & 31
    >>> 16
    
  3. NumPy is not a psychic, it does not know, whether you mean that e.g. [False, False] should be equal to True in a logical expression. In this it overrides a standard Python behaviour, which is: "Any empty collection with len(collection) == 0 is False".

  4. Probably an expected behaviour of NumPy's arrays's & operator.

Float a div above page content

The results container div has position: relative meaning it is still in the document flow and will change the layout of elements around it. You need to use position: absolute to achieve a 'floating' effect.

You should also check the markup you're using, you have phantom <li>s with no container <ul>, you could probably replace both the div#suggestions and div#autoSuggestionsList with a single <ul> and get the desired result.

SSL peer shut down incorrectly in Java

The accepted answer didn't work in my situation, not sure why. I switched from JRE1.7 to JRE1.8 and that resolved the issue automatically. JRE1.8 uses TLS1.2 by default

Convert np.array of type float64 to type uint8 scaling values

A better way to normalize your image is to take each value and divide by the largest value experienced by the data type. This ensures that images that have a small dynamic range in your image remain small and they're not inadvertently normalized so that they become gray. For example, if your image had a dynamic range of [0-2], the code right now would scale that to have intensities of [0, 128, 255]. You want these to remain small after converting to np.uint8.

Therefore, divide every value by the largest value possible by the image type, not the actual image itself. You would then scale this by 255 to produced the normalized result. Use numpy.iinfo and provide it the type (dtype) of the image and you will obtain a structure of information for that type. You would then access the max field from this structure to determine the maximum value.

So with the above, do the following modifications to your code:

import numpy as np
import cv2
[...]
info = np.iinfo(data.dtype) # Get the information of the incoming image type
data = data.astype(np.float64) / info.max # normalize the data to 0 - 1
data = 255 * data # Now scale by 255
img = data.astype(np.uint8)
cv2.imshow("Window", img)

Note that I've additionally converted the image into np.float64 in case the incoming data type is not so and to maintain floating-point precision when doing the division.

EL access a map value by Integer key

You can use all functions from Long, if you put the number into "(" ")". That way you can cast the long to an int:

<c:out value="${map[(1).intValue()]}"/>