Programs & Examples On #Dtd parsing

0

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

If you are using a non default MySQL port number then do the following:

  1. Stop your xampp/wamp/etc session
  2. Set port number used by MySQL in config.inc.php under the phpMyAdmin folder.
  3. For example if your MySQL port number is 33747 then paste the following
    $cfg['Servers'][$i]['port'] = 33747;
    
    under the
    /* Authentication type and info */
    
    section.
  4. Restart Apache and MySQL servers.

Wireshark vs Firebug vs Fiddler - pros and cons?

Fiddler is the winner every time when comparing to Charles.

The "customize rules" feature of fiddler is unparalleled in any http debugger. The ability to write code to manipulate http requests and responses on-the-fly is invaluable to me and the work I do in web development.

There are so many features to fiddler that charles just does not have, and likely won't ever have. Fiddler is light-years ahead.

Emulate a 403 error page

I understand you have a scenario with ErrorDocument already defined within your apache conf or .htaccess and want to make those pages appear when manually sending a 4xx status code via php.

Unfortunately this is not possible with common methods because php sends header directly to user's browser (not to Apache web server) whereas ErrorDocument is a display handler for http status generated from Apache.

"NODE_ENV" is not recognized as an internal or external command, operable command or batch file

I had the same problem and on windows platform and i just ran the below command

npm install -g win-node-env

and everything works normally

npm check and update package if needed

Check outdated packages

npm outdated

Check and pick packages to update

npx npm-check -u

npm oudated img

npx npm-check -u img

MetadataException: Unable to load the specified metadata resource

Just type path as follows instead of {Path.To.The.}: res:///{Path.To.The.}YourEdmxFileName.csdl|res:///{Path.To.The.}YourEdmxFileName.ssdl|res://*/{Path.To.The.}YourEdmxFileName.msl

How do I find the mime-type of a file with php?

According to the php manual, the finfo-file function is best way to do this. However, you will need to install the FileInfo PECL extension.

If the extension is not an option, you can use the outdated mime_content_type function.

Division of integers in Java

You don't even need doubles for this. Just multiply by 100 first and then divide. Otherwise the result would be less than 1 and get truncated to zero, as you saw.

edit: or if overflow is likely, if it would overflow (ie the dividend is bigger than 922337203685477581), divide the divisor by 100 first.

How to execute a program or call a system command from Python

This can be done in 2 ways:

1. os.system

   import os

To run a system command:

   os.system('cls')

To execute a program:

   os.system('code1.py')

2. subprocess.call

   import subprocess

To run a system command:

   subprocess.call('cls',shell=True)

To execute a program:

   subprocess.call('code1.py',shell=True)

How does #include <bits/stdc++.h> work in C++?

It is basically a header file that also includes every standard library and STL include file. The only purpose I can see for it would be for testing and education.

Se e.g. GCC 4.8.0 /bits/stdc++.h source.

Using it would include a lot of unnecessary stuff and increases compilation time.

Edit: As Neil says, it's an implementation for precompiled headers. If you set it up for precompilation correctly it could, in fact, speed up compilation time depending on your project. (https://gcc.gnu.org/onlinedocs/gcc/Precompiled-Headers.html)

I would, however, suggest that you take time to learn about each of the sl/stl headers and include them separately instead, and not use "super headers" except for precompilation purposes.

how to remove pagination in datatable

if you want to remove pagination and but want ordering of dataTable then add this script at the end of your page!

_x000D_
_x000D_
<script>_x000D_
$(document).ready(function() {        _x000D_
    $('#table_id').DataTable({_x000D_
        "paging":   false,_x000D_
       "info":     false_x000D_
    } );_x000D_
      _x000D_
  } );_x000D_
</script>
_x000D_
_x000D_
_x000D_

Does Eclipse have line-wrap

As mentioned in the post by VonC on this same page. Eclipse now has this capability as of 06/2016 Neon.

Try this plugin Eclipse platform plugin

It looks like eclipse only has the ability to do it manually on its own and here are the commands. At that point you must reformat the highlighted text manually.

It's not terribly obvious how to control Eclipse line width and line wrapping in your Java source files. Here's how and where:

Comment width and line wrapping is set in Preferences->Java->Code Style->Formatter, then click on the Edit button and select the Comments tab. I like Line Width for Comments to be 120.

Code line wrapping is set nearby, in Preferences->Java->Code Style- >Formatter, then click on the Edit button and select the Line Wrapping tab. I like a line width of 120 and indent size of 4.

Indentation is set separately, in Preferences->Java->Code Style- >Formatter, then click on the Edit button and select the Indentation tab. I like an indent size of 4, consistent with the Line Wrapping indent setting.

As if that's not enough, you can also set printer margins, tab size, etc, in Preferences>General>Editors>Text Editors where I set the Displayed Tab Width to 4 and Print Margin Column to 120 or more.

You can also check the Show Print Margin box to get a faint vertical line at the printer margin column

How do I update the GUI from another thread?

Simplest way is invoking as follows:

 Application.Current.Dispatcher.Invoke(new Action(() =>
             {
                    try
                    {
                        ///
                    }
                    catch (Exception)
                    {
                      //
                    }


                    }
     ));

matplotlib: how to change data points color based on some variable

If you want to plot lines instead of points, see this example, modified here to plot good/bad points representing a function as a black/red as appropriate:

def plot(xx, yy, good):
    """Plot data

    Good parts are plotted as black, bad parts as red.

    Parameters
    ----------
    xx, yy : 1D arrays
        Data to plot.
    good : `numpy.ndarray`, boolean
        Boolean array indicating if point is good.
    """
    import numpy as np
    import matplotlib.pyplot as plt
    fig, ax = plt.subplots()
    from matplotlib.colors import from_levels_and_colors
    from matplotlib.collections import LineCollection
    cmap, norm = from_levels_and_colors([0.0, 0.5, 1.5], ['red', 'black'])
    points = np.array([xx, yy]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    lines = LineCollection(segments, cmap=cmap, norm=norm)
    lines.set_array(good.astype(int))
    ax.add_collection(lines)
    plt.show()

Installing lxml module in python

You need to install Python's header files (python-dev package in debian/ubuntu) to compile lxml. As well as libxml2, libxslt, libxml2-dev, and libxslt-dev:

apt-get install python-dev libxml2 libxml2-dev libxslt-dev

Move textfield when keyboard appears swift

This is an improved version of @JosephLord and @Hlung's answer. It can apply whether you have tabbar or not. And it would perfectly restore view that is moved by keyboard to original position.

// You have to set this up in storyboard first!. 
// It's a vertical spacing constraint between view and bottom of superview.
@IBOutlet weak var bottomSpacingConstraint: NSLayoutConstraint! 

override func viewDidLoad() {
        super.viewDidLoad()            

        //    Receive(Get) Notification
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardNotification:", name: UIKeyboardWillShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardNotification:", name: UIKeyboardWillHideNotification, object: nil)


        self.originalConstraint = self.keyboardHeightLayoutConstraint?.constant //for original coordinate.
}

func keyboardNotification(notification: NSNotification) {
        let isShowing = notification.name == UIKeyboardWillShowNotification

        var tabbarHeight: CGFloat = 0
        if self.tabBarController? != nil {
            tabbarHeight = self.tabBarController!.tabBar.frame.height
        }
        if let userInfo = notification.userInfo {
            let endFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue()
            let duration:NSTimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
            let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber
            let animationCurveRaw = animationCurveRawNSN?.unsignedLongValue ?? UIViewAnimationOptions.CurveEaseInOut.rawValue
            let animationCurve:UIViewAnimationOptions = UIViewAnimationOptions(rawValue: animationCurveRaw)
            self.keyboardHeightLayoutConstraint?.constant = isShowing ? (endFrame!.size.height - tabbarHeight) : self.originalConstraint!
            UIView.animateWithDuration(duration,
                delay: NSTimeInterval(0),
                options: animationCurve,
                animations: { self.view.layoutIfNeeded() },
                completion: nil)
        }
}

Safari 3rd party cookie iframe trick no longer working?

I tricked Safari with a .htaccess:

#http://www.w3.org/P3P/validator.html
<IfModule mod_headers.c>
Header set P3P "policyref=\"/w3c/p3p.xml\", CP=\"NOI DSP COR NID CUR ADM DEV OUR BUS\""
Header set Set-Cookie "test_cookie=1"
</IfModule>

And it stopped working for me too. All my apps are losing the session in Safari and are redirecting out of Facebook. As I'm in a hurry to fix those apps, I'm currently searching for a solution. I'll keep you posted.

Edit (2012-04-06): Apparently Apple "fixed" it with 5.1.4. I'm sure this is the reaction to the Google-thing: "An issue existed in the enforcement of its cookie policy. Third-party websites could set cookies if the "Block Cookies" preference in Safari was set to the default setting of "From third parties and advertisers". http://support.apple.com/kb/HT5190

Prevent typing non-numeric in input type number

Try it:

document.querySelector("input").addEventListener("keyup", function () {
   this.value = this.value.replace(/\D/, "")
});

How to check if NSString begins with a certain character

As a more general answer, try using the hasPrefix method. For example, the code below checks to see if a string begins with 10, which is the error code used to identify a certain problem.

NSString* myString = @"10:Username taken";

if([myString hasPrefix:@"10"]) {
      //display more elegant error message
}

What is the best way to remove the first element from an array?

The size of arrays in Java cannot be changed. So, technically you cannot remove any elements from the array.

One way to simulate removing an element from the array is to create a new, smaller array, and then copy all of the elements from the original array into the new, smaller array.

String[] yourArray = Arrays.copyOfRange(oldArr, 1, oldArr.length);

However, I would not suggest the above method. You should really be using a List<String>. Lists allow you to add and remove items from any index. That would look similar to the following:

List<String> list = new ArrayList<String>(); // or LinkedList<String>();
list.add("Stuff");
// add lots of stuff
list.remove(0); // removes the first item

joining two select statements

Not sure what you are trying to do, but you have two select clauses. Do this instead:

SELECT * 
FROM ( SELECT * 
       FROM orders_products 
       INNER JOIN orders ON orders_products.orders_id = orders.orders_id 
       WHERE products_id = 181) AS A
JOIN ( SELECT * 
       FROM orders_products 
       INNER JOIN orders ON orders_products.orders_id = orders.orders_id
       WHERE products_id = 180) AS B

ON A.orders_id=B.orders_id

Update:

You could probably reduce it to something like this:

SELECT o.orders_id, 
       op1.products_id, 
       op1.quantity, 
       op2.products_id, 
       op2.quantity
FROM orders o
INNER JOIN orders_products op1 on o.orders_id = op1.orders_id  
INNER JOIN orders_products op2 on o.orders_id = op2.orders_id  
WHERE op1.products_id = 180
AND op2.products_id = 181

What is __future__ in Python used for and how/when to use it, and how it works

Or is it like saying "Since this is python v2.7, use that different 'print' function that has also been added to python v2.7, after it was added in python 3. So my 'print' will no longer be statements (eg print "message" ) but functions (eg, print("message", options). That way when my code is run in python 3, 'print' will not break."

In

from __future__ import print_function

print_function is the module containing the new implementation of 'print' as per how it is behaving in python v3.

This has more explanation: http://python3porting.com/noconv.html

What is the recommended way to delete a large number of items from DynamoDB?

What I ideally want to do is call LogTable.DeleteItem(user_id) - Without supplying the range, and have it delete everything for me.

An understandable request indeed; I can imagine advanced operations like these might get added over time by the AWS team (they have a history of starting with a limited feature set first and evaluate extensions based on customer feedback), but here is what you should do to avoid the cost of a full scan at least:

  1. Use Query rather than Scan to retrieve all items for user_id - this works regardless of the combined hash/range primary key in use, because HashKeyValue and RangeKeyCondition are separate parameters in this API and the former only targets the Attribute value of the hash component of the composite primary key..

    • Please note that you''ll have to deal with the query API paging here as usual, see the ExclusiveStartKey parameter:

      Primary key of the item from which to continue an earlier query. An earlier query might provide this value as the LastEvaluatedKey if that query operation was interrupted before completing the query; either because of the result set size or the Limit parameter. The LastEvaluatedKey can be passed back in a new query request to continue the operation from that point.

  2. Loop over all returned items and either facilitate DeleteItem as usual

    • Update: Most likely BatchWriteItem is more appropriate for a use case like this (see below for details).

Update

As highlighted by ivant, the BatchWriteItem operation enables you to put or delete several items across multiple tables in a single API call [emphasis mine]:

To upload one item, you can use the PutItem API and to delete one item, you can use the DeleteItem API. However, when you want to upload or delete large amounts of data, such as uploading large amounts of data from Amazon Elastic MapReduce (EMR) or migrate data from another database in to Amazon DynamoDB, this API offers an efficient alternative.

Please note that this still has some relevant limitations, most notably:

  • Maximum operations in a single request — You can specify a total of up to 25 put or delete operations; however, the total request size cannot exceed 1 MB (the HTTP payload).

  • Not an atomic operation — Individual operations specified in a BatchWriteItem are atomic; however BatchWriteItem as a whole is a "best-effort" operation and not an atomic operation. That is, in a BatchWriteItem request, some operations might succeed and others might fail. [...]

Nevertheless this obviously offers a potentially significant gain for use cases like the one at hand.

Possible to change where Android Virtual Devices are saved?

Variable name: ANDROID_SDK_HOME
Variable value: C:\Users>User Name

worked for me.

How do I create a basic UIButton programmatically?

'action:@selector(aMethod:)' write method like this :

- (void)aMethod:(UIButton*)button
   {
         NSLog(@"Button  clicked.");
  }

It works for me. Thanks. KS.

How to remove empty cells in UITableView?

Set a zero height table footer view (perhaps in your viewDidLoad method), like so:

Swift:

tableView.tableFooterView = UIView()

Objective-C:

tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];

Because the table thinks there is a footer to show, it doesn't display any cells beyond those you explicitly asked for.

Interface builder pro-tip:

If you are using a xib/Storyboard, you can just drag a UIView (with height 0pt) onto the bottom of the UITableView.

How do I run a batch file from my Java Application?

Process p = Runtime.getRuntime().exec( 
  new String[]{"cmd", "/C", "orgreg.bat"},
  null, 
  new File("D://TEST//home//libs//"));

tested with jdk1.5 and jdk1.6

This was working fine for me, hope it helps others too. to get this i have struggled more days. :(

How to Decode Json object in laravel and apply foreach loop on that in laravel

your string is NOT a valid json to start with.

a valid json will be,

{
    "area": [
        {
            "area": "kothrud"
        },
        {
            "area": "katraj"
        }
    ]
}

if you do a json_decode, it will yield,

stdClass Object
(
    [area] => Array
        (
            [0] => stdClass Object
                (
                    [area] => kothrud
                )

            [1] => stdClass Object
                (
                    [area] => katraj
                )

        )

)

Update: to use

$string = '

{
    "area": [
        {
            "area": "kothrud"
        },
        {
            "area": "katraj"
        }
    ]
}

';
            $area = json_decode($string, true);

            foreach($area['area'] as $i => $v)
            {
                echo $v['area'].'<br/>';
            }

Output:

kothrud
katraj

Update #2:

for that true:

When TRUE, returned objects will be converted into associative arrays. for more information, click here

What is a stack pointer used for in microprocessors?

The Stack is an area of memory for keeping temporary data. Stack is used by the CALL instruction to keep the return address for procedures The return RET instruction gets this value from the stack and returns to that offset. The same thing happens when an INT instruction calls an interrupt. It stores in the Stack the flag register, code segment and offset. The IRET instruction is used to return from interrupt call.

The Stack is a Last In First Out (LIFO) memory. Data is placed onto the Stack with a PUSH instruction and removed with a POP instruction. The Stack memory is maintained by two registers: the Stack Pointer (SP) and the Stack Segment (SS) register. When a word of data is PUSHED onto the stack the the High order 8-bit Byte is placed in location SP-1 and the Low 8-bit Byte is placed in location SP-2. The SP is then decremented by 2. The SP addds to the (SS x 10H) register, to form the physical stack memory address. The reverse sequence occurs when data is POPPED from the Stack. When a word of data is POPPED from the stack the the High order 8-bit Byte is obtained in location SP-1 and the Low 8-bit Byte is obtained in location SP-2. The SP is then incremented by 2.

Parsing JSON Object in Java

public class JsonParsing {

public static Properties properties = null;

public static JSONObject jsonObject = null;

static {
    properties = new Properties();
}

public static void main(String[] args) {

    try {

        JSONParser jsonParser = new JSONParser();

        File file = new File("src/main/java/read.json");

        Object object = jsonParser.parse(new FileReader(file));

        jsonObject = (JSONObject) object;

        parseJson(jsonObject);

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

public static void getArray(Object object2) throws ParseException {

    JSONArray jsonArr = (JSONArray) object2;

    for (int k = 0; k < jsonArr.size(); k++) {

        if (jsonArr.get(k) instanceof JSONObject) {
            parseJson((JSONObject) jsonArr.get(k));
        } else {
            System.out.println(jsonArr.get(k));
        }

    }
}

public static void parseJson(JSONObject jsonObject) throws ParseException {

    Set<Object> set = jsonObject.keySet();
    Iterator<Object> iterator = set.iterator();
    while (iterator.hasNext()) {
        Object obj = iterator.next();
        if (jsonObject.get(obj) instanceof JSONArray) {
            System.out.println(obj.toString());
            getArray(jsonObject.get(obj));
        } else {
            if (jsonObject.get(obj) instanceof JSONObject) {
                parseJson((JSONObject) jsonObject.get(obj));
            } else {
                System.out.println(obj.toString() + "\t"
                        + jsonObject.get(obj));
            }
        }
    }
}}

Background color not showing in print preview

That CSS property is all you need it works for me...When previewing in Chrome you have the option to see it BW and Color(Color: Options- Color or Black and white) so if you don't have that option, then I suggest to grab this Chrome extension and make your life easier:

https://chrome.google.com/webstore/detail/print-background-colors/gjecpgdgnlanljjdacjdeadjkocnnamk?hl=en

The site you added on fiddle needs this in your media print css (you have it just need to add it...

media print CSS in the body:

@media print {
body {-webkit-print-color-adjust: exact;}
}

UPDATE OK so your issue is bootstrap.css...it has a media print css as well as you do....you remove that and that should give you color....you need to either do your own or stick with bootstraps print css.

When I click print on this I see color.... http://jsfiddle.net/rajkumart08/TbrtD/1/embedded/result/

Detect a finger swipe through JavaScript on the iPhone and Android

I have found @givanse brilliant answer to be the most reliable and compatible across multiple mobile browsers for registering swipe actions.

However, there's a change in his code required to make it work in modern day mobile browsers that are using jQuery.

event.toucheswon't exist if jQuery is used and results in undefined and should be replaced by event.originalEvent.touches. Without jQuery, event.touches should work fine.

So the solution becomes,

document.addEventListener('touchstart', handleTouchStart, false);        
document.addEventListener('touchmove', handleTouchMove, false);

var xDown = null;                                                        
var yDown = null;                                                        

function handleTouchStart(evt) {                                         
    xDown = evt.originalEvent.touches[0].clientX;                                      
    yDown = evt.originalEvent.touches[0].clientY;                                      
};                                                

function handleTouchMove(evt) {
    if ( ! xDown || ! yDown ) {
        return;
    }

    var xUp = evt.originalEvent.touches[0].clientX;                                    
    var yUp = evt.originalEvent.touches[0].clientY;

    var xDiff = xDown - xUp;
    var yDiff = yDown - yUp;

    if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) {/*most significant*/
        if ( xDiff > 0 ) {
            /* left swipe */ 
        } else {
            /* right swipe */
        }                       
    } else {
        if ( yDiff > 0 ) {
            /* up swipe */ 
        } else { 
            /* down swipe */
        }                                                                 
    }
    /* reset values */
    xDown = null;
    yDown = null;                                             
};

Tested on:

  • Android: Chrome, UC Browser
  • iOS: Safari, Chrome, UC Browser

How to permanently export a variable in Linux?

You have to edit three files to set a permanent environment variable as follow:

  • ~/.bashrc

    When you open any terminal window this file will be run. Therefore, if you wish to have a permanent environment variable in all of your terminal windows you have to add the following line at the end of this file:

    export DISPLAY=0
    
  • ~/.profile

    Same as bashrc you have to put the mentioned command line at the end of this file to have your environment variable in every login of your OS.

  • /etc/environment

    If you want your environment variable in every window or application (not just terminal window) you have to edit this file. Add the following command at the end of this file:

    DISPLAY=0
    

    Note that in this file you do not have to write export command

Normally you have to restart your computer to apply these changes. But you can apply changes in bashrc and profile by these commands:

$ source ~/.bashrc
$ source ~/.profile

But for /etc/environment you have no choice but restarting (as far as I know)

A Simple Solution

I've written a simple script for these procedures to do all those work. You just have to set the name and value of your environment variable.

#!/bin/bash
echo "Enter variable name: "
read variable_name
echo "Enter variable value: "
read variable_value
echo "adding " $variable_name " to environment variables: " $variable_value
echo "export "$variable_name"="$variable_value>>~/.bashrc
echo $variable_name"="$variable_value>>~/.profile
echo $variable_name"="$variable_value>>/etc/environment
source ~/.bashrc
source ~/.profile
echo "do you want to restart your computer to apply changes in /etc/environment file? yes(y)no(n)"
read restart
case $restart in
    y) sudo shutdown -r 0;;
    n) echo "don't forget to restart your computer manually";;
esac
exit

Save these lines in a shfile then make it executable and just run it!

Eclipse says: “Workspace in use or cannot be created, chose a different one.” How do I unlock a workspace?

Another all-too-common reason for this problem is if you attempt to load a directory on a drive that is no longer connected. For example, Say you program in C:\Code\Java, but occasionally work off of a flash drive, H:\Code\Java. If you do not have the drive connected it can be easy to believe you are trying to load a valid directory without noticing your typo.

CSS vertical-align: text-bottom;

To use vertical-align properly, you should do it on table tag. But there is a way to make other html tags to behave as a table by assigning them a css of display:table to your parent, and display:table-cell on your child. Then vertical-align:bottom will work on that child.

HTML:

??????<div class="parent">
    <div class="child">
        This text is vertically aligned to bottom.    
    </div>
</div>????????????????????????

CSS:

?.parent {
    width: 300px;
    height: 50px;
    display:? table;
    border: 1px solid red;
}
.child { 
    display: table-cell;
    vertical-align: bottom;
}?

Here is a live example: link demo

Multiple conditions in WHILE loop

If your code, if the user enters 'X' (for instance), when you reach the while condition evaluation it will determine that 'X' is differente from 'n' (nChar != 'n') which will make your loop condition true and execute the code inside of your loop. The second condition is not even evaluated.

How to remove all duplicate items from a list

This should be faster and will preserve the original order:

seen = {}
new_list = [seen.setdefault(x, x) for x in my_list if x not in seen]

If you don't care about order, you can just:

new_list = list(set(my_list))

Convert a list to a string in C#

You could use string.Join:

List<string> list = new List<string>()
{
    "Red",
    "Blue",
    "Green"
};

string output = string.Join(Environment.NewLine, list.ToArray());    
Console.Write(output);

The result would be:

Red    
Blue    
Green

As an alternative to Environment.NewLine, you can replace it with a string based line-separator of your choosing.

Can I get the name of the currently running function in JavaScript?

For non-anonymous functions

function foo()
{ 
    alert(arguments.callee.name)
}

But in case of an error handler the result would be the name of the error handler function, wouldn't it?

Android customized button; changing text color

Use getColorStateList like this

setTextColor(resources.getColorStateList(R.color.button_states_color))

instead of getColor

setTextColor(resources.getColor(R.color.button_states_color))

How to sort multidimensional array by column?

The optional key parameter to sort/sorted is a function. The function is called for each item and the return values determine the ordering of the sort

>>> lst = [['John', 2], ['Jim', 9], ['Jason', 1]]
>>> def my_key_func(item):
...     print("The key for {} is {}".format(item, item[1]))
...     return item[1]
... 
>>> sorted(lst, key=my_key_func)
The key for ['John', 2] is 2
The key for ['Jim', 9] is 9
The key for ['Jason', 1] is 1
[['Jason', 1], ['John', 2], ['Jim', 9]]

taking the print out of the function leaves

>>> def my_key_func(item):
...     return item[1]

This function is simple enough to write "inline" as a lambda function

>>> sorted(lst, key=lambda item: item[1])
[['Jason', 1], ['John', 2], ['Jim', 9]]

Getting the HTTP Referrer in ASP.NET

Sometime you must to give all the link like this

System.Web.HttpContext.Current.Request.UrlReferrer.ToString();

(in option when "Current" not founded)

How can Bash execute a command in a different directory context?

If you want to return to your current working directory:

current_dir=$PWD;cd /path/to/your/command/dir;special command ARGS;cd $current_dir;
  1. We are setting a variable current_dir equal to your pwd
  2. after that we are going to cd to where you need to run your command
  3. then we are running the command
  4. then we are going to cd back to our variable current_dir

Another Solution by @apieceofbart pushd && YOUR COMMAND && popd

Can you "compile" PHP code and upload a binary-ish file, which will just be run by the byte code interpreter?

If you are simply looking for producing a binary executable from a PHP script, then please avoid trying to make your question extremely precise because it will make it appear that you know exactly what you need. Besides, most PHP developer have absolutely zero clue about what a bytecode is.

With that said, the answers is YES. I have just finished compiling a PHP script into a binary. And not just any binary. I have used the CDE application (link to Wayback Machine, the original link is now broken) to turn it into an portable binary that can be distributed with all the dependencies and executed without any issue… and it works beautifully.

All you need is to use phc.

How do I delete unpushed git commits?

Delete the most recent commit, keeping the work you've done:

git reset --soft HEAD~1

Delete the most recent commit, destroying the work you've done:

git reset --hard HEAD~1

Plotting with C#

I just wanted to supplement MajesticRa's recommendation of OxyPlot, and point out how OxyPlot can be used for a variety of plotting cases. The software is free and Open-Source, very polished, and allows for a variety of uses beyon normal 2D mapping.

I've been using OxyPlot for an unorthodox project, where I display (in WPF/C#) a map (Robotic Occupancy Grid) which I could overlay with LineSeries (Path Traveled) and PointSeries (Way Points). Using the OxyPlot ImageAnnotation feature I am able to display 60Hz Video within my OxyPlot, by periodically updating the ImageAnnotation on its own thread, while mapping Series of points overtop the video. The background video and points are even scalable and translatable.

Hopefully this is helpful for other looking to display plots overtop of images and videos.

How to display both icon and title of action inside ActionBar?

What worked for me was using 'always|withText'. If you have many menus, consider using 'ifRoom' instead of 'always'.

<item android:id="@id/resource_name"
android:title="text"
android:icon="@drawable/drawable_resource_name"
android:showAsAction="always|withText" />

Brew install docker does not include docker engine?

To install Docker for Mac with homebrew:

brew cask install docker

To install the command line completion:

brew install bash-completion
brew install docker-completion
brew install docker-compose-completion
brew install docker-machine-completion

Entity Framework - Code First - Can't Store List<String>

JSON.NET to the rescue.

You serialize it to JSON to persist in the Database and Deserialize it to reconstitute the .NET collection. This seems to perform better than I expected it to with Entity Framework 6 & SQLite. I know you asked for List<string> but here's an example of an even more complex collection that works just fine.

I tagged the persisted property with [Obsolete] so it would be very obvious to me that "this is not the property you are looking for" in the normal course of coding. The "real" property is tagged with [NotMapped] so Entity framework ignores it.

(unrelated tangent): You could do the same with more complex types but you need to ask yourself did you just make querying that object's properties too hard for yourself? (yes, in my case).

using Newtonsoft.Json;
....
[NotMapped]
public Dictionary<string, string> MetaData { get; set; } = new Dictionary<string, string>();

/// <summary> <see cref="MetaData"/> for database persistence. </summary>
[Obsolete("Only for Persistence by EntityFramework")]
public string MetaDataJsonForDb
{
    get
    {
        return MetaData == null || !MetaData.Any()
                   ? null
                   : JsonConvert.SerializeObject(MetaData);
    }

    set
    {
        if (string.IsNullOrWhiteSpace(value))
           MetaData.Clear();
        else
           MetaData = JsonConvert.DeserializeObject<Dictionary<string, string>>(value);
    }
}

Check if value is in select list with JQuery

_x000D_
_x000D_
if(!$('#select-box').find("option:contains('" + thevalue  + "')").length){_x000D_
//do stuff_x000D_
}
_x000D_
_x000D_
_x000D_

Conflict with dependency 'com.android.support:support-annotations'. Resolved versions for app (23.1.0) and test app (23.0.1) differ

In my case, I added below code in dependencies of app level build.gradle

androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})

After that, I clean the project and rebuild.My problem solved.

NullPointerException in Java with no StackTrace

exception.toString does not give you the StackTrace, it only returns

a short description of this throwable. The result is the concatenation of:

* the name of the class of this object
* ": " (a colon and a space)
* the result of invoking this object's getLocalizedMessage() method

Use exception.printStackTrace instead to output the StackTrace.

Case statement in MySQL

I hope this would provide you with the right solution:

Syntax:

   CASE  
        WHEN search_condition THEN statement_list  
       [WHEN search_condition THEN statement_list]....
       [ELSE statement_list]  
   END CASE

Implementation:

select id, action_heading,  
   case when
             action_type="Expense" then action_amount  
             else NULL   
             end as Expense_amt,   
    case when  
             action_type ="Income" then action_amount  
             else NULL  
             end as Income_amt  
  from tbl_transaction;

Here I am using CASE statement as it is more flexible than if-then-else. It allows more than one branch. And CASE statement is standard SQL and works in most databases.

Encode String to UTF-8

Use byte[] ptext = String.getBytes("UTF-8"); instead of getBytes(). getBytes() uses so-called "default encoding", which may not be UTF-8.

runOnUiThread in fragment

For Kotlin on fragment just do this

activity?.runOnUiThread(Runnable {
        //on main thread
    })

What are good grep tools for Windows?

FINDSTR is fairly powerful, supports regular expressions and has the advantages of being on all Windows machines already.

c:\> FindStr /?

Searches for strings in files.

FINDSTR [/B] [/E] [/L] [/R] [/S] [/I] [/X] [/V] [/N] [/M] [/O] [/P] [/F:file]
        [/C:string] [/G:file] [/D:dir list] [/A:color attributes] [/OFF[LINE]]
        strings [[drive:][path]filename[ ...]]

  /B         Matches pattern if at the beginning of a line.
  /E         Matches pattern if at the end of a line.
  /L         Uses search strings literally.
  /R         Uses search strings as regular expressions.
  /S         Searches for matching files in the current directory and all
             subdirectories.
  /I         Specifies that the search is not to be case-sensitive.
  /X         Prints lines that match exactly.
  /V         Prints only lines that do not contain a match.
  /N         Prints the line number before each line that matches.
  /M         Prints only the filename if a file contains a match.
  /O         Prints character offset before each matching line.
  /P         Skip files with non-printable characters.
  /OFF[LINE] Do not skip files with offline attribute set.
  /A:attr    Specifies color attribute with two hex digits. See "color /?"
  /F:file    Reads file list from the specified file(/ stands for console).
  /C:string  Uses specified string as a literal search string.
  /G:file    Gets search strings from the specified file(/ stands for console).
  /D:dir     Search a semicolon delimited list of directories
  strings    Text to be searched for.
  [drive:][path]filename
             Specifies a file or files to search.

Use spaces to separate multiple search strings unless the argument is prefixed
with /C.  For example, 'FINDSTR "hello there" x.y' searches for "hello" or
"there" in file x.y.  'FINDSTR /C:"hello there" x.y' searches for
"hello there" in file x.y.

Regular expression quick reference:
  .        Wildcard: any character
  *        Repeat: zero or more occurances of previous character or class
  ^        Line position: beginning of line
  $        Line position: end of line
  [class]  Character class: any one character in set
  [^class] Inverse class: any one character not in set
  [x-y]    Range: any characters within the specified range
  \x       Escape: literal use of metacharacter x
  \<xyz    Word position: beginning of word
  xyz\>    Word position: end of word

Example usage: findstr text_to_find * or to search recursively findstr /s text_to_find *

Change values of select box of "show 10 entries" of jquery datatable

$(document).ready(function() {
    $('#example').dataTable( {
    "aLengthMenu": [[25, 50, 75, -1], [25, 50, 75, "All"]],
    "pageLength": 25
    } );
} );

aLengthMenu : This parameter allows you to readily specify the entries in the length drop down menu that DataTables shows when pagination is enabled. It can be either a 1D array of options which will be used for both the displayed option and the value, or a 2D array which will use the array in the first position as the value, and the array in the second position as the displayed options (useful for language strings such as 'All').

Update

Since DataTables v1.10, the options you are looking for are pageLength and lengthMenu

How to do a case sensitive search in WHERE clause (I'm using SQL Server)?

use Latin1_General_CS as your collation in your sql db

Styles.Render in MVC4

It's calling the files included in that particular bundle which is declared inside the BundleConfig class in the App_Start folder.

In that particular case The call to @Styles.Render("~/Content/css") is calling "~/Content/site.css".

bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));

instanceof Vs getClass( )

I know it has been a while since this was asked, but I learned an alternative yesterday

We all know you can do:

if(o instanceof String) {   // etc

but what if you dont know exactly what type of class it needs to be? you cannot generically do:

if(o instanceof <Class variable>.getClass()) {   

as it gives a compile error.
Instead, here is an alternative - isAssignableFrom()

For example:

public static boolean isASubClass(Class classTypeWeWant, Object objectWeHave) {

    return classTypeWeWant.isAssignableFrom(objectWeHave.getClass())
}

Read only file system on Android

it sames that must extract and repack initrc.img and edit init file with the code of mount /system

How to change screen resolution of Raspberry Pi

You can change the display resolution graphically (without using Terminal) on Raspbian GNU/Linux 8 (jessie) using following window.

Application Menu > Preferences > Raspberry Pi Configuration > System > Set Resolution.

Click to view screenshots

Lazy Method for Reading Big File in Python?

Refer to python's official documentation https://docs.python.org/3/library/functions.html#iter

Maybe this method is more pythonic:

from functools import partial

"""A file object returned by open() is a iterator with
read method which could specify current read's block size"""
with open('mydata.db', 'r') as f_in:

    part_read = partial(f_in.read, 1024*1024)
    iterator = iter(part_read, b'')

    for index, block in enumerate(iterator, start=1):
        block = process_block(block)    # process your block data
        
        with open(f'{index}.txt', 'w') as f_out:
            f_out.write(block)

How do I check if a string contains another string in Swift?

Here you go! Ready for Xcode 8 and Swift 3.

import UIKit

let mString = "This is a String that contains something to search."
let stringToSearchUpperCase = "String"
let stringToSearchLowerCase = "string"

mString.contains(stringToSearchUpperCase) //true
mString.contains(stringToSearchLowerCase) //false
mString.lowercased().contains(stringToSearchUpperCase) //false
mString.lowercased().contains(stringToSearchLowerCase) //true

Connection Strings for Entity Framework

To enable the same edmx to access multiple databases and database providers and vise versa I use the following technique:

1) Define a ConnectionManager:

public static class ConnectionManager
{
    public static string GetConnectionString(string modelName)
    {
        var resourceAssembly = Assembly.GetCallingAssembly();

        var resources = resourceAssembly.GetManifestResourceNames();

        if (!resources.Contains(modelName + ".csdl")
            || !resources.Contains(modelName + ".ssdl")
            || !resources.Contains(modelName + ".msl"))
        {
            throw new ApplicationException(
                    "Could not find connection resources required by assembly: "
                    + System.Reflection.Assembly.GetCallingAssembly().FullName);
        }

        var provider = System.Configuration.ConfigurationManager.AppSettings.Get(
                        "MyModelUnitOfWorkProvider");

        var providerConnectionString = System.Configuration.ConfigurationManager.AppSettings.Get(
                        "MyModelUnitOfWorkConnectionString");

        string ssdlText;

        using (var ssdlInput = resourceAssembly.GetManifestResourceStream(modelName + ".ssdl"))
        {
            using (var textReader = new StreamReader(ssdlInput))
            {
                ssdlText = textReader.ReadToEnd();
            }
        }

        var token = "Provider=\"";
        var start = ssdlText.IndexOf(token);
        var end = ssdlText.IndexOf('"', start + token.Length);
        var oldProvider = ssdlText.Substring(start, end + 1 - start);

        ssdlText = ssdlText.Replace(oldProvider, "Provider=\"" + provider + "\"");

        var tempDir = Environment.GetEnvironmentVariable("TEMP") + '\\' + resourceAssembly.GetName().Name;
        Directory.CreateDirectory(tempDir);

        var ssdlOutputPath = tempDir + '\\' + Guid.NewGuid() + ".ssdl";

        using (var outputFile = new FileStream(ssdlOutputPath, FileMode.Create))
        {
            using (var outputStream = new StreamWriter(outputFile))
            {
                outputStream.Write(ssdlText);
            }
        }

        var eBuilder = new EntityConnectionStringBuilder
        {
            Provider = provider,

            Metadata = "res://*/" + modelName + ".csdl"
                        + "|" + ssdlOutputPath
                        + "|res://*/" + modelName + ".msl",

            ProviderConnectionString = providerConnectionString
        };

        return eBuilder.ToString();
    }
}

2) Modify the T4 that creates your ObjectContext so that it will use the ConnectionManager:

public partial class MyModelUnitOfWork : ObjectContext
{
    public const string ContainerName = "MyModelUnitOfWork";
    public static readonly string ConnectionString
        = ConnectionManager.GetConnectionString("MyModel");

3) Add the following lines to App.Config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="MyModelUnitOfWork" connectionString=... />
  </connectionStrings>
  <appSettings>
    <add key="MyModelUnitOfWorkConnectionString" value="data source=MyPc\SqlExpress;initial catalog=MyDB;integrated security=True;multipleactiveresultsets=True" />
    <add key="MyModelUnitOfWorkProvider" value="System.Data.SqlClient" />
  </appSettings>
</configuration>

The ConnectionManager will replace the ConnectionString and Provider to what ever is in the App.Config.

You can use the same ConnectionManager for all ObjectContexts (so they all read the same settings from App.Config), or edit the T4 so it creates one ConnectionManager for each (in its own namespace), so that each reads separate settings.

Two decimal places using printf( )

Use: "%.2f" or variations on that.

See the POSIX spec for an authoritative specification of the printf() format strings. Note that it separates POSIX extras from the core C99 specification. There are some C++ sites which show up in a Google search, but some at least have a dubious reputation, judging from comments seen elsewhere on SO.

Since you're coding in C++, you should probably be avoiding printf() and its relatives.

How do I change the background color of the ActionBar of an ActionBarActivity using XML?

try one line code :

getActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.MainColor)));

AngularJs .$setPristine to reset form

I solved the same problem of having to reset a form at its pristine state in Angular version 1.0.7 (no $setPristine method)

In my use case, the form, after being filled and submitted must disappear until it is again necessary for filling another record. So I made the show/hide effect by using ng-switch instead of ng-show. As I suspected, with ng-switch, the form DOM sub-tree is completely removed and later recreated. So the pristine state is automatically restored.

I like it because it is simple and clean but it may not be a fit for anybody's use case.

it may also imply some performance issues for big forms (?) In my situation I did not face this problem yet.

Iterating over a 2 dimensional python list

Use zip and itertools.chain. Something like:

>>> from itertools import chain
>>> l = chain.from_iterable(zip(*l))
<itertools.chain object at 0x104612610>
>>> list(l)
['0,0', '1,0', '2,0', '0,1', '1,1', '2,1']

How do I dynamically change the content in an iframe using jquery?

var handle = setInterval(changeIframe, 30000);
var sites = ["google.com", "yahoo.com"];
var index = 0;

function changeIframe() {
  $('#frame')[0].src = sites[index++];
  index = index >= sites.length ? 0 : index;
}

How to Get the Query Executed in Laravel 5? DB::getQueryLog() Returning Empty Array

Suppose you want to print the SQL query of the following statements.

$user = User::find(5);

You just need to do as follows:

DB::enableQueryLog();//enable query logging

$user = User::find(5);

print_r(DB::getQueryLog());//print sql query

This will print the last executed query in Laravel.

Vertically align text within a div

To make Omar's (or Mahendra's) solution even more universal, the block of code relative to Firefox should be replaced by the following:

/* Firefox */
display: flex;
justify-content: center;
align-items: center;

The problem with Omar's code, otherwise operative, arises when you want to center the box in the screen or in its immediate ancestor. This centering is done either by setting its position to

position: relative; or position:static; (not with position:absolute nor fixed).

And then margin: auto; or margin-right: auto; margin-left: auto;

Under this box center aligning environment, Omar's suggestion does not work. It doesn't work either in Internet Explorer 8 (yet 7.7% market share). So for Internet Explorer 8 (and other browsers), a workaround as seen in other above solutions should be considered.

Resize an Array while keeping current elements in Java?

Sorry, but at this time is not possible resize arrays, and may be never will be.

So my recommendation, is to think more to find a solution that allow you get from the beginning of the process, the size of the arrays that you will requiere. This often will implicate that your code need a little more time (lines) to run, but you will save a lot of memory resources.

Selecting an element in iFrame jQuery

Take a look at this post: http://praveenbattula.blogspot.com/2009/09/access-iframe-content-using-jquery.html

$("#iframeID").contents().find("[tokenid=" + token + "]").html();

Place your selector in the find method.

This may not be possible however if the iframe is not coming from your server. Other posts talk about permission denied errors.

jQuery/JavaScript: accessing contents of an iframe

How to get the client IP address in PHP

One of these :

    $ip = $_SERVER['REMOTE_ADDR'];
    $ip = $_SERVER['HTTP_CLIENT_IP'];
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    $ip = $_SERVER['HTTP_X_FORWARDED'];
    $ip = $_SERVER['HTTP_FORWARDED_FOR'];
    $ip = $_SERVER['HTTP_FORWARDED'];

SQL select * from column where year = 2010

T-SQL and others;

select * from t where year(Columnx) = 2010

Apache2: 'AH01630: client denied by server configuration'

Has anyone thought about that wamp server default not include the httpd-vhosts.conf file. My approach is to remove the note below

 conf
  # Virtual hosts
  Include conf/extra/httpd-vhosts.conf

in httpd.conf file. That is all.

Removing element from array in component state

I believe referencing this.state inside of setState() is discouraged (State Updates May Be Asynchronous).

The docs recommend using setState() with a callback function so that prevState is passed in at runtime when the update occurs. So this is how it would look:

Using Array.prototype.filter without ES6

removeItem : function(index) {
  this.setState(function(prevState){
    return { data : prevState.data.filter(function(val, i) {
      return i !== index;
    })};
  });
}

Using Array.prototype.filter with ES6 Arrow Functions

removeItem(index) {
  this.setState((prevState) => ({
    data: prevState.data.filter((_, i) => i !== index)
  }));
}

Using immutability-helper

import update from 'immutability-helper'
...
removeItem(index) {
  this.setState((prevState) => ({
    data: update(prevState.data, {$splice: [[index, 1]]})
  }))
}

Using Spread

function removeItem(index) {
  this.setState((prevState) => ({
    data: [...prevState.data.slice(0,index), ...prevState.data.slice(index+1)]
  }))
}

Note that in each instance, regardless of the technique used, this.setState() is passed a callback, not an object reference to the old this.state;

Quickly create a large file on a Linux system

Linux & all filesystems

xfs_mkfile 10240m 10Gigfile

Linux & and some filesystems (ext4, xfs, btrfs and ocfs2)

fallocate -l 10G 10Gigfile

OS X, Solaris, SunOS and probably other UNIXes

mkfile 10240m 10Gigfile

HP-UX

prealloc 10Gigfile 10737418240

Explanation

Try mkfile <size> myfile as an alternative of dd. With the -n option the size is noted, but disk blocks aren't allocated until data is written to them. Without the -n option, the space is zero-filled, which means writing to the disk, which means taking time.

mkfile is derived from SunOS and is not available everywhere. Most Linux systems have xfs_mkfile which works exactly the same way, and not just on XFS file systems despite the name. It's included in xfsprogs (for Debian/Ubuntu) or similar named packages.

Most Linux systems also have fallocate, which only works on certain file systems (such as btrfs, ext4, ocfs2, and xfs), but is the fastest, as it allocates all the file space (creates non-holey files) but does not initialize any of it.

How to convert a string with Unicode encoding to a string of letters

Shorter version:

public static String unescapeJava(String escaped) {
    if(escaped.indexOf("\\u")==-1)
        return escaped;

    String processed="";

    int position=escaped.indexOf("\\u");
    while(position!=-1) {
        if(position!=0)
            processed+=escaped.substring(0,position);
        String token=escaped.substring(position+2,position+6);
        escaped=escaped.substring(position+6);
        processed+=(char)Integer.parseInt(token,16);
        position=escaped.indexOf("\\u");
    }
    processed+=escaped;

    return processed;
}

Random number between 0 and 1 in python

random.randrange(0,2) this works!

Oracle: how to add minutes to a timestamp?

In addition to being able to add a number of days to a date, you can use interval data types assuming you are on Oracle 9i or later, which can be somewhat easier to read,

SQL> ed
Wrote file afiedt.buf
SELECT sysdate, sysdate + interval '30' minute FROM dual
SQL> /

SYSDATE              SYSDATE+INTERVAL'30'
-------------------- --------------------
02-NOV-2008 16:21:40 02-NOV-2008 16:51:40

Lua - Current time in milliseconds

I made a suitable solution for lua on Windows. I basically did what Kevlar suggested, but with a shared library rather than a DLL. This has been tested using cygwin.

I wrote some lua compatible C code, compiled it to a shared library (.so file via gcc in cygwin), and then loaded it up in lua using package.cpath and require" ". Wrote an adapter script for convenience. Here is all of the source:

first the C code, HighResTimer.c

////////////////////////////////////////////////////////////////
//HighResTimer.c by Cody Duncan
//
//compile with:  gcc -o Timer.so -shared HighResTimer.c -llua5.1
//compiled in cygwin after installing lua (cant remember if I 
//   installed via setup or if I downloaded and compiled lua, 
//   probably the former)
////////////////////////////////////////////////////////////////
#include <windows.h>

typedef unsigned __int64 u64;
double mNanoSecondsPerCount;

#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"


int prevInit = 0;
int currInit = 0;
u64 prevTime = 0;
u64 currTime = 0;
u64 FrequencyCountPerSec;

LARGE_INTEGER frequencyTemp;
static int readHiResTimerFrequency(lua_State *L)
{
    QueryPerformanceFrequency(&frequencyTemp);
    FrequencyCountPerSec = frequencyTemp.QuadPart;
    lua_pushnumber(L, frequencyTemp.QuadPart);
    return 1;
}

LARGE_INTEGER timerTemp;
static int storeTime(lua_State *L)
{
    QueryPerformanceCounter(&timerTemp);

    if(!prevInit)
    {
        prevInit = 1;
        prevTime = timerTemp.QuadPart;
    }
    else if (!currInit)
    {
        currInit = 1;
        currTime = timerTemp.QuadPart;
    }
    else
    {
        prevTime = currTime;
        currTime = timerTemp.QuadPart;
    }

    lua_pushnumber(L, timerTemp.QuadPart);
    return 1;
}

static int getNanoElapsed(lua_State *L)
{
    double mNanoSecondsPerCount = 1000000000/(double)FrequencyCountPerSec;
    double elapsedNano = (currTime - prevTime)*mNanoSecondsPerCount;
    lua_pushnumber(L, elapsedNano);
    return 1;
}


int luaopen_HighResolutionTimer (lua_State *L) {

    static const luaL_reg mylib [] = 
    {
        {"readHiResTimerFrequency", readHiResTimerFrequency},
        {"storeTime", storeTime},
        {"getNanoElapsed", getNanoElapsed},
        {NULL, NULL}  /* sentinel */
    };

    luaL_register(L,"timer",mylib);

    return 1;
}

--

--

Now lets get it loaded up in a lua script, HighResTimer.lua .

Note: I compiled the HighResTimer.c to a shared library, Timer.so

#!/bin/lua
------------------------------------
---HighResTimer.lua by Cody Duncan
---Wraps the High Resolution Timer Functions in
---   Timer.so
------------------------------------

package.cpath = "./Timer.so"     --assuming Timer.so is in the same directory
require "HighResolutionTimer"    --load up the module
timer.readHiResTimerFrequency(); --stores the tickFrequency


--call this before code that is being measured for execution time
function start()
    timer.storeTime();
end

--call this after code that is being measured for execution time
function stop()
    timer.storeTime();
end

--once the prior two functions have been called, call this to get the 
--time elapsed between them in nanoseconds
function getNanosElapsed()
    return timer.getNanoElapsed();
end

--

--

and Finally, utilize the timer, TimerTest.lua .

#!/bin/lua
------------------------------------
---TimerTest.lua by Cody Duncan
---
---HighResTimer.lua and Timer.so must 
---   be in the same directory as 
---   this script.
------------------------------------

require './HighResTimer' 

start();
for i = 0, 3000000 do io.write("") end --do essentially nothing 3million times.
stop();

--divide nanoseconds by 1 million to get milliseconds
executionTime = getNanosElapsed()/1000000; 
io.write("execution time: ", executionTime, "ms\n");

Note: Any comments were written after pasting the source code into the post editor, so technically this is untested, but hopefully the comments didn't befuddle anything. I will be sure to come back and provide a fix if it does.

Javascript onHover event

I don't think you need/want the timeout.

onhover (hover) would be defined as the time period while "over" something. IMHO

onmouseover = start...

onmouseout = ...end

For the record I've done some stuff with this to "fake" the hover event in IE6. It was rather expensive and in the end I ditched it in favor of performance.

How can I check if a checkbox is checked?

This should allow you to check if element with id='remember' is 'checked'

if (document.getElementById('remember').is(':checked')

Fastest way to copy a file in Node.js

Well, usually it is good to avoid asynchronous file operations. Here is the short (i.e. no error handling) sync example:

var fs = require('fs');
fs.writeFileSync(targetFile, fs.readFileSync(sourceFile));

How to get the first 2 letters of a string in Python?

t = "your string"

Play with the first N characters of a string with

def firstN(s, n=2):
    return s[:n]

which is by default equivalent to

t[:2]

Does Git Add have a verbose switch

I was debugging an issue with git and needed some very verbose output to figure out what was going wrong. I ended up setting the GIT_TRACE environment variable:

export GIT_TRACE=1
git add *.txt

You can also use these on the same line:

GIT_TRACE=1 git add *.txt

Output:

14:06:05.508517 git.c:415               trace: built-in: git add test.txt test2.txt
14:06:05.544890 git.c:415               trace: built-in: git config --get oh-my-zsh.hide-dirty

Center HTML Input Text Field Placeholder

By using the code snippet below, you are selecting the placeholder inside your input, and any code placed inside will affect only the placeholder.

input::-webkit-input-placeholder {
      text-align: center
}

How to check if $_GET is empty?

i guess the simplest way which doesn't require any operators is

if($_GET){
//do something if $_GET is set 
} 
if(!$_GET){
//do something if $_GET is NOT set 
} 

Unclosed Character Literal error

Character only takes one value dude! like: char y = 'h'; and maybe you typed like char y = 'hello'; or smthg. good luck. for the question asked above the answer is pretty simple u have to use DOUBLE QUOTES to give a string value. easy enough;)

How do I sort a VARCHAR column in SQL server that contains numbers?

you can always convert your varchar-column to bigint as integer might be too short...

select cast([yourvarchar] as BIGINT)

but you should always care for alpha characters

where ISNUMERIC([yourvarchar] +'e0') = 1

the +'e0' comes from http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/isnumeric-isint-isnumber

this would lead to your statement

SELECT
  *
FROM
  Table
ORDER BY
   ISNUMERIC([yourvarchar] +'e0') DESC
 , LEN([yourvarchar]) ASC

the first sorting column will put numeric on top. the second sorts by length, so 10 will preceed 0001 (which is stupid?!)

this leads to the second version:

SELECT
      *
    FROM
      Table
    ORDER BY
       ISNUMERIC([yourvarchar] +'e0') DESC
     , RIGHT('00000000000000000000'+[yourvarchar], 20) ASC

the second column now gets right padded with '0', so natural sorting puts integers with leading zeros (0,01,10,0100...) in correct order (correct!) - but all alphas would be enhanced with '0'-chars (performance)

so third version:

 SELECT
          *
        FROM
          Table
        ORDER BY
           ISNUMERIC([yourvarchar] +'e0') DESC
         , CASE WHEN ISNUMERIC([yourvarchar] +'e0') = 1
                THEN RIGHT('00000000000000000000' + [yourvarchar], 20) ASC
                ELSE LTRIM(RTRIM([yourvarchar]))
           END ASC

now numbers first get padded with '0'-chars (of course, the length 20 could be enhanced) - which sorts numbers right - and alphas only get trimmed

LINQ: "contains" and a Lambda query

The Linq extension method Any could work for you...

buildingStatus.Any(item => item.GetCharValue() == v.Status)

What is the default database path for MongoDB?

I depends on the version and the distro.

For example the default download pre-2.2 from the MongoDB site uses: /data/db but the Ubuntu install at one point used to use: var/lib/mongodb.

I think these have been standardised now so that 2.2+ will only use data/db whether it comes from direct download on the site or from the repos.

How to limit the number of selected checkboxes?

Using change event you can do something like this:

var limit = 3;
$('input.single-checkbox').on('change', function(evt) {
   if($(this).siblings(':checked').length >= limit) {
       this.checked = false;
   }
});

See this working demo

Python can't find module in the same folder

Your code is fine, I suspect your problem is how you are launching it.

You need to launch python from your '2014_07_13_test' directory.

Open up a command prompt and 'cd' into your '2014_07_13_test' directory.

For instance:

$ cd /path/to/2014_07_13_test
$ python test.py

If you cannot 'cd' into the directory like this you can add it to sys.path

In test.py:

import sys, os
sys.path.append('/path/to/2014_07_13_test')

Or set/edit the PYTHONPATH

And all should be well...

...well there is a slight mistake with your 'shebang' lines (the first line in both your files), there shouldn't be a space between the '#' and the '!'

There is a better shebang you should use.

Also you don't need the shebang line on every file... only the ones you intend to run from your shell as executable files.

Can you find all classes in a package using reflection?

Here's how I do it. I scan all the subfolders (sub-packages) and I don't try to load anonymous classes:

   /**
   * Attempts to list all the classes in the specified package as determined
   * by the context class loader, recursively, avoiding anonymous classes
   * 
   * @param pckgname
   *            the package name to search
   * @return a list of classes that exist within that package
   * @throws ClassNotFoundException
   *             if something went wrong
   */
  private static List<Class> getClassesForPackage(String pckgname) throws ClassNotFoundException {
      // This will hold a list of directories matching the pckgname. There may be more than one if a package is split over multiple jars/paths
      ArrayList<File> directories = new ArrayList<File>();
      String packageToPath = pckgname.replace('.', '/');
      try {
          ClassLoader cld = Thread.currentThread().getContextClassLoader();
          if (cld == null) {
              throw new ClassNotFoundException("Can't get class loader.");
          }

          // Ask for all resources for the packageToPath
          Enumeration<URL> resources = cld.getResources(packageToPath);
          while (resources.hasMoreElements()) {
              directories.add(new File(URLDecoder.decode(resources.nextElement().getPath(), "UTF-8")));
          }
      } catch (NullPointerException x) {
          throw new ClassNotFoundException(pckgname + " does not appear to be a valid package (Null pointer exception)");
      } catch (UnsupportedEncodingException encex) {
          throw new ClassNotFoundException(pckgname + " does not appear to be a valid package (Unsupported encoding)");
      } catch (IOException ioex) {
          throw new ClassNotFoundException("IOException was thrown when trying to get all resources for " + pckgname);
      }

      ArrayList<Class> classes = new ArrayList<Class>();
      // For every directoryFile identified capture all the .class files
      while (!directories.isEmpty()){
          File directoryFile  = directories.remove(0);             
          if (directoryFile.exists()) {
              // Get the list of the files contained in the package
              File[] files = directoryFile.listFiles();

              for (File file : files) {
                  // we are only interested in .class files
                  if ((file.getName().endsWith(".class")) && (!file.getName().contains("$"))) {
                      // removes the .class extension
                      int index = directoryFile.getPath().indexOf(packageToPath);
                      String packagePrefix = directoryFile.getPath().substring(index).replace('/', '.');;                          
                    try {                  
                      String className = packagePrefix + '.' + file.getName().substring(0, file.getName().length() - 6);                            
                      classes.add(Class.forName(className));                                
                    } catch (NoClassDefFoundError e)
                    {
                      // do nothing. this class hasn't been found by the loader, and we don't care.
                    }
                  } else if (file.isDirectory()){ // If we got to a subdirectory
                      directories.add(new File(file.getPath()));                          
                  }
              }
          } else {
              throw new ClassNotFoundException(pckgname + " (" + directoryFile.getPath() + ") does not appear to be a valid package");
          }
      }
      return classes;
  }  

How can labels/legends be added for all chart types in chart.js (chartjs.org)?

You can include a legend template in the chart options:

//legendTemplate takes a template as a string, you can populate the template with values from your dataset 
var options = {
  legendTemplate : '<ul>'
                  +'<% for (var i=0; i<datasets.length; i++) { %>'
                    +'<li>'
                    +'<span style=\"background-color:<%=datasets[i].lineColor%>\"></span>'
                    +'<% if (datasets[i].label) { %><%= datasets[i].label %><% } %>'
                  +'</li>'
                +'<% } %>'
              +'</ul>'
  }

  //don't forget to pass options in when creating new Chart
  var lineChart = new Chart(element).Line(data, options);

  //then you just need to generate the legend
  var legend = lineChart.generateLegend();

  //and append it to your page somewhere
  $('#chart').append(legend);

You'll also need to add some basic css to get it looking ok.

How to have git log show filenames like svn log -v

For full path names of changed files:

git log --name-only

For full path names and status of changed files:

git log --name-status

For abbreviated pathnames and a diffstat of changed files:

git log --stat

There's a lot more options, check out the docs.

jQuery see if any or no checkboxes are selected

Without using 'length' you can do it like this:

if ($('input[type=checkbox]').is(":checked")) {
      //any one is checked
}
else {
//none is checked
}

Interesting 'takes exactly 1 argument (2 given)' Python error

Summary (Some examples of how to define methods in classes in python)

#!/usr/bin/env python   # (if running from bash)

class Class1(object):

    def A(self, arg1):
        print arg1
        # this method requires an instance of Class1   
        # can access self.variable_name, and other methods in Class1

    @classmethod
    def B(cls, arg1):
        cls.C(arg1)
        # can access methods B and C in Class1 

    @staticmethod
    def C(arg1):
        print arg1
        # can access methods B and C in Class1 
        # (i.e. via Class1.B(...) and Class1.C(...))

Example

my_obj=Class1()

my_obj.A("1")
# Class1.A("2") # TypeError: method A() must be called with Class1 instance

my_obj.B("3")
Class1.B("4")
my_obj.C("5")
Class1.C("6")`

Restore DB — Error RESTORE HEADERONLY is terminating abnormally.

My guess is that you are trying to restore in lower versions which wont work

Using "super" in C++

I use this from time to time. Just when I find myself typing out the base class type a couple of times, I'll replace it with a typedef similar to yours.

I think it can be a good use. As you say, if your base class is a template it can save typing. Also, template classes may take arguments that act as policies for how the template should work. You're free to change the base type without having to fix up all your references to it as long as the interface of the base remains compatible.

I think the use through the typedef is enough already. I can't see how it would be built into the language anyway because multiple inheritence means there can be many base classes, so you can typedef it as you see fit for the class you logically feel is the most important base class.

Can constructors throw exceptions in Java?

Absolutely.

If the constructor doesn't receive valid input, or can't construct the object in a valid manner, it has no other option but to throw an exception and alert its caller.

Equivalent of shell 'cd' command to change the working directory?

cd() is easy to write using a generator and a decorator.

from contextlib import contextmanager
import os

@contextmanager
def cd(newdir):
    prevdir = os.getcwd()
    os.chdir(os.path.expanduser(newdir))
    try:
        yield
    finally:
        os.chdir(prevdir)

Then, the directory is reverted even after an exception is thrown:

os.chdir('/home')

with cd('/tmp'):
    # ...
    raise Exception("There's no place like /home.")
# Directory is now back to '/home'.

Error ITMS-90717: "Invalid App Store Icon"

I tried several of the things mentioned in this post (besides swapping to a .jpg) with no success. I solved it by opening the file in photoshop and using 'export to web'. Within that process/window is a checkbox for transparency.

Unable to find valid certification path to requested target - error even after cert imported

I am working on a tutorial for REST web services at www.udemy.com (REST Java Web Services). The example in the tutorial said that in order to have SSL, we must have a folder called "trust_store" in my eclipse "client" project that should contain a "key store" file (we had a "client" project to call the service, and "service" project that contained the REST web service - 2 projects in the same eclipse workspace, one the client, the other the service). To keep things simple, they said to copy "keystore.jks" from the glassfish app server (glassfish\domains\domain1\config\keystore.jks) we are using and put it into this "trust_store" folder that they had me make in the client project. That seems to make sense: the self-signed certs in the server's key_store would correspond to the certs in the client trust_store. Now, doing this, I was getting the error that the original post mentions. I have googled this and read that the error is due to the "keystore.jks" file on the client not containing a trusted/signed certificate, that the certificate it finds is self-signed.

To keep things clear, let me say that as I understand it, the "keystore.jks" contains self-signed certs, and the "cacerts.jks" file contains CA certs (signed by the CA). The "keystore.jks" is the "keystore" and the "cacerts.jks" is the "trust store". As "Bruno", a commenter, says above, "keystore.jks" is local, and "cacerts.jks" is for remote clients.

So, I said to myself, hey, glassfish also has the "cacerts.jks" file, which is glassfish's trust_store file. cacerts.jsk is supposed to contain CA certificates. And apparently I need my trust_store folder to contain a key store file that has at least one CA certificate. So, I tried putting the "cacerts.jks" file in the "trust_store" folder I had made, on my client project, and changing the VM properties to point to "cacerts.jks" instead of "keystore.jks". That got rid of the error. I guess all it needed was a CA cert to work.

This may not be ideal for production, or even for development beyond just getting something to work. For instance you could probably use "keytool" command to add CA certs to the "keystore.jks" file in the client. But anyway hopefully this at least narrows down the possible scenarios that could be going on here to cause the error.

ALSO: my approach seemed to be useful for the client (server cert added to client trust_store), it looks like the comments above to resolve the original post are useful for the server (client cert added to server trust_store). Cheers.

Eclipse project setup:

  • MyClientProject
  • src
  • test
  • JRE System Library
  • ...
  • trust_store
    ---cacerts.jks ---keystore.jks

Snippet from MyClientProject.java file:

static {
  // Setup the trustStore location and password
  System.setProperty("javax.net.ssl.trustStore","trust_store/cacerts.jks");
  // comment out below line
  System.setProperty("javax.net.ssl.trustStore","trust_store/keystore.jks");
  System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
  //System.setProperty("javax.net.debug", "all");

  // for localhost testing only
  javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
        public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
          return hostname.equals("localhost");
        }

  });
}

Vertically align an image inside a div with responsive height

Use this css, as you already have the markup for it:

.img-container {
    position: absolute;
    top: 50%;
    left: 50%;
}

.img-container > img {
  margin-top:-50%;
  margin-left:-50%;  
}

Here is a working JsBin: http://jsbin.com/ihilUnI/1/edit

This solution only works for square images (because a percentage margin-top value depends on the width of the container, not the height). For random-size images, you can do the following:

.img-container {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%); /* add browser-prefixes */
}

Working JsBin solution: http://jsbin.com/ihilUnI/2/edit

Should I use PATCH or PUT in my REST API?

I would generally prefer something a bit simpler, like activate/deactivate sub-resource (linked by a Link header with rel=service).

POST /groups/api/v1/groups/{group id}/activate

or

POST /groups/api/v1/groups/{group id}/deactivate

For the consumer, this interface is dead-simple, and it follows REST principles without bogging you down in conceptualizing "activations" as individual resources.

Jasmine.js comparing arrays

You can compare an array like the below mentioned if the array has some values

it('should check if the array are equal', function() {
        var mockArr = [1, 2, 3];
        expect(mockArr ).toEqual([1, 2, 3]);
 });

But if the array that is returned from some function has more than 1 elements and all are zero then verify by using

expect(mockArray[0]).toBe(0);

Chrome net::ERR_INCOMPLETE_CHUNKED_ENCODING error

I was getting net::ERR_INCOMPLETE_CHUNKED_ENCODING, upon closer inspection of the server error logs I found that it was due to PHP script execution timeout.

Adding this line on top of PHP script solved it for me:

ini_set('max_execution_time', 300); //300 seconds = 5 minutes

Ref: Fatal error: Maximum execution time of 30 seconds exceeded

Javascript loading CSV file into an array

The original code works fine for reading and separating the csv file data but you need to change the data type from csv to text.

Call Jquery function

To call the function on click of some html element (control).

$('#controlID').click(myFunction);

You will need to ensure you bind the event when your html element is ready on which you binding the event. You can put the code in document.ready

$(document).ready(function(){
    $('#controlID').click(myFunction);
});

You can use anonymous function to bind the event to the html element.

$(document).ready(function(){
    $('#controlID').click(function(){
         $.messager.show({  
            title:'My Title',  
            msg:'The message content',  
            showType:'fade',  
            style:{  
                right:'',  
                bottom:''  
            }  
        });  
    });
});

If you want to bind click with many elements you can use class selector

$('.someclass').click(myFunction);

Edit based on comments by OP, If you want to call function under some condition

You can use if for conditional execution, for example,

if(a == 3)
     myFunction();

Windows batch script to move files

You can try this:

:backup move C:\FilesToBeBackedUp\*.* E:\BackupPlace\ timeout 36000 goto backup

If that doesn't work try to replace "timeout" with sleep. Ik this post is over a year old, just helping anyone with the same problem.

Autocompletion of @author in Intellij

For Intellij IDEA Community 2019.1 you will need to follow these steps :

File -> New -> Edit File Templates.. -> Class -> /* Created by ${USER} on ${DATE} */

Alternative to file_get_contents?

If the file is local as your comment about SITE_PATH suggest, it's pretty simple just execute the script and cache the result in a variable using the output control functions :

function print_xml_data_file()
{
    include(XML_DATA_FILE_DIRECTORY . 'cms/data.php');
}

function get_xml_data()
{
    ob_start();
    print_xml_data_file();
    $xml_file = ob_get_contents();
    ob_end_clean();
    return $xml_file;
}

If it's remote as lot of others said curl is the way to go. If it isn't present try socket_create or fsockopen. If nothing work... change your hosting provider.

Various ways to remove local Git changes

Reason for adding an answer at this moment:

So far I was adding the conclusion and ‘answers’ to my initial question itself, making the question very lengthy, hence moving to separate answer.

I have also added more frequently used git commands that helps me on git, to help someone else too.

Basically to clean all local commits $ git reset --hard and $ git clean -d -f


First step before you do any commits is to configure your username and email that appears along with your commit.

#Sets the name you want attached to your commit transactions

$ git config --global user.name "[name]"

#Sets the email you want atached to your commit transactions

$ git config --global user.email "[email address]"

#List the global config

$ git config --list

#List the remote URL

$ git remote show origin

#check status

git status

#List all local and remote branches

git branch -a

#create a new local branch and start working on this branch

git checkout -b "branchname" 

or, it can be done as a two step process

create branch: git branch branchname work on this branch: git checkout branchname

#commit local changes [two step process:- Add the file to the index, that means adding to the staging area. Then commit the files that are present in this staging area]

git add <path to file>

git commit -m "commit message"

#checkout some other local branch

git checkout "local branch name"

#remove all changes in local branch [Suppose you made some changes in local branch like adding new file or modifying existing file, or making a local commit, but no longer need that] git clean -d -f and git reset --hard [clean all local changes made to the local branch except if local commit]

git stash -u also removes all changes

Note: It's clear that we can use either (1) combination of git clean –d –f and git reset --hard OR (2) git stash -u to achieve the desired result.

Note 1: Stashing, as the word means 'Store (something) safely and secretly in a specified place.' This can always be retreived using git stash pop. So choosing between the above two options is developer's call.

Note 2: git reset --hard will delete working directory changes. Be sure to stash any local changes you want to keep before running this command.

# Switch to the master branch and make sure you are up to date.

git checkout master

git fetch [this may be necessary (depending on your git config) to receive updates on origin/master ]

git pull

# Merge the feature branch into the master branch.

git merge feature_branch

# Reset the master branch to origin's state.

git reset origin/master

#Accidentally deleted a file from local , how to retrieve it back? Do a git status to get the complete filepath of the deleted resource

git checkout branchname <file path name>

that's it!

#Merge master branch with someotherbranch

git checkout master
git merge someotherbranchname

#rename local branch

git branch -m old-branch-name new-branch-name

#delete local branch

git branch -D branch-name

#delete remote branch

git push origin --delete branchname

or

git push origin :branch-name

#revert a commit already pushed to a remote repository

git revert hgytyz4567

#branch from a previous commit using GIT

git branch branchname <sha1-of-commit>

#Change commit message of the most recent commit that's already been pushed to remote

git commit --amend -m "new commit message"
git push --force origin <branch-name>

# Discarding all local commits on this branch [Removing local commits]

In order to discard all local commits on this branch, to make the local branch identical to the "upstream" of this branch, simply run

git reset --hard @{u}

Reference: http://sethrobertson.github.io/GitFixUm/fixup.html or do git reset --hard origin/master [if local branch is master]

# Revert a commit already pushed to a remote repository?

$ git revert ab12cd15

#Delete a previous commit from local branch and remote branch

Use-Case: You just commited a change to your local branch and immediately pushed to the remote branch, Suddenly realized , Oh no! I dont need this change. Now do what?

git reset --hard HEAD~1 [for deleting that commit from local branch. 1 denotes the ONE commit you made]

git push origin HEAD --force [both the commands must be executed. For deleting from remote branch]. Currently checked out branch will be referred as the branch where you are making this operation.

#Delete some of recent commits from local and remote repo and preserve to the commit that you want. ( a kind of reverting commits from local and remote)

Let's assume you have 3 commits that you've pushed to remote branch named 'develop'

commitid-1 done at 9am
commitid-2 done at 10am
commitid-3 done at 11am. // latest commit. HEAD is current here.

To revert to old commit ( to change the state of branch)

git log --oneline --decorate --graph // to see all your commitids

git clean -d -f // clean any local changes

git reset --hard commitid-1 // locally reverting to this commitid

git push -u origin +develop // push this state to remote. + to do force push

# Remove local git merge: Case: I am on master branch and merged master branch with a newly working branch phase2

$ git status

On branch master

$ git merge phase2 $ git status

On branch master

Your branch is ahead of 'origin/master' by 8 commits.

Q: How to get rid of this local git merge? Tried git reset --hard and git clean -d -f Both didn't work. The only thing that worked are any of the below ones:

$ git reset --hard origin/master

or

$ git reset --hard HEAD~8

or

$ git reset --hard 9a88396f51e2a068bb7 [sha commit code - this is the one that was present before all your merge commits happened]

#create gitignore file

touch .gitignore // create the file in mac or unix users

sample .gitignore contents:

.project
*.py
.settings

Reference link to GIT cheat sheet: https://services.github.com/on-demand/downloads/github-git-cheat-sheet.pdf

Python: Converting from ISO-8859-1/latin1 to UTF-8

Try decoding it first, then encoding:

apple.decode('iso-8859-1').encode('utf8')

When tracing out variables in the console, How to create a new line?

You should include it inside quotes '\n', See below,

console.log('roleName = '+roleName+ '\n' + 
             'role_ID = '+role_ID+  '\n' + 
             'modal_ID = '+modal_ID+ '\n' +  
             'related = '+related);

cancelling a handler.postdelayed process

Another way is to handle the Runnable itself:

Runnable r = new Runnable {
    public void run() {
        if (booleanCancelMember != false) {
            //do what you need
        }
    }
}

In Java, how do I convert a byte array to a string of hex digits while keeping leading zeros?

I found Integer.toHexString to be a little slow. If you are converting many bytes, you may want to consider building an array of Strings containing "00".."FF" and use the integer as the index. I.e.

hexString.append(hexArray[0xFF & messageDigest[i]]);

This is faster and ensures the correct length. Just requires the array of strings:

String[] hexArray = {
"00","01","02","03","04","05","06","07","08","09","0A","0B","0C","0D","0E","0F",
"10","11","12","13","14","15","16","17","18","19","1A","1B","1C","1D","1E","1F",
"20","21","22","23","24","25","26","27","28","29","2A","2B","2C","2D","2E","2F",
"30","31","32","33","34","35","36","37","38","39","3A","3B","3C","3D","3E","3F",
"40","41","42","43","44","45","46","47","48","49","4A","4B","4C","4D","4E","4F",
"50","51","52","53","54","55","56","57","58","59","5A","5B","5C","5D","5E","5F",
"60","61","62","63","64","65","66","67","68","69","6A","6B","6C","6D","6E","6F",
"70","71","72","73","74","75","76","77","78","79","7A","7B","7C","7D","7E","7F",
"80","81","82","83","84","85","86","87","88","89","8A","8B","8C","8D","8E","8F",
"90","91","92","93","94","95","96","97","98","99","9A","9B","9C","9D","9E","9F",
"A0","A1","A2","A3","A4","A5","A6","A7","A8","A9","AA","AB","AC","AD","AE","AF",
"B0","B1","B2","B3","B4","B5","B6","B7","B8","B9","BA","BB","BC","BD","BE","BF",
"C0","C1","C2","C3","C4","C5","C6","C7","C8","C9","CA","CB","CC","CD","CE","CF",
"D0","D1","D2","D3","D4","D5","D6","D7","D8","D9","DA","DB","DC","DD","DE","DF",
"E0","E1","E2","E3","E4","E5","E6","E7","E8","E9","EA","EB","EC","ED","EE","EF",
"F0","F1","F2","F3","F4","F5","F6","F7","F8","F9","FA","FB","FC","FD","FE","FF"};

How do I get row id of a row in sql server

There is a pseudocolumn called %%physloc%% that shows the physical address of the row.

See Equivalent of Oracle's RowID in SQL Server

Calculate difference in keys contained in two Python dictionaries

Here's a way that will work, allows for keys that evaluate to False, and still uses a generator expression to fall out early if possible. It's not exceptionally pretty though.

any(map(lambda x: True, (k for k in b if k not in a)))

EDIT:

THC4k posted a reply to my comment on another answer. Here's a better, prettier way to do the above:

any(True for k in b if k not in a)

Not sure how that never crossed my mind...

Find an object in SQL Server (cross-database)

SELECT NAME AS ObjectName
    ,schema_name(o.schema_id) AS SchemaName, OBJECT_NAME(o.parent_object_id) as TableName
    ,type
    ,o.type_desc
FROM sys.objects o
WHERE o.is_ms_shipped = 0
    AND o.NAME LIKE '%UniqueID%'
ORDER BY o.NAME

Can not get a simple bootstrap modal to work

I run into this issue too. I was including bootstrap.js AND bootstrap-modal.js. If you already have bootstrap.js, you don't need to include popover.

Why should Java 8's Optional not be used in arguments

The pattern with Optional is for one to avoid returning null. It's still perfectly possible to pass in null to a method.

While these aren't really official yet, you can use JSR-308 style annotations to indicate whether or not you accept null values into the function. Note that you'd have to have the right tooling to actually identify it, and it'd provide more of a static check than an enforceable runtime policy, but it would help.

public int calculateSomething(@NotNull final String p1, @NotNull final String p2) {}

How to use global variables in React Native?

You can use the global keyword to solve this.

Assume that you want to declare a variable called isFromManageUserAccount as a global variable you can use the following code.

global.isFromManageUserAccount=false;

After declaring like this you can use this variable anywhere in the application.

Import numpy on pycharm

It seems that each project may have a separate collection of python libraries in a project specific computing environment. To get this working with numpy I went to the terminal at the bottom of the pycharm window and ran pip install numpy and once the process finished running the install and indexing my python project was able to import numpy from the line of code import numpy as np. It seems you may need to do this for each project you setup in numpy.

TypeError: 'undefined' is not a function (evaluating '$(document)')

 ;(function($){
        // your code
    })(jQuery);

Place your js code inside the closure above , it should solve the problem.

Is there a WebSocket client implemented for Python?

Autobahn has a good websocket client implementation for Python as well as some good examples. I tested the following with a Tornado WebSocket server and it worked.

from twisted.internet import reactor
from autobahn.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS


class EchoClientProtocol(WebSocketClientProtocol):

   def sendHello(self):
      self.sendMessage("Hello, world!")

   def onOpen(self):
      self.sendHello()

   def onMessage(self, msg, binary):
      print "Got echo: " + msg
      reactor.callLater(1, self.sendHello)


if __name__ == '__main__':

   factory = WebSocketClientFactory("ws://localhost:9000")
   factory.protocol = EchoClientProtocol
   connectWS(factory)
   reactor.run()

Incrementing in C++ - When to use x++ or ++x?

From cppreference when incrementing iterators:

You should prefer pre-increment operator (++iter) to post-increment operator (iter++) if you are not going to use the old value. Post-increment is generally implemented as follows:

   Iter operator++(int)   {
     Iter tmp(*this); // store the old value in a temporary object
     ++*this;         // call pre-increment
     return tmp;      // return the old value   }

Obviously, it's less efficient than pre-increment.

Pre-increment does not generate the temporary object. This can make a significant difference if your object is expensive to create.

How to create a global variable?

if you want to use it in all of your classes you can use:

public var yourVariable = "something"

if you want to use just in one class you can use :

var yourVariable = "something"

How to read file from relative path in Java project? java.io.File cannot find the path specified

enter image description here

Assuming you want to read from resources directory in FileSystem class.

String file = "dummy.txt";
var path = Paths.get("src/com/company/fs/resources/", file);
System.out.println(path);

System.out.println(Files.readString(path));

Note: Leading . is not needed.

Sample database for exercise

Check out CodePlex for Microsoft SQL Server Community Projects & Samples

3rd party edit

On top of the link above you might look at

iconv - Detected an illegal character in input string

The illegal character is not in $matches[1], but in $xml

Try

iconv($matches[1], 'utf-8//TRANSLIT', $xml);

And showing us the input string would be nice for a better answer.

blur() vs. onblur()

I guess it's just because the onblur event is called as a result of the input losing focus, there isn't a blur action associated with an input, like there is a click action associated with a button

How to make audio autoplay on chrome

Use iframe instead:

<iframe id="stream" src="YOUTSOURCEAUDIOORVIDEOHERE" frameborder="0"></iframe>

How can I stop redis-server?

To stop redis server

sudo service redis-server stop

and check the status of it using

sudo service redis-server status

Importing variables from another file?

first.py:

a=5

second.py:

import first
print(first.a)

The result will be 5.

Checkbox angular material checked by default

Make sure you have this code on you component:

export class Component {
  checked = true;
}

How are zlib, gzip and zip related? What do they have in common and how are they different?

The most important difference is that gzip is only capable to compress a single file while zip compresses multiple files one by one and archives them into one single file afterwards. Thus, gzip comes along with tar most of the time (there are other possibilities, though). This comes along with some (dis)advantages.

If you have a big archive and you only need one single file out of it, you have to decompress the whole gzip file to get to that file. This is not required if you have a zip file.

On the other hand, if you compress 10 similiar or even identical files, the zip archive will be much bigger because each file is compressed individually, whereas in gzip in combination with tar a single file is compressed which is much more effective if the files are similiar (equal).

How to iterate through a DataTable

The above examples are quite helpful. But, if we want to check if a particular row is having a particular value or not. If yes then delete and break and in case of no value found straight throw error. Below code works:

foreach (DataRow row in dtData.Rows)
        {
            if (row["Column_name"].ToString() == txtBox.Text)
            {
                // Getting the sequence number from the textbox.
                string strName1 = txtRowDeletion.Text;

                // Creating the SqlCommand object to access the stored procedure
                // used to get the data for the grid.
                string strDeleteData = "Sp_name";
                SqlCommand cmdDeleteData = new SqlCommand(strDeleteData, conn);
                cmdDeleteData.CommandType = System.Data.CommandType.StoredProcedure;

                // Running the query.
                conn.Open();
                cmdDeleteData.ExecuteNonQuery();
                conn.Close();

                GetData();

                dtData = (DataTable)Session["GetData"];
                BindGrid(dtData);

                lblMsgForDeletion.Text = "The row successfully deleted !!" + txtRowDeletion.Text;
                txtRowDeletion.Text = "";
                break;
            }
            else
            {
                lblMsgForDeletion.Text = "The row is not present ";
            }
        }

Where to place and how to read configuration resource files in servlet based application?

It's your choice. There are basically three ways in a Java web application archive (WAR):


1. Put it in classpath

So that you can load it by ClassLoader#getResourceAsStream() with a classpath-relative path:

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("foo.properties");
// ...
Properties properties = new Properties();
properties.load(input);

Here foo.properties is supposed to be placed in one of the roots which are covered by the default classpath of a webapp, e.g. webapp's /WEB-INF/lib and /WEB-INF/classes, server's /lib, or JDK/JRE's /lib. If the propertiesfile is webapp-specific, best is to place it in /WEB-INF/classes. If you're developing a standard WAR project in an IDE, drop it in src folder (the project's source folder). If you're using a Maven project, drop it in /main/resources folder.

You can alternatively also put it somewhere outside the default classpath and add its path to the classpath of the appserver. In for example Tomcat you can configure it as shared.loader property of Tomcat/conf/catalina.properties.

If you have placed the foo.properties it in a Java package structure like com.example, then you need to load it as below

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("com/example/foo.properties");
// ...

Note that this path of a context class loader should not start with a /. Only when you're using a "relative" class loader such as SomeClass.class.getClassLoader(), then you indeed need to start it with a /.

ClassLoader classLoader = getClass().getClassLoader();
InputStream input = classLoader.getResourceAsStream("/com/example/foo.properties");
// ...

However, the visibility of the properties file depends then on the class loader in question. It's only visible to the same class loader as the one which loaded the class. So, if the class is loaded by e.g. server common classloader instead of webapp classloader, and the properties file is inside webapp itself, then it's invisible. The context class loader is your safest bet so you can place the properties file "everywhere" in the classpath and/or you intend to be able to override a server-provided one from the webapp on.


2. Put it in webcontent

So that you can load it by ServletContext#getResourceAsStream() with a webcontent-relative path:

InputStream input = getServletContext().getResourceAsStream("/WEB-INF/foo.properties");
// ...

Note that I have demonstrated to place the file in /WEB-INF folder, otherwise it would have been public accessible by any webbrowser. Also note that the ServletContext is in any HttpServlet class just accessible by the inherited GenericServlet#getServletContext() and in Filter by FilterConfig#getServletContext(). In case you're not in a servlet class, it's usually just injectable via @Inject.


3. Put it in local disk file system

So that you can load it the usual java.io way with an absolute local disk file system path:

InputStream input = new FileInputStream("/absolute/path/to/foo.properties");
// ...

Note the importance of using an absolute path. Relative local disk file system paths are an absolute no-go in a Java EE web application. See also the first "See also" link below.


Which to choose?

Just weigh the advantages/disadvantages in your own opinion of maintainability.

If the properties files are "static" and never needs to change during runtime, then you could keep them in the WAR.

If you prefer being able to edit properties files from outside the web application without the need to rebuild and redeploy the WAR every time, then put it in the classpath outside the project (if necessary add the directory to the classpath).

If you prefer being able to edit properties files programmatically from inside the web application using Properties#store() method, put it outside the web application. As the Properties#store() requires a Writer, you can't go around using a disk file system path. That path can in turn be passed to the web application as a VM argument or system property. As a precaution, never use getRealPath(). All changes in deploy folder will get lost on a redeploy for the simple reason that the changes are not reflected back in original WAR file.

See also:

Effective way to find any file's Encoding

.NET is not very helpful, but you can try the following algorithm:

  1. try to find the encoding by BOM(byte order mark) ... very likely not to be found
  2. try parsing into different encodings

Here is the call:

var encoding = FileHelper.GetEncoding(filePath);
if (encoding == null)
    throw new Exception("The file encoding is not supported. Please choose one of the following encodings: UTF8/UTF7/iso-8859-1");

Here is the code:

public class FileHelper
{
    /// <summary>
    /// Determines a text file's encoding by analyzing its byte order mark (BOM) and if not found try parsing into diferent encodings       
    /// Defaults to UTF8 when detection of the text file's endianness fails.
    /// </summary>
    /// <param name="filename">The text file to analyze.</param>
    /// <returns>The detected encoding or null.</returns>
    public static Encoding GetEncoding(string filename)
    {
        var encodingByBOM = GetEncodingByBOM(filename);
        if (encodingByBOM != null)
            return encodingByBOM;

        // BOM not found :(, so try to parse characters into several encodings
        var encodingByParsingUTF8 = GetEncodingByParsing(filename, Encoding.UTF8);
        if (encodingByParsingUTF8 != null)
            return encodingByParsingUTF8;

        var encodingByParsingLatin1 = GetEncodingByParsing(filename, Encoding.GetEncoding("iso-8859-1"));
        if (encodingByParsingLatin1 != null)
            return encodingByParsingLatin1;

        var encodingByParsingUTF7 = GetEncodingByParsing(filename, Encoding.UTF7);
        if (encodingByParsingUTF7 != null)
            return encodingByParsingUTF7;

        return null;   // no encoding found
    }

    /// <summary>
    /// Determines a text file's encoding by analyzing its byte order mark (BOM)  
    /// </summary>
    /// <param name="filename">The text file to analyze.</param>
    /// <returns>The detected encoding.</returns>
    private static Encoding GetEncodingByBOM(string filename)
    {
        // Read the BOM
        var byteOrderMark = new byte[4];
        using (var file = new FileStream(filename, FileMode.Open, FileAccess.Read))
        {
            file.Read(byteOrderMark, 0, 4);
        }

        // Analyze the BOM
        if (byteOrderMark[0] == 0x2b && byteOrderMark[1] == 0x2f && byteOrderMark[2] == 0x76) return Encoding.UTF7;
        if (byteOrderMark[0] == 0xef && byteOrderMark[1] == 0xbb && byteOrderMark[2] == 0xbf) return Encoding.UTF8;
        if (byteOrderMark[0] == 0xff && byteOrderMark[1] == 0xfe) return Encoding.Unicode; //UTF-16LE
        if (byteOrderMark[0] == 0xfe && byteOrderMark[1] == 0xff) return Encoding.BigEndianUnicode; //UTF-16BE
        if (byteOrderMark[0] == 0 && byteOrderMark[1] == 0 && byteOrderMark[2] == 0xfe && byteOrderMark[3] == 0xff) return Encoding.UTF32;

        return null;    // no BOM found
    }

    private static Encoding GetEncodingByParsing(string filename, Encoding encoding)
    {            
        var encodingVerifier = Encoding.GetEncoding(encoding.BodyName, new EncoderExceptionFallback(), new DecoderExceptionFallback());

        try
        {
            using (var textReader = new StreamReader(filename, encodingVerifier, detectEncodingFromByteOrderMarks: true))
            {
                while (!textReader.EndOfStream)
                {                        
                    textReader.ReadLine();   // in order to increment the stream position
                }

                // all text parsed ok
                return textReader.CurrentEncoding;
            }
        }
        catch (Exception ex) { }

        return null;    // 
    }
}

Casting objects in Java

Lets say you have Class A as superclass and Class B subclass of A.

public class A {

    public void printFromA(){
        System.out.println("Inside A");
    }
}
public class B extends A {

    public void printFromB(){
        System.out.println("Inside B");
    }

}

public class MainClass {

    public static void main(String []args){

        A a = new B();
        a.printFromA(); //this can be called without typecasting

        ((B)a).printFromB(); //the method printFromB needs to be typecast 
    }
}

JQuery $.ajax() post - data in a java servlet

You don't want a string, you really want a JS map of key value pairs. E.g., change:

 data: myDataVar.toString(),

with:

var myKeyVals = { A1984 : 1, A9873 : 5, A1674 : 2, A8724 : 1, A3574 : 3, A1165 : 5 }



var saveData = $.ajax({
      type: 'POST',
      url: "someaction.do?action=saveData",
      data: myKeyVals,
      dataType: "text",
      success: function(resultData) { alert("Save Complete") }
});
saveData.error(function() { alert("Something went wrong"); });

jQuery understands key value pairs like that, it does NOT understand a big string. It passes it simply as a string.

UPDATE: Code fixed.

Asp Net Web API 2.1 get client IP address

With Web API 2.2: Request.GetOwinContext().Request.RemoteIpAddress

How to convert binary string value to decimal

int num = Integer.parseInt("binaryString",2);

how to count the spaces in a java string?

If you use Java 8, the following should work:

long count = "0 1 2 3 4.".chars().filter(Character::isWhitespace).count();

This will also work in Java 8 using Eclipse Collections:

int count = Strings.asChars("0 1 2 3 4.").count(Character::isWhitespace);

Note: I am a committer for Eclipse Collections.

How to compile multiple java source files in command line

OR you could just use javac file1.java and then also use javac file2.java afterwards.

Submitting a multidimensional array via POST with php

you could submit all parameters with such naming:

params[0][topdiameter]
params[0][bottomdiameter]
params[1][topdiameter]
params[1][bottomdiameter]

then later you do something like this:

foreach ($_REQUEST['params'] as $item) {
    echo $item['topdiameter'];
    echo $item['bottomdiameter'];
}

Create a new RGB OpenCV image using Python?

The new cv2 interface for Python integrates numpy arrays into the OpenCV framework, which makes operations much simpler as they are represented with simple multidimensional arrays. For example, your question would be answered with:

import cv2  # Not actually necessary if you just want to create an image.
import numpy as np
blank_image = np.zeros((height,width,3), np.uint8)

This initialises an RGB-image that is just black. Now, for example, if you wanted to set the left half of the image to blue and the right half to green , you could do so easily:

blank_image[:,0:width//2] = (255,0,0)      # (B, G, R)
blank_image[:,width//2:width] = (0,255,0)

If you want to save yourself a lot of trouble in future, as well as having to ask questions such as this one, I would strongly recommend using the cv2 interface rather than the older cv one. I made the change recently and have never looked back. You can read more about cv2 at the OpenCV Change Logs.

Get a random boolean in python?

If you want to generate a number of random booleans you could use numpy's random module. From the documentation

np.random.randint(2, size=10)

will return 10 random uniform integers in the open interval [0,2). The size keyword specifies the number of values to generate.

How to detect control+click in Javascript from an onclick div attribute?

From above only , just edited so it works right away

<script>
    var control = false;
    $(document).on('keyup keydown', function (e) {
        control = e.ctrlKey;
    });

    $(function () {
        $('#1x').on('click', function () {
            if (control) {
                // control-click
                alert("Control+Click");
            } else {
                // single-click
                alert("Single Click");
            }
        });
    }); 

</script>
<p id="1x">Click me</p>

Disable browsers vertical and horizontal scrollbars

Try CSS.

If you want to remove Horizontal

overflow-x: hidden;

And if you want to remove Vertical

overflow-y: hidden;

How to get the path of current worksheet in VBA?

The quickest way

path = ThisWorkbook.Path & "\"

Regular Expression For Duplicate Words

Try this with below RE

  • \b start of word word boundary
  • \W+ any word character
  • \1 same word matched already
  • \b end of word
  • ()* Repeating again

    public static void main(String[] args) {
    
        String regex = "\\b(\\w+)(\\b\\W+\\b\\1\\b)*";//  "/* Write a RegEx matching repeated words here. */";
        Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE/* Insert the correct Pattern flag here.*/);
    
        Scanner in = new Scanner(System.in);
    
        int numSentences = Integer.parseInt(in.nextLine());
    
        while (numSentences-- > 0) {
            String input = in.nextLine();
    
            Matcher m = p.matcher(input);
    
            // Check for subsequences of input that match the compiled pattern
            while (m.find()) {
                input = input.replaceAll(m.group(0),m.group(1));
            }
    
            // Prints the modified sentence.
            System.out.println(input);
        }
    
        in.close();
    }
    

How should I use Outlook to send code snippets?

Years later I have a response.

  1. Use an online code highlighter like http://tohtml.com/ to highlight your code so you can paste marked up code from your IDE into Word. Depending on your IDE you may be able to skip this step.

  2. In Word 2010, go to insert->object->openDocument Text. Steps 2-3 are documented at How do you display code snippets in MS Word preserving format and syntax highlighting?.

  3. Paste your highlighted code into the object.

  4. Copy the whole object.

  5. Right-click-> paste special the object into Outlook.

This gives you a highlighted, contained box of code for use in emails in Outlook 2010.

OnItemCLickListener not working in listview

I had the same problem and tried all of the mentioned solutions to no avail. through testing i found that making the text selectable was preventing the listener to be called. So by switching it to false, or removing it my listener was called again.

android:textIsSelectable="false"

hope this helps someone who was stuck like me.

403 Forbidden error when making an ajax Post request in Django framework

I find all previous answers on-spot but let's put things in context.

The 403 forbidden response comes from the CSRF middleware (see Cross Site Request Forgery protection):

By default, a ‘403 Forbidden’ response is sent to the user if an incoming request fails the checks performed by CsrfViewMiddleware.

Many options are available. I would recommend to follow the answer of @fivef in order to make jQuery add the X-CSRFToken header before every AJAX request with $.ajaxSetup.

This answer requires the cookie jQuery plugin. If this is not desirable, another possibility is to add:

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');

BUT: if the setting CSRF_COOKIE_HTTPONLY is set to True, which often happens as the Security middleware recommends so, then the cookie is not there, even if @ensure_csrf_cookie() is used. In this case {% csrf_token %} must be provided in every form, which produces an output such as <input name="csrfmiddlewaretoken" value="cr6O9...FUXf6" type="hidden">. So the csrfToken variable would simply be obtained with:

var csrftoken = $('input[name="csrfmiddlewaretoken"]').val();

Again $.ajaxSetup would be required of course.

Other options which are available but not recommended are to disable the middleware or the csrf protection for the specific form with @csrf_exempt().

What does the "map" method do in Ruby?

It "maps" a function to each item in an Enumerable - in this case, a range. So it would call the block passed once for every integer from 0 to param_count (exclusive - you're right about the dots) and return an array containing each return value.

Here's the documentation for Enumerable#map. It also has an alias, collect.

Import a module from a relative path

Be sure that dirBar has the __init__.py file -- this makes a directory into a Python package.

Is there a workaround for ORA-01795: maximum number of expressions in a list is 1000 error?

There's also workaround doing disjunction of your array, worked for me as other solutions were hard to implement using some old framework.

select * from tableA where id = 1 or id = 2 or id = 3 ...

But for better perfo, I would use Nikolai Nechai's solution with unions, if possible.

How to convert JSONObjects to JSONArray?

Something like this:

JSONObject songs= json.getJSONObject("songs");
Iterator x = songs.keys();
JSONArray jsonArray = new JSONArray();

while (x.hasNext()){
    String key = (String) x.next();
    jsonArray.put(songs.get(key));
}

Create an empty list in python with certain size

You cannot assign to a list like lst[i] = something, unless the list already is initialized with at least i+1 elements. You need to use append to add elements to the end of the list. lst.append(something).

(You could use the assignment notation if you were using a dictionary).

Creating an empty list:

>>> l = [None] * 10
>>> l
[None, None, None, None, None, None, None, None, None, None]

Assigning a value to an existing element of the above list:

>>> l[1] = 5
>>> l
[None, 5, None, None, None, None, None, None, None, None]

Keep in mind that something like l[15] = 5 would still fail, as our list has only 10 elements.

range(x) creates a list from [0, 1, 2, ... x-1]

# 2.X only. Use list(range(10)) in 3.X.
>>> l = range(10)
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Using a function to create a list:

>>> def display():
...     s1 = []
...     for i in range(9): # This is just to tell you how to create a list.
...         s1.append(i)
...     return s1
... 
>>> print display()
[0, 1, 2, 3, 4, 5, 6, 7, 8]

List comprehension (Using the squares because for range you don't need to do all this, you can just return range(0,9) ):

>>> def display():
...     return [x**2 for x in range(9)]
... 
>>> print display()
[0, 1, 4, 9, 16, 25, 36, 49, 64]

Get ID of element that called a function

I know you don't want a jQuery solution but including javascript inside HTML is a big no no.

I mean you can do it but there are lots of reasons why you shouldn't (read up on unobtrusive javascript if you want the details).

So in the interest of other people who may see this question, here is the jQuery solution:

$(document).ready(function() {
  $('area').mouseover(function(event) {
    $('#preview').attr('src', 'images/' + $(event.srcElement).attr('id'));
  });
});

The major benefit is you don't mix javascript code with HTML. Further more, you only need to write this once and it will work for all tags as opposed to having to specify the handler for each separately.

Additional benefit is that every jQuery handler receives an event object that contains a lot of useful data - such as the source of the event, type of the event and so on making it much easier to write the kind of code you are after.

Finally since it's jQuery you don't need to think about cross-browser stuff - a major benefit especially when dealing with events.

What is the difference between declarations, providers, and import in NgModule?

Angular @NgModule constructs:

  1. import { x } from 'y';: This is standard typescript syntax (ES2015/ES6 module syntax) for importing code from other files. This is not Angular specific. Also this is technically not part of the module, it is just necessary to get the needed code within scope of this file.
  2. imports: [FormsModule]: You import other modules in here. For example we import FormsModule in the example below. Now we can use the functionality which the FormsModule has to offer throughout this module.
  3. declarations: [OnlineHeaderComponent, ReCaptcha2Directive]: You put your components, directives, and pipes here. Once declared here you now can use them throughout the whole module. For example we can now use the OnlineHeaderComponent in the AppComponent view (html file). Angular knows where to find this OnlineHeaderComponent because it is declared in the @NgModule.
  4. providers: [RegisterService]: Here our services of this specific module are defined. You can use the services in your components by injecting with dependency injection.

Example module:

// Angular
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

// Components
import { AppComponent } from './app.component';
import { OfflineHeaderComponent } from './offline/offline-header/offline-header.component';
import { OnlineHeaderComponent } from './online/online-header/online-header.component';

// Services
import { RegisterService } from './services/register.service';

// Directives
import { ReCaptcha2Directive } from './directives/re-captcha2.directive';

@NgModule({
  declarations: [
    OfflineHeaderComponent,,
    OnlineHeaderComponent,
    ReCaptcha2Directive,
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
  ],
  providers: [
    RegisterService,
  ],
  entryComponents: [
    ChangePasswordComponent,
    TestamentComponent,
    FriendsListComponent,
    TravelConfirmComponent
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Xcode couldn't find any provisioning profiles matching

I am now able to successfully build. Not sure exactly which step "fixed" things, but this was the sequence:

  • Tried automatic signing again. No go, so reverted to manual.
  • After reverting, I had no Eligible Profiles, all were ineligible. Strange.
  • I created a new certificate and profile, imported both. This too was "ineligible".
  • Removed the iOS platform and re-added it. I had tried this previously without luck.
  • After doing this, Xcode on its own defaulted to automatic signing. And this worked! Success!

While I am not sure exactly which parts were necessary, I think the previous certificates were the problem. I hate Xcode :(

Thanks for help.

HTML form submit to PHP script

Here is what I find works

  1. Set a form name
  2. Use a default select option, for example...

    <option value="-1" selected>Please Select</option>

So that if the form is submitted, use of JavaScript to halt the submission process can be implemented and verified at the server too.

  1. Try to use HTML5 attributes now they are supported.

This input

<input type="submit">

should be

<input name="Submit" type="submit" value="Submit">

whenever I use a form that fails, it is a failure due to the difference in calling the button name submit and name as Submit.

You should also set your enctype attribute for your form as forms fail on my web host if it's not set.

Using Intent in an Android application to show another activity

Add this line to your AndroidManifest.xml:

<activity android:name=".OrderScreen" /> 

Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers

this error probably is occurred most of the time due to missing closing tag. and further you can the following dependency to resolve this issue while supporting legacy HTML formate.

as it your code charset="UTF-8"> here is no closing for meta tag.

<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>                                 
</dependency>

reCAPTCHA ERROR: Invalid domain for site key

I tried for almost 4 Hours with this and finally figuring it out with guidance from here, I thought I would share my solution with you.

Ok so my domain is an addon domain. I also got "ERROR for site owner: Invalid domain for site key" I had checked that everything was correct almost a thousand times and it looked right to me, until I thought of it in terms of a desktop shortcut.

Solution:

So for an addon domain make sure that the parent url is also in the list of domains i.e: [ADDON DOMAIN].[PARENT DOMAIN].com . The addon location will be the folder that you set on your host so when using addon domains ensure to name the root with something logical.

Hope this helps someone else and thanks for the suggestions people.

How to add one column into existing SQL Table

Its work perfectly

ALTER TABLE `products` ADD `LastUpdate` varchar(200) NULL;

But if you want more precise in table then you can try AFTER.

ALTER TABLE `products` ADD `LastUpdate` varchar(200) NULL AFTER `column_name`;

It will add LastUpdate column after specified column name (column_name).

How does collections.defaultdict work?

Well, defaultdict can also raise keyerror in the following case:

    from collections import defaultdict
    d = defaultdict()
    print(d[3]) #raises keyerror

Always remember to give argument to the defaultdict like defaultdict(int).

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

Late answer but this works:

/* applies to GIF and PNG images; avoids blurry edges */
img[src$=".gif"], img[src$=".png"] {
    image-rendering: -moz-crisp-edges;         /* Firefox */
    image-rendering:   -o-crisp-edges;         /* Opera */
    image-rendering: -webkit-optimize-contrast;/* Webkit (non-standard naming) */
    image-rendering: crisp-edges;
    -ms-interpolation-mode: nearest-neighbor;  /* IE (non-standard property) */
}

https://developer.mozilla.org/en/docs/Web/CSS/image-rendering

Here is another link as well which talks about browser support:

https://css-tricks.com/almanac/properties/i/image-rendering/

How to fix the Hibernate "object references an unsaved transient instance - save the transient instance before flushing" error

One other possible reason: in my case, I was attempting to save the child before saving the parent, on a brand new entity.

The code was something like this in a User.java model:

this.lastName = lastName;
this.isAdmin = isAdmin;
this.accountStatus = "Active";
this.setNewPassword(password);
this.timeJoin = new Date();
create();

The setNewPassword() method creates a PasswordHistory record and adds it to the history collection in User. Since the create() statement hadn't been executed yet for the parent, it was trying to save to a collection of an entity that hadn't yet been created. All I had to do to fix it was to move the setNewPassword() call after the call to create().

this.lastName = lastName;
this.isAdmin = isAdmin;
this.accountStatus = "Active";
this.timeJoin = new Date();
create();
this.setNewPassword(password);

Scale iFrame css width 100% like an image

@Anachronist is closest here, @Simone not far off. The caveat with percentage padding on an element is that it's based on its parent's width, so if different to your container, the proportions will be off.

The most reliable, simplest answer is:

_x000D_
_x000D_
body {_x000D_
  /* for demo */_x000D_
  background: lightgray;_x000D_
}_x000D_
.fixed-aspect-wrapper {_x000D_
  /* anything or nothing, it doesn't matter */_x000D_
  width: 60%;_x000D_
  /* only need if other rulesets give this padding */_x000D_
  padding: 0;_x000D_
}_x000D_
.fixed-aspect-padder {_x000D_
  height: 0;_x000D_
  /* last padding dimension is (100 * height / width) of item to be scaled */_x000D_
  padding: 0 0 56.25%;_x000D_
  position: relative;_x000D_
  /* only need next 2 rules if other rulesets change these */_x000D_
  margin: 0;_x000D_
  width: auto;_x000D_
}_x000D_
.whatever-needs-the-fixed-aspect {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  /* for demo */_x000D_
  border: 0;_x000D_
  background: white;_x000D_
}
_x000D_
<div class="fixed-aspect-wrapper">_x000D_
  <div class="fixed-aspect-padder">_x000D_
    <iframe class="whatever-needs-the-fixed-aspect" src="/"></iframe>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm

Just in case if this helps anybody.

Python version: 3.7.7 platform: Ubuntu 18.04.4 LTS

This came with default python version 3.6.9, however I had installed my own 3.7.7 version python on it (installed building it from source)

tkinter was not working even when the help('module') shows tkinter in the list.

The following steps worked for me:

  1. sudo apt-get install tk-dev.

rebuild the python: 1. Navigate to your python folder and run the checks:

cd Python-3.7.7
sudo ./configure --enable-optimizations
  1. Build using make command: sudo make -j 8 --- here 8 are the number of processors, check yours using nproc command.
  2. Installing using:

    sudo make altinstall
    

Don't use sudo make install, it will overwrite default 3.6.9 version, which might be messy later.

  1. Check tkinter now
    python3.7 -m tkinter
    

A windows box will pop up, your tkinter is ready now.

How to determine CPU and memory consumption from inside a process?

Mac OS X - CPU

Overall CPU usage:

From Retrieve system information on MacOS X? :

#include <mach/mach_init.h>
#include <mach/mach_error.h>
#include <mach/mach_host.h>
#include <mach/vm_map.h>

static unsigned long long _previousTotalTicks = 0;
static unsigned long long _previousIdleTicks = 0;

// Returns 1.0f for "CPU fully pinned", 0.0f for "CPU idle", or somewhere in between
// You'll need to call this at regular intervals, since it measures the load between
// the previous call and the current one.
float GetCPULoad()
{
   host_cpu_load_info_data_t cpuinfo;
   mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT;
   if (host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO, (host_info_t)&cpuinfo, &count) == KERN_SUCCESS)
   {
      unsigned long long totalTicks = 0;
      for(int i=0; i<CPU_STATE_MAX; i++) totalTicks += cpuinfo.cpu_ticks[i];
      return CalculateCPULoad(cpuinfo.cpu_ticks[CPU_STATE_IDLE], totalTicks);
   }
   else return -1.0f;
}

float CalculateCPULoad(unsigned long long idleTicks, unsigned long long totalTicks)
{
  unsigned long long totalTicksSinceLastTime = totalTicks-_previousTotalTicks;
  unsigned long long idleTicksSinceLastTime  = idleTicks-_previousIdleTicks;
  float ret = 1.0f-((totalTicksSinceLastTime > 0) ? ((float)idleTicksSinceLastTime)/totalTicksSinceLastTime : 0);
  _previousTotalTicks = totalTicks;
  _previousIdleTicks  = idleTicks;
  return ret;
}

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2

I was running into a similar error in pywikipediabot. The .decode method is a step in the right direction but for me it didn't work without adding 'ignore':

ignore_encoding = lambda s: s.decode('utf8', 'ignore')

Ignoring encoding errors can lead to data loss or produce incorrect output. But if you just want to get it done and the details aren't very important this can be a good way to move faster.

How do I get the HTML code of a web page in PHP?

include_once('simple_html_dom.php');
$url="http://stackoverflow.com/questions/ask";
$html = file_get_html($url);

You can get the whole HTML code as an array (parsed form) using this code Download the 'simple_html_dom.php' file here http://sourceforge.net/projects/simplehtmldom/files/simple_html_dom.php/download

Getting Cannot bind argument to parameter 'Path' because it is null error in powershell

  1. PM>Uninstall-Package EntityFramework -Force
  2. PM>Iinstall-Package EntityFramework -Pre -Version 6.0.0

I solve this problem with this code in NugetPackageConsole.and it works.The problem was in the version. i thikn it will help others.

Concatenating null strings in Java

The second line is transformed to the following code:

s = (new StringBuilder()).append((String)null).append("hello").toString();

The append methods can handle null arguments.

C# List of objects, how do I get the sum of a property

Another alternative:

myPlanetsList.Select(i => i.Moons).Sum();

StringBuilder vs String concatenation in toString() in Java

In most cases, you won't see an actual difference between the two approaches, but it's easy to construct a worst case scenario like this one:

public class Main
{
    public static void main(String[] args)
    {
        long now = System.currentTimeMillis();
        slow();
        System.out.println("slow elapsed " + (System.currentTimeMillis() - now) + " ms");

        now = System.currentTimeMillis();
        fast();
        System.out.println("fast elapsed " + (System.currentTimeMillis() - now) + " ms");
    }

    private static void fast()
    {
        StringBuilder s = new StringBuilder();
        for(int i=0;i<100000;i++)
            s.append("*");      
    }

    private static void slow()
    {
        String s = "";
        for(int i=0;i<100000;i++)
            s+="*";
    }
}

The output is:

slow elapsed 11741 ms
fast elapsed 7 ms

The problem is that to += append to a string reconstructs a new string, so it costs something linear to the length of your strings (sum of both).

So - to your question:

The second approach would be faster, but it's less readable and harder to maintain. As I said, in your specific case you would probably not see the difference.

Uncaught TypeError: undefined is not a function on loading jquery-min.js

Yes, i also I fixed it changing in the js libraries to the unminified.

For example, in the tag, change:

<script type="text/javascript" src="js/jquery.ui.core.min.js"></script>
<script type="text/javascript" src="js/jquery.ui.widget.min.js"></script>
<script type="text/javascript" src="js/jquery.ui.rcarousel.min.js"></script>

For:

<script type="text/javascript" src="js/jquery.ui.core.js"></script>
<script type="text/javascript" src="js/jquery.ui.widget.js"></script>
<script type="text/javascript" src="js/jquery.ui.rcarousel.js"></script>

Quiting the 'min' as unminified.

Thanks for the idea.

Optimal number of threads per core

Hope this makes sense, Check the CPU and Memory utilization and put some threshold value. If the threshold value is crossed,don't allow to create new thread else allow...

Plotting a python dict in order of key values

Simply pass the sorted items from the dictionary to the plot() function. concentration.items() returns a list of tuples where each tuple contains a key from the dictionary and its corresponding value.

You can take advantage of list unpacking (with *) to pass the sorted data directly to zip, and then again to pass it into plot():

import matplotlib.pyplot as plt

concentration = {
    0: 0.19849878712984576,
    5000: 0.093917341754771386,
    10000: 0.075060643507712022,
    20000: 0.06673074282575861,
    30000: 0.057119318961966224,
    50000: 0.046134834546203485,
    100000: 0.032495766396631424,
    200000: 0.018536317451599615,
    500000: 0.0059499290585381479}

plt.plot(*zip(*sorted(concentration.items())))
plt.show()

sorted() sorts tuples in the order of the tuple's items so you don't need to specify a key function because the tuples returned by dict.item() already begin with the key value.

Creating email templates with Django

There is an error in the example.... if you use it as written, the following error occurs:

< type 'exceptions.Exception' >: 'dict' object has no attribute 'render_context'

You will need to add the following import:

from django.template import Context

and change the dictionary to be:

d = Context({ 'username': username })

See http://docs.djangoproject.com/en/1.2/ref/templates/api/#rendering-a-context

In Python script, how do I set PYTHONPATH?

You don't set PYTHONPATH, you add entries to sys.path. It's a list of directories that should be searched for Python packages, so you can just append your directories to that list.

sys.path.append('/path/to/whatever')

In fact, sys.path is initialized by splitting the value of PYTHONPATH on the path separator character (: on Linux-like systems, ; on Windows).

You can also add directories using site.addsitedir, and that method will also take into account .pth files existing within the directories you pass. (That would not be the case with directories you specify in PYTHONPATH.)

Return multiple values to a method caller

No, you can't return multiple values from a function in C# (for versions lower than C# 7), at least not in the way you can do it in Python.

However, there are a couple alternatives:

You can return an array of type object with the multiple values you want in it.

private object[] DoSomething()
{
    return new [] { 'value1', 'value2', 3 };
}

You can use out parameters.

private string DoSomething(out string outparam1, out int outparam2)
{
    outparam1 = 'value2';
    outparam2 = 3;
    return 'value1';
}

Using Chrome, how to find to which events are bound to an element

findEventHandlers is a jquery plugin, the raw code is here: https://raw.githubusercontent.com/ruidfigueiredo/findHandlersJS/master/findEventHandlers.js

Steps

  1. Paste the raw code directely into chrome's console(note:must have jquery loaded already)

  2. Use the following function call: findEventHandlers(eventType, selector);
    to find the corresponding's selector specified element's eventType handler.

Example:

findEventHandlers("click", "#clickThis");

Then if any, the available event handler will show bellow, you need to expand to find the handler, right click the function and select show function definition

See: https://blinkingcaret.wordpress.com/2014/01/17/quickly-finding-and-debugging-jquery-event-handlers/

How do you change the character encoding of a postgres database?

Dumping a database with a specific encoding and try to restore it on another database with a different encoding could result in data corruption. Data encoding must be set BEFORE any data is inserted into the database.

Check this : When copying any other database, the encoding and locale settings cannot be changed from those of the source database, because that might result in corrupt data.

And this : Some locale categories must have their values fixed when the database is created. You can use different settings for different databases, but once a database is created, you cannot change them for that database anymore. LC_COLLATE and LC_CTYPE are these categories. They affect the sort order of indexes, so they must be kept fixed, or indexes on text columns would become corrupt. (But you can alleviate this restriction using collations, as discussed in Section 22.2.) The default values for these categories are determined when initdb is run, and those values are used when new databases are created, unless specified otherwise in the CREATE DATABASE command.


I would rather rebuild everything from the begining properly with a correct local encoding on your debian OS as explained here :

su root

Reconfigure your local settings :

dpkg-reconfigure locales

Choose your locale (like for instance for french in Switzerland : fr_CH.UTF8)

Uninstall and clean properly postgresql :

apt-get --purge remove postgresql\*
rm -r /etc/postgresql/
rm -r /etc/postgresql-common/
rm -r /var/lib/postgresql/
userdel -r postgres
groupdel postgres

Re-install postgresql :

aptitude install postgresql-9.1 postgresql-contrib-9.1 postgresql-doc-9.1

Now any new database will be automatically be created with correct encoding, LC_TYPE (character classification), and LC_COLLATE (string sort order).

How to use ng-if to test if a variable is defined

I edited your plunker to include ABOS's solution.

<body ng-controller="MainCtrl">
    <ul ng-repeat='item in items'>
      <li ng-if='item.color'>The color is {{item.color}}</li>
      <li ng-if='item.shipping !== undefined'>The shipping cost is {{item.shipping}}</li>
    </ul>
  </body>

plunkerFork

process.waitFor() never returns

Asynchronous reading of stream combined with avoiding Wait with a timeout will solve the problem.

You can find a page explaining this here http://simplebasics.net/.net/process-waitforexit-with-a-timeout-will-not-be-able-to-collect-the-output-message/

How to reposition Chrome Developer Tools

As of october 2014, Version 39.0.2171.27 beta (64-bit)

I needed to go in the Chrome Web Developper pan into "Settings" and uncheck Split panels vertically when docked to right

How to list only the file names that changed between two commits?

It seems that no one has mentioned the switch --stat:

$ git diff --stat HEAD~5 HEAD
 .../java/org/apache/calcite/rex/RexSimplify.java   | 50 +++++++++++++++++-----
 .../apache/calcite/sql/fun/SqlTrimFunction.java    |  2 +-
 .../apache/calcite/sql2rel/SqlToRelConverter.java  | 16 +++++++
 .../org/apache/calcite/util/SaffronProperties.java | 19 ++++----
 .../org/apache/calcite/test/RexProgramTest.java    | 24 +++++++++++
 .../apache/calcite/test/SqlToRelConverterTest.java |  8 ++++
 .../apache/calcite/test/SqlToRelConverterTest.xml  | 15 +++++++
 pom.xml                                            |  2 +-
 .../apache/calcite/adapter/spark/SparkRules.java   |  7 +--
 9 files changed, 117 insertions(+), 26 deletions(-)

There are also --numstat

$ git diff --numstat HEAD~5 HEAD
40      10      core/src/main/java/org/apache/calcite/rex/RexSimplify.java
1       1       core/src/main/java/org/apache/calcite/sql/fun/SqlTrimFunction.java
16      0       core/src/main/java/org/apache/calcite/sql2rel/SqlToRelConverter.java
8       11      core/src/main/java/org/apache/calcite/util/SaffronProperties.java
24      0       core/src/test/java/org/apache/calcite/test/RexProgramTest.java
8       0       core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java
15      0       core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml
1       1       pom.xml
4       3       spark/src/main/java/org/apache/calcite/adapter/spark/SparkRules.java

and --shortstat

$ git diff --shortstat HEAD~5 HEAD
9 files changed, 117 insertions(+), 26 deletions(-)

What is so bad about singletons?

A singleton gets implemented using a static method. Static methods are avoided by people who do unit testing because they cannot be mocked or stubbed. Most people on this site are big proponents of unit testing. The generally most accepted convention to avoid them is using the inversion of control pattern.