Programs & Examples On #Biblatex

It is a management software for formatting lists of references, intended for use together with Latex.

react router v^4.0.0 Uncaught TypeError: Cannot read property 'location' of undefined

You're doing a few things wrong.

  1. First, browserHistory isn't a thing in V4, so you can remove that.

  2. Second, you're importing everything from react-router, it should be react-router-dom.

  3. Third, react-router-dom doesn't export a Router, instead, it exports a BrowserRouter so you need to import { BrowserRouter as Router } from 'react-router-dom.

Looks like you just took your V3 app and expected it to work with v4, which isn't a great idea.

How to reshape data from long to wide format

The base reshape function works perfectly fine:

df <- data.frame(
  year   = c(rep(2000, 12), rep(2001, 12)),
  month  = rep(1:12, 2),
  values = rnorm(24)
)
df_wide <- reshape(df, idvar="year", timevar="month", v.names="values", direction="wide", sep="_")
df_wide

Where

  • idvar is the column of classes that separates rows
  • timevar is the column of classes to cast wide
  • v.names is the column containing numeric values
  • direction specifies wide or long format
  • the optional sep argument is the separator used in between timevar class names and v.names in the output data.frame.

If no idvar exists, create one before using the reshape() function:

df$id   <- c(rep("year1", 12), rep("year2", 12))
df_wide <- reshape(df, idvar="id", timevar="month", v.names="values", direction="wide", sep="_")
df_wide

Just remember that idvar is required! The timevar and v.names part is easy. The output of this function is more predictable than some of the others, as everything is explicitly defined.

How to convert a multipart file to File?

You can also use the Apache Commons IO library and the FileUtils class. In case you are using maven you can load it using the above dependency.

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

The source for the MultipartFile save to disk.

File file = new File(directory, filename);

// Create the file using the touch method of the FileUtils class.
// FileUtils.touch(file);

// Write bytes from the multipart file to disk.
FileUtils.writeByteArrayToFile(file, multipartFile.getBytes());

Google Drive as FTP Server

With google-drive-ftp-adapter I have been able to access the My Drive area of Google Drive with the FileZilla FTP client. However, I have not been able to access the Shared with me area.

You can configure which Google account credentials it uses by changing the account property in the configuration.properties file from default to the desired Google account name. See the instructions at http://www.andresoviedo.org/google-drive-ftp-adapter/

How to open Visual Studio Code from the command line on OSX?

On OSX Mavericks I created a bash script named vscode (adapted from the .bashrc in VSCode Setup) in ~/bin:

#!/bin/bash

if [[ $# = 0 ]]
then
    open -a "Visual Studio Code"
else
    [[ $1 = /* ]] && F="$1" || F="$PWD/${1#./}"
    open -a "Visual Studio Code" --args "$F"
fi

vscode <file or directory> now works as expected.

Get current date/time in seconds

_x000D_
_x000D_
// The Current Unix Timestamp_x000D_
// 1443535752 seconds since Jan 01 1970. (UTC)_x000D_
_x000D_
// Current time in seconds_x000D_
console.log(Math.floor(new Date().valueOf() / 1000));  // 1443535752_x000D_
console.log(Math.floor(Date.now() / 1000));            // 1443535752_x000D_
console.log(Math.floor(new Date().getTime() / 1000));  // 1443535752
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

jQuery

_x000D_
_x000D_
console.log(Math.floor($.now() / 1000));               // 1443535752
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Calling a JavaScript function named in a variable

I'd avoid eval.

To solve this problem, you should know these things about JavaScript.

  1. Functions are first-class objects, so they can be properties of an object (in which case they are called methods) or even elements of arrays.
  2. If you aren't choosing the object a function belongs to, it belongs to the global scope. In the browser, that means you're hanging it on the object named "window," which is where globals live.
  3. Arrays and objects are intimately related. (Rumor is they might even be the result of incest!) You can often substitute using a dot . rather than square brackets [], or vice versa.

Your problem is a result of considering the dot manner of reference rather than the square bracket manner.

So, why not something like,

window["functionName"]();

That's assuming your function lives in the global space. If you've namespaced, then:

myNameSpace["functionName"]();

Avoid eval, and avoid passing a string in to setTimeout and setInterval. I write a lot of JS, and I NEVER need eval. "Needing" eval comes from not knowing the language deeply enough. You need to learn about scoping, context, and syntax. If you're ever stuck with an eval, just ask--you'll learn quickly.

How to show x and y axes in a MATLAB graph?

I know this is coming a bit late, but a colleague of mine figured something out:

figure, plot ((1:10),cos(rand(1,10))-0.75,'*-')
hold on
plot ((1:10),zeros(1,10),'k+-')
text([1:10]-0.09,ones(1,10).*-0.015,[{'0' '1'  '2' '3' '4' '5' '6' '7' '8' '9'}])
set(gca,'XTick',[], 'XColor',[1 1 1])
box off

"Parameter not valid" exception loading System.Drawing.Image

My guess is that byteArrayIn doesn't contain valid image data.

Please give more information though:

  • Which line of code is throwing an exception?
  • What's the message?
  • Where did you get byteArrayIn from, and are you sure it should contain a valid image?

How to change the default encoding to UTF-8 for Apache?

Place AddDefaultCharset UTF-8 into /etc/apache2/conf.d/charset. In fact, it's already there. You just have to uncomment it by removing the preceding #.

Calculating the distance between 2 points

If you are using System.Windows.Point data type to represent a point, you can use

// assuming p1 and p2 data types
Point p1, p2;
// distanc can be calculated as follows
double distance = Point.Subtract(p2, p1).Length;

Update 2017-01-08:

  • Add reference to Microsoft documentation
  • Result of Point.Subtract is System.Windows.Vector and it has also property LengthSquared to save one sqrt calculation if you just need to compare distance.
  • Adding reference to WindowsBase assembly may be needed in your project
  • You can also use operators

Example with LengthSquared and operators

// assuming p1 and p2 data types
Point p1, p2;
// distanc can be calculated as follows
double distanceSquared = (p2 - p1).LengthSquared;

How to construct a relative path in Java from two absolute paths (or URLs)?

org.apache.ant has a FileUtils class with a getRelativePath method. Haven't tried it myself yet, but could be worthwhile to check it out.

http://javadoc.haefelinger.it/org.apache.ant/1.7.1/org/apache/tools/ant/util/FileUtils.html#getRelativePath(java.io.File, java.io.File)

How to show the text on a ImageButton?

Best way:

<Button 
android:text="OK" 
android:id="@+id/buttonok" 
android:background="@drawable/buttonok"
android:layout_width="match_parent" 
android:layout_height="wrap_content"/>

Java converting Image to BufferedImage

If you are getting back a sun.awt.image.ToolkitImage, you can cast the Image to that, and then use getBufferedImage() to get the BufferedImage.

So instead of your last line of code where you are casting you would just do:

BufferedImage buffered = ((ToolkitImage) image).getBufferedImage();

How to encode a URL in Swift

In Mac OS 10.9 Maverics and iOS 7 NSURLComponents has been introduced which handles the encoding of the different URL parts in a pretty convenient way.

The NSURLComponents class is a class that is designed to parse URLs based on RFC 3986 and to construct URLs from their constituent parts. Its behavior differs subtly from the NSURL class, which conforms to older RFCs. However, you can easily obtain an NSURL object based on the contents of a URL components object or vice versa.

let address = "American Tourister, Abids Road, Bogulkunta, Hyderabad, Andhra Pradesh, India"

let components = NSURLComponents(string: "http://maps.googleapis.com/maps/api/geocode/json")!
// create a query item key=value
let queryItem = NSURLQueryItem(name: "address", value: address)
// add the query item to the URL, NSURLComponents takes care of adding the question mark.
components.queryItems = [queryItem]
// get the properly percent encoded string
let urlpath = components.string!
print(urlpath)

When do you use the "this" keyword?

I use it every time I can. I believe it makes the code more readable, and more readable code equals less bugs and more maintainability.

The maximum value for an int type in Go

One way to solve this problem is to get the starting points from the values themselves:

var minLen, maxLen uint
if len(sliceOfThings) > 0 {
  minLen = sliceOfThings[0].minLen
  maxLen = sliceOfThings[0].maxLen
  for _, thing := range sliceOfThings[1:] {
    if minLen > thing.minLen { minLen = thing.minLen }
    if maxLen < thing.maxLen { maxLen = thing.maxLen }
  }
}

Return Max Value of range that is determined by an Index & Match lookup

You can easily change the match-type to 1 when you are looking for the greatest value or to -1 when looking for the smallest value.

C Program to find day of week given date

/*
Program to calculate the day on a given date by User
*/

#include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
int dd=0,mm=0,i=0,yy=0,odd1=0,todd=0;//variable declaration for inputing the date
int remyr=0,remyr1=0,lyrs=0,oyrs=0,cyr=0,upyr=0,leap=0;//variable declaration for calculation of odd days
int montharr[12]={31,28,31,30,31,30,31,31,30,31,30,31};//array of month days
clrscr();
printf("Enter the date as DD-MM-YY for which you want to know the day\t:");
scanf("%d%d%d",&dd,&mm,&yy);  //input the date
/*
check out correct date or not?
*/
if(yy%100==0)
    {
    if(yy%400==0)
        {
        //its the leap year
        leap=1;
        if(dd>29&&mm==2)
            {

            printf("You have entered wrong date");
            getch();
            exit(0);
            }
        }
    else if(dd>28&&mm==2)
        {
        //not the leap year
        printf("You have entered wrong date");
        getch();
        exit(0);

        }
    }
else if(yy%4==0)
    {
    //again leap year
    leap=1;
    if(dd>29&mm==2)
        {
        printf("You have entered wrong date");
        getch();
        exit(0);

        }
    }
else if(dd>28&&mm==2)
    {
    //not the leap year
    printf("You have entered wrong date");
    getch();
    exit(0);

    }
//if the leap year feb month contains 29 days
if(leap==1)
{
montharr[1]=29;

}
//check date,month,year should not be beyond the limits

if((mm>12)||(dd>31)|| (yy>5000))
    {
    printf("Your date is wrong");
    getch();
    exit(0);

    }
//odd months should not contain more than 31 days
if((dd>31 && (mm == 1||mm==3||mm==5||mm==7||mm==8||mm==10||mm==12)))
    {
    printf("Your date is wrong");
    getch();
    exit(0);

    }
//even months should not contains more than 30 days

if((dd>30 && (mm == 4||mm==6||mm==9||mm==11)))
    {
    printf("Your date is wrong");
    getch();
    exit(0);

    }

//logic to calculate odd days.....
printf("\nYou have entered date: %d-%d-%d ",dd,mm,yy);
remyr1=yy-1;
remyr=remyr1%400;

cyr=remyr/100;
if(remyr==0)
    {
    oyrs=0;
    }
else if(cyr==0 && remyr>0)
    {
    oyrs=0;
    }


else if(cyr==1)
    {
    oyrs=5;
    }
else if(cyr==2)
    {
    oyrs=3;
    }
else if(cyr==3)
    {
    oyrs=1;
    }

    upyr=remyr%100;
    lyrs=upyr/4;
    odd1=lyrs+upyr;
    odd1=odd1%7;
    odd1=odd1+oyrs;
    for(i=0;i<mm-1;i++)
        {
        odd1=odd1+montharr[i];
        }
    todd=odd1+dd;
    if(todd>7)
        todd=todd%7;    //total odd days gives the re quired day....
    printf("\n\nThe day on %d-%d-%d :",dd,mm,yy);

    if(todd==0)
        printf("Sunday");
    if(todd==1)
        printf("Monday");
    if(todd==2)
        printf("Tuesday");
    if(todd==3)
        printf("Wednesday");
    if(todd==4)
        printf("Thrusday");
    if(todd==5)
        printf("Friday");
    if(todd==6)
        printf("Saturday");
getch();
}

How to install mcrypt extension in xampp

Right from the PHP Docs: PHP 5.3 Windows binaries uses the static version of the MCrypt library, no DLL are needed.

http://php.net/manual/en/mcrypt.requirements.php

But if you really want to download it, just go to the mcrypt sourceforge page

http://sourceforge.net/projects/mcrypt/files/?source=navbar

Could not load file or assembly System.Net.Http, Version=4.0.0.0 with ASP.NET (MVC 4) Web API OData Prerelease

I faced the same error. When I installed Unity Framework for Dependency Injection the new references of the Http and HttpFormatter has been added in my configuration. So here are the steps I followed.

I ran following command on nuGet Package Manager Console: PM> Install-Package Microsoft.ASPNet.WebAPI -pre

And added physical reference to the dll with version 5.0

How to select the first, second, or third element with a given class name?

Yes, you can do this. For example, to style the td tags that make up the different columns of a table you could do something like this:

table.myClass tr > td:first-child /* First column */
{
  /* some style here */
}
table.myClass tr > td:first-child+td /* Second column */
{
  /* some style here */
}
table.myClass tr > td:first-child+td+td /* Third column */
{
  /* some style here */
}

Python argparse command line flags without arguments

Your script is right. But by default is of None type. So it considers true of any other value other than None is assigned to args.argument_name variable.

I would suggest you to add a action="store_true". This would make the True/False type of flag. If used its True else False.

import argparse
parser = argparse.ArgumentParser('parser-name')
parser.add_argument("-f","--flag",action="store_true",help="just a flag argument")

usage

$ python3 script.py -f

After parsing when checked with args.f it returns true,

args = parser.parse_args()
print(args.f)
>>>true

How to add colored border on cardview?

Start From the material design update, it support app:strokeColor and also app:strokeWidth. see more

to use material design update. add following code to build.gradle(:app)

dependencies {
    // ...
    implementation 'com.google.android.material:material:1.0.0'
    // ...
  }

and Change CardView to MaterialCardView

Tool to generate JSON schema from JSON data

For node.js > 6.0.0 there is also the json-schema-by-example module.

Selecting rows where remainder (modulo) is 1 after division by 2?

select * from table where value % 2 = 1 works fine in mysql.

Setting up connection string in ASP.NET to SQL SERVER

If you want to write connection string in Web.config then write under given sting

<connectionStrings>
  <add name="Conn" connectionString="Data Source=192.168.1.25;Initial Catalog=Login;Persist Security Info=True;User ID=sa;Password=example.com"
   providerName="System.Data.SqlClient" />
 </connectionStrings>

OR

you right in aspx.cs file like

SqlConnection conn = new SqlConnection("Data Source=12.16.1.25;Initial Catalog=Login;Persist Security Info=True;User ID=sa;Password=example.com");

Not able to launch IE browser using Selenium2 (Webdriver) with Java

  1. Go to IE->Tools->Internet Options.
  2. Go to Security tab.
  3. Either Enable/Disable the protected mode for all(Internet, Local Intranet, Trusted Sites & Restricted Sites.)

How to trigger button click in MVC 4

yo can try this code

@using (Html.BeginForm("SignUp", "Account", FormMethod.Post)){<fieldset>
    <legend>Sign Up</legend>
    <table>
        <tr>
            <td>
                @Html.Label("User Name")
            </td>
            <td>
                @Html.TextBoxFor(account => account.Username)
            </td>
        </tr>
        <tr>
            <td>
                @Html.Label("Email")
            </td>
            <td>
                @Html.TextBoxFor(account => account.Email)
            </td>
        </tr>
        <tr>
            <td>
                @Html.Label("Password")
            </td>
            <td>
                @Html.TextBoxFor(account => account.Password)
            </td>
        </tr>
        <tr>
            <td>
                @Html.Label("Confirm Password")
            </td>
            <td>
                @Html.Password("txtPassword")
            </td>
        </tr>
        <tr>
            <td>
                <input type="submit" name="btnSubmit" value="Sign Up" />
            </td>
        </tr>
    </table>
</fieldset>}

mysql count group by having

SELECT COUNT(*) 
FROM   (SELECT COUNT(*) 
        FROM   movies 
        GROUP  BY id 
        HAVING COUNT(genre) = 4) t

Testing whether a value is odd or even

Maybe this? if(ourNumber % 2 !== 0)

Pandas convert string to int

You need add parameter errors='coerce' to function to_numeric:

ID = pd.to_numeric(ID, errors='coerce')

If ID is column:

df.ID = pd.to_numeric(df.ID, errors='coerce')

but non numeric are converted to NaN, so all values are float.

For int need convert NaN to some value e.g. 0 and then cast to int:

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)

Sample:

df = pd.DataFrame({'ID':['4806105017087','4806105017087','CN414149']})
print (df)
              ID
0  4806105017087
1  4806105017087
2       CN414149

print (pd.to_numeric(df.ID, errors='coerce'))
0    4.806105e+12
1    4.806105e+12
2             NaN
Name: ID, dtype: float64

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)
print (df)
              ID
0  4806105017087
1  4806105017087
2              0

EDIT: If use pandas 0.25+ then is possible use integer_na:

df.ID = pd.to_numeric(df.ID, errors='coerce').astype('Int64')
print (df)
              ID
0  4806105017087
1  4806105017087
2            NaN

Find duplicates and delete all in notepad++

You could use

Click TextFX ? Click TextFX Tools ? Click Sort lines case insensitive (at column) Duplicates and blank lines have been removed and the data has been sorted alphabetically.

as indicated above. However, the way I did it because I need to replace the duplicates by blank lines and not just remove the lines, once sorted alphabetically:

REPLACE:
((^.*$)(\n))(?=\k<1>)

by

$3

This will convert:

Shorts
Shorts
Shorts
Shorts
Shorts
Shorts Two Pack
Shorts Two Pack
Signature Braces
Signature Braces
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers

to:

Shorts

Shorts Two Pack

Signature Braces










Signature Cotton Trousers

That's how I did it because I specifically needed those lines.

typesafe select onChange event using reactjs and typescript

Since upgrading my typings to react 0.14.43 (I'm not sure exactly when this was introduced), the React.FormEvent type is now generic and this removes the need for a cast.

import React = require('react');

interface ITestState {
    selectedValue: string;
}

export class Test extends React.Component<{}, ITestState> {

    constructor() {
        super();
        this.state = { selectedValue: "A" };
    }

    change(event: React.FormEvent<HTMLSelectElement>) {
        // No longer need to cast to any - hooray for react!
        var safeSearchTypeValue: string = event.currentTarget.value;

        console.log(safeSearchTypeValue); // in chrome => B

        this.setState({
            selectedValue: safeSearchTypeValue
        });
    }

    render() {
        return (
            <div>
                <label htmlFor="searchType">Safe</label>
                <select className="form-control" id="searchType" onChange={ e => this.change(e) } value={ this.state.selectedValue }>
                    <option value="A">A</option>
                    <option value="B">B</option>
                </select>
                <h1>{this.state.selectedValue}</h1>
            </div>
        );
    }
}

How do I restart nginx only after the configuration test was successful on Ubuntu?

At least on Debian the nginx startup script has a reload function which does:

reload)
  log_daemon_msg "Reloading $DESC configuration" "$NAME"
  test_nginx_config
  start-stop-daemon --stop --signal HUP --quiet --pidfile $PID \
   --oknodo --exec $DAEMON
  log_end_msg $?
  ;;

Seems like all you'd need to do is call service nginx reload instead of restart since it calls test_nginx_config.

Best way to clear a PHP array's values

This is powerful and tested unset($gradearray);//re-set the array

Exception from HRESULT: 0x800A03EC Error

This must be the world's most generic error message because I got it today on the following command using Excel Interop:

Excel.WorkbookConnection conn;
conn.ODBCConnection.Connection = "DSN=myserver;";

What fixed it was specifying ODBC in the connection string:

conn.ODBCConnection.Connection = "ODBC;DSN=myserver;";

On the off chance anyone else has this error, I hope it helps.

Fatal error: Call to undefined function mb_detect_encoding()

On Windows open the file php.ini and make this changes:

Remove the comment and point to the ext directory

; extension_dir = "./" -> extension_dir = "C:/Php/ext"

Remove the comment of this extensions

  • extension=php_mbstring.dll
  • extension=php_mysqli.dll

Restart apache service

httpd -k restart

The type java.lang.CharSequence cannot be resolved in package declaration

"Java 8 support for Eclipse Kepler SR2", and the new "JavaSE-1.8" execution environment showed up automatically.

Download this one:- Eclipse kepler SR2

and then follow this link:- Eclipse_Java_8_Support_For_Kepler

MYSQL into outfile "access denied" - but my user has "ALL" access.. and the folder is CHMOD 777

Try executing this SQL command:

> grant all privileges 
  on YOUR_DATABASE.* 
  to 'asdfsdf'@'localhost' 
  identified by 'your_password';
> flush privileges; 

It seems that you are having issues with connecting to the database and not writing to the folder you’re mentioning.

Also, make sure you have granted FILE to user 'asdfsdf'@'localhost'.

> GRANT FILE ON *.* TO 'asdfsdf'@'localhost';

AngularJS - get element attributes values

If you are using Angular2+ following code will help

You can use following syntax to get attribute value from html element

//to retrieve html element

const element = fixture.debugElement.nativeElement.querySelector('name of element'); // example a, h1, p

//get attribute value from that element

  const attributeValue = element.attributeName // like textContent/href

Close dialog on click (anywhere)

A bit late but this is a solution that worked for me. Perfect if your modal is inside the overlay tag. So, the modal will close when you click anywhere outside the modal content.

HTML

<div class="modal">  
  <div class="overlay">
    <div class="modal-content">
      <p>HELLO WORLD!</p>
    </div>
  </div>
</div>

JS

$(document).on("click", function(event) {
  if ($(event.target).has(".modal-content").length) {
    $(".modal").hide();
  }
});

Here is a working example

Create dynamic URLs in Flask with url_for()

It takes keyword arguments for the variables:

url_for('add', variable=foo)

What is &#39; and why does Google search replace it with apostrophe?

It's HTML character references for encoding a character by its decimal code point

Look at the ASCII table here and you'll see that 39 (hex 0x27, octal 47) is the code for apostrophe

ASCII table

How do you declare string constants in C?

If you want a "const string" like your question says, I would really go for the version you stated in your question:

/* first version */
const char *HELLO2 = "Howdy";

Particularly, I would avoid:

/* second version */
const char HELLO2[] = "Howdy";

Reason: The problem with second version is that compiler will make a copy of the entire string "Howdy", PLUS that string is modifiable (so not really const).

On the other hand, first version is a const string accessible by const pointer HELLO2, and there is no way anybody can modify it.

How to Select Columns in Editors (Atom,Notepad++, Kate, VIM, Sublime, Textpad,etc) and IDEs (NetBeans, IntelliJ IDEA, Eclipse, Visual Studio, etc)

In MCEdit toggle Shift+F3 (ie F13) or F9->Edit ->Mark columns.

P.S. In this case, MCEdit is an editor written for the Midnight Commander.

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found

The SSL is not properly configured. Those trustAnchor errors usually mean that the trust store cannot be found. Check your configuration and make sure you are actually pointing to the trust store and that it is in place.

Make sure you have a -Djavax.net.ssl.trustStore system property set and then check that the path actually leads to the trust store.

You can also enable SSL debugging by setting this system property -Djavax.net.debug=all. Within the debug output you will notice it states that it cannot find the trust store.

Java - How to find the redirected url of a url?

public static URL getFinalURL(URL url) {
    try {
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setInstanceFollowRedirects(false);
        con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36");
        con.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
        con.addRequestProperty("Referer", "https://www.google.com/");
        con.connect();
        //con.getInputStream();
        int resCode = con.getResponseCode();
        if (resCode == HttpURLConnection.HTTP_SEE_OTHER
                || resCode == HttpURLConnection.HTTP_MOVED_PERM
                || resCode == HttpURLConnection.HTTP_MOVED_TEMP) {
            String Location = con.getHeaderField("Location");
            if (Location.startsWith("/")) {
                Location = url.getProtocol() + "://" + url.getHost() + Location;
            }
            return getFinalURL(new URL(Location));
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    return url;
}

To get "User-Agent" and "Referer" by yourself, just go to developer mode of one of your installed browser (E.g. press F12 on Google Chrome). Then go to tab 'Network' and then click on one of the requests. You should see it's details. Just press 'Headers' sub tab (the image below) request details

How to detect internet speed in JavaScript?

Even though this is old and answered, i´d like to share the solution i made out of it 2020

it comes with the flexibility to run at anytime and run a callback if greater and or smaller the specified mbps

you can start the test anywhere after you included the testConnectionSpeed Object by running the testConnectionSpeed.run(mbps, morefunction, lessfunction)

for example:

_x000D_
_x000D_
var testConnectionSpeed = {
  imageAddr : "https://upload.wikimedia.org/wikipedia/commons/a/a6/Brandenburger_Tor_abends.jpg", // this is just an example, you rather want an image hosted on your server
  downloadSize : 2707459, // this must match with the image above
  run:function(mbps_max,cb_gt,cb_lt){
    testConnectionSpeed.mbps_max = parseFloat(mbps_max) ? parseFloat(mbps_max) : 0;
    testConnectionSpeed.cb_gt = cb_gt;
    testConnectionSpeed.cb_lt = cb_lt;
    testConnectionSpeed.InitiateSpeedDetection();
  },
  InitiateSpeedDetection: function() {
    window.setTimeout(testConnectionSpeed.MeasureConnectionSpeed, 1);
  },
  result:function(){
    var duration = (endTime - startTime) / 1000;
    var bitsLoaded = testConnectionSpeed.downloadSize * 8;
    var speedBps = (bitsLoaded / duration).toFixed(2);
    var speedKbps = (speedBps / 1024).toFixed(2);
    var speedMbps = (speedKbps / 1024).toFixed(2);
    if(speedMbps >= (testConnectionSpeed.max_mbps ? testConnectionSpeed.max_mbps : 1) ){
      testConnectionSpeed.cb_gt ? testConnectionSpeed.cb_gt(speedMbps) : false;
    }else {
      testConnectionSpeed.cb_lt ? testConnectionSpeed.cb_lt(speedMbps) : false;
    }
  },
  MeasureConnectionSpeed:function() {
    var download = new Image();
    download.onload = function () {
        endTime = (new Date()).getTime();
        testConnectionSpeed.result();
    }
    startTime = (new Date()).getTime();
    var cacheBuster = "?nnn=" + startTime;
    download.src = testConnectionSpeed.imageAddr + cacheBuster;
  }
}




// start test immediatly, you could also call this on any event or whenever you want
testConnectionSpeed.run(1.5, function(mbps){console.log(">= 1.5Mbps ("+mbps+"Mbps)")}, function(mbps){console.log("< 1.5Mbps("+mbps+"Mbps)")} )
_x000D_
_x000D_
_x000D_

I used this successfuly to load lowres media for slow internet connections. You have to play around a bit because on the one hand, the larger the image, the more reasonable the test, on the other hand the test will take way much longer for slow connection and in my case I especially did not want slow connection users to load lots of MBs.

Support for "border-radius" in IE

SOLVED - not rendering border radius correctly in IE 10 and 11

For those not getting the -ms-border-radius: or the border-radius: to work in IE 10,11 And it renders all square then follow these steps:

  1. Click on the gear wheel at the top right of the IE browser
  2. Click on Compatibility view settings
  3. Now uncheck the 2 boxes that are checked by default.

Ensure that the boxes are unchecked as in pic

Equivalent of Oracle's RowID in SQL Server

I took this example from MS SQL example and you can see the @ID can be interchanged with integer or varchar or whatever. This was the same solution I was looking for, so I am sharing it. Enjoy!!

-- UPDATE statement with CTE references that are correctly matched.
DECLARE @x TABLE (ID int, Stad int, Value int, ison bit);
INSERT @x VALUES (1, 0, 10, 0), (2, 1, 20, 0), (6, 0, 40, 0), (4, 1, 50, 0), (5, 3, 60, 0), (9, 6, 20, 0), (7, 5, 10, 0), (8, 8, 220, 0);
DECLARE @Error int;
DECLARE @id int;

WITH cte AS (SELECT top 1 * FROM @x WHERE Stad=6)
UPDATE x -- cte is referenced by the alias.
SET ison=1, @id=x.ID
FROM cte AS x

SELECT *, @id as 'random' from @x
GO

Amazon products API - Looking for basic overview and information

Straight from the horse's moutyh: Summary of Product Advertising API Operations which has the following categories:

  • Find Items
  • Find Out More About Specific Items
  • Shopping Cart
  • Customer Content
  • Seller Information
  • Other Operations

No newline at end of file

It's not just bad style, it can lead to unexpected behavior when using other tools on the file.

Here is test.txt:

first line
second line

There is no newline character on the last line. Let's see how many lines are in the file:

$ wc -l test.txt
1 test.txt

Maybe that's what you want, but in most cases you'd probably expect there to be 2 lines in the file.

Also, if you wanted to combine files it may not behave the way you'd expect:

$ cat test.txt test.txt
first line
second linefirst line
second line

Finally, it would make your diffs slightly more noisy if you were to add a new line. If you added a third line, it would show an edit to the second line as well as the new addition.

ajax jquery simple get request

var settings = {
        "async": true,
        "crossDomain": true,
        "url": "<your URL Here>",
        "method": "GET",
        "headers": {
            "content-type": "application/x-www-form-urlencoded"
        },
        "data": {
            "username": "[email protected]",
            "password": "12345678"
        }
    }

    $.ajax(settings).done(function (response) {
        console.log(response);
    });

TypeError: unhashable type: 'dict'

You're trying to use a dict as a key to another dict or in a set. That does not work because the keys have to be hashable. As a general rule, only immutable objects (strings, integers, floats, frozensets, tuples of immutables) are hashable (though exceptions are possible). So this does not work:

>>> dict_key = {"a": "b"}
>>> some_dict[dict_key] = True
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'

To use a dict as a key you need to turn it into something that may be hashed first. If the dict you wish to use as key consists of only immutable values, you can create a hashable representation of it like this:

>>> key = frozenset(dict_key.items())

Now you may use key as a key in a dict or set:

>>> some_dict[key] = True
>>> some_dict
{frozenset([('a', 'b')]): True}

Of course you need to repeat the exercise whenever you want to look up something using a dict:

>>> some_dict[dict_key]                     # Doesn't work
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
>>> some_dict[frozenset(dict_key.items())]  # Works
True

If the dict you wish to use as key has values that are themselves dicts and/or lists, you need to recursively "freeze" the prospective key. Here's a starting point:

def freeze(d):
    if isinstance(d, dict):
        return frozenset((key, freeze(value)) for key, value in d.items())
    elif isinstance(d, list):
        return tuple(freeze(value) for value in d)
    return d

escaping question mark in regex javascript

Whenever you have a known pattern (i.e. you do not use a variable to build a RegExp), use literal regex notation where you only need to use single backslashes to escape special regex metacharacters:

var re = /I like your Apartment\. Could we schedule a viewing\?/g;
                               ^^                            ^^

Whenever you need to build a RegExp dynamically, use RegExp constructor notation where you MUST double backslashes for them to denote a literal backslash:

var questionmark_block = "\\?"; // A literal ?
var initial_subpattern = "I like your Apartment\\. Could we schedule a viewing"; // Note the dot must also be escaped to match a literal dot
var re = new RegExp(initial_subpattern + questionmark_block, "g");

And if you use the String.raw string literal you may use \ as is (see an example of using a template string literal where you may put variables into the regex pattern):

_x000D_
_x000D_
const questionmark_block = String.raw`\?`; // A literal ?
const initial_subpattern = "I like your Apartment\\. Could we schedule a viewing";
const re = new RegExp(`${initial_subpattern}${questionmark_block}`, 'g'); // Building pattern from two variables
console.log(re); // => /I like your Apartment\. Could we schedule a viewing\?/g
_x000D_
_x000D_
_x000D_

A must-read: RegExp: Description at MDN.

What does the 'export' command do?

In simple terms, environment variables are set when you open a new shell session. At any time if you change any of the variable values, the shell has no way of picking that change. that means the changes you made become effective in new shell sessions. The export command, on the other hand, provides the ability to update the current shell session about the change you made to the exported variable. You don't have to wait until new shell session to use the value of the variable you changed.

Difference between Inheritance and Composition

Inheritance brings out IS-A relation. Composition brings out HAS-A relation. Strategy pattern explain that Composition should be used in cases where there are families of algorithms defining a particular behaviour.
Classic example being of a duck class which implements a flying behaviour.

public interface Flyable{
 public void fly();
}

public class Duck {
 Flyable fly;

 public Duck(){
  fly = new BackwardFlying();
 }
}

Thus we can have multiple classes which implement flying eg:

public class BackwardFlying implements Flyable{
  public void fly(){
    Systemout.println("Flies backward ");
  }
}
public class FastFlying implements Flyable{
  public void fly(){
    Systemout.println("Flies 100 miles/sec");
  }
}

Had it been for inheritance, we would have two different classes of birds which implement the fly function over and over again. So inheritance and composition are completely different.

No server in windows>preferences

If above answers did not work for you then just click this link https://www.eclipse.org/downloads/packages/release/2020-06/r/eclipse-ide-enterprise-java-developers download according to your OS. And after downloading and extracting the ZIP open the extract folder and click on Eclipse application icon. enter image description here

Then just enter your workspace and get started. Now you will be able to see the servers option in Window->Show View, like this:

enter image description here

Calling async method on button click

This is what's killing you:

task.Wait();

That's blocking the UI thread until the task has completed - but the task is an async method which is going to try to get back to the UI thread after it "pauses" and awaits an async result. It can't do that, because you're blocking the UI thread...

There's nothing in your code which really looks like it needs to be on the UI thread anyway, but assuming you really do want it there, you should use:

private async void Button_Click(object sender, RoutedEventArgs 
{
    Task<List<MyObject>> task = GetResponse<MyObject>("my url");
    var items = await task;
    // Presumably use items here
}

Or just:

private async void Button_Click(object sender, RoutedEventArgs 
{
    var items = await GetResponse<MyObject>("my url");
    // Presumably use items here
}

Now instead of blocking until the task has completed, the Button_Click method will return after scheduling a continuation to fire when the task has completed. (That's how async/await works, basically.)

Note that I would also rename GetResponse to GetResponseAsync for clarity.

Encoding as Base64 in Java

On Android, use the static methods of the android.util.Base64 utility class. The referenced documentation says that the Base64 class was added in API level 8 (Android 2.2 (Froyo)).

import android.util.Base64;

byte[] encodedBytes = Base64.encode("Test".getBytes());
Log.d("tag", "encodedBytes " + new String(encodedBytes));

byte[] decodedBytes = Base64.decode(encodedBytes);
Log.d("tag", "decodedBytes " + new String(decodedBytes));

iPhone - Get Position of UIView within entire UIWindow

Swift 5+:

let globalPoint = aView.superview?.convert(aView.frame.origin, to: nil)

How do I read input character-by-character in Java?

In java 5 new feature added that is Scanner method who gives the chance to read input character by character in java.

for instance; for use Scanner method import java.util.Scanner; after in main method:define

Scanner myScanner = new Scanner(System.in); //for read character

char anything=myScanner.findInLine(".").charAt(0);

you anything store single character, if you want more read more character declare more object like anything1,anything2... more example for your answer please check in your hand(copy/paste)

     import java.util.Scanner;
     class ReverseWord  {

    public static void main(String args[]){
    Scanner myScanner=new Scanner(System.in);
    char c1,c2,c3,c4;

    c1 = myScanner.findInLine(".").charAt(0);
        c2 = myScanner.findInLine(".").charAt(0);
    c3 = myScanner.findInLine(".").charAt(0);
    c4 = myScanner.findInLine(".").charAt(0);

    System.out.print(c4);
    System.out.print(c3);
    System.out.print(c2);
    System.out.print(c1);
    System.out.println();

   }
  }

Converting string into datetime

I personally like the solution using the parser module, which is the second Answer to this question and is beautiful, as you don't have to construct any string literals to get it working. BUT, one downside is that it is 90% slower than the accepted answer with strptime.

from dateutil import parser
from datetime import datetime
import timeit

def dt():
    dt = parser.parse("Jun 1 2005  1:33PM")
def strptime():
    datetime_object = datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')

print(timeit.timeit(stmt=dt, number=10**5))
print(timeit.timeit(stmt=strptime, number=10**5))
>10.70296801342902
>1.3627995655316933

As long as you are not doing this a million times over and over again, I still think the parser method is more convenient and will handle most of the time formats automatically.

Replace only some groups with Regex

You can do this using lookahead and lookbehind:

var pattern = @"(?<=-)\d+(?=-)";
var replaced = Regex.Replace(text, pattern, "AA"); 

Calling an API from SQL Server stored procedure

I'd recommend using a CLR user defined function, if you already know how to program in C#, then the code would be;

using System.Data.SqlTypes;
using System.Net;

public partial class UserDefinedFunctions
{
 [Microsoft.SqlServer.Server.SqlFunction]
 public static SqlString http(SqlString url)
 {
  var wc = new WebClient();
  var html = wc.DownloadString(url.Value);
  return new SqlString (html);
 }
}

And here's installation instructions; https://blog.dotnetframework.org/2019/09/17/make-a-http-request-from-sqlserver-using-a-clr-udf/

Null vs. False vs. 0 in PHP

I think bad developers find all different uses of null/0/false in there code.

For example, one of the most common mistakes developers make is to return error code in the form of data with a function.

// On error GetChar returns -1
int GetChar()

This is an example of a sugar interface. This is exsplained in the book "Debuging the software development proccess" and also in another book "writing correct code".

The problem with this, is the implication or assumptions made on the char type. On some compilers the char type can be non-signed. So even though you return a -1 the compiler can return 1 instead. These kind of compiler assumptions in C++ or C are hard to spot.

Instead, the best way is not to mix error code with your data. So the following function.

char GetChar()

now becomes

// On success return 1
// on failure return 0
bool GetChar(int &char)

This means no matter how young the developer is in your development shop, he or she will never get this wrong. Though this is not talking about redudancy or dependies in code.

So in general, swapping bool as the first class type in the language is okay and i think joel spoke about it with his recent postcast. But try not to use mix and match bools with your data in your routines and you should be perfectly fine.

What are Makefile.am and Makefile.in?

DEVELOPER runs autoconf and automake:

  1. autoconf -- creates shippable configure script
    (which the installer will later run to make the Makefile)
  1. automake - creates shippable Makefile.in data file
    (which configure will later read to make the Makefile)

INSTALLER runs configure, make and sudo make install:

./configure       # Creates  Makefile        (from     Makefile.in).  
make              # Creates  the application (from the Makefile just created).  

sudo make install # Installs the application 
                  #   Often, by default its files are installed into /usr/local


INPUT/OUTPUT MAP

Notation below is roughly: inputs --> programs --> outputs

DEVELOPER runs these:

configure.ac -> autoconf -> configure (script) --- (*.ac = autoconf)
configure.in --> autoconf -> configure (script) --- (configure.in depreciated. Use configure.ac)

Makefile.am -> automake -> Makefile.in ----------- (*.am = automake)

INSTALLER runs these:

Makefile.in -> configure -> Makefile (*.in = input file)

Makefile -> make ----------> (puts new software in your downloads or temporary directory)
Makefile -> make install -> (puts new software in system directories)


"autoconf is an extensible package of M4 macros that produce shell scripts to automatically configure software source code packages. These scripts can adapt the packages to many kinds of UNIX-like systems without manual user intervention. Autoconf creates a configuration script for a package from a template file that lists the operating system features that the package can use, in the form of M4 macro calls."

"automake is a tool for automatically generating Makefile.in files compliant with the GNU Coding Standards. Automake requires the use of Autoconf."

Manuals:

Free online tutorials:


Example:

The main configure.ac used to build LibreOffice is over 12k lines of code, (but there are also 57 other configure.ac files in subfolders.)

From this my generated configure is over 41k lines of code.

And while the Makefile.in and Makefile are both only 493 lines of code. (But, there are also 768 more Makefile.in's in subfolders.)

allowing only alphabets in text box using java script

You can try:

 function onlyAlphabets(e, t) {
        return (e.charCode > 64 && e.charCode < 91) || (e.charCode > 96 && e.charCode < 123) || e.charCode == 32;   
    }

How to convert a string of bytes into an int?

In Python 3.2 and later, use

>>> int.from_bytes(b'y\xcc\xa6\xbb', byteorder='big')
2043455163

or

>>> int.from_bytes(b'y\xcc\xa6\xbb', byteorder='little')
3148270713

according to the endianness of your byte-string.

This also works for bytestring-integers of arbitrary length, and for two's-complement signed integers by specifying signed=True. See the docs for from_bytes.

SQL Server Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >=

The select statement in the cost part of your select is returning more than one value. You need to add more where clauses, or use an aggregation.

what is Array.any? for javascript

I believe this to be the cleanest and readable option:

var empty = [];
empty.some(x => x); //returns false

Why is a ConcurrentModificationException thrown and how to debug it

This is not a synchronization problem. This will occur if the underlying collection that is being iterated over is modified by anything other than the Iterator itself.

Iterator it = map.entrySet().iterator();
while (it.hasNext())
{
   Entry item = it.next();
   map.remove(item.getKey());
}

This will throw a ConcurrentModificationException when the it.hasNext() is called the second time.

The correct approach would be

   Iterator it = map.entrySet().iterator();
   while (it.hasNext())
   {
      Entry item = it.next();
      it.remove();
   }

Assuming this iterator supports the remove() operation.

Angular2 Exception: Can't bind to 'routerLink' since it isn't a known native property

In general, whenever you get an error like Can't bind to 'xxx' since it isn't a known native property, the most likely cause is forgetting to specify a component or a directive (or a constant that contains the component or the directive) in the directives metadata array. Such is the case here.

Since you did not specify RouterLink or the constant ROUTER_DIRECTIVES – which contains the following:

export const ROUTER_DIRECTIVES = [RouterOutlet, RouterLink, RouterLinkWithHref, 
  RouterLinkActive];

– in the directives array, then when Angular parses

<a [routerLink]="['RoutingTest']">Routing Test</a>

it doesn't know about the RouterLink directive (which uses attribute selector routerLink). Since Angular does know what the a element is, it assumes that [routerLink]="..." is a property binding for the a element. But it then discovers that routerLink is not a native property of a elements, hence it throws the exception about the unknown property.


I've never really liked the ambiguity of the syntax. I.e., consider

<something [whatIsThis]="..." ...>

Just by looking at the HTML we can't tell if whatIsThis is

  • a native property of something
  • a directive's attribute selector
  • a input property of something

We have to know which directives: [...] are specified in the component's/directive's metadata in order to mentally interpret the HTML. And when we forget to put something into the directives array, I feel this ambiguity makes it a bit harder to debug.

Correct way to try/except using Python requests module?

Exception object also contains original response e.response, that could be useful if need to see error body in response from the server. For example:

try:
    r = requests.post('somerestapi.com/post-here', data={'birthday': '9/9/3999'})
    r.raise_for_status()
except requests.exceptions.HTTPError as e:
    print (e.response.text)

How to determine whether a year is a leap year?

As a one-liner function:

def is_leap_year(year):
    """Determine whether a year is a leap year."""

    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

It's similar to the Mark's answer, but short circuits at the first test (note the parenthesis).

Alternatively, you can use the standard library's calendar.isleap, which has exactly the same implementation:

from calendar import isleap
print(isleap(1900))

How to send a html email with the bash command "sendmail"?

To follow up on the previous answer using mail :

Often times one's html output is interpreted by the client mailer, which may not format things using a fixed-width font. Thus your nicely formatted ascii alignment gets all messed up. To send old-fashioned fixed-width the way the God intended, try this:

{ echo -e "<pre>"
echo "Descriptive text here."
shell_command_1_here
another_shell_command
cat <<EOF

This is the ending text.
</pre><br>
</div>
EOF
} | mail -s "$(echo -e 'Your subject.\nContent-Type: text/html')" [email protected]

You don't necessarily need the "Descriptive text here." line, but I have found that sometimes the first line may, depending on its contents, cause the mail program to interpret the rest of the file in ways you did not intend. Try the script with simple descriptive text first, before fine tuning the output in the way that you want.

How do I trap ctrl-c (SIGINT) in a C# console app

Console.TreatControlCAsInput = true; has worked for me.

Docker Error bind: address already in use

The one that was using the port 8888 was Jupiter and I had to change the configuration file of Jupiter notebook to run on another port.

to list who is using that specific port. sudo lsof -i -P -n | grep 9

You can specify the port you want Jupyter to run uncommenting/editing the following line in ~/.jupyter/jupyter_notebook_config.py:

c.NotebookApp.port = 9999

In case you don't have a jupyter_notebook_config.py try running jupyter notebook --generate-config. See this for further details on Jupyter configuration.

How to import a CSS file in a React Component

  1. Install Style Loader and CSS Loader:

    npm install --save-dev style-loader
    npm install --save-dev css-loader
    
  2. Configure webpack

    module: {
            loaders: [
                {
                    test: /\.css$/,
                    loader: 'style-loader'
                }, {
                    test: /\.css$/,
                    loader: 'css-loader',
                    query: {
                        modules: true,
                        localIdentName: '[name]__[local]___[hash:base64:5]'
                    }
                }
            ]
        }
    

How can I check file size in Python?

You need the st_size property of the object returned by os.stat. You can get it by either using pathlib (Python 3.4+):

>>> from pathlib import Path
>>> Path('somefile.txt').stat()
os.stat_result(st_mode=33188, st_ino=6419862, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=1564, st_atime=1584299303, st_mtime=1584299400, st_ctime=1584299400)
>>> Path('somefile.txt').stat().st_size
1564

or using os.stat:

>>> import os
>>> os.stat('somefile.txt')
os.stat_result(st_mode=33188, st_ino=6419862, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=1564, st_atime=1584299303, st_mtime=1584299400, st_ctime=1584299400)
>>> os.stat('somefile.txt').st_size
1564

Output is in bytes.

Can I use library that used android support with Androidx projects.

API 29.+ usage AndroidX libraries. If you are using API 29.+, then you cannot remove these. If you want to remove AndroidX, then you need to remove the entire 29.+ API from your SDK:

SDK Settings

This will work fine.

Is Java RegEx case-insensitive?

Yes, case insensitivity can be enabled and disabled at will in Java regex.

It looks like you want something like this:

    System.out.println(
        "Have a meRry MErrY Christmas ho Ho hO"
            .replaceAll("(?i)\\b(\\w+)(\\s+\\1)+\\b", "$1")
    );
    // Have a meRry Christmas ho

Note that the embedded Pattern.CASE_INSENSITIVE flag is (?i) not \?i. Note also that one superfluous \b has been removed from the pattern.

The (?i) is placed at the beginning of the pattern to enable case-insensitivity. In this particular case, it is not overridden later in the pattern, so in effect the whole pattern is case-insensitive.

It is worth noting that in fact you can limit case-insensitivity to only parts of the whole pattern. Thus, the question of where to put it really depends on the specification (although for this particular problem it doesn't matter since \w is case-insensitive.

To demonstrate, here's a similar example of collapsing runs of letters like "AaAaaA" to just "A".

    System.out.println(
        "AaAaaA eeEeeE IiiIi OoooOo uuUuUuu"
            .replaceAll("(?i)\\b([A-Z])\\1+\\b", "$1")
    ); // A e I O u

Now suppose that we specify that the run should only be collapsed only if it starts with an uppercase letter. Then we must put the (?i) in the appropriate place:

    System.out.println(
        "AaAaaA eeEeeE IiiIi OoooOo uuUuUuu"
            .replaceAll("\\b([A-Z])(?i)\\1+\\b", "$1")
    ); // A eeEeeE I O uuUuUuu

More generally, you can enable and disable any flag within the pattern as you wish.

See also

Related questions

"Access is denied" JavaScript error when trying to access the document object of a programmatically-created <iframe> (IE-only)

IE works with iframe like all the other browsers (at least for main functions). You just have to keep a set of rules:

  • before you load any javascript in the iframe (that part of js which needs to know about the iframe parent), ensure that the parent has document.domain changed.
  • when all iframe resources are loaded, change document.domain to be the same as the one defined in parent. (You need to do this later because setting domain will cause the iframe resource's request to fail)

  • now you can make a reference for parent window: var winn = window.parent

  • now you can make a reference to parent HTML, in order to manipulate it: var parentContent = $('html', winn.document)
  • at this point you should have access to IE parent window/document and you can change it as you wont

How can I find a file/directory that could be anywhere on linux command line?

I hope this comment will help you to find out your local & server file path using terminal

 find "$(cd ..; pwd)" -name "filename"

Or just you want to see your Current location then run

 pwd "filename"

Java and SQLite

The wiki lists some more wrappers:

Setting POST variable without using form

you can do it using ajax or by sending http headers+content like:

POST /xyz.php HTTP/1.1
Host: www.mysite.com
User-Agent: Mozilla/4.0
Content-Length: 27
Content-Type: application/x-www-form-urlencoded

userid=joe&password=guessme

JavaScript: Collision detection

This is a lightweight solution I've come across -

function E() { // Check collision
    S = X - x;
    D = Y - y;
    F = w + W;
    return (S * S + D * D <= F * F)
}

The big and small variables are of two objects, (x coordinate, y coordinate, and w width)

From here.

Put byte array to JSON and vice versa

The typical way to send binary in json is to base64 encode it.

Java provides different ways to Base64 encode and decode a byte[]. One of these is DatatypeConverter.

Very simply

byte[] originalBytes = new byte[] { 1, 2, 3, 4, 5};
String base64Encoded = DatatypeConverter.printBase64Binary(originalBytes);
byte[] base64Decoded = DatatypeConverter.parseBase64Binary(base64Encoded);

You'll have to make this conversion depending on the json parser/generator library you use.

SSH Key: “Permissions 0644 for 'id_rsa.pub' are too open.” on mac

Just run below to your pem's

sudo chmod 600 /path/to/my/key.pem 

PHP Get Highest Value from Array

Here a solution inside an exercise:

function high($sentence)
{
    $alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'ñ', 'o', 'p', 'q', 'r', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
    $alphabet = array_flip($alphabet);

    $words = explode(" ", $sentence);

    foreach ($words as $word) {
        $letters = str_split($word);
        $points = 0;
        foreach ($letters as $letter)
            $points += $alphabet[$letter];
        $score[$word] = $points;
    }

    $value = max($score);
    $key = array_search($value, $score);

    return $key;
}

echo high("what time are we climbing up the volcano");

How can I calculate the time between 2 Dates in typescript

This is how it should be done in typescript:

(new Date()).valueOf() - (new Date("2013-02-20T12:01:04.753Z")).valueOf()

Better readability:

      var eventStartTime = new Date(event.startTime);
      var eventEndTime = new Date(event.endTime);
      var duration = eventEndTime.valueOf() - eventStartTime.valueOf();

invalid types 'int[int]' for array subscript

You are subscripting a three-dimensional array myArray[10][10][10] four times myArray[i][t][x][y]. You will probably need to add another dimension to your array. Also consider a container like Boost.MultiArray, though that's probably over your head at this point.

html form - make inputs appear on the same line

Wrap your multiple form elements in a div with a class that uses

display: table 

Inside that div, wrap each label and input in divs with a class that uses

display: table-cell

Stay away from floats!

Reference

How to configure the web.config to allow requests of any length

Something else to check: if your site is using MVC, this can happen if you added [Authorize] to your login controller class. It can't access the login method because it's not authorized so it redirects to the login method --> boom.

delete map[key] in go?

Copied from Go 1 release notes

In the old language, to delete the entry with key k from the map represented by m, one wrote the statement,

m[k] = value, false

This syntax was a peculiar special case, the only two-to-one assignment. It required passing a value (usually ignored) that is evaluated but discarded, plus a boolean that was nearly always the constant false. It did the job but was odd and a point of contention.

In Go 1, that syntax has gone; instead there is a new built-in function, delete. The call

delete(m, k)

will delete the map entry retrieved by the expression m[k]. There is no return value. Deleting a non-existent entry is a no-op.

Updating: Running go fix will convert expressions of the form m[k] = value, false into delete(m, k) when it is clear that the ignored value can be safely discarded from the program and false refers to the predefined boolean constant. The fix tool will flag other uses of the syntax for inspection by the programmer.

node.js hash string?

Here you can benchmark all supported hashes on your hardware, supported by your version of node.js. Some are cryptographic, and some is just for a checksum. Its calculating "Hello World" 1 million times for each algorithm. It may take around 1-15 seconds for each algorithm (Tested on the Standard Google Computing Engine with Node.js 4.2.2).

for(var i1=0;i1<crypto.getHashes().length;i1++){
  var Algh=crypto.getHashes()[i1];
  console.time(Algh);
  for(var i2=0;i2<1000000;i2++){
    crypto.createHash(Algh).update("Hello World").digest("hex");
  }
  console.timeEnd(Algh);  
}

Result:
DSA: 1992ms
DSA-SHA: 1960ms
DSA-SHA1: 2062ms
DSA-SHA1-old: 2124ms
RSA-MD4: 1893ms
RSA-MD5: 1982ms
RSA-MDC2: 2797ms
RSA-RIPEMD160: 2101ms
RSA-SHA: 1948ms
RSA-SHA1: 1908ms
RSA-SHA1-2: 2042ms
RSA-SHA224: 2176ms
RSA-SHA256: 2158ms
RSA-SHA384: 2290ms
RSA-SHA512: 2357ms
dsaEncryption: 1936ms
dsaWithSHA: 1910ms
dsaWithSHA1: 1926ms
dss1: 1928ms
ecdsa-with-SHA1: 1880ms
md4: 1833ms
md4WithRSAEncryption: 1925ms
md5: 1863ms
md5WithRSAEncryption: 1923ms
mdc2: 2729ms
mdc2WithRSA: 2890ms
ripemd: 2101ms
ripemd160: 2153ms
ripemd160WithRSA: 2210ms
rmd160: 2146ms
sha: 1929ms
sha1: 1880ms
sha1WithRSAEncryption: 1957ms
sha224: 2121ms
sha224WithRSAEncryption: 2290ms
sha256: 2134ms
sha256WithRSAEncryption: 2190ms
sha384: 2181ms
sha384WithRSAEncryption: 2343ms
sha512: 2371ms
sha512WithRSAEncryption: 2434ms
shaWithRSAEncryption: 1966ms
ssl2-md5: 1853ms
ssl3-md5: 1868ms
ssl3-sha1: 1971ms
whirlpool: 2578ms

What is the difference between single-quoted and double-quoted strings in PHP?

In PHP, single quote text is considered as string value and double quote text will parse the variables by replacing and processing their value.

$test = "variable";
echo "Hello Mr $test"; // the output would be: Hello Mr variable
echo 'Hello Mr $test'; // the output would be: Hello Mr $test

Here, double quote parse the value and single quote is considered as string value (without parsing the $test variable.)

How do you properly use WideCharToMultiByte

Here's a couple of functions (based on Brian Bondy's example) that use WideCharToMultiByte and MultiByteToWideChar to convert between std::wstring and std::string using utf8 to not lose any data.

// Convert a wide Unicode string to an UTF8 string
std::string utf8_encode(const std::wstring &wstr)
{
    if( wstr.empty() ) return std::string();
    int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);
    std::string strTo( size_needed, 0 );
    WideCharToMultiByte                  (CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL);
    return strTo;
}

// Convert an UTF8 string to a wide Unicode String
std::wstring utf8_decode(const std::string &str)
{
    if( str.empty() ) return std::wstring();
    int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);
    std::wstring wstrTo( size_needed, 0 );
    MultiByteToWideChar                  (CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed);
    return wstrTo;
}

Android ImageView Fixing Image Size

Try this

ImageView img
    Bitmap bmp;
    int width=100;
    int height=100;
    img=(ImageView)findViewById(R.id.imgView);
    bmp=BitmapFactory.decodeResource(getResources(),R.drawable.image);//image is your image                                                            
    bmp=Bitmap.createScaledBitmap(bmp, width,height, true);
    img.setImageBitmap(bmp);

Or If you want to load complete image size in memory then you can use

<ImageView
    android:id="@+id/img"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:src="@drawable/image" 
    android:scaleType="fitXY"/>

Readably print out a python dict() sorted by key

You could transform this dict a little to ensure that (as dicts aren't kept sorted internally), e.g.

pprint([(key, mydict[key]) for key in sorted(mydict.keys())])

Get the last inserted row ID (with SQL statement)

You can use:

SELECT IDENT_CURRENT('tablename')

to access the latest identity for a perticular table.

e.g. Considering following code:

INSERT INTO dbo.MyTable(columns....) VALUES(..........)

INSERT INTO dbo.YourTable(columns....) VALUES(..........)

SELECT IDENT_CURRENT('MyTable')

SELECT IDENT_CURRENT('YourTable')

This would yield to correct value for corresponding tables.

It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value.

IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.

CSS content generation before or after 'input' elements

This is not due to input tags not having any content per-se, but that their content is outside the scope of CSS.

input elements are a special type called replaced elements, these do not support :pseudo selectors like :before and :after.

In CSS, a replaced element is an element whose representation is outside the scope of CSS. These are kind of external objects whose representation is independent of the CSS. Typical replaced elements are <img>, <object>, <video> or form elements like <textarea> and <input>. Some elements, like <audio> or <canvas> are replaced elements only in specific cases. Objects inserted using the CSS content properties are anonymous replaced elements.

Note that this is even referred to in the spec:

This specification does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML).

And more explicitly:

Replaced elements do not have ::before and ::after pseudo-elements

Flushing footer to bottom of the page, twitter bootstrap

HenryW's answer is good, though I needed a few tweaks to get it working how I wanted. In particular the following also handles:

  • Avoiding the "jumpiness" on page load by first marking invisible and setting visible in javascript
  • Dealing with browser resizes gracefully
  • Additionally setting the footer back up the page if the browser gets smaller and the footer becomes bigger than the page
  • Height function tweaks

Here's what worked for me with those tweaks:

HTML:

<div id="footer" class="invisible">My sweet footer</div>

CSS:

#footer {
    padding-bottom: 30px;
}

JavaScript:

function setFooterStyle() {
    var docHeight = $(window).height();
    var footerHeight = $('#footer').outerHeight();
    var footerTop = $('#footer').position().top + footerHeight;
    if (footerTop < docHeight) {
        $('#footer').css('margin-top', (docHeight - footerTop) + 'px');
    } else {
        $('#footer').css('margin-top', '');
    }
    $('#footer').removeClass('invisible');
}
$(document).ready(function() {
    setFooterStyle();
    window.onresize = setFooterStyle;
});

Tab Escape Character?

Easy one! "\t"

Edit: In fact, here's something official: Escape Sequences

Bootstrap select dropdown list placeholder

<option value="" defaultValue disabled> Something </option>

you can replace defaultValue with selected but that would give warning.

printf and long double

In addition to the wrong modifier, which port of gcc to Windows? mingw uses the Microsoft C library and I seem to remember that this library has no support for 80bits long double (microsoft C compiler use 64 bits long double for various reasons).

HTML: How to make a submit button with text + image in it?

I have found a very easy solution! If you have a form and you want to have a custom submit button you can use some code like this:

<button type="submit">
    <img src="login.png" onmouseover="this.src='login2.png';" onmouseout="this.src='login.png';" />
</button>

Or just direct it to a link of a page.

"The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine" Error in importing process of xlsx to a sql server

I had the same problem. SSMS launches the 32bit version of the import and export wizard which has this issue. Try launching the 64bit version application and it should work fine.

receiving error: 'Error: SSL Error: SELF_SIGNED_CERT_IN_CHAIN' while using npm

For now I just switched registry URL from https to http. Like this:

npm config set registry="http://registry.npmjs.org/"

How can I sort a List alphabetically?

descending alphabet:

List<String> list;
...
Collections.sort(list);
Collections.reverse(list);

How to use a findBy method with comparative criteria

I like to use such static methods:

$result = $purchases_repository->matching(
    Criteria::create()->where(
        Criteria::expr()->gt('prize', 200)
    )
);

Of course, you can push logic when it is 1 condition, but when you have more conditions it is better to divide it into fragments, configure and pass it to the method:

$expr = Criteria::expr();

$criteria = Criteria::create();
$criteria->where($expr->gt('prize', 200));
$criteria->orderBy(['prize' => Criteria::DESC]);

$result = $purchases_repository->matching($criteria);

Dividing two integers to produce a float result

Cast the operands to floats:

float ans = (float)a / (float)b;

Horizontal Scroll Table in Bootstrap/CSS

You can also check for bootstrap datatable plugin as well for above issue.

It will have a large column table scrollable feature with lot of other options

$(document).ready(function() {
    $('#example').dataTable( {
        "scrollX": true
    } );
} );

for more info with example please check out this link

Permissions for /var/www/html

You just need 775 for /var/www/html as long as you are logging in as myuser. The 7 octal in the middle (which is for "group" acl) ensures that the group has permission to read/write/execute. As long as you belong to the group that owns the files, "myuser" should be able to write to them. You may need to give group permissions to all the files in the docuemnt root, though:

chmod -R g+w /var/www/html

Difference between "move" and "li" in MIPS assembly language

The move instruction copies a value from one register to another. The li instruction loads a specific numeric value into that register.

For the specific case of zero, you can use either the constant zero or the zero register to get that:

move $s0, $zero
li   $s0, 0

There's no register that generates a value other than zero, though, so you'd have to use li if you wanted some other number, like:

li $s0, 12345678

How to connect to a remote MySQL database with Java?

Plus, you should make sure the MySQL server's config (/etc/mysql/my.cnf, /etc/default/mysql on Debian) doesn't have "skip-networking" activated and is not binded exclusively to the loopback interface (127.0.0.1) but also to the interface/IP address you want connect to.

How different is Scrum practice from Agile Practice?

Agile is commonly regarded as an umbrella term. Scrum/Kanban are executions of Agile guiding principles from a project management perspective, whereas eXtreme Programming (XP) focuses on the engineering practices e.g., Unit Testing, Continuous Integration, Pair Programming etc.

Typically: Agile = Scrum + XP

How to plot a function curve in R

Lattice solution with additional settings which I needed:

library(lattice)
distribution<-function(x) {2^(-x*2)}
X<-seq(0,10,0.00001)
xyplot(distribution(X)~X,type="l", col = rgb(red = 255, green = 90, blue = 0, maxColorValue = 255), cex.lab = 3.5, cex.axis = 3.5, lwd=2 )
  1. If you need your range of values for x plotted in increments different from 1, e.g. 0.00001 you can use:

X<-seq(0,10,0.00001)

  1. You can change the colour of your line by defining a rgb value:

col = rgb(red = 255, green = 90, blue = 0, maxColorValue = 255)

  1. You can change the width of the plotted line by setting:

lwd = 2

  1. You can change the size of the labels by scaling them:

cex.lab = 3.5, cex.axis = 3.5

Example plot

gdb: how to print the current line or find the current line number?

The 'frame' command will give you what you are looking for. (This can be abbreviated just 'f'). Here is an example:

(gdb) frame
\#0  zmq::xsub_t::xrecv (this=0x617180, msg_=0x7ffff00008e0) at xsub.cpp:139
139         int rc = fq.recv (msg_);
(gdb)

Without an argument, 'frame' just tells you where you are at (with an argument it changes the frame). More information on the frame command can be found here.

How do I convert an object to an array?

$array = json_decode(json_encode($object), true);

I tried several ways to do a foreach with an object and THIS really is the most easy and cool workaround I have seen. Just one line :)

Replace input type=file by an image

This is my method if i got your point

HTML

<label for="FileInput">
    <img src="tools/img/upload2.png" style="cursor:pointer" onmouseover="this.src='tools/img/upload.png'" onmouseout="this.src='tools/img/upload2.png'" alt="Injaz Msila" style="float:right;margin:7px" />
</label>
<form action="upload.php">
    <input type="file" id="FileInput" style="cursor: pointer;  display: none"/>
    <input type="submit" id="Up" style="display: none;" />
</form>

jQuery

<script type="text/javascript">
    $( "#FileInput" ).change(function() {
      $( "#Up" ).click();
    });
</script>

Download a file from NodeJS Server using Express

'use strict';

var express = require('express');
var fs = require('fs');
var compress = require('compression');
var bodyParser = require('body-parser');

var app = express();
app.set('port', 9999);
app.use(bodyParser.json({ limit: '1mb' }));
app.use(compress());

app.use(function (req, res, next) {
    req.setTimeout(3600000)
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept,' + Object.keys(req.headers).join());

    if (req.method === 'OPTIONS') {
        res.write(':)');
        res.end();
    } else next();
});

function readApp(req,res) {
  var file = req.originalUrl == "/read-android" ? "Android.apk" : "Ios.ipa",
      filePath = "/home/sony/Documents/docs/";
  fs.exists(filePath, function(exists){
      if (exists) {     
        res.writeHead(200, {
          "Content-Type": "application/octet-stream",
          "Content-Disposition" : "attachment; filename=" + file});
        fs.createReadStream(filePath + file).pipe(res);
      } else {
        res.writeHead(400, {"Content-Type": "text/plain"});
        res.end("ERROR File does NOT Exists.ipa");
      }
    });  
}

app.get('/read-android', function(req, res) {
    var u = {"originalUrl":req.originalUrl};
    readApp(u,res) 
});

app.get('/read-ios', function(req, res) {
    var u = {"originalUrl":req.originalUrl};
    readApp(u,res) 
});

var server = app.listen(app.get('port'), function() {
    console.log('Express server listening on port ' + server.address().port);
});

request exceeds the configured maxQueryStringLength when using [Authorize]

For anyone else that may encounter this problem and it is not solved by either of the options above, this is what worked for me.

1. Click on the website in IIS
2. Double Click on Authentication under IIS
3. Enable Anonymous Authentication

I had disabled this because we were using our own Auth, but that lead to this same problem and the accepted answer did not help in any way.

How do you comment an MS-access Query?

NOTE: Confirmed with Access 2003, don't know about earlier versions.

For a query in an MDB you can right-click in the query designer (anywhere in the empty space where the tables are), select Properties from the context menu, and enter text in the Description property.

You're limited to 256 characters, but it's better than nothing.

You can get at the description programatically with something like this:

Dim db As Database
Dim qry As QueryDef

Set db = Application.CurrentDb
Set qry = db.QueryDefs("myQuery")

Debug.Print qry.Properties("Description")

Check if value exists in the array (AngularJS)

You could use indexOf function.

if(list.indexOf(createItem.artNr) !== -1) {
  $scope.message = 'artNr already exists!';
}

More about indexOf:

should use size_t or ssize_t

ssize_t is used for functions whose return value could either be a valid size, or a negative value to indicate an error. It is guaranteed to be able to store values at least in the range [-1, SSIZE_MAX] (SSIZE_MAX is system-dependent).

So you should use size_t whenever you mean to return a size in bytes, and ssize_t whenever you would return either a size in bytes or a (negative) error value.

See: http://pubs.opengroup.org/onlinepubs/007908775/xsh/systypes.h.html

An implementation of the fast Fourier transform (FFT) in C#

AForge.net is a free (open-source) library with Fast Fourier Transform support. (See Sources/Imaging/ComplexImage.cs for usage, Sources/Math/FourierTransform.cs for implemenation)

Re-ordering factor levels in data frame

Assuming your dataframe is mydf:

mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))

Difference between HttpModule and HttpClientModule

This is a good reference, it helped me switch my http requests to httpClient.

It compares the two in terms of differences and gives code examples.

This is just a few differences I dealt with while changing services to httpclient in my project (borrowing from the article I mentioned) :

Importing

import {HttpModule} from '@angular/http';
import {HttpClientModule} from '@angular/common/http';

Requesting and parsing response:

@angular/http

 this.http.get(url)
      // Extract the data in HTTP Response (parsing)
      .map((response: Response) => response.json() as GithubUser)
      .subscribe((data: GithubUser) => {
        // Display the result
        console.log('TJ user data', data);
      });

@angular/common/http

 this.http.get(url)
      .subscribe((data: GithubUser) => {
        // Data extraction from the HTTP response is already done
        // Display the result
        console.log('TJ user data', data);
      });

Note: You no longer have to extract the returned data explicitly; by default, if the data you get back is type of JSON, then you don't have to do anything extra.

But, if you need to parse any other type of response like text or blob, then make sure you add the responseType in the request. Like so:

Making the GET HTTP request with responseType option:

 this.http.get(url, {responseType: 'blob'})
      .subscribe((data) => {
        // Data extraction from the HTTP response is already done
        // Display the result
        console.log('TJ user data', data);
      });

Adding Interceptor

I also used interceptors for adding the token for my authorization to every request, reference.

like so:

@Injectable()
export class MyFirstInterceptor implements HttpInterceptor {

    constructor(private currentUserService: CurrentUserService) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        // get the token from a service
        const token: string = this.currentUserService.token;

        // add it if we have one
        if (token) {
            req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) });
        }

        // if this is a login-request the header is 
        // already set to x/www/formurl/encoded. 
        // so if we already have a content-type, do not 
        // set it, but if we don't have one, set it to 
        // default --> json
        if (!req.headers.has('Content-Type')) {
            req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
        }

        // setting the accept header
        req = req.clone({ headers: req.headers.set('Accept', 'application/json') });
        return next.handle(req);
    }
}

Its a pretty nice upgrade!

HTML form with two submit buttons and two "target" attributes

<form id='myForm'>
    <input type="button" name="first_btn" id="first_btn">
    <input type="button" name="second_btn" id="second_btn">
</form>

<script>

$('#first_btn').click(function(){
    var form = document.getElementById("myForm")
    form.action = "https://foo.com";
    form.submit();
});

$('#second_btn').click(function(){
    var form = document.getElementById("myForm")
    form.action = "http://bar.com";
    form.submit();
});

</script>

Meaning of "n:m" and "1:n" in database design

Many to Many (n:m) One to Many (1:n)

What strategies and tools are useful for finding memory leaks in .NET?

Big guns - Debugging Tools for Windows

This is an amazing collection of tools. You can analyze both managed and unmanaged heaps with it and you can do it offline. This was very handy for debugging one of our ASP.NET applications that kept recycling due to memory overuse. I only had to create a full memory dump of living process running on production server, all analysis was done offline in WinDbg. (It turned out some developer was overusing in-memory Session storage.)

"If broken it is..." blog has very useful articles on the subject.

Is there a typescript List<> and/or Map<> class/library?

Did they add a runtime List<> and/or Map<> type class to typepad 1.0

No, providing a runtime is not the focus of the TypeScript team.

is there a solid library out there someone wrote that provides this functionality?

I wrote (really just ported over buckets to typescript): https://github.com/basarat/typescript-collections

Update

JavaScript / TypeScript now support this natively and you can enable them with lib.d.ts : https://basarat.gitbooks.io/typescript/docs/types/lib.d.ts.html along with a polyfill if you want

Print specific part of webpage

Try this:

  1. Dump the innerHTML of the container into the iFrame (plus any print-specific CSS
  2. print the iFrame contents.

Try it out in JSFiddle (iframes don't appear to work in StackOverflow's preview)

You can see the code here, but it won't work due to what are probably security limitations in StackOverflow's renderer.

_x000D_
_x000D_
const printButton = document.getElementById('print-button');

printButton.addEventListener('click', event => {
  // build the new HTML page
  const content = document.getElementById('name-card').innerHTML;
  const printHtml = `<html>
      <head>
          <meta charset="utf-8">
          <title>Name Card</title>
      </head>
      <body>${content}</body>
  </html>`;
      
  // get the iframe
  let iFrame = document.getElementById('print-iframe');
  
  // set the iFrame contents and print
  iFrame.contentDocument.body.innerHTML = printHtml;
  iFrame.focus();
    iFrame.contentWindow.print();
  
});
_x000D_
<h1>Print your name badge</h1>
<div id="name-card" class="card">
  <p>Hello my name is</p>
  <h2>Max Powers</h2>
</div>
<p>You will be required to wear your name badge at all times</p>
<a id="print-button" class="btn btn-primary">Print</a>

<iframe id="print-iframe" width="0" height="0"></iframe>
_x000D_
_x000D_
_x000D_

How to load npm modules in AWS Lambda?

Hope this helps, with Serverless framework you can do something like this:

  1. Add these things in your serverless.yml file:

plugins: - serverless-webpack custom: webpackIncludeModules: forceInclude: - <your package name> (for example: node-fetch) 2. Then create your Lambda function, deploy it by serverless deploy, the package that included in serverless.yml will be there for you.

For more information about serverless: https://serverless.com/framework/docs/providers/aws/guide/quick-start/

ERROR 1698 (28000): Access denied for user 'root'@'localhost'

You want to access MySQL with root user but you're not providing root's correct password.

If you need to set a new password for root, MySQL's site has great documentation on how to do it: http://dev.mysql.com/doc/refman/5.7/en/resetting-permissions.html

I'll not show the process in here because MySql documentation on the above link it's clear and concise.

How to add property to object in PHP >= 5.3 strict mode without generating error

you should use magic methods __Set and __get. Simple example:

class Foo
{
    //This array stores your properties
private $content = array();

public function __set($key, $value)
{
            //Perform data validation here before inserting data
    $this->content[$key] = $value;
    return $this;
}

public function __get($value)
{       //You might want to check that the data exists here
    return $this->$content[$value];
}

}

Of course, don't use this example as this : no security at all :)

EDIT : seen your comments, here could be an alternative based on reflection and a decorator :

 class Foo
 {
private $content = array();
private $stdInstance;

public function __construct($stdInstance)
{
    $this->stdInstance = $stdInstance;
}

public function __set($key, $value)
{
    //Reflection for the stdClass object
    $ref = new ReflectionClass($this->stdInstance);
    //Fetch the props of the object

    $props = $ref->getProperties();

    if (in_array($key, $props)) {
        $this->stdInstance->$key = $value;
    } else {
        $this->content[$key] = $value;
    }
    return $this;
}

public function __get($value)
{
    //Search first your array as it is faster than using reflection
    if (array_key_exists($value, $this->content))
    {
        return $this->content[$value];
    } else {
        $ref = new ReflectionClass($this->stdInstance);

        //Fetch the props of the object
        $props = $ref->getProperties();

        if (in_array($value, $props)) {

        return $this->stdInstance->$value;
    } else {
        throw new \Exception('No prop in here...');
    }
}
 }
}

PS : I didn't test my code, just the general idea...

How to check a string against null in java?

With Java 7 you can use

if (Objects.equals(foo, null)) {
    ...
}

which will return true if both parameters are null.

How to get text in QlineEdit when QpushButton is pressed in a string?

Acepted solution implemented in PyQt5

import sys
from PyQt5.QtWidgets import QApplication, QDialog, QFormLayout
from PyQt5.QtWidgets import (QPushButton, QLineEdit)

class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        self.le = QLineEdit()
        self.le.setObjectName("host")
        self.le.setText("Host")

        self.pb = QPushButton()
        self.pb.setObjectName("connect")
        self.pb.setText("Connect")
        self.pb.clicked.connect(self.button_click)

        layout = QFormLayout()
        layout.addWidget(self.le)
        layout.addWidget(self.pb)
        self.setLayout(layout)

        self.setWindowTitle("Learning")

    def button_click(self):
        # shost is a QString object
        shost = self.le.text()
        print (shost)


app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()

How to get current moment in ISO 8601 format with date, hour, and minute?

As of Java 8 you can simply do:

Instant.now().toString();

From the java.time.Instant docs:

now

public static Instant now()

Obtains the current instant from the system clock.

This will query the system UTC clock to obtain the current instant.

 

toString

public String toString()

A string representation of this instant using ISO-8601 representation.

The format used is the same as DateTimeFormatter.ISO_INSTANT.

Difference between if () { } and if () : endif;

I feel that none of the preexisting answers fully identify the answer here, so I'm going to articulate my own perspective. Functionally, the two methods are the same. If the programer is familiar with other languages following C syntax, then they will likely feel more comfortable with the braces, or else if php is the first language that they're learning, they will feel more comfortable with the if endif syntax, since it seems closer to regular language.

If you're a really serious programmer and need to get things done fast, then I do believe that the curly brace syntax is superior because it saves time typing

if(/*condition*/){
    /*body*/ 
}

compared to

if(/*condition*/):
    /*body*/
endif;

This is especially true with other loops, say, a foreach where you would end up typing an extra 10 chars. With braces, you just need to type two characters, but for the keyword based syntax you have to type a whole extra keyword for every loop and conditional statement.

Visual Studio Copy Project

Following Shane's answer above (which works great BTW)…

You might encounter a slew of yellow triangles in the reference list. Most of these can be eliminated by a Build->Clean Solution and Build->Rebuild Solution.

I did happen to have some Google API references that were a little more stubborn...as well as NewtonSoft JSon.

Trying to reinstall the NuGet package of the same version didn't work.
Visual Studio thinks you already have it installed.

To get around this:
1: Write down the original version.
2: Install the next higher/lower version...then uninstall it.
3: Install the original version from step #1.

CSS checkbox input styling

With CSS 2 you can do this:

input[type='checkbox'] { ... }

This should be pretty widely supported by now. See support for browsers

Get the decimal part from a double

There is a cleaner and ways faster solution than the 'Math.Truncate' approach:

double frac = value % 1;

Equivalent of Super Keyword in C#

C# equivalent of your code is

  class Imagedata : PDFStreamEngine
  {
     // C# uses "base" keyword whenever Java uses "super" 
     // so instead of super(...) in Java we should call its C# equivalent (base):
     public Imagedata()
       : base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true)) 
     { }

     // Java methods are virtual by default, when C# methods aren't.
     // So we should be sure that processOperator method in base class 
     // (that is PDFStreamEngine)
     // declared as "virtual"
     protected override void processOperator(PDFOperator operations, List arguments)
     {
        base.processOperator(operations, arguments);
     }
  }

Oracle date to string conversion

Another thing to notice is you are trying to convert a date in mm/dd/yyyy but if you have any plans of comparing this converted date to some other date then make sure to convert it in yyyy-mm-dd format only since to_char literally converts it into a string and with any other format we will get undesired result. For any more explanation follow this: Comparing Dates in Oracle SQL

Get the last three chars from any string - Java

This method would be helpful :

String rightPart(String text,int length)
{
    if (text.length()<length) return text;
    String raw = "";
    for (int i = 1; i <= length; i++) {
        raw += text.toCharArray()[text.length()-i];
    }
    return new StringBuilder(raw).reverse().toString();
}

Xcode swift am/pm time to 24 hour format

Here is code for other way around

For Swift 3

 func amAppend(str:String) -> String{
    var temp = str
    var strArr = str.characters.split{$0 == ":"}.map(String.init)
    var hour = Int(strArr[0])!
    var min = Int(strArr[1])!
    if(hour > 12){
        temp = temp + "PM"
    }
    else{
        temp = temp + "AM"
    }
    return temp
}

Function inside a function.?

Not sure what the author of that code wanted to achieve. Definining a function inside another function does NOT mean that the inner function is only visible inside the outer function. After calling x() the first time, the y() function will be in global scope as well.

Does --disable-web-security Work In Chrome Anymore?

Check your windows task manager and make sure you kill all chrome processes before running the command.

Saving lists to txt file

@Jon's answer is great and will get you where you need to go. So why is your code printing out what it is. The answer: You're not writing out the contents of your list, but the String representation of your list itself, by an implicit call to Lists.verbList.ToString(). Object.ToString() defines the default behavior you're seeing here.

Flutter - The method was called on null

You should declare your method first in void initState(), so when the first time pages has been loaded, it will init your method first, hope it can help

In Node.js, how do I turn a string to a json?

You need to use this function.

JSON.parse(yourJsonString);

And it will return the object / array that was contained within the string.

How do I force "git pull" to overwrite local files?

These four commands work for me.

git reset --hard HEAD
git checkout origin/master
git branch -D master
git checkout -b master

To check/pull after executing these commands

git pull origin master

I tried a lot but finally got success with these commands.

How can I use a for each loop on an array?

I use the counter variable like Fink suggests. If you want For Each and to pass ByRef (which can be more efficient for long strings) you have to cast your element as a string using CStr

Sub Example()

    Dim vItm As Variant
    Dim aStrings(1 To 4) As String

    aStrings(1) = "one": aStrings(2) = "two": aStrings(3) = "three": aStrings(4) = "four"

    For Each vItm In aStrings
        do_something CStr(vItm)
    Next vItm

End Sub

Function do_something(ByRef sInput As String)

    Debug.Print sInput

End Function

This application has no explicit mapping for /error

I need to mention this way and give the reference to packages and it worked out. You may exclude @EnableAutoConfiguration this annotation but required for me to bypass any DB related depenencies.

@SpringBootApplication
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
@ComponentScan(basePackages = {"your package 1", "your package2"})

public class CommentStoreApplication {

    public static void main(String[] args) {
        SpringApplication.run(CommentStoreApplication.class, args);

    }
}

How to hide navigation bar permanently in android activity?

Snippets:

FullScreenFragment.java

HideNavigationBarComponent.java


This is for Android 4.4+

Try out immersive mode https://developer.android.com/training/system-ui/immersive.html

Fast snippet (for an Activity class):

private int currentApiVersion;

@Override
@SuppressLint("NewApi")
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    currentApiVersion = android.os.Build.VERSION.SDK_INT;

    final int flags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
        | View.SYSTEM_UI_FLAG_FULLSCREEN
        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;

    // This work only for android 4.4+
    if(currentApiVersion >= Build.VERSION_CODES.KITKAT)
    {

        getWindow().getDecorView().setSystemUiVisibility(flags);

        // Code below is to handle presses of Volume up or Volume down.
        // Without this, after pressing volume buttons, the navigation bar will
        // show up and won't hide
        final View decorView = getWindow().getDecorView();
        decorView
            .setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener()
            {

                @Override
                public void onSystemUiVisibilityChange(int visibility)
                {
                    if((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0)
                    {
                        decorView.setSystemUiVisibility(flags);
                    }
                }
            });
    }

}


@SuppressLint("NewApi")
@Override
public void onWindowFocusChanged(boolean hasFocus)
{
    super.onWindowFocusChanged(hasFocus);
    if(currentApiVersion >= Build.VERSION_CODES.KITKAT && hasFocus)
    {
        getWindow().getDecorView().setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
    }
}

If you have problems when you press Volume up or Volume down that your navigation bar show. I added code in onCreate see setOnSystemUiVisibilityChangeListener

Here is another related question:

Immersive mode navigation becomes sticky after volume press or minimise-restore

How to use `subprocess` command with pipes

You can try the pipe functionality in sh.py:

import sh
print sh.grep(sh.ps("-ax"), "process_name")

Wait until an HTML5 video loads

you can use preload="none" in the attribute of video tag so the video will be displayed only when user clicks on play button.

_x000D_
_x000D_
<video preload="none">
_x000D_
_x000D_
_x000D_

Converting string to numeric

As csgillespie said. stringsAsFactors is default on TRUE, which converts any text to a factor. So even after deleting the text, you still have a factor in your dataframe.

Now regarding the conversion, there's a more optimal way to do so. So I put it here as a reference :

> x <- factor(sample(4:8,10,replace=T))
> x
 [1] 6 4 8 6 7 6 8 5 8 4
Levels: 4 5 6 7 8
> as.numeric(levels(x))[x]
 [1] 6 4 8 6 7 6 8 5 8 4

To show it works.

The timings :

> x <- factor(sample(4:8,500000,replace=T))
> system.time(as.numeric(as.character(x)))
   user  system elapsed 
   0.11    0.00    0.11 
> system.time(as.numeric(levels(x))[x])
   user  system elapsed 
      0       0       0 

It's a big improvement, but not always a bottleneck. It gets important however if you have a big dataframe and a lot of columns to convert.

Sort array of objects by string property value

Way 1 :

You can use Underscore.js. Import underscore first.

 import * as _ from 'underscore';
 let SortedObjs = _.sortBy(objs, 'last_nom');

Way 2 : Use compare function.

function compare(first, second) {
     if (first.last_nom < second.last_nom)
         return -1;
     if (first.last_nom > second.last_nom)
       return 1;
    return 0;
 }

objs.sort(compare);

Keras model.summary() result - Understanding the # of Parameters

The number of parameters is 7850 because with every hidden unit you have 784 input weights and one weight of connection with bias. This means that every hidden unit gives you 785 parameters. You have 10 units so it sums up to 7850.

The role of this additional bias term is really important. It significantly increases the capacity of your model. You can read details e.g. here Role of Bias in Neural Networks.

How to encrypt a large file in openssl using public key

Maybe you should check out the accepted answer to this (How to encrypt data in php using Public/Private keys?) question.

Instead of manually working around the message size limitation (or perhaps a trait) of RSA, it shows how to use the S/mime feature of OpenSSL to do the same thing and not needing to juggle with the symmetric key manually.

Java generics: multiple generic parameters?

Even more, you can inherit generics :)

@SuppressWarnings("unchecked")
public <T extends Something<E>, E extends Enum<E> & SomethingAware> T getSomething(Class<T> clazz) {
        return (T) somethingHolderMap.get(clazz);
    }

HTTP Ajax Request via HTTPS Page

In some cases a one-way request without a response can be fired to a TCP server, without a SSL certificate. A TCP server, in contrast to a HTTP server, will catch you request. However there will be no access to any data sent from the browser, because the browser will not send any data without a positive certificate check. And in special cases even a bare TCP signal without any data is enough to execute some tasks. For example for an IoT device within a LAN to start a connection to an external service. Link

This is a kind of a "Wake Up" trigger, that works on a port without any security.

In case a response is needed, this can be implemented using a secured public https server, which can send the needed data back to the browser using e.g. Websockets.

Convert Map<String,Object> to Map<String,String>

There are two ways to do this. One is very simple but unsafe:

Map<String, Object> map = new HashMap<String, Object>();
Map<String, String> newMap = new HashMap<String, String>((Map)map);  // unchecked warning

The other way has no compiler warnings and ensures type safety at runtime, which is more robust. (After all, you can't guarantee the original map contains only String values, otherwise why wouldn't it be Map<String, String> in the first place?)

Map<String, Object> map = new HashMap<String, Object>();
Map<String, String> newMap = new HashMap<String, String>();
@SuppressWarnings("unchecked") Map<String, Object> intermediate =
    (Map)Collections.checkedMap(newMap, String.class, String.class);
intermediate.putAll(map);

How do I limit the number of results returned from grep?

Using tail:

#dmesg 
...
...
...
[132059.017752] cfg80211:   (57240000 KHz - 65880000 KHz @ 2160000 KHz), (N/A, 4000 mBm)
[132116.566238] cfg80211: Calling CRDA to update world regulatory domain
[132116.568939] cfg80211: World regulatory domain updated:
[132116.568942] cfg80211:   (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp)
[132116.568944] cfg80211:   (2402000 KHz - 2472000 KHz @ 40000 KHz), (300 mBi, 2000 mBm)
[132116.568945] cfg80211:   (2457000 KHz - 2482000 KHz @ 40000 KHz), (300 mBi, 2000 mBm)
[132116.568947] cfg80211:   (2474000 KHz - 2494000 KHz @ 20000 KHz), (300 mBi, 2000 mBm)
[132116.568948] cfg80211:   (5170000 KHz - 5250000 KHz @ 40000 KHz), (300 mBi, 2000 mBm)
[132116.568949] cfg80211:   (5735000 KHz - 5835000 KHz @ 40000 KHz), (300 mBi, 2000 mBm)
[132120.288218] cfg80211: Calling CRDA for country: GB
[132120.291143] cfg80211: Regulatory domain changed to country: GB
[132120.291146] cfg80211:   (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp)
[132120.291148] cfg80211:   (2402000 KHz - 2482000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291150] cfg80211:   (5170000 KHz - 5250000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291152] cfg80211:   (5250000 KHz - 5330000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291153] cfg80211:   (5490000 KHz - 5710000 KHz @ 40000 KHz), (N/A, 2700 mBm)
[132120.291155] cfg80211:   (57240000 KHz - 65880000 KHz @ 2160000 KHz), (N/A, 4000 mBm)
alex@ubuntu:~/bugs/navencrypt/dev-tools$ dmesg | grep cfg8021 | head 2
head: cannot open ‘2’ for reading: No such file or directory
alex@ubuntu:~/bugs/navencrypt/dev-tools$ dmesg | grep cfg8021 | tail -2
[132120.291153] cfg80211:   (5490000 KHz - 5710000 KHz @ 40000 KHz), (N/A, 2700 mBm)
[132120.291155] cfg80211:   (57240000 KHz - 65880000 KHz @ 2160000 KHz), (N/A, 4000 mBm)
alex@ubuntu:~/bugs/navencrypt/dev-tools$ dmesg | grep cfg8021 | tail -5
[132120.291148] cfg80211:   (2402000 KHz - 2482000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291150] cfg80211:   (5170000 KHz - 5250000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291152] cfg80211:   (5250000 KHz - 5330000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291153] cfg80211:   (5490000 KHz - 5710000 KHz @ 40000 KHz), (N/A, 2700 mBm)
[132120.291155] cfg80211:   (57240000 KHz - 65880000 KHz @ 2160000 KHz), (N/A, 4000 mBm)
alex@ubuntu:~/bugs/navencrypt/dev-tools$ dmesg | grep cfg8021 | tail -6
[132120.291146] cfg80211:   (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp)
[132120.291148] cfg80211:   (2402000 KHz - 2482000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291150] cfg80211:   (5170000 KHz - 5250000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291152] cfg80211:   (5250000 KHz - 5330000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291153] cfg80211:   (5490000 KHz - 5710000 KHz @ 40000 KHz), (N/A, 2700 mBm)
[132120.291155] cfg80211:   (57240000 KHz - 65880000 KHz @ 2160000 KHz), (N/A, 4000 mBm)
alex@ubuntu:~/bugs/navencrypt/dev-tools$ 

Returning a value even if no result

if you want both always a return value but never a null value you can combine count with coalesce :

select count(field1), coalesce(field1,'any_other_default_value') from table;

that because count, will force mysql to always return a value (0 if there is no values to count) and coalesce will force mysql to always put a value that is not null

Cannot find the '@angular/common/http' module

Refer to this: http: deprecate @angular/http in favor of @angular/common/http.

How to extend available properties of User.Identity

Whenever you want to extend the properties of User.Identity with any additional properties like the question above, add these properties to the ApplicationUser class first like so:

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }

    // Your Extended Properties
    public long? OrganizationId { get; set; }
}

Then what you need is to create an extension method like so (I create mine in an new Extensions folder):

namespace App.Extensions
{
    public static class IdentityExtensions
    {
        public static string GetOrganizationId(this IIdentity identity)
        {
            var claim = ((ClaimsIdentity)identity).FindFirst("OrganizationId");
            // Test for null to avoid issues during local testing
            return (claim != null) ? claim.Value : string.Empty;
        }
    }
}

When you create the Identity in the ApplicationUser class, just add the Claim -> OrganizationId like so:

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here => this.OrganizationId is a value stored in database against the user
        userIdentity.AddClaim(new Claim("OrganizationId", this.OrganizationId.ToString()));

        return userIdentity;
    }

Once you added the claim and have your extension method in place, to make it available as a property on your User.Identity, add a using statement on the page/file you want to access it:

in my case: using App.Extensions; within a Controller and @using. App.Extensions withing a .cshtml View file.

EDIT:

What you can also do to avoid adding a using statement in every View is to go to the Views folder, and locate the Web.config file in there. Now look for the <namespaces> tag and add your extension namespace there like so:

<add namespace="App.Extensions" />

Save your file and you're done. Now every View will know of your extensions.

You can access the Extension Method:

var orgId = User.Identity.GetOrganizationId();

error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

It simply means that one chose the wrong encoding to read the file.

On Mac, use file -I file.txt to find the correct encoding. On Linux, use file -i file.txt.

Call another rest api from my server in Spring-Boot

Instead of String you are trying to get custom POJO object details as output by calling another API/URI, try the this solution. I hope it will be clear and helpful for how to use RestTemplate also,

In Spring Boot, first we need to create Bean for RestTemplate under the @Configuration annotated class. You can even write a separate class and annotate with @Configuration like below.

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
       return builder.build();
    }
}

Then, you have to define RestTemplate with @Autowired or @Injected under your service/Controller, whereever you are trying to use RestTemplate. Use the below code,

@Autowired
private RestTemplate restTemplate;

Now, will see the part of how to call another api from my application using above created RestTemplate. For this we can use multiple methods like execute(), getForEntity(), getForObject() and etc. Here I am placing the code with example of execute(). I have even tried other two, I faced problem of converting returned LinkedHashMap into expected POJO object. The below, execute() method solved my problem.

ResponseEntity<List<POJO>> responseEntity = restTemplate.exchange(
    URL, 
    HttpMethod.GET, 
    null, 
    new ParameterizedTypeReference<List<POJO>>() {
    });
List<POJO> pojoObjList = responseEntity.getBody();

Happy Coding :)

How do I add an active class to a Link from React Router?

With [email protected] (though any 4.x.x should do I guess), we can use the withRouter HOC to accomplish this. For example, I want to implement the Bootstrap navbar and since it requires a class of active on <li class="nav-item"> and not on the anchor tag, I made a new component called NavItem to encapsulate a single li.nav-item. The implementation is as follows:

import React from "react";
import { Link, withRouter } from "react-router-dom";

const NavItem = ({ isActive, to, label }) => {
  let classes = ["nav-item"];
  if (isActive) classes.push("active");

  return (
    <li className={classes.join(" ")}>
      <Link className="nav-link" to={to}>
        {label}
      </Link>
    </li>
  );
};

export default withRouter(({ location, ...props }) => {
  const isActive = location.pathname === props.to;

  console.log(location.pathname, props.to);

  return <NavItem {...props} isActive={isActive} />;
});

As you can see, NavItem is just a stateless functional component which expects an isActive prop to determine whether active class should be added. Now, to update this prop as the location changes, we can make use of the withRouter HOC. You can pass any component to this function and it'll give it { match, location, history } objects in its props along with the ones you pass down. Here, I am creating a functional component inline which receives these objects and determines whether the current link is the active one using the location.pathname property. This'll give us a Boolean and we can return the NavItem along with isActive set to the value we computed using location.pathname.

A working example of this can be found here. Please let me know if there's an easier way to do this.

How do I select which GPU to run a job on?

In case of someone else is doing it in Python and it is not working, try to set it before do the imports of pycuda and tensorflow.

I.e.:

import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
...
import pycuda.autoinit
import tensorflow as tf
...

As saw here.

Is true == 1 and false == 0 in JavaScript?

Use === to equate the variables instead of ==.

== checks if the value of the variables is similar

=== checks if the value of the variables and the type of the variables are similar

Notice how

if(0===false) {
    document.write("oh!!! that's true");
}?

and

if(0==false) {
    document.write("oh!!! that's true");
}?

give different results

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

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

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

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

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

What you're doing there is:

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

Which we can simplify into a lambda:

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

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

map.forEach(map2::put);

change html input type by JS?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.or/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript" language="javascript">
function changefield(){
    document.getElementById("passwordbox").innerHTML = "<input id=\"passwordfield\" type=\"password\" name=\"password-field\" title=\"Password\" tabindex=\"2\" />";
    document.getElementById("password-field".focus();
}
</script>
</head>

<body>
<div id="passwordbox">
<input id="password-field" type="text" name="password-field" title="Password"onfocus="changefield();" value="Password" tabindex="2" />
</div>
<input type="submit" name="submit" value="sign in" tabindex="3" />

</body>
</html>

'workbooks.worksheets.activate' works, but '.select' does not

You can't select a sheet in a non-active workbook.

You must first activate the workbook, then you can select the sheet.

workbooks("A").activate
workbooks("A").worksheets("B").select 

When you use Activate it automatically activates the workbook.

Note you can select >1 sheet in a workbook:

activeworkbook.sheets(array("sheet1","sheet3")).select

but only one sheet can be Active, and if you activate a sheet which is not part of a multi-sheet selection then those other sheets will become un-selected.

What does `m_` variable prefix mean?

This is typical programming practice for defining variables that are member variables. So when you're using them later, you don't need to see where they're defined to know their scope. This is also great if you already know the scope and you're using something like intelliSense, you can start with m_ and a list of all your member variables are shown. Part of Hungarian notation, see the part about scope in the examples here.

How to make method call another one in classes?

Because the Method2 is static, all you have to do is call like this:

public class AllMethods
{
    public static void Method2()
    {
        // code here
    }
}

class Caller
{
    public static void Main(string[] args)
    {
        AllMethods.Method2();
    }
}

If they are in different namespaces you will also need to add the namespace of AllMethods to caller.cs in a using statement.

If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:

public class MyClass
{
    public void InstanceMethod() 
    { 
        // ...
    }
}

public static void Main(string[] args)
{
    var instance = new MyClass();
    instance.InstanceMethod();
}

Update

As of C# 6, you can now also achieve this with using static directive to call static methods somewhat more gracefully, for example:

// AllMethods.cs
namespace Some.Namespace
{
    public class AllMethods
    {
        public static void Method2()
        {
            // code here
        }
    }
}

// Caller.cs
using static Some.Namespace.AllMethods;

namespace Other.Namespace
{
    class Caller
    {
        public static void Main(string[] args)
        {
            Method2(); // No need to mention AllMethods here
        }
    }
}

Further Reading

jQuery ajax upload file in asp.net mvc

You can't upload files via ajax, you need to use an iFrame or some other trickery to do a full postback. This is mainly due to security concerns.

Here's a decent write-up including a sample project using SWFUpload and ASP.Net MVC by Steve Sanderson. It's the first thing I read getting this working properly with Asp.Net MVC (I was new to MVC at the time as well), hopefully it's as helpful for you.

What is the most effective way to get the index of an iterator of an std::vector?

I like this one: it - vec.begin(), because to me it clearly says "distance from beginning". With iterators we're used to thinking in terms of arithmetic, so the - sign is the clearest indicator here.

How to truncate milliseconds off of a .NET DateTime

New Method

String Date = DateTime.Today.ToString("dd-MMM-yyyy"); 

// define String pass parameter dd-mmm-yyyy return 24-feb-2016

Or shown on textbox

txtDate.Text = DateTime.Today.ToString("dd-MMM-yyyy");

// put on PageonLoad

Python class returning value

Use __new__ to return value from a class.

As others suggest __repr__,__str__ or even __init__ (somehow) CAN give you what you want, But __new__ will be a semantically better solution for your purpose since you want the actual object to be returned and not just the string representation of it.

Read this answer for more insights into __str__ and __repr__ https://stackoverflow.com/a/19331543/4985585

class MyClass():
    def __new__(cls):
        return list() #or anything you want

>>> MyClass()
[]   #Returns a true list not a repr or string

Detect if an element is visible with jQuery

You're looking for:

.is(':visible')

Although you should probably change your selector to use jQuery considering you're using it in other places anyway:

if($('#testElement').is(':visible')) {
    // Code
}

It is important to note that if any one of a target element's parent elements are hidden, then .is(':visible') on the child will return false (which makes sense).

jQuery 3

:visible has had a reputation for being quite a slow selector as it has to traverse up the DOM tree inspecting a bunch of elements. There's good news for jQuery 3, however, as this post explains (Ctrl + F for :visible):

Thanks to some detective work by Paul Irish at Google, we identified some cases where we could skip a bunch of extra work when custom selectors like :visible are used many times in the same document. That particular case is up to 17 times faster now!

Keep in mind that even with this improvement, selectors like :visible and :hidden can be expensive because they depend on the browser to determine whether elements are actually displaying on the page. That may require, in the worst case, a complete recalculation of CSS styles and page layout! While we don’t discourage their use in most cases, we recommend testing your pages to determine if these selectors are causing performance issues.


Expanding even further to your specific use case, there is a built in jQuery function called $.fadeToggle():

function toggleTestElement() {
    $('#testElement').fadeToggle('fast');
}

How to pass event as argument to an inline event handler in JavaScript?

You don't need to pass this, there already is the event object passed by default automatically, which contains event.target which has the object it's coming from. You can lighten your syntax:

This:

<p onclick="doSomething()">

Will work with this:

function doSomething(){
  console.log(event);
  console.log(event.target);
}

You don't need to instantiate the event object, it's already there. Try it out. And event.target will contain the entire object calling it, which you were referencing as "this" before.

Now if you dynamically trigger doSomething() from somewhere in your code, you will notice that event is undefined. This is because it wasn't triggered from an event of clicking. So if you still want to artificially trigger the event, simply use dispatchEvent:

document.getElementById('element').dispatchEvent(new CustomEvent("click", {'bubbles': true}));

Then doSomething() will see event and event.target as per usual!

No need to pass this everywhere, and you can keep your function signatures free from wiring information and simplify things.

How can I auto increment the C# assembly version via our CI platform (Hudson)?

I decided to use a couple of methods using a prebuild Powershell script(https://gist.github.com/bradjolicoeur/e77c508089aea6614af3) to increment on each successful build then in Global.asax I've going something like this:

  // We are using debug configuration, so increment our builds.
  if (System.Diagnostics.Debugger.IsAttached)
  {
      string version = System.Reflection.Assembly.GetExecutingAssembly()
                                                       .GetName()
                                                       .Version
                                                       .ToString();

      var psi = new ProcessStartInfo(@"svn", "commit -m \"Version: " + version + "\n \"");
      psi.WorkingDirectory = @"C:\CI\Projects\myproject";
      Process.Start(psi); 
  }

I still think the whole process is overcomplicated and I'm going to look into a more efficient method of achieving the same result. I wanted this mainly for passing the version into SVN and then into Jenkin's without too many addtional tools.

Calculate age given the birth date in the format YYYYMMDD

This is my modification:

  function calculate_age(date) {
     var today = new Date();
     var today_month = today.getMonth() + 1; //STRANGE NUMBERING //January is 0!
     var age = today.getYear() - date.getYear();

     if ((today_month > date.getMonth() || ((today_month == date.getMonth()) && (today.getDate() < date.getDate())))) {
       age--;
     }

    return age;
  };

Listing information about all database files in SQL Server

If you rename your Database, MS SQL Server does not rename the underlying files.

Following query gives you the current name of the database and the Logical file name (which might be the original name of the Database when it was created) and also corresponding physical file names.

Note: Un-comment the last line to see only the actual data files

select  db.database_id, 
        db.name "Database Name", 
        files.name "Logical File Name",
        files.physical_name
from    sys.master_files files 
        join sys.databases db on db.database_id = files.database_id 
--                           and files.type_desc = 'ROWS'

Reference:

https://docs.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-master-files-transact-sql?view=sql-server-ver15

https://docs.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-databases-transact-sql?view=sql-server-ver15

AngularJS accessing DOM elements inside directive template

This answer comes a little bit late, but I just was in a similar need.

Observing the comments written by @ganaraj in the question, One use case I was in the need of is, passing a classname via a directive attribute to be added to a ng-repeat li tag in the template.

For example, use the directive like this:

<my-directive class2add="special-class" />

And get the following html:

<div>
    <ul>
       <li class="special-class">Item 1</li>
       <li class="special-class">Item 2</li>
    </ul>
</div>

The solution found here applied with templateUrl, would be:

app.directive("myDirective", function() {
    return {
        template: function(element, attrs){
            return '<div><ul><li ng-repeat="item in items" class="'+attrs.class2add+'"></ul></div>';
        },
        link: function(scope, element, attrs) {
            var list = element.find("ul");
        }
    }
});

Just tried it successfully with AngularJS 1.4.9.

Hope it helps.

What size should TabBar images be?

Thumbs up first before use codes please!!! Create an image that fully cover the whole tab bar item for each item. This is needed to use the image you created as a tab bar item button. Be sure to make the height/width ratio be the same of each tab bar item too. Then:

UITabBarController *tabBarController = (UITabBarController *)self;
UITabBar *tabBar = tabBarController.tabBar;
UITabBarItem *tabBarItem1 = [tabBar.items objectAtIndex:0];
UITabBarItem *tabBarItem2 = [tabBar.items objectAtIndex:1];
UITabBarItem *tabBarItem3 = [tabBar.items objectAtIndex:2];
UITabBarItem *tabBarItem4 = [tabBar.items objectAtIndex:3];

int x,y;

x = tabBar.frame.size.width/4 + 4; //when doing division, it may be rounded so that you need to add 1 to each item; 
y = tabBar.frame.size.height + 10; //the height return always shorter, this is compensated by added by 10; you can change the value if u like.

//because the whole tab bar item will be replaced by an image, u dont need title
tabBarItem1.title = @"";
tabBarItem2.title = @"";
tabBarItem3.title = @"";
tabBarItem4.title = @"";

[tabBarItem1 setFinishedSelectedImage:[self imageWithImage:[UIImage imageNamed:@"item1-select.png"] scaledToSize:CGSizeMake(x, y)] withFinishedUnselectedImage:[self imageWithImage:[UIImage imageNamed:@"item1-deselect.png"] scaledToSize:CGSizeMake(x, y)]];//do the same thing for the other 3 bar item

Broken references in Virtualenvs

A update version @Chris Wedgwood's answer for keeping site-packages (keeping packages installed)

cd ~/.virtualenv/name_of_broken_venv


mv lib/python2.7/site-packages ./    
rm -rf .Python bin lib include
virtualenv .
rm -rf lib/python2.7/site-packages
mv ./site-packages lib/python2.7/

How to generate entire DDL of an Oracle schema (scriptable)?

The output of this query is very clean (original here)

clear screen
accept uname prompt 'Enter User Name : '
accept outfile prompt  ' Output filename : '

spool &&outfile..gen

SET LONG 20000 LONGCHUNKSIZE 20000 PAGESIZE 0 LINESIZE 1000 FEEDBACK OFF VERIFY OFF TRIMSPOOL ON

BEGIN
   DBMS_METADATA.set_transform_param (DBMS_METADATA.session_transform, 'SQLTERMINATOR', true);
   DBMS_METADATA.set_transform_param (DBMS_METADATA.session_transform, 'PRETTY', true);
END;
/

SELECT dbms_metadata.get_ddl('USER','&&uname') FROM dual;
SELECT DBMS_METADATA.GET_GRANTED_DDL('SYSTEM_GRANT','&&uname') from dual;
SELECT DBMS_METADATA.GET_GRANTED_DDL('ROLE_GRANT','&&uname') from dual;
SELECT DBMS_METADATA.GET_GRANTED_DDL('OBJECT_GRANT','&&uname') from dual;

spool off

How to create a static library with g++?

Can someone please tell me how to create a static library from a .cpp and a .hpp file? Do I need to create the .o and the the .a?

Yes.

Create the .o (as per normal):

g++ -c header.cpp

Create the archive:

ar rvs header.a header.o

Test:

g++ test.cpp header.a -o executable_name

Note that it seems a bit pointless to make an archive with just one module in it. You could just as easily have written:

g++ test.cpp header.cpp -o executable_name

Still, I'll give you the benefit of the doubt that your actual use case is a bit more complex, with more modules.

Hope this helps!

Is there a way to get the git root directory in one command?

Short solutions that work with submodules, in hooks, and inside the .git directory

Here's the short answer that most will want:

r=$(git rev-parse --git-dir) && r=$(cd "$r" && pwd)/ && echo "${r%%/.git/*}"

This will work anywhere in a git working tree (including inside the .git directory), but assumes that repository directory(s) are called .git (which is the default). With submodules, this will go to the root of the outermost containing repository.

If you want to get to the root of the current submodule use:

echo $(r=$(git rev-parse --show-toplevel) && ([[ -n $r ]] && echo "$r" || (cd $(git rev-parse --git-dir)/.. && pwd) ))

To easily execute a command in your submodule root, under [alias] in your .gitconfig, add:

sh = "!f() { root=$(pwd)/ && cd ${root%%/.git/*} && git rev-parse && exec \"$@\"; }; f"

This allows you to easily do things like git sh ag <string>

Robust solution that supports differently named or external .git or $GIT_DIR directories.

Note that $GIT_DIR may point somewhere external (and not be called .git), hence the need for further checking.

Put this in your .bashrc:

# Print the name of the git working tree's root directory
function git_root() {
  local root first_commit
  # git displays its own error if not in a repository
  root=$(git rev-parse --show-toplevel) || return
  if [[ -n $root ]]; then
    echo $root
    return
  elif [[ $(git rev-parse --is-inside-git-dir) = true ]]; then
    # We're inside the .git directory
    # Store the commit id of the first commit to compare later
    # It's possible that $GIT_DIR points somewhere not inside the repo
    first_commit=$(git rev-list --parents HEAD | tail -1) ||
      echo "$0: Can't get initial commit" 2>&1 && false && return
    root=$(git rev-parse --git-dir)/.. &&
      # subshell so we don't change the user's working directory
    ( cd "$root" &&
      if [[ $(git rev-list --parents HEAD | tail -1) = $first_commit ]]; then
        pwd
      else
        echo "$FUNCNAME: git directory is not inside its repository" 2>&1
        false
      fi
    )
  else
    echo "$FUNCNAME: Can't determine repository root" 2>&1
    false
  fi
}

# Change working directory to git repository root
function cd_git_root() {
  local root
  root=$(git_root) || return 1  # git_root will print any errors
  cd "$root"
}

Execute it by typing git_root (after restarting your shell: exec bash)