Programs & Examples On #Jcrop

Jcrop is the quick and easy way to add image cropping functionality to your web application. It combines the ease-of-use of a typical jQuery plugin with a powerful cross-platform DHTML cropping engine that is faithful to familiar desktop graphics applications.

Cropping images in the browser BEFORE the upload

The Pixastic library does exactly what you want. However, it will only work on browsers that have canvas support. For those older browsers, you'll either need to:

  1. supply a server-side fallback, or
  2. tell the user that you're very sorry, but he'll need to get a more modern browser.

Of course, option #2 isn't very user-friendly. However, if your intent is to provide a pure client-only tool and/or you can't support a fallback back-end cropper (e.g. maybe you're writing a browser extension or offline Chrome app, or maybe you can't afford a decent hosting provider that provides image manipulation libraries), then it's probably fair to limit your user base to modern browsers.

EDIT: If you don't want to learn Pixastic, I have added a very simple cropper on jsFiddle here. It should be possible to modify and integrate and use the drawCroppedImage function with Jcrop.

Android Bluetooth Example

I have also used following link as others have suggested you for bluetooth communication.

http://developer.android.com/guide/topics/connectivity/bluetooth.html

The thing is all you need is a class BluetoothChatService.java

this class has following threads:

  1. Accept
  2. Connecting
  3. Connected

Now when you call start function of the BluetoothChatService like:

mChatService.start();

It starts accept thread which means it will start looking for connection.

Now when you call

mChatService.connect(<deviceObject>,false/true);

Here first argument is device object that you can get from paired devices list or when you scan for devices you will get all the devices in range you can pass that object to this function and 2nd argument is a boolean to make secure or insecure connection.

connect function will start connecting thread which will look for any device which is running accept thread.

When such a device is found both accept thread and connecting thread will call connected function in BluetoothChatService:

connected(mmSocket, mmDevice, mSocketType);

this method starts connected thread in both the devices: Using this socket object connected thread obtains the input and output stream to the other device. And calls read function on inputstream in a while loop so that it's always trying read from other device so that whenever other device send a message this read function returns that message.

BluetoothChatService also has a write method which takes byte[] as input and calls write method on connected thread.

mChatService.write("your message".getByte());

write method in connected thread just write this byte data to outputsream of the other device.

public void write(byte[] buffer) {
   try {
       mmOutStream.write(buffer);
    // Share the sent message back to the UI Activity
    // mHandler.obtainMessage(
    // BluetoothGameSetupActivity.MESSAGE_WRITE, -1, -1,
    // buffer).sendToTarget();
    } catch (IOException e) {
    Log.e(TAG, "Exception during write", e);
     }
}

Now to communicate between two devices just call write function on mChatService and handle the message that you will receive on the other device.

Converting String To Float in C#

You can double.Parse("41.00027357629127");

Convert UIImage to NSData and convert back to UIImage in Swift?

Use imageWithData: method, which gets translated to Swift as UIImage(data:)

let image : UIImage = UIImage(data: imageData)

Making interface implementations async

An abstract class can be used instead of an interface (in C# 7.3).

// Like interface
abstract class IIO
{
    public virtual async Task<string> DoOperation(string Name)
    {
        throw new NotImplementedException(); // throwing exception
        // return await Task.Run(() => { return ""; }); // or empty do
    }
}

// Implementation
class IOImplementation : IIO
{
    public override async Task<string> DoOperation(string Name)
    {
        return await await Task.Run(() =>
        {
            if(Name == "Spiderman")
                return "ok";
            return "cancel";
        }); 
    }
}

Undoing accidental git stash pop

From git stash --help

Recovering stashes that were cleared/dropped erroneously
   If you mistakenly drop or clear stashes, they cannot be recovered through the normal safety mechanisms. However, you can try the
   following incantation to get a list of stashes that are still in your repository, but not reachable any more:

       git fsck --unreachable |
       grep commit | cut -d\  -f3 |
       xargs git log --merges --no-walk --grep=WIP

This helped me better than the accepted answer with the same scenario.

Generate list of all possible permutations of a string

Recursive Solution with driver main() method.

public class AllPermutationsOfString {
public static void stringPermutations(String newstring, String remaining) {
    if(remaining.length()==0)
        System.out.println(newstring);

    for(int i=0; i<remaining.length(); i++) {
        String newRemaining = remaining.replaceFirst(remaining.charAt(i)+"", "");
        stringPermutations(newstring+remaining.charAt(i), newRemaining);
    }
}

public static void main(String[] args) {
    String string = "abc";
    AllPermutationsOfString.stringPermutations("", string); 
}

}

How to convert file to base64 in JavaScript?

Here are a couple functions I wrote to get a file in a json format which can be passed around easily:

    //takes an array of JavaScript File objects
    function getFiles(files) {
        return Promise.all(files.map(file => getFile(file)));
    }

    //take a single JavaScript File object
    function getFile(file) {
        var reader = new FileReader();
        return new Promise((resolve, reject) => {
            reader.onerror = () => { reader.abort(); reject(new Error("Error parsing file"));}
            reader.onload = function () {

                //This will result in an array that will be recognized by C#.NET WebApi as a byte[]
                let bytes = Array.from(new Uint8Array(this.result));

                //if you want the base64encoded file you would use the below line:
                let base64StringFile = btoa(bytes.map((item) => String.fromCharCode(item)).join(""));

                //Resolve the promise with your custom file structure
                resolve({ 
                    bytes: bytes,
                    base64StringFile: base64StringFile,
                    fileName: file.name, 
                    fileType: file.type
                });
            }
            reader.readAsArrayBuffer(file);
        });
    }

    //using the functions with your file:

    file = document.querySelector('#files > input[type="file"]').files[0]
    getFile(file).then((customJsonFile) => {
         //customJsonFile is your newly constructed file.
         console.log(customJsonFile);
    });

    //if you are in an environment where async/await is supported

    files = document.querySelector('#files > input[type="file"]').files
    let customJsonFiles = await getFiles(files);
    //customJsonFiles is an array of your custom files
    console.log(customJsonFiles);

Remove Last Comma from a string

The greatly upvoted answer removes not only the final comma, but also any spaces that follow. But removing those following spaces was not what was part of the original problem. So:

let str = 'abc,def,ghi, ';
let str2 = str.replace(/,(?=\s*$)/, '');
alert("'" + str2 + "'");
'abc,def,ghi '

https://jsfiddle.net/dc8moa3k/

Discard all and get clean copy of latest revision?

To delete untracked on *nix without the purge extension you can use

hg pull
hg update -r MY_BRANCH -C
hg status -un|xargs rm

Which is using

update -r --rev REV revision

update -C --clean discard uncommitted changes (no backup)

status -u --unknown show only unknown (not tracked) files

status -n --no-status hide status prefix

Select DataFrame rows between two dates

With my testing of pandas version 0.22.0 you can now answer this question easier with more readable code by simply using between.

# create a single column DataFrame with dates going from Jan 1st 2018 to Jan 1st 2019
df = pd.DataFrame({'dates':pd.date_range('2018-01-01','2019-01-01')})

Let's say you want to grab the dates between Nov 27th 2018 and Jan 15th 2019:

# use the between statement to get a boolean mask
df['dates'].between('2018-11-27','2019-01-15', inclusive=False)

0    False
1    False
2    False
3    False
4    False

# you can pass this boolean mask straight to loc
df.loc[df['dates'].between('2018-11-27','2019-01-15', inclusive=False)]

    dates
331 2018-11-28
332 2018-11-29
333 2018-11-30
334 2018-12-01
335 2018-12-02

Notice the inclusive argument. very helpful when you want to be explicit about your range. notice when set to True we return Nov 27th of 2018 as well:

df.loc[df['dates'].between('2018-11-27','2019-01-15', inclusive=True)]

    dates
330 2018-11-27
331 2018-11-28
332 2018-11-29
333 2018-11-30
334 2018-12-01

This method is also faster than the previously mentioned isin method:

%%timeit -n 5
df.loc[df['dates'].between('2018-11-27','2019-01-15', inclusive=True)]
868 µs ± 164 µs per loop (mean ± std. dev. of 7 runs, 5 loops each)


%%timeit -n 5

df.loc[df['dates'].isin(pd.date_range('2018-01-01','2019-01-01'))]
1.53 ms ± 305 µs per loop (mean ± std. dev. of 7 runs, 5 loops each)

However, it is not faster than the currently accepted answer, provided by unutbu, only if the mask is already created. but if the mask is dynamic and needs to be reassigned over and over, my method may be more efficient:

# already create the mask THEN time the function

start_date = dt.datetime(2018,11,27)
end_date = dt.datetime(2019,1,15)
mask = (df['dates'] > start_date) & (df['dates'] <= end_date)

%%timeit -n 5
df.loc[mask]
191 µs ± 28.5 µs per loop (mean ± std. dev. of 7 runs, 5 loops each)

How do I check if the user is pressing a key?

In java you don't check if a key is pressed, instead you listen to KeyEvents. The right way to achieve your goal is to register a KeyEventDispatcher, and implement it to maintain the state of the desired key:

import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;

public class IsKeyPressed {
    private static volatile boolean wPressed = false;
    public static boolean isWPressed() {
        synchronized (IsKeyPressed.class) {
            return wPressed;
        }
    }

    public static void main(String[] args) {
        KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {

            @Override
            public boolean dispatchKeyEvent(KeyEvent ke) {
                synchronized (IsKeyPressed.class) {
                    switch (ke.getID()) {
                    case KeyEvent.KEY_PRESSED:
                        if (ke.getKeyCode() == KeyEvent.VK_W) {
                            wPressed = true;
                        }
                        break;

                    case KeyEvent.KEY_RELEASED:
                        if (ke.getKeyCode() == KeyEvent.VK_W) {
                            wPressed = false;
                        }
                        break;
                    }
                    return false;
                }
            }
        });
    }
}

Then you can always use:

if (IsKeyPressed.isWPressed()) {
    // do your thing.
}

You can, of course, use same method to implement isPressing("<some key>") with a map of keys and their state wrapped inside IsKeyPressed.

How to determine the version of Gradle?

Check in the folder structure of the project the files within the /gradle/wrapper/ The gradle-wrapper.jar version should be the one specified in the gradle-wrapper.properties

Need to remove href values when printing in Chrome

It doesn't. Somewhere in your print stylesheet, you must have this section of code:

a[href]::after {
    content: " (" attr(href) ")"
}

The only other possibility is you have an extension doing it for you.

IIS - can't access page by ip address instead of localhost

The IIS is a multi web site server. The way is distinct the site is by the host header name. So you need to setup that on your web site.

Here is the steps that you need to follow:

How to configure multiple IIS websites to access using host headers?

In general, open your web site properties, locate the Ip Address and near its there is the advanced, "multiple identities for this web site". There you need ether to add all income to this site with a star: "*", ether place the names you like to work with.

What is the best way to access redux store outside a react component?

Found a solution. So I import the store in my api util and subscribe to it there. And in that listener function I set the axios' global defaults with my newly fetched token.

This is what my new api.js looks like:

// tooling modules
import axios from 'axios'

// store
import store from '../store'
store.subscribe(listener)

function select(state) {
  return state.auth.tokens.authentication_token
}

function listener() {
  let token = select(store.getState())
  axios.defaults.headers.common['Authorization'] = token;
}

// configuration
const api = axios.create({
  baseURL: 'http://localhost:5001/api/v1',
  headers: {
    'Content-Type': 'application/json',
  }
})

export default api

Maybe it can be further improved, cause currently it seems a bit inelegant. What I could do later is add a middleware to my store and set the token then and there.

Why should text files end with a newline?

Why should (text) files end with a newline?

As well expressed by many, because:

  1. Many programs do not behave well, or fail without it.

  2. Even programs that well handle a file lack an ending '\n', the tool's functionality may not meet the user's expectations - which can be unclear in this corner case.

  3. Programs rarely disallow final '\n' (I do not know of any).


Yet this begs the next question:

What should code do about text files without a newline?

  1. Most important - Do not write code that assumes a text file ends with a newline. Assuming a file conforms to a format leads to data corruption, hacker attacks and crashes. Example:

    // Bad code
    while (fgets(buf, sizeof buf, instream)) {
      // What happens if there is no \n, buf[] is truncated leading to who knows what
      buf[strlen(buf) - 1] = '\0';  // attempt to rid trailing \n
      ...
    }
    
  2. If the final trailing '\n' is needed, alert the user to its absence and the action taken. IOWs, validate the file's format. Note: This may include a limit to the maximum line length, character encoding, etc.

  3. Define clearly, document, the code's handling of a missing final '\n'.

  4. Do not, as possible, generate a file the lacks the ending '\n'.

how to display toolbox on the left side of window of Visual Studio Express for windows phone 7 development?

In Visual Studio Express 2013 for web it's hidden away in View > Other Windows > Toolbox.

XmlWriter to Write to a String Instead of to a File

Use StringBuilder:

var sb = new StringBuilder();
    using (XmlWriter xmlWriter = XmlWriter.Create(sb))
    {
        ...
    }
return sb.ToString();

Google Maps V3 - How to calculate the zoom level for a given bounds

Thanks, that helped me a lot in finding the most suitable zoom factor to correctly display a polyline. I find the maximum and minimum coordinates among the points I have to track and, in case the path is very "vertical", I just added few lines of code:

var GLOBE_WIDTH = 256; // a constant in Google's map projection
var west = <?php echo $minLng; ?>;
var east = <?php echo $maxLng; ?>;
*var north = <?php echo $maxLat; ?>;*
*var south = <?php echo $minLat; ?>;*
var angle = east - west;
if (angle < 0) {
    angle += 360;
}
*var angle2 = north - south;*
*if (angle2 > angle) angle = angle2;*
var zoomfactor = Math.round(Math.log(960 * 360 / angle / GLOBE_WIDTH) / Math.LN2);

Actually, the ideal zoom factor is zoomfactor-1.

Running EXE with parameters

To start the process with parameters, you can use following code:

string filename = Path.Combine(cPath,"HHTCtrlp.exe");
var proc = System.Diagnostics.Process.Start(filename, cParams);

To kill/exit the program again, you can use following code:

proc.CloseMainWindow(); 
proc.Close();

Get parent directory of running script

Got it myself, it's a bit kludgy but it works:

substr(dirname($_SERVER['SCRIPT_NAME']), 0, strrpos(dirname($_SERVER['SCRIPT_NAME']), '/') + 1)

So if I have /path/to/folder/index.php, this results in /path/to/.

Can I change the headers of the HTTP request sent by the browser?

Use some javascript!

xmlhttp=new XMLHttpRequest();
xmlhttp.open('PUT',http://www.mydomain.org/documents/standards/browsers/supportlist)
xmlhttp.send("page content goes here");

Why does ++[[]][+[]]+[+[]] return the string "10"?

Perhaps the shortest possible ways to evaluate an expression into "10" without digits are:

+!+[] + [+[]] // "10"

-~[] + [+[]] // "10"

//========== Explanation ==========\\

+!+[] : +[] Converts to 0. !0 converts to true. +true converts to 1. -~[] = -(-1) which is 1

[+[]] : +[] Converts to 0. [0] is an array with a single element 0.

Then JS evaluates the 1 + [0], thus Number + Array expression. Then the ECMA specification works: + operator converts both operands to a string by calling the toString()/valueOf() functions from the base Object prototype. It operates as an additive function if both operands of an expression are numbers only. The trick is that arrays easily convert their elements into a concatenated string representation.

Some examples:

1 + {} //    "1[object Object]"
1 + [] //    "1"
1 + new Date() //    "1Wed Jun 19 2013 12:13:25 GMT+0400 (Caucasus Standard Time)"

There's a nice exception that two Objects addition results in NaN:

[] + []   //    ""
[1] + [2] //    "12"
{} + {}   //    NaN
{a:1} + {b:2}     //    NaN
[1, {}] + [2, {}] //    "1,[object Object]2,[object Object]"

Is it possible to ignore one single specific line with Pylint?

import config.logging_settings # pylint: disable=W0611

That was simple and is specific for that line.

You can and should use the more readable form:

import config.logging_settings # pylint: disable=unused-import

How to set Oracle's Java as the default Java in Ubuntu?

If you're doing any sort of development you need to point to the JDK (Java Development Kit). Otherwise, you can point to the JRE (Java Runtime Environment).

The JDK contains everything the JRE has and more. If you're just executing Java programs, you can point to either the JRE or the JDK.

You should set JAVA_HOME based on current Java you are using. readlink will print value of a symbolic link for current Java and sed will adjust it to JRE directory:

export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")

If you want to set up JAVA_HOME to JDK you should go up one folder more:

export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:jre/bin/java::")

Checking if a file is a directory or just a file

Normally you want to perform this check atomically with using the result, so stat() is useless. Instead, open() the file read-only first and use fstat(). If it's a directory, you can then use fdopendir() to read it. Or you can try opening it for writing to begin with, and the open will fail if it's a directory. Some systems (POSIX 2008, Linux) also have an O_DIRECTORY extension to open which makes the call fail if the name is not a directory.

Your method with opendir() is also good if you want a directory, but you should not close it afterwards; you should go ahead and use it.

How to sort an STL vector?

Like explained in other answers you need to provide a comparison function. If you would like to keep the definition of that function close to the sort call (e.g. if it only makes sense for this sort) you can define it right there with boost::lambda. Use boost::lambda::bind to call the member function.

To e.g. sort by member variable or function data1:

#include <algorithm>
#include <vector>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/lambda.hpp>
using boost::lambda::bind;
using boost::lambda::_1;
using boost::lambda::_2;

std::vector<myclass> object(10000);
std::sort(object.begin(), object.end(),
    bind(&myclass::data1, _1) < bind(&myclass::data1, _2));

How do I get LaTeX to hyphenate a word that contains a dash?

multi\hskip0pt-\hskip0pt disciplinary

You can e.g. define like

\def\:{\hskip0pt}

and then write

multi\:-\:disciplinary

Note that the babel Russian language package has its own set of dashes that do not prohibit hyphenation, "~ (double quotation+tilde) for example.

Creating a BAT file for python script

start xxx.py

You can use this for some other file types.

YouTube API to fetch all videos on a channel

Here is the code that will return all video ids under your channel

<?php 
    $baseUrl = 'https://www.googleapis.com/youtube/v3/';
    // https://developers.google.com/youtube/v3/getting-started
    $apiKey = 'API_KEY';
    // If you don't know the channel ID see below
    $channelId = 'CHANNEL_ID';

    $params = [
        'id'=> $channelId,
        'part'=> 'contentDetails',
        'key'=> $apiKey
    ];
    $url = $baseUrl . 'channels?' . http_build_query($params);
    $json = json_decode(file_get_contents($url), true);

    $playlist = $json['items'][0]['contentDetails']['relatedPlaylists']['uploads'];

    $params = [
        'part'=> 'snippet',
        'playlistId' => $playlist,
        'maxResults'=> '50',
        'key'=> $apiKey
    ];
    $url = $baseUrl . 'playlistItems?' . http_build_query($params);
    $json = json_decode(file_get_contents($url), true);

    $videos = [];
    foreach($json['items'] as $video)
        $videos[] = $video['snippet']['resourceId']['videoId'];

    while(isset($json['nextPageToken'])){
        $nextUrl = $url . '&pageToken=' . $json['nextPageToken'];
        $json = json_decode(file_get_contents($nextUrl), true);
        foreach($json['items'] as $video)
            $videos[] = $video['snippet']['resourceId']['videoId'];
    }
    print_r($videos);

Note: You can get channel id at https://www.youtube.com/account_advanced after logged in.

angularjs - ng-repeat: access key and value from JSON array object

Solution I have json object which has data

[{"name":"Ata","email":"[email protected]"}]

You can use following approach to iterate through ng-repeat and use table format instead of list.

<div class="container" ng-controller="fetchdataCtrl">    
  <ul ng-repeat="item in numbers">
    <li>            
      {{item.name}}: {{item.email}}
    </li>
  </ul>     
</div>

No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'

I know this is an older question, but I felt the answer from t3chb0t led me to the best path and felt like sharing. You don't even need to go so far as implementing all the formatter's methods. I did the following for the content-type "application/vnd.api+json" being returned by an API I was using:

public class VndApiJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
    public VndApiJsonMediaTypeFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/vnd.api+json"));
    }
}

Which can be used simply like the following:

HttpClient httpClient = new HttpClient("http://api.someaddress.com/");
HttpResponseMessage response = await httpClient.GetAsync("person");

List<System.Net.Http.Formatting.MediaTypeFormatter> formatters = new List<System.Net.Http.Formatting.MediaTypeFormatter>();
formatters.Add(new System.Net.Http.Formatting.JsonMediaTypeFormatter());
formatters.Add(new VndApiJsonMediaTypeFormatter());

var responseObject = await response.Content.ReadAsAsync<Person>(formatters);

Super simple and works exactly as I expected.

Determine the size of an InputStream

you can get the size of InputStream using getBytes(inputStream) of Utils.java check this following link

Get Bytes from Inputstream

String split on new line, tab and some number of spaces

You can use this

string.strip().split(":")

Get json value from response

var results = {"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}
console.log(results.id)
=>2231f87c-a62c-4c2c-8f5d-b76d11942301

results is now an object.

Difference between Activity Context and Application Context

The reason I think is that ProgressDialog is attached to the activity that props up the ProgressDialog as the dialog cannot remain after the activity gets destroyed so it needs to be passed this(ActivityContext) that also gets destroyed with the activity whereas the ApplicationContext remains even after the activity gets destroyed.

Change SVN repository URL

If you are using TortoiseSVN client then you can follow the below steps

Right-click in the source directory and then click on SVN Relocate Image#1

After that, you need to change the URL to what you want, click ok, it will be taking a few seconds.Image#2

jQuery if Element has an ID?

Like this:

var $aWithId = $('.parent a[id]');

Following OP's comment, test it like this:

if($aWithId.length) //or without using variable: if ($('.parent a[id]').length)

Will return all anchor tags inside elements with class parent which have an attribute ID specified

Xcode 6.1 - How to uninstall command line tools?

You can simply delete this folder

/Library/Developer/CommandLineTools

Please note: This is the root /Library, not user's ~/Library).

Using malloc for allocation of multi-dimensional arrays with different row lengths

First, you need to allocate array of pointers like char **c = malloc( N * sizeof( char* )), then allocate each row with a separate call to malloc, probably in the loop:


/* N is the number of rows  */
/* note: c is char** */
if (( c = malloc( N*sizeof( char* ))) == NULL )
{ /* error */ }

for ( i = 0; i < N; i++ )
{
  /* x_i here is the size of given row, no need to
   * multiply by sizeof( char ), it's always 1
   */
  if (( c[i] = malloc( x_i )) == NULL )
  { /* error */ }

  /* probably init the row here */
}

/* access matrix elements: c[i] give you a pointer
 * to the row array, c[i][j] indexes an element
 */
c[i][j] = 'a';

If you know the total number of elements (e.g. N*M) you can do this in a single allocation.

How can I pull from remote Git repository and override the changes in my local repository?

Provided that the remote repository is origin, and that you're interested in master:

git fetch origin
git reset --hard origin/master

This tells it to fetch the commits from the remote repository, and position your working copy to the tip of its master branch.

All your local commits not common to the remote will be gone.

cURL not working (Error #77) for SSL connections on CentOS for non-root users

Turns out that the problem was with face that the script was running from a cPanel "email piped to script", so was running as the user, so is was a user problem, but was not affecting the web server at all.

The cause for the user not being able to access the /etc/pki directory was due to them only having jailed ssh access. Once I granted full access, it all worked fine.

Thanks for the info though, Remi.

CSS way to horizontally align table

This should work:

<div style="text-align:center;">
  <table style="margin: 0 auto;">
    <!-- table markup here. -->
  </table>
</div>

How do I run a Python program?

I have tried many of the commands listed above, however none worked, even after setting my path to include the directory where I installed Python.

The command py -3 file.py always works for me, and if I want to run Python 2 code, as long as Python 2 is in my path, just changing the command to py -2 file.py works perfectly.

I am using Windows, so I'm not too sure if this command will work on Linux, or Mac, but it's worth a try.

ImportError: No module named sklearn.cross_validation

train_test_split is part of the module sklearn.model_selection, hence, you may need to import the module from model_selection

Code:

from sklearn.model_selection import train_test_split

Check if all elements in a list are identical

You can convert the list to a set. A set cannot have duplicates. So if all the elements in the original list are identical, the set will have just one element.

if len(set(input_list)) == 1:
    # input_list has all identical elements.

System.Data.SqlClient.SqlException: Invalid object name 'dbo.Projects'

I have tried almost all the answers from below list, but did not work for me. But read the exception well and then tried rename my Dbset name TransactionsModel to Transactions and it work for me.

old Code:

public class MyContext : DbContext
    {
        //....
        public DbSet<Models.TransactionsModel> TransactionsModel { get; set; }
    }

New Code:

public class MyContext : DbContext
    {
        //....
        public DbSet<Models.TransactionsModel> Transactions { get; set; }
    }

Java ResultSet how to check if there are any results

According to the most viable answer the suggestion is to use "isBeforeFirst()". That's not the best solution if you don't have a "forward only type".

There's a method called ".first()". It's less overkill to get the exact same result. You check whether there is something in your "resultset" and don't advance your cursor.

The documentation states: "(...) false if there are no rows in the result set".

if(rs.first()){
    //do stuff      
}

You can also just call isBeforeFirst() to test if there are any rows returned without advancing the cursor, then proceed normally. – SnakeDoc Sep 2 '14 at 19:00

However, there's a difference between "isBeforeFirst()" and "first()". First generates an exception if done on a resultset from type "forward only".

Compare the two throw sections: http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#isBeforeFirst() http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#first()

Okay, basically this means that you should use "isBeforeFirst" as long as you have a "forward only" type. Otherwise it's less overkill to use "first()".

Force drop mysql bypassing foreign key constraint

Drop database exist in all versions of MySQL. But if you want to keep the table structure, here is an idea

mysqldump --no-data --add-drop-database --add-drop-table -hHOSTNAME -uUSERNAME -p > dump.sql

This is a program, not a mysql command

Then, log into mysql and

source dump.sql;

Drop-down menu that opens up/upward with pure css

Add bottom:100% to your #menu:hover ul li:hover ul rule

Demo 1

#menu:hover ul li:hover ul {
    position: absolute;
    margin-top: 1px;
    font: 10px;
    bottom: 100%; /* added this attribute */
}

Or better yet to prevent the submenus from having the same effect, just add this rule

Demo 2

#menu>ul>li:hover>ul { 
    bottom:100%;
}

Demo 3

source: http://jsfiddle.net/W5FWW/4/

And to get back the border you can add the following attribute

#menu>ul>li:hover>ul { 
    bottom:100%;
    border-bottom: 1px solid transparent
}

How can I get a uitableViewCell by indexPath?

Here is a code to get custom cell from index path

 NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:0];
 YourCell *cell = (YourCell *)[tblRegister cellForRowAtIndexPath:indexPath];

For Swift

let indexpath = NSIndexPath(forRow: 2, inSection: 0)
let currentCell = tblTest.cellForRowAtIndexPath(indexpath) as! CellTest

For Swift 4 (for collectionview)

let indexpath = NSIndexPath(row: 2, section: 0)
let cell = self.colVw!.cellForItem(at: indexpath as IndexPath) as? ColViewCell

Resolving a Git conflict with binary files

I've come across two strategies for managing diff/merge of binary files with Git on windows.

  1. Tortoise git lets you configure diff/merge tools for different file types based on their file extensions. See 2.35.4.3. Diff/Merge Advanced Settings http://tortoisegit.org/docs/tortoisegit/tgit-dug-settings.html. This strategy of course relys on suitable diff/merge tools being available.

  2. Using git attributes you can specify a tool/command to convert your binary file to text and then let your default diff/merge tool do it's thing. See http://git-scm.com/book/it/v2/Customizing-Git-Git-Attributes. The article even gives an example of using meta data to diff images.

I got both strategies to work with binary files of software models, but we went with tortoise git as the configuration was easy.

Switch case with conditions

Something I came upon while trying to work a spinner was to allow for flexibility within the script without the use of a ton of if statements.

Since this is a simpler solution than iterating through an array to check for a single instance of a class present it keeps the script cleaner. Any suggestions for cleaning the code further are welcome.

$('.next').click(function(){
        var imageToSlide = $('#imageSprite'); // Get id of image

        switch(true) {
            case (imageToSlide.hasClass('pos1')):
                imageToSlide.removeClass('pos1').addClass('pos2');
                break;
            case (imageToSlide.hasClass('pos2')):
                imageToSlide.removeClass('pos2').addClass('pos3');
                break;
            case (imageToSlide.hasClass('pos3')):
                imageToSlide.removeClass('pos3').addClass('pos4');
                break;
            case (imageToSlide.hasClass('pos4')):
                imageToSlide.removeClass('pos4').addClass('pos1');
        }
    }); ` 

How to perform a for-each loop over all the files under a specified path?

Here is a better way to loop over files as it handles spaces and newlines in file names:

#!/bin/bash

find . -type f -iname "*.txt" -print0 | while IFS= read -r -d $'\0' line; do
    echo "$line"
    ls -l "$line"    
done

javax.persistence.NoResultException: No entity found for query

When using java 8, you may take advantage of stream API and simplify code to

return (YourEntityClass) entityManager.createQuery()
....
.getResultList()
.stream().findFirst();

That will give you java.util.Optional

If you prefer null instead, all you need is

 ...
.getResultList()
.stream().findFirst().orElse(null);

Dump all tables in CSV format using 'mysqldump'

First, I can give you the answer for one table:

The trouble with all these INTO OUTFILE or --tab=tmpfile (and -T/path/to/directory) answers is that it requires running mysqldump on the same server as the MySQL server, and having those access rights.

My solution was simply to use mysql (not mysqldump) with the -B parameter, inline the SELECT statement with -e, then massage the ASCII output with sed, and wind up with CSV including a header field row:

Example:

 mysql -B -u username -p password database -h dbhost -e "SELECT * FROM accounts;" \
 | sed "s/\"/\"\"/g;s/'/\'/;s/\t/\",\"/g;s/^/\"/;s/$/\"/;s/\n//g"

"id","login","password","folder","email" "8","mariana","xxxxxxxxxx","mariana","" "3","squaredesign","xxxxxxxxxxxxxxxxx","squaredesign","[email protected]" "4","miedziak","xxxxxxxxxx","miedziak","[email protected]" "5","Sarko","xxxxxxxxx","Sarko","" "6","Logitrans Poland","xxxxxxxxxxxxxx","LogitransPoland","" "7","Amos","xxxxxxxxxxxxxxxxxxxx","Amos","" "9","Annabelle","xxxxxxxxxxxxxxxx","Annabelle","" "11","Brandfathers and Sons","xxxxxxxxxxxxxxxxx","BrandfathersAndSons","" "12","Imagine Group","xxxxxxxxxxxxxxxx","ImagineGroup","" "13","EduSquare.pl","xxxxxxxxxxxxxxxxx","EduSquare.pl","" "101","tmp","xxxxxxxxxxxxxxxxxxxxx","_","[email protected]"

Add a > outfile.csv at the end of that one-liner, to get your CSV file for that table.

Next, get a list of all your tables with

mysql -u username -ppassword dbname -sN -e "SHOW TABLES;"

From there, it's only one more step to make a loop, for example, in the Bash shell to iterate over those tables:

 for tb in $(mysql -u username -ppassword dbname -sN -e "SHOW TABLES;"); do
     echo .....;
 done

Between the do and ; done insert the long command I wrote in Part 1 above, but substitute your tablename with $tb instead.

How to make a deep copy of Java ArrayList

public class Person{

    String s;
    Date d;
    ...

    public Person clone(){
        Person p = new Person();
        p.s = this.s.clone();
        p.d = this.d.clone();
        ...
        return p;
    }
}

In your executing code:

ArrayList<Person> clone = new ArrayList<Person>();
for(Person p : originalList)
    clone.add(p.clone());

SQL Server 2012 can't start because of a login failure

I had a similar issue that was resolved with the following:

  1. In Services.MSC click on the Log On tab and add the user with minimum privileges and password (on the service that is throwing the login error)
  2. By Starting Sql Server to run as Administrator

If the user is a domain user use Domain username and password

How to link 2 cell of excel sheet?

Just follow these Steps :

If you want the contents of, say, C1 to mirror the contents of cell A1, you just need to set the formula in C1 to =A1. From this point forward, anything you type in A1 will show up in C1 as well.

To Link Multiple Cells in Excel From Another Worksheet :

Step 1

Click the worksheet tab at the bottom of the screen that contains a range of precedent cells to which you want to link. A range is a block or group of adjacent cells. For example, assume you want to link a range of blank cells in “Sheet1” to a range of precedent cells in “Sheet2.” Click the “Sheet2” tab.

Step 2

Determine the precedent range’s width in columns and height in rows. In this example, assume cells A1 through A4 on “Sheet2” contain a list of numbers 1, 2, 3 and 4, respectively, which will be your precedent cells. This precedent range is one column wide by four rows high.

Step 3

Click the worksheet tab at the bottom of the screen that contains the blank cells in which you will insert a link. In this example, click the “Sheet1” tab.

Step 4

Select the range of blank cells you want to link to the precedent cells. This range must be the same size as the precedent range, but can be in a different location on the worksheet. Click and hold the mouse button on the top left cell of the range, drag the mouse cursor to the bottom right cell in the range and release the mouse button to select the range. In this example, assume you want to link cells C1 through C4 to the precedent range. Click and hold on cell C1, drag the mouse to cell C4 and release the mouse to highlight the range.

Step 5

Type “=,” the worksheet name containing the precedent cells, “!,” the top left cell of the precedent range, “:” and the bottom right cell of the precedent range. Press “Ctrl,” “Shift” and “Enter” simultaneously to complete the array formula. Each dependent cell is now linked to the cell in the precedent range that’s in the same respective location within the range. In this example, type “=Sheet2!A1:A4” and press “Ctrl,” “Shift” and “Enter” simultaneously. Cells C1 through C4 on “Sheet1” now contain the array formula “{=Sheet2!A1:A4}” surrounded by curly brackets, and show the same data as the precedent cells in “Sheet2.”

Good Luck !!!

Where can I find the assembly System.Web.Extensions dll?

I had this problem myself. Most of the information I could find online was related to people having this problem with an ASP.NET web application. I was creating a Win Forms stand alone app so most of the advice wasn't helpful for me.

Turns out that the problem was that my project was set to use the ".NET 4 Framework Client Profile" as the target framework and the System.Web.Extensions reference was not in the list for adding. I changed the target to ".NET 4 Framework" and then the reference was available by the normal methods.

Here is what worked for me step by step:

  1. Right Click you project Select Properties
  2. Change your Target Framework to ".NET Framework 4"
  3. Do whatever you need to do to save the changes and close the preferences tab
  4. Right click on the References item in your Solution Explorer
  5. Choose Add Reference...
  6. In the .NET tab, scroll down to System.Web.Extensions and add it.

printf format specifiers for uint32_t and size_t

If you don't want to use the PRI* macros, another approach for printing ANY integer type is to cast to intmax_t or uintmax_t and use "%jd" or %ju, respectively. This is especially useful for POSIX (or other OS) types that don't have PRI* macros defined, for instance off_t.

How can I access global variable inside class in Python

class flag:
    ## Store pseudo-global variables here

    keys=False

    sword=True

    torch=False


## test the flag class

print('______________________')

print(flag.keys)
print(flag.sword)
print (flag.torch)


## now change the variables

flag.keys=True
flag.sword= not flag.sword
flag.torch=True

print('______________________')

print(flag.keys)
print(flag.sword)
print (flag.torch)

adb connection over tcp not working now

Thanks to sud007 for this answer. In my case, I only need this part of the solution:

In CMD/Terminal:

$ adb kill-server

$ adb tcpip 5555
restarting in TCP mode port: 5555

$ adb connect 192.168.XXX.XXX

This bug brings more errors than unable to connect to 192.168.XXX.XXX:5555: Connection refused. In my case, I could connect to the device, but when you try to run the app. AndroidStudio stay in Installing APK forever. In this case, I needed to restart the phone too.

Add a list item through javascript

The above answer was helpful for me, but it might be useful (or best practice) to add the name on submit, as I wound up doing. Hopefully this will be helpful to someone. CodePen Sample

    <form id="formAddName">
      <fieldset>
        <legend>Add Name </legend>
            <label for="firstName">First Name</label>
            <input type="text" id="firstName" name="firstName" />

        <button>Add</button>
      </fieldset>
    </form>

      <ol id="demo"></ol>

<script>
    var list = document.getElementById('demo');
    var entry = document.getElementById('formAddName');
    entry.onsubmit = function(evt) {
    evt.preventDefault();
    var firstName = document.getElementById('firstName').value;
    var entry = document.createElement('li');
    entry.appendChild(document.createTextNode(firstName));
    list.appendChild(entry);
  }
</script>

How do I change file permissions in Ubuntu

So that you don't mess up other permissions already on the file, use the flag +, such as via

sudo chmod -R o+rw /var/www

django no such table:

Updated answer for Django migrations without south plugin:

Like T.T suggested in his answer, my previous answer was for south migration plugin, when Django hasn't any schema migration features. Now (works in Django 1.9+):

T.T wrote:

You can try this!

python manage.py makemigrations

python manage.py migrate --run-syncdb

Outdated for south migrations plugin

As I can see you done it all in wrong order, to fix it up your should complete this checklist (I assume you can't delete sqlite3 database file to start over):

  1. Grab any SQLite GUI tool (i.e. http://sqliteadmin.orbmu2k.de/)
  2. Change your model definition to match database definition (best approach is to comment new fields)
  3. Delete migrations folder in your model
  4. Delete rows in south_migrationhistory table where app_name match your application name (probably homework)
  5. Invoke: ./manage.py schemamigration <app_name> --initial
  6. Create tables by ./manage.py migrate <app_name> --fake (--fake will skip SQL execute because table already exists in your database)
  7. Make changes to your app's model
  8. Invoke ./manage.py schemamigration <app_name> --auto
  9. Then apply changes to database: ./manage.py migrate <app_name>

Steps 7,8,9 repeat whenever your model needs any changes.

Error: fix the version conflict (google-services plugin)

Same error gets thrown when

apply plugin: 'com.google.gms.google-services'

is not added to bottom of the module build.gradle file.

How to configure a HTTP proxy for svn

In windows 7, you may have to edit this file

C:\Users\<UserName>\AppData\Roaming\Subversion\servers

[global]
http-proxy-host = ip.add.re.ss
http-proxy-port = 3128

Bootstrap combining rows (rowspan)

Paul's answer seems to defeat the purpose of bootstrap; that of being responsive to the viewport / screen size.

By nesting rows and columns you can achieve the same result, while retaining responsiveness.

Here is an up-to-date response to this problem;

_x000D_
_x000D_
<div class="container-fluid">_x000D_
  <h1>  Responsive Nested Bootstrap </h1> _x000D_
  <div class="row">_x000D_
    <div class="col-md-5" style="background-color:red;">Span 5</div>_x000D_
    <div class="col-md-3" style="background-color:blue;">Span 3</div>_x000D_
    <div class="col-md-2">_x000D_
      <div class="row">_x000D_
        <div class="container" style="background-color:green;">Span 2</div>_x000D_
      </div>_x000D_
      <div class="row">_x000D_
        <div class="container" style="background-color:purple;">Span 2</div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="col-md-2" style="background-color:yellow;">Span 2</div>_x000D_
  </div>_x000D_
  _x000D_
  <div class="row">_x000D_
    <div class="col-md-6">_x000D_
      <div class="row">_x000D_
        <div class="container" style="background-color:yellow;">Span 6</div>_x000D_
      </div>_x000D_
      <div class="row">_x000D_
        <div class="container" style="background-color:green;">Span 6</div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="col-md-6" style="background-color:red;">Span 6</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can view the codepen here.

How to print a dictionary line by line in Python?

# Declare and Initialize Map
map = {}

map ["New"] = 1
map ["to"] = 1
map ["Python"] = 5
map ["or"] = 2

# Print Statement
for i in map:
  print ("", i, ":", map[i])

#  New : 1
#  to : 1
#  Python : 5
#  or : 2

How to map and remove nil values in Ruby

Definitely compact is the best approach for solving this task. However, we can achieve the same result just with a simple subtraction:

[1, nil, 3, nil, nil] - [nil]
 => [1, 3]

Unable to open a file with fopen()

Well, now you know there is a problem, the next step is to figure out what exactly the error is, what happens when you compile and run this?:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    FILE *file;
    file = fopen("TestFile1.txt", "r");
    if (file == NULL) {
      perror("Error");
    } else {
      fclose(file);
    }
}

How to find the lowest common ancestor of two nodes in any binary tree?

public class LeastCommonAncestor {

    private TreeNode root;

    private static class TreeNode {
        TreeNode left;
        TreeNode right;
        int item;

        TreeNode (TreeNode left, TreeNode right, int item) {
            this.left = left;
            this.right = right;
            this.item = item;
        }
    }

    public void createBinaryTree (Integer[] arr) {
        if (arr == null)  {
            throw new NullPointerException("The input array is null.");
        }

        root = new TreeNode(null, null, arr[0]);

        final Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);

        final int half = arr.length / 2;

        for (int i = 0; i < half; i++) {
            if (arr[i] != null) {
                final TreeNode current = queue.poll();
                final int left = 2 * i + 1;
                final int right = 2 * i + 2;

                if (arr[left] != null) {
                    current.left = new TreeNode(null, null, arr[left]);
                    queue.add(current.left);
                }
                if (right < arr.length && arr[right] != null) {
                    current.right = new TreeNode(null, null, arr[right]);
                    queue.add(current.right);
                }
            }
        }
    }

    private static class LCAData {
        TreeNode lca;
        int count;

        public LCAData(TreeNode parent, int count) {
            this.lca = parent;
            this.count = count;
        }
    }


    public int leastCommonAncestor(int n1, int n2) {
        if (root == null) {
            throw new NoSuchElementException("The tree is empty.");
        }

        LCAData lcaData = new LCAData(null, 0);
       // foundMatch (root, lcaData, n1,  n2);

        /**
         * QQ: boolean was returned but never used by caller.
         */
        foundMatchAndDuplicate (root, lcaData, n1,  n2, new HashSet<Integer>());

        if (lcaData.lca != null) {
            return lcaData.lca.item;
        } else {
            /**
             * QQ: Illegal thrown after processing function.
             */
            throw new IllegalArgumentException("The tree does not contain either one or more of input data. ");
        }
    }

//    /**
//     * Duplicate n1, n1         Duplicate in Tree
//     *      x                           x               => succeeds
//     *      x                           1               => fails.
//     *      1                           x               => succeeds by throwing exception
//     *      1                           1               => succeeds
//     */
//    private boolean foundMatch (TreeNode node, LCAData lcaData, int n1, int n2) {
//        if (node == null) {
//            return false;
//        }
//
//        if (lcaData.count == 2) {
//            return false;
//        }
//
//        if ((node.item == n1 || node.item == n2) && lcaData.count == 1) {
//            lcaData.count++;
//            return true;
//        }
//
//        boolean foundInCurrent = false;
//        if (node.item == n1 || node.item == n2) {
//            lcaData.count++;
//            foundInCurrent = true;
//        }
//
//        boolean foundInLeft = foundMatch(node.left, lcaData, n1, n2);
//        boolean foundInRight = foundMatch(node.right, lcaData, n1, n2);
//
//        if ((foundInLeft && foundInRight) || (foundInCurrent && foundInRight) || (foundInCurrent && foundInLeft)) {
//            lcaData.lca = node;
//            return true; 
//        }
//        return foundInCurrent || (foundInLeft || foundInRight);
//    }


    private boolean foundMatchAndDuplicate (TreeNode node, LCAData lcaData, int n1, int n2, Set<Integer> set) {
        if (node == null) {
            return false;
        }

        // when both were found
        if (lcaData.count == 2) {
            return false;
        }

        // when only one of them is found
        if ((node.item == n1 || node.item == n2) && lcaData.count == 1) {
            if (!set.contains(node.item)) {
                lcaData.count++;
                return true;
            }
        }

        boolean foundInCurrent = false;  
        // when nothing was found (count == 0), or a duplicate was found (count == 1)
        if (node.item == n1 || node.item == n2) {
            if (!set.contains(node.item)) {
                set.add(node.item);
                lcaData.count++;
            }
            foundInCurrent = true;
        }

        boolean foundInLeft = foundMatchAndDuplicate(node.left, lcaData, n1, n2, set);
        boolean foundInRight = foundMatchAndDuplicate(node.right, lcaData, n1, n2, set);

        if (((foundInLeft && foundInRight) || 
                (foundInCurrent && foundInRight) || 
                    (foundInCurrent && foundInLeft)) &&
                        lcaData.lca == null) {
            lcaData.lca = node;
            return true; 
        }
        return foundInCurrent || (foundInLeft || foundInRight);
    }




    public static void main(String args[]) {
        /**
         * Binary tree with unique values.
         */
        Integer[] arr1 = {1, 2, 3, 4, null, 6, 7, 8, null, null, null, null, 9};
        LeastCommonAncestor commonAncestor = new LeastCommonAncestor();
        commonAncestor.createBinaryTree(arr1);

        int ancestor = commonAncestor.leastCommonAncestor(2, 4);
        System.out.println("Expected 2, actual " + ancestor);

        ancestor = commonAncestor.leastCommonAncestor(2, 7);
        System.out.println("Expected 1, actual " +ancestor);

        ancestor = commonAncestor.leastCommonAncestor(2, 6);
        System.out.println("Expected 1, actual " + ancestor);

        ancestor = commonAncestor.leastCommonAncestor(2, 1);
        System.out.println("Expected 1, actual " +ancestor);

        ancestor = commonAncestor.leastCommonAncestor(3, 8);
        System.out.println("Expected 1, actual " +ancestor);

        ancestor = commonAncestor.leastCommonAncestor(7, 9);
        System.out.println("Expected 3, actual " +ancestor);

        // duplicate request 
        try {
            ancestor = commonAncestor.leastCommonAncestor(7, 7);
        } catch (Exception e) {
            System.out.println("expected exception");
        }

        /**
         * Binary tree with duplicate values.
         */
        Integer[] arr2 = {1, 2, 8, 4, null, 6, 7, 8, null, null, null, null, 9};
        commonAncestor = new LeastCommonAncestor();
        commonAncestor.createBinaryTree(arr2);

        // duplicate requested
        ancestor = commonAncestor.leastCommonAncestor(8, 8);
        System.out.println("Expected 1, actual " + ancestor);

        ancestor = commonAncestor.leastCommonAncestor(4, 8);
        System.out.println("Expected 4, actual " +ancestor);

        ancestor = commonAncestor.leastCommonAncestor(7, 8);
        System.out.println("Expected 8, actual " +ancestor);

        ancestor = commonAncestor.leastCommonAncestor(2, 6);
        System.out.println("Expected 1, actual " + ancestor);

         ancestor = commonAncestor.leastCommonAncestor(8, 9);  
        System.out.println("Expected 8, actual " +ancestor); // failed.
    }
}

How do I pass multiple parameter in URL?

You can pass multiple parameters as "?param1=value1&param2=value2"

But it's not secure. It's vulnerable to Cross Site Scripting (XSS) Attack.

Your parameter can be simply replaced with a script.

Have a look at this article and article

You can make it secure by using API of StringEscapeUtils

static String   escapeHtml(String str) 
          Escapes the characters in a String using HTML entities.

Even using https url for security without above precautions is not a good practice.

Have a look at related SE question:

Is URLEncoder.encode(string, "UTF-8") a poor validation?

Connect with SSH through a proxy

I use -o "ProxyCommand=nc -X 5 -x proxyhost:proxyport %h %p" ssh option to connect through socks5 proxy on OSX.

What are abstract classes and abstract methods?

Once you get what abstract means in Java, you would ask: why they put this in ? Java may work without abstract stuff, BUT it makes part of a certain OO style or vocabulary. There exists really situations where an abstract class or method is an elegant way to express the program authors intention. Most when you are programming a framework or a library that will be used by others.

How can one grab a stack trace in C?

There is no platform independent way to do it.

The nearest thing you can do is to run the code without optimizations. That way you can attach to the process (using the visual c++ debugger or GDB) and get a usable stack trace.

PHP: If internet explorer 6, 7, 8 , or 9

if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match("/(?i)msie|trident|edge/",$_SERVER['HTTP_USER_AGENT'])) {
// eh, IE found
}

How to UPSERT (MERGE, INSERT ... ON DUPLICATE UPDATE) in PostgreSQL?

Here are some examples for insert ... on conflict ... (pg 9.5+) :

  • Insert, on conflict - do nothing.
    insert into dummy(id, name, size) values(1, 'new_name', 3)
    on conflict do nothing;`  
    
  • Insert, on conflict - do update, specify conflict target via column.
    insert into dummy(id, name, size) values(1, 'new_name', 3)
    on conflict(id)
    do update set name = 'new_name', size = 3;  
    
  • Insert, on conflict - do update, specify conflict target via constraint name.
    insert into dummy(id, name, size) values(1, 'new_name', 3)
    on conflict on constraint dummy_pkey
    do update set name = 'new_name', size = 4;
    

apt-get for Cygwin?

you can always make a bash alias to setup*.exe files in $home/.bashrc

cygwin 32bit

alias cyg-get="/cygdrive/c/cygwin/setup-x86.exe -q -P"

cygwin 64bit

alias cyg-get="/cygdrive/c/cygwin64/setup-x86_64.exe -q -P"

now you can install packages with

cyg-get <package>

Configuring diff tool with .gitconfig

Refer to Microsoft vscode-tips-and-tricks. Just run these commands in your terminal:

git config --global merge.tool code

But firstly you need add code command to your PATH. enter image description here

Convert dd-mm-yyyy string to date

Using moment.js example:

var from = '11-04-2017' // OR $("#datepicker").val();
var milliseconds = moment(from, "DD-MM-YYYY").format('x');
var f = new Date(milliseconds)

Where is adb.exe in windows 10 located?

  • Open android studio

enter image description here

  • Press configure or if project opens go to settings enter image description here

  • lookup Android SDK shown in picture enter image description here

  • You can see your Android SDK Location. Open file in file explorer to that location.

  • Add this to end or direct through to this

\platform-tools\adb.exe

full path on my pc is :

C:\Users\Daniel\AppData\Local\Android\Sdk\platform-tools

Why XML-Serializable class need a parameterless constructor

During an object's de-serialization, the class responsible for de-serializing an object creates an instance of the serialized class and then proceeds to populate the serialized fields and properties only after acquiring an instance to populate.

You can make your constructor private or internal if you want, just so long as it's parameterless.

What does it mean when an HTTP request returns status code 0?

An HTTP response code of 0 indicates that the AJAX request was cancelled.

This can happen either from a timeout, XHR abortion or a firewall stomping on the request. A timeout is common, it means the request failed to execute within a specified time. An XHR Abortion is very simple to do... you can actually call .abort() on an XMLHttpRequest object to cancel the AJAX call. (This is good practice for a single page application if you don't want AJAX calls returning and attempting to reference objects that have been destroyed.) As mentioned in the marked answer, a firewall would also be capable of cancelling the request and trigger this 0 response.

XHR Abort: Abort Ajax requests using jQuery

var xhr = $.ajax({
    type: "POST",
    url: "some.php",
    data: "name=John&location=Boston",
    success: function(msg){
       alert( "Data Saved: " + msg );
    }
});

//kill the request
xhr.abort()

It's worth noting that running the .abort() method on an XHR object will also fire the error callback. If you're doing any kind of error handling that parses these objects, you'll quickly notice that an aborted XHR and a timeout XHR are identical, but with jQuery the textStatus that is passed to the error callback will be "abort" when aborted and "timeout" with a timeout occurs. If you're using Zepto (very very similar to jQuery) the errorType will be "error" when aborted and "timeout" when a timeout occurs.

jQuery: error(jqXHR, textStatus, errorThrown);
Zepto:  error(xhr, errorType, error);

What is the use of style="clear:both"?

clear:both makes the element drop below any floated elements that precede it in the document.

You can also use clear:left or clear:right to make it drop below only those elements that have been floated left or right.

+------------+ +--------------------+
|            | |                    |
| float:left | |   without clear    |
|            | |                    |
|            | +--------------------+
|            | +--------------------+
|            | |                    |
|            | |  with clear:right  |
|            | |  (no effect here,  |
|            | |   as there is no   |
|            | |   float:right      |
|            | |   element)         |
|            | |                    |
|            | +--------------------+
|            |
+------------+
+---------------------+
|                     |
|   with clear:left   |
|    or clear:both    |
|                     |
+---------------------+

Global Angular CLI version greater than local version

It is caused because global and local angular versions are different. To update global angular version, first you need to run the following command in command prompt or vs code terminal

npm install --save-dev @angular/cli@latest

After that if there are any vulnerability found then run the following command to fix them

npm audit fix

"make clean" results in "No rule to make target `clean'"

I suppose you have figured it out by now. The answer is hidden in your first mail itself.

The make command by default looks for makefile, Makefile, and GNUMakefile as the input file and you are having Makefile.txt in your folder. Just remove the file extension (.txt) and it should work.

Pandas: rolling mean by time interval

I found that user2689410 code broke when I tried with window='1M' as the delta on business month threw this error:

AttributeError: 'MonthEnd' object has no attribute 'delta'

I added the option to pass directly a relative time delta, so you can do similar things for user defined periods.

Thanks for the pointers, here's my attempt - hope it's of use.

def rolling_mean(data, window, min_periods=1, center=False):
""" Function that computes a rolling mean
Reference:
    http://stackoverflow.com/questions/15771472/pandas-rolling-mean-by-time-interval

Parameters
----------
data : DataFrame or Series
       If a DataFrame is passed, the rolling_mean is computed for all columns.
window : int, string, Timedelta or Relativedelta
         int - number of observations used for calculating the statistic,
               as defined by the function pd.rolling_mean()
         string - must be a frequency string, e.g. '90S'. This is
                  internally converted into a DateOffset object, and then
                  Timedelta representing the window size.
         Timedelta / Relativedelta - Can directly pass a timedeltas.
min_periods : int
              Minimum number of observations in window required to have a value.
center : bool
         Point around which to 'center' the slicing.

Returns
-------
Series or DataFrame, if more than one column
"""
def f(x, time_increment):
    """Function to apply that actually computes the rolling mean
    :param x:
    :return:
    """
    if not center:
        # adding a microsecond because when slicing with labels start
        # and endpoint are inclusive
        start_date = x - time_increment + timedelta(0, 0, 1)
        end_date = x
    else:
        start_date = x - time_increment/2 + timedelta(0, 0, 1)
        end_date = x + time_increment/2
    # Select the date index from the
    dslice = col[start_date:end_date]

    if dslice.size < min_periods:
        return np.nan
    else:
        return dslice.mean()

data = DataFrame(data.copy())
dfout = DataFrame()
if isinstance(window, int):
    dfout = pd.rolling_mean(data, window, min_periods=min_periods, center=center)

elif isinstance(window, basestring):
    time_delta = pd.datetools.to_offset(window).delta
    idx = Series(data.index.to_pydatetime(), index=data.index)
    for colname, col in data.iteritems():
        result = idx.apply(lambda x: f(x, time_delta))
        result.name = colname
        dfout = dfout.join(result, how='outer')

elif isinstance(window, (timedelta, relativedelta)):
    time_delta = window
    idx = Series(data.index.to_pydatetime(), index=data.index)
    for colname, col in data.iteritems():
        result = idx.apply(lambda x: f(x, time_delta))
        result.name = colname
        dfout = dfout.join(result, how='outer')

if dfout.columns.size == 1:
    dfout = dfout.ix[:, 0]
return dfout

And the example with a 3 day time window to calculate the mean:

from pandas import Series, DataFrame
import pandas as pd
from datetime import datetime, timedelta
import numpy as np
from dateutil.relativedelta import relativedelta

idx = [datetime(2011, 2, 7, 0, 0),
           datetime(2011, 2, 7, 0, 1),
           datetime(2011, 2, 8, 0, 1, 30),
           datetime(2011, 2, 9, 0, 2),
           datetime(2011, 2, 10, 0, 4),
           datetime(2011, 2, 11, 0, 5),
           datetime(2011, 2, 12, 0, 5, 10),
           datetime(2011, 2, 12, 0, 6),
           datetime(2011, 2, 13, 0, 8),
           datetime(2011, 2, 14, 0, 9)]
idx = pd.Index(idx)
vals = np.arange(len(idx)).astype(float)
s = Series(vals, index=idx)
# Now try by passing the 3 days as a relative time delta directly.
rm = rolling_mean(s, window=relativedelta(days=3))
>>> rm
Out[2]: 
2011-02-07 00:00:00    0.0
2011-02-07 00:01:00    0.5
2011-02-08 00:01:30    1.0
2011-02-09 00:02:00    1.5
2011-02-10 00:04:00    3.0
2011-02-11 00:05:00    4.0
2011-02-12 00:05:10    5.0
2011-02-12 00:06:00    5.5
2011-02-13 00:08:00    6.5
2011-02-14 00:09:00    7.5
Name: 0, dtype: float64

Docker compose, running containers in net:host

Maybe I am answering very late. But I was also having a problem configuring host network in docker compose. Then I read the documentation thoroughly and made the changes and it worked. Please note this configuration is for docker-compose version "3.7". Here einwohner_net and elk_net_net are my user-defined networks required for my application. I am using host net to get some system metrics.

Link To Documentation https://docs.docker.com/compose/compose-file/#host-or-none

version: '3.7'
services:
  app:
    image: ramansharma/einwohnertomcat:v0.0.1
    deploy:
      replicas: 1
      ports:
       - '8080:8080'
    volumes:
     - type: bind
       source: /proc
       target: /hostfs/proc
       read_only: true
     - type: bind
       source: /sys/fs/cgroup
       target: /hostfs/sys/fs/cgroup
       read_only: true
     - type: bind
       source: /
       target: /hostfs
       read_only: true
    networks:
     hostnet: {}
    networks:
     - einwohner_net
     - elk_elk_net
networks:
 einwohner_net:
 elk_elk_net:
   external: true
 hostnet:
   external: true
   name: host

Guzzle 6: no more json() method for responses

If you guys still interested, here is my workaround based on Guzzle middleware feature:

  1. Create JsonAwaraResponse that will decode JSON response by Content-Type HTTP header, if not - it will act as standard Guzzle Response:

    <?php
    
    namespace GuzzleHttp\Psr7;
    
    
    class JsonAwareResponse extends Response
    {
        /**
         * Cache for performance
         * @var array
         */
        private $json;
    
        public function getBody()
        {
            if ($this->json) {
                return $this->json;
            }
            // get parent Body stream
            $body = parent::getBody();
    
            // if JSON HTTP header detected - then decode
            if (false !== strpos($this->getHeaderLine('Content-Type'), 'application/json')) {
                return $this->json = \json_decode($body, true);
            }
            return $body;
        }
    }
    
  2. Create Middleware which going to replace Guzzle PSR-7 responses with above Response implementation:

    <?php
    
    $client = new \GuzzleHttp\Client();
    
    /** @var HandlerStack $handler */
    $handler = $client->getConfig('handler');
    $handler->push(\GuzzleHttp\Middleware::mapResponse(function (\Psr\Http\Message\ResponseInterface $response) {
        return new \GuzzleHttp\Psr7\JsonAwareResponse(
            $response->getStatusCode(),
            $response->getHeaders(),
            $response->getBody(),
            $response->getProtocolVersion(),
            $response->getReasonPhrase()
        );
    }), 'json_decode_middleware');
    

After this to retrieve JSON as PHP native array use Guzzle as always:

$jsonArray = $client->get('http://httpbin.org/headers')->getBody();

Tested with guzzlehttp/guzzle 6.3.3

How to: Add/Remove Class on mouseOver/mouseOut - JQuery .hover?

You forgot the dot of class selector of result class.

Live Demo

$(".result").hover(
  function () {
    $(this).addClass("result_hover");
  },
  function () {
    $(this).removeClass("result_hover");
  }
);

You can use toggleClass on hover event

Live Demo

 $(".result").hover(function () {
    $(this).toggleClass("result_hover");
 });

Batch file include external file for variables

The best option according to me is to have key/value pairs file as it could be read from other scripting languages.

Other thing is I would prefer to have an option for comments in the values file - which can be easy achieved with eol option in for /f command.

Here's the example

values file:

;;;;;; file with example values ;;;;;;;;

;; Will be processed by a .bat file
;; ';' can be used for commenting a line

First_Value=value001

;;Do not let spaces arround the equal sign
;; As this makes the processing much easier
;; and reliable

Second_Value=%First_Value%_test

;;as call set will be used in reading script
;; refering another variables will be possible.

Third_Value=Something

;;; end

Reading script:

@echo off

:::::::::::::::::::::::::::::
set "VALUES_FILE=E:\scripts\example.values"
:::::::::::::::::::::::::::::

FOR /F "usebackq eol=; tokens=* delims=" %%# in (
    "%VALUES_FILE%"
) do (
    call set "%%#"
)

echo %First_Value% -- %Second_Value% -- %Third_Value%

iptables LOG and DROP in one rule

Although already over a year old, I stumbled across this question a couple of times on other Google search and I believe I can improve on the previous answer for the benefit of others.

Short answer is you cannot combine both action in one line, but you can create a chain that does what you want and then call it in a one liner.

Let's create a chain to log and accept:

iptables -N LOG_ACCEPT

And let's populate its rules:

iptables -A LOG_ACCEPT -j LOG --log-prefix "INPUT:ACCEPT:" --log-level 6
iptables -A LOG_ACCEPT -j ACCEPT

Now let's create a chain to log and drop:

iptables -N LOG_DROP

And let's populate its rules:

iptables -A LOG_DROP -j LOG --log-prefix "INPUT:DROP: " --log-level 6
iptables -A LOG_DROP -j DROP

Now you can do all actions in one go by jumping (-j) to you custom chains instead of the default LOG / ACCEPT / REJECT / DROP:

iptables -A <your_chain_here> <your_conditions_here> -j LOG_ACCEPT
iptables -A <your_chain_here> <your_conditions_here> -j LOG_DROP

Simple 'if' or logic statement in Python

Here's a Boolean thing:

if (not suffix == "flac" )  or (not suffix == "cue" ):   # WRONG! FAILS
    print  filename + ' is not a flac or cue file'

but

if not (suffix == "flac"  or suffix == "cue" ):     # CORRECT!
       print  filename + ' is not a flac or cue file'

(not a) or (not b) == not ( a and b ) , is false only if a and b are both true

not (a or b) is true only if a and be are both false.

Is Xamarin free in Visual Studio 2015?

Visual Studio 2015 does include Xamarin Starter edition https://xamarin.com/starter

Xamarin Starter is free and allows developers to build and publish simple apps with the following limitations:

  • Contain no more than 128k of compiled user code (IL)
  • Do NOT call out to native third party libraries (i.e., developers may not P/Invoke into C/C++/Objective-C/Java)
  • Built using Xamarin.iOS / Xamarin.Android (NOT Xamarin.Forms)

Xamarin Starter installs automatically with Visual Studio 2015, and works with VS 2012, 2013, and 2015 (including Community Editions). When your app outgrows Starter, you will be offered the opportunity to upgrade to a paid subscription, which you can learn more about here: https://store.xamarin.com/

How to create a library project in Android Studio and an application project that uses the library project

Google’s Gradle Plugin recommended way for configuring your gradle files to build multiple projects has some shortcomings If you have multiple projects depending upon one library project, this post briefly explain Google’s recommended configuration, its shortcomings, and recommend a different way to configure your gradle files to support multi-project setups in Android Studio:

An alternative multiproject setup for android studio

A Different Way :

It turns out there’s a better way to manage multiple projects in Android Studio. The trick is to create separate Android Studio projects for your libraries and to tell gradle that the module for the library that your app depends on is located in the library’s project directory. If you wanted to use this method with the project structure I’ve described above, you would do the following:

  1. Create an Android Studio project for the StickyListHeaders library
  2. Create an Android Studio project for App2
  3. Create an Android Studio project for App1
  4. Configure App1 and App2 to build the modules in the StickyListHeaders project.

The 4th step is the hard part, so that’s the only step that I’ll describe in detail. You can reference modules that are external to your project’s directory by adding a project statement in your settings.gradle file and by setting the projectDir property on the ProjectDescriptor object that’s returned by that project statement:

enter image description here

The code one has to put in settings.gradle:

include ':library1'
project(':library1').projectDir = new File('../StickyListHeader/library1')

If you’ve done this correctly, you’ll notice that the modules referenced by your project will show up in the project navigator, even if those modules are external to the project directory:

enter image description here

This allows you to work on library code and app code simultaneously. Version control integration also works just fine when you reference modules externally this way. You can commit and push your modifications to the library code just like you can commit and push modifications to your app code.

This way of setting up multiple projects avoids the difficulties that plague Google’s recommended configuration. Because we are referencing a module that is outside of the project directory we don’t have to make extra copies of the library module for every app that depends on it and we can version our libraries without any sort of git submodule nonsense.

Unfortunately, this other way of setting up multiple projects is very difficult to find. Obviously, its not something you’ll figure out from looking at Google’s guide, and at this point, there’s no way to configure your projects in this way by using the UI of Android Studio.

What is the difference between i++ and ++i?

Just for the record, in C++, if you can use either (i.e.) you don't care about the ordering of operations (you just want to increment or decrement and use it later) the prefix operator is more efficient since it doesn't have to create a temporary copy of the object. Unfortunately, most people use posfix (var++) instead of prefix (++var), just because that is what we learned initially. (I was asked about this in an interview). Not sure if this is true in C#, but I assume it would be.

How to make an element in XML schema optional?

Try this

<xs:element name="description" type="xs:string" minOccurs="0" maxOccurs="1" />

if you want 0 or 1 "description" elements, Or

<xs:element name="description" type="xs:string" minOccurs="0" maxOccurs="unbounded" />

if you want 0 to infinity number of "description" elements.

Disable Buttons in jQuery Mobile

UPDATE:

Since this question still gets a lot of hits I'm also adding the current jQM Docs on how to disable the button:

Updated Examples:

enable enable a disabled form button

$('[type="submit"]').button('enable');  

disable disable a form button

$('[type="submit"]').button('disable'); 

refresh update the form button
If you manipulate a form button via JavaScript, you must call the refresh method on it to update the visual styling.

$('[type="submit"]').button('refresh');

Original Post Below:

Live Example: http://jsfiddle.net/XRjh2/2/

UPDATE:

Using @naugtur example below: http://jsfiddle.net/XRjh2/16/

UPDATE #2:

Link button example:

JS

var clicked = false;

$('#myButton').click(function() {
    if(clicked === false) {
        $(this).addClass('ui-disabled');
        clicked = true;
        alert('Button is now disabled');
    } 
});

$('#enableButton').click(function() {
    $('#myButton').removeClass('ui-disabled');
    clicked = false; 
});

HTML

<div data-role="page" id="home">
    <div data-role="content">

        <a href="#" data-role="button" id="myButton">Click button</a>
        <a href="#" data-role="button" id="enableButton">Enable button</a>

    </div>
</div>

NOTE: - http://jquerymobile.com/demos/1.0rc2/docs/buttons/buttons-types.html

Links styled like buttons have all the same visual options as true form-based buttons below, but there are a few important differences. Link-based buttons aren't part of the button plugin and only just use the underlying buttonMarkup plugin to generate the button styles so the form button methods (enable, disable, refresh) aren't supported. If you need to disable a link-based button (or any element), it's possible to apply the disabled class ui-disabled yourself with JavaScript to achieve the same effect.

How can I SELECT multiple columns within a CASE WHEN on SQL Server?

Actually you can do it.

Although, someone should note that repeating the CASE statements are not bad as it seems. SQL Server's query optimizer is smart enough to not execute the CASE twice so that you won't get any performance hit because of that.

Additionally, someone might use the following logic to not repeat the CASE (if it suits you..)

INSERT INTO dbo.T1
(
    Col1,
    Col2,
    Col3
)
SELECT
    1,
    SUBSTRING(MyCase.MergedColumns, 0, CHARINDEX('%', MyCase.MergedColumns)),
    SUBSTRING(MyCase.MergedColumns, CHARINDEX('%', MyCase.MergedColumns) + 1, LEN(MyCase.MergedColumns) - CHARINDEX('%', MyCase.MergedColumns))
FROM
    dbo.T1 t
LEFT OUTER JOIN
(
    SELECT CASE WHEN 1 = 1 THEN '2%3' END MergedColumns
) AS MyCase ON 1 = 1

This will insert the values (1, 2, 3) for each record in the table T1. This uses a delimiter '%' to split the merged columns. You can write your own split function depending on your needs (e.g. for handling null records or using complex delimiter for varchar fields etc.). But the main logic is that you should join the CASE statement and select from the result set of the join with using a split logic.

Winforms TableLayoutPanel adding rows programmatically

This works perfectly for adding rows and controls in a TableLayoutPanel.

Define a blank Tablelayoutpanel with 3 columns in the design page

    Dim TableLayoutPanel3 As New TableLayoutPanel()

    TableLayoutPanel3.Name = "TableLayoutPanel3"

    TableLayoutPanel3.Location = New System.Drawing.Point(32, 287)

    TableLayoutPanel3.AutoSize = True

    TableLayoutPanel3.Size = New System.Drawing.Size(620, 20)

    TableLayoutPanel3.ColumnCount = 3

    TableLayoutPanel3.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single

    TableLayoutPanel3.BackColor = System.Drawing.Color.Transparent

    TableLayoutPanel3.ColumnStyles.Add(New ColumnStyle(SizeType.Percent, 26.34146!))

    TableLayoutPanel3.ColumnStyles.Add(New ColumnStyle(SizeType.Percent, 73.65854!))

    TableLayoutPanel3.ColumnStyles.Add(New ColumnStyle(SizeType.Absolute, 85.0!))

    Controls.Add(TableLayoutPanel3)

Create a button btnAddRow to add rows on each click

     Private Sub btnAddRow_Click(sender As System.Object, e As System.EventArgs) Handles btnAddRow.Click

          TableLayoutPanel3.GrowStyle = TableLayoutPanelGrowStyle.AddRows

          TableLayoutPanel3.RowStyles.Add(New RowStyle(SizeType.Absolute, 20))

          TableLayoutPanel3.SuspendLayout()

          TableLayoutPanel3.RowCount += 1

          Dim tb1 As New TextBox()

          Dim tb2 As New TextBox()

          Dim tb3 As New TextBox()

          TableLayoutPanel3.Controls.Add(tb1 , 0, TableLayoutPanel3.RowCount - 1)

          TableLayoutPanel3.Controls.Add(tb2, 1, TableLayoutPanel3.RowCount - 1)

          TableLayoutPanel3.Controls.Add(tb3, 2, TableLayoutPanel3.RowCount - 1)

          TableLayoutPanel3.ResumeLayout()

          tb1.Focus()

 End Sub

Error executing command 'ant' on Mac OS X 10.9 Mavericks when building for Android with PhoneGap/Cordova

The error message proved to be true as Apache Ant isn't in the path of Mac OS X Mavericks anymore.

Bulletproof solution:

  1. Download and install Homebrew by executing following command in terminal:

    ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

  2. Install Apache Ant via Homebrew by executing

    brew install ant

Run the PhoneGap build again and it should successfully compile and install your Android app.

Draw a curve with css

@Navaneeth and @Antfish, no need to transform you can do like this also because in above solution only top border is visible so for inside curve you can use bottom border.

_x000D_
_x000D_
.box {_x000D_
  width: 500px;_x000D_
  height: 100px;_x000D_
  border: solid 5px #000;_x000D_
  border-color: transparent transparent #000 transparent;_x000D_
  border-radius: 0 0 240px 50%/60px;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
_x000D_
_x000D_

What is ANSI format?

Once upon a time Microsoft, like everyone else, used 7-bit character sets, and they invented their own when it suited them, though they kept ASCII as a core subset. Then they realised the world had moved on to 8-bit encodings and that there were international standards around, such as the ISO-8859 family. In those days, if you wanted to get hold of an international standard and you lived in the US, you bought it from the American National Standards Institute, ANSI, who republished international standards with their own branding and numbers (that's because the US government wants conformance to American standards, not international standards). So Microsoft's copy of ISO-8859 said "ANSI" on the cover. And because Microsoft weren't very used to standards in those days, they didn't realise that ANSI published lots of other standards as well. So they referred to the standards in the ISO-8859 family (and the variants that they invented, because they didn't really understand standards in those days) by the name on the cover, "ANSI", and it found its way into Microsoft user documentation and hence into the user community. That was about 30 years ago, but you still sometimes hear the name today.

How to do something to each file in a directory with a batch script

Easiest method:

From Command Line, use:

for %f in (*.*) do echo %f

From a Batch File (double up the % percent signs):

for %%f in (*.*) do echo %%f

From a Batch File with folder specified as 1st parameter:

for %%f in (%1\*.*) do echo %%f

There is an error in XML document (1, 41)

First check the variables declared using proper Datatypes. I had a same problem then I have checked, by mistake I declared SAPUser as int datatype so that the error occurred. One more thing XML file stores its data using concept like array but its first index starts having +1. e.g. if error is in(7,2) then check for 6th line always.....

Why I am getting Cannot pass parameter 2 by reference error when I am using bindParam with a constant value?

For those who still have problems (Cannot pass parameter 2 by reference), define a variable with null value, not just pass null to PDO:

bindValue(':param', $n = null, PDO::PARAM_INT);

Hope this helps.

What is Common Gateway Interface (CGI)?

The idea behind CGI is that a program/script (whether Perl or even C) receives input via STDIN (the request data) and outputs data via STDOUT (echo, printf statements).

The reason most PHP scripts don't qualify is that they are run under the PHP Apache module.

How to keep onItemSelected from firing off on a newly instantiated Spinner?

This is not an elegant solution either. In fact it's rather Rube-Goldberg but it seems to work. I make sure the spinner has been used at least once by extending the array adapter and overriding its getDropDownView. In the new getDropDownView method I have a boolean flag that is set to show the dropdown menu has been used at least once. I ignore calls to the listener until the flag is set.

MainActivity.onCreate():

ActionBar ab = getActionBar();
ab.setDisplayShowTitleEnabled(false);
ab.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
ab.setListNavigationCallbacks(null, null);

ArrayList<String> abList = new ArrayList<String>();
abList.add("line 1");
...

ArAd  abAdapt = new ArAd (this
   , android.R.layout.simple_list_item_1
   , android.R.id.text1, abList);
ab.setListNavigationCallbacks(abAdapt, MainActivity.this);

overriden array adapter:

private static boolean viewed = false;
private class ArAd extends ArrayAdapter<String> {
    private ArAd(Activity a
            , int layoutId, int resId, ArrayList<String> list) {
        super(a, layoutId, resId, list);
        viewed = false;
    }
    @Override
    public View getDropDownView(int position, View convertView,
            ViewGroup parent) {
        viewed = true;
        return super.getDropDownView(position, convertView, parent);
    }
}

modified listener:

@Override
public boolean onNavigationItemSelected(
   int itemPosition, long itemId) {
   if (viewed) {
     ...
   }
   return false;
}

What port number does SOAP use?

SOAP (Simple Object Access Protocol) is the communication protocol in the web service scenario.

One benefit of SOAP is that it allowas RPC to execute through a firewall. But to pass through a firewall, you will probably want to use 80. it uses port no.8084 To the firewall, a SOAP conversation on 80 looks like a POST to a web page. However, there are extensions in SOAP which are specifically aimed at the firewall. In the future, it may be that firewalls will be configured to filter SOAP messages. But as of today, most firewalls are SOAP ignorant.

so exclusively open SOAP Port in Firewalls

How do you uninstall a python package that was installed using distutils?

for Python in Windows:

python -m pip uninstall "package_keyword"
uninstall **** (y/n)?

How to set multiple commands in one yaml file with Kubernetes?

I am not sure if the question is still active but due to the fact that I did not find the solution in the above answers I decided to write it down.

I use the following approach:

readinessProbe:
  exec:
    command:
    - sh
    - -c
    - |
      command1
      command2 && command3

I know my example is related to readinessProbe, livenessProbe, etc. but suspect the same case is for the container commands. This provides flexibility as it mirrors a standard script writing in Bash.

How to set web.config file to show full error message

not sure if it'll work in your scenario, but try adding the following to your web.config under <system.web>:

  <system.web>
    <customErrors mode="Off" />
  ...
  </system.web>

works in my instance.

also see:

CustomErrors mode="Off"

Spark difference between reduceByKey vs groupByKey vs aggregateByKey vs combineByKey

  • groupByKey() is just to group your dataset based on a key. It will result in data shuffling when RDD is not already partitioned.
  • reduceByKey() is something like grouping + aggregation. We can say reduceBykey() equvelent to dataset.group(...).reduce(...). It will shuffle less data unlike groupByKey().
  • aggregateByKey() is logically same as reduceByKey() but it lets you return result in different type. In another words, it lets you have a input as type x and aggregate result as type y. For example (1,2),(1,4) as input and (1,"six") as output. It also takes zero-value that will be applied at the beginning of each key.

Note : One similarity is they all are wide operations.

Tree view of a directory/folder in Windows?

tree /f /a

About

The Windows command tree /f /a produces a tree of the current folder and all files & folders contained within it in ASCII format.

The output can be redirected to a text file using the > parameter.

Method

For Windows 8.1 or Windows 10, follow these steps:

  1. Navigate into the folder in file explorer.
  2. Press Shift, right-click mouse, and select "Open command window here".
  3. Type tree /f /a > tree.txt and press Enter.
  4. Open the new tree.txt file in your favourite text editor/viewer.

Note: Windows 7, Vista, XP and earlier users can type cmd in the run command box in the start menu for a command window.

Error Message: Type or namespace definition, or end-of-file expected

  1. Make sure you have System.Web referenced
  2. Get rid of the two } at the end.

Get the latest record from mongodb collection

This is how to get the last record from all MongoDB documents from the "foo" collection.(change foo,x,y.. etc.)

db.foo.aggregate([{$sort:{ x : 1, date : 1 } },{$group: { _id: "$x" ,y: {$last:"$y"},yz: {$last:"$yz"},date: { $last : "$date" }}} ],{   allowDiskUse:true  })

you can add or remove from the group

help articles: https://docs.mongodb.com/manual/reference/operator/aggregation/group/#pipe._S_group

https://docs.mongodb.com/manual/reference/operator/aggregation/last/

What is the difference between class and instance methods?

An update to the above answers, I agree instance methods use an instance of a class, whereas a class method can be used with just the class name.

There is NO more any difference between instance method & class method after automatic reference counting came to existence in Objective-C.

For Example[NS StringWithformat:..] a class method & [[NSString alloc] initwihtformat:..] an instance method, both are same after ARC

How to use the 'main' parameter in package.json?

Just think of it as the "starting point".

In a sense of object-oriented programming, say C#, it's the init() or constructor of the object class, that's what "entry point" meant.

For example

public class IamMain  // when export and require this guy
{
    public IamMain()  // this is "main"
    {...}

    ...   // many others such as function, properties, etc.
}

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

Inner join with count() on three tables

It makes more sense to join the item with the orders than with the people !

SELECT
    people.pe_name,
    COUNT(distinct orders.ord_id) AS num_orders,
    COUNT(items.item_id) AS num_items
FROM
    people
    INNER JOIN orders ON orders.pe_id = people.pe_id
         INNER JOIN items ON items.ord_id = orders.ord_id
GROUP BY
    people.pe_id;

Joining the items with the people provokes a lot of doublons. For example, the cake items in order 3 will be linked with the order 2 via the join between the people, and you don't want this to happen !!

So :

1- You need a good understanding of your schema. Items are link to orders, and not to people.

2- You need to count distinct orders for one person, else you will count as many items as orders.

Nullable type as a generic parameter possible?

Just had to do something incredible similar to this. My code:

public T IsNull<T>(this object value, T nullAlterative)
{
    if(value != DBNull.Value)
    {
        Type type = typeof(T);
        if (type.IsGenericType && 
            type.GetGenericTypeDefinition() == typeof(Nullable<>).GetGenericTypeDefinition())
        {
            type = Nullable.GetUnderlyingType(type);
        }

        return (T)(type.IsEnum ? Enum.ToObject(type, Convert.ToInt32(value)) :
            Convert.ChangeType(value, type));
    }
    else 
        return nullAlternative;
}

Delete/Reset all entries in Core Data?

Assuming you are using MagicalRecord and have a default persistence store:

I don't like all the solutions that assume certain files to exist and/or demand entering the entities names or classes. This is a Swift(2), safe way to delete all the data from all the entities. After deleting it will recreate a fresh stack too (I am actually not sure as to how neccessery this part is).

It's godo for "logout" style situations when you want to delete everything but have a working store and moc to get new data in (once the user logs in...)

extension NSManagedObject {

    class func dropAllData() {

        MagicalRecord.saveWithBlock({ context in

            for name in NSManagedObjectModel.MR_defaultManagedObjectModel().entitiesByName.keys {
                do { try self.deleteAll(name, context: context) }
                catch { print("?? ?? Error when deleting \(name): \(error)") }
            }

            }) { done, err in
                MagicalRecord.cleanUp()
                MagicalRecord.setupCoreDataStackWithStoreNamed("myStoreName")
        }
    }

    private class func deleteAll(name: String, context ctx: NSManagedObjectContext) throws {
        let all = NSFetchRequest(entityName: name)
        all.includesPropertyValues = false

        let allObjs = try ctx.executeFetchRequest(all)
        for obj in allObjs {
            obj.MR_deleteEntityInContext(ctx)
        }

    }
}

How to install pip for Python 3.6 on Ubuntu 16.10?

This answer assumes that you have python3.6 installed. For python3.7, replace 3.6 with 3.7. For python3.8, replace 3.6 with 3.8, but it may also first require the python3.8-distutils package.

Installation with sudo

With regard to installing pip, using curl (instead of wget) avoids writing the file to disk.

curl https://bootstrap.pypa.io/get-pip.py | sudo -H python3.6

The -H flag is evidently necessary with sudo in order to prevent errors such as the following when installing pip for an updated python interpreter:

The directory '/home/someuser/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.

The directory '/home/someuser/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.

Installation without sudo

curl https://bootstrap.pypa.io/get-pip.py | python3.6 - --user

This may sometimes give a warning such as:

WARNING: The script wheel is installed in '/home/ubuntu/.local/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.

Verification

After this, pip, pip3, and pip3.6 can all be expected to point to the same target:

$ (pip -V && pip3 -V && pip3.6 -V) | uniq
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)

Of course you can alternatively use python3.6 -m pip as well.

$ python3.6 -m pip -V
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)

How to create Gmail filter searching for text only at start of subject line?

Regex is not on the list of search features, and it was on (more or less, as Better message search functionality (i.e. Wildcard and partial word search)) the list of pre-canned feature requests, so the answer is "you cannot do this via the Gmail web UI" :-(

There are no current Labs features which offer this. SIEVE filters would be another way to do this, that too was not supported, there seems to no longer be any definitive statement on SIEVE support in the Gmail help.

Updated for link rot The pre-canned list of feature requests was, er canned, the original is on archive.org dated 2012, now you just get redirected to a dumbed down page telling you how to give feedback. Lack of SIEVE support was covered in answer 78761 Does Gmail support all IMAP features?, since some time in 2015 that answer silently redirects to the answer about IMAP client configuration, archive.org has a copy dated 2014.

With the current search facility brackets of any form () {} [] are used for grouping, they have no observable effect if there's just one term within. Using (aaa|bbb) and [aaa|bbb] are equivalent and will both find words aaa or bbb. Most other punctuation characters, including \, are treated as a space or a word-separator, + - : and " do have special meaning though, see the help.

As of 2016, only the form "{term1 term2}" is documented for this, and is equivalent to the search "term1 OR term2".

You can do regex searches on your mailbox (within limits) programmatically via Google docs: http://www.labnol.org/internet/advanced-gmail-search/21623/ has source showing how it can be done (copy the document, then Tools > Script Editor to get the complete source).

You could also do this via IMAP as described here: Python IMAP search for partial subject and script something to move messages to different folder. The IMAP SEARCH verb only supports substrings, not regex (Gmail search is further limited to complete words, not substrings), further processing of the matches to apply a regex would be needed.

For completeness, one last workaround is: Gmail supports plus addressing, if you can change the destination address to [email protected] it will still be sent to your mailbox where you can filter by recipient address. Make sure to filter using the full email address to:[email protected]. This is of course more or less the same thing as setting up a dedicated Gmail address for this purpose :-)

Concatenate a vector of strings/character

Matt's answer is definitely the right answer. However, here's an alternative solution for comic relief purposes:

do.call(paste, c(as.list(sdata), sep = ""))

What is the difference between response.sendRedirect() and request.getRequestDispatcher().forward(request,response)

To simply explain the difference,

  response.sendRedirect("login.jsp");

doesn't prepend the contextpath (refers to the application/module in which the servlet is bundled)

but, whereas

 request.getRequestDispathcer("login.jsp").forward(request, response);

will prepend the contextpath of the respective application

Furthermore, Redirect request is used to redirect to resources to different servers or domains. This transfer of control task is delegated to the browser by the container. That is, the redirect sends a header back to the browser / client. This header contains the resource url to be redirected by the browser. Then the browser initiates a new request to the given url.

Forward request is used to forward to resources available within the server from where the call is made. This transfer of control is done by the container internally and browser / client is not involved.

anchor jumping by using javascript

Not enough rep for a comment.

The getElementById() based method in the selected answer won't work if the anchor has name but not id set (which is not recommended, but does happen in the wild).

Something to bare in mind if you don't have control of the document markup (e.g. webextension).

The location based method in the selected answer can also be simplified with location.replace:

function jump(hash) { location.replace("#" + hash) }

Deprecation warning in Moment.js - Not in a recognized ISO format

const dateFormat = 'MM-DD-YYYY';

const currentDateStringType = moment(new Date()).format(dateFormat);
    
const currentDate = moment(new Date() ,dateFormat);  // use this 

moment.suppressDeprecationWarnings = true;

Set HTML dropdown selected option using JSTL

In Servlet do:

String selectedRole = "rat"; // Or "cat" or whatever you'd like.
request.setAttribute("selectedRole", selectedRole);

Then in JSP do:

<select name="roleName">
    <c:forEach items="${roleNames}" var="role">
        <option value="${role}" ${role == selectedRole ? 'selected' : ''}>${role}</option>
    </c:forEach>
</select>

It will print the selected attribute of the HTML <option> element so that you end up like:

<select name="roleName">
    <option value="cat">cat</option>
    <option value="rat" selected>rat</option>
    <option value="unicorn">unicorn</option>
</select>

Apart from the problem: this is not a combo box. This is a dropdown. A combo box is an editable dropdown.

How to create correct JSONArray in Java using JSONObject

Please try this ... hope it helps

JSONObject jsonObj1=null;
JSONObject jsonObj2=null;
JSONArray array=new JSONArray();
JSONArray array2=new JSONArray();

jsonObj1=new JSONObject();
jsonObj2=new JSONObject();


array.put(new JSONObject().put("firstName", "John").put("lastName","Doe"))
.put(new JSONObject().put("firstName", "Anna").put("v", "Smith"))
.put(new JSONObject().put("firstName", "Peter").put("v", "Jones"));

array2.put(new JSONObject().put("firstName", "John").put("lastName","Doe"))
.put(new JSONObject().put("firstName", "Anna").put("v", "Smith"))
.put(new JSONObject().put("firstName", "Peter").put("v", "Jones"));

jsonObj1.put("employees", array);
jsonObj1.put("manager", array2);

Response response = null;
response = Response.status(Status.OK).entity(jsonObj1.toString()).build();
return response;

No WebApplicationContext found: no ContextLoaderListener registered?

You'll have to have a ContextLoaderListener in your web.xml - It loads your configuration files.

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

You need to understand the difference between Web application context and root application context .

In the web MVC framework, each DispatcherServlet has its own WebApplicationContext, which inherits all the beans already defined in the root WebApplicationContext. These inherited beans defined can be overridden in the servlet-specific scope, and new scope-specific beans can be defined local to a given servlet instance.

The dispatcher servlet's application context is a web application context which is only applicable for the Web classes . You cannot use these for your middle tier layers . These need a global app context using ContextLoaderListener .

Read the spring reference here for spring mvc .

How to access to the parent object in c#

I would give the parent an ID, and store the parentID in the child object, so that you can pull information about the parent as needed without creating a parent-owns-child/child-owns-parent loop.

Is there a developers api for craigslist.org

Craiglist is pretty stingy with their data , they even go out of their way to block scraping. If you use ruby here is a gem I wrote to help scrape craiglist data you can search through multiple cities , calculate average price ect...

Resolve host name to an ip address

Go to your client machine and type in:

nslookup server.company.com

substituting the real host name of your server for server.company.com, of course.

That should tell you which DNS server your client is using (if any) and what it thinks the problem is with the name.

To force an application to use an IP address, generally you just configure it to use the IP address instead of a host name. If the host name is hard-coded, or the application insists on using a host name in preference to an IP address (as one of your other comments seems to indicate), then you're probably out of luck there.

However, you can change the way that most machine resolve the host names, such as with /etc/resolv.conf and /etc/hosts on UNIXy systems and a local hosts file on Windows-y systems.

How to Create a real one-to-one relationship in SQL Server

This can be done by creating a simple primary foreign key relationship and setting the foreign key column to unique in the following manner:

CREATE TABLE [Employee] (
    [ID]    INT PRIMARY KEY
,   [Name]  VARCHAR(50)
);

CREATE TABLE [Salary] (
    [EmployeeID]    INT UNIQUE NOT NULL
,   [SalaryAmount]  INT 
);

ALTER TABLE [Salary]
ADD CONSTRAINT FK_Salary_Employee FOREIGN KEY([EmployeeID]) 
    REFERENCES [Employee]([ID]);

Schema

INSERT INTO [Employee] (
    [ID]
,   [Name]
)
VALUES
    (1, 'Ram')
,   (2, 'Rahim')
,   (3, 'Pankaj')
,   (4, 'Mohan');

INSERT INTO [Salary] (
    [EmployeeID]
,   [SalaryAmount]
)
VALUES
    (1, 2000)
,   (2, 3000)
,   (3, 2500)
,   (4, 3000);

Check to see if everything is fine

SELECT * FROM [Employee];
SELECT * FROM [Salary];

Now Generally in Primary Foreign Relationship (One to many), you could enter multiple times EmployeeID, but here an error will be thrown

INSERT INTO [Salary] (
    [EmployeeID]
,   [SalaryAmount]
)
VALUES
    (1, 3000);

The above statement will show error as

Violation of UNIQUE KEY constraint 'UQ__Salary__7AD04FF0C044141D'. Cannot insert duplicate key in object 'dbo.Salary'. The duplicate key value is (1).

Where is Java's Array indexOf?

There is none. Either use a java.util.List*, or you can write your own indexOf():

public static <T> int indexOf(T needle, T[] haystack)
{
    for (int i=0; i<haystack.length; i++)
    {
        if (haystack[i] != null && haystack[i].equals(needle)
            || needle == null && haystack[i] == null) return i;
    }

    return -1;
}

*you can make one from your array using Arrays#asList()

Simple proof that GUID is not unique

You could hash the GUIDs. That way, you should get a result much faster.

Oh, of course, running multiple threads at the same time is also a good idea, that way you'll increase the chance of a race condition generating the same GUID twice on different threads.

What is the difference between % and %% in a cmd file?

(Explanation in more details can be found in an archived Microsoft KB article.)

Three things to know:

  1. The percent sign is used in batch files to represent command line parameters: %1, %2, ...
  2. Two percent signs with any characters in between them are interpreted as a variable:

    echo %myvar%

  3. Two percent signs without anything in between (in a batch file) are treated like a single percent sign in a command (not a batch file): %%f

Why's that?

For example, if we execute your (simplified) command line

FOR /f %f in ('dir /b .') DO somecommand %f

in a batch file, rule 2 would try to interpret

%f in ('dir /b .') DO somecommand %

as a variable. In order to prevent that, you have to apply rule 3 and escape the % with an second %:

FOR /f %%f in ('dir /b .') DO somecommand %%f

AngularJs - ng-model in a SELECT

You can use the ng-selected directive on the option elements. It takes expression that if truthy will set the selected property.

In this case:

<option ng-selected="data.unit == item.id" 
        ng-repeat="item in units" 
        ng-value="item.id">{{item.label}}</option>

Demo

_x000D_
_x000D_
angular.module("app",[]).controller("myCtrl",function($scope) {_x000D_
    $scope.units = [_x000D_
        {'id': 10, 'label': 'test1'},_x000D_
        {'id': 27, 'label': 'test2'},_x000D_
        {'id': 39, 'label': 'test3'},_x000D_
    ]_x000D_
_x000D_
        $scope.data = {_x000D_
        'id': 1,_x000D_
        'unit': 27_x000D_
        }_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<div ng-app="app" ng-controller="myCtrl">_x000D_
    <select class="form-control" ng-change="unitChanged()" ng-model="data.unit">_x000D_
         <option ng-selected="data.unit == item.id" ng-repeat="item in units" ng-value="item.id">{{item.label}}</option>_x000D_
    </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags?

<?php header("Access-Control-Allow-Origin: http://example.com"); ?>

This command disables only first console warning info

console

Result: console result

Linux cmd to search for a class file among jars irrespective of jar path

Linux, Walkthrough to find a class file among many jars.

Go to the directory that contains the jars underneath.

eric@dev /home/el/kafka_2.10-0.8.1.1/libs $ ls
blah.txt                             metrics-core-2.2.0.jar
jopt-simple-3.2.jar                  scala-library-2.10.1.jar
kafka_2.10-0.8.1.1-sources.jar       zkclient-0.3.jar
kafka_2.10-0.8.1.1-sources.jar.asc   zookeeper-3.3.4.jar
log4j-1.2.15.jar

I'm looking for which jar provides for the Producer class.

Understand how the for loop works:

eric@dev /home/el/kafka_2.10-0.8.1.1/libs $ for i in `seq 1 3`; do
> echo $i
> done
1
2
3

Understand why find this works:

eric@dev /home/el/kafka_2.10-0.8.1.1/libs $ find . -name "*.jar"
./slf4j-api-1.7.2.jar
./zookeeper-3.3.4.jar
./kafka_2.10-0.8.1.1-javadoc.jar
./slf4j-1.7.7/osgi-over-slf4j-1.7.7-sources.jar

You can pump all the jars underneath into the for loop:

eric@dev /home/el/kafka_2.10-0.8.1.1/libs $ for i in `find . -name "*.jar"`; do
> echo $i
> done

./slf4j-api-1.7.2.jar
./zookeeper-3.3.4.jar
./kafka_2.10-0.8.1.1-javadoc.jar
./kafka_2.10-0.8.1.1-sources.jar

Now we can operate on each one:

Do a jar tf on every jar and cram it into blah.txt:

for i in `find . -name "*.jar"`; do echo $i; jar tf $i; done > blah.txt

Inspect blah.txt, it's a list of all the classes in all the jars. You can search that file for the class you want, then look for the jar that came before it, that's the one you want.

What algorithm for a tic-tac-toe game can I use to determine the "best move" for the AI?

A typical algo for tic-tac-toe should look like this:

Board : A nine-element vector representing the board. We store 2 (indicating Blank), 3 (indicating X), or 5 (indicating O). Turn: An integer indicating which move of the game about to be played. The 1st move will be indicated by 1, last by 9.

The Algorithm

The main algorithm uses three functions.

Make2: returns 5 if the center square of the board is blank i.e. if board[5]=2. Otherwise, this function returns any non-corner square (2, 4, 6 or 8).

Posswin(p): Returns 0 if player p can’t win on his next move; otherwise, it returns the number of the square that constitutes a winning move. This function will enable the program both to win and to block opponents win. This function operates by checking each of the rows, columns, and diagonals. By multiplying the values of each square together for an entire row (or column or diagonal), the possibility of a win can be checked. If the product is 18 (3 x 3 x 2), then X can win. If the product is 50 (5 x 5 x 2), then O can win. If a winning row (column or diagonal) is found, the blank square in it can be determined and the number of that square is returned by this function.

Go (n): makes a move in square n. this procedure sets board [n] to 3 if Turn is odd, or 5 if Turn is even. It also increments turn by one.

The algorithm has a built-in strategy for each move. It makes the odd numbered move if it plays X, the even-numbered move if it plays O.

Turn = 1    Go(1)   (upper left corner).
Turn = 2    If Board[5] is blank, Go(5), else Go(1).
Turn = 3    If Board[9] is blank, Go(9), else Go(3).
Turn = 4    If Posswin(X) is not 0, then Go(Posswin(X)) i.e. [ block opponent’s win], else Go(Make2).
Turn = 5    if Posswin(X) is not 0 then Go(Posswin(X)) [i.e. win], else if Posswin(O) is not 0, then Go(Posswin(O)) [i.e. block win], else if Board[7] is blank, then Go(7), else Go(3). [to explore other possibility if there be any ].
Turn = 6    If Posswin(O) is not 0 then Go(Posswin(O)), else if Posswin(X) is not 0, then Go(Posswin(X)), else Go(Make2).
Turn = 7    If Posswin(X) is not 0 then Go(Posswin(X)), else if Posswin(X) is not 0, then Go(Posswin(O)) else go anywhere that is blank.
Turn = 8    if Posswin(O) is not 0 then Go(Posswin(O)), else if Posswin(X) is not 0, then Go(Posswin(X)), else go anywhere that is blank.
Turn = 9    Same as Turn=7.

I have used it. Let me know how you guys feel.

Deserializing JSON to .NET object using Newtonsoft (or LINQ to JSON maybe?)

Finally Get State Name From JSON

Thankyou!

Imports System
Imports System.Text
Imports System.IO
Imports System.Net
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Imports System.collections.generic

Public Module Module1
    Public Sub Main()

         Dim url As String = "http://maps.google.com/maps/api/geocode/json&address=attur+salem&sensor=false"
            Dim request As WebRequest = WebRequest.Create(url)
        dim response As WebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
        dim reader As New StreamReader(response.GetResponseStream(), Encoding.UTF8)
          Dim dataString As String = reader.ReadToEnd()

        Dim getResponse As JObject = JObject.Parse(dataString)

        Dim dictObj As Dictionary(Of String, Object) = getResponse.ToObject(Of Dictionary(Of String, Object))()
        'Get State Name
        Console.WriteLine(CStr(dictObj("results")(0)("address_components")(2)("long_name")))
    End Sub
End Module

Deserialize a json string to an object in python

>>> j = '{"action": "print", "method": "onData", "data": "Madan Mohan"}'
>>> import json
>>> 
>>> class Payload(object):
...     def __init__(self, j):
...         self.__dict__ = json.loads(j)
... 
>>> p = Payload(j)
>>>
>>> p.action
'print'
>>> p.method
'onData'
>>> p.data
'Madan Mohan'

How to use multiple LEFT JOINs in SQL?

You have two choices, depending on your table order

create table aa (sht int)
create table cc (sht int)
create table cd (sht int)
create table ab (sht int)

-- type 1    
select * from cd
inner join cc on cd.sht = cc.sht
LEFT JOIN ab ON ab.sht = cd.sht
LEFT JOIN aa ON aa.sht = cc.sht

-- type 2
select * from cc
inner join cc on cd.sht = cc.sht
LEFT JOIN ab
LEFT JOIN aa
ON aa.sht = ab.sht
ON ab.sht = cd.sht

Using multiple IF statements in a batch file

The explanation given by Merlyn above is pretty complete. However, I would like to elaborate on coding standards.

When several IF's are chained, the final command is executed when all the previous conditions are meet; this is equivalent to an AND operator. I used this behavior now and then, but I clearly indicate what I intend to do via an auxiliary Batch variable called AND:

SET AND=IF

IF EXIST somefile.txt %AND% EXIST someotherfile.txt SET var=somefile.txt,someotherfile.txt

Of course, this is NOT a true And operator and must not be used in combination with ELSE clause. This is just a programmer aid to increase the legibility of an instruction that is rarely used.

When I write Batch programs I always use several auxiliary variables that I designed with the sole purpose of write more readable code. For example:

SET AND=IF
SET THEN=(
SET ELSE=) ELSE (
SET NOELSE=
SET ENDIF=)
SET BEGIN=(
SET END=)
SET RETURN=EXIT /B

These variables aids in writting Batch programs in a much clearer way and helps to avoid subtle errors, as Merlyn suggested. For example:

IF EXIST "somefile.txt" %THEN%
  IF EXIST "someotherfile.txt" %THEN%
    SET var="somefile.txt,someotherfile.txt"
  %NOELSE%
  %ENDIF%
%NOELSE%
%ENDIF%

IF EXIST "%~1" %THEN%
  SET "result=%~1"
%ELSE%
  SET "result="
%ENDIF%

I even have variables that aids in writting WHILE-DO and REPEAT-UNTIL like constructs. This means that Batch variables may be used in some degree as preprocessor values.

Count number of rows matching a criteria

sum is used to add elements; nrow is used to count the number of rows in a rectangular array (typically a matrix or data.frame); length is used to count the number of elements in a vector. You need to apply these functions correctly.

Let's assume your data is a data frame named "dat". Correct solutions:

nrow(dat[dat$sCode == "CA",])
length(dat$sCode[dat$sCode == "CA"])
sum(dat$sCode == "CA")

Write a number with two decimal places SQL Server

If you only need two decimal places, simplest way is..

SELECT CAST(12 AS DECIMAL(16,2))

OR

SELECT CAST('12' AS DECIMAL(16,2))

Output

12.00

Simple excel find and replace for formulas

It turns out that the solution was to switch to R1C1 Cell Reference. My worksheet was structured in such a way that every formula had the same structure just different references. Luck though, they were always positioned the same way

=((E9-E8)/E8) 

became

=((R[-1]C-R[-2]C)/R[-2]C)

and

(EXP((LN(E9/E8)/14.32))-1)

became

=(EXP((LN(R[-1]C/R[-2]C)/14.32))-1)

In R1C1 Reference, every formula was identical so the find and replace required no wildcards. Thank you to those who answered!

How can I replace text with CSS?

Text replacement with pseudo-elements and CSS visibility

HTML

<p class="replaced">Original Text</p>

CSS

.replaced {
    visibility: hidden;
    position: relative;
}

.replaced:after {
    visibility: visible;
    position: absolute;
    top: 0;
    left: 0;
    content: "This text replaces the original.";
}

phpmailer error "Could not instantiate mail function"

We nee to change the values of 'SMTP' in php.ini file php.ini file is located into

EasyPHP-DevServer-14.1VC11\binaries\php\php_runningversion\php.ini

What is the strict aliasing rule?

The best explanation I have found is by Mike Acton, Understanding Strict Aliasing. It's focused a little on PS3 development, but that's basically just GCC.

From the article:

"Strict aliasing is an assumption, made by the C (or C++) compiler, that dereferencing pointers to objects of different types will never refer to the same memory location (i.e. alias each other.)"

So basically if you have an int* pointing to some memory containing an int and then you point a float* to that memory and use it as a float you break the rule. If your code does not respect this, then the compiler's optimizer will most likely break your code.

The exception to the rule is a char*, which is allowed to point to any type.

bootstrap button shows blue outline when clicked

Actually in bootstrap is defined all variables for all cases. In your case you just have to override default variable '$input-btn-focus-box-shadow' from '_variables.scss' file. Like so: $input-btn-focus-box-shadow: none; Note that you need to override that variable in your own custom '_yourCusomVarsFile.scss'. And that file should be import in project in first order and then bootstrap like so:

@import "yourCusomVarsFile";
@import "bootstrap/scss/bootstrap";
@import "someOther";

The bootstraps vars goes with flag '!default'.

$input-focus-box-shadow: $input-btn-focus-box-shadow !default;

So in your file, you will override default values. Here the illustration:

$input-focus-box-shadow: none;
$input-focus-box-shadow: $input-btn-focus-box-shadow !default;

The very first var have more priority then second one. The same is for the rest states and cases. Hope it will help you.

Here is '_variable.scss' file from repo, where you can find all initials values from bootstrap: https://github.com/twbs/bootstrap/blob/v4-dev/scss/_variables.scss

Chears

How do you performance test JavaScript code?

I have a small tool where I can quickly run small test-cases in the browser and immediately get the results:

JavaScript Speed Test

You can play with code and find out which technique is better in the tested browser.

The proxy server received an invalid response from an upstream server

This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.

There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.

The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like

1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host

EDIT

Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication

getting the ng-object selected with ng-change

<select ng-model="item.size.code">
<option ng-repeat="size in sizes" ng-attr-value="size.code">{{size.name}}          </option>
</select>

What is the difference between concurrency and parallelism?

Concurrency vs Parallelism

Rob Pike in 'Concurrency Is Not Parallelism'

Concurrency is about dealing with lots of things at once.

Parallelism is about doing lots of things at once.

[Concurrency theory]

Concurrency - handles waiting operation
Parallelism - handles thread stuff

My vision of concurrency and parallelism

enter image description here

[Sync vs Async]

Where does pip install its packages?

pip list -v can be used to list packages' install locations, introduced in https://pip.pypa.io/en/stable/news/#b1-2018-03-31

Show install locations when list command ran with “-v” option. (#979)

>pip list -v
Package                  Version   Location                                                             Installer
------------------------ --------- -------------------------------------------------------------------- ---------
alabaster                0.7.12    c:\users\me\appdata\local\programs\python\python38\lib\site-packages pip
apipkg                   1.5       c:\users\me\appdata\local\programs\python\python38\lib\site-packages pip
argcomplete              1.10.3    c:\users\me\appdata\local\programs\python\python38\lib\site-packages pip
astroid                  2.3.3     c:\users\me\appdata\local\programs\python\python38\lib\site-packages pip
...

This feature is introduced in pip 10.0.0b1. On Ubuntu 18.04 (Bionic Beaver), pip or pip3 installed with sudo apt install python-pip or sudo apt install python3-pip is 9.0.1 which doesn't have this feature.

Check https://github.com/pypa/pip/issues/5599 for suitable ways of upgrading pip or pip3.

How to debug a Flask app

Use loggers and print statements in the Development Environment, you can go for sentry in case of production environments.

PowerShell: how to grep command output?

There are two problems. As in the question, select-string needs to operate on the output string, which can be had from "out-string". Also, select-string doesn't operate linewise on strings that are piped to it. Here is a generic solution

(alias|out-string) -split "`n" | select-string Write 

Is it possible to capture the stdout from the sh DSL command in the pipeline

Now, the sh step supports returning stdout by supplying the parameter returnStdout.

// These should all be performed at the point where you've
// checked out your sources on the slave. A 'git' executable
// must be available.
// Most typical, if you're not cloning into a sub directory
gitCommit = sh(returnStdout: true, script: 'git rev-parse HEAD').trim()
// short SHA, possibly better for chat notifications, etc.
shortCommit = gitCommit.take(6)

See this example.

How to fast-forward a branch to head?

Try git merge origin/master. If you want to be sure that it only does a fast-forward, you can say git merge --ff-only origin/master.

Adding git branch on the Bash command prompt

vim ~/.bash

parse_git_branch() {
     git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}

export PS1="\u@\h \[\033[32m\]\w\[\033[33m\]\$(parse_git_branch)\[\033[00m\] $"

To reflect latest changes run following command

source ~/.bashrc

Output:-

chandrakant@NDL41104 ~/Chandrakant/CodeBase/LaravelApp (development) $

Editing the date formatting of x-axis tick labels in matplotlib

From the package matplotlib.dates as shown in this example the date format can be applied to the axis label and ticks for plot.

Below I have given an example for labeling axis ticks for multiplots

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd

df = pd.read_csv('US_temp.csv')
plt.plot(df['Date'],df_f['MINT'],label='Min Temp.')
plt.plot(df['Date'],df_f['MAXT'],label='Max Temp.')
plt.legend()
####### Use the below functions #######
dtFmt = mdates.DateFormatter('%b') # define the formatting
plt.gca().xaxis.set_major_formatter(dtFmt) # apply the format to the desired axis
plt.show()

As simple as that

How to run a cron job inside a docker container?

When you deploy your container on another host, just note that it won't start any processes automatically. You need to make sure that 'cron' service is running inside your container. In our case, I am using Supervisord with other services to start cron service.

[program:misc]
command=/etc/init.d/cron restart
user=root
autostart=true
autorestart=true
stderr_logfile=/var/log/misc-cron.err.log
stdout_logfile=/var/log/misc-cron.out.log
priority=998

Java: Integer equals vs. ==

Besides these given great answers, What I have learned is that:

NEVER compare objects with == unless you intend to be comparing them by their references.

How to size an Android view based on its parent's dimensions

I believe that Mayras XML-approach can come in neat. However it is possible to make it more accurate, with one view only by setting the weightSum. I would not call this a hack anymore but in my opinion the most straightforward approach:

<LinearLayout android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:weightSum="1">
    <ImageView android:layout_height="fill_parent"
               android:layout_width="0dp"
               android:layout_weight="0.5"/>
</LinearLayout>

Like this you can use any weight, 0.6 for instance (and centering) is the weight I like to use for buttons.

Append text with .bat

Any line starting with a "REM" is treated as a comment, nothing is executed including the redirection.

Also, the %date% variable may contain "/" characters which are treated as path separator characters, leading to the system being unable to create the desired log file.

Convert float64 column to int64 in Pandas

consider using

df['column name'].astype('Int64')

nan will be changed to NaN

SCCM 2012 application install "Failed" in client Software Center

The execmgr.log will show the commandline and ccmcache folder used for installation. Typically, required apps don't show on appenforce.log and some clients will have outdated appenforce or no ppenforce.log files. execmgr.log also shows required hidden uninstall actions as well.

You may want to save the blog link. I still reference it from time to time.

Get a list of dates between two dates using a function

if you're in a situation like me where procedures and functions are prohibited, and your sql user does not have permissions for insert, therefore insert not allowed, also "set/declare temporary variables like @c is not allowed", but you want to generate a list of dates in a specific period, say current year to do some aggregation, use this

select * from 
(select adddate('1970-01-01',t4*10000 + t3*1000 + t2*100 + t1*10 + t0) gen_date from
 (select 0 t0 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 t1 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 t2 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 t3 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 t4 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 gen_date between '2017-01-01' and '2017-12-31'

How to change int into int64?

This is called type conversion :

i := 23
var i64 int64
i64 = int64(i)

jQuery textbox change event doesn't fire until textbox loses focus?

Try this:

$("#textbox").bind('paste',function() {alert("Change detected!");});

See demo on JSFiddle.

Replace whole line containing a string using Sed

cat find_replace | while read pattern replacement ; do
sed -i "/${pattern}/c ${replacement}" file    
done 

find_replace file contains 2 columns, c1 with pattern to match, c2 with replacement, the sed loop replaces each line conatining one of the pattern of variable 1

How do I change a TCP socket to be non-blocking?

I know it's an old question, but for everyone on google ending up here looking for information on how to deal with blocking and non-blocking sockets here is an in depth explanation of the different ways how to deal with the I/O modes of sockets - http://dwise1.net/pgm/sockets/blocking.html.

Quick summary:

  • So Why do Sockets Block?

  • What are the Basic Programming Techniques for Dealing with Blocking Sockets?

    • Have a design that doesn't care about blocking
    • Using select
    • Using non-blocking sockets.
    • Using multithreading or multitasking

The specified DSN contains an architecture mismatch between the Driver and Application. JAVA

None of these did it for me. I did find the answer on MSDN. There were hints to it though. The architecture in the error is referring to 32 vs 64 bits. My solution was to find out which my app is running under (Access) which 2010 is 32b. I found this by looking in the Process tab of Task Manager where all 32b processes have * 32 the end of their names. As was said, the control panel will launch the 64 bit version of ODBC from here

c:\windows\system32\odbcad32.exe

and the 32 bit version is here:

c:\windows\sysWOW64\odbcad32.exe (easiest to copy and paste into run dialog)

So I set up DSNs with names ending in 32 and 64 in each of the corresponding ODBC control panels (AKA Administrator) that pointed to the same thing. Then, I picked/pick the correct one based on whether the app using it is 32b or 64b.

How do I return clean JSON from a WCF Service?

If you want nice json without hardcoding attributes into your service classes,

use <webHttp defaultOutgoingResponseFormat="Json"/> in your behavior config

File size exceeds configured limit (2560000), code insight features not available

Windows default install location for Webstorm:

C:\Program Files\JetBrains\WebStorm 2019.1.3\bin\idea.properties

I went x4 default for intellisense and x5 for file size

(my business workstation is a beast though: 8th gen i7, 32Gb RAM, NVMe PCIE3.0x4 SDD, gloat, etc, gloat, etc)

#---------------------------------------------------------------------
# Maximum file size (kilobytes) IDE should provide code assistance for.
# The larger file is the slower its editor works and higher overall system memory requirements are
# if code assistance is enabled. Remove this property or set to very large number if you need
# code assistance for any files available regardless their size.
#--------------------------------------------------------------------- 
idea.max.intellisense.filesize=10000

    #---------------------------------------------------------------------
    # Maximum file size (kilobytes) IDE is able to open.
    #--------------------------------------------------------------------- 

idea.max.content.load.filesize=100000

Java - How to create new Entry (key, value)

If you look at the documentation of Map.Entry you will find that it is a static interface (an interface which is defined inside the Map interface an can be accessed through Map.Entry) and it has two implementations

All Known Implementing Classes:
AbstractMap.SimpleEntry, AbstractMap.SimpleImmutableEntry

The class AbstractMap.SimpleEntry provides 2 constructors:

Constructors and Description
AbstractMap.SimpleEntry(K key, V value)
Creates an entry representing a mapping from the specified key to the
specified value.
AbstractMap.SimpleEntry(Map.Entry<? extends K,? extends V> entry)
Creates an entry representing the same mapping as the specified entry.

An example use case:

import java.util.Map;
import java.util.AbstractMap.SimpleEntry;

public class MyClass {
    public static void main(String args[]) {
      Map.Entry e = new SimpleEntry<String, String>("Hello","World");

      System.out.println(e.getKey()+" "+e.getValue());
    }
}

Simulate delayed and dropped packets on Linux

One of the most used tool in the scientific community to that purpose is DummyNet. Once you have installed the ipfw kernel module, in order to introduce 50ms propagation delay between 2 machines simply run these commands:

./ipfw pipe 1 config delay 50ms
./ipfw add 1000 pipe 1 ip from $IP_MACHINE_1 to $IP_MACHINE_2

In order to also introduce 50% of packet losses you have to run:

./ipfw pipe 1 config plr 0.5

Here more details.

How to tell if node.js is installed or not

(This is for windows OS but concept can be applied to other OS)

Running command node -v will be able to confirm if it is installed, however it will not be able to confirm if it is NOT installed. (Executable may not be on your PATH)

Two ways you can check if it is actually installed:

  1. Check default install location C:\Program Files\nodejs\

or

  1. Go to System Settings -> Add or Remove Programs and filter by node, it should show you if you have it installed. For me, it shows as title:"Node.js" and description "Node.js Foundation", with no version specified. Install size is 52.6MB

If you don't have it installed, get it from here https://nodejs.org/en/download/

Filter array to have unique values

I've always used:

unique = (arr) => arr.filter((item, i, s) => s.lastIndexOf(item) == i);

But recently I had to get unique values for:

["1", 1, "2", 2, "3", 3]

And my old standby didn't cut it, so I came up with this:

uunique = (arr) => Object.keys(Object.assign({}, ...arr.map(a=>({[a]:true}))));

How can I commit a single file using SVN over a network?

strange that your command works, i thougth it would need a target directory. but it looks like it assumes current pwd as default.

cd myapp
svn ci page1.html

you can also just do svn ci in or on that folder and it will detect all changes automatically and give you a list of what will be checked in

man svn tells you the rest

UITableView Separator line

Here is an alternate way to add a custom separator line to a UITableView by making a CALayer for the image and using that as the separator line.

// make a CALayer for the image for the separator line

CALayer *separator = [CALayer layer];
separator.contents = (id)[UIImage imageNamed:@"myImage.png"].CGImage;
separator.frame = CGRectMake(0, 54, self.view.frame.size.width, 2);
[cell.layer addSublayer:separator];

How do I add a margin between bootstrap columns without wrapping

Change the number of @grid-columns. Then use -offset. Changing the number of columns will allow you to control the amount of space between columns. E.g.

variables.less (approx line 294).

@grid-columns:              20;

someName.html

<div class="row">
  <div class="col-md-4 col-md-offset-1">First column</div>
  <div class="col-md-13 col-md-offset-1">Second column</div>
</div>

How do you add a Dictionary of items into another Dictionary

import Foundation

let x = ["a":1]
let y = ["b":2]

let out = NSMutableDictionary(dictionary: x)
out.addEntriesFromDictionary(y)

The result is an NSMutableDictionary not a Swift typed dictionary, but the syntax to use it is the same (out["a"] == 1 in this case) so you'd only have a problem if you're using third-party code which expects a Swift dictionary, or really need the type checking.

The short answer here is that you actually do have to loop. Even if you're not entering it explicitly, that's what the method you're calling (addEntriesFromDictionary: here) will do. I'd suggest if you're a bit unclear on why that would be the case you should consider how you would merge the leaf nodes of two B-trees.

If you really actually need a Swift native dictionary type in return, I'd suggest:

let x = ["a":1]
let y = ["b":2]

var out = x
for (k, v) in y {
    out[k] = v
}

The downside of this approach is that the dictionary index - however it's done - may be rebuilt several times in the loop, so in practice this is about 10x slower than the NSMutableDictionary approach.

VirtualBox Cannot register the hard disk already exists

Here is the solution for that find the UUID of box

vboxmanage list hdds

then delete by

vboxmanage closemedium disk <uuid> --delete

Count the number of all words in a string

I've found the following function and regex useful for word counts, especially in dealing with single vs. double hyphens, where the former generally should not count as a word break, eg, well-known, hi-fi; whereas double hyphen is a punctuation delimiter that is not bounded by white-space--such as for parenthetical remarks.

txt <- "Don't you think e-mail is one word--and not two!" #10 words
words <- function(txt) { 
length(attributes(gregexpr("(\\w|\\w\\-\\w|\\w\\'\\w)+",txt)[[1]])$match.length) 
}

words(txt) #10 words

Stringi is a useful package. But it over-counts words in this example due to hyphen.

stringi::stri_count_words(txt) #11 words

Replace all non-alphanumeric characters in a string

Regex to the rescue!

import re

s = re.sub('[^0-9a-zA-Z]+', '*', s)

Example:

>>> re.sub('[^0-9a-zA-Z]+', '*', 'h^&ell`.,|o w]{+orld')
'h*ell*o*w*orld'

What command shows all of the topics and offsets of partitions in Kafka?

Kafka ships with some tools you can use to accomplish this.

List topics:

# ./bin/kafka-topics.sh --list --zookeeper localhost:2181
test_topic_1
test_topic_2
...

List partitions and offsets:

# ./bin/kafka-run-class.sh kafka.tools.ConsumerOffsetChecker --broker-info --group test_group --topic test_topic --zookeeper localhost:2181
Group           Topic                  Pid Offset          logSize         Lag             Owner
test_group      test_topic             0   698020          698021          1              test_group-0
test_group      test_topic             1   235699          235699          0               test_group-1
test_group      test_topic             2   117189          117189          0               test_group-2

Update for 0.9 (and higher) consumer APIs

If you're using the new apis, there's a new tool you can use: kafka-consumer-groups.sh.

./bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --group count_errors --describe
GROUP                          TOPIC                          PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             OWNER
count_errors                   logs                           2          2908278         2908278         0               consumer-1_/10.8.0.55
count_errors                   logs                           3          2907501         2907501         0               consumer-1_/10.8.0.43
count_errors                   logs                           4          2907541         2907541         0               consumer-1_/10.8.0.177
count_errors                   logs                           1          2907499         2907499         0               consumer-1_/10.8.0.115
count_errors                   logs                           0          2907469         2907469         0               consumer-1_/10.8.0.126

How to read file using NPOI

private DataTable GetDataTableFromExcel(String Path)
    {
        XSSFWorkbook wb;
        XSSFSheet sh;
        String Sheet_name;

        using (var fs = new FileStream(Path, FileMode.Open, FileAccess.Read))
        {
            wb = new XSSFWorkbook(fs);

               Sheet_name= wb.GetSheetAt(0).SheetName;  //get first sheet name
        }
        DataTable DT = new DataTable();
        DT.Rows.Clear();
        DT.Columns.Clear();

        // get sheet
        sh = (XSSFSheet)wb.GetSheet(Sheet_name);

        int i = 0;
        while (sh.GetRow(i) != null)
        {
            // add neccessary columns
            if (DT.Columns.Count < sh.GetRow(i).Cells.Count)
            {
                for (int j = 0; j < sh.GetRow(i).Cells.Count; j++)
                {
                    DT.Columns.Add("", typeof(string));
                }
            }

            // add row
            DT.Rows.Add();

            // write row value
            for (int j = 0; j < sh.GetRow(i).Cells.Count; j++)
            {
                var cell = sh.GetRow(i).GetCell(j);

                if (cell != null)
                {
                    // TODO: you can add more cell types capatibility, e. g. formula
                    switch (cell.CellType)
                    {
                        case NPOI.SS.UserModel.CellType.Numeric:
                            DT.Rows[i][j] = sh.GetRow(i).GetCell(j).NumericCellValue;
                            //dataGridView1[j, i].Value = sh.GetRow(i).GetCell(j).NumericCellValue;

                            break;
                        case NPOI.SS.UserModel.CellType.String:
                            DT.Rows[i][j] = sh.GetRow(i).GetCell(j).StringCellValue;

                            break;
                    }
                }
            }

            i++;
        }

        return DT;
    }

Accessing a Dictionary.Keys Key through a numeric index

One alternative would be a KeyedCollection if the key is embedded in the value.

Just create a basic implementation in a sealed class to use.

So to replace Dictionary<string, int> (which isn't a very good example as there isn't a clear key for a int).

private sealed class IntDictionary : KeyedCollection<string, int>
{
    protected override string GetKeyForItem(int item)
    {
        // The example works better when the value contains the key. It falls down a bit for a dictionary of ints.
        return item.ToString();
    }
}

KeyedCollection<string, int> intCollection = new ClassThatContainsSealedImplementation.IntDictionary();

intCollection.Add(7);

int valueByIndex = intCollection[0];