Programs & Examples On #Isight

iSight is a webcam, both external and internal, developed and marketed by Apple Inc. The external iSight was connected to a computer via a FireWire cable, and came with a set of mounts to place it atop any then-current Apple display, laptop computer, all-in-one desktop computer, or flat surface. Currently iSight camera are

Timestamp conversion in Oracle for YYYY-MM-DD HH:MM:SS format

Use TO_TIMESTAMP function

TO_TIMESTAMP(date_string,'YYYY-MM-DD HH24:MI:SS')

Finding out the name of the original repository you cloned from in Git

This is quick Bash command, that you're probably searching for, will print only a basename of the remote repository:

Where you fetch from:

basename $(git remote show -n origin | grep Fetch | cut -d: -f2-)

Alternatively where you push to:

basename $(git remote show -n origin | grep Push | cut -d: -f2-)

Especially the -n option makes the command much quicker.

Bind TextBox on Enter-key press

This is how I solved this problem. I created a special event handler that went into the code behind:

private void TextBox_KeyEnterUpdate(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        TextBox tBox = (TextBox)sender;
        DependencyProperty prop = TextBox.TextProperty;

        BindingExpression binding = BindingOperations.GetBindingExpression(tBox, prop);
        if (binding != null) { binding.UpdateSource(); }
    }
}

Then I just added this as a KeyUp event handler in the XAML:

<TextBox Text="{Binding TextValue1}" KeyUp="TextBox_KeyEnterUpdate" />
<TextBox Text="{Binding TextValue2}" KeyUp="TextBox_KeyEnterUpdate" />

The event handler uses its sender reference to cause it's own binding to get updated. Since the event handler is self-contained then it should work in a complex DataTemplate. This one event handler can now be added to all the textboxes that need this feature.

Check if inputs are empty using jQuery

Consider using the jQuery validation plugin instead. It may be slightly overkill for simple required fields, but it mature enough that it handles edge cases you haven't even thought of yet (nor would any of us until we ran into them).

You can tag the required fields with a class of "required", run a $('form').validate() in $(document).ready() and that's all it takes.

It's even hosted on the Microsoft CDN too, for speedy delivery: http://www.asp.net/ajaxlibrary/CDN.ashx

Android: Clear the back stack

In kotlin it is almost same like java. Only | symbol is replaced by or text. So, it is written like-

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)

How to ignore certain files in Git

  1. Go to .gitignore file and add the entry for the files you want to ignore
  2. Run git rm -r --cached .
  3. Now run git add .

PHP - Insert date into mysql

Unless you want to insert different dates than "today", you can use CURDATE():

$sql = 'INSERT INTO data_tables (title, date_of_event) VALUES ("%s", CURDATE())';
$sql = sprintf ($sql, $_POST['post_title']);

PS! Please do not forget to sanitize your MySQL input, especially via mysql_real_escape_string ()

String comparison technique used by Python

Strings are compared lexicographically using the numeric equivalents (the result of the built-in function ord()) of their characters. Unicode and 8-bit strings are fully interoperable in this behavior.

How to Set/Update State of StatefulWidget from other StatefulWidget in Flutter?

Old one but I would add my answer as per my findings:

var ancestralState = context.findAncestorStateOfType<ParentState>();
      ancestralState.setState(() {
        // here you can access public vars and update state.
        ...
      });

How to pattern match using regular expression in Scala?

You can do this because regular expressions define extractors but you need to define the regex pattern first. I don't have access to a Scala REPL to test this but something like this should work.

val Pattern = "([a-cA-C])".r
word.firstLetter match {
   case Pattern(c) => c bound to capture group here
   case _ =>
}

How to navigate through a vector using iterators? (C++)

In C++-11 you can do:

std::vector<int> v = {0, 1, 2, 3, 4, 5};
for (auto i : v)
{
   // access by value, the type of i is int
   std::cout << i << ' ';
}
std::cout << '\n';

See here for variations: https://en.cppreference.com/w/cpp/language/range-for

Filtering array of objects with lodash based on property value

Lodash has a "map" function that works just like jQuerys:

_x000D_
_x000D_
var myArr =  [{ name: "john", age:23 },_x000D_
              { name: "john", age:43 },_x000D_
              { name: "jimi", age:10 },_x000D_
              { name: "bobi", age:67 }];_x000D_
_x000D_
var johns = _.map(myArr, function(o) {_x000D_
    if (o.name == "john") return o;_x000D_
});_x000D_
_x000D_
// Remove undefines from the array_x000D_
johns = _.without(johns, undefined)
_x000D_
_x000D_
_x000D_

How to retrieve the hash for the current commit in Git?

Another one, using git log:

git log -1 --format="%H"

It's very similar to the of @outofculture though a bit shorter.

git undo all uncommitted or unsaved changes

there is also git stash - which "stashes" your local changes and can be reapplied at a later time or dropped if is no longer required

more info on stashing

How to preSelect an html dropdown list with php?

you can use this..

<select name="select_name">
    <option value="1"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='1')?' selected="selected"':'');?>>Yes</option>
    <option value="2"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='2')?' selected="selected"':'');?>>No</option>
    <option value="3"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='3')?' selected="selected"':'');?>>Fine</option>
</select>

Java ElasticSearch None of the configured nodes are available

Check your elasticsearch.yml, "transport.host" property must be "0.0.0.0" not "127.0.0.1" or "localhost"

How to display image from database using php

For example if you use this code , you can load image from db (mysql) and display it in php5 ;)

<?php
   $con =mysql_connect("localhost", "root" , "");
   $sdb= mysql_select_db("my_database",$con);
   $sql = "SELECT * FROM `news` WHERE 1";
   $mq = mysql_query($sql) or die ("not working query");
   $row = mysql_fetch_array($mq) or die("line 44 not working");
   $s=$row['photo'];
   echo $row['photo'];

   echo '<img src="'.$s.'" alt="HTML5 Icon" style="width:128px;height:128px">';
   ?>

How do I do a multi-line string in node.js?

Take a look at the mstring module for node.js.

This is a simple little module that lets you have multi-line strings in JavaScript.

Just do this:

var M = require('mstring')

var mystring = M(function(){/*** Ontario Mining and Forestry Group ***/})

to get

mystring === "Ontario\nMining and\nForestry\nGroup"

And that's pretty much it.

How It Works
In Node.js, you can call the .toString method of a function, and it will give you the source code of the function definition, including any comments. A regular expression grabs the content of the comment.

Yes, it's a hack. Inspired by a throwaway comment from Dominic Tarr.


note: The module (as of 2012/13/11) doesn't allow whitespace before the closing ***/, so you'll need to hack it in yourself.

MySQL select where column is not empty

you can use like operator wildcard to achieve this:

SELECT t.phone, 
       t.phone2 
FROM jewishyellow.users t
WHERE t.phone LIKE '813%' 
  AND t.phone2 like '[0-9]';

in this way, you could get all phone2 that have a number prefix.

Split code over multiple lines in an R script

Bah, comments are too small. Anyway, @Dirk is very right.

R doesn't need to be told the code starts at the next line. It is smarter than Python ;-) and will just continue to read the next line whenever it considers the statement as "not finished". Actually, in your case it also went to the next line, but R takes the return as a character when it is placed between "".

Mind you, you'll have to make sure your code isn't finished. Compare

a <- 1 + 2
+ 3

with

a <- 1 + 2 +
3

So, when spreading code over multiple lines, you have to make sure that R knows something is coming, either by :

  • leaving a bracket open, or
  • ending the line with an operator

When we're talking strings, this still works but you need to be a bit careful. You can open the quotation marks and R will read on until you close it. But every character, including the newline, will be seen as part of the string :

x <- "This is a very
long string over two lines."
x
## [1] "This is a very\nlong string over two lines."
cat(x)
## This is a very
## long string over two lines.

That's the reason why in this case, your code didn't work: a path can't contain a newline character (\n). So that's also why you better use the solution with paste() or paste0() Dirk proposed.

When should I use a List vs a LinkedList

Essentially, a List<> in .NET is a wrapper over an array. A LinkedList<> is a linked list. So the question comes down to, what is the difference between an array and a linked list, and when should an array be used instead of a linked list. Probably the two most important factors in your decision of which to use would come down to:

  • Linked lists have much better insertion/removal performance, so long as the insertions/removals are not on the last element in the collection. This is because an array must shift all remaining elements that come after the insertion/removal point. If the insertion/removal is at the tail end of the list however, this shift is not needed (although the array may need to be resized, if its capacity is exceeded).
  • Arrays have much better accessing capabilities. Arrays can be indexed into directly (in constant time). Linked lists must be traversed (linear time).

How do I get logs/details of ansible-playbook module executions?

The playbook script task will generate stdout just like the non-playbook command, it just needs to be saved to a variable using register. Once we've got that, the debug module can print to the playbook output stream.

tasks:
- name: Hello yourself
  script: test.sh
  register: hello

- name: Debug hello
  debug: var=hello

- name: Debug hello.stdout as part of a string
  debug: "msg=The script's stdout was `{{ hello.stdout }}`."

Output should look something like this:

TASK: [Hello yourself] ******************************************************** 
changed: [MyTestHost]

TASK: [Debug hello] *********************************************************** 
ok: [MyTestHost] => {
    "hello": {
        "changed": true, 
        "invocation": {
            "module_args": "test.sh", 
            "module_name": "script"
        }, 
        "rc": 0, 
        "stderr": "", 
        "stdout": "Hello World\r\n", 
        "stdout_lines": [
            "Hello World"
        ]
    }
}

TASK: [Debug hello.stdout as part of a string] ******************************** 
ok: [MyTestHost] => {
    "msg": "The script's stdout was `Hello World\r\n`."
}

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

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

How to add to the end of lines containing a pattern with sed or awk?

Solution with awk:

awk '{if ($1 ~ /^all/) print $0, "anotherthing"; else print $0}' file

Simply: if the row starts with all print the row plus "anotherthing", else print just the row.

Wait 5 seconds before executing next line

You should not just try to pause 5 seconds in javascript. It doesn't work that way. You can schedule a function of code to run 5 seconds from now, but you have to put the code that you want to run later into a function and the rest of your code after that function will continue to run immediately.

For example:

function stateChange(newState) {
    setTimeout(function(){
        if(newState == -1){alert('VIDEO HAS STOPPED');}
    }, 5000);
}

But, if you have code like this:

stateChange(-1);
console.log("Hello");

The console.log() statement will run immediately. It will not wait until after the timeout fires in the stateChange() function. You cannot just pause javascript execution for a predetermined amount of time.

Instead, any code that you want to run delays must be inside the setTimeout() callback function (or called from that function).

If you did try to "pause" by looping, then you'd essentially "hang" the Javascript interpreter for a period of time. Because Javascript runs your code in only a single thread, when you're looping nothing else can run (no other event handlers can get called). So, looping waiting for some variable to change will never work because no other code can run to change that variable.

Why doesn't Java allow overriding of static methods?

Method overriding is made possible by dynamic dispatching, meaning that the declared type of an object doesn't determine its behavior, but rather its runtime type:

Animal lassie = new Dog();
lassie.speak(); // outputs "woof!"
Animal kermit = new Frog();
kermit.speak(); // outputs "ribbit!"

Even though both lassie and kermit are declared as objects of type Animal, their behavior (method .speak()) varies because dynamic dispatching will only bind the method call .speak() to an implementation at run time - not at compile time.

Now, here's where the static keyword starts to make sense: the word "static" is an antonym for "dynamic". So the reason why you can't override static methods is because there is no dynamic dispatching on static members - because static literally means "not dynamic". If they dispatched dynamically (and thus could be overriden) the static keyword just wouldn't make sense anymore.

How to upload images into MySQL database using PHP code

This is the perfect code for uploading and displaying image through MySQL database.

<html>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" name="submit" value="Upload"/>
</form>
<?php
    if(isset($_POST['submit']))
    {
     if(getimagesize($_FILES['image']['tmp_name'])==FALSE)
     {
        echo " error ";
     }
     else
     {
        $image = $_FILES['image']['tmp_name'];
        $image = addslashes(file_get_contents($image));
        saveimage($image);
     }
    }
    function saveimage($image)
    {
        $dbcon=mysqli_connect('localhost','root','','dbname');
        $qry="insert into tablename (name) values ('$image')";
        $result=mysqli_query($dbcon,$qry);
        if($result)
        {
            echo " <br/>Image uploaded.";
            header('location:urlofpage.php');
        }
        else
        {
            echo " error ";
        }
    }
?>
</body>
</html>

Adding event listeners to dynamically added elements using jQuery

Using .on() you can define your function once, and it will execute for any dynamically added elements.

for example

$('#staticDiv').on('click', 'yourSelector', function() {
  //do something
});

How to align absolutely positioned element to center?

Move the parent div to the middle with

left: 50%;
top: 50%;
margin-left: -50px;

Move the second layer over the other with

position: relative;
left: -100px;

Syntax error due to using a reserved word as a table or column name in MySQL

The Problem

In MySQL, certain words like SELECT, INSERT, DELETE etc. are reserved words. Since they have a special meaning, MySQL treats it as a syntax error whenever you use them as a table name, column name, or other kind of identifier - unless you surround the identifier with backticks.

As noted in the official docs, in section 10.2 Schema Object Names (emphasis added):

Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers.

...

If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.

...

The identifier quote character is the backtick ("`"):

A complete list of keywords and reserved words can be found in section 10.3 Keywords and Reserved Words. In that page, words followed by "(R)" are reserved words. Some reserved words are listed below, including many that tend to cause this issue.

  • ADD
  • AND
  • BEFORE
  • BY
  • CALL
  • CASE
  • CONDITION
  • DELETE
  • DESC
  • DESCRIBE
  • FROM
  • GROUP
  • IN
  • INDEX
  • INSERT
  • INTERVAL
  • IS
  • KEY
  • LIKE
  • LIMIT
  • LONG
  • MATCH
  • NOT
  • OPTION
  • OR
  • ORDER
  • PARTITION
  • RANK
  • REFERENCES
  • SELECT
  • TABLE
  • TO
  • UPDATE
  • WHERE

The Solution

You have two options.

1. Don't use reserved words as identifiers

The simplest solution is simply to avoid using reserved words as identifiers. You can probably find another reasonable name for your column that is not a reserved word.

Doing this has a couple of advantages:

  • It eliminates the possibility that you or another developer using your database will accidentally write a syntax error due to forgetting - or not knowing - that a particular identifier is a reserved word. There are many reserved words in MySQL and most developers are unlikely to know all of them. By not using these words in the first place, you avoid leaving traps for yourself or future developers.

  • The means of quoting identifiers differs between SQL dialects. While MySQL uses backticks for quoting identifiers by default, ANSI-compliant SQL (and indeed MySQL in ANSI SQL mode, as noted here) uses double quotes for quoting identifiers. As such, queries that quote identifiers with backticks are less easily portable to other SQL dialects.

Purely for the sake of reducing the risk of future mistakes, this is usually a wiser course of action than backtick-quoting the identifier.

2. Use backticks

If renaming the table or column isn't possible, wrap the offending identifier in backticks (`) as described in the earlier quote from 10.2 Schema Object Names.

An example to demonstrate the usage (taken from 10.3 Keywords and Reserved Words):

mysql> CREATE TABLE interval (begin INT, end INT);
ERROR 1064 (42000): You have an error in your SQL syntax.
near 'interval (begin INT, end INT)'

mysql> CREATE TABLE `interval` (begin INT, end INT); Query OK, 0 rows affected (0.01 sec)

Similarly, the query from the question can be fixed by wrapping the keyword key in backticks, as shown below:

INSERT INTO user_details (username, location, `key`)
VALUES ('Tim', 'Florida', 42)";               ^   ^

Should I use Python 32bit or Python 64bit

64 bit version will allow a single process to use more RAM than 32 bit, however you may find that the memory footprint doubles depending on what you are storing in RAM (Integers in particular).

For example if your app requires > 2GB of RAM, so you switch from 32bit to 64bit you may find that your app is now requiring > 4GB of RAM.

Check whether all of your 3rd party modules are available in 64 bit, otherwise it may be easier to stick to 32bit in the meantime

Basic http file downloading and saving to disk in python?

Exotic Windows Solution

import subprocess

subprocess.run("powershell Invoke-WebRequest {} -OutFile {}".format(your_url, filename), shell=True)

How do I free my port 80 on localhost Windows?

I was trying to install nginx from here - http://nginx.org/en/docs/windows.html

Going to http://localhost/ will show something, at least a proper "not found" message
This is because 80 is the default port, and it was taken by other processes.

Now run below command:

net stop http

    // Above command stopped below services  
    // - SSDP Discovery  
    // - Print Spooler  
    // - BranchCache  
    // - Function Discovery Resource Publication  
    // - Function Discovery Provider Host  

Now, going to http://localhost/ will fail with a broken link page message.

Main process was BranchCache
This process, after stopped, will restart in a few seconds.
So we need to run other commands we need soon, an example below:

// this will stop
net stop http

// immeidately run other command you want to
start nginx

Now, going to http://localhost/ gave me:

Welcome to nginx!

Hope that helps.

Authorize attribute in ASP.NET MVC

One advantage is that you are compiling access into the application, so it cannot accidentally be changed by someone modifying the Web.config.

This may not be an advantage to you, and might be a disadvantage. But for some kinds of access, it may be preferrable.

Plus, I find that authorization information in the Web.config pollutes it, and makes it harder to find things. So in some ways its preference, in others there is no other way to do it.

Embedding JavaScript engine into .NET

i believe all the major opensource JS engines (JavaScriptCore, SpiderMonkey, V8, and KJS) provide embedding APIs. The only one I am actually directly familiar with is JavaScriptCore (which is name of the JS engine the SquirrelFish lives in) which provides a pure C API. If memory serves (it's been a while since i used .NET) .NET has fairly good support for linking in C API's.

I'm honestly not sure what the API's for the other engines are like, but I do know that they all provide them.

That said, depending on your purposes JScript.NET may be best, as all of these other engines will require you to include them with your app, as JSC is the only one that actually ships with an OS, but that OS is MacOS :D

Find an object in array?

Swift 4,

Another way to achieve this using filter function,

if let object = elements.filter({ $0.title == "title" }).first {
    print("found")
} else {
    print("not found")
}

Different between parseInt() and valueOf() in java?

  • valueOf - converts to Wrapper class
  • parseInt - converts to primitive type

Integer.parseInt accept only String and return primitive integer type (int).

   public static int parseInt(String s) throws NumberFormatException {
        return parseInt(s,10);
    }

Iteger.valueOf accept int and String. If value is String, valueOf convert it to the the simple int using parseInt and return new Integer if input is less than -128 or greater than 127. If input is in range (-128 - 127) it always return the Integer objects from an internal IntegerCache. Integer class maintains an inner static IntegerCache class which acts as the cache and holds integer objects from -128 to 127 and that’s why when we try to get integer object for 127 (for example) we always get the same object.

Iteger.valueOf(200) will give new Integer from 200. It's like new Integer(200) Iteger.valueOf(127) is the same as Integer = 127;

If you wont to convert String to the Integer use Iteger.valueOf.

If you wont to convert String to the simple int use Integer.parseInt. It works faster.

  public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

  public static Integer valueOf(String s) throws NumberFormatException {
        return Integer.valueOf(parseInt(s, 10));
  }

  private static class IntegerCache {
      static final int low = -128;
      static final int high;
      static final Integer cache[];

    static {
        // high value may be configured by property
        int h = 127;
        String integerCacheHighPropValue =
            sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
        if (integerCacheHighPropValue != null) {
            try {
                int i = parseInt(integerCacheHighPropValue);
                i = Math.max(i, 127);
                // Maximum array size is Integer.MAX_VALUE
                h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
            } catch( NumberFormatException nfe) {
                // If the property cannot be parsed into an int, ignore it.
            }
        }
        high = h;

        cache = new Integer[(high - low) + 1];
        int j = low;
        for(int k = 0; k < cache.length; k++)
            cache[k] = new Integer(j++);

        // range [-128, 127] must be interned (JLS7 5.1.7)
        assert IntegerCache.high >= 127;
    }

    private IntegerCache() {}
  }

And comparing Integer.valueOf(127) == Integer.valueOf(127) return true

Integer a = 127; // Compiler converts this line to Integer a = Integer.valueOf(127);
Integer b = 127; // Compiler converts this line to Integer b = Integer.valueOf(127);
a == b; // return true 

Because it takes the Integer objects with the same references from the cache.

But Integer.valueOf(128) == Integer.valueOf(128) is false, because 128 is out of IntegerCache range and it return new Integer, so objects will have different references.

Regex to check whether a string contains only numbers

var reg = /^\d+$/;

should do it. The original matches anything that consists of exactly one digit.

Variable's memory size in Python

Regarding the internal structure of a Python long, check sys.int_info (or sys.long_info for Python 2.7).

>>> import sys
>>> sys.int_info
sys.int_info(bits_per_digit=30, sizeof_digit=4)

Python either stores 30 bits into 4 bytes (most 64-bit systems) or 15 bits into 2 bytes (most 32-bit systems). Comparing the actual memory usage with calculated values, I get

>>> import math, sys
>>> a=0
>>> sys.getsizeof(a)
24
>>> a=2**100
>>> sys.getsizeof(a)
40
>>> a=2**1000
>>> sys.getsizeof(a)
160
>>> 24+4*math.ceil(100/30)
40
>>> 24+4*math.ceil(1000/30)
160

There are 24 bytes of overhead for 0 since no bits are stored. The memory requirements for larger values matches the calculated values.

If your numbers are so large that you are concerned about the 6.25% unused bits, you should probably look at the gmpy2 library. The internal representation uses all available bits and computations are significantly faster for large values (say, greater than 100 digits).

Checking if a variable is initialized

If for instance you use strings instead of chars, you might be able do something like this:

    //a is a string of length 1
    string a;
    //b is the char in which we'll put the char stored in a
    char b;
    bool isInitialized(){
      if(a.length() != NULL){
        b = a[0];
        return true;
      }else return false;
    }

Accessing members of items in a JSONArray with Java

HashMap regs = (HashMap) parser.parse(stringjson);

(String)((HashMap)regs.get("firstlevelkey")).get("secondlevelkey");

Is there a download function in jsFiddle?

There is not such a proper way to download all the things all together from JSFiddle but there is a hack way to do just that. Simply add "embedded/" or "embedded/result/" at the end of your JSFiddle URL!, and then you can save the whole page as an HTML file + the external libraries (if you wants).

Do you get charged for a 'stopped' instance on EC2?

No.

You get charged for:

  1. Online time
  2. Storage space (assumably you store the image on S3 [EBS])
  3. Elastic IP addresses
  4. Bandwidth

So... if you stop the EC2 instance you will only have to pay for the storage of the image on S3 (assuming you store an image ofcourse) and any IP addresses you've reserved.

How to restore SQL Server 2014 backup in SQL Server 2008

Please use SQL Server Data Tools from SQL Server Integration Services (Transfer Database Task) as here: https://stackoverflow.com/a/27777823/2127493

Http Get using Android HttpURLConnection

Try getting the input stream from this you can then get the text data as so:-

    URL url;
    HttpURLConnection urlConnection = null;
    try {
        url = new URL("http://www.mysite.se/index.asp?data=99");

        urlConnection = (HttpURLConnection) url
                .openConnection();

        InputStream in = urlConnection.getInputStream();

        InputStreamReader isw = new InputStreamReader(in);

        int data = isw.read();
        while (data != -1) {
            char current = (char) data;
            data = isw.read();
            System.out.print(current);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }    
    }

You can probably use other inputstream readers such as buffered reader also.

The problem is that when you open the connection - it does not 'pull' any data.

How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter?

This worked for me

class _SplashScreenState extends State<SplashScreen> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: FittedBox(
        child: Image.asset("images/my_image.png"),
        fit: BoxFit.fill,
      ),);
  }
}

Creating your own header file in C

#ifndef MY_HEADER_H
# define MY_HEADER_H

//put your function headers here

#endif

MY_HEADER_H serves as a double-inclusion guard.

For the function declaration, you only need to define the signature, that is, without parameter names, like this:

int foo(char*);

If you really want to, you can also include the parameter's identifier, but it's not necessary because the identifier would only be used in a function's body (implementation), which in case of a header (parameter signature), it's missing.

This declares the function foo which accepts a char* and returns an int.

In your source file, you would have:

#include "my_header.h"

int foo(char* name) {
   //do stuff
   return 0;
}

jQuery posting valid json in request body

An actual JSON request would look like this:

data: '{"command":"on"}',

Where you're sending an actual JSON string. For a more general solution, use JSON.stringify() to serialize an object to JSON, like this:

data: JSON.stringify({ "command": "on" }),

To support older browsers that don't have the JSON object, use json2.js which will add it in.


What's currently happening is since you have processData: false, it's basically sending this: ({"command":"on"}).toString() which is [object Object]...what you see in your request.

Select current date by default in ASP.Net Calendar control

I too had the same problem in VWD 2010 and, by chance, I had two controls. One was available in code behind and one wasn't accessible. I thought that the order of statements in the controls was causing the issue. I put 'runat' before 'SelectedDate' and that seemed to fix it. When I put 'runat' after 'SelectedDate' it still worked! Unfortunately, I now don't know why it didn't work and haven't got the original that didn't work.

These now all work:-

<asp:Calendar ID="calDateFrom" SelectedDate="08/02/2011" SelectionMode="Day" runat="server"></asp:Calendar>
<asp:Calendar runat="server" SelectionMode="Day" SelectedDate="08/15/2011 12:00:00 AM" ID="Calendar1" VisibleDate="08/03/2011 12:00:00 AM"></asp:Calendar>
<asp:Calendar SelectionMode="Day" SelectedDate="08/31/2011 12:00:00 AM" runat="server" ID="calDateTo"></asp:Calendar>

Serializing to JSON in jQuery

I did find this somewhere. Can't remember where though... probably on StackOverflow :)

$.fn.serializeObject = function(){
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

jQuery Set Cursor Position in Text Area

I had to get this working for contenteditable elements and jQuery and tought someone might want it ready to use:

$.fn.getCaret = function(n) {
    var d = $(this)[0];
    var s, r;
    r = document.createRange();
    r.selectNodeContents(d);
    s = window.getSelection();
    console.log('position: '+s.anchorOffset+' of '+s.anchorNode.textContent.length);
    return s.anchorOffset;
};

$.fn.setCaret = function(n) {
    var d = $(this)[0];
    d.focus();
    var r = document.createRange();
    var s = window.getSelection();
    r.setStart(d.childNodes[0], n);
    r.collapse(true);
    s.removeAllRanges();
    s.addRange(r);
    console.log('position: '+s.anchorOffset+' of '+s.anchorNode.textContent.length);
    return this;
};

Usage $(selector).getCaret() returns the number offset and $(selector).setCaret(num) establishes the offeset and sets focus on element.

Also a small tip, if you run $(selector).setCaret(num) from console it will return the console.log but you won't visualize the focus since it is established at the console window.

Bests ;D

Table row and column number in jQuery

$('td').click(function() {
    var myCol = $(this).index();
    var $tr = $(this).closest('tr');
    var myRow = $tr.index();
});

Capture the screen shot using .NET

It's certainly possible to grab a screenshot using the .NET Framework. The simplest way is to create a new Bitmap object and draw into that using the Graphics.CopyFromScreen method.

Sample code:

using (Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width, 
                                            Screen.PrimaryScreen.Bounds.Height))
using (Graphics g = Graphics.FromImage(bmpScreenCapture))
{
    g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
                     Screen.PrimaryScreen.Bounds.Y,
                     0, 0,
                     bmpScreenCapture.Size,
                     CopyPixelOperation.SourceCopy);
}

Caveat: This method doesn't work properly for layered windows. Hans Passant's answer here explains the more complicated method required to get those in your screen shots.

SQL Error with Order By in Subquery

Add the Top command to your sub query...

SELECT 
(
SELECT TOP 100 PERCENT 
    COUNT(1) 
FROM 
    Seanslar 
WHERE 
    MONTH(tarihi) = 4
GROUP BY 
    refKlinik_id
ORDER BY 
    refKlinik_id
) as dorduncuay

:)

How to git ignore subfolders / subdirectories?

You can use .gitignore in the top level to ignore all directories in the project with the same name. For example:

Debug/
Release/

This should update immediately so it's visible when you do git status. Ensure that these directories are not already added to git, as that will override the ignores.

unexpected T_VARIABLE, expecting T_FUNCTION

check that you entered a variable as argument with the '$' symbol

Get only filename from url in php without any variable values which exist in the url

$url = "learner.com/learningphp.php?lid=1348";
$l = parse_url($url);
print_r(stristr($l['path'], "/"));

how to add values to an array of objects dynamically in javascript?

In Year 2019, we can use Javascript's ES6 Spread syntax to do it concisely and efficiently

data = [...data, {"label": 2, "value": 13}]

Examples

_x000D_
_x000D_
var data = [_x000D_
      {"label" : "1", "value" : 12},_x000D_
      {"label" : "1", "value" : 12},_x000D_
      {"label" : "1", "value" : 12},_x000D_
    ];_x000D_
    _x000D_
data = [...data, {"label" : "2", "value" : 14}] _x000D_
console.log(data)
_x000D_
_x000D_
_x000D_

For your case (i know it was in 2011), we can do it with map() & forEach() like below

_x000D_
_x000D_
var lab = ["1","2","3","4"];_x000D_
var val = [42,55,51,22];_x000D_
_x000D_
//Using forEach()_x000D_
var data = [];_x000D_
val.forEach((v,i) => _x000D_
   data= [...data, {"label": lab[i], "value":v}]_x000D_
)_x000D_
_x000D_
//Using map()_x000D_
var dataMap = val.map((v,i) => _x000D_
 ({"label": lab[i], "value":v})_x000D_
)_x000D_
_x000D_
console.log('data: ', data);_x000D_
console.log('dataMap : ', dataMap);
_x000D_
_x000D_
_x000D_

Read and write a String from text file

I want to show you only the first part, that is read. Here's how simply you can read:

Swift 3:

let s = try String(contentsOfFile: Bundle.main.path(forResource: "myFile", ofType: "txt")!)

Swift 2:

let s = try! String(contentsOfFile: NSBundle.mainBundle().pathForResource("myFile", ofType: "txt")!)

How to get the list of all database users

Go for this:

 SELECT name,type_desc FROM sys.sql_logins

Displaying files (e.g. images) stored in Google Drive on a website

Here's the simple view link:

https://drive.google.com/uc?id=FILE_ID

e.g. https://drive.google.com/uc?id=0B9o1MNFt5ld1N3k1cm9tVnZxQjg

You can do the same for other file types, e.g. MP3, PDF, etc.

How to set Navigation Drawer to be opened from right to left

Making it open from rtl isn't good for user experience, to make it responsive to the user locale I just added the following line to my DrawerLayout parameters:

android:layoutDirection="locale"

Added it to my AppBarLayout to make the hamburger layout match the drawer opening direction too.

How does facebook, gmail send the real time notification?

According to a slideshow about Facebook's Messaging system, Facebook uses the comet technology to "push" message to web browsers. Facebook's comet server is built on the open sourced Erlang web server mochiweb.

In the picture below, the phrase "channel clusters" means "comet servers".

System overview

Many other big web sites build their own comet server, because there are differences between every company's need. But build your own comet server on a open source comet server is a good approach.

You can try icomet, a C1000K C++ comet server built with libevent. icomet also provides a JavaScript library, it is easy to use as simple as:

var comet = new iComet({
    sign_url: 'http://' + app_host + '/sign?obj=' + obj,
    sub_url: 'http://' + icomet_host + '/sub',
    callback: function(msg){
        // on server push
        alert(msg.content);
    }
});

icomet supports a wide range of Browsers and OSes, including Safari(iOS, Mac), IEs(Windows), Firefox, Chrome, etc.

How can I replace a regex substring match in Javascript?

using str.replace(regex, $1);:

var str   = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;

if (str.match(regex)) {
    str = str.replace(regex, "$1" + "1" + "$2");
}

Edit: adaptation regarding the comment

Structuring online documentation for a REST API

That's a very complex question for a simple answer.

You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like apiary.io and apiblueprint.org.

Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.

At the very top level I think quality REST API docs require at least the following:

  • a list of all your API endpoints (base/relative URLs)
  • corresponding HTTP GET/POST/... method type for each endpoint
  • request/response MIME-type (how to encode params and parse replies)
  • a sample request/response, including HTTP headers
  • type and format specified for all params, including those in the URL, body and headers
  • a brief text description and important notes
  • a short code snippet showing the use of the endpoint in popular web programming languages

Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.

ValueError: math domain error

Your code is doing a log of a number that is less than or equal to zero. That's mathematically undefined, so Python's log function raises an exception. Here's an example:

>>> from math import log
>>> log(-1)
Traceback (most recent call last):
  File "<pyshell#59>", line 1, in <module>
    log(-1)
ValueError: math domain error

Without knowing what your newtonRaphson2 function does, I'm not sure I can guess where the invalid x[2] value is coming from, but hopefully this will lead you on the right track.

Running conda with proxy

One mistake I was making was saving the file as a.condarc or b.condarc.

Save it only as .condarc and paste the following code in the file and save the file in your home directory. Make necessary changes to hostname, user etc.

channels:
- defaults

show_channel_urls: True
allow_other_channels: True

proxy_servers:
    http: http://user:pass@hostname:port
    https: http://user:pass@hostname:port


ssl_verify: False

How to make a promise from setTimeout

This is not an answer to the original question. But, as an original question is not a real-world problem it should not be a problem. I tried to explain to a friend what are promises in JavaScript and the difference between promise and callback.

Code below serves as an explanation:

//very basic callback example using setTimeout
//function a is asynchronous function
//function b used as a callback
function a (callback){
    setTimeout (function(){
       console.log ('using callback:'); 
       let mockResponseData = '{"data": "something for callback"}'; 
       if (callback){
          callback (mockResponseData);
       }
    }, 2000);

} 

function b (dataJson) {
   let dataObject = JSON.parse (dataJson);
   console.log (dataObject.data);   
}

a (b);

//rewriting above code using Promise
//function c is asynchronous function
function c () {
   return new Promise(function (resolve, reject) {
     setTimeout (function(){
       console.log ('using promise:'); 
       let mockResponseData = '{"data": "something for promise"}'; 
       resolve(mockResponseData); 
    }, 2000);      
   }); 

}

c().then (b);

JsFiddle

Best practice multi language website

It depends on how much content your website has. At first I used a database like all other people here, but it can be time-consuming to script all the workings of a database. I don't say that this is an ideal method and especially if you have a lot of text, but if you want to do it fast without using a database, this method could work, though, you can't allow users to input data which will be used as translation-files. But if you add the translations yourself, it will work:

Let's say you have this text:

Welcome!

You can input this in a database with translations, but you can also do this:

$welcome = array(
"English"=>"Welcome!",
"German"=>"Willkommen!",
"French"=>"Bienvenue!",
"Turkish"=>"Hosgeldiniz!",
"Russian"=>"????? ??????????!",
"Dutch"=>"Welkom!",
"Swedish"=>"Välkommen!",
"Basque"=>"Ongietorri!",
"Spanish"=>"Bienvenito!"
"Welsh"=>"Croeso!");

Now, if your website uses a cookie, you have this for example:

$_COOKIE['language'];

To make it easy let's transform it in a code which can easily be used:

$language=$_COOKIE['language'];

If your cookie language is Welsh and you have this piece of code:

echo $welcome[$language];

The result of this will be:

Croeso!

If you need to add a lot of translations for your website and a database is too consuming, using an array can be an ideal solution.

Javascript Regex: How to put a variable inside a regular expression?

You can use the RegExp object:

var regexstring = "whatever";
var regexp = new RegExp(regexstring, "gi");
var str = "whateverTest";
var str2 = str.replace(regexp, "other");
document.write(str2);

Then you can construct regexstring in any way you want.

You can read more about it here.

How to handle button clicks using the XML onClick within Fragments

This is another way:

1.Create a BaseFragment like this:

public abstract class BaseFragment extends Fragment implements OnClickListener

2.Use

public class FragmentA extends BaseFragment 

instead of

public class FragmentA extends Fragment

3.In your activity:

public class MainActivity extends ActionBarActivity implements OnClickListener

and

BaseFragment fragment = new FragmentA;

public void onClick(View v){
    fragment.onClick(v);
}

Hope it helps.

C/C++ line number

Use __LINE__ (that's double-underscore LINE double-underscore), the preprocessor will replace it with the line number on which it is encountered.

android - How to get view from context?

For example you can find any textView:

TextView textView = (TextView) ((Activity) context).findViewById(R.id.textView1);

When to use CouchDB over MongoDB and vice versa

I summarize the answers found in that article:

http://www.quora.com/How-does-MongoDB-compare-to-CouchDB-What-are-the-advantages-and-disadvantages-of-each

MongoDB: Better querying, data storage in BSON (faster access), better data consistency, multiple collections

CouchDB: Better replication, with master to master replication and conflict resolution, data storage in JSON (human-readable, better access through REST services), querying through map-reduce.

So in conclusion, MongoDB is faster, CouchDB is safer.

Also: http://nosql.mypopescu.com/post/298557551/couchdb-vs-mongodb

Reading a single char in Java

Using nextline and System.in.read as often proposed requires the user to hit enter after typing a character. However, people searching for an answer to this question, may also be interested in directly respond to a key press in a console!

I found a solution to do so using jline3, wherein we first change the terminal into rawmode to directly respond to keys, and then wait for the next entered character:

var terminal = TerminalBuilder.terminal()
terminal.enterRawMode()
var reader = terminal.reader()

var c = reader.read()
<dependency>
    <groupId>org.jline</groupId>
    <artifactId>jline</artifactId>
    <version>3.12.3</version>
</dependency>

How to Identify port number of SQL server

You can also use this query

USE MASTER GO xp_readerrorlog 0, 1, N'Server is listening on' GO

Source : sqlauthority blog

ASP.NET MVC 3 - redirect to another action

You will need to return the result of RedirectToAction.

Read url to string in few lines of java code

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


Here is the traditional way to do this:

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

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

        StringBuilder response = new StringBuilder();
        String inputLine;

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

        in.close();

        return response.toString();
    }

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

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

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

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

How do I access store state in React Redux?

If you want to do some high-powered debugging, you can subscribe to every change of the state and pause the app to see what's going on in detail as follows.

store.js
store.subscribe( () => {
  console.log('state\n', store.getState());
  debugger;
});

Place that in the file where you do createStore.

To copy the state object from the console to the clipboard, follow these steps:

  1. Right-click an object in Chrome's console and select Store as Global Variable from the context menu. It will return something like temp1 as the variable name.

  2. Chrome also has a copy() method, so copy(temp1) in the console should copy that object to your clipboard.

https://stackoverflow.com/a/25140576

https://scottwhittaker.net/chrome-devtools/2016/02/29/chrome-devtools-copy-object.html

You can view the object in a json viewer like this one: http://jsonviewer.stack.hu/

You can compare two json objects here: http://www.jsondiff.com/

Iterate through DataSet

foreach (DataTable table in dataSet.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        foreach (object item in row.ItemArray)
        {
            // read item
        }
    }
}

Or, if you need the column info:

foreach (DataTable table in dataSet.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        foreach (DataColumn column in table.Columns)
        {
            object item = row[column];
            // read column and item
        }
    }
}

Fullscreen Activity in Android?

Using Android Studio (current version is 2.2.2 at moment) is very easy to add a fullscreen activity.

See the steps:

  1. Right click on your java main package > Select “New” > Select “Activity” > Then, click on “Fullscreen Activity”.

Step one

  1. Customize the activity (“Activity Name”, “Layout Name” and so on) and click “finish”.

Step two

Done!

Now you have a fullscreen activity made easily (see the java class and the activity layout to know how the things works)!

Building a fat jar using maven

Note: If you are a spring-boot application, read the end of answer

Add following plugin to your pom.xml The latest version can be found at

...
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>CHOOSE LATEST VERSION HERE</version>
            <configuration>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
            </configuration>
            <executions>
                <execution>
                    <id>assemble-all</id>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
...

After configuring this plug-in, running mvn package will produce two jars: one containing just the project classes, and a second fat jar with all dependencies with the suffix "-jar-with-dependencies".

if you want correct classpath setup at runtime then also add following plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <configuration>
        <archive>
            <manifest>
                <addClasspath>true</addClasspath>
                <mainClass>fully.qualified.MainClass</mainClass>
            </manifest>
        </archive>
    </configuration>
</plugin>

For spring boot application use just following plugin (choose appropriate version of it)

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <fork>true</fork>
        <mainClass>${start-class}</mainClass>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>repackage</goal>
            </goals>
        </execution>
    </executions>
</plugin>

How to write DataFrame to postgres table?

For Python 2.7 and Pandas 0.24.2 and using Psycopg2

Psycopg2 Connection Module

def dbConnect (db_parm, username_parm, host_parm, pw_parm):
    # Parse in connection information
    credentials = {'host': host_parm, 'database': db_parm, 'user': username_parm, 'password': pw_parm}
    conn = psycopg2.connect(**credentials)
    conn.autocommit = True  # auto-commit each entry to the database
    conn.cursor_factory = RealDictCursor
    cur = conn.cursor()
    print ("Connected Successfully to DB: " + str(db_parm) + "@" + str(host_parm))
    return conn, cur

Connect to the database

conn, cur = dbConnect(databaseName, dbUser, dbHost, dbPwd)

Assuming dataframe to be present already as df

output = io.BytesIO() # For Python3 use StringIO
df.to_csv(output, sep='\t', header=True, index=False)
output.seek(0) # Required for rewinding the String object
copy_query = "COPY mem_info FROM STDOUT csv DELIMITER '\t' NULL ''  ESCAPE '\\' HEADER "  # Replace your table name in place of mem_info
cur.copy_expert(copy_query, output)
conn.commit()

:first-child not working as expected

:first-child selects the first h1 if and only if it is the first child of its parent element. In your example, the ul is the first child of the div.

The name of the pseudo-class is somewhat misleading, but it's explained pretty clearly here in the spec.

jQuery's :first selector gives you what you're looking for. You can do this:

$('.detail_container h1:first').css("color", "blue");

How to printf a 64-bit integer as hex?

The warning from your compiler is telling you that your format specifier doesn't match the data type you're passing to it.

Try using %lx or %llx. For more portability, include inttypes.h and use the PRIx64 macro.

For example: printf("val = 0x%" PRIx64 "\n", val); (note that it's string concatenation)

Ruby's File.open gives "No such file or directory - text.txt (Errno::ENOENT)" error

Ditto Casper's answer:

puts Dir.pwd

As soon as you know current working directory, specify the file path relatively to that directory.

For example, if your working directory is project root, you can open a file under it directly like this

json_file = File.read(myfile.json)

horizontal scrollbar on top and bottom of table

To simulate a second horizontal scrollbar on top of an element, put a "dummy" div above the element that has horizontal scrolling, just high enough for a scrollbar. Then attach handlers of the "scroll" event for the dummy element and the real element, to get the other element in synch when either scrollbar is moved. The dummy element will look like a second horizontal scrollbar above the real element.

For a live example, see this fiddle

Here's the code:

HTML:

<div class="wrapper1">
  <div class="div1"></div>
</div>
<div class="wrapper2">
  <div class="div2">
    <!-- Content Here -->
  </div>
</div>

CSS:

.wrapper1, .wrapper2 {
  width: 300px;
  overflow-x: scroll;
  overflow-y:hidden;
}

.wrapper1 {height: 20px; }
.wrapper2 {height: 200px; }

.div1 {
  width:1000px;
  height: 20px;
}

.div2 {
  width:1000px;
  height: 200px;
  background-color: #88FF88;
  overflow: auto;
}

JS:

$(function(){
  $(".wrapper1").scroll(function(){
    $(".wrapper2").scrollLeft($(".wrapper1").scrollLeft());
  });
  $(".wrapper2").scroll(function(){
    $(".wrapper1").scrollLeft($(".wrapper2").scrollLeft());
  });
});

How can I position my jQuery dialog to center?

Try this for older versions and somebody who don't want to use position:

$("#dialog-div-id").dialog({position: ['center', 'top'],....

Byte array to image conversion

In one line:

Image.FromStream(new MemoryStream(byteArrayIn));

Unexpected 'else' in "else" error

I would suggest to read up a bit on the syntax. See here.

if (dsnt<0.05) {
  wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE) 
} else if (dst<0.05) {
    wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else 
  t.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)

How to delete columns in a CSV file?

Use of Pandas module will be much easier.

import pandas as pd
f=pd.read_csv("test.csv")
keep_col = ['day','month','lat','long']
new_f = f[keep_col]
new_f.to_csv("newFile.csv", index=False)

And here is short explanation:

>>>f=pd.read_csv("test.csv")
>>> f
   day  month  year  lat  long
0    1      4  2001   45   120
1    2      4  2003   44   118
>>> keep_col = ['day','month','lat','long'] 
>>> f[keep_col]
    day  month  lat  long
0    1      4   45   120
1    2      4   44   118
>>>

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

COMBOBOXID.DropDownStyle = ComboBoxStyle.DropDownList;

Onclick javascript to make browser go back to previous page?

Simple. One line.

<button onclick="javascript:window.history.back();">Go Back</button>

Like Wim's and Malik's answer, but just in one line.

How to convert Observable<any> to array[]

This should work:

GetCountries():Observable<CountryData[]>  {
  return this.http.get(`http://services.groupkt.com/country/get/all`)
    .map((res:Response) => <CountryData[]>res.json());
}

For this to work you will need to import the following:

import 'rxjs/add/operator/map'

Complexities of binary tree traversals

Depth first traversal of a binary tree is of order O(n).

Algo -- <b>
    PreOrderTrav():-----------------T(n)<b>
    if root is null---------------O(1)<b>
      return null-----------------O(1)<b>
    else:-------------------------O(1)<b>
      print(root)-----------------O(1)<b>
      PreOrderTrav(root.left)-----T(n/2)<b>
      PreOrderTrav(root.right)----T(n/2)<b>

If the time complexity of the algo is T(n) then it can be written as T(n) = 2*T(n/2) + O(1). If we apply back substitution we will get T(n) = O(n).

How to find the minimum value of a column in R?

Since it is a numeric operation, we should be converting it to numeric form first. This operation cannot take place if the data is in factor data type.
Check the data type of the columns using str().

min(as.numeric(data[,2]))

How to position a DIV in a specific coordinates?

You can also use position fixed css property.

<!-- html code --> 
<div class="box" id="myElement"></div>

/* css code */
.box {
    position: fixed;
}

// js code

document.getElementById('myElement').style.top = 0; //or whatever 
document.getElementById('myElement').style.left = 0; // or whatever

Problems using Maven and SSL behind proxy

I had the same problem with SSL and maven. My companies IT policy restricts me to make any changes to the computers configuration, so I copied the entire .m2 from my other computer and pasted it .m2 folder and it worked.

.m2 folder is usually found under c\user\admin

Extract regression coefficient values

A summary.lm object stores these values in a matrix called 'coefficients'. So the value you are after can be accessed with:

a2Pval <- summary(mg)$coefficients[2, 4]

Or, more generally/readably, coef(summary(mg))["a2","Pr(>|t|)"]. See here for why this method is preferred.

HTML - how to make an entire DIV a hyperlink?

alternative would be javascript and forwarding via the onclick event

<div onclick="window.location.href='somewhere...';">...</div>

Query a parameter (postgresql.conf setting) like "max_connections"

You can use SHOW:

SHOW max_connections;

This returns the currently effective setting. Be aware that it can differ from the setting in postgresql.conf as there are a multiple ways to set run-time parameters in PostgreSQL. To reset the "original" setting from postgresql.conf in your current session:

RESET max_connections;

However, not applicable to this particular setting. The manual:

This parameter can only be set at server start.

To see all settings:

SHOW ALL;

There is also pg_settings:

The view pg_settings provides access to run-time parameters of the server. It is essentially an alternative interface to the SHOW and SET commands. It also provides access to some facts about each parameter that are not directly available from SHOW, such as minimum and maximum values.

For your original request:

SELECT *
FROM   pg_settings
WHERE  name = 'max_connections';

Finally, there is current_setting(), which can be nested in DML statements:

SELECT current_setting('max_connections');

Related:

Convert base-2 binary number string to int

If you are using python3.6 or later you can use f-string to do the conversion:

Binary to decimal:

>>> print(f'{0b1011010:#0}')
90

>>> bin_2_decimal = int(f'{0b1011010:#0}')
>>> bin_2_decimal
90

binary to octal hexa and etc.

>>> f'{0b1011010:#o}'
'0o132'  # octal

>>> f'{0b1011010:#x}'
'0x5a'   # hexadecimal

>>> f'{0b1011010:#0}'
'90'     # decimal

Pay attention to 2 piece of information separated by colon.

In this way, you can convert between {binary, octal, hexadecimal, decimal} to {binary, octal, hexadecimal, decimal} by changing right side of colon[:]

:#b -> converts to binary
:#o -> converts to octal
:#x -> converts to hexadecimal 
:#0 -> converts to decimal as above example

Try changing left side of colon to have octal/hexadecimal/decimal.

Easy way to test a URL for 404 in PHP?

I found this answer here:

if(($twitter_XML_raw=file_get_contents($timeline))==false){
    // Retrieve HTTP status code
    list($version,$status_code,$msg) = explode(' ',$http_response_header[0], 3);

    // Check the HTTP Status code
    switch($status_code) {
        case 200:
                $error_status="200: Success";
                break;
        case 401:
                $error_status="401: Login failure.  Try logging out and back in.  Password are ONLY used when posting.";
                break;
        case 400:
                $error_status="400: Invalid request.  You may have exceeded your rate limit.";
                break;
        case 404:
                $error_status="404: Not found.  This shouldn't happen.  Please let me know what happened using the feedback link above.";
                break;
        case 500:
                $error_status="500: Twitter servers replied with an error. Hopefully they'll be OK soon!";
                break;
        case 502:
                $error_status="502: Twitter servers may be down or being upgraded. Hopefully they'll be OK soon!";
                break;
        case 503:
                $error_status="503: Twitter service unavailable. Hopefully they'll be OK soon!";
                break;
        default:
                $error_status="Undocumented error: " . $status_code;
                break;
    }

Essentially, you use the "file get contents" method to retrieve the URL, which automatically populates the http response header variable with the status code.

Set The Window Position of an application via command line

Have found that AutoHotKey is very good for window positioning tasks.

Here is an example script. Call it notepad.ahk and then run it from the command line or double click on it.

Run, notepad.exe
WinWait, ahk_class Notepad
WinActivate
WinMove A,, 10, 10, A_ScreenWidth-20, A_ScreenHeight-20

It will start an application (notepad) and then adjust the window size so that it is centered in the window with a 10 pixel border on all sides.

How do I use Linq to obtain a unique list of properties from a list of objects?

        int[] numbers = {1,2,3,4,5,3,6,4,7,8,9,1,0 };
        var nonRepeats = (from n in numbers select n).Distinct();


        foreach (var d in nonRepeats)
        {

            Response.Write(d);
        }

OUTPUT

1234567890

What do <o:p> elements do anyway?

Couldn't find any official documentation (no surprise there) but according to this interesting article, those elements are injected in order to enable Word to convert the HTML back to fully compatible Word document, with everything preserved.

The relevant paragraph:

Microsoft added the special tags to Word's HTML with an eye toward backward compatibility. Microsoft wanted you to be able to save files in HTML complete with all of the tracking, comments, formatting, and other special Word features found in traditional DOC files. If you save a file in HTML and then reload it in Word, theoretically you don't loose anything at all.

This makes lots of sense.

For your specific question.. the o in the <o:p> means "Office namespace" so anything following the o: in a tag means "I'm part of Office namespace" - in case of <o:p> it just means paragraph, the equivalent of the ordinary <p> tag.

I assume that every HTML tag has its Office "equivalent" and they have more.

Ball to Ball Collision - Detection and Handling

You have two easy ways to do this. Jay has covered the accurate way of checking from the center of the ball.

The easier way is to use a rectangle bounding box, set the size of your box to be 80% the size of the ball, and you'll simulate collision pretty well.

Add a method to your ball class:

public Rectangle getBoundingRect()
{
   int ballHeight = (int)Ball.Height * 0.80f;
   int ballWidth = (int)Ball.Width * 0.80f;
   int x = Ball.X - ballWidth / 2;
   int y = Ball.Y - ballHeight / 2;

   return new Rectangle(x,y,ballHeight,ballWidth);
}

Then, in your loop:

// Checks every ball against every other ball. 
// For best results, split it into quadrants like Ryan suggested. 
// I didn't do that for simplicity here.
for (int i = 0; i < balls.count; i++)
{
    Rectangle r1 = balls[i].getBoundingRect();

    for (int k = 0; k < balls.count; k++)
    {

        if (balls[i] != balls[k])
        {
            Rectangle r2 = balls[k].getBoundingRect();

            if (r1.Intersects(r2))
            {
                 // balls[i] collided with balls[k]
            }
        }
    }
}

Convert json data to a html table

Thanks all for your replies. I wrote one myself. Please note that this uses jQuery.

Code snippet:

_x000D_
_x000D_
var myList = [_x000D_
  { "name": "abc", "age": 50 },_x000D_
  { "age": "25", "hobby": "swimming" },_x000D_
  { "name": "xyz", "hobby": "programming" }_x000D_
];_x000D_
_x000D_
// Builds the HTML Table out of myList._x000D_
function buildHtmlTable(selector) {_x000D_
  var columns = addAllColumnHeaders(myList, selector);_x000D_
_x000D_
  for (var i = 0; i < myList.length; i++) {_x000D_
    var row$ = $('<tr/>');_x000D_
    for (var colIndex = 0; colIndex < columns.length; colIndex++) {_x000D_
      var cellValue = myList[i][columns[colIndex]];_x000D_
      if (cellValue == null) cellValue = "";_x000D_
      row$.append($('<td/>').html(cellValue));_x000D_
    }_x000D_
    $(selector).append(row$);_x000D_
  }_x000D_
}_x000D_
_x000D_
// Adds a header row to the table and returns the set of columns._x000D_
// Need to do union of keys from all records as some records may not contain_x000D_
// all records._x000D_
function addAllColumnHeaders(myList, selector) {_x000D_
  var columnSet = [];_x000D_
  var headerTr$ = $('<tr/>');_x000D_
_x000D_
  for (var i = 0; i < myList.length; i++) {_x000D_
    var rowHash = myList[i];_x000D_
    for (var key in rowHash) {_x000D_
      if ($.inArray(key, columnSet) == -1) {_x000D_
        columnSet.push(key);_x000D_
        headerTr$.append($('<th/>').html(key));_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
  $(selector).append(headerTr$);_x000D_
_x000D_
  return columnSet;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<body onLoad="buildHtmlTable('#excelDataTable')">_x000D_
  <table id="excelDataTable" border="1">_x000D_
  </table>_x000D_
</body>
_x000D_
_x000D_
_x000D_

MySQL vs MySQLi when using PHP

What is better is PDO; it's a less crufty interface and also provides the same features as MySQLi.

Using prepared statements is good because it eliminates SQL injection possibilities; using server-side prepared statements is bad because it increases the number of round-trips.

Describe table structure

sp_help tablename in sql server -- sp_help [ [ @objname = ] 'name' ]

desc tablename in oracle -- DESCRIBE { table-Name | view-Name }

C++ cast to derived class

First of all - prerequisite for downcast is that object you are casting is of the type you are casting to. Casting with dynamic_cast will check this condition in runtime (provided that casted object has some virtual functions) and throw bad_cast or return NULL pointer on failure. Compile-time casts will not check anything and will just lead tu undefined behaviour if this prerequisite does not hold.
Now analyzing your code:

DerivedType m_derivedType = m_baseType;

Here there is no casting. You are creating a new object of type DerivedType and try to initialize it with value of m_baseType variable.

Next line is not much better:

DerivedType m_derivedType = (DerivedType)m_baseType;

Here you are creating a temporary of DerivedType type initialized with m_baseType value.

The last line

DerivedType * m_derivedType = (DerivedType*) & m_baseType;

should compile provided that BaseType is a direct or indirect public base class of DerivedType. It has two flaws anyway:

  1. You use deprecated C-style cast. The proper way for such casts is
    static_cast<DerivedType *>(&m_baseType)
  2. The actual type of casted object is not of DerivedType (as it was defined as BaseType m_baseType; so any use of m_derivedType pointer will result in undefined behaviour.

How to only find files in a given directory, and ignore subdirectories using bash

I got here with a bit more general problem - I wanted to find files in directories matching pattern but not in their subdirectories.

My solution (assuming we're looking for all cpp files living directly in arch directories):

find . -path "*/arch/*/*" -prune -o -path "*/arch/*.cpp" -print

I couldn't use maxdepth since it limited search in the first place, and didn't know names of subdirectories that I wanted to exclude.

SQL not a single-group group function

Well the problem simply-put is that the SUM(TIME) for a specific SSN on your query is a single value, so it's objecting to MAX as it makes no sense (The maximum of a single value is meaningless).

Not sure what SQL database server you're using but I suspect you want a query more like this (Written with a MSSQL background - may need some translating to the sql server you're using):

SELECT TOP 1 SSN, SUM(TIME)
FROM downloads
GROUP BY SSN
ORDER BY 2 DESC

This will give you the SSN with the highest total time and the total time for it.

Edit - If you have multiple with an equal time and want them all you would use:

SELECT
SSN, SUM(TIME)
FROM downloads
GROUP BY SSN
HAVING SUM(TIME)=(SELECT MAX(SUM(TIME)) FROM downloads GROUP BY SSN))

Create a data.frame with m columns and 2 rows

For completeness:

Along the lines of Chase's answer, I usually use as.data.frame to coerce the matrix to a data.frame:

m <- as.data.frame(matrix(0, ncol = 30, nrow = 2))

EDIT: speed test data.frame vs. as.data.frame

system.time(replicate(10000, data.frame(matrix(0, ncol = 30, nrow = 2))))
   user  system elapsed 
  8.005   0.108   8.165 

system.time(replicate(10000, as.data.frame(matrix(0, ncol = 30, nrow = 2))))
   user  system elapsed 
  3.759   0.048   3.802 

Yes, it appears to be faster (by about 2 times).

Java null check why use == instead of .equals()

You code breaks Demeter's law. That's why it's better to refactor the design itself. As a workaround, you can use Optional

   obj = Optional.ofNullable(object1)
    .map(o -> o.getIdObject11())
    .map(o -> o.getIdObject111())
    .map(o -> o.getDescription())
    .orElse("")

above is to check to hierarchy of a object so simply use

Optional.ofNullable(object1) 

if you have only one object to check

Hope this helps !!!!

Counting Line Numbers in Eclipse

A very simple plugin for counting actual lines of source code is step counter eclipse plugin. Please download and try.

github link

Place the downloaded jar file under eclipse\plugin folder and restart eclipse.

Rightclick and select step counter enter image description here

Step Result enter image description here

Loading custom functions in PowerShell

I kept using this all this time

Import-module .\build_functions.ps1 -Force

How do I terminate a thread in C++11?

I guess the thread that needs to be killed is either in any kind of waiting mode, or doing some heavy job. I would suggest using a "naive" way.

Define some global boolean:

std::atomic_bool stop_thread_1 = false;

Put the following code (or similar) in several key points, in a way that it will cause all functions in the call stack to return until the thread naturally ends:

if (stop_thread_1)
    return;

Then to stop the thread from another (main) thread:

stop_thread_1 = true;
thread1.join ();
stop_thread_1 = false; //(for next time. this can be when starting the thread instead)

HTTP GET Request in Node.js Express

Request and Superagent are pretty good libraries to use.

note: request is deprecated, use at your risk!

Using request:

var request=require('request');

request.get('https://someplace',options,function(err,res,body){
  if(err) //TODO: handle err
  if(res.statusCode === 200 ) //etc
  //TODO Do something with response
});

Why should a Java class implement comparable?

Comparable is used to compare instances of your class. We can compare instances from many ways that is why we need to implement a method compareTo in order to know how (attributes) we want to compare instances.

Dog class:

package test;
import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        Dog d1 = new Dog("brutus");
        Dog d2 = new Dog("medor");
        Dog d3 = new Dog("ara");
        Dog[] dogs = new Dog[3];
        dogs[0] = d1;
        dogs[1] = d2;
        dogs[2] = d3;

        for (int i = 0; i < 3; i++) {
            System.out.println(dogs[i].getName());
        }
        /**
         * Output:
         * brutus
         * medor
         * ara
         */

        Arrays.sort(dogs, Dog.NameComparator);
        for (int i = 0; i < 3; i++) {
            System.out.println(dogs[i].getName());
        }
        /**
         * Output:
         * ara
         * medor
         * brutus
         */

    }
}

Main class:

package test;

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        Dog d1 = new Dog("brutus");
        Dog d2 = new Dog("medor");
        Dog d3 = new Dog("ara");
        Dog[] dogs = new Dog[3];
        dogs[0] = d1;
        dogs[1] = d2;
        dogs[2] = d3;

        for (int i = 0; i < 3; i++) {
            System.out.println(dogs[i].getName());
        }
        /**
         * Output:
         * brutus
         * medor
         * ara
         */

        Arrays.sort(dogs, Dog.NameComparator);
        for (int i = 0; i < 3; i++) {
            System.out.println(dogs[i].getName());
        }
        /**
         * Output:
         * ara
         * medor
         * brutus
         */

    }
}

Here is a good example how to use comparable in Java:

http://www.onjava.com/pub/a/onjava/2003/03/12/java_comp.html?page=2

Jdbctemplate query for string: EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0

IMHO returning a null is a bad solution because now you have the problem of sending and interpreting it at the (likely) front end client. I had the same error and I solved it by simply returning a List<FooObject>. I used JDBCTemplate.query().

At the front end (Angular web client), I simply examine the list and if it is empty (of zero length), treat it as no records found.

The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'

In my case this was actually a symptom of the server, hosted on AWS, lacking an IP for the external network. It would attempt to download namespaces from springframework.org and fail to make a connection.

Problem in running .net framework 4.0 website on iis 7.0

In our case the solution to this problem did not involve the "ISAPI and CGI Restrictions" settings. The error started occuring after operations staff had upgraded the server to .NET 4.5 by accident, then downgraded to .NET 4.0 again. This caused some of the IIS websites to forget their respective correct application pools, and it caused some of the application pools to switch from .NET Framework 4.0 to 2.0. Changing these settings back fixed the problem.

The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe

Being terminological, [[ operator extracts the element from a list whereas [ operator takes subset of a list.

How can I print message in Makefile?

It's not clear what you want, or whether you want this trick to work with different targets, or whether you've defined these targets elsewhere, or what version of Make you're using, but what the heck, I'll go out on a limb:

ifeq (yes, ${TEST})
CXXFLAGS := ${CXXFLAGS} -DDESKTOP_TEST
test:
$(info ************  TEST VERSION ************)
else
release:
$(info ************ RELEASE VERSIOIN **********)
endif

Java AES and using my own Key

    byte[] seed = (SALT2 + username + password).getBytes();
    SecureRandom random = new SecureRandom(seed);
    KeyGenerator generator;
    generator = KeyGenerator.getInstance("AES");
    generator.init(random);
    generator.init(256);
    Key keyObj = generator.generateKey();

How do you get a directory listing in C?

I've created an open source (BSD) C header that deals with this problem. It currently supports POSIX and Windows. Please check it out:

https://github.com/cxong/tinydir

tinydir_dir dir;
tinydir_open(&dir, "/path/to/dir");

while (dir.has_next)
{
    tinydir_file file;
    tinydir_readfile(&dir, &file);

    printf("%s", file.name);
    if (file.is_dir)
    {
        printf("/");
    }
    printf("\n");

    tinydir_next(&dir);
}

tinydir_close(&dir);

Postgres could not connect to server

Had a similar problem; a pid file was blocking postgres from starting up. To fix it:

$ rm /usr/local/var/postgres/postmaster.pid
$ brew services restart postgresql

and then all is well.

wget ssl alert handshake failure

Below command for download files from TLSv1.2 website.

curl -v --tlsv1.2 https://example.com/filename.zip

It`s worked!

php_network_getaddresses: getaddrinfo failed: Name or service not known

Had such a problem (with https://github.com/PHPMailer/PHPMailer), just reload PHP and everything start worked

for Centos 6 and 7:

service php-fpm restart 

How to export a Hive table into a CSV file?

The following script should work for you:

#!/bin/bash
hive -e "insert overwrite local directory '/LocalPath/'
row format delimited fields terminated by ','
select * from Mydatabase,Mytable limit 100"
cat /LocalPath/* > /LocalPath/table.csv

I used limit 100 to limit the size of data since I had a huge table, but you can delete it to export the entire table.

YouTube embedded video: set different thumbnail

Using the concept from waldyrious's answer, I've created the following solution that also addresses the issue of the video playing behind the image on tab restore or using the browser's back button to come back to the page with the video.

HTML

<div class="js-video-lead">
  <img class="hide" src="link/to/lead/image.jpg" />
  <iframe frameborder="0" height="240" src="https://www.youtube.com/embed/<code here>" width="426"></iframe>
</div>

The "hide" class is from Bootstrap and simply applies display: none; so that the image is not visible on page load if JavaScript is disabled.

JavaScript

function video_lead_play_state(element, active)
{
    var $active = $(element).closest(".js-video-lead").find(".btn-play-active");
    var $default = $(element).closest(".js-video-lead").find(".btn-play-default");

    if (active) {
        $active.show();
        $default.hide();
    } else {
        $active.hide();
        $default.show();
    }
}


$(document).ready(function () {
    // hide the videos and show the images
    var $videos = $(".js-video-lead iframe");
    $videos.hide();
    $(".js-video-lead > img").not(".btn-play").show();

    // position the video holders
    $(".js-video-lead").css("position", "relative");

    // prevent autoplay on load and add the play button
    $videos.each(function (index, video) {
        var $video = $(video);

        // prevent autoplay due to normal navigation
        var url = $video.attr("src");
        if (url.indexOf("&autoplay") > -1) {
            url = url.replace("&autoplay=1", "");
        } else {
            url = url.replace("?autoplay=1", "");
        }
        $video.attr("src", url).removeClass(
            "js-video-lead-autoplay"
        );

        // add and position the play button
        var top = parseInt(parseFloat($video.css("height")) / 2) - 15;
        var left = parseInt(parseFloat($video.css("width")) / 2) - 21;
        var $btn_default = $("<img />").attr("src", "play-default.png").css({
            "position": "absolute",
            "top": top + "px",
            "left": left + "px",
            "z-index": 100
        }).addClass("btn-play btn-play-default");
        var $btn_active = $("<img />").attr("src", "play-active.png").css({
            "display": "none",
            "position": "absolute",
            "top": top + "px",
            "left": left + "px",
            "z-index": 110
        }).addClass("btn-play btn-play-active");
        $(".js-video-lead").append($btn_default).append($btn_active);
    });


    $(".js-video-lead img").on("click", function (event) {
        var $holder = $(this).closest(".js-video-lead");
        var $video = $holder.find("iframe");
        var url = $video.attr("src");
        url += (url.indexOf("?") > -1) ? "&" : "?";
        url += "autoplay=1";
        $video.addClass("js-video-lead-autoplay").attr("src", url);
        $holder.find("img").remove();
        $video.show();
    });

    $(".js-video-lead > img").on("mouseenter", function (event) {
        video_lead_play_state(this, true);
    });

    $(".js-video-lead > img").not(".btn-play").on("mouseleave", function (event) {
        video_lead_play_state(this, false);
    });
});

jQuery is required for this solution and it should work with multiple embedded videos (with different lead images) on the same page.

The code utilizes two images play-default.png and play-active.png which are small (42 x 30) images of the YouTube play button. play-default.png is black with some transparency and is displayed initially. play-active.png is red and is displayed when the user moves the mouse over the image. This mimic's the expected behavior that a normal embedded YouTube video exhibits.

How to remove square brackets in string using regex?

Use this regular expression to match square brackets or single quotes:

/[\[\]']+/g

Replace with the empty string.

_x000D_
_x000D_
console.log("['abc','xyz']".replace(/[\[\]']+/g,''));
_x000D_
_x000D_
_x000D_

onClick function of an input type="button" not working

You have to change the ID of the button to be different from the function name JSFiddle

_x000D_
_x000D_
var counter = 0;_x000D_
_x000D_
_x000D_
function moreFields() {_x000D_
  counter++;_x000D_
  var newFields = document.getElementById('readroot').cloneNode(true);_x000D_
  newFields.id = '';_x000D_
  newFields.style.display = 'block';_x000D_
  var newField = newFields.childNodes;_x000D_
  for (var i = 0; i < newField.length; i++) {_x000D_
    var theName = newField[i].name_x000D_
    if (theName) newField[i].name = theName + counter;_x000D_
  }_x000D_
  var insertHere = document.getElementById('writeroot');_x000D_
  insertHere.parentNode.insertBefore(newFields, insertHere);_x000D_
}_x000D_
_x000D_
window.onload = moreFields();
_x000D_
<div id="readroot" style="display: none">_x000D_
  <input type="button" value="Remove review" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />_x000D_
  <br />_x000D_
  <br />_x000D_
  <input name="cd" value="title" />_x000D_
  <select name="rankingsel">_x000D_
    <option>Rating</option>_x000D_
    <option value="excellent">Excellent</option>_x000D_
    <option value="good">Good</option>_x000D_
    <option value="ok">OK</option>_x000D_
    <option value="poor">Poor</option>_x000D_
    <option value="bad">Bad</option>_x000D_
  </select>_x000D_
  <br />_x000D_
  <br />_x000D_
  <textarea rows="5" cols="20" name="review">Short review</textarea>_x000D_
  <br />Radio buttons included to test them in Explorer:_x000D_
  <br />_x000D_
  <input type="radio" name="something" value="test1" />Test 1_x000D_
  <br />_x000D_
  <input type="radio" name="something" value="test2" />Test 2</div>_x000D_
<form method="post" action="index1.php"> <span id="writeroot"></span>_x000D_
_x000D_
  <input type="button" onclick="moreFields();" id="moreFieldsButton" value="Give me more fields!" />_x000D_
  <input type="submit" value="Send form" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

Raising a number to a power in Java

we can use

Math.pow(2, 4);

this mean 2 to the power 4 (2^4)

answer = 16

How do I upgrade the Python installation in Windows 10?

Every minor version of Python, that is any 3.x and 2.x version, will install side-by-side with other versions on your computer. Only patch versions will upgrade existing installations.

So if you want to keep your installed Python 2.7 around, then just let it and install a new version using the installer. If you want to get rid of Python 2.7, you can uninstall it before or after installing a newer version—there is no difference to this.

Current Python 3 installations come with the py.exe launcher, which by default is installed into the system directory. This makes it available from the PATH, so you can automatically run it from any shell just by using py instead of python as the command. This avoids you having to put the current Python installation into PATH yourself. That way, you can easily have multiple Python installations side-by-side without them interfering with each other. When running, just use py script.py instead of python script.py to use the launcher. You can also specify a version using for example py -3 or py -3.6 to launch a specific version, otherwise the launcher will use the current default (which will usually be the latest 3.x).

Using the launcher, you can also run Python 2 scripts (which are often syntax incompatible to Python 3), if you decide to keep your Python 2.7 installation. Just use py -2 script.py to launch a script.


As for PyPI packages, every Python installation comes with its own folder where modules are installed into. So if you install a new version and you want to use modules you installed for a previous version, you will have to install them first for the new version. Current versions of the installer also offer you to install pip; it’s enabled by default, so you already have pip for every installation. Unless you explicitly add a Python installation to the PATH, you cannot just use pip though. Luckily, you can also simply use the py.exe launcher for this: py -m pip runs pip. So for example to install Beautiful Soup for Python 3.6, you could run py -3.6 -m pip install beautifulsoup4.

Modifying Objects within stream in Java8 while iterating

Yes, you can modify state of objects inside your stream, but most often you should avoid modifying state of source of stream. From non-interference section of stream package documentation we can read that:

For most data sources, preventing interference means ensuring that the data source is not modified at all during the execution of the stream pipeline. The notable exception to this are streams whose sources are concurrent collections, which are specifically designed to handle concurrent modification. Concurrent stream sources are those whose Spliterator reports the CONCURRENT characteristic.

So this is OK

  List<User> users = getUsers();
  users.stream().forEach(u -> u.setProperty(value));
//                       ^    ^^^^^^^^^^^^^

but this in most cases is not

  users.stream().forEach(u -> users.remove(u));
//^^^^^                       ^^^^^^^^^^^^

and may throw ConcurrentModificationException or even other unexpected exceptions like NPE:

List<Integer> list = IntStream.range(0, 10).boxed().collect(Collectors.toList());

list.stream()
    .filter(i -> i > 5)
    .forEach(i -> list.remove(i));  //throws NullPointerException

Change default timeout for mocha

Adding this for completeness. If you (like me) use a script in your package.json file, just add the --timeout option to mocha:

"scripts": {
  "test": "mocha 'test/**/*.js' --timeout 10000",
  "test-debug": "mocha --debug 'test/**/*.js' --timeout 10000"
},

Then you can run npm run test to run your test suite with the timeout set to 10,000 milliseconds.

Get value of input field inside an iframe

document.getElementById("idframe").contentWindow.document.getElementById("idelement").value;

Storing SHA1 hash values in MySQL

A SHA1 hash is 40 chars long!

Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code

After trying all the solutions, I was missing is to enable this option in:

Targets -> Build Phases -> Embedded pods frameworks

In newer versions it may be listed as:

Targets -> Build Phases -> Bundle React Native code and images

  • Run script only when installing

Build Phases

One line if-condition-assignment

You can definitely use num1 = (20 if someBoolValue else num1) if you want.

htmlentities() vs. htmlspecialchars()

This is being encoded with htmlentities.

implode( "\t", array_values( get_html_translation_table( HTML_ENTITIES ) ) ):

" & < >
¡ ¢ £ ¤ ¥ ¦ § ¨ © ª « ¬ ­ ® ¯ ° ± ² ³ ´ µ ¶ · ¸ ¹ º » ¼ ½ ¾ ¿ À Á Â Ã Ä Å Æ Ç È É Ê Ë Ì Í Î Ï Ð Ñ Ò Ó Ô Õ Ö × Ø Ù Ú Û Ü Ý Þ ß à á â ã ä å æ ç è é ê ë ì í î ï ð ñ ò ó ô õ ö ÷ ø ù ú û ü ý þ ÿ Œ œ Š š Ÿ ƒ ˆ ˜ ? ? G ? ? ? ? T ? ? ? ? ? ? ? ? ? S ? ? F ? ? O a ß ? d e ? ? ? ? ? ? µ ? ? ? p ? ? s t ? f ? ? ? ? ? ? ? ? ? ? – — ‘ ’ ‚ “ ” „ † ‡ • … ‰ ' " ‹ › ? / € I P R ™ ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Ø ? ? ? ? ? ? - * v ? 8 ? ? ? n ? ? ? ~ ? ˜ ? = = = ? ? ? ? ? ? ? ? · ? ? ? ? ? ? ? ? ? ? ?

This is being encoded with htmlspecialchars.

implode( "\t", array_values( get_html_translation_table( HTML_SPECIALCHARS ) ) ):

" & < >

Is it possible to hide the cursor in a webpage using CSS or Javascript?

I did it with transparent *.cur 1px to 1px, but it looks like small dot. :( I think it's the best cross-browser thing that I can do. CSS2.1 has no value 'none' for 'cursor' property - it was added in CSS3. Thats why it's workable not everywhere.

Trying to make bootstrap modal wider

If you need this solution for only few types of modals just use style="width:90%" attribute.

example:

div class="modal-dialog modal-lg" style="width:90%"

note: this will change only this particular modal

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

what about this simple inArray function:

Function isInArray(ByRef stringToBeFound As String, ByRef arr As Variant) As Boolean
For Each element In arr
    If element = stringToBeFound Then
        isInArray = True
        Exit Function
    End If
Next element
End Function

Passing additional variables from command line to make

export ROOT_DIR=<path/value>

Then use the variable, $(ROOT_DIR) in the Makefile.

Does Eclipse have line-wrap

In Eclipse v4.7 (Oxygen):

Window menu ? Editor ? Toggle Word Wrap (Shift+Alt+Y)

Can I run javascript before the whole page is loaded?

Not only can you, but you have to make a special effort not to if you don't want to. :-)

When the browser encounters a classic script tag when parsing the HTML, it stops parsing and hands over to the JavaScript interpreter, which runs the script. The parser doesn't continue until the script execution is complete (because the script might do document.write calls to output markup that the parser should handle).

That's the default behavior, but you have a few options for delaying script execution:

  1. Use JavaScript modules. A type="module" script is deferred until the HTML has been fully parsed and the initial DOM created. This isn't the primary reason to use modules, but it's one of the reasons:

    <script type="module" src="./my-code.js"></script>
    <!-- Or -->
    <script type="module">
    // Your code here
    </script>
    

    The code will be fetched (if it's separate) and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. (If your module code is inline rather than in its own file, it is also deferred until HTML parsing is complete.)

    This wasn't available when I first wrote this answer in 2010, but here in 2020, all major modern browsers support modules natively, and if you need to support older browsers, you can use bundlers like Webpack and Rollup.js.

  2. Use the defer attribute on a classic script tag:

    <script defer src="./my-code.js"></script>
    

    As with the module, the code in my-code.js will be fetched and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. But, defer doesn't work with inline script content, only with external files referenced via src.

  3. I don't think it's what you want, but you can use the async attribute to tell the browser to fetch the JavaScript code in parallel with the HTML parsing, but then run it as soon as possible, even if the HTML parsing isn't complete. You can put it on a type="module" tag, or use it instead of defer on a classic script tag.

  4. Put the script tag at the end of the document, just prior to the closing </body> tag:

    <!doctype html>
    <html>
    <!-- ... -->
    <body>
    <!-- The document's HTML goes here -->
    <script type="module" src="./my-code.js"></script><!-- Or inline script -->
    </body>
    </html>
    

    That way, even though the code is run as soon as its encountered, all of the elements defined by the HTML above it exist and are ready to be used.

    It used to be that this caused an additional delay on some browsers because they wouldn't start fetching the code until the script tag was encountered, but modern browsers scan ahead and start prefetching. Still, this is very much the third choice at this point, both modules and defer are better options.

The spec has a useful diagram showing a raw script tag, defer, async, type="module", and type="module" async and the timing of when the JavaScript code is fetched and run:

enter image description here

Here's an example of the default behavior, a raw script tag:

_x000D_
_x000D_
.found {_x000D_
    color: green;_x000D_
}
_x000D_
<p>Paragraph 1</p>_x000D_
<script>_x000D_
    if (typeof NodeList !== "undefined" && !NodeList.prototype.forEach) {_x000D_
        NodeList.prototype.forEach = Array.prototype.forEach;_x000D_
    }_x000D_
    document.querySelectorAll("p").forEach(p => {_x000D_
        p.classList.add("found");_x000D_
    });_x000D_
</script>_x000D_
<p>Paragraph 2</p>
_x000D_
_x000D_
_x000D_

(See my answer here for details around that NodeList code.)

When you run that, you see "Paragraph 1" in green but "Paragraph 2" is black, because the script ran synchronously with the HTML parsing, and so it only found the first paragraph, not the second.

In contrast, here's a type="module" script:

_x000D_
_x000D_
.found {_x000D_
    color: green;_x000D_
}
_x000D_
<p>Paragraph 1</p>_x000D_
<script type="module">_x000D_
    document.querySelectorAll("p").forEach(p => {_x000D_
        p.classList.add("found");_x000D_
    });_x000D_
</script>_x000D_
<p>Paragraph 2</p>
_x000D_
_x000D_
_x000D_

Notice how they're both green now; the code didn't run until HTML parsing was complete. That would also be true with a defer script with external content (but not inline content).

(There was no need for the NodeList check there because any modern browser supporting modules already has forEach on NodeList.)

In this modern world, there's no real value to the DOMContentLoaded event of the "ready" feature that PrototypeJS, jQuery, ExtJS, Dojo, and most others provided back in the day (and still provide); just use modules or defer. Even back in the day, there wasn't much reason for using them (and they were often used incorrectly, holding up page presentation while the entire jQuery library was loaded because the script was in the head instead of after the document), something some developers at Google flagged up early on. This was also part of the reason for the YUI recommendation to put scripts at the end of the body, again back in the day.

How to programmatically close a JFrame

If you want the GUI to behave as if you clicked the X close button then you need to dispatch a window closing event to the Window. The ExitAction from Closing An Application allows you to add this functionality to a menu item or any component that uses Actions easily.

frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));

Importing a csv into mysql via command line

You can simply import by

mysqlimport --ignore-lines=1 --lines-terminated-by='\n' --fields-terminated-by=',' --fields-enclosed-by='"' --verbose --local -uroot -proot db_name csv_import.csv

Note: Csv File name and Table name should be same

Can functions be passed as parameters?

I hope the below example will provide more clarity.

package main

type EmployeeManager struct{
    category            string
    city                string
    calculateSalary     func() int64
}


func NewEmployeeManager() (*EmployeeManager,error){

    return &EmployeeManager{
        category : "MANAGEMENT",
        city : "NY",
        calculateSalary: func() int64 {
            var calculatedSalary int64
            // some formula
            return calculatedSalary
        },
    },nil
}

func (self *EmployeeManager) emWithSalaryCalculation(){
    self.calculateSalary = func() int64 {
        var calculatedSalary int64
        // some new formula
        return calculatedSalary
    }
}

func updateEmployeeInfo(em EmployeeManager){
    // Some code
}

func processEmployee(){
    updateEmployeeInfo(struct {
        category        string
        city            string
        calculateSalary func() int64
    }{category: "", city: "", calculateSalary: func() int64 {
        var calculatedSalary int64
        // some new formula
        return calculatedSalary
    }})
}

mysqli_connect(): (HY000/2002): No connection could be made because the target machine actively refused it

If you look at your XAMPP Control Panel, it's clearly stated that the port to the MySQL server is 3306 - you provided 3360. The 3306 is default, and thus doesn't need to be specified. Even so, the 5th parameter of mysqli_connect() is the port, which is where it should be specified.

You could just remove the port specification altogether, as you're using the default port, making it

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db     = 'test_db13';

References

Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

This type of issue generally occurs while migrating one server to another, one folder to another. Laravel keeps the cache and configuration (file name ) when the folder is different then this problem occurs.

Solution Run Following command:

php artisan config:cache

https://laravel.com/docs/5.6/configuration#configuration-caching

Clear History and Reload Page on Login/Logout Using Ionic Framework

I tried many methods, but found this method is absolutely correct:

$window.location.reload();

Hope this help others stuck for days like me with version: angular 1.5.5, ionic 1.2.4, angular-ui-router 1.0.0

Double vs. BigDecimal?

A BigDecimal is an exact way of representing numbers. A Double has a certain precision. Working with doubles of various magnitudes (say d1=1000.0 and d2=0.001) could result in the 0.001 being dropped alltogether when summing as the difference in magnitude is so large. With BigDecimal this would not happen.

The disadvantage of BigDecimal is that it's slower, and it's a bit more difficult to program algorithms that way (due to + - * and / not being overloaded).

If you are dealing with money, or precision is a must, use BigDecimal. Otherwise Doubles tend to be good enough.

I do recommend reading the javadoc of BigDecimal as they do explain things better than I do here :)

Credit card expiration dates - Inclusive or exclusive?

I had a Automated Billing setup online and the credit card said it say good Thru 10/09, but the card was rejected the first week in October and again the next week. Each time it was rejected it cost me a $10 fee. Don't assume it good thru the end of the month if you have automatic billing setup.

How can I delete derived data in Xcode 8?

In Xcode 8, all the derived data is automatically cleaned. If you want to do it by hand, go to Locations tab from the Preferences, locate project's derived data folder, and delete files related to the project.

In macOS 10.12 and later, Xcode cleans up stale derived data, precompiled headers, and module caches. (23282174)

Xcode 8.0 Release Notes

Credits to @charmingToad

But from what I observed, the same behaviour is typical when using Xcode 8 on OS X 10.11.5/6

Difference between applicationContext.xml and spring-servlet.xml in Spring Framework

In Servlet technology if you want to pass any input to a particular servlet then you need to pass in init param like below code.

 <servlet>
    <servlet-name>DBController</servlet-name>
    <servlet-class>com.test.controller.DBController</servlet-class>
    <init-param>
        <param-name>username</param-name>
        <param-value>John</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>DBController</servlet-name>
    <url-pattern>/DBController</url-pattern>
</servlet-mapping>

If you want to pass some in put that is common for all servlets then that time you need to configure context param. Example

 <context-param>
    <param-name>email</param-name>
    <param-value>[email protected]</param-value>
</context-param>

SO exactly like this when ever we are working with Spring MVC we need to provide some information to Predefined servlet provided by Spring that is DispatcherServlet through init param. So the configuration is as fallows, here we are providing the spring-servlet.xml as init parameter to DispatcherServlet.

 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
              http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>Spring MVC App</display-name>

    <servlet>
        <servlet-name>SpringController</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>SpringController</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
</web-app>

Again we need some context param. That is applicable for whole application. So we can provide the root context that is applicationcontext.xml The configuration is like this:

    <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationcontext.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
        <servlet-name>SpringController</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>SpringController</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>

How to download PDF automatically using js?

Use the download attribute.

var link = document.createElement('a');
link.href = url;
link.download = 'file.pdf';
link.dispatchEvent(new MouseEvent('click'));

How to get the selected index of a RadioGroup in Android

just use this:

    int index = 2;
    boolean option3Checked = radioGroup.getCheckedRadioButtonId() == radioGroup.getChildAt(2).getId();

ReferenceError: $ is not defined

i was facing the same problem in the wp-admin section of the site. I enqueued the underscore script cdn and it fixed the problem.

function kk_admin_scripts() {
    wp_enqueue_script('underscore', '//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js' );
}
add_action( 'admin_enqueue_scripts', 'kk_admin_scripts' );

Android soft keyboard covers EditText field

I had the same issue and searching the people said to add adjustPan, while in my case adjustResize worked.

<activity
    android:name=".YOUR.ACTIVITY"
    ...
    android:windowSoftInputMode="adjustResize"
/>

How to get a list of programs running with nohup

You cannot exactly get a list of commands started with nohup but you can see them along with your other processes by using the command ps x. Commands started with nohup will have a question mark in the TTY column.

Cannot import scipy.misc.imread

If you have Pillow installed with scipy and it is still giving you error then check your scipy version because it has been removed from scipy since 1.3.0rc1.

rather install scipy 1.1.0 by :

pip install scipy==1.1.0

check https://github.com/scipy/scipy/issues/6212


The method imread in scipy.misc requires the forked package of PIL named Pillow. If you are having problem installing the right version of PIL try using imread in other packages:

from matplotlib.pyplot import imread
im = imread(image.png)

To read jpg images without PIL use:

import cv2 as cv
im = cv.imread(image.jpg)

You can try from scipy.misc.pilutil import imread instead of from scipy.misc import imread

Please check the GitHub page : https://github.com/amueller/mglearn/issues/2 for more details.

How do I catch a numpy warning like it's an exception (not just for testing)?

Remove warnings.filterwarnings and add:

numpy.seterr(all='raise')

How to create a file in Android?

From here: http://www.anddev.org/working_with_files-t115.html

//Writing a file...  



try { 
       // catches IOException below
       final String TESTSTRING = new String("Hello Android");

       /* We have to use the openFileOutput()-method
       * the ActivityContext provides, to
       * protect your file from others and
       * This is done for security-reasons.
       * We chose MODE_WORLD_READABLE, because
       *  we have nothing to hide in our file */             
       FileOutputStream fOut = openFileOutput("samplefile.txt",
                                                            MODE_PRIVATE);
       OutputStreamWriter osw = new OutputStreamWriter(fOut); 

       // Write the string to the file
       osw.write(TESTSTRING);

       /* ensure that everything is
        * really written out and close */
       osw.flush();
       osw.close();

//Reading the file back...

       /* We have to use the openFileInput()-method
        * the ActivityContext provides.
        * Again for security reasons with
        * openFileInput(...) */

        FileInputStream fIn = openFileInput("samplefile.txt");
        InputStreamReader isr = new InputStreamReader(fIn);

        /* Prepare a char-Array that will
         * hold the chars we read back in. */
        char[] inputBuffer = new char[TESTSTRING.length()];

        // Fill the Buffer with data from the file
        isr.read(inputBuffer);

        // Transform the chars to a String
        String readString = new String(inputBuffer);

        // Check if we read back the same chars that we had written out
        boolean isTheSame = TESTSTRING.equals(readString);

        Log.i("File Reading stuff", "success = " + isTheSame);

    } catch (IOException ioe) 
      {ioe.printStackTrace();}

Could not open ServletContext resource

Are you having Tomcat unpack the WAR file? It seems that the files cannot be found on the classpath when a WAR file is loaded and it is not being unpacked.

How to get current page URL in MVC 3

The case (single page style) for browser history

HttpContext.Request.UrlReferrer

Java client certificates over HTTPS/SSL

While not recommended, you can also disable SSL cert validation alltogether:

import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

public class SSLTool {

  public static void disableCertificateValidation() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { 
      new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() { 
          return new X509Certificate[0]; 
        }
        public void checkClientTrusted(X509Certificate[] certs, String authType) {}
        public void checkServerTrusted(X509Certificate[] certs, String authType) {}
    }};

    // Ignore differences between given hostname and certificate hostname
    HostnameVerifier hv = new HostnameVerifier() {
      public boolean verify(String hostname, SSLSession session) { return true; }
    };

    // Install the all-trusting trust manager
    try {
      SSLContext sc = SSLContext.getInstance("SSL");
      sc.init(null, trustAllCerts, new SecureRandom());
      HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
      HttpsURLConnection.setDefaultHostnameVerifier(hv);
    } catch (Exception e) {}
  }
}

How to format background color using twitter bootstrap?

Bootstrap default "contextual backgrounds" helper classes to change the background color:

.bg-primary
.bg-default
.bg-info
.bg-warning
.bg-danger

If you need set custom background color then, you can write your own custom classes in style.css( a custom css file) example below

.bg-pink
{
  background-color: #CE6F9E;
}

Accessing a value in a tuple that is in a list

OR you can use pandas:

>>> import pandas as pd
>>> L = [(1,2),(2,3),(4,5),(3,4),(6,7),(6,7),(3,8)]
>>> df=pd.DataFrame(L)
>>> df[1]
0    2
1    3
2    5
3    4
4    7
5    7
6    8
Name: 1, dtype: int64
>>> df[1].tolist()
[2, 3, 5, 4, 7, 7, 8]
>>> 

Or numpy:

>>> import numpy as np
>>> L = [(1,2),(2,3),(4,5),(3,4),(6,7),(6,7),(3,8)]
>>> arr=np.array(L)
>>> arr.T[1]
array([2, 3, 5, 4, 7, 7, 8])
>>> arr.T[1].tolist()
[2, 3, 5, 4, 7, 7, 8]
>>> 

Get table column names in MySQL?

The following SQL statements are nearly equivalent:

SELECT COLUMN_NAME
  FROM INFORMATION_SCHEMA.COLUMNS
 WHERE table_name = 'tbl_name'
  [AND table_schema = 'db_name']
  [AND column_name LIKE 'wild']

SHOW COLUMNS
FROM tbl_name
[FROM db_name]
[LIKE 'wild']

Reference: INFORMATION_SCHEMA COLUMNS

I can't access http://localhost/phpmyadmin/

sudo apt-get -y --reinstall install phpmyadmin;
sudo service apache2 restart;

Hope this helps.

Reading a huge .csv file

I do a fair amount of vibration analysis and look at large data sets (tens and hundreds of millions of points). My testing showed the pandas.read_csv() function to be 20 times faster than numpy.genfromtxt(). And the genfromtxt() function is 3 times faster than the numpy.loadtxt(). It seems that you need pandas for large data sets.

I posted the code and data sets I used in this testing on a blog discussing MATLAB vs Python for vibration analysis.

Get full query string in C# ASP.NET

This should work fine for you.

Write this code in the Page_Load event of the page.

string ID = Request.QueryString["id"].ToString();
Response.Redirect("http://www.example.com/rendernews.php?id=" + ID);

Angular cookies

I ended creating my own functions:

@Component({
    selector: 'cookie-consent',
    template: cookieconsent_html,
    styles: [cookieconsent_css]
})
export class CookieConsent {
    private isConsented: boolean = false;

    constructor() {
        this.isConsented = this.getCookie(COOKIE_CONSENT) === '1';
    }

    private getCookie(name: string) {
        let ca: Array<string> = document.cookie.split(';');
        let caLen: number = ca.length;
        let cookieName = `${name}=`;
        let c: string;

        for (let i: number = 0; i < caLen; i += 1) {
            c = ca[i].replace(/^\s+/g, '');
            if (c.indexOf(cookieName) == 0) {
                return c.substring(cookieName.length, c.length);
            }
        }
        return '';
    }

    private deleteCookie(name) {
        this.setCookie(name, '', -1);
    }

    private setCookie(name: string, value: string, expireDays: number, path: string = '') {
        let d:Date = new Date();
        d.setTime(d.getTime() + expireDays * 24 * 60 * 60 * 1000);
        let expires:string = `expires=${d.toUTCString()}`;
        let cpath:string = path ? `; path=${path}` : '';
        document.cookie = `${name}=${value}; ${expires}${cpath}`;
    }

    private consent(isConsent: boolean, e: any) {
        if (!isConsent) {
            return this.isConsented;
        } else if (isConsent) {
            this.setCookie(COOKIE_CONSENT, '1', COOKIE_CONSENT_EXPIRE_DAYS);
            this.isConsented = true;
            e.preventDefault();
        }
    }
}

Is it acceptable and safe to run pip install under sudo?

It looks like your permissions are messed up. Type chown -R markwalker ~ in the Terminal and try pip again? Let me know if you're sorted.

Concatenating strings doesn't work as expected

Your code, as written, works. You’re probably trying to achieve something unrelated, but similar:

std::string c = "hello" + "world";

This doesn’t work because for C++ this seems like you’re trying to add two char pointers. Instead, you need to convert at least one of the char* literals to a std::string. Either you can do what you’ve already posted in the question (as I said, this code will work) or you do the following:

std::string c = std::string("hello") + "world";

Best way to use PHP to encrypt and decrypt passwords?

Check out mycrypt(): http://us.php.net/manual/en/book.mcrypt.php

And if you're using postgres there's pgcrypto for database level encryption. (makes it easier to search and sort)

How to run a method every X seconds

If you are familiar with RxJava, you can use Observable.interval(), which is pretty neat.

Observable.interval(60, TimeUnits.SECONDS)
          .flatMap(new Function<Long, ObservableSource<String>>() {
                @Override
                public ObservableSource<String> apply(@NonNull Long aLong) throws Exception {
                    return getDataObservable(); //Where you pull your data
                }
            });

The downside of this is that you have to architect polling your data in a different way. However, there are a lot of benefits to the Reactive Programming way:

  1. Instead of controlling your data via a callback, you create a stream of data that you subscribe to. This separates the concern of "polling data" logic and "populating UI with your data" logic so that you do not mix your "data source" code and your UI code.
  2. With RxAndroid, you can handle threads in just 2 lines of code.

    Observable.interval(60, TimeUnits.SECONDS)
          .flatMap(...) // polling data code
          .subscribeOn(Schedulers.newThread()) // poll data on a background thread
          .observeOn(AndroidSchedulers.mainThread()) // populate UI on main thread
          .subscribe(...); // your UI code
    

Please check out RxJava. It has a high learning curve but it will make handling asynchronous calls in Android so much easier and cleaner.

In Python, how do I create a string of n characters in one line of code?

if you just want any letters:

 'a'*10  # gives 'aaaaaaaaaa'

if you want consecutive letters (up to 26):

 ''.join(['%c' % x for x in range(97, 97+10)])  # gives 'abcdefghij'

What is the use of static constructors?

From Static Constructors (C# Programming Guide):

A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.

Static constructors have the following properties:

  • A static constructor does not take access modifiers or have parameters.

  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

  • A static constructor cannot be called directly.

  • The user has no control on when the static constructor is executed in the program.

  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.

  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

How to uninstall Ruby from /usr/local?

It's not a good idea to uninstall 1.8.6 if it's in /usr/bin. That is owned by the OS and is expected to be there.

If you put /usr/local/bin in your PATH before /usr/bin then things you have installed in /usr/local/bin will be found before any with the same name in /usr/bin, effectively overwriting or updating them, without actually doing so. You can still reach them by explicitly using /usr/bin in your #! interpreter invocation line at the top of your code.

@Anurag recommended using RVM, which I'll second. I use it to manage 1.8.7 and 1.9.1 in addition to the OS's 1.8.6.

How can I override inline styles with external CSS?

The only way to override inline style is by using !important keyword beside the CSS rule. The following is an example of it.

_x000D_
_x000D_
div {
        color: blue !important;
       /* Adding !important will give this rule more precedence over inline style */
    }
_x000D_
<div style="font-size: 18px; color: red;">
    Hello, World. How can I change this to blue?
</div>
_x000D_
_x000D_
_x000D_

Important Notes:

  • Using !important is not considered as a good practice. Hence, you should avoid both !important and inline style.

  • Adding the !important keyword to any CSS rule lets the rule forcefully precede over all the other CSS rules for that element.

  • It even overrides the inline styles from the markup.

  • The only way to override is by using another !important rule, declared either with higher CSS specificity in the CSS, or equal CSS specificity later in the code.

  • Must Read - CSS Specificity by MDN

How to set ObjectId as a data type in mongoose

The solution provided by @dex worked for me. But I want to add something else that also worked for me: Use

let UserSchema = new Schema({
   username: {
     type: String
   },
   events: [{
     type: ObjectId,
     ref: 'Event' // Reference to some EventSchema
   }]
})

if what you want to create is an Array reference. But if what you want is an Object reference, which is what I think you might be looking for anyway, remove the brackets from the value prop, like this:

let UserSchema = new Schema({
   username: {
     type: String
   },
   events: {
     type: ObjectId,
     ref: 'Event' // Reference to some EventSchema
   }
})

Look at the 2 snippets well. In the second case, the value prop of key events does not have brackets over the object def.

Get Absolute URL from Relative path (refactored method)

If you're in the context of an MVC Controller or View you can use the UrlHelper which should be accessible via just Url

Url.Content("~/content/images/myimage.jpg")

Which will be fully expanded to /virtual_directoryname/content/images/myimage.jpg

This can be used in a controller or .cshtml file

Yes it is a little odd that it's called Content but it's meant to be used to get an absolute path to a resource so it makes sense

RegEx match open tags except XHTML self-contained tags

Here's a PCRE regular expression for XML/XHTML, built from a simplified EBNF syntax definition:

/
(?(DEFINE)
(?<tag> (?&tagempty) | (?&tagopen) ((?&textnode) | (?&tag) | (?&comment))* (?&tagclose))
(?<tagunnested> (?&tagempty) | (?&tagopen) ((?&textnode) | (?&comment))* (?&tagclose))
(?<textnode> [^<>]+)
(?<comment> <!--([\s\S]*?)-->)
(?<tagopen> < (?&tagname) (?&attrlist)? (?&ws)* >)
(?<tagempty> < (?&tagname) (?&ws)* (?&attrlist)? (?&ws)* \/>)
(?<tagclose> <\/ (?&tagname) (?&ws)* >)
(?<attrlist> ((?&ws)+ (?&attr))+)
(?<attr> (?&attrunquoted) | (?&attrsinglequoted) | (?&attrdoublequoted) | (?&attrempty))
(?<attrempty> (?&attrname))
(?<attrunquoted> (?&attrname) (?&ws)* = (?&ws)* (?&attrunquotedvalue))
(?<attrsinglequoted> (?&attrname) (?&ws)* = (?&ws)* ' (?&attrsinglequotedvalue) ')
(?<attrdoublequoted> (?&attrname) (?&ws)* = (?&ws)* " (?&attrdoublequotedvalue) ")
(?<tagname> (?&alphabets) ((?&alphabets) | (?&digits))*)
(?<attrname>(?&alphabets)+((?&alphabets)|(?&digits)|[:-]) )
(?<attrunquotedvalue> [^\s"'=<>`]+)
(?<attrsinglequotedvalue> [^']+)
(?<attrdoublequotedvalue> [^"]+)
(?<alphabets> [a-zA-Z])
(?<digits> [0-9])
(?<ws> \s)
)
(?&tagopen)
/x

This illustrates how to build regular expressions for context-free grammars. You can match other parts of the definition by changing the match on the last line from (?&tagopen) to e.g. (?&tagunnested)

The real question is: Should you do it?

For XML/XHTML the consensus is no!

Credits to nikic for supplying the idea.

Wheel file installation

You normally use a tool like pip to install wheels. Leave it to the tool to discover and download the file if this is for a project hosted on PyPI.

For this to work, you do need to install the wheel package:

pip install wheel

You can then tell pip to install the project (and it'll download the wheel if available), or the wheel file directly:

pip install project_name  # discover, download and install
pip install wheel_file.whl  # directly install the wheel

The wheel module, once installed, also is runnable from the command line, you can use this to install already-downloaded wheels:

python -m wheel install wheel_file.whl

Also see the wheel project documentation.

How to do relative imports in Python?

Let me just put this here for my own reference. I know that it is not good Python code, but I needed a script for a project I was working on and I wanted to put the script in a scripts directory.

import os.path
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

Using "margin: 0 auto;" in Internet Explorer 8

One more time: we all hate IE!

<div style="width:100%;background-color:blue;">
    <div style="margin:0 auto;width:300px;background-color:red;">
        Not Working
    </div>
</div>

<div style="width:100%;background-color:green;text-align:center;">
    <div style="margin:0 auto;width:300px;background-color:orange;text-align:left;">
        Working, but dumb that you have to use text-align
    </div>
</div>

Server certificate verification failed: issuer is not trusted

string cmdArguments = $@"/k svn log --trust-server-cert --non-interactive ""{servidor}"" --username alex --password alex -r {numeroRevisao}";
ProcessStartInfo cmd = new ProcessStartInfo("cmd.exe", cmdArguments);

cmd.CreateNoWindow = true;
cmd.RedirectStandardOutput = true;
cmd.RedirectStandardError = true;
cmd.WindowStyle = ProcessWindowStyle.Hidden;
cmd.UseShellExecute = false;

Process reg = Process.Start(cmd);
string output = "";

using (System.IO.StreamReader myOutput = reg.StandardOutput)
{
    output += myOutput.ReadToEnd();
}
using (System.IO.StreamReader myError = reg.StandardError)
{
    output += myError.ReadToEnd();
}

return output;

How to send json data in the Http request using NSURLRequest

You can try this code for send json string

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ARRAY_CONTAIN_JSON_STRING options:NSJSONWritin*emphasized text*gPrettyPrinted error:NULL];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *WS_test = [NSString stringWithFormat:@"www.test.com?xyz.php&param=%@",jsonString];

regex to match a single character that is anything but a space

The following should suffice:

[^ ]

If you want to expand that to anything but white-space (line breaks, tabs, spaces, hard spaces):

[^\s]

or

\S  # Note this is a CAPITAL 'S'!

Which Android IDE is better - Android Studio or Eclipse?

Both are equally good. With Android Studio you have ADT tools integrated, and with eclipse you need to integrate them manually. With Android Studio, it feels like a tool designed from the outset with Android development in mind. Go ahead, they have same features.