Programs & Examples On #Tlbexp

Using setattr() in python

I'm here in general only to find out that through dict it is necessary to work inside setattr XD

java.lang.IllegalArgumentException: No converter found for return value of type

Faced same error recently - the pojo had getters/setters and all jackson dependencies were imported in pom correctly but some how "< scope > " was "provided" for jackson dependency and this caused the issue. Removing " < Scope > " from jackson dependency fixed the issue

Python: Find a substring in a string and returning the index of the substring

late to the party, was searching for same, as "in" is not valid, I had just created following.

def find_str(full, sub):
    index = 0
    sub_index = 0
    position = -1
    for ch_i,ch_f in enumerate(full) :
        if ch_f.lower() != sub[sub_index].lower():
            position = -1
            sub_index = 0
        if ch_f.lower() == sub[sub_index].lower():
            if sub_index == 0 :
                position = ch_i

            if (len(sub) - 1) <= sub_index :
                break
            else:
                sub_index += 1

    return position

print(find_str("Happy birthday", "py"))
print(find_str("Happy birthday", "rth"))
print(find_str("Happy birthday", "rh"))

which produces

3
8
-1

remove lower() in case case insensitive find not needed.

print highest value in dict with key

just :

 mydict = {'A':4,'B':10,'C':0,'D':87}
 max(mydict.items(), key=lambda x: x[1])

How to configure "Shorten command line" method for whole project in IntelliJ

Inside your .idea folder, change workspace.xml file

Add

<property name="dynamic.classpath" value="true" />

to

  <component name="PropertiesComponent">
.
.
.
  </component>

Example

 <component name="PropertiesComponent">
    <property name="project.structure.last.edited" value="Project" />
    <property name="project.structure.proportion" value="0.0" />
    <property name="project.structure.side.proportion" value="0.0" />
    <property name="settings.editor.selected.configurable" value="preferences.pluginManager" />
    <property name="dynamic.classpath" value="true" />
  </component>

If you don't see one, feel free to add it yourself

 <component name="PropertiesComponent">
    <property name="dynamic.classpath" value="true" />
  </component>

Creating a REST API using PHP

Trying to write a REST API from scratch is not a simple task. There are many issues to factor and you will need to write a lot of code to process requests and data coming from the caller, authentication, retrieval of data and sending back responses.

Your best bet is to use a framework that already has this functionality ready and tested for you.

Some suggestions are:

Phalcon - REST API building - Easy to use all in one framework with huge performance

Apigility - A one size fits all API handling framework by Zend Technologies

Laravel API Building Tutorial

and many more. Simple searches on Bitbucket/Github will give you a lot of resources to start with.

How to uninstall downloaded Xcode simulator?

NOTE: This will only remove a device configuration from the Xcode devices list. To remove the simulator files from your hard drive see the previous answer.

For Xcode 7 just use Window \ Devices menu in Xcode:

Devices menu

Then select emulator to delete in the list on the left side and right click on it. Here is Delete option: enter image description here

That's all.

How to programmatically move, copy and delete files and directories on SD?

Xamarin Android

public static bool MoveFile(string CurrentFilePath, string NewFilePath)
{
    try
    {
        using (var f = new File(CurrentFilePath))
        using (var i = new FileInputStream(f))
        using (var o = new FileOutputStream(NewFilePath))
        {
            i.Channel.TransferTo(0, i.Channel.Size(), o.Channel);
            f.Delete();
        }

        return true;
    }
    catch { return false; }
}

public static bool CopyFile(string CurrentFilePath, string NewFilePath)
{
    try
    {
        using (var i = new FileInputStream(CurrentFilePath))
        using (var o = new FileOutputStream(NewFilePath))
            i.Channel.TransferTo(0, i.Channel.Size(), o.Channel);

        return true;
    }
    catch { return false; }
}

public static bool DeleteFile(string FilePath)
{
    try
    {
        using (var file = new File(FilePath))
            file.Delete();

        return true;
    }
    catch { return false; }
}

Import SQL file into mysql

Ok so, I'm using Linux but I think this holds true for Windows too. You can do this either directly from the command prompt

> mysql -u <user name> -p<password> <database name> < sqlfilename.sql

Or from within the mysql prompt, you can use:

mysql>source sqlfilename.sql

But both these approaches have their own benefits in the results they display. In the first approach, the script exits as soon as it encounters an error. And the better part, is that it tells you the exact line number in the source file where the error occurred. However, it ONLY displays errors. If it didn't encounter any errors, the scripts displays NOTHING. Which can be a little unnerving. Because you're most often running a script with a whole pile of commands.

Now second approach (from within the mysql prompt) has the benefit that it displays a message for every different MySQL command in the script. If it encounters errors, it displays the mysql error message but continues on through the scripts. This can be good, because you can then go back and fix all the errors before you run the script again. The downside is that it does NOT display the line numbers in the script where the errors were encountered. This can be a bit of a pain. But the error messages are as descriptive so you could probably figure out where the problem is.

I, for one, prefer the directly-from-OS-command line approach.

How to convert base64 string to image?

You can try using open-cv to save the file since it helps with image type conversions internally. The sample code:

import cv2
import numpy as np

def save(encoded_data, filename):
    nparr = np.fromstring(encoded_data.decode('base64'), np.uint8)
    img = cv2.imdecode(nparr, cv2.IMREAD_ANYCOLOR)
    return cv2.imwrite(filename, img)

Then somewhere in your code you can use it like this:

save(base_64_string, 'testfile.png');
save(base_64_string, 'testfile.jpg');
save(base_64_string, 'testfile.bmp');

Scaling a System.Drawing.Bitmap to a given size while maintaining aspect ratio

The bitmap constructor has resizing built in.

Bitmap original = (Bitmap)Image.FromFile("DSC_0002.jpg");
Bitmap resized = new Bitmap(original,new Size(original.Width/4,original.Height/4));
resized.Save("DSC_0002_thumb.jpg");

http://msdn.microsoft.com/en-us/library/0wh0045z.aspx

If you want control over interpolation modes see this post.

Android: How to create a Dialog without a title?

I found Three Way to do this >

1) Using requestWindowFeature

Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(dialog.getWindow().FEATURE_NO_TITLE); 

2) Using style (style.xml)

<style name="FullHeightDialog" parent="android:style/Theme.Dialog">
   <item name="android:windowNoTitle">true</item>
</style>

Dialog dialog = new Dialog(context, R.style.FullHeightDialog);

3) Using XML theme in AndroidManifest.xml

 android:theme="@android:style/Theme.NoTitleBar"

How to check all versions of python installed on osx and centos

we can directly use this to see all the pythons installed both by current user and the root by the following: whereis python

IntelliJ Organize Imports

Under "Settings -> Editor -> General -> Auto Import" there are several options regarding automatic imports. Only unambiguous imports may be added automatically; this is one of the options.

Git merge master into feature branch

I add my answer, similar to others but maybe it will be the quickest one to read and implement.

NOTE: Rebase is not needed in this case.

Assume I have a repo1 and two branches master and dev-user.

dev-user is a branch done at a certain state of master.

Now assume that both dev-user and master advance.

At some point I want dev-user to get all the commits made in master.

How do I do it?

I go first in my repository root folder

cd name_of_the_repository

then

git checkout master 
git pull 
git checkout dev-user
git pull
git merge master 
git push 

I hope this helps someone else in the same situation.

How to get all child inputs of a div element (jQuery)

You need

var i = $("#panel input"); 

or, depending on what exactly you want (see below)

var i = $("#panel :input"); 

the > will restrict to children, you want all descendants.

EDIT: As Nick pointed out, there's a subtle difference between $("#panel input") and $("#panel :input).

The first one will only retrieve elements of type input, that is <input type="...">, but not <textarea>, <button> and <select> elements. Thanks Nick, didn't know this myself and corrected my post accordingly. Left both options, because I guess the OP wasn't aware of that either and -technically- asked for inputs... :-)

What are the differences between "=" and "<-" assignment operators in R?

x = y = 5 is equivalent to x = (y = 5), because the assignment operators "group" right to left, which works. Meaning: assign 5 to y, leaving the number 5; and then assign that 5 to x.

This is not the same as (x = y) = 5, which doesn't work! Meaning: assign the value of y to x, leaving the value of y; and then assign 5 to, umm..., what exactly?

When you mix the different kinds of assignment operators, <- binds tighter than =. So x = y <- 5 is interpreted as x = (y <- 5), which is the case that makes sense.

Unfortunately, x <- y = 5 is interpreted as (x <- y) = 5, which is the case that doesn't work!

See ?Syntax and ?assignOps for the precedence (binding) and grouping rules.

What is the role of "Flatten" in Keras?

Flatten make explicit how you serialize a multidimensional tensor (tipically the input one). This allows the mapping between the (flattened) input tensor and the first hidden layer. If the first hidden layer is "dense" each element of the (serialized) input tensor will be connected with each element of the hidden array. If you do not use Flatten, the way the input tensor is mapped onto the first hidden layer would be ambiguous.

Align div right in Bootstrap 3

Add offset8 to your class, for example:

<div class="offset8">aligns to the right</div>

Using ffmpeg to change framerate

You can use this command and the video duration is still unaltered.

ffmpeg -i input.mp4 -r 24 output.mp4

Connect Bluestacks to Android Studio

Steps to connect Blue Stack with Android Studio

  1. Close Android Studio.
  2. Go to adb.exe location (default location: %LocalAppData%\Android\sdk\platform-tools)
  3. Run adb connect localhost:5555 from this location.
  4. Start Android Studio and you will get Blue Stack as emulator when you run your app.

How do I configure modprobe to find my module?

I think the key is to copy the module to the standard paths.

Once that is done, modprobe only accepts the module name, so leave off the path and ".ko" extension.

Copying Code from Inspect Element in Google Chrome

Click on the line or element you want to copy. Copy to clipboard. Paste.

The only tricky thing is if you click on a line, you get everything that line includes if it was folded. For example if you click on a div, and copy, you get everything that the div includes.

You can also get only what you want by Right Clicking, and select 'Edit as HTML'. This will make that section essentially text, with none of the folding activated. You can then select, copy and paste the relevant bits.

VB.NET - If string contains "value1" or "value2"

Here is the alternative solution to check whether a particular string contains some predefined string. It uses IndexOf Function:

'this is your string
Dim strMyString As String = "aaSomethingbb"

'if your string contains these strings
Dim TargetString1 As String = "Something"
Dim TargetString2 As String = "Something2"

If strMyString.IndexOf(TargetString1) <> -1 Or strMyString.IndexOf(TargetString2) <> -1 Then

End If

NOTE: This solution has been tested with Visual Studio 2010.

How to redirect to a 404 in Rails?

routes.rb
  get '*unmatched_route', to: 'main#not_found'

main_controller.rb
  def not_found
    render :file => "#{Rails.root}/public/404.html", :status => 404, :layout => false
  end

Python, remove all non-alphabet chars from string

Use re.sub

import re

regex = re.compile('[^a-zA-Z]')
#First parameter is the replacement, second parameter is your input string
regex.sub('', 'ab3d*E')
#Out: 'abdE'

Alternatively, if you only want to remove a certain set of characters (as an apostrophe might be okay in your input...)

regex = re.compile('[,\.!?]') #etc.

jQuery first child of "this"

you can use DOM

$(this).children().first()
// is equivalent to
$(this.firstChild)

DateTime2 vs DateTime in SQL Server

Accepted answer is great, just know that if you are sending a DateTime2 to the frontend - it gets rounded to the normal DateTime equivalent.

This caused a problem for me because in a solution of mine I had to compare what was sent with what was on the database when resubmitted, and my simple comparison '==' didn't allow for rounding. So it had to be added.

The listener supports no services

for listener support no services you can use the following command to set local_listener paramter in your spfile use your listener port and server ip address

alter system set local_listener='(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=192.168.1.101)(PORT=1520)))' sid='testdb' scope=spfile;

How do I display images from Google Drive on a website?

List View

<iframe src="https://drive.google.com/embeddedfolderview?id=YOURID#list" width="700" height="500" frameborder="0"></iframe>

Grid View

<iframe src="https://drive.google.com/embeddedfolderview?id=YOURID#grid" width="700" height="500" frameborder="0"></iframe>

Read More at: https://thomas.vanhoutte.be/miniblog/embed-add-google-drive-folder-file-website/

How to write std::string to file?

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

Using global variables in a function

Python uses a simple heuristic to decide which scope it should load a variable from, between local and global. If a variable name appears on the left hand side of an assignment, but is not declared global, it is assumed to be local. If it does not appear on the left hand side of an assignment, it is assumed to be global.

>>> import dis
>>> def foo():
...     global bar
...     baz = 5
...     print bar
...     print baz
...     print quux
... 
>>> dis.disassemble(foo.func_code)
  3           0 LOAD_CONST               1 (5)
              3 STORE_FAST               0 (baz)

  4           6 LOAD_GLOBAL              0 (bar)
              9 PRINT_ITEM          
             10 PRINT_NEWLINE       

  5          11 LOAD_FAST                0 (baz)
             14 PRINT_ITEM          
             15 PRINT_NEWLINE       

  6          16 LOAD_GLOBAL              1 (quux)
             19 PRINT_ITEM          
             20 PRINT_NEWLINE       
             21 LOAD_CONST               0 (None)
             24 RETURN_VALUE        
>>> 

See how baz, which appears on the left side of an assignment in foo(), is the only LOAD_FAST variable.

Remove a symlink to a directory

Use rm symlinkname but do not include a forward slash at the end (do not use: rm symlinkname/). You will then be asked if you want to remove the symlink, y to answer yes.

Determine if an element has a CSS class with jQuery

Use the hasClass method:

jQueryCollection.hasClass(className);

or

$(selector).hasClass(className);

The argument is (obviously) a string representing the class you are checking, and it returns a boolean (so it doesn't support chaining like most jQuery methods).

Note: If you pass a className argument that contains whitespace, it will be matched literally against the collection's elements' className string. So if, for instance, you have an element,

<span class="foo bar" />

then this will return true:

$('span').hasClass('foo bar')

and these will return false:

$('span').hasClass('bar foo')
$('span').hasClass('foo  bar')

Getting PEAR to work on XAMPP (Apache/MySQL stack on Windows)

I fixed

avast deletes your server.php in your directory so disable the antivirus

check the (server.php) file on your laravel folder

server.php

_x000D_
_x000D_
<?php_x000D_
_x000D_
/**_x000D_
 * Laravel - A PHP Framework For Web Artisans_x000D_
 *_x000D_
 * @package  Laravel_x000D_
 * @author   Taylor Otwell <[email protected]>_x000D_
 */_x000D_
_x000D_
$uri = urldecode(_x000D_
    parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)_x000D_
);_x000D_
_x000D_
// This file allows us to emulate Apache's "mod_rewrite" functionality from the_x000D_
// built-in PHP web server. This provides a convenient way to test a Laravel_x000D_
// application without having installed a "real" web server software here._x000D_
if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) {_x000D_
    return false;_x000D_
}_x000D_
_x000D_
require_once __DIR__.'/public/index.php';
_x000D_
_x000D_
_x000D_

How to check if an object implements an interface?

In general for AnInterface and anInstance of any class:

AnInterface.class.isAssignableFrom(anInstance.getClass());

Strange Characters in database text: Ã, Ã, ¢, â‚ €,

I encountered today quite a similar problem : mysqldump dumped my utf-8 base encoding utf-8 diacritic characters as two latin1 characters, although the file itself is regular utf8.

For example : "é" was encoded as two characters "é". These two characters correspond to the utf8 two bytes encoding of the letter but it should be interpreted as a single character.

To solve the problem and correctly import the database on another server, I had to convert the file using the ftfy (stands for "Fixes Text For You). (https://github.com/LuminosoInsight/python-ftfy) python library. The library does exactly what I expect : transform bad encoded utf-8 to correctly encoded utf-8.

For example : This latin1 combination "é" is turned into an "é".

ftfy comes with a command line script but it transforms the file so it can not be imported back into mysql.

I wrote a python3 script to do the trick :

#!/usr/bin/python3
# coding: utf-8

import ftfy

# Set input_file
input_file = open('mysql.utf8.bad.dump', 'r', encoding="utf-8")
# Set output file
output_file = open ('mysql.utf8.good.dump', 'w')

# Create fixed output stream
stream = ftfy.fix_file(
    input_file,
    encoding=None,
    fix_entities='auto', 
    remove_terminal_escapes=False, 
    fix_encoding=True, 
    fix_latin_ligatures=False, 
    fix_character_width=False, 
    uncurl_quotes=False, 
    fix_line_breaks=False, 
    fix_surrogates=False, 
    remove_control_chars=False, 
    remove_bom=False, 
    normalization='NFC'
)

# Save stream to output file
stream_iterator = iter(stream)
while stream_iterator:
    try:
        line = next(stream_iterator)
        output_file.write(line)
    except StopIteration:
        break

Custom Drawable for ProgressBar/ProgressDialog

Your style should look like this:

<style parent="@android:style/Widget.ProgressBar" name="customProgressBar">
    <item name="android:indeterminateDrawable">@anim/mp3</item>
</style>

jQuery append and remove dynamic table row

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <script>`enter code here`
        $(document).ready(function () {
var result=1;
$('input').keyup(function(){`enter code here`
     $('tr').each(function () {
         var sum = $(this).find('td.combat').text();
         var combat = $(this).find('input.combat').val();
         if (!isNaN(sum) && sum.length !== 0 && !isNaN(combat) && combat.length !== 0) {
                 result = parseFloat(sum)*parseFloat(combat);
             }

         $(this).find('.total-combat').html(result);
        });
    });
 $('.add').click(function(){
        var sno = $(this).parent().siblings('.sno').text();
        var cust = $(this).parent().siblings('.cust').text();
        var price = $(this).parent().siblings('td.combat').text();
        var rowValue = [];
        $(this).closest('tr').find("input").each(function() {
                  rowValue.push($(this).val());
                  return $(this).val(); 
                 });

         var rowValue1 = [];
        $(this).closest('tr').find("span").each(function() {
                  rowValue1.push($(this).text());
                  return $(this).val(); 
                 });

                    var markup = "<tr><td class='sno'>" + sno + "</td><td class='custname'>" + cust +"</td><td class='price'>" + price +"</td><td><input type='text' class='newtext' value="+ rowValue[0] +"></td><td class='total'>" + rowValue1[0] +"</td><td><input type='submit' class='update' value='upd'><input type='button' class='del' value='del'></td></tr>";



        var rightcol = $(this).closest('tr').find(".cust");
        var row_count =  $('.tbl1 tbody tr').length;
        alert(row_count);

        if (row_count == 0) {


                        $(".tbl1 tbody").append(markup);


        }
        else
        {
            var tes=0;
            $('.tbl1 tbody tr').each(function(){
                        var leftcol = $(this).find(".custname");

                            if(rightcol.html() == leftcol.html()) {
                                alert(leftcol.html()+"-----------------"+rightcol.html());
                                $(this).find('.sno').text(sno);
                                $(this).find('.custname').text(cust);
                                $(this).find('.price').text(price);
                                $(this).find('.newtext').val(rowValue[0]);
                                $(this).find('.total').text(rowValue1[0]);
                                tes++;
                     }
            });
                if(tes==0){
                    $(".tbl1 tbody").append(markup);
                }    


        }

});
            $(".tb").on("click", ".update", function(e) {
                var rowValues = [];
                                    $(this).closest('tr').find("input").each(function() {
                                  rowValues.push($(this).val());
                                  return $(this).val(); 

                                 });
                    var total=$(this).closest('tr').find('.total').text();
                    var right_cols = $(this).closest('tr').find(".custname");

                $('.tbl tbody tr').each(function(){
                        var row = $(this);
                        var left_cols = $(this).find(".cust");
                            if(left_cols.html() == right_cols.html()) {

                                $(this).find('.text').val(rowValues[0]);
                                $(this).find('.total-combat').text(total);
                             }
                         });



        });         
                $(".tb").on("keyup", "input", function() {
                 $('tr').each(function () {
                     var sum = $(this).find('td.price').text();
                     var combat = $(this).find('input.newtext').val();
                     if (!isNaN(sum) && sum.length !== 0 && !isNaN(combat) && combat.length !== 0) {
                            result = parseFloat(sum)*parseFloat(combat);
                         }

                        $(this).find('.total').html(result);
                    });
                });
         $(".tb").on("click", ".del", function() {
                  $(this).closest('tr').remove();
              });
});


    </script>
<style>

    .table_style {
    width: 500px;
    margin: 0px auto;
    }
    table{
    width: 100%;
    border-collapse: collapse;
    }
    table tr td{
    width: 50%;
    border: 5px solid #ff751a;
    padding: 5px;
    }
    table tr th{
    border: 5px solid #79ff4d;
    padding: 5px;
    }
    input{
        width:35px;
    }
    .tbl1{
        margin-top: 50px;
        border: 0px solid #cdcdcd;
    }
    .btn{
        float:left;
    }
    </style>
        <title>E-Commerce-Table</title>
</head>
<body>

<div class="table_style">
    <caption>Price-List</caption>
<table class="tbl">
    <tr>
        <th>S.No</th>
        <th>P.Name</th>
        <th>Price</th>
        <th>Qnty</th>
        <th>Rate</th>   
        <th>action</th>
    </tr>
    <tbody>
    <tr>
        <td class="sno">1</td>
        <td class="cust">A</td>
        <td class="combat">5</td>
        <td class="tester"><input type="number" id="qnty1" name="Qnty" value="0" class="combat text"></td>
        <td><span class="total-combat"></span></td>
        <td><input type="submit" name="submit" value="Add" class="add"></td>
    </tr>
    <tr>
        <td class="sno">2</td>
        <td class="cust">B</td>
        <td class="combat">8</td>
        <td><input type="number" id="qnty2" name="Qnty" value="0" class="combat text"></td>
        <td><span class="total-combat"></span></td>
        <td><input type="submit" name="submit" value="Add" class="add"></td>
    </tr>
    <tr>
        <td class="sno">3</td>
        <td class="cust">C</td>
        <td class="combat">7</td>
        <td><input type="number" id="qnty3" name="Qnty" value="0" class="combat text"></td>
        <td><span class="total-combat"></span></td>
        <td><input type="submit" name="submit" value="Add" class="add"></td>
    </tr>
    <tr>
        <td class="sno">4</td>
        <td class="cust">D</td>
        <td class="combat">2</td>
        <td><input type="number" id="qnty4" name="Qnty" value="0" class="combat text"></td>
        <td><span class="total-combat"></span></td>
        <td><input type="submit" name="submit" value="Add" class="add"></td>
    </tr>
</tbody>

</table>

     <table class="tbl1">
        <thead>
            <tr>
                <th>S.No</th>
                <th>P.Name</th>
                <th>Price</th>
                <th>Qnty</th>
                <th>Rate</th>
                <th>action</th>
            </tr>
        </thead>
        <tbody class="tb">

        </tbody>
    </table>
    <button type="submit" name="addtocart" id="btn">Add-to-cart</button>
</div>

</body>
</html>

What is your favorite C programming trick?

Declaring array's of pointer to functions for implementing finite state machines.

int (* fsm[])(void) = { ... }

The most pleasing advantage is that it is simple to force each stimulus/state to check all code paths.

In an embedded system, I'll often map an ISR to point to such a table and revector it as needed (outside the ISR).

Declaring variables in Excel Cells

I also just found out how to do this with the Excel Name Manager (Formulas > Defined Names Section > Name Manager).

You can define a variable that doesn't have to "live" within a cell and then you can use it in formulas.

Excel Name Manager

nginx: how to create an alias url route?

server {
  server_name example.com;
  root /path/to/root;
  location / {
    # bla bla
  }
  location /demo {
    alias /path/to/root/production/folder/here;
  }
}

If you need to use try_files inside /demo you'll need to replace alias with a root and do a rewrite because of the bug explained here

How to tell if a file is git tracked (by shell exit code)?

I suggest a custom alias on you .gitconfig.

You have to way to do:

1) With git command:

git config --global alias.check-file <command>

2) Editing ~/.gitconfig and add this line on alias section:

[alias]
    check-file = "!f() { if [ $# -eq 0 ]; then echo 'Filename missing!'; else tracked=$(git ls-files ${1}); if [[ -z ${tracked} ]]; then echo 'File not tracked'; else echo 'File tracked'; fi; fi;  };  f"

Once launched command (1) or saved file (2), on your workspace you can test it:

$ git check-file
$ Filename missing 

$ git check-file README.md
$ File tracked 

$ git check-file foo
$ File not tracked

How to Set JPanel's Width and Height?

Board.setPreferredSize(new Dimension(x, y));
.
.
//Main.add(Board, BorderLayout.CENTER);
Main.add(Board, BorderLayout.CENTER);
Main.setLocations(x, y);
Main.pack();
Main.setVisible(true);

Git merge is not possible because I have unmerged files

It might be the Unmerged paths that cause

error: Merging is not possible because you have unmerged files.

If so, try:

git status

if it says

You have unmerged paths.

do as suggested: either resolve conflicts and then commit or abort the merge entirely with

git merge --abort

You might also see files listed under Unmerged paths, which you can resolve by doing

git rm <file>

Refresh DataGridView when updating data source

Well, it doesn't get much better than that. Officially, you should use

dataGridView1.DataSource = typeof(List); 
dataGridView1.DataSource = itemStates;

It's still a "clear/reset source" kind of solution, but I have yet to find anything else that would reliably refresh the DGV data source.

pip install - locale.Error: unsupported locale setting

Ubuntu:

$ sudo vi /etc/default/locale

Add below setting at the end of file.

LC_ALL = en_US.UTF-8

Git remote branch deleted, but still it appears in 'branch -a'

Try:

git remote prune origin

From the Git remote documentation:

prune

Deletes all stale remote-tracking branches under <name>. These stale branches have already been removed from the remote repository referenced by <name>, but are still locally available in "remotes/<name>".

With --dry-run option, report what branches will be pruned, but do not actually prune them.

Android: How to detect double-tap?

If you are using Kotlin then you can do it like this:

I spend a lot of time to convert this code to Kotlin hope it save someone's time

Create a gesture detector:

      val gestureDetector = GestureDetector(this, object : GestureDetector.SimpleOnGestureListener() {
            override fun onDoubleTap(e: MotionEvent): Boolean {

                Toast.makeText(this@DemoActivity,"Double Tap",Toast.LENGTH_LONG).show()

                //Show or hide Ip address on double tap
                toggleIPaddressVisibility()

                return true;
            }

            override fun onLongPress(e: MotionEvent) {
                super.onLongPress(e);

                //rotate frame on long press
                toggleFrameRotation()

                Toast.makeText(this@DemoActivity,"LongClick",Toast.LENGTH_LONG).show()
            }

            override fun onDoubleTapEvent(e: MotionEvent): Boolean {
                return true
            }

            override fun onDown(e: MotionEvent): Boolean {
                return true
            }
        })

Assign to any of your view:

        IPAddress.setOnTouchListener { v, event ->
          return@setOnTouchListener  gestureDetector.onTouchEvent(event)
        }

JPA: JOIN in JPQL

Join on one-to-many relation in JPQL looks as follows:

select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName 

When several properties are specified in select clause, result is returned as Object[]:

Object[] temp = (Object[]) em.createNamedQuery("...")
    .setParameter("groupName", groupName)
    .getSingleResult(); 
String fname = (String) temp[0];
String lname = (String) temp[1];

By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:

@Entity @Table(name = "Users")     
public class User implements Serializable { ... } 

What causes a java.lang.StackOverflowError

Stack Overflow exceptions can occur when a thread stack continues to grow in size until reaching the maximum limit.

Adjusting the Stack Sizes (Xss and Xmso) options...

I suggest you see this link: http://www-01.ibm.com/support/docview.wss?uid=swg21162896 There are many possible causes to a StackOverflowError, as you can see in the link....

TypeError: 'module' object is not callable

When configuring an console_scripts entrypoint in setup.py I found this issue existed when the endpoint was a module or package rather than a function within the module.

Traceback (most recent call last):
   File "/Users/ubuntu/.virtualenvs/virtualenv/bin/mycli", line 11, in <module>
load_entry_point('my-package', 'console_scripts', 'mycli')()
TypeError: 'module' object is not callable

For example

from setuptools import setup
setup (
# ...
    entry_points = {
        'console_scripts': [mycli=package.module.submodule]
    },
# ...
)

Should have been

from setuptools import setup
setup (
# ...
    entry_points = {
        'console_scripts': [mycli=package.module.submodule:main]
    },
# ...
)

So that it would refer to a callable function rather than the module itself. It seems to make no difference if the module has a if __name__ == '__main__': block. This will not make the module callable.

How to get the current time in milliseconds from C in Linux?

You have to do something like this:

struct timeval  tv;
gettimeofday(&tv, NULL);

double time_in_mill = 
         (tv.tv_sec) * 1000 + (tv.tv_usec) / 1000 ; // convert tv_sec & tv_usec to millisecond

How to get list of dates between two dates in mysql select query

Try:

select * from 
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'

-for date ranges up to nearly 300 years in the future.

[Corrected following a suggested edit by UrvishAtSynapse.]

Remove leading comma from a string

remove leading or trailing characters:

function trimLeadingTrailing(inputStr, toRemove) {
    // use a regex to match toRemove at the start (^)
    // and at the end ($) of inputStr
    const re = new Regex(`/^${toRemove}|{toRemove}$/`);
    return inputStr.replace(re, '');
}

How do I bind Twitter Bootstrap tooltips to dynamically created elements?

In Bootstrap 5, which doesn't use jQuery, you can do this:

_x000D_
_x000D_
const btn = document.createElement('button');
btn.innerHTML = 'Click me';
btn.dataset['toggle'] = 'tooltip';
btn.dataset['placement'] = 'top';
btn.title = 'Your Tooltip Here';
new bootstrap.Tooltip(btn);

document.getElementById('parent').appendChild(btn);
_x000D_
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-CuOF+2SnTUfTwSZjCXf01h7uYhfOBuxIhGKPbfEJ3+FqH/s6cIFN9bGr1HmAg4fQ" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-popRpmFF9JQgExhfw5tZT4I9/CI5e2QcuUZPOVXb1m7qUmeR2b50u+YFEYe1wgzy" crossorigin="anonymous"></script>
<div id="parent"></div>
_x000D_
_x000D_
_x000D_

How to try convert a string to a Guid

use code like this:

new Guid("9D2B0228-4D0D-4C23-8B49-01A698857709")

instead of "9D2B0228-4D0D-4C23-8B49-01A698857709" you can set your string value

"Repository does not have a release file" error

im use this code to and suggest you:

1) sudo sed -i -e 's|disco|eoan|g' /etc/apt/sources.list
2) sudo apt update

how to list all sub directories in a directory

show all directry and sub directories

def dir():

from glob import glob

dir = []

dir = glob("path")

def all_sub_dir(dir):
{

     for item in dir:

            {
                b = "{}\*".format(item)
                dir += glob(b)
            }
         print(dir)
}

How to use: while not in

anding strings does not do what you think it does - use any to check if any of the strings are in the list:

while not any(word in list_of_words for word in ['AND', 'OR', 'NOT']):
    print 'No boolean'

Also, if you want a simple check, an if might be better suited than a while...

Case insensitive access for generic dictionary

Its not very elegant but in case you cant change the creation of dictionary, and all you need is a dirty hack, how about this:

var item = MyDictionary.Where(x => x.Key.ToLower() == MyIndex.ToLower()).FirstOrDefault();
    if (item != null)
    {
        TheValue = item.Value;
    }

How to iterate through a list of objects in C++

You're close.

std::list<Student>::iterator it;
for (it = data.begin(); it != data.end(); ++it){
    std::cout << it->name;
}

Note that you can define it inside the for loop:

for (std::list<Student>::iterator it = data.begin(); it != data.end(); ++it){
    std::cout << it->name;
}

And if you are using C++11 then you can use a range-based for loop instead:

for (auto const& i : data) {
    std::cout << i.name;
}

Here auto automatically deduces the correct type. You could have written Student const& i instead.

How to print current date on python3?

I use this which is standard for every time

import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))

Best way to generate xml?

Use lxml.builder class, from: http://lxml.de/tutorial.html#the-e-factory

import lxml.builder as lb
from lxml import etree

nstext = "new story"
story = lb.E.Asset(
  lb.E.Attribute(nstext, name="Name", act="set"),
  lb.E.Relation(lb.E.Asset(idref="Scope:767"),
            name="Scope", act="set")
  )

print 'story:\n', etree.tostring(story, pretty_print=True)

Output:

story:
<Asset>
  <Attribute name="Name" act="set">new story</Attribute>
  <Relation name="Scope" act="set">
    <Asset idref="Scope:767"/>
  </Relation>
</Asset>

How can I perform a short delay in C# without using sleep?

You can probably use timers : http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx

Timers can provide you a precision up to 1 millisecond. Depending on the tick interval an event will be generated. Do your stuff inside the tick event.

Any way to make plot points in scatterplot more transparent in R?

Transparency can be coded in the color argument as well. It is just two more hex numbers coding a transparency between 0 (fully transparent) and 255 (fully visible). I once wrote this function to add transparency to a color vector, maybe it is usefull here?

addTrans <- function(color,trans)
{
  # This function adds transparancy to a color.
  # Define transparancy with an integer between 0 and 255
  # 0 being fully transparant and 255 being fully visable
  # Works with either color and trans a vector of equal length,
  # or one of the two of length 1.

  if (length(color)!=length(trans)&!any(c(length(color),length(trans))==1)) stop("Vector lengths not correct")
  if (length(color)==1 & length(trans)>1) color <- rep(color,length(trans))
  if (length(trans)==1 & length(color)>1) trans <- rep(trans,length(color))

  num2hex <- function(x)
  {
    hex <- unlist(strsplit("0123456789ABCDEF",split=""))
    return(paste(hex[(x-x%%16)/16+1],hex[x%%16+1],sep=""))
  }
  rgb <- rbind(col2rgb(color),trans)
  res <- paste("#",apply(apply(rgb,2,num2hex),2,paste,collapse=""),sep="")
  return(res)
}

Some examples:

cols <- sample(c("red","green","pink"),100,TRUE)

# Fully visable:
plot(rnorm(100),rnorm(100),col=cols,pch=16,cex=4)

# Somewhat transparant:
plot(rnorm(100),rnorm(100),col=addTrans(cols,200),pch=16,cex=4)

# Very transparant:
plot(rnorm(100),rnorm(100),col=addTrans(cols,100),pch=16,cex=4)

XMLHttpRequest blocked by CORS Policy

I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer

What is the difference between T(n) and O(n)?

There's a simple way (a trick, I guess) to remember which notation means what.

All of the Big-O notations can be considered to have a bar.

When looking at a O, the bar is at the bottom, so it is an (asymptotic) lower bound.

When looking at a T, the bar is obviously in the middle. So it is an (asymptotic) tight bound.

When handwriting O, you usually finish at the top, and draw a squiggle. Therefore O(n) is the upper bound of the function. To be fair, this one doesn't work with most fonts, but it is the original justification of the names.

Functional style of Java 8's Optional.ifPresent and if-not-Present?

Another solution could be following:

This is how you use it:

    final Opt<String> opt = Opt.of("I'm a cool text");
    opt.ifPresent()
        .apply(s -> System.out.printf("Text is: %s\n", s))
        .elseApply(() -> System.out.println("no text available"));

Or in case you in case of the opposite use case is true:

    final Opt<String> opt = Opt.of("This is the text");
    opt.ifNotPresent()
        .apply(() -> System.out.println("Not present"))
        .elseApply(t -> /*do something here*/);

This are the ingredients:

  1. Little modified Function interface, just for the "elseApply" method
  2. Optional enhancement
  3. A little bit of curring :-)

The "cosmetically" enhanced Function interface.

@FunctionalInterface
public interface Fkt<T, R> extends Function<T, R> {

    default R elseApply(final T t) {
        return this.apply(t);
    }

}

And the Optional wrapper class for enhancement:

public class Opt<T> {

    private final Optional<T> optional;

    private Opt(final Optional<T> theOptional) {
        this.optional = theOptional;
    }

    public static <T> Opt<T> of(final T value) {
        return new Opt<>(Optional.of(value));
    }

    public static <T> Opt<T> of(final Optional<T> optional) {
        return new Opt<>(optional);
    }

    public static <T> Opt<T> ofNullable(final T value) {
        return new Opt<>(Optional.ofNullable(value));
    }

    public static <T> Opt<T> empty() {
        return new Opt<>(Optional.empty());
    }

    private final BiFunction<Consumer<T>, Runnable, Void> ifPresent = (present, notPresent) -> {
        if (this.optional.isPresent()) {
            present.accept(this.optional.get());
        } else {
            notPresent.run();
        }
        return null;
    };

   private final BiFunction<Runnable, Consumer<T>, Void> ifNotPresent = (notPresent, present) -> {
        if (!this.optional.isPresent()) {
            notPresent.run();
        } else {
            present.accept(this.optional.get());
        }
        return null;
    };

    public Fkt<Consumer<T>, Fkt<Runnable, Void>> ifPresent() {
        return Opt.curry(this.ifPresent);
    }

    public Fkt<Runnable, Fkt<Consumer<T>, Void>> ifNotPresent() {
        return Opt.curry(this.ifNotPresent);
    }

    private static <X, Y, Z> Fkt<X, Fkt<Y, Z>> curry(final BiFunction<X, Y, Z> function) {
        return (final X x) -> (final Y y) -> function.apply(x, y);
    }
}

This should do the trick and could serve as a basic template how to deal with such requirements.

The basic idea here is following. In a non functional style programming world you would probably implement a method taking two parameter where the first is a kind of runnable code which should be executed in case the value is available and the other parameter is the runnable code which should be run in case the value is not available. For the sake of better readability, you can use curring to split the function of two parameter in two functions of one parameter each. This is what I basically did here.

Hint: Opt also provides the other use case where you want to execute a piece of code just in case the value is not available. This could be done also via Optional.filter.stuff but I found this much more readable.

Hope that helps!

Good programming :-)

Vuex - passing multiple parameters to mutation

Mutations expect two arguments: state and payload, where the current state of the store is passed by Vuex itself as the first argument and the second argument holds any parameters you need to pass.

The easiest way to pass a number of parameters is to destruct them:

mutations: {
    authenticate(state, { token, expiration }) {
        localStorage.setItem('token', token);
        localStorage.setItem('expiration', expiration);
    }
}

Then later on in your actions you can simply

store.commit('authenticate', {
    token,
    expiration,
});

Adding Table rows Dynamically in Android

Create an init() function and point the table layout. Then create the needed rows and columns.

   public void init() {
            TableLayout stk = (TableLayout) findViewById(R.id.table_main);
            TableRow tbrow0 = new TableRow(this);
            TextView tv0 = new TextView(this);
            tv0.setText(" Sl.No ");
            tv0.setTextColor(Color.WHITE);
            tbrow0.addView(tv0);
            TextView tv1 = new TextView(this);
            tv1.setText(" Product ");
            tv1.setTextColor(Color.WHITE);
            tbrow0.addView(tv1);
            TextView tv2 = new TextView(this);
            tv2.setText(" Unit Price ");
            tv2.setTextColor(Color.WHITE);
            tbrow0.addView(tv2);
            TextView tv3 = new TextView(this);
            tv3.setText(" Stock Remaining ");
            tv3.setTextColor(Color.WHITE);
            tbrow0.addView(tv3);
            stk.addView(tbrow0);
            for (int i = 0; i < 25; i++) {
                TableRow tbrow = new TableRow(this);
                TextView t1v = new TextView(this);
                t1v.setText("" + i);
                t1v.setTextColor(Color.WHITE);
                t1v.setGravity(Gravity.CENTER);
                tbrow.addView(t1v);
                TextView t2v = new TextView(this);
                t2v.setText("Product " + i);
                t2v.setTextColor(Color.WHITE);
                t2v.setGravity(Gravity.CENTER);
                tbrow.addView(t2v);
                TextView t3v = new TextView(this);
                t3v.setText("Rs." + i);
                t3v.setTextColor(Color.WHITE);
                t3v.setGravity(Gravity.CENTER);
                tbrow.addView(t3v);
                TextView t4v = new TextView(this);
                t4v.setText("" + i * 15 / 32 * 10);
                t4v.setTextColor(Color.WHITE);
                t4v.setGravity(Gravity.CENTER);
                tbrow.addView(t4v);
                stk.addView(tbrow);
            }

        }

Call init function in your onCreate method:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        init();
    }

Layout file like:

 <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#3d455b"
        android:layout_alignParentLeft="true" >

        <HorizontalScrollView
            android:id="@+id/hscrll1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" >

            <RelativeLayout
                android:id="@+id/RelativeLayout1"
                android:layout_width="fill_parent"
                android:layout_gravity="center"
                android:layout_height="fill_parent"
                android:orientation="vertical" >

                <TableLayout
                    android:id="@+id/table_main"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerHorizontal="true" >
                </TableLayout>
            </RelativeLayout>
        </HorizontalScrollView>
    </ScrollView>

Will look like:

enter image description here

no module named zlib

After you install the missing zlib dev package you can also use pythonbrew to uninstall and then reinstall the version of python you wanted and it seems like it picks up the new package to compile to correct abilities. This way you can keep using pythonbrew and don't have to do the compilation yourself (though it isn't that difficult)

what's the easiest way to put space between 2 side-by-side buttons in asp.net

you can use btnSubmit::before { margin-left: 20px; }

ReactJS - Does render get called any time "setState" is called?

Yes. It calls the render() method every time we call setState only except when "shouldComponentUpdate" returns false.

How can I make text appear on next line instead of overflowing?

Well, you can stick one or more "soft hyphens" (&#173;) in your long unbroken strings. I doubt that old IE versions deal with that correctly, but what it's supposed to do is tell the browser about allowable word breaks that it can use if it has to.

Now, how exactly would you pick where to stuff those characters? That depends on the actual string and what it means, I guess.

Auto-fit TextView for Android

Warning, bug in Android 3 (Honeycomb) and Android 4.0 (Ice Cream Sandwich)

Androids versions: 3.1 - 4.04 have a bug, that setTextSize() inside of TextView works only for the first time (first invocation).

The bug is described in Issue 22493: TextView height bug in Android 4.0 and Issue 17343: button's height and text does not return to its original state after increase and decrease the text size on HoneyComb.

The workaround is to add a newline character to text assigned to TextView before changing size:

final String DOUBLE_BYTE_SPACE = "\u3000";
textView.append(DOUBLE_BYTE_SPACE);

I use it in my code as follow:

final String DOUBLE_BYTE_SPACE = "\u3000";
AutoResizeTextView textView = (AutoResizeTextView) view.findViewById(R.id.aTextView);
String fixString = "";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR1
   && android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {  
    fixString = DOUBLE_BYTE_SPACE;
}
textView.setText(fixString + "The text" + fixString);

I add this "\u3000" character on left and right of my text, to keep it centered. If you have it aligned to left then append to the right only. Of course it can be also embedded with AutoResizeTextView widget, but I wanted to keep fix code outside.

Adding author name in Eclipse automatically to existing files

To old files I don't know how to do it... I think you will need a script to go thru all files and add the header.

To change the new ones you can do this.

Go to Eclipse menu bar

  1. Window menu.
  2. Preferences
  3. search for Templates
  4. go to Code templates
  5. click on +code
  6. Click on New Java files
  7. Click Edit
  8. add

/**
${user}
*/

And it's done every new File will have your name on it !

Drop data frame columns by name

list(NULL) also works:

dat <- mtcars
colnames(dat)
# [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear"
# [11] "carb"
dat[,c("mpg","cyl","wt")] <- list(NULL)
colnames(dat)
# [1] "disp" "hp"   "drat" "qsec" "vs"   "am"   "gear" "carb"

switch case statement error: case expressions must be constant expression

Simple solution for this problem is :

Click on the switch and then press CTL+1, It will change your switch to if-else block statement, and will resolve your problem

How to print to console using swift playground?

You may still have trouble displaying the output in the Assistant Editor. Rather than wrapping the string in println(), simply output the string. For example:

for index in 1...5 {
    "The number is \(index)"
}

Will write (5 times) in the playground area. This will allow you to display it in the Assistant Editor (via the little circle on the far right edge).

However, if you were to println("The number is \(index)") you wouldn't be able to visualize it in the Assistant Editor.

CSS transition fade in

I believe you could addClass to the element. But either way you'd have to use Jquery or reg JS

div {
  opacity:0;
  transition:opacity 1s linear;*
}
div.SomeClass {
  opacity:1;
}

Passing a method parameter using Task.Factory.StartNew

For passing a single integer I agree with Reed Copsey's answer. If in the future you are going to pass more complicated constucts I personally like to pass all my variables as an Anonymous Type. It will look something like this:

foreach(int id in myIdsToCheck)
{
    Task.Factory.StartNew( (Object obj) => 
        {
           var data = (dynamic)obj;
           CheckFiles(data.id, theBlockingCollection,
               cancelCheckFile.Token, 
               TaskCreationOptions.LongRunning, 
               TaskScheduler.Default);
        }, new { id = id }); // Parameter value
}

You can learn more about it in my blog

How can I know which radio button is selected via jQuery?

To get the value of the selected radio that uses a class:

$('.class:checked').val()

How can I break up this long line in Python?

Personally I dislike hanging open blocks, so I'd format it as:

logger.info(
    'Skipping {0} because its thumbnail was already in our system as {1}.'
    .format(line[indexes['url']], video.title)
)

In general I wouldn't bother struggle too hard to make code fit exactly within a 80-column line. It's worth keeping line length down to reasonable levels, but the hard 80 limit is a thing of the past.

How to create a HashMap with two keys (Key-Pair, Value)?

There are several options:

2 dimensions

Map of maps

Map<Integer, Map<Integer, V>> map = //...
//...

map.get(2).get(5);

Wrapper key object

public class Key {

    private final int x;
    private final int y;

    public Key(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Key)) return false;
        Key key = (Key) o;
        return x == key.x && y == key.y;
    }

    @Override
    public int hashCode() {
        int result = x;
        result = 31 * result + y;
        return result;
    }

}

Implementing equals() and hashCode() is crucial here. Then you simply use:

Map<Key, V> map = //...

and:

map.get(new Key(2, 5));

Table from Guava

Table<Integer, Integer, V> table = HashBasedTable.create();
//...

table.get(2, 5);

Table uses map of maps underneath.

N dimensions

Notice that special Key class is the only approach that scales to n-dimensions. You might also consider:

Map<List<Integer>, V> map = //...

but that's terrible from performance perspective, as well as readability and correctness (no easy way to enforce list size).

Maybe take a look at Scala where you have tuples and case classes (replacing whole Key class with one-liner).

Detecting arrow key presses in JavaScript

Modern answer since keyCode is now deprecated in favor of key:

document.onkeydown = function (e) {
    switch (e.key) {
        case 'ArrowUp':
            // up arrow
            break;
        case 'ArrowDown':
            // down arrow
            break;
        case 'ArrowLeft':
            // left arrow
            break;
        case 'ArrowRight':
            // right arrow
    }
};

echo that outputs to stderr

Combining solution suggested by James Roth and Glenn Jackman

  • add ANSI color code to display the error message in red:
echoerr() { printf "\e[31;1m%s\e[0m\n" "$*" >&2; }

# if somehow \e is not working on your terminal, use \u001b instead
# echoerr() { printf "\u001b[31;1m%s\u001b[0m\n" "$*" >&2; }

echoerr "This error message should be RED"

Align items in a stack panel?

Could not get this working using a DockPanel quite the way I wanted and reversing the flow direction of a StackPanel is troublesome. Using a grid is not an option as items inside of it may be hidden at runtime and thus I do not know the total number of columns at design time. The best and simplest solution I could come up with is:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>
    <StackPanel Grid.Column="1" Orientation="Horizontal">
        <!-- Right aligned controls go here -->
    </StackPanel>
</Grid>

This will result in controls inside of the StackPanel being aligned to the right side of the available space regardless of the number of controls - both at design and runtime. Yay! :)

Why should I use an IDE?

IDEs are basically:

  • Editor w/code completion, refactoring and documentation
  • Debugger
  • Filesystem explorer
  • SCMS client
  • Build tool

all in a single package.

You can have all this (and some more) using separate tools or just a great programmable editor and extra tools, like Emacs (Vim as well but has a little less IDEbility IMO).

If you find yourself switching a lot between one utility and the next that could be integrated in the environment or if you are missing some of the abilities listed here (and more completely in other posts), maybe it's time to move to an IDE (or to improve the IDEbility of your environment by adding macros or what not). If you have built yourself an 'IDE' (in the sense I mention above) using more than one program, then there's no need to move to an actual IDE.

Retrieve all values from HashMap keys in an ArrayList Java

It has method to find all values from map:

Map<K, V> map=getMapObjectFromXyz();
Collection<V> vs= map.values();
     

Iterate over vs to do some operation

What is the purpose of the return statement?

In python, we start defining a function with "def" and generally, but not necessarily, end the function with "return".

A function of variable x is denoted as f(x). What this function does? Suppose, this function adds 2 to x. So, f(x)=x+2

Now, the code of this function will be:

def A_function (x):
    return x + 2

After defining the function, you can use that for any variable and get result. Such as:

print A_function (2)
>>> 4

We could just write the code slightly differently, such as:

def A_function (x):
    y = x + 2
    return y
print A_function (2)

That would also give "4".

Now, we can even use this code:

def A_function (x):
    x = x + 2
    return x
print A_function (2)

That would also give 4. See, that the "x" beside return actually means (x+2), not x of "A_function(x)".

I guess from this simple example, you would understand the meaning of return command.

How can I create a text box for a note in markdown?

Similar to Etienne's solution, a simple table formats nicely:

| | |
|-|-|
|`NOTE` | This is something I want you to notice. It has a lot of text, and I want that text to wrap within a cell to the right of the `NOTE`, instead of under it.|

Another alternative (which comes with more emphasis), is to make the content the header of a body-less table:

|`NOTE` | This is something I want you to notice. It has a lot of text, and I want that text to wrap within a cell to the right of the `NOTE`, instead of under it.|
|-|-|

Finally, you can include a horizontal line (thematic break) to create a closed box (although the line style is a little different than the header line in the table):

| | |
|-|-|
|`NOTE` | This is something I want you to notice. It has a lot of text, and I want that text to wrap within a cell to the right of the `NOTE`, instead of under it.|

---

Note the empty line after the text.

Efficient way to rotate a list in python

Numpy can do this using the roll command:

>>> import numpy
>>> a=numpy.arange(1,10) #Generate some data
>>> numpy.roll(a,1)
array([9, 1, 2, 3, 4, 5, 6, 7, 8])
>>> numpy.roll(a,-1)
array([2, 3, 4, 5, 6, 7, 8, 9, 1])
>>> numpy.roll(a,5)
array([5, 6, 7, 8, 9, 1, 2, 3, 4])
>>> numpy.roll(a,9)
array([1, 2, 3, 4, 5, 6, 7, 8, 9])

How to set custom favicon in Express?

No extra middlewares required. Just use:

app.use('/favicon.ico', express.static('images/favicon.ico'));

php - insert a variable in an echo string

Variable interpolation does not happen in single quotes. You need to use double quotes as:

$i = 1
echo "<p class=\"paragraph$i\"></p>";
++i;

ERROR : [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

For anyone coming to this latterly, I was having this problem over a Windows network, and offer an additional thing to check:

Python script connecting would work from commandline on my (linux) machine, but some users had problems connecting - that it worked from CLI suggested the DSN and credentials were right. The issue for us was that the group security policy required the ODBC credentials to be set on every machine. Once we added that (for some reason, the user had three of the four ODBC credentials they needed for our various systems), they were able to connect.

You can of course do that at group level, but as it was a simple omission on the part of one machine, I did it in Control Panel > ODBC Drivers > New

Serialize an object to string

Code Safety Note

Regarding the accepted answer, it is important to use toSerialize.GetType() instead of typeof(T) in XmlSerializer constructor: if you use the first one the code covers all possible scenarios, while using the latter one fails sometimes.

Here is a link with some example code that motivate this statement, with XmlSerializer throwing an Exception when typeof(T) is used, because you pass an instance of a derived type to a method that calls SerializeObject<T>() that is defined in the derived type's base class: http://ideone.com/1Z5J1. Note that Ideone uses Mono to execute code: the actual Exception you would get using the Microsoft .NET runtime has a different Message than the one shown on Ideone, but it fails just the same.

For the sake of completeness I post the full code sample here for future reference, just in case Ideone (where I posted the code) becomes unavailable in the future:

using System;
using System.Xml.Serialization;
using System.IO;

public class Test
{
    public static void Main()
    {
        Sub subInstance = new Sub();
        Console.WriteLine(subInstance.TestMethod());
    }

    public class Super
    {
        public string TestMethod() {
            return this.SerializeObject();
        }
    }

    public class Sub : Super
    {
    }
}

public static class TestExt {
    public static string SerializeObject<T>(this T toSerialize)
    {
        Console.WriteLine(typeof(T).Name);             // PRINTS: "Super", the base/superclass -- Expected output is "Sub" instead
        Console.WriteLine(toSerialize.GetType().Name); // PRINTS: "Sub", the derived/subclass

        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
        StringWriter textWriter = new StringWriter();

        // And now...this will throw and Exception!
        // Changing new XmlSerializer(typeof(T)) to new XmlSerializer(subInstance.GetType()); 
        // solves the problem
        xmlSerializer.Serialize(textWriter, toSerialize);
        return textWriter.ToString();
    }
}

Can I map a hostname *and* a port with /etc/hosts?

If you really need to do this, use reverse proxy.

For example, with nginx as reverse proxy

server {
  listen       api.mydomain.com:80;
  server_name  api.mydomain.com;
  location / {
    proxy_pass http://127.0.0.1:8000;
  }
}

Can we cast a generic object to a custom object type in javascript?

No.

But if you're looking to treat your person1 object as if it were a Person, you can call methods on Person's prototype on person1 with call:

Person.prototype.getFullNamePublic = function(){
    return this.lastName + ' ' + this.firstName;
}
Person.prototype.getFullNamePublic.call(person1);

Though this obviously won't work for privileged methods created inside of the Person constructor—like your getFullName method.

Gradle DSL method not found: 'runProguard'

runProguard has been renamed to minifyEnabled in version 0.14.0 (2014/10/31) or more in Gradle.

To fix this, you need to change runProguard to minifyEnabled in the build.gradle file of your project.

enter image description here

Possible to view PHP code of a website?

Noone cand read the file except for those who have access to the file. You must make the code readable (but not writable) by the web server. If the php code handler is running properly you can't read it by requesting by name from the web server.

If someone compromises your server you are at risk. Ensure that the web server can only write to locations it absolutely needs to. There are a few locations under /var which should be properly configured by your distribution. They should not be accessible over the web. /var/www should not be writable, but may contain subdirectories written to by the web server for dynamic content. Code handlers should be disabled for these.

Ensure you don't do anything in your php code which can lead to code injection. The other risk is directory traversal using paths containing .. or begining with /. Apache should already be patched to prevent this when it is handling paths. However, when it runs code, including php, it does not control the paths. Avoid anything that allows the web client to pass a file path.

WPF Label Foreground Color

I checked your XAML, it works fine - e.g. both labels have a gray foreground.
My guess is that you have some style which is affecting the way it looks...

Try moving your XAML to a brand-new window and see for yourself... Then, check if you have any themes or styles (in the Window.Resources for instance) which might be affecting the labels...

Make selected block of text uppercase

I'm using the change-case extension and it works fine. I defined the shortcuts:

{ 
  "key": "ctrl+shift+u", 
  "command": "extension.changeCase.upper", 
  "when": "editorTextFocus" 
},
{ 
  "key": "ctrl+u",
  "command": "extension.changeCase.lower", 
  "when": "editorTextFocus" 
},

Set Response Status Code

Since PHP 5.4 you can use http_response_code.

http_response_code(404);

This will take care of setting the proper HTTP headers.

If you are running PHP < 5.4 then you have two options:

  1. Upgrade.
  2. Use this http_response_code function implemented in PHP.

INNER JOIN vs INNER JOIN (SELECT . FROM)

There won't be much difference. Howver version 2 is easier when you have some calculations, aggregations, etc that should be joined outside of it

--Version 2 
SELECT p.Name, s.OrderQty 
FROM Product p 
INNER JOIN 
(SELECT ProductID, SUM(OrderQty) as OrderQty FROM SalesOrderDetail GROUP BY ProductID
HAVING SUM(OrderQty) >1000) s 
on p.ProductID = s.ProdctId 

move a virtual machine from one vCenter to another vCenter

For moving a virtual machine you need not clone the VM, just copy the VM files (after powering the VM off) to external HDD and register the same on destination host.

Laravel 5 Carbon format datetime

Date Casting for Laravel 6.x and 7.x

/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
   'created_at' => 'datetime:Y-m-d',
   'updated_at' => 'datetime:Y-m-d',
   'deleted_at' => 'datetime:Y-m-d h:i:s'
];

It easy for Laravel 5 in your Model add property protected $dates = ['created_at', 'cached_at']. See detail here https://laravel.com/docs/5.2/eloquent-mutators#date-mutators

Date Mutators: Laravel 5.x

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
   /**
   * The attributes that should be mutated to dates.
   *
   * @var array
   */
   protected $dates = ['created_at', 'updated_at', 'deleted_at'];
}

You can format date like this $user->created_at->format('M d Y'); or any format that support by PHP.

Regex pattern including all special characters

(^\W$)

^ - start of the string, \W - match any non-word character [^a-zA-Z0-9_], $ - end of the string

Twitter - How to embed native video from someone else's tweet into a New Tweet or a DM

I eventually figured out an easy way to do it:

  1. On your Twitter feed, click the date/time of the tweet containing the video. That will open the single tweet view
  2. Look for the down-pointing arrow at the top-right corner of the tweet, click it to open drop-down menue
  3. Select the "Embed Video" option and copy the HTML embed code and Paste it to Notepad
  4. Find the last "t.co" shortened URL inside the HTML code (should be something like this: https://``t.co/tQM43ftXyM). Copy this URL and paste it in a new browser tab.
  5. The browser will expand the shortened URL to something which looks like this: https://twitter.com/UserName/status/828267001496784896/video/1

This is the link to the Twitter Card containing the native video. Pasting this link in a new tweet or DM will include the native video in it!

Encode a FileStream to base64 with c#

When dealing with large streams, like a file sized over 4GB - you don't want to load the file into memory (as a Byte[]) because not only is it very slow, but also may cause a crash as even in 64-bit processes a Byte[] cannot exceed 2GB (or 4GB with gcAllowVeryLargeObjects).

Fortunately there's a neat helper in .NET called ToBase64Transform which processes a stream in chunks. For some reason Microsoft put it in System.Security.Cryptography and it implements ICryptoTransform (for use with CryptoStream), but disregard that ("a rose by any other name...") just because you aren't performing any cryprographic tasks.

You use it with CryptoStream like so:

using System.Security.Cryptography;
using System.IO;

//

using( FileStream   inputFile    = new FileStream( @"C:\VeryLargeFile.bin", FileMode.Open, FileAccess.Read, FileShare.None, bufferSize: 1024 * 1024, useAsync: true ) ) // When using `useAsync: true` you get better performance with buffers much larger than the default 4096 bytes.
using( CryptoStream base64Stream = new CryptoStream( inputFile, new ToBase64Transform(), CryptoStreamMode.Read ) )
using( FileStream   outputFile   = new FileStream( @"C:\VeryLargeBase64File.txt", FileMode.CreateNew, FileAccess.Write, FileShare.None, bufferSize: 1024 * 1024, useAsync: true ) )
{
    await base64Stream.CopyToAsync( outputFile ).ConfigureAwait(false);
}

Determine a user's timezone

There's no such way to figure the timezone in the actual HTML code or any user-agent string, but what you can do is make a basic function getting it using JavaScript.

I don't know how to code with JavaScript yet so my function might take time to make.

However, you can try to get the actual timezone also using JavaScript with the getTzimezoneOffset() function in the Date section or simply new Date().getTimezoneOffset();.

ping response "Request timed out." vs "Destination Host unreachable"

As khaos said, a destination unreachable could also mean that something is blocking the way from or to your destination. For example an ACL that filters bad IP addresses.

Best way to convert text files between character sets?

DOS/Windows: use Code page

chcp 65001>NUL
type ascii.txt > unicode.txt

Command chcp can be used to change the code page. Code page 65001 is Microsoft name for UTF-8. After setting code page, the output generated by following commands will be of code page set.

How to upload a file from Windows machine to Linux machine using command lines via PuTTy?

Pscp.exe is painfully slow.

Uploading files using WinSCP is like 10 times faster.

So, to do that from command line, first you got to add the winscp.com file to your %PATH%. It's not a top-level domain, but an executable .com file, which is located in your WinSCP installation directory.

Then just issue a simple command and your file will be uploaded much faster putty ever could:

WinSCP.com /command "open sftp://username:[email protected]:22" "put your_large_file.zip /var/www/somedirectory/" "exit"

And make sure your check the synchronize folders feature, which is basically what rsync does, so you won't ever want to use pscp.exe again.

WinSCP.com /command "help synchronize"

How can I color a UIImage in Swift?

Since I found Darko's answer very helpful in colorizing custom pins for mapView annotations, but had to do some conversions for Swift 3, thought I'd share the updated code along with my recommendation for his answer:

extension UIImage {
    func maskWithColor(color: UIColor) -> UIImage {

        var maskImage = self.CGImage
        let width = self.size.width
        let height = self.size.height
        let bounds = CGRect(x: 0, y: 0, width: width, height: height)

        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
        let bitmapContext = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)

        bitmapContext!.clip(to: bounds, mask: maskImage!)
        bitmapContext!.setFillColor(color.cgColor)
        bitmapContext!.fill(bounds)

        let cImage = bitmapContext!.makeImage()
        let coloredImage = UIImage(CGImage: cImage)

        return coloredImage!
    }
}

Do I commit the package-lock.json file created by npm 5?

I don't commit this file in my projects. What's the point ?

  1. It's generated
  2. It's the cause of a SHA1 code integrity err in gitlab with gitlab-ci.yml builds

Though it's true that I never use ^ in my package.json for libs because I had bad experiences with it.

How do I count cells that are between two numbers in Excel?

=COUNTIFS(H5:H21000,">=100", H5:H21000,"<999")

GridView must be placed inside a form tag with runat="server" even after the GridView is within a form tag

Just after your Page_Load add this:

public override void VerifyRenderingInServerForm(Control control)
{
    //base.VerifyRenderingInServerForm(control);
}

Note that I don't do anything in the function.

EDIT: Tim answered the same thing. :) You can also find the answer Here

Count number of objects in list

I spent ages trying to figure this out but it is simple! You can use length(·). length(mylist) will tell you the number of objects mylist contains.

... and just realised someone had already answered this- sorry!

How to use cookies in Python Requests

Summary (@Freek Wiekmeijer, @gtalarico) other's answer:

Logic of Login

  • Many resource(pages, api) need authentication, then can access, otherwise 405 Not Allowed
  • Common authentication=grant access method are:
    • cookie
    • auth header
      • Basic xxx
      • Authorization xxx

How use cookie in requests to auth

  1. first get/generate cookie
  2. send cookie for following request
  • manual set cookie in headers
  • auto process cookie by requests's
    • session to auto manage cookies
    • response.cookies to manually set cookies

use requests's session auto manage cookies

curSession = requests.Session() 
# all cookies received will be stored in the session object

payload={'username': "yourName",'password': "yourPassword"}
curSession.post(firstUrl, data=payload)
# internally return your expected cookies, can use for following auth

# internally use previously generated cookies, can access the resources
curSession.get(secondUrl)

curSession.get(thirdUrl)

manually control requests's response.cookies

payload={'username': "yourName",'password': "yourPassword"}
resp1 = requests.post(firstUrl, data=payload)

# manually pass previously returned cookies into following request
resp2 = requests.get(secondUrl, cookies= resp1.cookies)

resp3 = requests.get(thirdUrl, cookies= resp2.cookies)

Programmatically create a UIView with color gradient

SWIFT 3

To add a gradient layer on your view

  • Bind your view outlet

    @IBOutlet var YOURVIEW : UIView!
    
  • Define the CAGradientLayer()

    var gradient = CAGradientLayer()
    
  • Here is the code you have to write in your viewDidLoad

    YOURVIEW.layoutIfNeeded()

    gradient.startPoint = CGPoint(x: CGFloat(0), y: CGFloat(1)) gradient.endPoint = CGPoint(x: CGFloat(1), y: CGFloat(0)) gradient.frame = YOURVIEW.bounds gradient.colors = [UIColor.red.cgColor, UIColor.green.cgColor] gradient.colors = [ UIColor(red: 255.0/255.0, green: 56.0/255.0, blue: 224.0/255.0, alpha: 1.0).cgColor,UIColor(red: 86.0/255.0, green: 13.0/255.0, blue: 232.0/255.0, alpha: 1.0).cgColor,UIColor(red: 16.0/255.0, green: 173.0/255.0, blue: 245.0/255.0, alpha: 1.0).cgColor] gradient.locations = [0.0 ,0.6 ,1.0] YOURVIEW.layer.insertSublayer(gradient, at: 0)

Variable length (Dynamic) Arrays in Java

How about using a List instead? For example, ArrayList<integer>

How to uninstall mini conda? python

your have to comment that line in ~/.bashrc:

#export PATH=/home/jolth/miniconda3/bin:$PATH

and run:

source ~/.bashrc

Append to the end of a file in C

Open with append:

pFile2 = fopen("myfile2.txt", "a");

then just write to pFile2, no need to fseek().

Javascript: best Singleton pattern

(1) UPDATE 2019: ES7 Version

class Singleton {
    static instance;

    constructor() {
        if (instance) {
            return instance;
        }

        this.instance = this;
    }

    foo() {
        // ...
    }
}

console.log(new Singleton() === new Singleton());

(2) ES6 Version

class Singleton {
    constructor() {
        const instance = this.constructor.instance;
        if (instance) {
            return instance;
        }

        this.constructor.instance = this;
    }

    foo() {
        // ...
    }
}

console.log(new Singleton() === new Singleton());

Best solution found: http://code.google.com/p/jslibs/wiki/JavascriptTips#Singleton_pattern

function MySingletonClass () {

  if (arguments.callee._singletonInstance) {
    return arguments.callee._singletonInstance;
  }

  arguments.callee._singletonInstance = this;

  this.Foo = function () {
    // ...
  };
}

var a = new MySingletonClass();
var b = MySingletonClass();
console.log( a === b ); // prints: true

For those who want the strict version:

(function (global) {
  "use strict";
  var MySingletonClass = function () {

    if (MySingletonClass.prototype._singletonInstance) {
      return MySingletonClass.prototype._singletonInstance;
    }

    MySingletonClass.prototype._singletonInstance = this;

    this.Foo = function() {
      // ...
    };
  };

var a = new MySingletonClass();
var b = MySingletonClass();
global.result = a === b;

} (window));

console.log(result);

Listening for variable changes in JavaScript

This is what I did: Call JSON.stringify twice and compare the two strings...

Drawbacks:

  • You can only know whether the whole object changes
  • You have to detect changes manually
  • You better have only primitive fields in the object(no properties, no functions...)

Equivalent of varchar(max) in MySQL?

The max length of a varchar is subject to the max row size in MySQL, which is 64KB (not counting BLOBs):

VARCHAR(65535)

However, note that the limit is lower if you use a multi-byte character set:

VARCHAR(21844) CHARACTER SET utf8

Here are some examples:

The maximum row size is 65535, but a varchar also includes a byte or two to encode the length of a given string. So you actually can't declare a varchar of the maximum row size, even if it's the only column in the table.

mysql> CREATE TABLE foo ( v VARCHAR(65534) );
ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs

But if we try decreasing lengths, we find the greatest length that works:

mysql> CREATE TABLE foo ( v VARCHAR(65532) );
Query OK, 0 rows affected (0.01 sec)

Now if we try to use a multibyte charset at the table level, we find that it counts each character as multiple bytes. UTF8 strings don't necessarily use multiple bytes per string, but MySQL can't assume you'll restrict all your future inserts to single-byte characters.

mysql> CREATE TABLE foo ( v VARCHAR(65532) ) CHARSET=utf8;
ERROR 1074 (42000): Column length too big for column 'v' (max = 21845); use BLOB or TEXT instead

In spite of what the last error told us, InnoDB still doesn't like a length of 21845.

mysql> CREATE TABLE foo ( v VARCHAR(21845) ) CHARSET=utf8;
ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs

This makes perfect sense, if you calculate that 21845*3 = 65535, which wouldn't have worked anyway. Whereas 21844*3 = 65532, which does work.

mysql> CREATE TABLE foo ( v VARCHAR(21844) ) CHARSET=utf8;
Query OK, 0 rows affected (0.32 sec)

How do I concatenate two text files in PowerShell?

You could use the Add-Content cmdlet. Maybe it is a little faster than the other solutions, because I don't retrieve the content of the first file.

gc .\file2.txt| Add-Content -Path .\file1.txt

how to write value into cell with vba code without auto type conversion?

Indeed, just as commented by Tim Williams, the way to make it work is pre-formatting as text. Thus, to do it all via VBA, just do that:

Cells(1, 1).NumberFormat = "@"
Cells(1, 1).Value = "1234,56"

Get JSON Data from URL Using Android?

If you get the server response as a String, without using a third party library you can do

JSONObject json = new JSONObject(response);
JSONObject jsonResponse = json.getJSONObject("response");
String team = jsonResponse.getString("Team");

Here is the documentation

Otherwise to parse json you can use Gson or Jackson

EDIT without libraries (not tested)

class retrievedata extends AsyncTask<Void, Void, String>{
    @Override
    protected String doInBackground(Void... params) {

        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;

        URL url;
        try {
            url = new URL("http://myurlhere.com");
            urlConnection.setRequestMethod("GET"); //Your method here 
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null)
                buffer.append(line + "\n");

            if (buffer.length() == 0)
                return null;

            return buffer.toString();
        } catch (IOException e) {
            Log.e(TAG, "IO Exception", e);
            exception = e;
            return null;
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    exception = e;
                    Log.e(TAG, "Error closing stream", e);
                }
            }
        }
    }

    @Override
    protected void onPostExecute(String response) {
        if(response != null) {
            JSONObject json = new JSONObject(response);
            JSONObject jsonResponse = json.getJSONObject("response");
            String team = jsonResponse.getString("Team");
        }
    }
}

how to create a login page when username and password is equal in html

<html>
    <head>
        <title>Login page</title>
    </head>
    <body>
        <h1>Simple Login Page</h1>
        <form name="login">
            Username<input type="text" name="userid"/>
            Password<input type="password" name="pswrd"/>
            <input type="button" onclick="check(this.form)" value="Login"/>
            <input type="reset" value="Cancel"/>
        </form>
        <script language="javascript">
            function check(form) { /*function to check userid & password*/
                /*the following code checkes whether the entered userid and password are matching*/
                if(form.userid.value == "myuserid" && form.pswrd.value == "mypswrd") {
                    window.open('target.html')/*opens the target page while Id & password matches*/
                }
                else {
                    alert("Error Password or Username")/*displays error message*/
                }
            }
        </script>
    </body>
</html>

Is there a difference between using a dict literal and a dict constructor?

I think you have pointed out the most obvious difference. Apart from that,

the first doesn't need to lookup dict which should make it a tiny bit faster

the second looks up dict in locals() and then globals() and the finds the builtin, so you can switch the behaviour by defining a local called dict for example although I can't think of anywhere this would be a good idea apart from maybe when debugging

What is a non-capturing group in regular expressions?

It makes the group non-capturing, which means that the substring matched by that group will not be included in the list of captures. An example in ruby to illustrate the difference:

"abc".match(/(.)(.)./).captures #=> ["a","b"]
"abc".match(/(?:.)(.)./).captures #=> ["b"]

How do I format date and time on ssrs report?

hi friend please try this expression your report

="Page " + Globals!PageNumber.ToString() + " of " + Globals!OverallTotalPages.ToString() + vbcrlf + "Generated: " + Globals!ExecutionTime.ToString()

Does Android support near real time push notification?

Have a look at the Xtify platform. Looks like this is what they are doing,

Running Selenium Webdriver with a proxy in Python

My solution:

def my_proxy(PROXY_HOST,PROXY_PORT):
        fp = webdriver.FirefoxProfile()
        # Direct = 0, Manual = 1, PAC = 2, AUTODETECT = 4, SYSTEM = 5
        print PROXY_PORT
        print PROXY_HOST
        fp.set_preference("network.proxy.type", 1)
        fp.set_preference("network.proxy.http",PROXY_HOST)
        fp.set_preference("network.proxy.http_port",int(PROXY_PORT))
        fp.set_preference("general.useragent.override","whater_useragent")
        fp.update_preferences()
        return webdriver.Firefox(firefox_profile=fp)

Then call in your code:

my_proxy(PROXY_HOST,PROXY_PORT)

I had issues with this code because I was passing a string as a port #:

 PROXY_PORT="31280"

This is important:

int("31280")

You must pass an integer instead of a string or your firefox profile will not be set to a properly port and connection through proxy will not work.

Immutable array in Java

Another one answer

static class ImmutableArray<T> {
    private final T[] array;

    private ImmutableArray(T[] a){
        array = Arrays.copyOf(a, a.length);
    }

    public static <T> ImmutableArray<T> from(T[] a){
        return new ImmutableArray<T>(a);
    }

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

{
    final ImmutableArray<String> sample = ImmutableArray.from(new String[]{"a", "b", "c"});
}

Regex to remove letters, symbols except numbers

Simple:

var removedText = self.val().replace(/[^0-9]+/, '');

^ - means NOT

Pandas rename column by position?

You can do this:

df.rename(columns={ df.columns[1]: "whatever" })

Reading value from console, interactively

The Readline API has changed quite a bit since 12'. The doc's show a useful example to capture user input from a standard stream :

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question('What do you think of Node.js? ', (answer) => {
  console.log('Thank you for your valuable feedback:', answer);
  rl.close();
});

More information here.

How to add a WiX custom action that happens only on uninstall (via MSI)?

You can do this with a custom action. You can add a refrence to your custom action under <InstallExecuteSequence>:

<InstallExecuteSequence>
...
  <Custom Action="FileCleaner" After='InstallFinalize'>
          Installed AND NOT UPGRADINGPRODUCTCODE</Custom>

Then you will also have to define your Action under <Product>:

<Product> 
...
  <CustomAction Id='FileCleaner' BinaryKey='FileCleanerEXE' 
                ExeCommand='' Return='asyncNoWait'  />

Where FileCleanerEXE is a binary (in my case a little c++ program that does the custom action) which is also defined under <Product>:

<Product> 
...
  <Binary Id="FileCleanerEXE" SourceFile="path\to\fileCleaner.exe" />

The real trick to this is the Installed AND NOT UPGRADINGPRODUCTCODE condition on the Custom Action, with out that your action will get run on every upgrade (since an upgrade is really an uninstall then reinstall). Which if you are deleting files is probably not want you want during upgrading.

On a side note: I recommend going through the trouble of using something like C++ program to do the action, instead of a batch script because of the power and control it provides -- and you can prevent the "cmd prompt" window from flashing while your installer runs.

slideToggle JQuery right to left

You can do this using additional effects as a part of jQuery-ui

$('.show_hide').click(function () {
    $(".slidingDiv").toggle("slide");
});

Test Link

Automatically start a Windows Service on install

You corrupted your designer. ReAdd your Installer Component. It should have a serviceInstaller and a serviceProcessInstaller. The serviceInstaller with property Startup Method set to Automatic will startup when installed and after each reboot.

What causes signal 'SIGILL'?

It could be some un-initialized function pointer, in particular if you have corrupted memory (then the bogus vtable of C++ bad pointers to invalid objects might give that).

BTW gdb watchpoints & tracepoints, and also valgrind might be useful (if available) to debug such issues. Or some address sanitizer.

How to run a shell script in OS X by double-clicking?

Alternatively, you could create a regular Mac OS X application from your script using Platypus

"Permission Denied" trying to run Python on Windows 10

I experienced the same issue, but in addition to Python being blocked, all programs in the Scripts folder were too. The other answers about aliases, path and winpty didn't help.

I finally found that it was my antivirus (Avast) which decided overnight for some reason to just block all compiled python scripts for some reason.

The fix is fortunately easy: simply whitelist the whole Python directory. See here for a full explanation.

open link in iframe

Because the target of the link matches the name of the iframe, the link will open in the iframe. Try this:

<iframe src="http://stackoverflow.com/" name="iframe_a">
<p>Your browser does not support iframes.</p>
</iframe>

<a href="http://www.cnn.com" target="iframe_a">www.cnn.com</a>

Getting all request parameters in Symfony 2

Since you are in a controller, the action method is given a Request parameter.

You can access all POST data with $request->request->all();. This returns a key-value pair array.

When using GET requests you access data using $request->query->all();

Reading PDF content with itextsharp dll in VB.NET or C#

Here is a VB.NET solution based on ShravankumarKumar's solution.

This will ONLY give you the text. The images are a different story.

Public Shared Function GetTextFromPDF(PdfFileName As String) As String
    Dim oReader As New iTextSharp.text.pdf.PdfReader(PdfFileName)

    Dim sOut = ""

    For i = 1 To oReader.NumberOfPages
        Dim its As New iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy

        sOut &= iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(oReader, i, its)
    Next

    Return sOut
End Function

Wait some seconds without blocking UI execution

hi this is my suggestion

 .......
var t = Task.Run(async () => await Task.Delay(TimeSpan.FromSeconds(Consts.FiveHundred)).ConfigureAwait(false));
                //just to wait task is done
                t.Wait();

keep in mind put the "wait" otherwise the Delay run without affect application

Receiving login prompt using integrated windows authentication

I have a Windows 2008 server that I'm working on, so my answer is not completely the same as what the OP has on a Windows 2003 server.

Here is what I did (recording this here so I can find it later).

I was having this same issue:

login prompt

In my Web.config file, I had this section:

<system.web>
    <authentication mode="Windows" />
    <authorization>
        <allow users="*" />
        <deny users="?" />
    </authorization>
</system.web>

Under IIS, all of these seems to be solved under the Authentication icon.

  1. Edit Permissions: Make sure your ASP.NET account has permission. Mine was not originally added.

ASP.NET permission

Now go into the features of Authentication:

Authentication Features

Enable Anonymous Authentication with the IUSR:

Anonymous Authentication

Enable Windows Authentication, then Right-Click to set the Providers.

NTLM needs to be FIRST!

Windows Authentication

Next, check that under Advanced Settings... the Extended Protection is Accept and Enable Kernel-mode authentication is CHECKED:

Advanced Settings

Once I did this, I went back to my web application, clicked the Browse link, and logged in without having to provide my credentials again.

I hope this proves beneficial to many of you, and I hope it is useful for me later as well.

How to add files/folders to .gitignore in IntelliJ IDEA?

right click on the project create a file with name .ignore, then you can see that file opened.

at the right top of the file you can see install plugins or else you can install using plugins(plugin name - .ignore).

Now when ever you give a right click on the file or project you can see the option call add to .ignore

PHP reindex array?

This might not be the simplest answer as compared to using array_values().

Try this

$array = array( 0 => 'string1', 2 => 'string2', 4 => 'string3', 5 => 'string4');
$arrays =$array;
print_r($array);
$array=array();
$i=0;
    foreach($arrays as $k => $item)
    {
    $array[$i]=$item;
        unset($arrays[$k]);
        $i++;

    }

print_r($array);

Demo

What is the difference between String and StringBuffer in Java?

While I understand that this is not a major differentiating factor, I noticed today that StringBuffer(and StringBuilder) provides some interesting methods that String doesn't.

  • reverse()
  • setCharAt()

websocket.send() parameter

As I understand it, you want the server be able to send messages through from client 1 to client 2. You cannot directly connect two clients because one of the two ends of a WebSocket connection needs to be a server.

This is some pseudocodish JavaScript:

Client:

var websocket = new WebSocket("server address");

websocket.onmessage = function(str) {
  console.log("Someone sent: ", str);
};

// Tell the server this is client 1 (swap for client 2 of course)
websocket.send(JSON.stringify({
  id: "client1"
}));

// Tell the server we want to send something to the other client
websocket.send(JSON.stringify({
  to: "client2",
  data: "foo"
}));

Server:

var clients = {};

server.on("data", function(client, str) {
  var obj = JSON.parse(str);

  if("id" in obj) {
    // New client, add it to the id/client object
    clients[obj.id] = client;
  } else {
    // Send data to the client requested
    clients[obj.to].send(obj.data);
  }
});

How to check if bootstrap modal is open, so I can use jquery validate?

Why complicate things when it can be done with simple jQuery like following.

$('#myModal').on('shown.bs.modal', function (e) {
    console.log('myModal is shown');
    // Your actual function here
})

Laravel 5 – Clear Cache in Shared Hosting Server

I believe the more efficient approach to this is to use the cron job module in the shared server admin panel to run the laravel scheduler command which will in turn call the configured artisan command, something like this should do the job:

* * * * * /usr/bin/php /var/www/web/artisan schedule:run /dev/null 2>&1

With scheduler setup in cron, you can edit the schedule method in \App\Console\Kernel.php to call the right artisan command, something like this:

$schedule->command('queue:work')->cron('* * * * *')->withoutOverlapping();
$schedule->command('route:cache')->cron('0 0 * * *')->withoutOverlapping();

You can always delete the lines above after the commands run

How to round the double value to 2 decimal points?

you can also use this code

public static double roundToDecimals(double d, int c)  
{   
   int temp = (int)(d * Math.pow(10 , c));  
   return ((double)temp)/Math.pow(10 , c);  
}

It gives you control of how many numbers after the point are needed.

d = number to round;   
c = number of decimal places  

think it will be helpful

How do you test a public/private DSA keypair?

Assuming you have the public keys inside X.509 certificates, and assuming they are RSA keys, then for each public key, do

    openssl x509 -in certfile -modulus -noout

For each private key, do

    openssl rsa -in keyfile -modulus -noout

Then match the keys by modulus.

Hide axis and gridlines Highcharts

If you doesn't want to touch the config object, you just hide the grid by css:

.chart-container .highcharts-grid {
   display: none;
}

How to define two fields "unique" as couple

There is a simple solution for you called unique_together which does exactly what you want.

For example:

class MyModel(models.Model):
  field1 = models.CharField(max_length=50)
  field2 = models.CharField(max_length=50)

  class Meta:
    unique_together = ('field1', 'field2',)

And in your case:

class Volume(models.Model):
  id = models.AutoField(primary_key=True)
  journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name = "Journal")
  volume_number = models.CharField('Volume Number', max_length=100)
  comments = models.TextField('Comments', max_length=4000, blank=True)

  class Meta:
    unique_together = ('journal_id', 'volume_number',)

Checking if form has been submitted - PHP

if ($_SERVER['REQUEST_METHOD'] == 'POST').

How do I check if a given string is a legal/valid file name under Windows?

From MSDN, here's a list of characters that aren't allowed:

Use almost any character in the current code page for a name, including Unicode characters and characters in the extended character set (128–255), except for the following:

  • The following reserved characters are not allowed: < > : " / \ | ? *
  • Characters whose integer representations are in the range from zero through 31 are not allowed.
  • Any other character that the target file system does not allow.

MySQL equivalent of DECODE function in Oracle

You can use IF() where in Oracle you would have used DECODE().

mysql> select if(emp_id=1,'X','Y') as test, emp_id from emps; 

Set color of text in a Textbox/Label to Red and make it bold in asp.net C#

TextBox1.ForeColor = Color.Red;
TextBox1.Font.Bold = True;

Or this can be done using a CssClass (recommended):

.highlight
{
  color:red;
  font-weight:bold;
}

TextBox1.CssClass = "highlight";

Or the styles can be added inline:

TextBox1.Attributes["style"] = "color:red; font-weight:bold;";

Changing precision of numeric column in Oracle

If the table is compressed this will work:

alter table EVAPP_FEES add AMOUNT_TEMP NUMBER(14,2);

update EVAPP_FEES set AMOUNT_TEMP = AMOUNT;

update EVAPP_FEES set AMOUNT = null;

alter table EVAPP_FEES modify AMOUNT NUMBER(14,2);

update EVAPP_FEES set AMOUNT = AMOUNT_TEMP;

alter table EVAPP_FEES move nocompress;

alter table EVAPP_FEES drop column AMOUNT_TEMP;

alter table EVAPP_FEES compress;

The program can't start because cygwin1.dll is missing... in Eclipse CDT

You can compile with either Cygwin's g++ or MinGW (via stand-alone or using Cygwin package). However, in order to run it, you need to add the Cygwin1.dll (and others) PATH to the system Windows PATH, before any cygwin style paths.

Thus add: ;C:\cygwin64\bin to the end of your Windows system PATH variable.

Also, to compile for use in CMD or PowerShell, you may need to use:

x86_64-w64-mingw32-g++.exe -static -std=c++11 prog_name.cc -o prog_name.exe

(This invokes the cross-compiler, if installed.)

Assigning a variable NaN in python without numpy

A more consistent (and less opaque) way to generate inf and -inf is to again use float():

>> positive_inf = float('inf')
>> positive_inf
inf
>> negative_inf = float('-inf')
>> negative_inf
-inf

Note that the size of a float varies depending on the architecture, so it probably best to avoid using magic numbers like 9e999, even if that is likely to work.

import sys
sys.float_info
sys.float_info(max=1.7976931348623157e+308,
               max_exp=1024, max_10_exp=308,
               min=2.2250738585072014e-308, min_exp=-1021,
               min_10_exp=-307, dig=15, mant_dig=53,
               epsilon=2.220446049250313e-16, radix=2, rounds=1)

How to get HttpRequestMessage data

I suggest that you should not do it like this. Action methods should be designed to be easily unit-tested. In this case, you should not access data directly from the request, because if you do it like this, when you want to unit test this code you have to construct a HttpRequestMessage.

You should do it like this to let MVC do all the model binding for you:

[HttpPost]
public void Confirmation(YOURDTO yourobj)//assume that you define YOURDTO elsewhere
{
        //your logic to process input parameters.

}

In case you do want to access the request. You just access the Request property of the controller (not through parameters). Like this:

[HttpPost]
public void Confirmation()
{
    var content = Request.Content.ReadAsStringAsync().Result;
}

In MVC, the Request property is actually a wrapper around .NET HttpRequest and inherit from a base class. When you need to unit test, you could also mock this object.

CSS: how to position element in lower right?

Set the CSS position: relative; on the box. This causes all absolute positions of objects inside to be relative to the corners of that box. Then set the following CSS on the "Bet 5 days ago" line:

position: absolute;
bottom: 0;
right: 0;

If you need to space the text farther away from the edge, you could change 0 to 2px or similar.

Is it possible to implement a Python for range loop without an iterator variable?

Off the top of my head, no.

I think the best you could do is something like this:

def loop(f,n):
    for i in xrange(n): f()

loop(lambda: <insert expression here>, 5)

But I think you can just live with the extra i variable.

Here is the option to use the _ variable, which in reality, is just another variable.

for _ in range(n):
    do_something()

Note that _ is assigned the last result that returned in an interactive python session:

>>> 1+2
3
>>> _
3

For this reason, I would not use it in this manner. I am unaware of any idiom as mentioned by Ryan. It can mess up your interpreter.

>>> for _ in xrange(10): pass
...
>>> _
9
>>> 1+2
3
>>> _
9

And according to Python grammar, it is an acceptable variable name:

identifier ::= (letter|"_") (letter | digit | "_")*

Most efficient solution for reading CLOB to String, and String to CLOB in Java?

I can not use the "int length" constructor for StringBuilder since the length of my CLOB is longer than a int and needs a long value.

If the CLOB length is greater than fits in an int, the CLOB data won't fit in a String either. You'll have to use a streaming approach to deal with this much XML data.

If the actual length of the CLOB is smaller than Integer.MAX_VALUE, just force the long to int by putting (int) in front of it.

Java ArrayList clear() function

Your assumptions don't seem to be right. After a clear(), the newly added data start from index 0.

Can I convert long to int?

Wouldn't

(int) Math.Min(Int32.MaxValue, longValue)

be the correct way, mathematically speaking?

How can I output a UTF-8 CSV in PHP that Excel will read properly?

This works fine in excel for both Windows and also Mac OS.

Fix issues in excel that are not displaying characters containing diacritics, cyrillic letters, greek letter and currency symbols.

function writeCSV($filename, $headings, $data) {   

    //Use tab as field separator
    $newTab  = "\t";
    $newLine  = "\n";

    $fputcsv  =  count($headings) ? '"'. implode('"'.$newTab.'"', $headings).'"'.$newLine : '';

    // Loop over the * to export
    if (! empty($data)) {
      foreach($data as $item) {
        $fputcsv .= '"'. implode('"'.$newTab.'"', $item).'"'.$newLine;
      }
    }

    //Convert CSV to UTF-16
    $encoded_csv = mb_convert_encoding($fputcsv, 'UTF-16LE', 'UTF-8');

    // Output CSV-specific headers
    header('Set-Cookie: fileDownload=true; path=/'); //This cookie is needed in order to trigger the success window.
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private",false);
    header("Content-Type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"$filename.csv\";" );
    header("Content-Transfer-Encoding: binary");
    header('Content-Length: '. strlen($encoded_csv));
    echo chr(255) . chr(254) . $encoded_csv; //php array convert to csv/excel

    exit;
}

How can you tell if a value is not numeric in Oracle?

You can use the following regular expression which will match integers (e.g., 123), floating-point numbers (12.3), and numbers with exponents (1.2e3):

^-?\d*\.?\d+([eE]-?\d+)?$

If you want to accept + signs as well as - signs (as Oracle does with TO_NUMBER()), you can change each occurrence of - above to [+-]. So you might rewrite your block of code above as follows:

IF (option_id = 0021) THEN 
    IF NOT REGEXP_LIKE(value, '^[+-]?\d*\.?\d+([eE][+-]?\d+)?$') OR TO_NUMBER(value) < 10000 OR TO_NUMBER(value) > 7200000 THEN
        ip_msg(6214,option_name);
        RETURN;
    END IF;
END IF;

I am not altogether certain that would handle all values so you may want to add an EXCEPTION block or write a custom to_number() function as @JustinCave suggests.

How to find the foreach index?

I would like to add this, I used this in laravel to just index my table:

  • With $loop->index
  • I also preincrement it with ++$loop to start at 1

My Code:

@foreach($resultsPerCountry->first()->studies as $result)
  <tr>
    <td>{{ ++$loop->index}}</td>                                    
  </tr>
@endforeach

Pandas convert dataframe to array of tuples

More pythonic way:

df = data_set[['data_date', 'data_1', 'data_2']]
map(tuple,df.values)

Android Emulator sdcard push error: Read-only file system

Android studio version 0.8.9 and above has a bug creating AVDs.

See Issue 78434.

Workaround

  • go to your ADV folder in .android folder and find your AVD config.ini
  • open it with a text editor that can handle unix newlines. (Notepad will run the lines together since they don't have CR-LFs.)
  • change hw.sdCard=no to hw.sdCard=yes

this should work for everyone in new builds

Can I convert a C# string value to an escaped string literal

Hallgrim's answer was excellent. Here's a small tweak in case you need to parse out additional whitespace characters and linebreaks with a c# regular expression. I needed this in the case of a serialized Json value for insertion into google sheets and ran into trouble as the code was inserting tabs, +, spaces, etc.

  provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);
  var literal = writer.ToString();
  var r2 = new Regex(@"\"" \+.\n[\s]+\""", RegexOptions.ECMAScript);
  literal = r2.Replace(literal, "");
  return literal;

Get AVG ignoring Null or Zero values

In Case of not considering '0' or 'NULL' in average function. Simply use

AVG(NULLIF(your_column_name,0))

bind/unbind service example (android)

Add these methods to your Activity:

private MyService myServiceBinder;
public ServiceConnection myConnection = new ServiceConnection() {

    public void onServiceConnected(ComponentName className, IBinder binder) {
        myServiceBinder = ((MyService.MyBinder) binder).getService();
        Log.d("ServiceConnection","connected");
        showServiceData();
    }

    public void onServiceDisconnected(ComponentName className) {
        Log.d("ServiceConnection","disconnected");
        myService = null;
    }
};

public Handler myHandler = new Handler() {
    public void handleMessage(Message message) {
        Bundle data = message.getData();
    }
};

public void doBindService() {
    Intent intent = null;
    intent = new Intent(this, BTService.class);
    // Create a new Messenger for the communication back
    // From the Service to the Activity
    Messenger messenger = new Messenger(myHandler);
    intent.putExtra("MESSENGER", messenger);

    bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
}

And you can bind to service by ovverriding onResume(), and onPause() at your Activity class.

@Override
protected void onResume() {

    Log.d("activity", "onResume");
    if (myService == null) {
        doBindService();
    }
    super.onResume();
}

@Override
protected void onPause() {
    //FIXME put back

    Log.d("activity", "onPause");
    if (myService != null) {
        unbindService(myConnection);
        myService = null;
    }
    super.onPause();
}

Note, that when binding to a service only the onCreate() method is called in the service class. In your Service class you need to define the myBinder method:

private final IBinder mBinder = new MyBinder();
private Messenger outMessenger;

@Override
public IBinder onBind(Intent arg0) {
    Bundle extras = arg0.getExtras();
    Log.d("service","onBind");
    // Get messager from the Activity
    if (extras != null) {
        Log.d("service","onBind with extra");
        outMessenger = (Messenger) extras.get("MESSENGER");
    }
    return mBinder;
}

public class MyBinder extends Binder {
    MyService getService() {
        return MyService.this;
    }
}

After you defined these methods you can reach the methods of your service at your Activity:

private void showServiceData() {  
    myServiceBinder.myMethod();
}

and finally you can start your service when some event occurs like _BOOT_COMPLETED_

public class MyReciever  extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals("android.intent.action.BOOT_COMPLETED")) {
            Intent service = new Intent(context, myService.class);
            context.startService(service);
        }
    }
}

note that when starting a service the onCreate() and onStartCommand() is called in service class and you can stop your service when another event occurs by stopService() note that your event listener should be registerd in your Android manifest file:

<receiver android:name="MyReciever" android:enabled="true" android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
</receiver>

Why is Maven downloading the maven-metadata.xml every time?

It is possibly to use the flag -o,--offline "Work offline" to prevent that.

Like this:

maven compile -o

Create multiple threads and wait all of them to complete

I don't know if there is a better way, but the following describes how I did it with a counter and background worker thread.

private object _lock = new object();
private int _runningThreads = 0;

private int Counter{
    get{
        lock(_lock)
            return _runningThreads;
    }
    set{
        lock(_lock)
            _runningThreads = value;
    }
}

Now whenever you create a worker thread, increment the counter:

var t = new BackgroundWorker();
// Add RunWorkerCompleted handler

// Start thread
Counter++;

In work completed, decrement the counter:

private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    Counter--;
}

Now you can check for the counter anytime to see if any thread is running:

if(Couonter>0){
    // Some thread is yet to finish.
}

How to Turn Off Showing Whitespace Characters in Visual Studio IDE

In Visual Studio 2010 the key sequence CTRL+E, S will also toggle display of whitespace characters.

how to use php DateTime() function in Laravel 5

I didn't mean to copy the same answer, that is why I didn't accept my own answer.

Actually when I add use DateTime in top of the controller solves this problem.

How to export a mysql database using Command Prompt?

Give this command to export your database, this will include date as well

mysqldump -u[username] -p[userpassword] --databases yourdatabase | gzip > /home/pi/database_backup/database_`date '+%m-%d-%Y'`.sql.gz

(no space after -p)

How do I return the response from an asynchronous call?

Angular1

For people who are using AngularJS, can handle this situation using Promises.

Here it says,

Promises can be used to unnest asynchronous functions and allows one to chain multiple functions together.

You can find a nice explanation here also.

Example found in docs mentioned below.

  promiseB = promiseA.then(
    function onSuccess(result) {
      return result + 1;
    }
    ,function onError(err) {
      //Handle error
    }
  );

 // promiseB will be resolved immediately after promiseA is resolved 
 // and its value will be the result of promiseA incremented by 1.

Angular2 and Later

In Angular2 with look at the following example, but its recommended to use Observables with Angular2.

 search(term: string) {
     return this.http
  .get(`https://api.spotify.com/v1/search?q=${term}&type=artist`)
  .map((response) => response.json())
  .toPromise();

}

You can consume that in this way,

search() {
    this.searchService.search(this.searchField.value)
      .then((result) => {
    this.result = result.artists.items;
  })
  .catch((error) => console.error(error));
}

See the original post here. But Typescript does not support native es6 Promises, if you want to use it, you might need plugin for that.

Additionally here is the promises spec define here.

Regular Expression to find a string included between two characters while EXCLUDING the delimiters

Most updated solution

If you are using Javascript, the best solution that I came up with is using match instead of exec method. Then, iterate matches and remove the delimiters with the result of the first group using $1

const text = "This is a test string [more or less], [more] and [less]";
const regex = /\[(.*?)\]/gi;
const resultMatchGroup = text.match(regex); // [ '[more or less]', '[more]', '[less]' ]
const desiredRes = resultMatchGroup.map(match => match.replace(regex, "$1"))
console.log("desiredRes", desiredRes); // [ 'more or less', 'more', 'less' ]

As you can see, this is useful for multiple delimiters in the text as well

What's the Kotlin equivalent of Java's String[]?

There's no special case for String, because String is an ordinary referential type on JVM, in contrast with Java primitives (int, double, ...) -- storing them in a reference Array<T> requires boxing them into objects like Integer and Double. The purpose of specialized arrays like IntArray in Kotlin is to store non-boxed primitives, getting rid of boxing and unboxing overhead (the same as Java int[] instead of Integer[]).

You can use Array<String> (and Array<String?> for nullables), which is equivalent to String[] in Java:

val stringsOrNulls = arrayOfNulls<String>(10) // returns Array<String?>
val someStrings = Array<String>(5) { "it = $it" }
val otherStrings = arrayOf("a", "b", "c")

See also: Arrays in the language reference

How to convert xml into array in php?

The method used in the accepted answer drop attributes when encountering child elements with only a text node. For example:

$xml = '<container><element attribute="123">abcd</element></container>';
print_r(json_decode(json_encode(simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA)),1));

Array
(
    [element] => abcd
)

My solution (and I wish I could give credit here because I'm sure I adapted this from something):

function XMLtoArray($xml) {
    $previous_value = libxml_use_internal_errors(true);
    $dom = new DOMDocument('1.0', 'UTF-8');
    $dom->preserveWhiteSpace = false; 
    $dom->loadXml($xml);
    libxml_use_internal_errors($previous_value);
    if (libxml_get_errors()) {
        return [];
    }
    return DOMtoArray($dom);
}

function DOMtoArray($root) {
    $result = array();

    if ($root->hasAttributes()) {
        $attrs = $root->attributes;
        foreach ($attrs as $attr) {
            $result['@attributes'][$attr->name] = $attr->value;
        }
    }

    if ($root->hasChildNodes()) {
        $children = $root->childNodes;
        if ($children->length == 1) {
            $child = $children->item(0);
            if (in_array($child->nodeType,[XML_TEXT_NODE,XML_CDATA_SECTION_NODE])) {
                $result['_value'] = $child->nodeValue;
                return count($result) == 1
                    ? $result['_value']
                    : $result;
            }

        }
        $groups = array();
        foreach ($children as $child) {
            if (!isset($result[$child->nodeName])) {
                $result[$child->nodeName] = DOMtoArray($child);
            } else {
                if (!isset($groups[$child->nodeName])) {
                    $result[$child->nodeName] = array($result[$child->nodeName]);
                    $groups[$child->nodeName] = 1;
                }
                $result[$child->nodeName][] = DOMtoArray($child);
            }
        }
    }
    return $result;
}

$xml = '
    <aaaa Version="1.0">
       <bbb>
         <cccc>
           <dddd id="123" />
           <eeee name="john" age="24" />
           <ffff type="employee">Supervisor</ffff>
         </cccc>
       </bbb>
    </aaaa>
';
print_r(XMLtoArray($xml));

Array
(
    [aaaa] => Array
        (
            [@attributes] => Array
                (
                    [Version] => 1.0
                )

            [bbb] => Array
                (
                    [cccc] => Array
                        (
                            [dddd] => Array
                                (
                                    [@attributes] => Array
                                        (
                                            [id] => 123
                                        )

                                )

                            [eeee] => Array
                                (
                                    [@attributes] => Array
                                        (
                                            [name] => john
                                            [age] => 24
                                        )

                                )

                            [ffff] => Array
                                (
                                    [@attributes] => Array
                                        (
                                            [type] => employee
                                        )

                                    [_value] => Supervisor
                                )

                        )

                )

        )

)

Which is the correct C# infinite loop, for (;;) or while (true)?

while(true)
{

}

Is always what I've used and what I've seen others use for a loop that has to be broken manually.

How to convert date format to DD-MM-YYYY in C#

DateTime dt = DateTime.Now;

String.Format("{0:dd-MM-yyyy}", dt);

Android Button click go to another xml page

Change your FirstyActivity to:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn_go=(Button)findViewById(R.id.YOUR_BUTTON_ID);
            btn_go.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                  Log.i("clicks","You Clicked B1");
              Intent i=new Intent(
                     MainActivity.this,
                     MainActivity2.class);
              startActivity(i);
            }
        }
    });

}

Hope it will help you.

100% Min Height CSS layout

Try this:

body{ height: 100%; }
#content { 
    min-height: 500px;
    height: 100%;
}
#footer {
    height: 100px;
    clear: both !important;
}

The div element below the content div must have clear:both.

Rails 3 execute custom sql query without a model

I'd recommend using ActiveRecord::Base.connection.exec_query instead of ActiveRecord::Base.connection.execute which returns a ActiveRecord::Result (available in rails 3.1+) which is a bit easier to work with.

Then you can access it in various the result in various ways like .rows, .each, or .to_hash

From the docs:

result = ActiveRecord::Base.connection.exec_query('SELECT id, title, body FROM posts')
result # => #<ActiveRecord::Result:0xdeadbeef>


# Get the column names of the result:
result.columns
# => ["id", "title", "body"]

# Get the record values of the result:
result.rows
# => [[1, "title_1", "body_1"],
      [2, "title_2", "body_2"],
      ...
     ]

# Get an array of hashes representing the result (column => value):
result.to_hash
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
      {"id" => 2, "title" => "title_2", "body" => "body_2"},
      ...
     ]

# ActiveRecord::Result also includes Enumerable.
result.each do |row|
  puts row['title'] + " " + row['body']
end

note: copied my answer from here