Programs & Examples On #Iis modules

align an image and some text on the same line without using div width?

Try

<p>Click on <img src="/storage/help/button2.1.png" width="auto" 
height="28"align="middle"/> button will show a page as bellow</p>

It works for me

How to check if a row exists in MySQL? (i.e. check if an email exists in MySQL)

After validation and before INSERT check if username already exists, using mysqli(procedural). This works:

//check if username already exists
       include 'phpscript/connect.php'; //connect to your database

       $sql = "SELECT username FROM users WHERE username = '$username'";
       $result = $conn->query($sql);

       if($result->num_rows > 0) {
           $usernameErr =  "username already taken"; //takes'em back to form
       } else { // go on to INSERT new record

PHP - Redirect and send data via POST

Another solution if you would like to avoid a curl call and have the browser redirect like normal and mimic a POST call:

save the post and do a temporary redirect:

function post_redirect($url) {
    $_SESSION['post_data'] = $_POST;
    header('Location: ' . $url);
}

Then always check for the session variable post_data:

if (isset($_SESSION['post_data'])) {
    $_POST = $_SESSION['post_data'];
    $_SERVER['REQUEST_METHOD'] = 'POST';
    unset($_SESSION['post_data']);
}

There will be some missing components such as the apache_request_headers() will not show a POST Content header, etc..

Making heatmap from pandas DataFrame

If you don't need a plot per say, and you're simply interested in adding color to represent the values in a table format, you can use the style.background_gradient() method of the pandas data frame. This method colorizes the HTML table that is displayed when viewing pandas data frames in e.g. the JupyterLab Notebook and the result is similar to using "conditional formatting" in spreadsheet software:

import numpy as np 
import pandas as pd


index= ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
cols = ['A', 'B', 'C', 'D']
df = pd.DataFrame(abs(np.random.randn(5, 4)), index=index, columns=cols)
df.style.background_gradient(cmap='Blues')

enter image description here

For detailed usage, please see the more elaborate answer I provided on the same topic previously and the styling section of the pandas documentation.

urllib2.HTTPError: HTTP Error 403: Forbidden

NSE website has changed and the older scripts are semi-optimum to current website. This snippet can gather daily details of security. Details include symbol, security type, previous close, open price, high price, low price, average price, traded quantity, turnover, number of trades, deliverable quantities and ratio of delivered vs traded in percentage. These conveniently presented as list of dictionary form.

Python 3.X version with requests and BeautifulSoup

from requests import get
from csv import DictReader
from bs4 import BeautifulSoup as Soup
from datetime import date
from io import StringIO 

SECURITY_NAME="3MINDIA" # Change this to get quote for another stock
START_DATE= date(2017, 1, 1) # Start date of stock quote data DD-MM-YYYY
END_DATE= date(2017, 9, 14)  # End date of stock quote data DD-MM-YYYY


BASE_URL = "https://www.nseindia.com/products/dynaContent/common/productsSymbolMapping.jsp?symbol={security}&segmentLink=3&symbolCount=1&series=ALL&dateRange=+&fromDate={start_date}&toDate={end_date}&dataType=PRICEVOLUMEDELIVERABLE"




def getquote(symbol, start, end):
    start = start.strftime("%-d-%-m-%Y")
    end = end.strftime("%-d-%-m-%Y")

    hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
         'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
         'Referer': 'https://cssspritegenerator.com',
         'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
         'Accept-Encoding': 'none',
         'Accept-Language': 'en-US,en;q=0.8',
         'Connection': 'keep-alive'}

    url = BASE_URL.format(security=symbol, start_date=start, end_date=end)
    d = get(url, headers=hdr)
    soup = Soup(d.content, 'html.parser')
    payload = soup.find('div', {'id': 'csvContentDiv'}).text.replace(':', '\n')
    csv = DictReader(StringIO(payload))
    for row in csv:
        print({k:v.strip() for k, v in row.items()})


 if __name__ == '__main__':
     getquote(SECURITY_NAME, START_DATE, END_DATE)

Besides this is relatively modular and ready to use snippet.

A fatal error has been detected by the Java Runtime Environment: SIGSEGV, libjvm

add new server (tomcat) with different location. if i am not make mistake you are run multiple project with same tomcat and add same tomcat server on same location ..

add new tomcat for each new workspace.

What is the difference between Multiple R-squared and Adjusted R-squared in a single-variate least squares regression?

The "adjustment" in adjusted R-squared is related to the number of variables and the number of observations.

If you keep adding variables (predictors) to your model, R-squared will improve - that is, the predictors will appear to explain the variance - but some of that improvement may be due to chance alone. So adjusted R-squared tries to correct for this, by taking into account the ratio (N-1)/(N-k-1) where N = number of observations and k = number of variables (predictors).

It's probably not a concern in your case, since you have a single variate.

Some references:

  1. How high, R-squared?
  2. Goodness of fit statistics
  3. Multiple regression
  4. Re: What is "Adjusted R^2" in Multiple Regression

Get the content of a sharepoint folder with Excel VBA

I spent some time on this very problem - I was trying to verify a file existed before opening it.

Eventually, I came up with a solution using XML and SOAP - use the EnumerateFolder method and pull in an XML response with the folder's contents.

I blogged about it here.

How do I get the height of a div's full content with jQuery?

scrollHeight is a property of a DOM object, not a function:

Height of the scroll view of an element; it includes the element padding but not its margin.

Given this:

<div id="x" style="height: 100px; overflow: hidden;">
    <div style="height: 200px;">
        pancakes
    </div>
</div>

This yields 200:

$('#x')[0].scrollHeight

For example: http://jsfiddle.net/ambiguous/u69kQ/2/ (run with the JavaScript console open).

C# find biggest number

You can use the Math.Max method to return the maximum of two numbers, e.g. for int:

int maximum = Math.Max(number1, Math.Max(number2, number3))

There ist also the Max() method from LINQ which you can use on any IEnumerable.

Could not connect to SMTP host: localhost, port: 25; nested exception is: java.net.ConnectException: Connection refused: connect

The mail server on CentOS 6 and other IPv6 capable server platforms may be bound to IPv6 localhost (::1) instead of IPv4 localhost (127.0.0.1).

Typical symptoms:

[root@host /]# telnet 127.0.0.1 25
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused

[root@host /]# telnet localhost 25
Trying ::1...
Connected to localhost.
Escape character is '^]'.
220 host ESMTP Exim 4.72 Wed, 14 Aug 2013 17:02:52 +0100

[root@host /]# netstat -plant | grep 25
tcp        0      0 :::25                       :::*                        LISTEN      1082/exim           

If this happens, make sure that you don't have two entries for localhost in /etc/hosts with different IP addresses, like this (bad) example:

[root@host /]# cat /etc/hosts
127.0.0.1 localhost.localdomain localhost localhost4.localdomain4 localhost4
::1       localhost localhost.localdomain localhost6 localhost6.localdomain6

To avoid confusion, make sure you only have one entry for localhost, preferably an IPv4 address, like this:

[root@host /]# cat /etc/hosts
127.0.0.1 localhost  localhost.localdomain   localhost4.localdomain4 localhost4
::1       localhost6 localhost6.localdomain6

Where can I download mysql jdbc jar from?

Here's a one-liner using Maven:

mvn dependency:get -Dartifact=mysql:mysql-connector-java:5.1.38

Then, with default settings, it's available in:

$HOME/.m2/repository/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38.jar

Just replace the version number if you need a different one.

Declare a dictionary inside a static class

OK - so I'm working in ASP 2.x (not my choice...but hey who's bitching?).

None of the initialize Dictionary examples would work. Then I came across this: http://kozmic.pl/archive/2008/03/13/framework-tips-viii-initializing-dictionaries-and-collections.aspx

...which hipped me to the fact that one can't use collections initialization in ASP 2.x.

How to create JSON object using jQuery

Just put your data into an Object like this:

var myObject = new Object();
myObject.name = "John";
myObject.age = 12;
myObject.pets = ["cat", "dog"];

Afterwards stringify it via:

var myString = JSON.stringify(myObject);

You don't need jQuery for this. It's pure JS.

Java 8 stream's .min() and .max(): why does this compile?

Apart from the information given by David M. Lloyd one could add that the mechanism that allows this is called target typing.

The idea is that the type the compiler assigns to a lambda expressions or a method references does not depend only on the expression itself, but also on where it is used.

The target of an expression is the variable to which its result is assigned or the parameter to which its result is passed.

Lambda expressions and method references are assigned a type which matches the type of their target, if such a type can be found.

See the Type Inference section in the Java Tutorial for more information.

Image scaling causes poor quality in firefox/internet explorer but not chrome

Seems Chrome downscaling is best but the real question is why use such a massive image on the web if you use show is so massively scaled down? Downloadtimes as seen on the test page above are terrible. Especially for responsive websites a certain amount of scaling makes sense, actually more a scale up than scale down though. But never in such a (sorry pun) scale.

Seems this is more a theoretical problem which Chrome seems to deal with nicely but actually should not happen and actually should not be used in practice IMHO.

var.replace is not a function

You should probably do some validations before you actually execute your function :

function trim(str) {
    if(typeof str !== 'string') {
        throw new Error('only string parameter supported!');
    }

    return str.replace(/^\s+|\s+$/g,'');
}

How to View Oracle Stored Procedure using SQLPlus?

check your casing, the name is typically stored in upper case

SELECT * FROM all_source WHERE name = 'DAILY_UPDATE' ORDER BY TYPE, LINE;

How to download files using axios

The function to make the API call with axios:

  function getFileToDownload (apiUrl) {
     return axios.get(apiUrl, {
       responseType: 'arraybuffer',
       headers: {
         'Content-Type': 'application/json'
       }
     })
  }

Call the function and then download the excel file you get:

getFileToDownload('putApiUrlHere')
  .then (response => {
      const type = response.headers['content-type']
      const blob = new Blob([response.data], { type: type, encoding: 'UTF-8' })
      const link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      link.download = 'file.xlsx'
      link.click()
  })

How to return a specific element of an array?

Make sure return type of you method is same what you want to return. Eg: `

  public int get(int[] r)
  {
     return r[0];
  }

`

Note : return type is int, not int[], so it is able to return int.

In general, prototype can be

public Type get(Type[] array, int index)
{
    return array[index];
}

npm start error with create-react-app

Yes you should not install react-scripts globally, it will not work.

I think i didn't use the --save when i first created the project (on another machine), so for me this fixed the problem :

npm install --save react react-dom react-scripts

Efficient way to Handle ResultSet in Java

public static List<HashMap<Object, Object>> GetListOfDataFromResultSet(ResultSet rs) throws SQLException {
        ResultSetMetaData metaData = rs.getMetaData();
        int count = metaData.getColumnCount();
        String[] columnName = new String[count];
        List<HashMap<Object,Object>> lst=new ArrayList<>();
        while(rs.next()) {
            HashMap<Object,Object> map=new HashMap<>();
            for (int i = 1; i <= count; i++){
                   columnName[i-1] = metaData.getColumnLabel(i);
                   map.put(columnName[i-1], rs.getObject(i));
            }
            lst.add(map);

        }
        return lst;
    }

What is the shortest function for reading a cookie by name in JavaScript?

code from google analytics ga.js

function c(a){
    var d=[],
        e=document.cookie.split(";");
    a=RegExp("^\\s*"+a+"=\\s*(.*?)\\s*$");
    for(var b=0;b<e.length;b++){
        var f=e[b].match(a);
        f&&d.push(f[1])
    }
    return d
}

How to overplot a line on a scatter plot in python?

plt.plot(X_plot, X_plot*results.params[0] + results.params[1])

versus

plt.plot(X_plot, X_plot*results.params[1] + results.params[0])

C++ multiline string literal

// C++11. 
std::string index_html=R"html(
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>VIPSDK MONITOR</title>
    <meta http-equiv="refresh" content="10">
</head>
<style type="text/css">
</style>
</html>
)html";

SVN change username

You could ask your colleague to create a patch, which will collapse all the changes that have been made into a single file that you can apply to your own check out. This will update all of your files appropriately and then you can revert the changes on his side and check yours in.

DELETE_FAILED_INTERNAL_ERROR Error while Installing APK

Below solution worked for my Xiaomi mobile phone:

Go to Settings -> Additional settings -> Developer options and check Install via USB, if toast The device is temporarily restricted shown, please turn your WI-FI off, turn on mobile data. Then try it again.

If A.S. Instance Run is still not work when you finished all steps above, perhaps you turned on MIUI optimization, please follow below step and try again:

Settings -> Additional settings -> Developer options and uncheck Turn on MIUI optimization

How to iterate over the files of a certain directory, in Java?

If you have the directory name in myDirectoryPath,

import java.io.File;
...
  File dir = new File(myDirectoryPath);
  File[] directoryListing = dir.listFiles();
  if (directoryListing != null) {
    for (File child : directoryListing) {
      // Do something with child
    }
  } else {
    // Handle the case where dir is not really a directory.
    // Checking dir.isDirectory() above would not be sufficient
    // to avoid race conditions with another process that deletes
    // directories.
  }

What is a raw type and why shouldn't we use it?

What is a raw type and why do I often hear that they shouldn't be used in new code?

A "raw type" is the use of a generic class without specifying a type argument(s) for its parameterized type(s), e.g. using List instead of List<String>. When generics were introduced into Java, several classes were updated to use generics. Using these class as a "raw type" (without specifying a type argument) allowed legacy code to still compile.

"Raw types" are used for backwards compatibility. Their use in new code is not recommended because using the generic class with a type argument allows for stronger typing, which in turn may improve code understandability and lead to catching potential problems earlier.

What is the alternative if we can't use raw types, and how is it better?

The preferred alternative is to use generic classes as intended - with a suitable type argument (e.g. List<String>). This allows the programmer to specify types more specifically, conveys more meaning to future maintainers about the intended use of a variable or data structure, and it allows compiler to enforce better type-safety. These advantages together may improve code quality and help prevent the introduction of some coding errors.

For example, for a method where the programmer wants to ensure a List variable called 'names' contains only Strings:

List<String> names = new ArrayList<String>();
names.add("John");          // OK
names.add(new Integer(1));  // compile error

Checking if a variable is defined?

Use defined? YourVariable
Keep it simple silly .. ;)

jQuery: Check if div with certain class name exists

check if the div exists with a certain class

if ($(".mydivclass").length > 0) //it exists 
{

}

Reading/parsing Excel (xls) files with Python

I think Pandas is the best way to go. There is already one answer here with Pandas using ExcelFile function, but it did not work properly for me. From here I found the read_excel function which works just fine:

import pandas as pd
dfs = pd.read_excel("your_file_name.xlsx", sheet_name="your_sheet_name")
print(dfs.head(10))

P.S. You need to have the xlrd installed for read_excel function to work

Update 21-03-2020: As you may see here, there are issues with the xlrd engine and it is going to be deprecated. The openpyxl is the best replacement. So as described here, the canonical syntax should be:

dfs = pd.read_excel("your_file_name.xlsx", sheet_name="your_sheet_name", engine="openpyxl")

Programmatically set the initial view controller using Storyboards

UPDATED ANSWER for iOS 13 and scene delegate:

make sure in your info.plist file you go into Application Scene Manifest -> Scene Configuration -> Application Session Role -> Item 0 and delete the reference to the main storyboard there as well. Otherwise you'll get the same warning about failing to instantiate from storyboard.

Also, move the code from the app delegate to the scene delegate method scene(_:willConnectTo:options:), since this is where life cycle events are handled now.

Better way to convert file sizes in Python

I wanted 2 way conversion, and I wanted to use Python 3 format() support to be most pythonic. Maybe try datasize library module? https://pypi.org/project/datasize/

$ pip install -qqq datasize
$ python
...
>>> from datasize import DataSize
>>> 'My new {:GB} SSD really only stores {:.2GiB} of data.'.format(DataSize('750GB'),DataSize(DataSize('750GB') * 0.8))
'My new 750GB SSD really only stores 558.79GiB of data.'

How to use lifecycle method getDerivedStateFromProps as opposed to componentWillReceiveProps

About the removal of componentWillReceiveProps: you should be able to handle its uses with a combination of getDerivedStateFromProps and componentDidUpdate, see the React blog post for example migrations. And yes, the object returned by getDerivedStateFromProps updates the state similarly to an object passed to setState.

In case you really need the old value of a prop, you can always cache it in your state with something like this:

state = {
  cachedSomeProp: null
  // ... rest of initial state
};

static getDerivedStateFromProps(nextProps, prevState) {
  // do things with nextProps.someProp and prevState.cachedSomeProp
  return {
    cachedSomeProp: nextProps.someProp,
    // ... other derived state properties
  };
}

Anything that doesn't affect the state can be put in componentDidUpdate, and there's even a getSnapshotBeforeUpdate for very low-level stuff.

UPDATE: To get a feel for the new (and old) lifecycle methods, the react-lifecycle-visualizer package may be helpful.

Finding all objects that have a given property inside a collection

Guava has a very powerful searching capabilities when it comes to such type of problems. For example, if your area searching an object based on one of it properties you may consider:

Iterables.tryFind(listOfCats, new Predicate<Cat>(){
    @Override
    boolean apply(@Nullable Cat input) {
        return "tom".equalsIgnoreCase(input.name());
    }
}).or(new Cat("Tom"));

in case it's possible that the Tom cat is not in the listOfCats, it will be returned, thus allowing you to avoid NPE.

Can HTML be embedded inside PHP "if" statement?

Yes.

<?  if($my_name == 'someguy') { ?>
        HTML_GOES_HERE
<?  } ?>

jQuery: Load Modal Dialog Contents via Ajax

<button class="btn" onClick="openDialog('New Type','Sample.html')">Middle</button>

<script type="text/javascript">
    function openDialog(title,url) {
        $('.opened-dialogs').dialog("close");

        $('<div class="opened-dialogs">').html('loading...').dialog({
            position:  ['center',20],
            open: function () {
                $(this).load(url);

            },
            close: function(event, ui) {
                    $(this).remove();
            },

            title: title,
            minWidth: 600            
        });

        return false;
    }
</script>

How do I initialize the base (super) class?

As of python 3.5.2, you can use:

class C(B):
def method(self, arg):
    super().method(arg)    # This does the same thing as:
                           # super(C, self).method(arg)

https://docs.python.org/3/library/functions.html#super

Escaping quotation marks in PHP

Use the addslashes function:

 $str = "Is your name O'Reilly?";

 // Outputs: Is your name O\'Reilly?
   echo addslashes($str);

Gulp error: The following tasks did not complete: Did you forget to signal async completion?

For me the issue was different: Angular-cli was not installed (I installed a new Node version using NVM and simply forgot to reinstall angular cli)

You can check running "ng version".

If you don't have it just run "npm install -g @angular/cli"

ERROR: SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it

if you are using XAMPP and WAMP together in the same machine add sql server port number

<connection>
                <host><![CDATA[localhost:3390]]></host>
                <username><![CDATA[root]]></username>
                <password><![CDATA[]]></password>
                <dbname><![CDATA[sritoss_1910]]></dbname>
                <initStatements><![CDATA[SET NAMES utf8]]></initStatements>
                <model><![CDATA[mysql4]]></model>
                <type><![CDATA[pdo_mysql]]></type>
                <pdoType><![CDATA[]]></pdoType>
                <active>1</active>
</connection>

Take a full page screenshot with Firefox on the command-line

Firefox Screenshots is a new tool that ships with Firefox. It is not a developer tool, it is aimed at end-users of the browser.

To take a screenshot, click on the page actions menu in the address bar, and click "take a screenshot". If you then click "Save full page", it will save the full page, scrolling for you.


(source: mozilla.net)

How to identify if a webpage is being loaded inside an iframe or directly into the browser window?

Following on what @magnoz was saying, here is a code implementation of his answer.

constructor() {
    let windowLen = window.frames.length;
    let parentLen = parent.frames.length;

    if (windowLen == 0 && parentLen >= 1) {
        this.isInIframe = true
        console.log('Is in Iframe!')
    } else {
        console.log('Is in main window!')
    }
}

How to open warning/information/error dialog in Swing?

Just complementing: It's kind of obvious, but you can use static imports to give you a hand, like this:

import static javax.swing.JOptionPane.*;

public class SimpleDialog(){
    public static void main(String argv[]) {
        showMessageDialog(null, "Message", "Title", ERROR_MESSAGE);
    }
}

Add element to a list In Scala

You are using an immutable list. The operations on the List return a new List. The old List remains unchanged. This can be very useful if another class / method holds a reference to the original collection and is relying on it remaining unchanged. You can either use different named vals as in

val myList1 = 1.0 :: 5.5 :: Nil 
val myList2 = 2.2 :: 3.7 :: mylist1

or use a var as in

var myList = 1.0 :: 5.5 :: Nil 
myList :::= List(2.2, 3.7)

This is equivalent syntax for:

myList = myList.:::(List(2.2, 3.7))

Or you could use one of the mutable collections such as

val myList = scala.collection.mutable.MutableList(1.0, 5.5)
myList.++=(List(2.2, 3.7))

Not to be confused with the following that does not modify the original mutable List, but returns a new value:

myList.++:(List(2.2, 3.7))

However you should only use mutable collections in performance critical code. Immutable collections are much easier to reason about and use. One big advantage is that immutable List and scala.collection.immutable.Vector are Covariant. Don't worry if that doesn't mean anything to you yet. The advantage of it is you can use it without fully understanding it. Hence the collection you were using by default is actually scala.collection.immutable.List its just imported for you automatically.

I tend to use List as my default collection. From 2.12.6 Seq defaults to immutable Seq prior to this it defaulted to immutable.

console.writeline and System.out.println

They're essentially the same, if your program is run from an interactive prompt and you haven't redirected stdin or stdout:

public class ConsoleTest {
    public static void main(String[] args) {
        System.out.println("Console is: " + System.console());
    }
}

results in:

$ java ConsoleTest
Console is: java.io.Console@2747ee05
$ java ConsoleTest </dev/null
Console is: null
$ java ConsoleTest | cat
Console is: null

The reason Console exists is to provide features that are useful in the specific case that you're being run from an interactive command line:

  • secure password entry (hard to do cross-platform)
  • synchronisation (multiple threads can prompt for input and Console will queue them up nicely, whereas if you used System.in/out then all of the prompts would appear simultaneously).

Notice above that redirecting even one of the streams results in System.console() returning null; another irritation is that there's often no Console object available when spawned from another program such as Eclipse or Maven.

Extract text from a string

Using -replace

 $string = '% O0033(SUB RAD MSD 50R III) G91G1X-6.4Z-2.F500 G3I6.4Z-8.G3I6.4 G3R3.2X6.4F500 G91G0Z5. G91G1X-10.4 G3I10.4 G3R5.2X10.4 G90G0Z2. M99 %'
 $program = $string -replace '^%\sO\d{4}\((.+?)\).+$','$1'
 $program

SUB RAD MSD 50R III

How to center a component in Material-UI and make it responsive?

With other answers used, xs='auto' did a trick for me.

<Grid container
    alignItems='center'
    justify='center'
    style={{ minHeight: "100vh" }}>

    <Grid item xs='auto'>
        <GoogleLogin
            clientId={process.env.REACT_APP_GOOGLE_CLIENT_ID}
            buttonText="Log in with Google"
            onSuccess={this.handleLogin}
            onFailure={this.handleLogin}
             cookiePolicy={'single_host_origin'}
         />
    </Grid>
</Grid>

The real difference between "int" and "unsigned int"

The printf function interprets the value that you pass it according to the format specifier in a matching position. If you tell printf that you pass an int, but pass unsigned instead, printf would re-interpret one as the other, and print the results that you see.

What is the difference between AF_INET and PF_INET in socket programming?

There are situations where it matters.

If you pass AF_INET to socket() in Cygwin, your socket may or may not be randomly reset. Passing PF_INET ensures that the connection works right.

Cygwin is self-admittedly a huge mess for socket programming, but it is a real world case where AF_INET and PF_INET are not identical.

How do I compile a Visual Studio project from the command-line?

To be honest I have to add my 2 cents.

You can do it with msbuild.exe. There are many version of the msbuild.exe.

C:\Windows\Microsoft.NET\Framework64\v2.0.50727\msbuild.exe C:\Windows\Microsoft.NET\Framework64\v3.5\msbuild.exe C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe
C:\Windows\Microsoft.NET\Framework\v2.0.50727\msbuild.exe C:\Windows\Microsoft.NET\Framework\v3.5\msbuild.exe C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe

Use version you need. Basically you have to use the last one.

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe

So how to do it.

  1. Run the COMMAND window

  2. Input the path to msbuild.exe

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe

  1. Input the path to the project solution like

"C:\Users\Clark.Kent\Documents\visual studio 2012\Projects\WpfApplication1\WpfApplication1.sln"

  1. Add any flags you need after the solution path.

  2. Press ENTER

Note you can get help about all possible flags like

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe /help

Creating virtual directories in IIS express

In answer to the further question -

"is there anyway to apply this within the Visual Studio project? In a multi-developer environment, if someone else check's out the code on their machine, then their local IIS Express wouldn't be configured with the virtual directory and cause runtime errors wouldn't it?"

I never found a consistant answer to this anywhere but then figured out you could do it with a post build event using the XmlPoke task in the project file for the website -

<Target Name="AfterBuild">
    <!-- Get the local directory root (and strip off the website name) -->
    <PropertyGroup>
        <LocalTarget>$(ProjectDir.Replace('MyWebSite\', ''))</LocalTarget>
    </PropertyGroup>

    <!-- Now change the virtual directories as you need to -->
    <XmlPoke XmlInputPath="..\..\Source\Assemblies\MyWebSite\.vs\MyWebSite\config\applicationhost.config" 
        Value="$(LocalTarget)AnotherVirtual" 
        Query="/configuration/system.applicationHost/sites/site[@name='MyWebSite']/application[@path='/']/virtualDirectory[@path='/AnotherVirtual']/@physicalPath"/>
</Target>

You can use this technique to repoint anything in the file before IISExpress starts up. This would allow you to initially force an applicationHost.config file into GIT (assuming it is ignored by gitignore) then subsequently repoint all the paths at build time. GIT will ignore any changes to the file so it's now easy to share them around.

In answer to the futher question about adding other applications under one site:

You can create the site in your application hosts file just like the one on your server. For example:

  <site name="MyWebSite" id="2">
    <application path="/" applicationPool="Clr4IntegratedAppPool">
      <virtualDirectory path="/" physicalPath="C:\GIT\MyWebSite\Main" />
      <virtualDirectory path="/SharedContent" physicalPath="C:\GIT\SharedContent" />
      <virtualDirectory path="/ServerResources" physicalPath="C:\GIT\ServerResources" />
    </application>
    <application path="/AppSubSite" applicationPool="Clr4IntegratedAppPool">
      <virtualDirectory path="/" physicalPath="C:\GIT\AppSubSite\" />
      <virtualDirectory path="/SharedContent" physicalPath="C:\GIT\SharedContent" />
      <virtualDirectory path="/ServerResources" physicalPath="C:\GIT\ServerResources" />
    </application>
    <bindings>
      <binding protocol="http" bindingInformation="*:4076:localhost" />
    </bindings>
  </site>

Then use the above technique to change the folder locations at build time.

Hide all warnings in ipython

I eventually figured it out. Place:

import warnings
warnings.filterwarnings('ignore')

inside ~/.ipython/profile_default/startup/disable-warnings.py. I'm leaving this question and answer for the record in case anyone else comes across the same issue.

Quite often it is useful to see a warning once. This can be set by:

warnings.filterwarnings(action='once')

Docker Repository Does Not Have a Release File on Running apt-get update on Ubuntu

As suggested in official docker document also. Try running this:

  • sudo vi /etc/apt/sources.list

Then remove/comment any (deb [arch=amd64] https://download.docker.com/linux/ubuntu/ xenial stable) such entry at the last lines of the file.

Then in terminal run this command:

  • sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu/ bionic stable"

  • sudo apt-get update

It worked in my case.

Set value of textbox using JQuery

1) you are calling it wrong way try:

$(input[name="searchBar"]).val('hi')

2) if it doesn't work call your .js file at the end of the page or trigger your function on document.ready event

$(document).ready(function() {
  $(input[name="searchBar"]).val('hi');
});

Twitter Bootstrap Button Text Word Wrap

Try this: add white-space: normal; to the style definition of the Bootstrap Button or you can replace the code you displayed with the one below

<div class="col-lg-3"> <!-- FIRST COL -->
  <div class="panel panel-default">
    <div class="panel-body"> 
    <h4>Posted on</h4>
    <p>22nd September 2013</p>
    <h4>Tags</h4>
    <a href="#" class="btn btn-primary btn-xs col-lg-12" style="margin-bottom:4px;white-space: normal;">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</a>
   <a href="#" class="btn btn-primary btn-xs col-lg-12" style="margin-bottom:4px;white-space: normal;">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</a>
   <a href="#" class="btn btn-primary btn-xs col-lg-12" style="margin-bottom:4px;white-space: normal;">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</a>
           </div>
  </div>
</div>

I have updated your fiddle here to show how it comes out.

Dynamic WHERE clause in LINQ

I came up with a solution that even I can understand... by using the 'Contains' method you can chain as many WHERE's as you like. If the WHERE is an empty string, it's ignored (or evaluated as a select all). Here is my example of joining 2 tables in LINQ, applying multiple where clauses and populating a model class to be returned to the view. (this is a select all).

public ActionResult Index()
    {
        string AssetGroupCode = "";
        string StatusCode = "";
        string SearchString = "";

        var mdl = from a in _db.Assets
                  join t in _db.Tags on a.ASSETID equals t.ASSETID
                  where a.ASSETGROUPCODE.Contains(AssetGroupCode)
                  && a.STATUSCODE.Contains(StatusCode)
                  && (
                  a.PO.Contains(SearchString)
                  || a.MODEL.Contains(SearchString)
                  || a.USERNAME.Contains(SearchString)
                  || a.LOCATION.Contains(SearchString)
                  || t.TAGNUMBER.Contains(SearchString)
                  || t.SERIALNUMBER.Contains(SearchString)
                  )
                  select new AssetListView
                  {
                      AssetId = a.ASSETID,
                      TagId = t.TAGID,
                      PO = a.PO,
                      Model = a.MODEL,
                      UserName = a.USERNAME,
                      Location = a.LOCATION,
                      Tag = t.TAGNUMBER,
                      SerialNum = t.SERIALNUMBER
                  };


        return View(mdl);
    }

How to get Chrome to allow mixed content?

running the following command helps me running https web-page, with iframe which has ws (unsecured) connection

chrome.exe --user-data-dir=c:\temp-chrome --disable-web-security --allow-running-insecure-content

How to import RecyclerView for Android L-preview

The steps before me are just missing one step.

After altering the build.gradle (Module:app) and adding the following dependencies:

compile 'com.android.support:cardview-v7:21.0.+'
compile 'com.android.support:recyclerview-v7:21.0.+'

(Add cardview if necessary)

You must then must go to Build > Clean Project to get rid of any errors

Converting a SimpleXML Object to an Array

I found this in the PHP manual comments:

/**
 * function xml2array
 *
 * This function is part of the PHP manual.
 *
 * The PHP manual text and comments are covered by the Creative Commons 
 * Attribution 3.0 License, copyright (c) the PHP Documentation Group
 *
 * @author  k dot antczak at livedata dot pl
 * @date    2011-04-22 06:08 UTC
 * @link    http://www.php.net/manual/en/ref.simplexml.php#103617
 * @license http://www.php.net/license/index.php#doc-lic
 * @license http://creativecommons.org/licenses/by/3.0/
 * @license CC-BY-3.0 <http://spdx.org/licenses/CC-BY-3.0>
 */
function xml2array ( $xmlObject, $out = array () )
{
    foreach ( (array) $xmlObject as $index => $node )
        $out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;

    return $out;
}

It could help you. However, if you convert XML to an array you will loose all attributes that might be present, so you cannot go back to XML and get the same XML.

How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function?

I was facing the same issue, here is line from error

File "/usr/lib/python3/dist-packages/numpy/lib/npyio.py", line 260, in __getitem__

So i solve the issue by updating "npyio.py" file. In npyio.py line 196 assigning value to allow_pickle so i update this line as

self.allow_pickle = True

How to capture Enter key press?

You need to create a handler for the onkeypress action.

HTML

<input name="keywords" type="text" id="keywords" size="50" onkeypress="handleEnter(this, event)" />

JS

function handleEnter(inField, e)
{
    var charCode;

    //Get key code (support for all browsers)
    if(e && e.which)
    {
        charCode = e.which;
    }
    else if(window.event)
    {
        e = window.event;
        charCode = e.keyCode;
    }

    if(charCode == 13)
    {
       //Call your submit function
    }
}

Passing Arrays to Function in C++

The syntaxes

int[]

and

int[X] // Where X is a compile-time positive integer

are exactly the same as

int*

when in a function parameter list (I left out the optional names).

Additionally, an array name decays to a pointer to the first element when passed to a function (and not passed by reference) so both int firstarray[3] and int secondarray[5] decay to int*s.

It also happens that both an array dereference and a pointer dereference with subscript syntax (subscript syntax is x[y]) yield an lvalue to the same element when you use the same index.

These three rules combine to make the code legal and work how you expect; it just passes pointers to the function, along with the length of the arrays which you cannot know after the arrays decay to pointers.

Is there any WinSCP equivalent for linux?

scp file user@host:/path/on/host

How to find the number of days between two dates

If you are using MySQL there is the DATEDIFF function which calculate the days between two dates:

SELECT dtCreated
    , bActive
    , dtLastPaymentAttempt
    , dtLastUpdated
    , dtLastVisit
    , DATEDIFF(dtLastUpdated, dtCreated) as Difference
FROM Customers
WHERE (bActive = 'true') 
    AND (dtLastUpdated > CONVERT(DATETIME, '2012-01-0100:00:00', 102))

How to delete a workspace in Perforce (using p4v)?

If you have successfully deleted from workspace tab but still it is showing in drop down menu. Then also you can successfully remove that by following these steps:

  1. Go to C:/Users/user_name/.p4qt

user_name will be your username of your computer

  1. Inside 001Clients folder WorkspaceSettings.xml file will be there.

There will be two tag

  1. varName = "RecentlyUsedWorkspaces" remove the deleted workspace tag

  2. A propertyList tag will be there with varName=deleted_workspace_name delete that tag.

from drop down menu workspace name will be deleted

How to show an empty view with a RecyclerView?

One more way is to use addOnChildAttachStateChangeListener which handles appearing/disappearing child views in RecyclerView.

recyclerView.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
            @Override
            public void onChildViewAttachedToWindow(@NonNull View view) {
                forEmptyTextView.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onChildViewDetachedFromWindow(@NonNull View view) {
                forEmptyTextView.setVisibility(View.VISIBLE);
            }
        });

Check if a time is between two times (time DataType)

This should also work (even in SQL-Server 2005):

SELECT *
FROM dbo.MyTable
WHERE Created >= DATEADD(hh,23,DATEADD(day, DATEDIFF(day, 0, Created - 1), 0))
  AND Created <  DATEADD(hh,7,DATEADD(day, DATEDIFF(day, 0, Created), 0))

DEMO

Pandas get the most frequent values of a column

Not Obvious, But Fast

f, u = pd.factorize(df.name.values)
counts = np.bincount(f)
u[counts == counts.max()]

array(['alex', 'helen'], dtype=object)

How to reload current page in ReactJS?

You can use window.location.reload(); in your componentDidMount() lifecycle method. If you are using react-router, it has a refresh method to do that.

Edit: If you want to do that after a data update, you might be looking to a re-render not a reload and you can do that by using this.setState(). Here is a basic example of it to fire a re-render after data is fetched.

import React from 'react'

const ROOT_URL = 'https://jsonplaceholder.typicode.com';
const url = `${ROOT_URL}/users`;

class MyComponent extends React.Component {
    state = {
        users: null
    }
    componentDidMount() {
        fetch(url)
            .then(response => response.json())
            .then(users => this.setState({users: users}));
    }
    render() {
        const {users} = this.state;
        if (users) {
            return (
                <ul>
                    {users.map(user => <li>{user.name}</li>)}
                </ul>
            )
        } else {
            return (<h1>Loading ...</h1>)
        }
    }
}

export default MyComponent;

Threading pool similar to the multiprocessing Pool?

I just found out that there actually is a thread-based Pool interface in the multiprocessing module, however it is hidden somewhat and not properly documented.

It can be imported via

from multiprocessing.pool import ThreadPool

It is implemented using a dummy Process class wrapping a python thread. This thread-based Process class can be found in multiprocessing.dummy which is mentioned briefly in the docs. This dummy module supposedly provides the whole multiprocessing interface based on threads.

how to loop through each row of dataFrame in pyspark

If you want to do something to each row in a DataFrame object, use map. This will allow you to perform further calculations on each row. It's the equivalent of looping across the entire dataset from 0 to len(dataset)-1.

Note that this will return a PipelinedRDD, not a DataFrame.

javascript function wait until another function to finish

There are several ways I can think of to do this.

Use a callback:

 function FunctInit(someVarible){
      //init and fill screen
      AndroidCallGetResult();  // Enables Android button.
 }

 function getResult(){ // Called from Android button only after button is enabled
      //return some variables
 }

Use a Timeout (this would probably be my preference):

 var inited = false;
 function FunctInit(someVarible){
      //init and fill screen
      inited = true;
 }

 function getResult(){
      if (inited) {
           //return some variables
      } else {
           setTimeout(getResult, 250);
      }
 }

Wait for the initialization to occur:

 var inited = false;
 function FunctInit(someVarible){
      //init and fill screen
      inited = true;
 }

 function getResult(){
      var a = 1;
      do { a=1; }
      while(!inited);
      //return some variables
 }

How to get json key and value in javascript?

//By using jquery json parser    
var obj = $.parseJSON('{"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}');
alert(obj['jobtitel']);

//By using javasript json parser
var t = JSON.parse('{"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}');
alert(t['jobtitel'])

Check this jsfiddle

As of jQuery 3.0, $.parseJSON is deprecated. To parse JSON strings use the native JSON.parse method instead.

Source: http://api.jquery.com/jquery.parsejson/

How to use matplotlib tight layout with Figure?

Just call fig.tight_layout() as you normally would. (pyplot is just a convenience wrapper. In most cases, you only use it to quickly generate figure and axes objects and then call their methods directly.)

There shouldn't be a difference between the QtAgg backend and the default backend (or if there is, it's a bug).

E.g.

import matplotlib.pyplot as plt

#-- In your case, you'd do something more like:
# from matplotlib.figure import Figure
# fig = Figure()
#-- ...but we want to use it interactive for a quick example, so 
#--    we'll do it this way
fig, axes = plt.subplots(nrows=4, ncols=4)

for i, ax in enumerate(axes.flat, start=1):
    ax.set_title('Test Axes {}'.format(i))
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')

plt.show()

Before Tight Layout

enter image description here

After Tight Layout

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=4, ncols=4)

for i, ax in enumerate(axes.flat, start=1):
    ax.set_title('Test Axes {}'.format(i))
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')

fig.tight_layout()

plt.show()

enter image description here

'sudo gem install' or 'gem install' and gem locations

Installing Ruby gems on a Mac is a common source of confusion and frustration. Unfortunately, most solutions are incomplete, outdated, and provide bad advice. I'm glad the accepted answer here says to NOT use sudo, which you should never need to do, especially if you don't understand what it does. While I used RVM years ago, I would recommend chruby in 2020.

Some of the other answers here provide alternative options for installing gems, but they don't mention the limitations of those solutions. What's missing is an explanation and comparison of the various options and why you might choose one over the other. I've attempted to cover most common scenarios in my definitive guide to installing Ruby gems on a Mac.

Please initialize the log4j system properly. While running web service

If you are using Logger.getLogger(ClassName.class) then place your log4j.properties file in your class path:

yourproject/javaresoures/src/log4j.properties (Put inside src folder)

Using Vim's tabs like buffers

Vim :help window explains the confusion "tabs vs buffers" pretty well.

A buffer is the in-memory text of a file.
A window is a viewport on a buffer.
A tab page is a collection of windows.

Opening multiple files is achieved in vim with buffers. In other editors (e.g. notepad++) this is done with tabs, so the name tab in vim maybe misleading.

Windows are for the purpose of splitting the workspace and displaying multiple files (buffers) together on one screen. In other editors this could be achieved by opening multiple GUI windows and rearranging them on the desktop.

Finally in this analogy vim's tab pages would correspond to multiple desktops, that is different rearrangements of windows.

As vim help: tab-page explains a tab page can be used, when one wants to temporarily edit a file, but does not want to change anything in the current layout of windows and buffers. In such a case another tab page can be used just for the purpose of editing that particular file.

Of course you have to remember that displaying the same file in many tab pages or windows would result in displaying the same working copy (buffer).

Storing a file in a database as opposed to the file system?

We made the decision to store as varbinary for http://www.freshlogicstudios.com/Products/Folders/ halfway expecting performance issues. I can say that we've been pleasantly surprised at how well it's worked out.

Unable instantiate android.gms.maps.MapFragment

I faced the same problem ant it took me tow days to figure out a solution that worked for me :

  1. Delete the project google-play-services_lib (right click on the project delete )
  2. Delete the project containing the Google maps demo ( MainActivity in my case ) if you have one
  3. Copy the project google-play-services_lib( extras\google\google_play_services\libproject\google-play-services_lib) into your workspace then import it as General project (File->import->existing projects into workspase )
  4. Right click on your project ( in which you want to load the map ) -> Android -> add (under library ) google-play-services_lib

You should see something like this :

notice the

Note : You should not have something like this ( the project should be referred from your workspace ):

enter image description here

I think that the problem is that tow projects are referencing the same library

Is there any standard for JSON API response format?

The basic framework suggested looks fine, but the error object as defined is too limited. One often cannot use a single value to express the problem, and instead a chain of problems and causes is needed.

I did a little research and found that the most common format for returning error (exceptions) is a structure of this form:

{
   "success": false,
   "error": {
      "code": "400",
      "message": "main error message here",
      "target": "approx what the error came from",
      "details": [
         {
            "code": "23-098a",
            "message": "Disk drive has frozen up again.  It needs to be replaced",
            "target": "not sure what the target is"
         }
      ],
      "innererror": {
         "trace": [ ... ],
         "context": [ ... ]
      }
   }
}

This is the format proposed by the OASIS data standard OASIS OData and seems to be the most standard option out there, however there does not seem to be high adoption rates of any standard at this point. This format is consistent with the JSON-RPC specification.

You can find the complete open source library that implements this at: Mendocino JSON Utilities. This library supports the JSON Objects as well as the exceptions.

The details are discussed in my blog post on Error Handling in JSON REST API

ORACLE IIF Statement

In PL/SQL, there is a trick to use the undocumented OWA_UTIL.ITE function.

SET SERVEROUTPUT ON

DECLARE
    x   VARCHAR2(10);
BEGIN
    x := owa_util.ite('a' = 'b','T','F');
    dbms_output.put_line(x);
END;
/

F

PL/SQL procedure successfully completed.

Python argparse command line flags without arguments

Adding a quick snippet to have it ready to execute:

Source: myparser.py

import argparse
parser = argparse.ArgumentParser(description="Flip a switch by setting a flag")
parser.add_argument('-w', action='store_true')

args = parser.parse_args()
print args.w

Usage:

python myparser.py -w
>> True

iptables block access to port 8000 except from IP address

You can always use iptables to delete the rules. If you have a lot of rules, just output them using the following command.

iptables-save > myfile

vi to edit them from the commend line. Just use the "dd" to delete the lines you no longer want.

iptables-restore < myfile and you're good to go.  

REMEMBER THAT IF YOU DON'T CONFIGURE YOUR OS TO SAVE THE RULES TO A FILE AND THEN LOAD THE FILE DURING THE BOOT THAT YOUR RULES WILL BE LOST.

How to install an APK file on an Android phone?

outside device,we can use :

adb install file.apk

or adb install -r file.apk

  adb install [-l] [-r] [-s] [--algo <algorithm name> --key <hex-encoded key> --iv <hex-encoded iv>] <file>
                               - push this package file to the device and install it
                                 ('-l' means forward-lock the app)
                                 ('-r' means reinstall the app, keeping its data)
                                 ('-s' means install on SD card instead of internal storage)
                                 ('--algo', '--key', and '--iv' mean the file is encrypted already)

inside devices also, we can use:

pm install file.apk

or pm install -r file.apk

pm install: installs a package to the system.  Options:
    -l: install the package with FORWARD_LOCK.
    -r: reinstall an exisiting app, keeping its data.
    -t: allow test .apks to be installed.
    -i: specify the installer package name.
    -s: install package on sdcard.
    -f: install package on internal flash.
    -d: allow version code downgrade.

For more then one apk file on Linux we can use xargs and on windows we can use for loop.
Linux / Unix sample :

ls -1 *.apk | xargs -I xxx adb install -r xxx

android:layout_height 50% of the screen size

To achieve this feat, define a outer linear layout with a weightSum={amount of weight to distribute}.

it defines the maximum weight sum. If unspecified, the sum is computed by adding the layout_weight of all of the children. This can be used for instance to give a single child 50% of the total available space by giving it a layout_weight of 0.5 and setting the weightSum to 1.0.Another example would be set weightSum=2, and if the two children set layout_weight=1 then each would get 50% of the available space.

WeightSum is dependent on the amount of children in the parent layout.

Java converting int to hex and back again

As Integer.toHexString(byte/integer) is not working when you are trying to convert signed bytes like UTF-16 decoded characters you have to use:

Integer.toString(byte/integer, 16);

or

String.format("%02X", byte/integer);

reverse you can use

Integer.parseInt(hexString, 16);

Docker: Container keeps on restarting again on again

try running

docker stop CONTAINER_ID & docker rm -v CONTAINER_ID

Thanks

There is no argument given that corresponds to the required formal parameter - .NET Error

In the constructor of

 public class ErrorEventArg : EventArgs

You have to add "base" as follows:

    public ErrorEventArg(string errorMsg, string lastQuery) : base (string errorMsg, string lastQuery)
    {
        ErrorMsg = errorMsg;
        LastQuery = lastQuery;
    }

That solved it for me

Get list of a class' instance methods

TestClass.methods(false) 

to get only methods that belong to that class only.

TestClass.instance_methods(false) would return the methods from your given example (since they are instance methods of TestClass).

Getting the inputstream from a classpath resource (XML file)

Some of the "getResourceAsStream()" options in this answer didn't work for me, but this one did:

SomeClassWithinYourSourceDir.class.getClassLoader().getResourceAsStream("yourResource");

How to copy part of an array to another array in C#?

In case if you want to implement your own Array.Copy method.

Static method which is of generic type.

 static void MyCopy<T>(T[] sourceArray, long sourceIndex, T[] destinationArray, long destinationIndex, long copyNoOfElements)
 {
  long totaltraversal = sourceIndex + copyNoOfElements;
  long sourceArrayLength = sourceArray.Length;

  //to check all array's length and its indices properties before copying
  CheckBoundaries(sourceArray, sourceIndex, destinationArray, copyNoOfElements, sourceArrayLength);
   for (long i = sourceIndex; i < totaltraversal; i++)
     {
      destinationArray[destinationIndex++] = sourceArray[i]; 
     } 
  }

Boundary method implementation.

private static void CheckBoundaries<T>(T[] sourceArray, long sourceIndex, T[] destinationArray, long copyNoOfElements, long sourceArrayLength)
        {
            if (sourceIndex >= sourceArray.Length)
            {
                throw new IndexOutOfRangeException();
            }
            if (copyNoOfElements > sourceArrayLength)
            {
                throw new IndexOutOfRangeException();
            }
            if (destinationArray.Length < copyNoOfElements)
            {
                throw new IndexOutOfRangeException();
            }
        }

PHP filesize MB/KB conversion

//Get the size in bytes
function calculateFileSize($size)
{
   $sizes = ['B', 'KB', 'MB', 'GB'];
   $count=0;
   if ($size < 1024) {
    return $size . " " . $sizes[$count];
    } else{
     while ($size>1024){
        $size=round($size/1024,2);
        $count++;
    }
     return $size . " " . $sizes[$count];
   }
}

go get results in 'terminal prompts disabled' error for github private repo

If you just want go get to work real fast, and move along with your work...

Just export GIT_TERMINAL_PROMPT=1

$ export GIT_TERMINAL_PROMPT=1
$ go get [whatever]

It will now prompt you for a user/pass for the rest of your shell session. Put this in your .profile or setup git as above for a more permanent solution.

How do I copy the contents of one ArrayList into another?

Came across this while facing the same issue myself.

Saying arraylist1 = arraylist2 sets them both to point at the same place so if you alter either the data alters and thus both lists always stay the same.

To copy values into an independent list I just used foreach to copy the contents:

ArrayList list1 = new ArrayList();
ArrayList list2 = new ArrayList();

fill list1 in whatever way you currently are.

foreach(<type> obj in list1)
{
    list2.Add(obj);
}

Append text to textarea with javascript

Give this a try:

<!DOCTYPE html>
<html>
<head>
    <title>List Test</title>
    <style>
        li:hover {
            cursor: hand; cursor: pointer;
        }
    </style>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("li").click(function(){
                $('#alltext').append($(this).text());
            });
        });
    </script>
</head>
<body>

    <h2>List items</h2>
    <ol>
        <li>Hello</li>
        <li>World</li>
        <li>Earthlings</li>
    </ol>
    <form>
        <textarea id="alltext"></textarea>
    </form>

</body>
</html>

Cannot find "Package Explorer" view in Eclipse

For Eclipse version 4.3.0.v20130605-2000. You can use the Java (default) perspective. In this perspective, it provides the Package Explorer view.

To use the Java (default) perspective: Window -> Open Perspective -> Other... -> Java (default) -> Ok

If you already use the Java (default) perspective but accidentally close the Package Explorer view, you can open it by; Window -> Show View -> Package Explorer (Alt+Shift+Q,P)

If the Package Explorer still doesn't appear in the Java (default) perspective, I suggest you to right-click on the Java (default) perspective button that is located in the top-right of the Eclipse IDE and then select Reset. The Java (default) perspective will show the Package Explorer view, Code pane, Outline view, Problems, JavaDoc and Declaration View.

Node.js: How to read a stream into a buffer?

I suggest to have array of buffers and concat to resulting buffer only once at the end. Its easy to do manually, or one could use node-buffers

Setting the height of a SELECT in IE

i wanted to set the height of the select box to be smaller than the default. i used

select {
   position: relative;
   height: 10px !important;
   display: inline-block;
}

this works on ie7 and ie8. you might only need the height property, i just added the position and display to override properties inherited from higher up the dom.

Is there a Java equivalent or methodology for the typedef keyword in C++?

There is no typedef in java as of 1.6, what you can do is make a wrapper class for what you want since you can't subclass final classes (Integer, Double, etc)

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

I've been searching answer but couldn't find but finally I could fix this by adding play-service-ads dependency let's try this:

*) File -> Project Structure... -> Under the module you can find app and there is a option called dependencies and you can add com.google.android.gms:play-services-ads:x.x.x dependency to your project

I faced this problem when I try to import Eclipse projects into Android Studio.

Image

ASP.NET MVC: Custom Validation by DataAnnotation

A bit late to answer, but for who is searching. You can easily do this by using an extra property with the data annotation:

public string foo { get; set; }
public string bar { get; set; }

[MinLength(20, ErrorMessage = "too short")]
public string foobar 
{ 
    get
    {
        return foo + bar;
    }
}

That's all that is too it really. If you really want to display in a specific place the validation error as well, you can add this in your view:

@Html.ValidationMessage("foobar", "your combined text is too short")

doing this in the view can come in handy if you want to do localization.

Hope this helps!

How to compare 2 dataTables

The OP, MAW74656, originally posted this answer in the question body in response to the accepted answer, as explained in this comment:

I used this and wrote a public method to call the code and return the boolean.

The OP's answer:

Code Used:

public bool tablesAreTheSame(DataTable table1, DataTable table2)
{
    DataTable dt;
    dt = getDifferentRecords(table1, table2);

    if (dt.Rows.Count == 0)
        return true;
    else
        return false;
}

//Found at http://canlu.blogspot.com/2009/05/how-to-compare-two-datatables-in-adonet.html
private DataTable getDifferentRecords(DataTable FirstDataTable, DataTable SecondDataTable)
{
    //Create Empty Table     
    DataTable ResultDataTable = new DataTable("ResultDataTable");

    //use a Dataset to make use of a DataRelation object     
    using (DataSet ds = new DataSet())
    {
        //Add tables     
        ds.Tables.AddRange(new DataTable[] { FirstDataTable.Copy(), SecondDataTable.Copy() });

        //Get Columns for DataRelation     
        DataColumn[] firstColumns = new DataColumn[ds.Tables[0].Columns.Count];
        for (int i = 0; i < firstColumns.Length; i++)
        {
            firstColumns[i] = ds.Tables[0].Columns[i];
        }

        DataColumn[] secondColumns = new DataColumn[ds.Tables[1].Columns.Count];
        for (int i = 0; i < secondColumns.Length; i++)
        {
            secondColumns[i] = ds.Tables[1].Columns[i];
        }

        //Create DataRelation     
        DataRelation r1 = new DataRelation(string.Empty, firstColumns, secondColumns, false);
        ds.Relations.Add(r1);

        DataRelation r2 = new DataRelation(string.Empty, secondColumns, firstColumns, false);
        ds.Relations.Add(r2);

        //Create columns for return table     
        for (int i = 0; i < FirstDataTable.Columns.Count; i++)
        {
            ResultDataTable.Columns.Add(FirstDataTable.Columns[i].ColumnName, FirstDataTable.Columns[i].DataType);
        }

        //If FirstDataTable Row not in SecondDataTable, Add to ResultDataTable.     
        ResultDataTable.BeginLoadData();
        foreach (DataRow parentrow in ds.Tables[0].Rows)
        {
            DataRow[] childrows = parentrow.GetChildRows(r1);
            if (childrows == null || childrows.Length == 0)
                ResultDataTable.LoadDataRow(parentrow.ItemArray, true);
        }

        //If SecondDataTable Row not in FirstDataTable, Add to ResultDataTable.     
        foreach (DataRow parentrow in ds.Tables[1].Rows)
        {
            DataRow[] childrows = parentrow.GetChildRows(r2);
            if (childrows == null || childrows.Length == 0)
                ResultDataTable.LoadDataRow(parentrow.ItemArray, true);
        }
        ResultDataTable.EndLoadData();
    }

    return ResultDataTable;
}

Calculating Pearson correlation and significance in Python

The following code is a straight-up interpretation of the definition:

import math

def average(x):
    assert len(x) > 0
    return float(sum(x)) / len(x)

def pearson_def(x, y):
    assert len(x) == len(y)
    n = len(x)
    assert n > 0
    avg_x = average(x)
    avg_y = average(y)
    diffprod = 0
    xdiff2 = 0
    ydiff2 = 0
    for idx in range(n):
        xdiff = x[idx] - avg_x
        ydiff = y[idx] - avg_y
        diffprod += xdiff * ydiff
        xdiff2 += xdiff * xdiff
        ydiff2 += ydiff * ydiff

    return diffprod / math.sqrt(xdiff2 * ydiff2)

Test:

print pearson_def([1,2,3], [1,5,7])

returns

0.981980506062

This agrees with Excel, this calculator, SciPy (also NumPy), which return 0.981980506 and 0.9819805060619657, and 0.98198050606196574, respectively.

R:

> cor( c(1,2,3), c(1,5,7))
[1] 0.9819805

EDIT: Fixed a bug pointed out by a commenter.

Extract a part of the filepath (a directory) in Python

In Python 3.4 you can use the pathlib module:

>>> from pathlib import Path
>>> p = Path('C:\Program Files\Internet Explorer\iexplore.exe')
>>> p.name
'iexplore.exe'
>>> p.suffix
'.exe'
>>> p.root
'\\'
>>> p.parts
('C:\\', 'Program Files', 'Internet Explorer', 'iexplore.exe')
>>> p.relative_to('C:\Program Files')
WindowsPath('Internet Explorer/iexplore.exe')
>>> p.exists()
True

what's data-reactid attribute in html?

The data-reactid attribute is a custom attribute used so that React can uniquely identify its components within the DOM.

This is important because React applications can be rendered at the server as well as the client. Internally React builds up a representation of references to the DOM nodes that make up your application (simplified version is below).

{
  id: '.1oqi7occu80',
  node: DivRef,
  children: [
    {
      id: '.1oqi7occu80.0',
      node: SpanRef,
      children: [
        {
          id: '.1oqi7occu80.0.0',
          node: InputRef,
          children: []
        }
      ]
    }
  ]
}

There's no way to share the actual object references between the server and the client and sending a serialized version of the entire component tree is potentially expensive. When the application is rendered at the server and React is loaded at the client, the only data it has are the data-reactid attributes.

<div data-reactid='.loqi70ccu80'>
  <span data-reactid='.loqi70ccu80.0'>
    <input data-reactid='.loqi70ccu80.0' />
  </span>
</div>

It needs to be able to convert that back into the data structure above. The way it does that is with the unique data-reactid attributes. This is called inflating the component tree.

You might also notice that if React renders at the client-side, it uses the data-reactid attribute, even though it doesn't need to lose its references. In some browsers, it inserts your application into the DOM using .innerHTML then it inflates the component tree straight away, as a performance boost.

The other interesting difference is that client-side rendered React ids will have an incremental integer format (like .0.1.4.3), whereas server-rendered ones will be prefixed with a random string (such as .loqi70ccu80.1.4.3). This is because the application might be rendered across multiple servers and it's important that there are no collisions. At the client-side, there is only one rendering process, which means counters can be used to ensure unique ids.

React 15 uses document.createElement instead, so client rendered markup won't include these attributes anymore.

Html.RenderPartial() syntax with Razor

@Html.Partial("NameOfPartialView")

Stored procedure return into DataSet in C# .Net

I should tell you the basic steps and rest depends upon your own effort. You need to perform following steps.

  • Create a connection string.
  • Create a SQL connection
  • Create SQL command
  • Create SQL data adapter
  • fill your dataset.

Do not forget to open and close connection. follow this link for more under standing.

Which is faster: Stack allocation or Heap allocation

Remark that the considerations are typically not about speed and performance when choosing stack versus heap allocation. The stack acts like a stack, which means it is well suited for pushing blocks and popping them again, last in, first out. Execution of procedures is also stack-like, last procedure entered is first to be exited. In most programming languages, all the variables needed in a procedure will only be visible during the procedure's execution, thus they are pushed upon entering a procedure and popped off the stack upon exit or return.

Now for an example where the stack cannot be used:

Proc P
{
  pointer x;
  Proc S
  {
    pointer y;
    y = allocate_some_data();
    x = y;
  }
}

If you allocate some memory in procedure S and put it on the stack and then exit S, the allocated data will be popped off the stack. But the variable x in P also pointed to that data, so x is now pointing to some place underneath the stack pointer (assume stack grows downwards) with an unknown content. The content might still be there if the stack pointer is just moved up without clearing the data beneath it, but if you start allocating new data on the stack, the pointer x might actually point to that new data instead.

Append text with .bat

I am not proficient at batch scripting but I can tell you that REM stands for Remark. The append won't occur as it is essentially commented out.

http://technet.microsoft.com/en-us/library/bb490986.aspx

Also, the append operator redirects the output of a command to a file. In the snippet you posted it is not clear what output should be redirected.

How to filter rows containing a string pattern from a Pandas dataframe

df[df['ids'].str.contains('ball', na = False)] # valid for (at least) pandas version 0.17.1

Step-by-step explanation (from inner to outer):

  • df['ids'] selects the ids column of the data frame (technically, the object df['ids'] is of type pandas.Series)
  • df['ids'].str allows us to apply vectorized string methods (e.g., lower, contains) to the Series
  • df['ids'].str.contains('ball') checks each element of the Series as to whether the element value has the string 'ball' as a substring. The result is a Series of Booleans indicating True or False about the existence of a 'ball' substring.
  • df[df['ids'].str.contains('ball')] applies the Boolean 'mask' to the dataframe and returns a view containing appropriate records.
  • na = False removes NA / NaN values from consideration; otherwise a ValueError may be returned.

Why is the <center> tag deprecated in HTML?

You can add this to your css and use <div class="center"></div>

.center{
  text-align: center;
  margin: auto;
  justify-content: center;
  display: flex;
}

or if you want to keep <center></center> and be prepared in case its ever removed, add this to your css

center{
  text-align: center;
  margin: auto;
  justify-content: center;
  display: flex;
}

What is the difference between "is None" and "== None"

It depends on what you are comparing to None. Some classes have custom comparison methods that treat == None differently from is None.

In particular the output of a == None does not even have to be boolean !! - a frequent cause of bugs.

For a specific example take a numpy array where the == comparison is implemented elementwise:

import numpy as np
a = np.zeros(3) # now a is array([0., 0., 0.])
a == None #compares elementwise, outputs array([False, False, False]), i.e. not boolean!!!
a is None #compares object to object, outputs False

How do I correct "Commit Failed. File xxx is out of date. xxx path not found."

I had the same problem after merging a branch with a ton of changes back into my trunk. The only two solutions I could see was to do the svn move solution offered by Pacifika or manually merging the files with a diff tool. But I did find a workaround...

The machine that wasn't working was running Subversion client 1.6.5. I did the exact same thing on a machine with Subversion 1.5.4 and it worked! On both machines I did a 1) clean checkout of trunk, 2) svn merge ..., and 3) svn commit. My server is 1.5.x for what that's worth.

Hope this helps somebody.

How can I add reflection to a C++ application?

There are two kinds of reflection swimming around.

  1. Inspection by iterating over members of a type, enumerating its methods and so on.

    This is not possible with C++.
  2. Inspection by checking whether a class-type (class, struct, union) has a method or nested type, is derived from another particular type.

    This kind of thing is possible with C++ using template-tricks. Use boost::type_traits for many things (like checking whether a type is integral). For checking for the existance of a member function, use Is it possible to write a template to check for a function's existence? . For checking whether a certain nested type exists, use plain SFINAE .

If you are rather looking for ways to accomplish 1), like looking how many methods a class has, or like getting the string representation of a class id, then i'm afraid there is no Standard C++ way of doing this. You have to use either

  • A Meta Compiler like the Qt Meta Object Compiler which translates your code adding additional meta informations.
  • A Framework constisting of macros that allow you to add the required meta-informations. You would need to tell the framework all methods, the class-names, base-classes and everything it needs.

C++ is made with speed in mind. If you want high-level inspection, like C# or Java has, then I'm afraid i have to tell you there is no way without some effort.

How do you set the EditText keyboard to only consist of numbers on Android?

After several tries, I got it! I'm setting the keyboard values programmatically like this:

myEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);

Or if you want you can edit the XML like so:

android: inputType = "numberPassword"

Both configs will display password bullets, so we need to create a custom ClickableSpan class:

private class NumericKeyBoardTransformationMethod extends PasswordTransformationMethod {
    @Override
    public CharSequence getTransformation(CharSequence source, View view) {
        return source;
    }
}

Finally we need to implement it on the EditText in order to display the characters typed.

myEditText.setTransformationMethod(new NumericKeyBoardTransformationMethod());

This is how my keyboard looks like now:

Last executed queries for a specific database

This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):

SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC

This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.

What does $1 [QSA,L] mean in my .htaccess file?

Not the place to give a complete tutorial, but here it is in short;

RewriteCond basically means "execute the next RewriteRule only if this is true". The !-l path is the condition that the request is not for a link (! means not, -l means link)

The RewriteRule basically means that if the request is done that matches ^(.+)$ (matches any URL except the server root), it will be rewritten as index.php?url=$1 which means a request for ollewill be rewritten as index.php?url=olle).

QSA means that if there's a query string passed with the original URL, it will be appended to the rewrite (olle?p=1 will be rewritten as index.php?url=olle&p=1.

L means if the rule matches, don't process any more RewriteRules below this one.

For more complete info on this, follow the links above. The rewrite support can be a bit hard to grasp, but there are quite a few examples on stackoverflow to learn from.

Beautiful Soup and extracting a div and its contents by ID

I used:

soup.findAll('tag', attrs={'attrname':"attrvalue"})

As my syntax for find/findall; that said, unless there are other optional parameters between the tag and attribute list, this shouldn't be different.

moment.js get current time in milliseconds?

Since this thread is the first one from Google I found, one accurate and lazy way I found is :

const momentObject = moment().toObject();
// date doesn't exist with duration, but day does so use it instead
//   -1 because moment start from date 1, but a duration start from 0
const durationCompatibleObject = { ... momentObject, day: momentObject.date - 1 };
delete durationCompatibleObject.date;

const yourDuration = moment.duration(durationCompatibleObject);
// yourDuration.asMilliseconds()

now just add some prototypes (such as toDuration()) / .asMilliseconds() into moment and you can easily switch to milliseconds() or whatever !

Return content with IHttpActionResult for non-OK response

Anyone who is interested in returning anything with any statuscode with returning ResponseMessage:

//CreateResponse(HttpStatusCode, T value)
return ResponseMessage(Request.CreateResponse(HttpStatusCode.XX, object));

How to check if an integer is in a given range?

I think

if (0 < i && i < 100) 

is more elegant. Looks like maths equation.

If you are looking for something special you can try:

Math.max(0, i) == Math.min(i, 100)

at least it uses library.

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

I did below modifications and I am able to start the Hive Shell without any errors:

1. ~/.bashrc

Inside bashrc file add the below environment variables at End Of File : sudo gedit ~/.bashrc

#Java Home directory configuration
export JAVA_HOME="/usr/lib/jvm/java-9-oracle"
export PATH="$PATH:$JAVA_HOME/bin"

# Hadoop home directory configuration
export HADOOP_HOME=/usr/local/hadoop
export PATH=$PATH:$HADOOP_HOME/bin
export PATH=$PATH:$HADOOP_HOME/sbin

export HIVE_HOME=/usr/lib/hive
export PATH=$PATH:$HIVE_HOME/bin

2. hive-site.xml

You have to create this file(hive-site.xml) in conf directory of Hive and add the below details

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>

<property>
  <name>javax.jdo.option.ConnectionURL</name>
  <value>jdbc:mysql://localhost/metastore?createDatabaseIfNotExist=true</value>
</property>


<property>
  <name>javax.jdo.option.ConnectionDriverName</name>
  <value>com.mysql.jdbc.Driver</value>
</property>

<property>
  <name>javax.jdo.option.ConnectionUserName</name>
  <value>root</value>
</property>

<property>
  <name>javax.jdo.option.ConnectionPassword</name>
  <value>root</value>
</property>

<property>
  <name>datanucleus.autoCreateSchema</name>
  <value>true</value>
</property>

<property>
  <name>datanucleus.fixedDatastore</name>
  <value>true</value>
</property>

<property>
 <name>datanucleus.autoCreateTables</name>
 <value>True</value>
 </property>

</configuration>

3. You also need to put the jar file(mysql-connector-java-5.1.28.jar) in the lib directory of Hive

4. Below installations required on your Ubuntu to Start the Hive Shell:

  1. MySql
  2. Hadoop
  3. Hive
  4. Java

5. Execution Part:

  1. Start all services of Hadoop: start-all.sh

  2. Enter the jps command to check whether all Hadoop services are up and running: jps

  3. Enter the hive command to enter into hive shell: hive

How to pass a null variable to a SQL Stored Procedure from C#.net code

I use a method to convert to DBNull if it is null

    // Converts to DBNull, if Null
    public static object ToDBNull(object value)
    {
        if (null != value)
            return value;
        return DBNull.Value;
    }

So when setting the parameter, just call the function

    sqlComm.Parameters.Add(new SqlParameter("@NoteNo", LibraryHelper.ToDBNull(NoteNo)));

This will ensure any nulls, get changed to DBNull.Value, else it will stay the same.

How to use jQuery in AngularJS

This should be working. Please have a look at this fiddle.

$(function() {
   $( "#slider" ).slider();
});//Links to jsfiddle must be accompanied by code

Make sure you're loading the libraries in this order: jQuery, jQuery UI CSS, jQuery UI, AngularJS.

How to copy a file from remote server to local machine?

When you use scp you have to tell the host name and ip address from where you want to copy the file. For instance, if you are at the remote host and you want to transfer the file to your pc you may use something like this:

scp -P[portnumber] myfile_at_remote_host [user]@[your_ip_address]:/your/path/

Example:

scp -P22 table [email protected]:/home/me/Desktop/

On the other hand, if you are at your are actually on your machine you may use something like this:

scp -P[portnumber] [remote_login]@[remote's_ip_address]:/remote/path/myfile_at_remote_host /your/path/

Example:

scp -P22 [fake_user]@222.222.222.222:/remote/path/table /home/me/Desktop/

Change the "From:" address in Unix "mail"

On CentOS this worked for me:

echo "email body" | mail -s "Subject here" -r from_email_address email_address_to

Where is the itoa function in Linux?

Where is the itoa function in Linux?

There is no such function in Linux. I use this code instead.

/*
=============
itoa

Convert integer to string

PARAMS:
- value     A 64-bit number to convert
- str       Destination buffer; should be 66 characters long for radix2, 24 - radix8, 22 - radix10, 18 - radix16.
- radix     Radix must be in range -36 .. 36. Negative values used for signed numbers.
=============
*/

char* itoa (unsigned long long  value,  char str[],  int radix)
{
    char        buf [66];
    char*       dest = buf + sizeof(buf);
    boolean     sign = false;

    if (value == 0) {
        memcpy (str, "0", 2);
        return str;
    }

    if (radix < 0) {
        radix = -radix;
        if ( (long long) value < 0) {
            value = -value;
            sign = true;
        }
    }

    *--dest = '\0';

    switch (radix)
    {
    case 16:
        while (value) {
            * --dest = '0' + (value & 0xF);
            if (*dest > '9') *dest += 'A' - '9' - 1;
            value >>= 4;
        }
        break;
    case 10:
        while (value) {
            *--dest = '0' + (value % 10);
            value /= 10;
        }
        break;

    case 8:
        while (value) {
            *--dest = '0' + (value & 7);
            value >>= 3;
        }
        break;

    case 2:
        while (value) {
            *--dest = '0' + (value & 1);
            value >>= 1;
        }
        break;

    default:            // The slow version, but universal
        while (value) {
            *--dest = '0' + (value % radix);
            if (*dest > '9') *dest += 'A' - '9' - 1;
            value /= radix;
        }
        break;
    }

    if (sign) *--dest = '-';

    memcpy (str, dest, buf +sizeof(buf) - dest);
    return str;
}

Why do abstract classes in Java have constructors?

All the classes including the abstract classes can have constructors.Abstract class constructors will be called when its concrete subclass will be instantiated

What causes: "Notice: Uninitialized string offset" to appear?

Check out the contents of your array with

echo '<pre>' . print_r( $arr, TRUE ) . '</pre>';

Multi-select dropdown list in ASP.NET

I like the Infragistics controls. The WebDropDown has what you need. The only drawback is they can be a bit spendy.

Convert from MySQL datetime to another format with PHP

To convert a date retrieved from MySQL into the format requested (mm/dd/yy H:M (AM/PM)):

// $datetime is something like: 2014-01-31 13:05:59
$time = strtotime($datetimeFromMysql);
$myFormatForView = date("m/d/y g:i A", $time);
// $myFormatForView is something like: 01/31/14 1:05 PM

Refer to the PHP date formatting options to adjust the format.

How can I remove space (margin) above HTML header?

This css allowed chrome and firefox to render all other elements on my page normally and remove the margin above my h1 tag. Also, as a page is resized em can work better than px.

h1 {
  margin-top: -.3em;
  margin-bottom: 0em;
}

" netsh wlan start hostednetwork " command not working no matter what I try

netsh wlan set hostednetwork mode=allow ssid=dhiraj key=7870049877

How to scroll to an element?

You could try this way:

 handleScrollToElement = e => {
    const elementTop = this.gate.offsetTop;
    window.scrollTo(0, elementTop);
 };

 render(){
  return(
      <h2 ref={elem => (this.gate = elem)}>Payment gate</h2>
 )}

How can I add a box-shadow on one side of an element?

div {
 border: 1px solid #666;
    width: 50px;
    height: 50px;
    -webkit-box-shadow: inset 10px 0px 5px -1px #888 ;
}

IntelliJ Organize Imports

That plugin will automatically do the "organize import" action on file save: https://github.com/dubreuia/intellij-plugin-save-actions.

To install: "File > Settings > Plugins > Browse repositories... > Search 'Save Actions' > Category 'Code tools'". Then activate the "organize import" save action.

Find max and second max salary for a employee table MySQL

Try

SELECT 

   SUBSTRING( GROUP_CONCAT( Salary ), 1 , LOCATE(",", GROUP_CONCAT( Salary ) ) -1 ) AS max_salary,

   SUBSTRING( GROUP_CONCAT( Salary ), LOCATE(",", GROUP_CONCAT( Salary ) ) +1 ) AS second_max_salary

FROM 
   (
     SELECT Salary FROM `Employee` ORDER BY Salary DESC LIMIT 0,2
   ) a

Demo here

Calculate the date yesterday in JavaScript

You can use momentjs it is very helpful you can achieve a lot of things with this library.

Get yesterday date with current timing moment().subtract(1, 'days').toString()

Get yesterday date with a start of the date moment().subtract(1, 'days').startOf('day').toString()

What's the difference between a single precision and double precision floating point operation?

First of all float and double are both used for representation of numbers fractional numbers. So, the difference between the two stems from the fact with how much precision they can store the numbers.

For example: I have to store 123.456789 One may be able to store only 123.4567 while other may be able to store the exact 123.456789.

So, basically we want to know how much accurately can the number be stored and is what we call precision.

Quoting @Alessandro here

The precision indicates the number of decimal digits that are correct, i.e. without any kind of representation error or approximation. In other words, it indicates how many decimal digits one can safely use.

Float can accurately store about 7-8 digits in the fractional part while Double can accurately store about 15-16 digits in the fractional part

So, double can store double the amount of fractional part as of float. That is why Double is called double the float

How to use LINQ to select object with minimum or maximum property value

A way via extension function on IEnumerable that returns both the object and the minimum found. It takes a Func that can do any operation on the object in the collection:

public static (double min, T obj) tMin<T>(this IEnumerable<T> ienum, 
            Func<T, double> aFunc)
        {
            var okNull = default(T);
            if (okNull != null)
                throw new ApplicationException("object passed to Min not nullable");

            (double aMin, T okObj) best = (double.MaxValue, okNull);
            foreach (T obj in ienum)
            {
                double q = aFunc(obj);
                if (q < best.aMin)
                    best = (q, obj);
            }
            return (best);
        }

Example where object is an Airport and we want to find closest Airport to a given (latitude, longitude). Airport has a dist(lat, lon) function.

(double okDist, Airport best) greatestPort = airPorts.tMin(x => x.dist(okLat, okLon));

Eclipse error: indirectly referenced from required .class files?

For me, it happens when I upgrade my jdk to 1.8.0_60 with my old set of jars has been used for long time. If I fall back to jdk1.7.0_25, all these problem are gone. It seems a problem about the compatibility between the JRE and the libraries.

Copy Notepad++ text with formatting?

It seems to me that the best and easiest way is commented by Dennis G:

And now go to [Settings > Shortcut Mapper > Plugin Commands > Copy all Formats to clipboard] and set it to CTRL+SHIFT+C --> Instant joy. CTRL+C to copy the raw text, CTRL+SHIFT+C to copy with formatting. This should be default.

Hoping help someone just like me!

fork() and wait() with two child processes

It looks to me as though the basic problem is that you have one wait() call rather than a loop that waits until there are no more children. You also only wait if the last fork() is successful rather than if at least one fork() is successful.

You should only use _exit() if you don't want normal cleanup operations - such as flushing open file streams including stdout. There are occasions to use _exit(); this is not one of them. (In this example, you could also, of course, simply have the children return instead of calling exit() directly because returning from main() is equivalent to exiting with the returned status. However, most often you would be doing the forking and so on in a function other than main(), and then exit() is often appropriate.)


Hacked, simplified version of your code that gives the diagnostics I'd want. Note that your for loop skipped the first element of the array (mine doesn't).

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

int main(void)
{
    pid_t child_pid, wpid;
    int status = 0;
    int i;
    int a[3] = {1, 2, 1};

    printf("parent_pid = %d\n", getpid());
    for (i = 0; i < 3; i++)
    {
        printf("i = %d\n", i);
        if ((child_pid = fork()) == 0)
        {
            printf("In child process (pid = %d)\n", getpid());
            if (a[i] < 2)
            {
                printf("Should be accept\n");
                exit(1);
            }
            else
            {
                printf("Should be reject\n");
                exit(0);
            }
            /*NOTREACHED*/
        }
    }

    while ((wpid = wait(&status)) > 0)
    {
        printf("Exit status of %d was %d (%s)\n", (int)wpid, status,
               (status > 0) ? "accept" : "reject");
    }
    return 0;
}

Example output (MacOS X 10.6.3):

parent_pid = 15820
i = 0
i = 1
In child process (pid = 15821)
Should be accept
i = 2
In child process (pid = 15822)
Should be reject
In child process (pid = 15823)
Should be accept
Exit status of 15823 was 256 (accept)
Exit status of 15822 was 0 (reject)
Exit status of 15821 was 256 (accept)

Web Service vs WCF Service

This answer is based on an article that no longer exists:

Summary of article:

"Basically, WCF is a service layer that allows you to build applications that can communicate using a variety of communication mechanisms. With it, you can communicate using Peer to Peer, Named Pipes, Web Services and so on.

You can’t compare them because WCF is a framework for building interoperable applications. If you like, you can think of it as a SOA enabler. What does this mean?

Well, WCF conforms to something known as ABC, where A is the address of the service that you want to communicate with, B stands for the binding and C stands for the contract. This is important because it is possible to change the binding without necessarily changing the code. The contract is much more powerful because it forces the separation of the contract from the implementation. This means that the contract is defined in an interface, and there is a concrete implementation which is bound to by the consumer using the same idea of the contract. The datamodel is abstracted out."

... later ...

"should use WCF when we need to communicate with other communication technologies (e,.g. Peer to Peer, Named Pipes) rather than Web Service"

How to present a simple alert message in java?

I'll be the first to admit Java can be very verbose, but I don't think this is unreasonable:

JOptionPane.showMessageDialog(null, "My Goodness, this is so concise");

If you statically import javax.swing.JOptionPane.showMessageDialog using:

import static javax.swing.JOptionPane.showMessageDialog;

This further reduces to

showMessageDialog(null, "This is even shorter");

How can I export a GridView.DataSource to a datatable or dataset?

I have used below line of code and it works, Try this

DataTable dt =  dataSource.Tables[0];

how to define variable in jquery

You can also use text() to set or get the text content of selected elements

var text1 = $("#idName").text();

What is the main difference between Inheritance and Polymorphism?

Polymorphism is an approach to expressing common behavior between types of objects that have similar traits. It also allows for variations of those traits to be created through overriding. Inheritance is a way to achieve polymorphism through an object hierarchy where objects express relationships and abstract behaviors. It isn't the only way to achieve polymorphism though. Prototype is another way to express polymorphism that is different from inheritance. JavaScript is an example of a language that uses prototype. I'd imagine there are other ways too.

Can't bind to 'formGroup' since it isn't a known property of 'form'

I had the same issue and the problem was in fact only that I forgot to import and declare the component which holds the form in the module:

import { ContactFormComponent } from './contact-form/contact-form.component';

@NgModule({
    declarations: [..., ContactFormComponent, ...],
    imports: [CommonModule, HomeRoutingModule, SharedModule]
})
export class HomeModule {}

Rotate an image in image source in html

This might be your script-free solution: http://davidwalsh.name/css-transform-rotate

It's supported in all browsers prefixed and, in IE10-11 and all still-used Firefox versions, unprefixed.

That means that if you don't care for old IEs (the bane of web designers) you can skip the -ms- and -moz- prefixes to economize space.

However, the Webkit browsers (Chrome, Safari, most mobile navigators) still need -webkit-, and there's a still-big cult following of pre-Next Opera and using -o- is sensate.

Why is using the JavaScript eval function a bad idea?

  1. Improper use of eval opens up your code for injection attacks

  2. Debugging can be more challenging (no line numbers, etc.)

  3. eval'd code executes slower (no opportunity to compile/cache eval'd code)

Edit: As @Jeff Walden points out in comments, #3 is less true today than it was in 2008. However, while some caching of compiled scripts may happen this will only be limited to scripts that are eval'd repeated with no modification. A more likely scenario is that you are eval'ing scripts that have undergone slight modification each time and as such could not be cached. Let's just say that SOME eval'd code executes more slowly.

Choose File Dialog

Adding to the mix: the OI File Manager has a public api registered at openintents.org

http://www.openintents.org/filemanager

http://www.openintents.org/action/org-openintents-action-pick-file/

Converting Integers to Roman Numerals - Java

We can avoid the loop and if with this solution:

public class RomanNumber {

    private final static Supplier<TreeMap<Integer, String>> romanNumerals = () -> {
        final TreeMap<Integer, String> map = new TreeMap<>();
        map.put(1000, "M");
        map.put(900, "CM");
        map.put(500, "D");
        map.put(400, "CD");
        map.put(100, "C");
        map.put(90, "XC");
        map.put(50, "L");
        map.put(40, "XL");
        map.put(10, "X");
        map.put(9, "IX");
        map.put(5, "V");
        map.put(4, "IV");
        map.put(1, "I");
        return map;
    };

    private static Function<TreeMap<Integer, String>, Function<Integer, String>> numeralConverter = map -> number -> Optional
            .ofNullable(map.floorKey(number))
            .filter(number::equals)
            .map(map::get)
            .or(() -> Optional
                    .ofNullable(map.floorKey(number))
                    .map(num -> map.get(num) + RomanNumber.numeralConverter.apply(map).apply(number - num))
            ).orElse("NaN");

    public static Function<Integer, String> toRoman = numeralConverter.apply(romanNumerals.get());
}

Colorizing text in the console with C++

Add a little Color to your Console Text

  HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
  // you can loop k higher to see more color choices
  for(int k = 1; k < 255; k++)
  {
    // pick the colorattribute k you want
    SetConsoleTextAttribute(hConsole, k);
    cout << k << " I want to be nice today!" << endl;
  }

alt text

Character Attributes Here is how the "k" value be interpreted.

Getting time span between two times in C#?

Two points:

  1. Check your inputs. I can't imagine a situation where you'd get 2 hours by subtracting the time values you're talking about. If I do this:

        DateTime startTime = Convert.ToDateTime("7:00 AM");
        DateTime endtime = Convert.ToDateTime("2:00 PM");
        TimeSpan duration = startTime - endtime;
    

    ... I get -07:00:00 as the result. And even if I forget to provide the AM/PM value:

        DateTime startTime = Convert.ToDateTime("7:00");
        DateTime endtime = Convert.ToDateTime("2:00");
        TimeSpan duration = startTime - endtime;
    

    ... I get 05:00:00. So either your inputs don't contain the values you have listed or you are in a machine environment where they are begin parsed in an unexpected way. Or you're not actually getting the results you are reporting.

  2. To find the difference between a start and end time, you need to do endTime - startTime, not the other way around.

How to send password securely over HTTP?

HTTPS is so powerful because it uses asymmetric cryptography. This type of cryptography not only allows you to create an encrypted tunnel but you can verify that you are talking to the right person, and not a hacker.

Here is Java source code which uses the asymmetric cipher RSA (used by PGP) to communicate: http://www.hushmail.com/services/downloads/

How does ifstream's eof() work?

-1 is get's way of saying you've reached the end of file. Compare it using the std::char_traits<char>::eof() (or std::istream::traits_type::eof()) - avoid -1, it's a magic number. (Although the other one is a bit verbose - you can always just call istream::eof)

The EOF flag is only set once a read tries to read past the end of the file. If I have a 3 byte file, and I only read 3 bytes, EOF is false, because I've not tried to read past the end of the file yet. While this seems confusing for files, which typically know their size, EOF is not known until a read is attempted on some devices, such as pipes and network sockets.

The second example works as inf >> foo will always return inf, with the side effect of attempt to read something and store it in foo. inf, in an if or while, will evaluate to true if the file is "good": no errors, no EOF. Thus, when a read fails, inf evaulates to false, and your loop properly aborts. However, take this common error:

while(!inf.eof())  // EOF is false here
{
    inf >> x;      // read fails, EOF becomes true, x is not set
    // use x       // we use x, despite our read failing.
}

However, this:

while(inf >> x)  // Attempt read into x, return false if it fails
{
    // will only be entered if read succeeded.
}

Which is what we want.

'Java' is not recognized as an internal or external command

In my case, PATH was properly SET but PATHEXT has been cleared by me by mistake with .exe extension. That why window can't find java or anything .exe application from command prompt. Hope it can help someone.

Jest spyOn function called

In your test code your are trying to pass App to the spyOn function, but spyOn will only work with objects, not classes. Generally you need to use one of two approaches here:

1) Where the click handler calls a function passed as a prop, e.g.

class App extends Component {

  myClickFunc = () => {
      console.log('clickity clickcty');
      this.props.someCallback();
  }
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <p className="App-intro" onClick={this.myClickFunc}>
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

You can now pass in a spy function as a prop to the component, and assert that it is called:

describe('my sweet test', () => {
 it('clicks it', () => {
    const spy = jest.fn();
    const app = shallow(<App someCallback={spy} />)
    const p = app.find('.App-intro')
    p.simulate('click')
    expect(spy).toHaveBeenCalled()
 })
})

2) Where the click handler sets some state on the component, e.g.

class App extends Component {
  state = {
      aProperty: 'first'
  }

  myClickFunc = () => {
      console.log('clickity clickcty');
      this.setState({
          aProperty: 'second'
      });
  }
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <p className="App-intro" onClick={this.myClickFunc}>
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

You can now make assertions about the state of the component, i.e.

describe('my sweet test', () => {
 it('clicks it', () => {
    const app = shallow(<App />)
    const p = app.find('.App-intro')
    p.simulate('click')
    expect(app.state('aProperty')).toEqual('second');
 })
})

Bulk package updates using Conda

Before you proceed to conda update --all command, first update conda with conda update conda command if you haven't update it for a long time. It happent to me (Python 2.7.13 on Anaconda 64 bits).

How can I display a messagebox in ASP.NET?

Using AJAX Modal Popup and creating a Message Box Class:

Messsage Box Class:

public class MessageBox
{
    ModalPopupExtender _modalPop;
    Page _page;
    object _sender;
    Panel _pnl;

    public enum Buttons
    {
        AbortRetryIgnore,
        OK,
        OKCancel,
        RetryCancel,
        YesNo,
        YesNoCancel
    }
    public enum DefaultButton
    {
        Button1,
        Button2,
        Button3
    }
    public enum MessageBoxIcon
    {
        Asterisk,
        Exclamation,
        Hand,
        Information,
        None,
        Question,
        Warning

    }

    public MessageBox(Page page, object sender, Panel pnl)
    {
        _page = page;
        _sender = sender;
        _pnl = pnl;
        _modalPop = new ModalPopupExtender();

        _modalPop.ID = "popUp";
        _modalPop.PopupControlID = "ModalPanel";

    }


    public void Show(String strTitle, string strMessage, Buttons buttons, DefaultButton defaultbutton, MessageBoxIcon msbi)
    {
        MasterPage mPage = _page.Master;
        Label lblTitle = null;
        Label lblError = null;
        Button btn1 = null;
        Button btn2 = null;
        Button btn3 = null;
        Image imgIcon = null;



        lblTitle = ((Default)_page.Master).messageBoxTitle;
        lblError = ((Default)_page.Master).messageBoxMsg;
        btn1 = ((Default)_page.Master).button1;
        btn2 = ((Default)_page.Master).button2;
        btn3 = ((Default)_page.Master).button3;
        imgIcon = ((Default)_page.Master).messageBoxIcon;

        lblTitle.Text = strTitle;
        lblError.Text = strMessage;

        btn1.CssClass = "btn btn-default";
        btn2.CssClass = "btn btn-default";
        btn3.CssClass = "btn btn-default";

        switch (msbi)
        {
            case MessageBoxIcon.Asterisk:
                //imgIcon.ImageUrl = "~/img/asterisk.jpg";
                break;
            case MessageBoxIcon.Exclamation:
                //imgIcon.ImageUrl = "~/img/exclamation.jpg";
                break;
            case MessageBoxIcon.Hand:
                break;
            case MessageBoxIcon.Information:
                break;
            case MessageBoxIcon.None:
                break;
            case MessageBoxIcon.Question:
                break;
            case MessageBoxIcon.Warning:
                break;
        }
        switch (buttons)
        {
            case Buttons.AbortRetryIgnore:
                btn1.Text = "Abort";
                btn2.Text = "Retry";
                btn3.Text = "Ignore";
                btn1.Visible = true;
                btn2.Visible = true;
                btn3.Visible = true;

                break;

            case Buttons.OK:
                btn1.Text = "OK";
                btn1.Visible = true;
                btn2.Visible = false;
                btn3.Visible = false;
                break;

            case Buttons.OKCancel:
                btn1.Text = "OK";
                btn2.Text = "Cancel";
                btn1.Visible = true;
                btn2.Visible = true;
                btn3.Visible = false;
                break;

            case Buttons.RetryCancel:
                btn1.Text = "Retry";
                btn2.Text = "Cancel";
                btn1.Visible = true;
                btn2.Visible = true;
                btn3.Visible = false;
                break;

            case Buttons.YesNo:
                btn1.Text = "No";
                btn2.Text = "Yes";
                btn1.Visible = true;
                btn2.Visible = true;
                btn3.Visible = false;
                break;

            case Buttons.YesNoCancel:
                btn1.Text = "Yes";
                btn2.Text = "No";
                btn3.Text = "Cancel";
                btn1.Visible = true;
                btn2.Visible = true;
                btn3.Visible = true;
                break;
        }

        if (defaultbutton == DefaultButton.Button1)
        {
            btn1.CssClass = "btn btn-primary";
            btn2.CssClass = "btn btn-default";
            btn3.CssClass = "btn btn-default";
        }

        else if (defaultbutton == DefaultButton.Button2)
        {
            btn1.CssClass = "btn btn-default";
            btn2.CssClass = "btn btn-primary";
            btn3.CssClass = "btn btn-default";
        }

        else if (defaultbutton == DefaultButton.Button3)
        {
            btn1.CssClass = "btn btn-default";
            btn2.CssClass = "btn btn-default";
            btn3.CssClass = "btn btn-primary";
        }

        FirePopUp();
    }

    private void FirePopUp()
    {
        _modalPop.TargetControlID = ((Button)_sender).ID;
        _modalPop.DropShadow = true;
        _modalPop.OkControlID = //btn 1 / 2 / 3;
        _modalPop.CancelControlID = //btn 1 / 2 / 3;
        _modalPop.BackgroundCssClass = "modalBackground";
        _pnl.Controls.Add(_modalPop);
        _modalPop.Show();

    }

In my MasterPage code:

  #region AlertBox
    public Button button1
    {
        get
        { return this.btn1; }
    }
    public Button button2
    {
        get
        { return this.btn2; }
    }
    public Button button3
    {
        get
        { return this.btn1; }
    }

    public Label messageBoxTitle
    {
        get
        { return this.lblMessageBoxTitle; }
    }

    public Label messageBoxMsg
    {
        get
        { return this.lblMessage; }
    }

    public Image messageBoxIcon
    {
        get
        { return this.img; }
    }

    public DialogResult res
    {
        get { return res; }
        set { res = value; }
    }

    #endregion

In my MasterPage aspx:

On the header add reference (just for some style)

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet">

On the Content:

<asp:Panel ID="ModalPanel" runat="server" style="display: none; position: absolute; top:0;">
        <asp:Panel ID="pnlAlertBox" runat="server" >
        <div class="modal-dialog" >
            <div ID="modalContent" runat="server" class="modal-content">
                <div class="modal-header">  
                    <h4 class="modal-title" id="myModalLabel">
                         <asp:Label ID="lblMessageBoxTitle" runat="server" Text="This is the MessageBox Caption"></asp:Label>
                    </h4>
                </div>
                <div ID="modalbody" class="modal-body" style="width:800px; height:600px">
                    <asp:Image ID="img" runat="server" Height="20px" Width="20px"/>
                    <asp:Label ID="lblMessage" runat="server" Text="Here Goes My Message"></asp:Label>
                </div>
                <div class="modal-footer">
                    <asp:Button ID="btn1" runat="server" OnClick="btn_Click" CssClass="btn btn-default" Text="Another Button" />
                    <asp:Button ID="btn2" runat="server" OnClick="btn_Click" CssClass="btn btn-default" Text="Cancel" />
                    <asp:Button ID="btn3" runat="server" OnClick="btn_Click" CssClass="btn btn-primary" Text="Ok" />
                </div>
            </div>
        </div>
    </asp:Panel>
   </asp:Panel>

And to call it from a button, button code:

protected void btnTest_Click(object sender, EventArgs e)
        {
            MessageBox msgBox = new MessageBox(this, sender, aPanel);
            msgBox.Show("This is my Caption", "this is my message", MessageBox.Buttons.AbortRetryIgnore, MessageBox.DefaultButton.Button1, MessageBox.MessageBoxIcon.Asterisk);

        }

Pull new updates from original GitHub repository into forked GitHub repository

In addition to VonC's answer, you could tweak it to your liking even further.

After fetching from the remote branch, you would still have to merge the commits. I would replace

$ git fetch upstream

with

$ git pull upstream master

since git pull is essentially git fetch + git merge.

How to loop through all elements of a form jQuery

Do one of the two jQuery serializers inside your form submit to get all inputs having a submitted value.

var criteria = $(this).find('input,select').filter(function () {
    return ((!!this.value) && (!!this.name));
}).serializeArray();

var formData = JSON.stringify(criteria);

serializeArray() will produce an array of names and values

0: {name: "OwnLast", value: "Bird"}
1: {name: "OwnFirst", value: "Bob"}
2: {name: "OutBldg[]", value: "PDG"}
3: {name: "OutBldg[]", value: "PDA"}

var criteria = $(this).find('input,select').filter(function () {
    return ((!!this.value) && (!!this.name));
}).serialize();

serialize() creates a text string in standard URL-encoded notation

"OwnLast=Bird&OwnFirst=Bob&OutBldg%5B%5D=PDG&OutBldg%5B%5D=PDA"

How to create a backup of a single table in a postgres database?

I was trying to run pg_dump from within psql command prompt and I was not able to trace output file anywhere on my ubuntu 20.04 box. I tried finding by find / -name "myfilename.sql".

Instead When I tried pg_dump from /home/ubuntu, I found my output file in /home/ubuntu

In Python, how do I use urllib to see if a website is 404 or 200?

import urllib2

try:
    fileHandle = urllib2.urlopen('http://www.python.org/fish.html')
    data = fileHandle.read()
    fileHandle.close()
except urllib2.URLError, e:
    print 'you got an error with the code', e

How to show uncommitted changes in Git and some Git diffs in detail

For me, the only thing which worked is

git diff HEAD

including the staged files, git diff --cached only shows staged files.

How to put/get multiple JSONObjects to JSONArray?

Once you have put the values into the JSONObject then put the JSONObject into the JSONArray staright after.

Something like this maybe:

jsonObj.put("value1", 1);
jsonObj.put("value2", 900);
jsonObj.put("value3", 1368349);
jsonArray.put(jsonObj);

Then create new JSONObject, put the other values into it and add it to the JSONArray:

jsonObj.put("value1", 2);
jsonObj.put("value2", 1900);
jsonObj.put("value3", 136856);
jsonArray.put(jsonObj);

Default nginx client_max_body_size

You have to increase client_max_body_size in nginx.conf file. This is the basic step. But if your backend laravel then you have to do some changes in the php.ini file as well. It depends on your backend. Below I mentioned file location and condition name.

sudo vim /etc/nginx/nginx.conf.

After open the file adds this into HTTP section.

client_max_body_size 100M;

Add 10 seconds to a Date

The Date() object in javascript is not that smart really.

If you just focus on adding seconds it seems to handle things smoothly but if you try to add X number of seconds then add X number of minute and hours, etc, to the same Date object you end up in trouble. So I simply fell back to only using the setSeconds() method and converting my data into seconds (which worked fine).

If anyone can demonstrate adding time to a global Date() object using all the set methods and have the final time come out correctly I would like to see it but I get the sense that one set method is to be used at a time on a given Date() object and mixing them leads to a mess.

var vTime = new Date();

var iSecondsToAdd = ( iSeconds + (iMinutes * 60) + (iHours * 3600) + (iDays * 86400) );

vTime.setSeconds(iSecondsToAdd);

Here is some more documentation that may help:

Get last 5 characters in a string

str.Substring(str.Length - 5)

How to verify CuDNN installation?

To check installation of CUDA, run below command, if it’s installed properly then below command will not throw any error and will print correct version of library.

function lib_installed() { /sbin/ldconfig -N -v $(sed 's/:/ /' <<< $LD_LIBRARY_PATH) 2>/dev/null | grep $1; }
function check() { lib_installed $1 && echo "$1 is installed" || echo "ERROR: $1 is NOT installed"; }
check libcuda
check libcudart

To check installation of CuDNN, run below command, if CuDNN is installed properly then you will not get any error.

function lib_installed() { /sbin/ldconfig -N -v $(sed 's/:/ /' <<< $LD_LIBRARY_PATH) 2>/dev/null | grep $1; }
function check() { lib_installed $1 && echo "$1 is installed" || echo "ERROR: $1 is NOT installed"; }
check libcudnn 

OR

you can run below command from any directory

nvcc -V

it should give output something like this

 nvcc: NVIDIA (R) Cuda compiler driver
 Copyright (c) 2005-2016 NVIDIA Corporation
 Built on Tue_Jan_10_13:22:03_CST_2017
 Cuda compilation tools, release 8.0, V8.0.61

How to get the currently logged in user's user id in Django?

I wrote this in an ajax view, but it is a more expansive answer giving the list of currently logged in and logged out users.

The is_authenticated attribute always returns True for my users, which I suppose is expected since it only checks for AnonymousUsers, but that proves useless if you were to say develop a chat app where you need logged in users displayed.

This checks for expired sessions and then figures out which user they belong to based on the decoded _auth_user_id attribute:

def ajax_find_logged_in_users(request, client_url):
    """
    Figure out which users are authenticated in the system or not.
    Is a logical way to check if a user has an expired session (i.e. they are not logged in)
    :param request:
    :param client_url:
    :return:
    """
    # query non-expired sessions
    sessions = Session.objects.filter(expire_date__gte=timezone.now())
    user_id_list = []
    # build list of user ids from query
    for session in sessions:
        data = session.get_decoded()
        # if the user is authenticated
        if data.get('_auth_user_id'):
            user_id_list.append(data.get('_auth_user_id'))

    # gather the logged in people from the list of pks
    logged_in_users = CustomUser.objects.filter(id__in=user_id_list)
    list_of_logged_in_users = [{user.id: user.get_name()} for user in logged_in_users]

    # Query all logged in staff users based on id list
    all_staff_users = CustomUser.objects.filter(is_resident=False, is_active=True, is_superuser=False)
    logged_out_users = list()
    # for some reason exclude() would not work correctly, so I did this the long way.
    for user in all_staff_users:
        if user not in logged_in_users:
            logged_out_users.append(user)
    list_of_logged_out_users = [{user.id: user.get_name()} for user in logged_out_users]

    # return the ajax response
    data = {
        'logged_in_users': list_of_logged_in_users,
        'logged_out_users': list_of_logged_out_users,
    }
    print(data)

    return HttpResponse(json.dumps(data))

How can I determine the character encoding of an excel file?

For Excel 2010 it should be UTF-8. Instruction by MS :
http://msdn.microsoft.com/en-us/library/bb507946:

"The basic document structure of a SpreadsheetML document consists of the Sheets and Sheet elements, which reference the worksheets in the Workbook. A separate XML file is created for each Worksheet. For example, the SpreadsheetML for a workbook that has two worksheets name MySheet1 and MySheet2 is located in the Workbook.xml file and is shown in the following code example.

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
<workbook xmlns=http://schemas.openxmlformats.org/spreadsheetml/2006/main xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
    <sheets>
        <sheet name="MySheet1" sheetId="1" r:id="rId1" /> 
        <sheet name="MySheet2" sheetId="2" r:id="rId2" /> 
    </sheets>
</workbook>

The worksheet XML files contain one or more block level elements such as SheetData. sheetData represents the cell table and contains one or more Row elements. A row contains one or more Cell elements. Each cell contains a CellValue element that represents the value of the cell. For example, the SpreadsheetML for the first worksheet in a workbook, that only has the value 100 in cell A1, is located in the Sheet1.xml file and is shown in the following code example.

<?xml version="1.0" encoding="UTF-8" ?> 
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <sheetData>
        <row r="1">
            <c r="A1">
                <v>100</v> 
            </c>
        </row>
    </sheetData>
</worksheet>

"

Detection of cell encodings:

https://metacpan.org/pod/Spreadsheet::ParseExcel::Cell

http://forums.asp.net/t/1608228.aspx/1

How to resize image (Bitmap) to a given size?

Bitmap scaledBitmap = scaleDown(realImage, MAX_IMAGE_SIZE, true);

Scale down method:

public static Bitmap scaleDown(Bitmap realImage, float maxImageSize,
        boolean filter) {
    float ratio = Math.min(
            (float) maxImageSize / realImage.getWidth(),
            (float) maxImageSize / realImage.getHeight());
    int width = Math.round((float) ratio * realImage.getWidth());
    int height = Math.round((float) ratio * realImage.getHeight());

    Bitmap newBitmap = Bitmap.createScaledBitmap(realImage, width,
            height, filter);
    return newBitmap;
}

Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

I had the experienced the same issue in different context of my project and there are different scenarios like

 - object is accessed from various source like (server side and client)
 - without any interval accessing the same object from a different place

In the first case

When I issue a server cal, before save the that object their one call from js and trying to save and another place, I got like, js call is going two, three times(I thing that call binding thing cause the issue)

I solved by

e.preventDefault()

The second case,

object.lock()

How to create JSON string in C#

Using Newtonsoft.Json makes it really easier:

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string json = JsonConvert.SerializeObject(product);

Documentation: Serializing and Deserializing JSON

Why do Sublime Text 3 Themes not affect the sidebar?

The most recent version of Sublime has fixed this issue, click on Preferences, click on Theme select Adaptive.sublime-theme. This will change the sidebar to a dark colored background.

Android Log.v(), Log.d(), Log.i(), Log.w(), Log.e() - When to use each one?

Let's go in reverse order:

  • Log.e: This is for when bad stuff happens. Use this tag in places like inside a catch statement. You know that an error has occurred and therefore you're logging an error.

  • Log.w: Use this when you suspect something shady is going on. You may not be completely in full on error mode, but maybe you recovered from some unexpected behavior. Basically, use this to log stuff you didn't expect to happen but isn't necessarily an error. Kind of like a "hey, this happened, and it's weird, we should look into it."

  • Log.i: Use this to post useful information to the log. For example: that you have successfully connected to a server. Basically use it to report successes.

  • Log.d: Use this for debugging purposes. If you want to print out a bunch of messages so you can log the exact flow of your program, use this. If you want to keep a log of variable values, use this.

  • Log.v: Use this when you want to go absolutely nuts with your logging. If for some reason you've decided to log every little thing in a particular part of your app, use the Log.v tag.

And as a bonus...

  • Log.wtf: Use this when stuff goes absolutely, horribly, holy-crap wrong. You know those catch blocks where you're catching errors that you never should get...yeah, if you wanna log them use Log.wtf

Call a stored procedure with another in Oracle

Calling one procedure from another procedure:

One for a normal procedure:

CREATE OR REPLACE SP_1() AS 
BEGIN
/*  BODY */
END SP_1;

Calling procedure SP_1 from SP_2:

CREATE OR REPLACE SP_2() AS
BEGIN
/* CALL PROCEDURE SP_1 */
SP_1();
END SP_2;

Call a procedure with REFCURSOR or output cursor:

CREATE OR REPLACE SP_1
(
oCurSp1 OUT SYS_REFCURSOR
) AS
BEGIN
/*BODY */
END SP_1;

Call the procedure SP_1 which will return the REFCURSOR as an output parameter

CREATE OR REPLACE SP_2 
(
oCurSp2 OUT SYS_REFCURSOR
) AS `enter code here`
BEGIN
/* CALL PROCEDURE SP_1 WITH REF CURSOR AS OUTPUT PARAMETER */
SP_1(oCurSp2);
END SP_2;

wget command to download a file and save as a different filename

Use the -O file option.

E.g.

wget google.com
...
16:07:52 (538.47 MB/s) - `index.html' saved [10728]

vs.

wget -O foo.html google.com
...
16:08:00 (1.57 MB/s) - `foo.html' saved [10728]

Bat file to run a .exe at the command prompt

it is very simple code for executing notepad bellow code type into a notepad and save to extension .bat Exapmle:notepad.bat

start "c:\windows\system32" notepad.exe   

(above code "c:\windows\system32" is path where you kept your .exe program and notepad.exe is your .exe program file file)

enjoy!

enum - getting value of enum on string conversion

You are printing the enum object. Use the .value attribute if you wanted just to print that:

print(D.x.value)

See the Programmatic access to enumeration members and their attributes section:

If you have an enum member and need its name or value:

>>>
>>> member = Color.red
>>> member.name
'red'
>>> member.value
1

You could add a __str__ method to your enum, if all you wanted was to provide a custom string representation:

class D(Enum):
    def __str__(self):
        return str(self.value)

    x = 1
    y = 2

Demo:

>>> from enum import Enum
>>> class D(Enum):
...     def __str__(self):
...         return str(self.value)
...     x = 1
...     y = 2
... 
>>> D.x
<D.x: 1>
>>> print(D.x)
1

Print array elements on separate lines in Bash?

Another useful variant is pipe to tr:

echo "${my_array[@]}" | tr ' ' '\n'

This looks simple and compact

SQL SERVER: Check if variable is null and then assign statement for Where Clause

is null is the syntax I use for such things, when COALESCE is of no help.

Try:

if (@zipCode is null)
  begin
    ([Portal].[dbo].[Address].Position.Filter(@radiusBuff) = 1)   
  end
else 
  begin
    ([Portal].[dbo].[Address].PostalCode=@zipCode )
  end  

Bad Request, Your browser sent a request that this server could not understand

in my magento2 website ,show exactly the same error when click a product,

my solution is to go to edit the value of Search Engine Optimization - URL Key of this product,

make sure that there are only alphabet,number and - in URL Key, such as 100-washed-cotton-duvet-cover-set, deleting all other special characters ,such as % .

How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?

This is rather verbose and don't like it but it's the only thing that worked for me:

if (inputFile && inputFile.current) {
        ((inputFile.current as never) as HTMLInputElement).click()
}

only

if (inputFile && inputFile.current) {
        inputFile.current.click() // also with ! or ? didn't work
}

didn't work for me. Typesript version: 3.9.7 with eslint and recommended rules.

How to prevent Browser cache for php site

You can try this:

    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");
    header("Connection: close");

Hopefully it will help prevent Cache, if any!

Write a file in external storage in Android

 ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext()); //getappcontext for just this activity context get
 File file = contextWrapper.getDir(file_path, Context.MODE_PRIVATE);  
 if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) 
 { 
  saveToExternalStorage.setEnabled(false);
 }
 else
 {
  External_File = new File(getExternalFilesDir(file_path), file_name);//if ready then create a file for external 
 }

}
 try
  {
   FileInputStream fis = new FileInputStream(External_File);
   DataInputStream in = new DataInputStream(fis);
   BufferedReader br =new BufferedReader(new InputStreamReader(in));
   String strLine;
   while ((strLine = br.readLine()) != null) 
   {
    myData = myData + strLine;
   }
   in.close();
  }
  catch (IOException e) 
  {
   e.printStackTrace();
  }
  InputText.setText("Save data of External file::::  "+myData);


private static boolean isExternalStorageReadOnly() 
{ 
 String extStorageState = Environment.getExternalStorageState(); 
 if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState))
 { 
  return true; 
 } 
 return false; 
} 

private static boolean isExternalStorageAvailable()
{ 
 String extStorageState = Environment.getExternalStorageState(); 
 if (Environment.MEDIA_MOUNTED.equals(extStorageState))
 { 
  return true; 
 } 
 return false; 
} 

HTML-5 date field shows as "mm/dd/yyyy" in Chrome, even when valid date is set

Had the same problem. A colleague solved this with jQuery.Globalize.

<script src="/Scripts/jquery.validate.js" type="text/javascript"></script>
<script src="/Scripts/jquery.globalize/globalize.js" type="text/javascript"></script>
<script src="/Scripts/jquery.globalize/cultures/globalize.culture.nl.js"></script>
<script type="text/javascript">
    var lang = 'nl';

    $(function () {
        Globalize.culture(lang);
    });

    // fixing a weird validation issue with dates (nl date notation) and Google Chrome
    $.validator.methods.date = function(value, element) {
        var d = Globalize.parseDate(value);
        return this.optional(element) || !/Invalid|NaN/.test(d);
    };
</script>

I am using jQuery Datepicker for selecting the date.

String concatenation: concat() vs "+" operator

When using +, the speed decreases as the string's length increases, but when using concat, the speed is more stable, and the best option is using the StringBuilder class which has stable speed in order to do that.

I guess you can understand why. But the totally best way for creating long strings is using StringBuilder() and append(), either speed will be unacceptable.

How to get JavaScript variable value in PHP

You will need to use JS to send the URL back with a variable in it such as: http://www.site.com/index.php?uid=1

by using something like this in JS:

window.location.href=”index.php?uid=1";

Then in the PHP code use $_GET:

$somevar = $_GET["uid"]; //puts the uid varialbe into $somevar

Calculate mean across dimension in a 2D array

If you do this a lot, NumPy is the way to go.

If for some reason you can't use NumPy:

>>> map(lambda x:sum(x)/float(len(x)), zip(*a))
[45.0, 10.5]

Excel 2010: how to use autocomplete in validation list

Here is a very good way to handle this (found on ozgrid):

Let's say your list is on Sheet2 and you wish to use the Validation List with AutoComplete on Sheet1.

On Sheet1 A1 Enter =Sheet2!A1 and copy down including as many spare rows as needed (say 300 rows total). Hide these rows and use this formula in the Refers to: for a dynamic named range called MyList:

=OFFSET(Sheet1!$A$1,0,0,MATCH("*",Sheet1!$A$1:$A$300,-1),1)

Now in the cell immediately below the last hidden row use Data Validation and for the List Source use =MyList

[EDIT] Adapted version for Excel 2007+ (couldn't test on 2010 though but AFAIK, there is nothing really specific to a version).
Let's say your data source is on Sheet2!A1:A300 and let's assume your validation list (aka autocomplete) is on cell Sheet1!A1.

  1. Create a dynamic named range MyList that will depend on the value of the cell where you put the validation

    =OFFSET(Sheet2!$A$1,MATCH(Sheet1!$A$1&"*",Sheet2!$A$1:$A$300,0)-1,0,COUNTA(Sheet2!$A:$A))

  2. Add the validation list on cell Sheet1!A1 that will refert to the list =MyList

Caveats

  1. This is not a real autocomplete as you have to type first and then click on the validation arrow : the list will then begin at the first matching element of your list

  2. The list will go till the end of your data. If you want to be more precise (keep in the list only the matching elements), you can change the COUNTA with a SUMLPRODUCT that will calculate the number of matching elements

  3. Your source list must be sorted

How to compare character ignoring case in primitive types

You have to consider the Turkish I problem when comparing characters/ lowercasing / uppercasing:

I suggest to convert to String and use toLowerCase with invariant culture (in most cases at least).

public final static Locale InvariantLocale = new Locale(Empty, Empty, Empty); str.toLowerCase(InvariantLocale)

See similar C# string.ToLower() and string.ToLowerInvariant()

Note: Don't use String.equalsIgnoreCase http://nikolajlindberg.blogspot.co.il/2008/03/beware-of-java-comparing-turkish.html

SVN checkout the contents of a folder, not the folder itself

Just add the directory on the command line:

svn checkout svn://192.168.1.1/projectname/ target-directory/