Programs & Examples On #One time password

One time passwords are designed as single use passwords which expire after use. They are often more secure than single factor authentication methods such as username-password (something the user knows) due to their single use which makes replay attacks impossible

OTP (token) should be automatically read from the message

Yes, this is possible now in browsers also. Chrome release this feature in version 84 and above. With the help of WEBOTP API, we can detect OTP on the web for mobile devices.

Here is a Web-OTP integrated code with Angular PWA Apps: https://github.com/Rohit3230/webOtpAutoReadByAngular

Go for live working URL for angular PWA app. https://rohit3230.github.io/webOtpAutoReadByAngular/

When increasing the size of VARCHAR column on a large table could there be any problems?

Changing to Varchar(1200) from Varchar(200) should cause you no issue as it is only a metadata change and as SQL server 2008 truncates excesive blank spaces you should see no performance differences either so in short there should be no issues with making the change.

How do I use NSTimer?

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(timerCalled) userInfo:nil repeats:NO];

-(void)timerCalled
{
     NSLog(@"Timer Called");
     // Your Code
}

Microsoft.WebApplication.targets was not found, on the build server. What's your solution?

Anyone coming here for Visual Studio 2017. I had the similar issue and couldn't compile the project after update to 15.6.1. I had to install MSBulild tools but still the error was there.

I was able to fix the issue by copying the v14.0 folder from C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio to the same folder as v15.0 and that resolved all the errors. So now my folder structure looks like below, where both folders contain the same content.

enter image description here

How do I check which version of NumPy I'm using?

You can also check if your version is using MKL with:

import numpy
numpy.show_config()

How to compare binary files to check if they are the same?

Radiff2 is a tool designed to compare binary files, similar to how regular diff compares text files.

Try radiff2 which is a part of radare2 disassembler. For instance, with this command:

radiff2 -x file1.bin file2.bin

You get pretty formatted two columns output where differences are highlighted.

Javascript: How to remove the last character from a div or a string?

$('#mainn').text(function (_,txt) {
    return txt.slice(0, -1);
});

demo --> http://jsfiddle.net/d72ML/8/

How do you properly use WideCharToMultiByte

Elaborating on the answer provided by Brian R. Bondy: Here's an example that shows why you can't simply size the output buffer to the number of wide characters in the source string:

#include <windows.h>
#include <stdio.h>
#include <wchar.h>
#include <string.h>

/* string consisting of several Asian characters */
wchar_t wcsString[] = L"\u9580\u961c\u9640\u963f\u963b\u9644";

int main() 
{

    size_t wcsChars = wcslen( wcsString);

    size_t sizeRequired = WideCharToMultiByte( 950, 0, wcsString, -1, 
                                               NULL, 0,  NULL, NULL);

    printf( "Wide chars in wcsString: %u\n", wcsChars);
    printf( "Bytes required for CP950 encoding (excluding NUL terminator): %u\n",
             sizeRequired-1);

    sizeRequired = WideCharToMultiByte( CP_UTF8, 0, wcsString, -1,
                                        NULL, 0,  NULL, NULL);
    printf( "Bytes required for UTF8 encoding (excluding NUL terminator): %u\n",
             sizeRequired-1);
}

And the output:

Wide chars in wcsString: 6
Bytes required for CP950 encoding (excluding NUL terminator): 12
Bytes required for UTF8 encoding (excluding NUL terminator): 18

How to convert datatype:object to float64 in python?

You can try this:

df['2nd'] = pd.to_numeric(df['2nd'].str.replace(',', ''))
df['CTR'] = pd.to_numeric(df['CTR'].str.replace('%', ''))

How to rename a file using Python

import shutil
import os

files = os.listdir("./pics/") 

for key in range(0, len(files)):
   print files[key]
   shutil.move("./pics/" + files[key],"./pics/img" + str(key) + ".jpeg")

This should do it. python 3+

Setting device orientation in Swift iOS

From ios 10.0 we need set { self.orientations = newValue } for setting up the orientation, Make sure landscape property is enabled in your project.

private var orientations = UIInterfaceOrientationMask.landscapeLeft
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
    get { return self.orientations }
    set { self.orientations = newValue }
}

How to use multiple LEFT JOINs in SQL?

Yes, but the syntax is different than what you have

SELECT
    <fields>
FROM
    <table1>
    LEFT JOIN <table2>
        ON <criteria for join>
        AND <other criteria for join>
    LEFT JOIN <table3> 
        ON <criteria for join>
        AND <other criteria for join>

How do I run a Java program from the command line on Windows?

To complete the answer :

  1. The Java File

    TheJavaFile.java
    
  2. Compile the Java File to a *.class file

    javac TheJavaFile.java
    
    • This will create a TheJavaFile.class file
  3. Execution of the Java File

    java TheJavaFile
    
  4. Creation of an executable *.jar file

    • You've got two options here -

      1. With an external manifest file :

        • Create the manifest file say - MANIFEST.mf

        • The MANIFEST file is nothing but an explicit entry of the Main Class

        • jar -cvfm TheJavaFile.jar MANIFEST.mf TheJavaFile.class

      2. Executable by Entry Point:

        • jar -cvfe TheJavaFile.jar <MainClass> TheJavaFile.class
  5. To run the Jar File

    java -jar TheJavaFile.jar
    

How to remove leading whitespace from each line in a file

Use:

sed -e **'s/^[ \t]*//'**  name_of_file_from_which_you_want_to_remove_space > 'name _file_where_you_want_to_store_output'

For example:

sed -e 's/^[ \t]*//'  file1.txt > output.txt

Note:

s/: Substitute command ~ replacement for pattern (^[ \t]*) on each addressed line

^[ \t]*: Search pattern ( ^ – start of the line; [ \t]* match one or more blank spaces including tab)

//: Replace (delete) all matched patterns

Two statements next to curly brace in an equation

Or this:

f(x)=\begin{cases}
0, & -\pi\leqslant x <0\\
\pi, & 0 \leqslant x \leqslant +\pi
\end{cases}

Does Eclipse have line-wrap

Try AhtiK Eclipse WordWrap, it works for me: http://www.ahtik.com/eclipse-update/

seek() function?

When you open a file, the system points to the beginning of the file. Any read or write you do will happen from the beginning. A seek() operation moves that pointer to some other part of the file so you can read or write at that place.

So, if you want to read the whole file but skip the first 20 bytes, open the file, seek(20) to move to where you want to start reading, then continue with reading the file.

Or say you want to read every 10th byte, you could write a loop that does seek(9, 1) (moves 9 bytes forward relative to the current positions), read(1) (reads one byte), repeat.

Proper use of errors

Simple solution to emit and show message by Exception.

try {
  throw new TypeError("Error message");
}
catch (e){
  console.log((<Error>e).message);//conversion to Error type
}

Caution

Above is not a solution if we don't know what kind of error can be emitted from the block. In such cases type guards should be used and proper handling for proper error should be done - take a look on @Moriarty answer.

Converting List<Integer> to List<String>

Another Solution using Guava and Java 8

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<String> strings = Lists.transform(numbers, number -> String.valueOf(number));

java.lang.IllegalArgumentException: contains a path separator

String all = "";
        try {
            BufferedReader br = new BufferedReader(new FileReader(filePath));
            String strLine;
            while ((strLine = br.readLine()) != null){
                all = all + strLine;
            }
        } catch (IOException e) {
            Log.e("notes_err", e.getLocalizedMessage());
        }

How can the default node version be set using NVM?

You can also like this:

$ nvm alias default lts/fermium

Python: Passing variables between functions

Read up the concept of a name space. When you assign a variable in a function, you only assign it in the namespace of this function. But clearly you want to use it between all functions.

def defineAList():
    #list = ['1','2','3'] this creates a new list, named list in the current namespace.
    #same name, different list!

    list.extend['1', '2', '3', '4'] #this uses a method of the existing list, which is in an outer namespace
    print "For checking purposes: in defineAList, list is",list
    return list

Alternatively, you can pass it around:

def main():
    new_list = defineAList()
    useTheList(new_list)

Is there a "not equal" operator in Python?

There are two operators in Python for the "not equal" condition -

a.) != If values of the two operands are not equal, then the condition becomes true. (a != b) is true.

b.) <> If values of the two operands are not equal, then the condition becomes true. (a <> b) is true. This is similar to the != operator.

Android/Java - Date Difference in days

There's a simple solution, that at least for me, is the only feasible solution.

The problem is that all the answers I see being tossed around - using Joda, or Calendar, or Date, or whatever - only take the amount of milliseconds into consideration. They end up counting the number of 24-hour cycles between two dates, rather than the actual number of days. So something from Jan 1st 11pm to Jan 2nd 1am will return 0 days.

To count the actual number of days between startDate and endDate, simply do:

// Find the sequential day from a date, essentially resetting time to start of the day
long startDay = startDate.getTime() / 1000 / 60 / 60 / 24;
long endDay = endDate.getTime() / 1000 / 60 / 60 / 24;

// Find the difference, duh
long daysBetween = endDay - startDay;

This will return "1" between Jan 2nd and Jan 1st. If you need to count the end day, just add 1 to daysBetween (I needed to do that in my code since I wanted to count the total number of days in the range).

This is somewhat similar to what Daniel has suggested but smaller code I suppose.

Click outside menu to close in jquery

2 options that you can investigate:

  • On showing of the menu, place a large empty DIV behind it covering up the rest of the page and give that an on-click event to close the menu (and itself). This is akin to the methods used with lightboxes where clicking on the background closes the lightbox
  • On showing of the menu, attach a one-time click event handler on the body that closes the menu. You use jQuery's '.one()' for this.

Good PHP ORM Library?

Until PHP 5.3 release don't expect to have a good ORM. It's a OO limitation of PHP.

Convert pandas.Series from dtype object to float, and errors to nans

In [30]: pd.Series([1,2,3,4,'.']).convert_objects(convert_numeric=True)
Out[30]: 
0     1
1     2
2     3
3     4
4   NaN
dtype: float64

'if' statement in jinja2 template

We need to remember that the {% endif %} comes after the {% else %}.

So this is an example:

{% if someTest %}
     <p> Something is True </p>
{% else %}
     <p> Something is False </p>
{% endif %}

Python Binomial Coefficient

A bit shortened multiplicative variant given by PM 2Ring and alisianoi. Works with python 3 and doesn't require any packages.

def comb(n, k):
  # Remove the next two lines if out-of-range check is not needed
  if k < 0 or k > n:
    return None
  x = 1
  for i in range(min(k, n - k)):
    x = x*(n - i)//(i + 1)
  return x

Or

from functools import reduce
def comb(n, k):
  return (None if k < 0 or k > n else
    reduce(lambda x, i: x*(n - i)//(i + 1), range(min(k, n - k)), 1))

The division is done right after multiplication not to accumulate high numbers.

Parsing JSON Object in Java

I'm assuming you want to store the interestKeys in a list.

Using the org.json library:

JSONObject obj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");

List<String> list = new ArrayList<String>();
JSONArray array = obj.getJSONArray("interests");
for(int i = 0 ; i < array.length() ; i++){
    list.add(array.getJSONObject(i).getString("interestKey"));
}

How can I create a correlation matrix in R?

You could use 'corrplot' package.

d <- data.frame(x1=rnorm(10),
                 x2=rnorm(10),
                 x3=rnorm(10))
M <- cor(d) # get correlations

library('corrplot') #package corrplot
corrplot(M, method = "circle") #plot matrix

enter image description here

More information here: http://cran.r-project.org/web/packages/corrplot/vignettes/corrplot-intro.html

Connect Android Studio with SVN

  1. Run Android Studio.
  2. From the menu bar, select Android Studio
  3. Under IDE Settings, click Plugins and then select Search Subversion Integration
  4. Check SubVersion.
  5. Restart Android Studio.

Get the POST request body from HttpServletRequest

This works for both GET and POST:

@Context
private HttpServletRequest httpRequest;


private void printRequest(HttpServletRequest httpRequest) {
    System.out.println(" \n\n Headers");

    Enumeration headerNames = httpRequest.getHeaderNames();
    while(headerNames.hasMoreElements()) {
        String headerName = (String)headerNames.nextElement();
        System.out.println(headerName + " = " + httpRequest.getHeader(headerName));
    }

    System.out.println("\n\nParameters");

    Enumeration params = httpRequest.getParameterNames();
    while(params.hasMoreElements()){
        String paramName = (String)params.nextElement();
        System.out.println(paramName + " = " + httpRequest.getParameter(paramName));
    }

    System.out.println("\n\n Row data");
    System.out.println(extractPostRequestBody(httpRequest));
}

static String extractPostRequestBody(HttpServletRequest request) {
    if ("POST".equalsIgnoreCase(request.getMethod())) {
        Scanner s = null;
        try {
            s = new Scanner(request.getInputStream(), "UTF-8").useDelimiter("\\A");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s.hasNext() ? s.next() : "";
    }
    return "";
}

How can I install MacVim on OS X?

  • Step 1. Install homebrew from here: http://brew.sh
  • Step 1.1. Run export PATH=/usr/local/bin:$PATH
  • Step 2. Run brew update
  • Step 3. Run brew install vim && brew install macvim
  • Step 4. Run brew link macvim

You now have the latest versions of vim and macvim managed by brew. Run brew update && brew upgrade every once in a while to upgrade them.

This includes the installation of the CLI mvim and the mac application (which both point to the same thing).

I use this setup and it works like a charm. Brew even takes care of installing vim with the preferable options.

Is there a way to make mv create the directory to be moved to if it doesn't exist?

mkdir -p `dirname /destination/moved_file_name.txt`  
mv /full/path/the/file.txt  /destination/moved_file_name.txt

In Javascript, how to conditionally add a member to an object?

With EcmaScript2015 you can use Object.assign:

Object.assign(a, conditionB ? { b: 1 } : null,
                 conditionC ? { c: 2 } : null,
                 conditionD ? { d: 3 } : null);

_x000D_
_x000D_
var a, conditionB, conditionC, conditionD;_x000D_
conditionC = true;_x000D_
a = {};_x000D_
Object.assign(a, conditionB ? { b: 1 } : null,_x000D_
                 conditionC ? { c: 2 } : null,_x000D_
                 conditionD ? { d: 3 } : null);_x000D_
_x000D_
console.log(a);
_x000D_
_x000D_
_x000D_

Some remarks:

  • Object.assign modifies the first argument in-place, but it also returns the updated object: so you can use this method in a bigger expression that further manipulates the object.
  • Instead of null you could pass undefined or {}, with the same result. You could even provide 0 instead, because primitive values are wrapped, and Number has no own enumerable properties.

Even more concise

Taking the second point further, you could shorten it as follows (as @Jamie has pointed out), as falsy values have no own enumerable properties (false, 0, NaN, null, undefined, '', except document.all):

Object.assign(a, conditionB && { b: 1 },
                 conditionC && { c: 2 },
                 conditionD && { d: 3 });

_x000D_
_x000D_
var a, conditionB, conditionC, conditionD;_x000D_
conditionC = "this is truthy";_x000D_
conditionD = NaN; // falsy_x000D_
a = {};_x000D_
Object.assign(a, conditionB && { b: 1 },_x000D_
                 conditionC && { c: 2 },_x000D_
                 conditionD && { d: 3 });_x000D_
console.log(a);
_x000D_
_x000D_
_x000D_

How do you read scanf until EOF in C?

I guess best way to do this is ...

int main()
{
    char str[100];
    scanf("[^EOF]",str);
    printf("%s",str);
    return 0;     
}

Browser back button handling

You can also add hash when page is loading:

location.hash = "noBack";

Then just handle location hash change to add another hash:

$(window).on('hashchange', function() {
    location.hash = "noBack";
});

That makes hash always present and back button tries to remove hash at first. Hash is then added again by "hashchange" handler - so page would never actually can be changed to previous one.

How do you find all subclasses of a given class in Java?

The reason you see a difference between your implementation and Eclipse is because you scan each time, while Eclipse (and other tools) scan only once (during project load most of the times) and create an index. Next time you ask for the data it doesn't scan again, but look at the index.

How to insert a line break before an element using CSS

You can also use the pre-encoded HTML entity for a line break &#10; in your content and it'll have the same effect.

JavaScript single line 'if' statement - best syntax, this alternative?

Example in arrow functions:

let somethingTrue = true
[1,2,3,4,5].map(i=>somethingTrue && i*2)

In promises:

Promise.resolve()
  .then(_=>checkTrueFalse && asyncFunc())
  .then(_=>{ .. })

Otherwise:

if(somethingTrue) thenDo()

If it's just a simple conditional, I prefer using if(value) whenever possible because the word if in the beginning of the statement says more about what's happening than paranthesis and questionmarks.

Read text from response

Your "application/xrds+xml" was giving me issues, I was receiving a Content-Length of 0 (no response).

After removing that, you can access the response using response.GetResponseStream().

HttpWebRequest request = WebRequest.Create("http://google.com") as HttpWebRequest;

//request.Accept = "application/xrds+xml";  
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

WebHeaderCollection header = response.Headers;

var encoding = ASCIIEncoding.ASCII;
using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
{
    string responseText = reader.ReadToEnd();
}

Force a screen update in Excel VBA

Add a DoEvents function inside the loop, see below.

You may also want to ensure that the Status bar is visible to the user and reset it when your code completes.

Sub ProgressMeter()

Dim booStatusBarState As Boolean
Dim iMax As Integer
Dim i As Integer

iMax = 10000

    Application.ScreenUpdating = False
''//Turn off screen updating

    booStatusBarState = Application.DisplayStatusBar
''//Get the statusbar display setting

    Application.DisplayStatusBar = True
''//Make sure that the statusbar is visible

    For i = 1 To iMax ''// imax is usually 30 or so
        fractionDone = CDbl(i) / CDbl(iMax)
        Application.StatusBar = Format(fractionDone, "0%") & " done..."
        ''// or, alternatively:
        ''// statusRange.value = Format(fractionDone, "0%") & " done..."
        ''// Some code.......

        DoEvents
        ''//Yield Control

    Next i

    Application.DisplayStatusBar = booStatusBarState
''//Reset Status bar display setting

    Application.StatusBar = False
''//Return control of the Status bar to Excel

    Application.ScreenUpdating = True
''//Turn on screen updating

End Sub

Missing .map resource?

jQuery recently started using source maps.

For example, let's look at the minified jQuery 2.0.3 file's first few lines.

/*! jQuery v2.0.3 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license
//@ sourceMappingURL=jquery.min.map
*/

Excerpt from Introduction to JavaScript Source Maps:

Have you ever found yourself wishing you could keep your client-side code readable and more importantly debuggable even after you've combined and minified it, without impacting performance? Well now you can through the magic of source maps.

Basically it's a way to map a combined/minified file back to an unbuilt state. When you build for production, along with minifying and combining your JavaScript files, you generate a source map which holds information about your original files. When you query a certain line and column number in your generated JavaScript you can do a lookup in the source map which returns the original location. Developer tools (currently WebKit nightly builds, Google Chrome, or Firefox 23+) can parse the source map automatically and make it appear as though you're running unminified and uncombined files.

emphasis mine

It's incredibly useful, and will only download if the user opens dev tools.

Solution

Remove the source mapping line, or do nothing. It isn't really a problem.


Side note: your server should return 404, not 500. It could point to a security problem if this happens in production.

How to part DATE and TIME from DATETIME in MySQL

Simply,
SELECT TIME(column_name), DATE(column_name)

jQuery posting JSON

You post JSON like this

$.ajax(url, {
    data : JSON.stringify(myJSObject),
    contentType : 'application/json',
    type : 'POST',
    ...

if you pass an object as settings.data jQuery will convert it to query parameters and by default send with the data type application/x-www-form-urlencoded; charset=UTF-8, probably not what you want

How to concatenate two strings in C++?

It is better to use C++ string class instead of old style C string, life would be much easier.

if you have existing old style string, you can covert to string class

    char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
    cout<<greeting + "and there \n"; //will not compile because concat does \n not work on old C style string
    string trueString = string (greeting);
    cout << trueString + "and there \n"; // compiles fine
    cout << trueString + 'c'; // this will be fine too. if one of the operand if C++ string, this will work too

How to refresh activity after changing language (Locale) inside application

For Android 4.2 (API 17), you need to use android:configChanges="locale|layoutDirection" in your AndroidManifest.xml. See onConfigurationchanged is not called over jellybean(4.2.1)

WCF Error "This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case"

Try to browse the service in the browser and in the Https mode, if it is not brow-sable then it proves the reason for this error. Now, to solve this error you need to check :

  • https port , check if it is not being used by some other resources (website)
  • Check if certificate for https are properly configured or not (check signing authority, self signed certificate, using multiple certificate )
  • check WCF service binding and configuration for Https mode

Difference between string and char[] types in C++

Well, string type is a completely managed class for character strings, while char[] is still what it was in C, a byte array representing a character string for you.

In terms of API and standard library everything is implemented in terms of strings and not char[], but there are still lots of functions from the libc that receive char[] so you may need to use it for those, apart from that I would always use std::string.

In terms of efficiency of course a raw buffer of unmanaged memory will almost always be faster for lots of things, but take in account comparing strings for example, std::string has always the size to check it first, while with char[] you need to compare character by character.

How do you increase the max number of concurrent connections in Apache?

change the MaxClients directive. it is now on 256.

Animation CSS3: display + opacity

I changed a bit but the result is beautiful.

.child {
    width: 0px;
    height: 0px;
    opacity: 0;
}

.parent:hover child {
    width: 150px;
    height: 300px;
    opacity: .9;
}

Thank you to everyone.

How to pass prepareForSegue: an object

Simply grab a reference to the target view controller in prepareForSegue: method and pass any objects you need to there. Here's an example...

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Make sure your segue name in storyboard is the same as this line
    if ([[segue identifier] isEqualToString:@"YOUR_SEGUE_NAME_HERE"])
    {
        // Get reference to the destination view controller
        YourViewController *vc = [segue destinationViewController];

        // Pass any objects to the view controller here, like...
        [vc setMyObjectHere:object];
    }
}

REVISION: You can also use performSegueWithIdentifier:sender: method to activate the transition to a new view based on a selection or button press.

For instance, consider I had two view controllers. The first contains three buttons and the second needs to know which of those buttons has been pressed before the transition. You could wire the buttons up to an IBAction in your code which uses performSegueWithIdentifier: method, like this...

// When any of my buttons are pressed, push the next view
- (IBAction)buttonPressed:(id)sender
{
    [self performSegueWithIdentifier:@"MySegue" sender:sender];
}

// This will get called too before the view appears
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"MySegue"]) {

        // Get destination view
        SecondView *vc = [segue destinationViewController];

        // Get button tag number (or do whatever you need to do here, based on your object
        NSInteger tagIndex = [(UIButton *)sender tag];

        // Pass the information to your destination view
        [vc setSelectedButton:tagIndex];
    }
}

EDIT: The demo application I originally attached is now six years old, so I've removed it to avoid any confusion.

How to view .img files?

If you want to open .img files, you can use 7-zip, which is freeware...

http://www.7-zip.org/

Once installed, right click on the relevant img file, hover over "7-zip", then click "Open Archive". Bear in mind, you need a seperate program, or Windows 7 to burn the image to disc!

Hope this helps!

Edit: Proof that it works (not my video, credit to howtodothe on YouTube).

How do I push to GitHub under a different username?

Follow the following steps:

  1. You must understand that, you define author before commiting! the commits are already frozen: they have whatever name is set for their author and committer, and these cannot be changed.
# you can check what's currently:
git config user.name
git config user.email

git config user.name "your_github_username"
git config user.email "your_github_email"

# Again check what's currently:
git config user.name
git config user.email
  1. Check to whom your commit is tagged to?
git log
# once you're confirmed that it's tagged to you, then you should move to step 3

In case, the author is wrong then you can easily undo last commit without losing changes

Also, before moving to step3, don't forget to follow step one for sanity check.!

  1. give yourself a prompt to enter github_username and github_password
git config --local credential.helper ""
git push
# it will ask you to enter your github_username and github_password

How to require a controller in an angularjs directive

There is a good stackoverflow answer here by Mark Rajcok:

AngularJS directive controllers requiring parent directive controllers?

with a link to this very clear jsFiddle: http://jsfiddle.net/mrajcok/StXFK/

<div ng-controller="MyCtrl">
    <div screen>
        <div component>
            <div widget>
                <button ng-click="widgetIt()">Woo Hoo</button>
            </div>
        </div>
    </div>
</div>

JavaScript

var myApp = angular.module('myApp',[])

.directive('screen', function() {
    return {
        scope: true,
        controller: function() {
            this.doSomethingScreeny = function() {
                alert("screeny!");
            }
        }
    }
})

.directive('component', function() {
    return {
        scope: true,
        require: '^screen',
        controller: function($scope) {
            this.componentFunction = function() {
                $scope.screenCtrl.doSomethingScreeny();
            }
        },
        link: function(scope, element, attrs, screenCtrl) {
            scope.screenCtrl = screenCtrl
        }
    }
})

.directive('widget', function() {
    return {
        scope: true,
        require: "^component",
        link: function(scope, element, attrs, componentCtrl) {
            scope.widgetIt = function() {
                componentCtrl.componentFunction();
            };
        }
    }
})


//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
    $scope.name = 'Superhero';
}

Jackson serialization: ignore empty values (or null)

You have the annotation in the wrong place - it needs to be on the class, not the field. i.e:

@JsonInclude(Include.NON_NULL) //or Include.NON_EMPTY, if that fits your use case 
public static class Request {
  // ...
}

As noted in comments, in versions below 2.x the syntax for this annotation is:

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) // or JsonSerialize.Inclusion.NON_EMPTY

The other option is to configure the ObjectMapper directly, simply by calling mapper.setSerializationInclusion(Include.NON_NULL);

(for the record, I think the popularity of this answer is an indication that this annotation should be applicable on a field-by-field basis, @fasterxml)

What is the best way to remove a table row with jQuery?

if you have HTML like this

<tr>
 <td><span class="spanUser" userid="123"></span></td>
 <td><span class="spanUser" userid="123"></span></td>
</tr>

where userid="123" is a custom attribute that you can populate dynamically when you build the table,

you can use something like

  $(".spanUser").live("click", function () {

        var span = $(this);   
        var userid = $(this).attr('userid');

        var currentURL = window.location.protocol + '//' + window.location.host;
        var url = currentURL + "/Account/DeleteUser/" + userid;

        $.post(url, function (data) {
          if (data) {
                   var tdTAG = span.parent(); // GET PARENT OF SPAN TAG
                   var trTAG = tdTAG.parent(); // GET PARENT OF TD TAG
                   trTAG.remove(); // DELETE TR TAG == DELETE AN ENTIRE TABLE ROW 
             } else {
                alert('Sorry, there is some error.');
            }
        }); 

     });

So in that case you don't know the class or id of the TR tag but anyway you are able to delete it.

How to fix the datetime2 out-of-range conversion error using DbContext and SetInitializer?

Even though this question is quite old and there are great answers already, I thought I should put one more which explains 3 different approaches to solve this problem.

1st Approach

Explicitly map DateTime property public virtual DateTime Start { get; set; } to datetime2 in corresponding column in the table. Because by default EF will map it to datetime.

This can be done by fluent API or data annotation.

  1. Fluent API

    In DbContext class overide OnModelCreating and configure property Start (for explanation reasons it's a property of EntityClass class).

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //Configure only one property 
        modelBuilder.Entity<EntityClass>()
            .Property(e => e.Start)
            .HasColumnType("datetime2");
    
       //or configure all DateTime Preperties globally(EF 6 and Above)
        modelBuilder.Properties<DateTime>()
            .Configure(c => c.HasColumnType("datetime2"));
    }
    
  2. Data annotation

    [Column(TypeName="datetime2")]
    public virtual DateTime Start { get; set; }
    

2nd Approach

Initialize Start to a default value in EntityClass constructor.This is good as if for some reason the value of Start is not set before saving the entity into the database start will always have a default value. Make sure default value is greater than or equal to SqlDateTime.MinValue ( from January 1, 1753 to December 31, 9999)

public class EntityClass
{
    public EntityClass()
    {
        Start= DateTime.Now;
    }
    public DateTime Start{ get; set; }
}

3rd Approach

Make Start to be of type nullable DateTime -note ? after DateTime-

public virtual DateTime? Start { get; set; }

For more explanation read this post

How does lock work exactly?

lock is actually hidden Monitor class.

How to randomly pick an element from an array

Use the Random class:

int getRandomNumber(int[] arr)
{
  return arr[(new Random()).nextInt(arr.length)];
}

change image opacity using javascript

First set the opacity explicitly in your HTML thus:

<div id="box" style="height:150px; width:150px; background-color:orange; margin:25px; opacity:1"></div>

otherwise it is 0 or null

this is then in my .js file

document.getElementById("fadeButton90").addEventListener("click", function(){
document.getElementById("box").style.opacity  =   document.getElementById("box").style.opacity*0.90; });

Android - Handle "Enter" in an EditText

Hardware keyboards always yield enter events, but software keyboards return different actionIDs and nulls in singleLine EditTexts. This code responds every time the user presses enter in an EditText that this listener has been set to, regardless of EditText or keyboard type.

import android.view.inputmethod.EditorInfo;
import android.view.KeyEvent;
import android.widget.TextView.OnEditorActionListener;

listener=new TextView.OnEditorActionListener() {
  @Override
  public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
    if (event==null) {
      if (actionId==EditorInfo.IME_ACTION_DONE);
      // Capture soft enters in a singleLine EditText that is the last EditText.
      else if (actionId==EditorInfo.IME_ACTION_NEXT);
      // Capture soft enters in other singleLine EditTexts
      else return false;  // Let system handle all other null KeyEvents
    }
    else if (actionId==EditorInfo.IME_NULL) { 
    // Capture most soft enters in multi-line EditTexts and all hard enters.
    // They supply a zero actionId and a valid KeyEvent rather than
    // a non-zero actionId and a null event like the previous cases.
      if (event.getAction()==KeyEvent.ACTION_DOWN); 
      // We capture the event when key is first pressed.
      else  return true;   // We consume the event when the key is released.  
    }
    else  return false; 
    // We let the system handle it when the listener
    // is triggered by something that wasn't an enter.


    // Code from this point on will execute whenever the user
    // presses enter in an attached view, regardless of position, 
    // keyboard, or singleLine status.

    if (view==multiLineEditText)  multiLineEditText.setText("You pressed enter");
    if (view==singleLineEditText)  singleLineEditText.setText("You pressed next");
    if (view==lastSingleLineEditText)  lastSingleLineEditText.setText("You pressed done");
    return true;   // Consume the event
  }
};

The default appearance of the enter key in singleLine=false gives a bent arrow enter keypad. When singleLine=true in the last EditText the key says DONE, and on the EditTexts before it it says NEXT. By default, this behavior is consistent across all vanilla, android, and google emulators. The scrollHorizontal attribute doesn't make any difference. The null test is important because the response of phones to soft enters is left to the manufacturer and even in the emulators, the vanilla Level 16 emulators respond to long soft enters in multi-line and scrollHorizontal EditTexts with an actionId of NEXT and a null for the event.

Declaring multiple variables in JavaScript

I think it's a matter of personal preference. I prefer to do it in the following way:

   var /* Variables */
            me = this, that = scope,
            temp, tempUri, tempUrl,
            videoId = getQueryString()["id"],
            host = location.protocol + '//' + location.host,
            baseUrl = "localhost",
            str = "Visit W3Schools",
            n = str.search(/w3schools/i),
            x = 5,
            y = 6,
            z = x + y
   /* End Variables */;

Nginx Different Domains on Same IP

Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.

They should be

server {
    listen      80;
    server_name www.domain1.com;
    root /var/www/domain1;
}

server {
    listen       80;
    server_name www.domain2.com;
    root /var/www/domain2;
}

Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.

Is it possible to get a history of queries made in postgres

pgBadger is another option - also listed here: https://github.com/dhamaniasad/awesome-postgres#utilities

Requires some additional setup in advance to capture the necessary data in the postgres logs though, see the official website.

Wait until page is loaded with Selenium WebDriver for Python

Here I did it using a rather simple form:

from selenium import webdriver
browser = webdriver.Firefox()
browser.get("url")
searchTxt=''
while not searchTxt:
    try:    
      searchTxt=browser.find_element_by_name('NAME OF ELEMENT')
      searchTxt.send_keys("USERNAME")
    except:continue

BACKUP LOG cannot be performed because there is no current database backup

Another cause of this issue is when the Take tail-log backup before restore "Options" setting is enabled.

On the "Options" tab, Disable/uncheck Take tail-log backup before restore before restoring to a database that doesn't yet exist.

Why is quicksort better than mergesort?

Mu! Quicksort is not better, it is well suited for a different kind of application, than mergesort.

Mergesort is worth considering if speed is of the essence, bad worst-case performance cannot be tolerated, and extra space is available.1

You stated that they «They're both O(nlogn) […]». This is wrong. «Quicksort uses about n^2/2 comparisons in the worst case.»1.

However the most important property according to my experience is the easy implementation of sequential access you can use while sorting when using programming languages with the imperative paradigm.

1 Sedgewick, Algorithms

How exactly does __attribute__((constructor)) work?

Here is a "concrete" (and possibly useful) example of how, why, and when to use these handy, yet unsightly constructs...

Xcode uses a "global" "user default" to decide which XCTestObserver class spews it's heart out to the beleaguered console.

In this example... when I implicitly load this psuedo-library, let's call it... libdemure.a, via a flag in my test target á la..

OTHER_LDFLAGS = -ldemure

I want to..

  1. At load (ie. when XCTest loads my test bundle), override the "default" XCTest "observer" class... (via the constructor function) PS: As far as I can tell.. anything done here could be done with equivalent effect inside my class' + (void) load { ... } method.

  2. run my tests.... in this case, with less inane verbosity in the logs (implementation upon request)

  3. Return the "global" XCTestObserver class to it's pristine state.. so as not to foul up other XCTest runs which haven't gotten on the bandwagon (aka. linked to libdemure.a). I guess this historically was done in dealloc.. but I'm not about to start messing with that old hag.

So...

#define USER_DEFS NSUserDefaults.standardUserDefaults

@interface      DemureTestObserver : XCTestObserver @end
@implementation DemureTestObserver

__attribute__((constructor)) static void hijack_observer() {

/*! here I totally hijack the default logging, but you CAN
    use multiple observers, just CSV them, 
    i.e. "@"DemureTestObserverm,XCTestLog"
*/
  [USER_DEFS setObject:@"DemureTestObserver" 
                forKey:@"XCTestObserverClass"];
  [USER_DEFS synchronize];
}

__attribute__((destructor)) static void reset_observer()  {

  // Clean up, and it's as if we had never been here.
  [USER_DEFS setObject:@"XCTestLog" 
                forKey:@"XCTestObserverClass"];
  [USER_DEFS synchronize];
}

...
@end

Without the linker flag... (Fashion-police swarm Cupertino demanding retribution, yet Apple's default prevails, as is desired, here)

enter image description here

WITH the -ldemure.a linker flag... (Comprehensible results, gasp... "thanks constructor/destructor"... Crowd cheers) enter image description here

How to dockerize maven project? and how many ways to accomplish it?

Working example.

This is not a spring boot tutorial. It's the updated answer to a question on how to run a Maven build within a Docker container.

Question originally posted 4 years ago.

1. Generate an application

Use the spring initializer to generate a demo app

https://start.spring.io/

enter image description here

Extract the zip archive locally

2. Create a Dockerfile

#
# Build stage
#
FROM maven:3.6.0-jdk-11-slim AS build
COPY src /home/app/src
COPY pom.xml /home/app
RUN mvn -f /home/app/pom.xml clean package

#
# Package stage
#
FROM openjdk:11-jre-slim
COPY --from=build /home/app/target/demo-0.0.1-SNAPSHOT.jar /usr/local/lib/demo.jar
EXPOSE 8080
ENTRYPOINT ["java","-jar","/usr/local/lib/demo.jar"]

Note

  • This example uses a multi-stage build. The first stage is used to build the code. The second stage only contains the built jar and a JRE to run it (note how jar is copied between stages).

3. Build the image

docker build -t demo .

4. Run the image

$ docker run --rm -it demo:latest

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.3.RELEASE)

2019-02-22 17:18:57.835  INFO 1 --- [           main] com.example.demo.DemoApplication         : Starting DemoApplication v0.0.1-SNAPSHOT on f4e67677c9a9 with PID 1 (/usr/local/bin/demo.jar started by root in /)
2019-02-22 17:18:57.837  INFO 1 --- [           main] com.example.demo.DemoApplication         : No active profile set, falling back to default profiles: default
2019-02-22 17:18:58.294  INFO 1 --- [           main] com.example.demo.DemoApplication         : Started DemoApplication in 0.711 seconds (JVM running for 1.035)

Misc

Read the Docker hub documentation on how the Maven build can be optimized to use a local repository to cache jars.

Update (2019-02-07)

This question is now 4 years old and in that time it's fair to say building application using Docker has undergone significant change.

Option 1: Multi-stage build

This new style enables you to create more light-weight images that don't encapsulate your build tools and source code.

The example here again uses the official maven base image to run first stage of the build using a desired version of Maven. The second part of the file defines how the built jar is assembled into the final output image.

FROM maven:3.5-jdk-8 AS build  
COPY src /usr/src/app/src  
COPY pom.xml /usr/src/app  
RUN mvn -f /usr/src/app/pom.xml clean package

FROM gcr.io/distroless/java  
COPY --from=build /usr/src/app/target/helloworld-1.0.0-SNAPSHOT.jar /usr/app/helloworld-1.0.0-SNAPSHOT.jar  
EXPOSE 8080  
ENTRYPOINT ["java","-jar","/usr/app/helloworld-1.0.0-SNAPSHOT.jar"]  

Note:

  • I'm using Google's distroless base image, which strives to provide just enough run-time for a java app.

Option 2: Jib

I haven't used this approach but seems worthy of investigation as it enables you to build images without having to create nasty things like Dockerfiles :-)

https://github.com/GoogleContainerTools/jib

The project has a Maven plugin which integrates the packaging of your code directly into your Maven workflow.


Original answer (Included for completeness, but written ages ago)

Try using the new official images, there's one for Maven

https://registry.hub.docker.com/_/maven/

The image can be used to run Maven at build time to create a compiled application or, as in the following examples, to run a Maven build within a container.

Example 1 - Maven running within a container

The following command runs your Maven build inside a container:

docker run -it --rm \
       -v "$(pwd)":/opt/maven \
       -w /opt/maven \
       maven:3.2-jdk-7 \
       mvn clean install

Notes:

  • The neat thing about this approach is that all software is installed and running within the container. Only need docker on the host machine.
  • See Dockerfile for this version

Example 2 - Use Nexus to cache files

Run the Nexus container

docker run -d -p 8081:8081 --name nexus sonatype/nexus

Create a "settings.xml" file:

<settings>
  <mirrors>
    <mirror>
      <id>nexus</id>
      <mirrorOf>*</mirrorOf>
      <url>http://nexus:8081/content/groups/public/</url>
    </mirror>
  </mirrors>
</settings>

Now run Maven linking to the nexus container, so that dependencies will be cached

docker run -it --rm \
       -v "$(pwd)":/opt/maven \
       -w /opt/maven \
       --link nexus:nexus \
       maven:3.2-jdk-7 \
       mvn -s settings.xml clean install

Notes:

  • An advantage of running Nexus in the background is that other 3rd party repositories can be managed via the admin URL transparently to the Maven builds running in local containers.

Why is synchronized block better than synchronized method?

Because lock is expensive, when you are using synchronized block you lock only if _instance == null, and after _instance finally initialized you'll never lock. But when you synchronize on method you lock unconditionally, even after the _instance is initialized. This is the idea behind double-checked locking optimization pattern http://en.wikipedia.org/wiki/Double-checked_locking.

Change tab bar tint color on iOS 7

What finally worked for me was:

[self.tabBar setTintColor:[UIColor redColor]];
[self.tabBar setBarTintColor:[UIColor yellowColor]];

Copy folder recursively in Node.js

Here's a function that recursively copies a directory and its contents to another directory:

const fs = require("fs")
const path = require("path")

/**
 * Look ma, it's cp -R.
 * @param {string} src  The path to the thing to copy.
 * @param {string} dest The path to the new copy.
 */
var copyRecursiveSync = function(src, dest) {
  var exists = fs.existsSync(src);
  var stats = exists && fs.statSync(src);
  var isDirectory = exists && stats.isDirectory();
  if (isDirectory) {
    fs.mkdirSync(dest);
    fs.readdirSync(src).forEach(function(childItemName) {
      copyRecursiveSync(path.join(src, childItemName),
                        path.join(dest, childItemName));
    });
  } else {
    fs.copyFileSync(src, dest);
  }
};

How do you tell if a checkbox is selected in Selenium for Java?

If you are using Webdriver then the item you are looking for is Selected.

Often times in the render of the checkbox doesn't actually apply the attribute checked unless specified.

So what you would look for in Selenium Webdriver is this

isChecked = e.findElement(By.tagName("input")).Selected;

As there is no Selected in WebDriver Java API, the above code should be as follows:

isChecked = e.findElement(By.tagName("input")).isSelected();

Create the perfect JPA entity

My 2 cents addition to the answers here are:

  1. With reference to Field or Property access (away from performance considerations) both are legitimately accessed by means of getters and setters, thus, my model logic can set/get them in the same manner. The difference comes to play when the persistence runtime provider (Hibernate, EclipseLink or else) needs to persist/set some record in Table A which has a foreign key referring to some column in Table B. In case of a Property access type, the persistence runtime system uses my coded setter method to assign the cell in Table B column a new value. In case of a Field access type, the persistence runtime system sets the cell in Table B column directly. This difference is not of importance in the context of a uni-directional relationship, yet it is a MUST to use my own coded setter method (Property access type) for a bi-directional relationship provided the setter method is well designed to account for consistency. Consistency is a critical issue for bi-directional relationships refer to this link for a simple example for a well-designed setter.

  2. With reference to Equals/hashCode: It is impossible to use the Eclipse auto-generated Equals/hashCode methods for entities participating in a bi-directional relationship, otherwise they will have a circular reference resulting in a stackoverflow Exception. Once you try a bidirectional relationship (say OneToOne) and auto-generate Equals() or hashCode() or even toString() you will get caught in this stackoverflow exception.

Redirecting exec output to a buffer or file

After forking, use dup2(2) to duplicate the file's FD into stdout's FD, then exec.

Compiling problems: cannot find crt1.o

What helped me is to create a symbolic link:

sudo ln -s /usr/lib/x86_64-linux-gnu /usr/lib64

CSS Float: Floating an image to the left of the text

I almost always just use overflow:hidden on my text-elements in those situations, it often works like a charm ;)

.post-container {
 margin: 20px 20px 0 0;
 border:5px solid #333;
}
.post-thumb img {
 float: left;
}
.post-content {
 overflow:hidden;
}

How to sort multidimensional array by column?

Yes. The sorted built-in accepts a key argument:

sorted(li,key=lambda x: x[1])
Out[31]: [['Jason', 1], ['John', 2], ['Jim', 9]]

note that sorted returns a new list. If you want to sort in-place, use the .sort method of your list (which also, conveniently, accepts a key argument).

or alternatively,

from operator import itemgetter
sorted(li,key=itemgetter(1))
Out[33]: [['Jason', 1], ['John', 2], ['Jim', 9]]

Read more on the python wiki.

How to unpublish an app in Google Play Developer Console

Click on Store Listing and then click on 'Unpublish App'.

See image for details

Round a divided number in Bash

I think this should be enough.

$ echo "3/2" | bc 

What is correct content-type for excel files?

For BIFF .xls files

application/vnd.ms-excel

For Excel2007 and above .xlsx files

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

How to create a fixed sidebar layout with Bootstrap 4?

something like this?

_x000D_
_x000D_
#sticky-sidebar {_x000D_
position:fixed;_x000D_
max-width: 20%;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-xs-4">_x000D_
      <div class="col-xs-12" id="sticky-sidebar">_x000D_
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="col-xs-8" id="main">_x000D_
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
    </div>_x000D_
  </div>_x000D_
</div
_x000D_
_x000D_
_x000D_

Getting coordinates of marker in Google Maps API

var lat = homeMarker.getPosition().lat();
var lng = homeMarker.getPosition().lng();

See the google.maps.LatLng docs and google.maps.Marker getPosition().

How to "z-index" to make a menu always on top of the content

#right { 
  background-color: red;
  height: 300px;
  width: 300px;
  z-index: 9999;
  margin-top: 0px;
  position: absolute;
  top:0;
  right:0;
}

position: absolute; top:0; right:0; do the work here! :) Also remove the floating!

Reference list item by index within Django template?

@jennifer06262016, you can definitely add another filter to return the objects inside a django Queryset.

@register.filter 
def get_item(Queryset):
    return Queryset.your_item_key

In that case, you would type something like this {{ Queryset|index:x|get_item }} into your template to access some dictionary object. It works for me.

Force Java timezone as GMT/UTC

Execute this line in MySQL to reset your timezone:

SET @@global.time_zone = '+00:00';

check if jquery has been loaded, then load it if false

Old post but I made an good solution what is tested on serval places.

https://github.com/CreativForm/Load-jQuery-if-it-is-not-already-loaded

CODE:

(function(url, position, callback){
    // default values
    url = url || 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js';
    position = position || 0;

    // Check is jQuery exists
    if (!window.jQuery) {
        // Initialize <head>
        var head = document.getElementsByTagName('head')[0];
        // Create <script> element
        var script = document.createElement("script");
        // Append URL
        script.src = url;
        // Append type
        script.type = 'text/javascript';
        // Append script to <head>
        head.appendChild(script);
        // Move script on proper position
        head.insertBefore(script,head.childNodes[position]);

        script.onload = function(){
            if(typeof callback == 'function') {
                callback(jQuery);
            }
        };
    } else {
        if(typeof callback == 'function') {
            callback(jQuery);
        }
    }
}('https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js', 5, function($){ 
    console.log($);
}));

At GitHub is better explanation but generaly this function you can add anywhere in your HTML code and you will initialize jquery if is not already loaded.

Can a Byte[] Array be written to a file in C#?

You can do this using System.IO.BinaryWriter which takes a Stream so:

var bw = new BinaryWriter(File.Open("path",FileMode.OpenOrCreate);
bw.Write(byteArray);

How to send JSON instead of a query string with $.ajax?

While I know many architectures like ASP.NET MVC have built-in functionality to handle JSON.stringify as the contentType my situation is a little different so maybe this may help someone in the future. I know it would have saved me hours!

Since my http requests are being handled by a CGI API from IBM (AS400 environment) on a different subdomain these requests are cross origin, hence the jsonp. I actually send my ajax via javascript object(s). Here is an example of my ajax POST:

 var data = {USER : localProfile,  
        INSTANCE : "HTHACKNEY",  
        PAGE : $('select[name="PAGE"]').val(), 
        TITLE : $("input[name='TITLE']").val(), 
        HTML : html,
        STARTDATE : $("input[name='STARTDATE']").val(), 
        ENDDATE : $("input[name='ENDDATE']").val(),
        ARCHIVE : $("input[name='ARCHIVE']").val(), 
        ACTIVE : $("input[name='ACTIVE']").val(), 
        URGENT : $("input[name='URGENT']").val(), 
        AUTHLST :  authStr};
        //console.log(data);
       $.ajax({
            type: "POST",
           url:   "http://www.domian.com/webservicepgm?callback=?",
           data:  data,
           dataType:'jsonp'
       }).
       done(function(data){
         //handle data.WHATEVER
       });

How do a send an HTTPS request through a proxy in Java?

HTTPS proxy doesn't make sense because you can't terminate your HTTP connection at the proxy for security reasons. With your trust policy, it might work if the proxy server has a HTTPS port. Your error is caused by connecting to HTTP proxy port with HTTPS.

You can connect through a proxy using SSL tunneling (many people call that proxy) using proxy CONNECT command. However, Java doesn't support newer version of proxy tunneling. In that case, you need to handle the tunneling yourself. You can find sample code here,

http://www.javaworld.com/javaworld/javatips/jw-javatip111.html

EDIT: If you want defeat all the security measures in JSSE, you still need your own TrustManager. Something like this,

 public SSLTunnelSocketFactory(String proxyhost, String proxyport){
      tunnelHost = proxyhost;
      tunnelPort = Integer.parseInt(proxyport);
      dfactory = (SSLSocketFactory)sslContext.getSocketFactory();
 }

 ...

 connection.setSSLSocketFactory( new SSLTunnelSocketFactory( proxyHost, proxyPort ) );
 connection.setDefaultHostnameVerifier( new HostnameVerifier()
 {
    public boolean verify( String arg0, SSLSession arg1 )
    {
        return true;
    }
 }  );

EDIT 2: I just tried my program I wrote a few years ago using SSLTunnelSocketFactory and it doesn't work either. Apparently, Sun introduced a new bug sometime in Java 5. See this bug report,

http://bugs.sun.com/view_bug.do?bug_id=6614957

The good news is that the SSL tunneling bug is fixed so you can just use the default factory. I just tried with a proxy and everything works as expected. See my code,

public class SSLContextTest {

    public static void main(String[] args) {

        System.setProperty("https.proxyHost", "proxy.xxx.com");
        System.setProperty("https.proxyPort", "8888");

        try {

            SSLContext sslContext = SSLContext.getInstance("SSL");

            // set up a TrustManager that trusts everything
            sslContext.init(null, new TrustManager[] { new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    System.out.println("getAcceptedIssuers =============");
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] certs,
                        String authType) {
                    System.out.println("checkClientTrusted =============");
                }

                public void checkServerTrusted(X509Certificate[] certs,
                        String authType) {
                    System.out.println("checkServerTrusted =============");
                }
            } }, new SecureRandom());

            HttpsURLConnection.setDefaultSSLSocketFactory(
                    sslContext.getSocketFactory());

            HttpsURLConnection
                    .setDefaultHostnameVerifier(new HostnameVerifier() {
                        public boolean verify(String arg0, SSLSession arg1) {
                            System.out.println("hostnameVerifier =============");
                            return true;
                        }
                    });

            URL url = new URL("https://www.verisign.net");
            URLConnection conn = url.openConnection();
            BufferedReader reader = 
                new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }
}

This is what I get when I run the program,

checkServerTrusted =============
hostnameVerifier =============
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
......

As you can see, both SSLContext and hostnameVerifier are getting called. HostnameVerifier is only involved when the hostname doesn't match the cert. I used "www.verisign.net" to trigger this.

SQL Current month/ year question

In SQL Server you can use YEAR, MONTH and DAY instead of DATEPART.
(at least in SQL Server 2005/2008, I'm not sure about SQL Server 2000 and older)

I prefer using these "short forms" because to me, YEAR(getdate()) is shorter to type and better to read than DATEPART(yyyy, getdate()).

So you could also query your table like this:

select *
from your_table
where month_column = MONTH(getdate())
and year_column = YEAR(getdate())

Why do you have to link the math library in C?

There's a thorough discussion of linking to external libraries in An Introduction to GCC - Linking with external libraries. If a library is a member of the standard libraries (like stdio), then you don't need to specify to the compiler (really the linker) to link them.

EDIT: After reading some of the other answers and comments, I think the libc.a reference and the libm reference that it links to both have a lot to say about why the two are separate.

Note that many of the functions in 'libm.a' (the math library) are defined in 'math.h' but are not present in libc.a. Some are, which may get confusing, but the rule of thumb is this--the C library contains those functions that ANSI dictates must exist, so that you don't need the -lm if you only use ANSI functions. In contrast, `libm.a' contains more functions and supports additional functionality such as the matherr call-back and compliance to several alternative standards of behavior in case of FP errors. See section libm, for more details.

How can I convert IPV6 address to IPV4 address?

The IPAddress Java library can accomplish what you are describing here.

IPv6 addresses are 16 bytes. Using that library, if you are starting with a 16-byte array you can construct the IPv6 address object:

IPv6Address addr = new IPv6Address(bytes); //bytes is byte[16]

From there you can check if the address is IPv4 mapped, IPv4 compatible, IPv4 translated, and so on (there are many possible ways IPv6 represents IPv4 addresses). In most cases, if an IPv6 address represents an IPv4 address, the ipv4 address is in the lower 4 bytes, and so you can get the derived IPv4 address as follows. Afterwards, you can convert back to bytes, which will be just 4 bytes for IPv4.

    if(addr.isIPv4Compatible() || addr.isIPv4Mapped()) {
        IPv4Address derivedIpv4Address = addr.getEmbeddedIPv4Address();
        byte ipv4Bytes[] = derivedIpv4Address.getBytes();
        ...
     }

The javadoc is available at the link.

RunAs A different user when debugging in Visual Studio

I'm using the following method based on @Watki02's answer:

  1. Shift r-click the application to debug
  2. Run as different user
  3. Attach the debugger to the application

That way you can keep your visual studio instance as your own user whilst debugging from the other.

Whoops, looks like something went wrong. Laravel 5.0

  1. Rename the .env.example to .env
  2. Go to bootstrap=>app.php and uncomment $app->withEloquent();
  3. Make sure that APP_DEBUG=true in .env file. Now it will work.

How to Find And Replace Text In A File With C#

You need to write all the lines you read into the output file, even if you don't change them.

Something like:

using (var input = File.OpenText("input.txt"))
using (var output = new StreamWriter("output.txt")) {
  string line;
  while (null != (line = input.ReadLine())) {
     // optionally modify line.
     output.WriteLine(line);
  }
}

If you want to perform this operation in place then the easiest way is to use a temporary output file and at the end replace the input file with the output.

File.Delete("input.txt");
File.Move("output.txt", "input.txt");

(Trying to perform update operations in the middle of text file is rather hard to get right because always having the replacement the same length is hard given most encodings are variable width.)

EDIT: Rather than two file operations to replace the original file, better to use File.Replace("input.txt", "output.txt", null). (See MSDN.)

Move seaborn plot legend to a different position?

Modifying the example here:

You can use legend_out = False

import seaborn as sns
sns.set(style="whitegrid")

titanic = sns.load_dataset("titanic")

g = sns.factorplot("class", "survived", "sex",
                    data=titanic, kind="bar",
                    size=6, palette="muted",
                   legend_out=False)
g.despine(left=True)
g.set_ylabels("survival probability")

enter image description here

Proper way to initialize C++ structs

You need to initialize whatever members you have in your struct, e.g.:

struct MyStruct {
  private:
    int someInt_;
    float someFloat_;

  public:
    MyStruct(): someInt_(0), someFloat_(1.0) {} // Initializer list will set appropriate values

};

How to get a path to the desktop for current user in C#?

 string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
 string extension = ".log";
 filePath += @"\Error Log\" + extension;
 if (!Directory.Exists(filePath))
 {
      Directory.CreateDirectory(filePath);
 }

Bootstrap 3 - How to load content in modal body via AJAX?

create an empty modal box on the current page and below is the ajax call you can see how to fetch the content in result from another html page.

 $.ajax({url: "registration.html", success: function(result){
            //alert("success"+result);
              $("#contentBody").html(result);
            $("#myModal").modal('show'); 

        }});

once the call is done you will get the content of the page by the result to then you can insert the code in you modal's content id using.

You can call controller and get the page content and you can show that in your modal.

below is the example of Bootstrap 3 modal in that we are loading content from registration.html page...

index.html
------------------------------------------------
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<script type="text/javascript">
function loadme(){
    //alert("loadig");

    $.ajax({url: "registration.html", success: function(result){
        //alert("success"+result);
          $("#contentBody").html(result);
        $("#myModal").modal('show'); 

    }});
}
</script>
</head>
<body>

<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" onclick="loadme()">Load me</button>


<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content" >
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Modal Header</h4>
      </div>
      <div class="modal-body" id="contentBody">

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>

  </div>
</div>

</body>
</html>

registration.html
-------------------- 
<!DOCTYPE html>
<html>
<style>
body {font-family: Arial, Helvetica, sans-serif;}

form {
    border: 3px solid #f1f1f1;
    font-family: Arial;
}

.container {
    padding: 20px;
    background-color: #f1f1f1;
    width: 560px;
}

input[type=text], input[type=submit] {
    width: 100%;
    padding: 12px;
    margin: 8px 0;
    display: inline-block;
    border: 1px solid #ccc;
    box-sizing: border-box;
}

input[type=checkbox] {
    margin-top: 16px;
}

input[type=submit] {
    background-color: #4CAF50;
    color: white;
    border: none;
}

input[type=submit]:hover {
    opacity: 0.8;
}
</style>
<body>

<h2>CSS Newsletter</h2>

<form action="/action_page.php">
  <div class="container">
    <h2>Subscribe to our Newsletter</h2>
    <p>Lorem ipsum text about why you should subscribe to our newsletter blabla. Lorem ipsum text about why you should subscribe to our newsletter blabla.</p>
  </div>

  <div class="container" style="background-color:white">
    <input type="text" placeholder="Name" name="name" required>
    <input type="text" placeholder="Email address" name="mail" required>
    <label>
      <input type="checkbox" checked="checked" name="subscribe"> Daily Newsletter
    </label>
  </div>

  <div class="container">
    <input type="submit" value="Subscribe">
  </div>
</form>

</body>
</html>

How to make CSS3 rounded corners hide overflow in Chrome/Opera

As for me none of the solutions worked well, only using:

-webkit-mask-image: -webkit-radial-gradient(circle, white, black);

on the wrapper element did the job.

Here the example: http://jsfiddle.net/gpawlik/qWdf6/74/

jquery save json data object in cookie

Now there is already no need to use JSON.stringify explicitly. Just execute this line of code

$.cookie.json = true;

After that you can save any object in cookie, which will be automatically converted to JSON and back from JSON when reading cookie.

var user = { name: "name", age: 25 }
$.cookie('user', user);
...

var currentUser = $.cookie('user');
alert('User name is ' + currentUser.name);

But JSON library does not come with jquery.cookie, so you have to download it by yourself and include into html page before jquery.cookie.js

String to object in JS

In your case

var KeyVal = string.split(", ");
var obj = {};
var i;
for (i in KeyVal) {
    KeyVal[i] = KeyVal[i].split(":");
    obj[eval(KeyVal[i][0])] = eval(KeyVal[i][1]);
}

How to create a box when mouse over text in pure CSS?

Exactly what they said, it will work.

In the parent element stablish a max-height.

I'm taking sandeep example and adding the max-height and if required you can add max-width property. The text will stay where It should stay (If possible, in some cases you will need to change some values to make it stay in there)

span{
    background: none repeat scroll 0 0 #F8F8F8;
    border: 5px solid #DFDFDF;
    color: #717171;
    font-size: 13px;
    height: 30px;
    letter-spacing: 1px;
    line-height: 30px;
    margin: 0 auto;
    position: relative;
    text-align: center;
    text-transform: uppercase;
    top: -80px;
    left:-30px;
    display:none;
    padding:0 20px;
}

span:after{
    content:'';
    position:absolute;
    bottom:-10px;
    width:10px;
    height:10px;
    border-bottom:5px solid #dfdfdf;
    border-right:5px solid #dfdfdf;
    background:#f8f8f8;
    left:50%;
    margin-left:-5px;
    -moz-transform:rotate(45deg);
    -webkit-transform:rotate(45deg);
     transform:rotate(45deg);
}

p{
    margin:100px;
    float:left;
    position:relative;
    cursor:pointer;
    max-height: 10px;
}

p:hover span{
    display:block;
}

max-height in the p paragraph, second to last one, last line.

Test it before rating it useless.

T-SQL stored procedure that accepts multiple Id values

A superfast XML Method, if you want to use a stored procedure and pass the comma separated list of Department IDs :

Declare @XMLList xml
SET @XMLList=cast('<i>'+replace(@DepartmentIDs,',','</i><i>')+'</i>' as xml)
SELECT x.i.value('.','varchar(5)') from @XMLList.nodes('i') x(i))

All credit goes to Guru Brad Schulz's Blog

Exception thrown in catch and finally clause

Based on reading your answer and seeing how you likely came up with it, I believe you think an "exception-in-progress" has "precedence". Keep in mind:

When an new exception is thrown in a catch block or finally block that will propagate out of that block, then the current exception will be aborted (and forgotten) as the new exception is propagated outward. The new exception starts unwinding up the stack just like any other exception, aborting out of the current block (the catch or finally block) and subject to any applicable catch or finally blocks along the way.

Note that applicable catch or finally blocks includes:

When a new exception is thrown in a catch block, the new exception is still subject to that catch's finally block, if any.

Now retrace the execution remembering that, whenever you hit throw, you should abort tracing the current exception and start tracing the new exception.

Modify SVG fill color when being served as Background-Image

One way to do this is to serve your svg from some server side mechanism. Simply create a resource server side that outputs your svg according to GET parameters, and you serve it on a certain url.

Then you just use that url in your css.

Because as a background img, it isn't part of the DOM and you can't manipulate it. Another possibility would be to use it regularly, embed it in a page in a normal way, but position it absolutely, make it full width & height of a page and then use z-index css property to put it behind all the other DOM elements on a page.

check if array is empty (vba excel)

The problem with VBA is that there are both dynamic and static arrays...

Dynamic Array Example

Dim myDynamicArray() as Variant

Static Array Example

Dim myStaticArray(10) as Variant
Dim myOtherStaticArray(0 To 10) as Variant

Using error handling to check if the array is empty works for a Dynamic Array, but a static array is by definition not empty, there are entries in the array, even if all those entries are empty.

So for clarity's sake, I named my function "IsZeroLengthArray".

    Public Function IsZeroLengthArray(ByRef subject() As Variant) As Boolean
        'Tell VBA to proceed if there is an error to the next line.
        On Error Resume Next
    
        Dim UpperBound As Integer
        Dim ErrorNumber As Long
        Dim ErrorDescription As String
        Dim ErrorSource As String
    
        'If the array is empty this will throw an error because a zero-length 
          'array has no UpperBound (or LowerBound).
        'This only works for dynamic arrays.  If this was a static array there 
          'would be both an upper and lower bound.
        UpperBound = UBound(subject)


        'Store the Error Number and then clear the Error object 
         'because we want VBA to treat unintended errors normally
        ErrorNumber = Err.Number
        ErrorDescription = Err.Description
        ErrorSource = Err.Source
        Err.Clear
        On Error GoTo 0
    
        'Check the Error Object to see if we have a "subscript out of range" error.  
          'If we do (the number is 9) then we can assume that the array is zero-length.
        If ErrorNumber = 9 Then
            IsZeroLengthArray = True

        'If the Error number is something else then 9 we want to raise 
        'that error again...
        ElseIf ErrorNumber <> 0 Then
            Err.Raise ErrorNumber, ErrorSource, ErrorDescription

        'If the Error number is 0 then we have no error and can assume that the
         'array is not of zero-length
        ElseIf ErrorNumber = 0 Then
            IsZeroLengthArray = False
        End If
    End Function

I hope that this helps others as it helped me.

How to make bootstrap column height to 100% row height?

You can solve that using display table.

Here is the updated JSFiddle that solves your problem.

CSS

.body {
    display: table;
    background-color: green;
}

.left-side {
    background-color: blue;
    float: none;
    display: table-cell;
    border: 1px solid;
}

.right-side {
    background-color: red;
    float: none;
    display: table-cell;
    border: 1px solid;
}

HTML

<div class="row body">
        <div class="col-xs-9 left-side">
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
        </div>
        <div class="col-xs-3 right-side">
            asdfdf
        </div>
    </div>

How to use RecyclerView inside NestedScrollView?

Replace your recyclerView with,

<android.support.v7.widget.RecyclerView
    android:id="@+id/conversation"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

here,

app:layout_behavior="@string/appbar_scrolling_view_behavior"

will manage the rest of things.

One more thing, no need to put your recyclerView inside NestedScrollView

How to display hidden characters by default (ZERO WIDTH SPACE ie. &#8203)

A very simple solution is to search your file(s) for non-ascii characters using a regular expression. This will nicely highlight all the spots where they are found with a border.

Search for [^\x00-\x7F] and check the box for Regex.

The result will look like this (in dark mode):

zero width space made visible

Rails has_many with alias name

Give this a shot:

has_many :jobs, foreign_key: "user_id", class_name: "Task"

Note, that :as is used for polymorphic associations.

Receive result from DialogFragment

In Kotlin

    // My DialogFragment
class FiltroDialogFragment : DialogFragment(), View.OnClickListener {
    
    var listener: InterfaceCommunicator? = null

    override fun onAttach(context: Context?) {
        super.onAttach(context)
        listener = context as InterfaceCommunicator
    }

    interface InterfaceCommunicator {
        fun sendRequest(value: String)
    }   

    override fun onClick(v: View) {
        when (v.id) {
            R.id.buttonOk -> {    
        //You can change value             
                listener?.sendRequest('send data')
                dismiss()
            }
            
        }
    }
}

// My Activity

class MyActivity: AppCompatActivity(),FiltroDialogFragment.InterfaceCommunicator {

    override fun sendRequest(value: String) {
    // :)
    Toast.makeText(this, value, Toast.LENGTH_LONG).show()
    }
}
 

I hope it serves, if you can improve please edit it. My English is not very good

"implements Runnable" vs "extends Thread" in Java

Thread holds behaviour which is not intended to be accessed;

  • it's synchronized lock is used for join etc.
  • it has methods you can access by accident.

however if you sub-class Thread have to consider more Thread is implemented.

public class ThreadMain {
    public int getId() {
        return 12345678;
    }

    public String getName() {
        return "Hello World";
    }

    public String getState() {
        return "testing";
    }

    public void example() {
        new Thread() {
            @Override
            public void run() {
                System.out.println("id: "+getId()+", name: "+getName()+", state: "+getState());
            }
        }.start();
    }

    public static void main(String[] args) {
        new ThreadMain().example();
    }
}

If you run this you might expect

id: 12345678, name: Hello World, state: testing

however, you are not calling the methods you think you are because you are using the method in Thread not ThreadMain and instead you see something like

id: 11, name: Thread-0, state: RUNNABLE

Python division

Specifying a float by placing a '.' after the number will also cause it to default to float.

>>> 1 / 2
0

>>> 1. / 2.
0.5

How to install Jdk in centos

Try the following to see if you have the proper repository installed:

# yum search java | grep 'java-'

This is going to return a list of available packages that have java in the title. Specifically we are interested in the java- anything, as the jdk will typically be in 'java-version#' type format... Anyhow, if you have to install a repo look at Dag Wieers repo:

http://dag.wieers.com/rpm/FAQ.php#B

After you've got it installed try yum search again... This time you'll have a bunch of java stuff.

# yum search java | grep 'java-'

This will return the list of the available java packages. You can install one like this:

# yum install java-1.7.0-openjdk.x86_64

Force index use in Oracle

There is an appropriate index on column_having_index, and its use actually increase performance, but Oracle didn't use it...
You should gather statistics on your table to let optimizer see that index access can help. Using direct hint is not a good practice.

private final static attribute vs private final attribute

Final: Once a final variable has been assigned, it always contains the same value. wherever the variable is static or not static: it will be only one variable for all instances initialized one time in Memory

How to access URL segment(s) in blade in Laravel 5?

The double curly brackets are processed via Blade -- not just plain PHP. This syntax basically echos the calculated value.

{{ Request::segment(1) }} 

Using Python's os.path, how do I go up one directory?

I think the easiest thing to do is just to reuse dirname() So you can call

os.path.dirname(os.path.dirname( __file__ ))

if you file is at /Users/hobbes3/Sites/mysite/templates/method.py

This will return "/Users/hobbes3/Sites/mysite"

Using both Python 2.x and Python 3.x in IPython Notebook

Following are the steps to add the python2 kernel to jupyter notebook::

open a terminal and create a new python 2 environment: conda create -n py27 python=2.7

activate the environment: Linux source activate py27 or windows activate py27

install the kernel in the env: conda install notebook ipykernel

install the kernel for outside the env: ipython kernel install --user

close the env: source deactivate

Although a late answer hope someone finds it useful :p

How to use sys.exit() in Python

sys.exit() raises a SystemExit exception which you are probably assuming as some error. If you want your program not to raise SystemExit but return gracefully, you can wrap your functionality in a function and return from places you are planning to use sys.exit

How to copy data from one table to another new table in MySQL?

You should create table2 first.

insert into table2(field1,field2,...)
select field1,field2,....
from table1
where condition;

LIKE operator in LINQ

Just add to string object extention methods.

public static class StringEx
{
    public static bool Contains(this String str, string[] Arr, StringComparison comp)
    {
        if (Arr != null)
        {
            foreach (string s in Arr)
            {
                if (str.IndexOf(s, comp)>=0)
                { return true; }
            }
        }

        return false;
    }

    public static bool Contains(this String str,string[] Arr)
    {
        if (Arr != null)
        {
            foreach (string s in Arr)
            {
                if (str.Contains(s))
                { return true; }
            }
        }

        return false;
    }
}

usage:

use namespase that contains this class;

var sPortCode = Database.DischargePorts
            .Where(p => p.PortName.Contains(new string [] {"BALTIMORE"},  StringComparison.CurrentCultureIgnoreCase) )
            .Single().PortCode;

How to find the installed pandas version

Run:

pip  list

You should get a list of packages (including panda) and their versions, e.g.:

beautifulsoup4 (4.5.1)
cycler (0.10.0)
jdcal (1.3)
matplotlib (1.5.3)
numpy (1.11.1)
openpyxl (2.2.0b1)
pandas (0.18.1)
pip (8.1.2)
pyparsing (2.1.9)
python-dateutil (2.2)
python-nmap (0.6.1)
pytz (2016.6.1)
requests (2.11.1)
setuptools (20.10.1)
six (1.10.0)
SQLAlchemy (1.0.15)
xlrd (1.0.0)

Create an empty list in python with certain size

s1 = []
for i in range(11):
   s1.append(i)

print s1

To create a list, just use these brackets: "[]"

To add something to a list, use list.append()

CSS property to pad text inside of div

Just use div { padding: 20px; } and substract 40px from your original div width.

Like Philip Wills pointed out, you can also use box-sizing instead of substracting 40px:

div {
    padding: 20px;
    -moz-box-sizing: border-box; 
    box-sizing: border-box;
}

The -moz-box-sizing is for Firefox.

How do I show the schema of a table in a MySQL database?

You can also use shorthand for describe as desc for table description.

desc [db_name.]table_name;

or

use db_name;
desc table_name;

You can also use explain for table description.

explain [db_name.]table_name;

See official doc

Will give output like:

+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id       | int(10)     | NO   | PRI | NULL    |       |
| name     | varchar(20) | YES  |     | NULL    |       |
| age      | int(10)     | YES  |     | NULL    |       |
| sex      | varchar(10) | YES  |     | NULL    |       |
| sal      | int(10)     | YES  |     | NULL    |       |
| location | varchar(20) | YES  |     | Pune    |       |
+----------+-------------+------+-----+---------+-------+

Where value in column containing comma delimited values

Just came to know about this when I was searching for a solution to a similar problem. SQL has a new keyword called CONTAINS you can use that. For more details see http://msdn.microsoft.com/en-us/library/ms187787.aspx

How to set a text box for inputing password in winforms?

private void cbShowHide_CheckedChanged(object sender, EventArgs e)
{
    if (cbShowHide.Checked)
    {
        txtPin.UseSystemPasswordChar = PasswordPropertyTextAttribute.No.Password;
    }
    else
    {
        //Hides Textbox password
        txtPin.UseSystemPasswordChar = PasswordPropertyTextAttribute.Yes.Password;
    }
}

Copy this code to show and hide your textbox using a checkbox

How to change the JDK for a Jenkins job?

There is a JDK dropdown in "job name" -> Configure in Jenkins web ui. It will list all JDKs available in Jenkins configuration.

Setting up an MS-Access DB for multi-user access

I have found the SMB2 protocol introduced in Vista to lock the access databases. It can be disabled by the following regedit:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\LanmanServer\Parameters] "Smb2"=dword:00000000

AppStore - App status is ready for sale, but not in app store

We published it today after having 'Release this version'. It took 15 minutes to show on the App Store.

This is due to App Store will sync the data across servers.

CreateProcess: No such file or directory

I had the same problem and I tried everything with no result,, What fixed the problem for me was changing the order of the library paths in the PATH variable. I had cygwin as well as some other compilers so there was probably some sort of collision between them. What I did was putting the C:\MinGW\bin; path first before all other paths and it fixed the problem for me!

How to provide a file download from a JSF backing bean?

Introduction

You can get everything through ExternalContext. In JSF 1.x, you can get the raw HttpServletResponse object by ExternalContext#getResponse(). In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream() without the need to grab the HttpServletResponse from under the JSF hoods.

On the response, you should set the Content-Type header so that the client knows which application to associate with the provided file. And, you should set the Content-Length header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition header to attachment if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.

Most important part is to call FacesContext#responseComplete() to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException with a message like getoutputstream() has already been called for this response when the JSF implementation calls getWriter() to render HTML.

Turn off ajax / don't use remote command!

You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink> and <h:commandButton>. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.

In case you're using e.g. PrimeFaces <p:commandXxx>, then you need to make sure that you explicitly turn off ajax via ajax="false" attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" /> in the command component.

Generic JSF 2.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();

    ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
    ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = ec.getResponseOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Generic JSF 1.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

    response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
    response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = response.getOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Common static file example

In case you need to stream a static file from the local disk file system, substitute the code as below:

File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();

// ...

Files.copy(file.toPath(), output);

Common dynamic file example

In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output there where the API being used expects an OutputStream.

E.g. iText PDF:

String fileName = "dynamic.pdf";
String contentType = "application/pdf";

// ...

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();

E.g. Apache POI HSSF:

String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";

// ...

HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();

Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.

Utility method

If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile() methods taking either a File, or an InputStream, or a byte[], and specifying whether the file should be downloaded as an attachment (true) or inline (false).

public void download() throws IOException {
    Faces.sendFile(file, true);
}

Yes, this code is complete as-is. You don't need to invoke responseComplete() and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.

JavaScript: filter() for Objects

If you wish to mutate the same object rather than create a new one.

The following example will delete all 0 or empty values:

const sev = { a: 1, b: 0, c: 3 };
const deleteKeysBy = (obj, predicate) =>
  Object.keys(obj)
    .forEach( (key) => {
      if (predicate(obj[key])) {
        delete(obj[key]);
      }
    });

deleteKeysBy(sev, val => !val);

Merge/flatten an array of arrays

solve this problem using single line of code..

_x000D_
_x000D_
function unflatten(arr){_x000D_
    return arr.reduce((prevProps, nextProps) => {_x000D_
        return prevProps.concat(Array.isArray(nextProps) ? unflatten(nextProps) : nextProps)_x000D_
    }, [])_x000D_
}
_x000D_
_x000D_
_x000D_

https://codepen.io/jyotishman/pen/BayVeoQ

Winforms TableLayoutPanel adding rows programmatically

I just had a related problem (which is how I found this thread), where my dynamically added row and column styles were not taking effect. I usually consider SuspendLayout()/ResumeLayout() as optimizations, but in this case, wrapping my code in them made the rows and columns behave correctly.

How to set selected value on select using selectpicker plugin from bootstrap

$('#mybutton').click(function(){
   $('select[name=selValue]').val(1);
   $('select[name=selValue]').change();
});

This worked for me.

Running AMP (apache mysql php) on Android

Have you tried using Linux Installer to get a full Debian build on the phone? It's billed as being able to run a full LAMP environment in about 300M and has gotten some good reviews.

Calling another method java GUI

I'm not sure what you're trying to do, but here's something to consider: c(); won't do anything. c is an instance of the class checkbox and not a method to be called. So consider this:

public class FirstWindow extends JFrame {      public FirstWindow() {         checkbox c = new checkbox();         c.yourMethod(yourParameters); // call the method you made in checkbox     } }  public class checkbox extends JFrame {      public checkbox(yourParameters) {          // this is the constructor method used to initialize instance variables     }      public void yourMethod() // doesn't have to be void     {         // put your code here     } } 

Why is AJAX returning HTTP status code 0?

In my case, it was caused by running my django server under http://127.0.0.1:8000/ but sending the ajax call to http://localhost:8000/. Even though you would expect them to map to the same address, they don't so make sure you're not sending your requests to localhost.

Error:Execution failed for task ':app:processDebugResources'. > java.io.IOException: Could not delete folder "" in android studio

If it says:

The term 'gradlew' is not recognized

Then using following command

npm start -- --reset-cache

worked for me. cheers!

Does WGET timeout?

Prior to version 1.14, wget timeout arguments were not adhered to if downloading over https due to a bug.

jQuery text() and newlines

Using the CSS white-space property is probably the best solution. Use Firebug or Chrome Developer Tools to identify the source of the extra padding you were seeing.

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

Check out the contents of your array with

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

How can I represent an infinite number in Python?

No one seems to have mentioned about the negative infinity explicitly, so I think I should add it.

For negative infinity:

-math.inf

For positive infinity (just for the sake of completeness):

math.inf

How to add new column to an dataframe (to the front not end)?

df <- data.frame(b = c(1, 1, 1), c = c(2, 2, 2), d = c(3, 3, 3))
df
##   b c d
## 1 1 2 3
## 2 1 2 3
## 3 1 2 3

df <- data.frame(a = c(0, 0, 0), df)
df
##   a b c d
## 1 0 1 2 3
## 2 0 1 2 3
## 3 0 1 2 3

Difference between java.exe and javaw.exe

java.exe is the console app while javaw.exe is windows app (console-less). You can't have Console with javaw.exe.

How do I add my bot to a channel?

Now all clients allow to do it, but it's not pretty simple.
In any Telegram client:

  1. Open Channel info (in app title)
  2. Choose Administrators
  3. Add Administrator
  4. There will be no bots in contact list, so you need to search for it. Enter your bot's username
  5. Clicking on it you make it as administrator.

enter image description here

Pure Javascript listen to input value change

Actually, the ticked answer is exactly right, but the answer can be in ES6 shape:

HTMLInputElementObject.oninput = () => {
  console.log('run'); // Do something
}

Or can be written like below:

HTMLInputElementObject.addEventListener('input', (evt) => {
  console.log('run'); // Do something
});

How to check "hasRole" in Java Code with Spring Security?

you can use the isUserInRole method of the HttpServletRequest object.

something like:

public String createForm(HttpSession session, HttpServletRequest request,  ModelMap   modelMap) {


    if (request.isUserInRole("ROLE_ADMIN")) {
        // code here
    }
}

How do I install a NuGet package .nupkg file locally?

On Linux, with NuGet CLI, the commands are similar. To install my.nupkg, run

nuget add -Source some/directory my.nupkg

Then run dotnet restore from that directory

dotnet restore --source some/directory Project.sln

or add that directory as a NuGet source

nuget sources Add -Name MySource -Source some/directory

and then tell msbuild to use that directory with /p:RestoreAdditionalSources=MySource or /p:RestoreSources=MySource. The second switch will disable all other sources, which is good for offline scenarios, for example.

Center a popup window on screen?

Based on Facebook's but uses a media query rather than user agent regex to calc if there is enough room (with some space) for the popup, otherwise goes full screen. Tbh popups on mobile open as new tabs anyway.

function popupCenter(url, title, w, h) {
  const hasSpace = window.matchMedia(`(min-width: ${w + 20}px) and (min-height: ${h + 20}px)`).matches;
  const isDef = v => typeof v !== 'undefined';
  const screenX = isDef(window.screenX) ? window.screenX : window.screenLeft;
  const screenY = isDef(window.screenY) ? window.screenY : window.screenTop;
  const outerWidth = isDef(window.outerWidth) ? window.outerWidth : document.documentElement.clientWidth;
  const outerHeight = isDef(window.outerHeight) ? window.outerHeight : document.documentElement.clientHeight - 22;
  const targetWidth = hasSpace ? w : null;
  const targetHeight = hasSpace ? h : null;
  const V = screenX < 0 ? window.screen.width + screenX : screenX;
  const left = parseInt(V + (outerWidth - targetWidth) / 2, 10);
  const right = parseInt(screenY + (outerHeight - targetHeight) / 2.5, 10);
  const features = [];

  if (targetWidth !== null) {
    features.push(`width=${targetWidth}`);
  }

  if (targetHeight !== null) {
    features.push(`height=${targetHeight}`);
  }

  features.push(`left=${left}`);
  features.push(`top=${right}`);
  features.push('scrollbars=1');

  const newWindow = window.open(url, title, features.join(','));

  if (window.focus) {
    newWindow.focus();
  }

  return newWindow;
}

How can I convert tabs to spaces in every file of a directory?

No body mentioned rpl? Using rpl you can replace any string. To convert tabs to spaces,

rpl -R -e "\t" "    "  .

very simple.

How to switch to new window in Selenium for Python?

You can do it by using window_handles and switch_to_window method.

Before clicking the link first store the window handle as

window_before = driver.window_handles[0]

after clicking the link store the window handle of newly opened window as

window_after = driver.window_handles[1]

then execute the switch to window method to move to newly opened window

driver.switch_to_window(window_after)

and similarly you can switch between old and new window. Following is the code example

import unittest
from selenium import webdriver

class GoogleOrgSearch(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox()

    def test_google_search_page(self):
        driver = self.driver
        driver.get("http://www.cdot.in")
        window_before = driver.window_handles[0]
        print window_before
        driver.find_element_by_xpath("//a[@href='http://www.cdot.in/home.htm']").click()
        window_after = driver.window_handles[1]
        driver.switch_to_window(window_after)
        print window_after
        driver.find_element_by_link_text("ATM").click()
        driver.switch_to_window(window_before)

    def tearDown(self):
        self.driver.close()

if __name__ == "__main__":
    unittest.main()

C++ - How to append a char to char*?

The function name does not reflect the semantic of the function. In fact you do not append a character. You create a new character array that contains the original array plus the given character. So if you indeed need a function that appends a character to a character array I would write it the following way

bool AppendCharToCharArray( char *array, size_t n, char c )
{
    size_t sz = std::strlen( array );

    if ( sz + 1 < n ) 
    {
        array[sz] = c;
        array[sz + 1] = '\0';
    }       

    return ( sz + 1 < n );
} 

If you need a function that will contain a copy of the original array plus the given character then it could look the following way

char * CharArrayPlusChar( const char *array, char c )
{
    size_t sz = std::strlen( array );
    char *s = new char[sz + 2];

    std::strcpy( s, array );
    s[sz] = c;
    s[sz + 1] = '\0';

    return ( s );
} 

Android Studio Error: Error:CreateProcess error=216, This version of %1 is not compatible with the version of Windows you're running

Don't worry... Its much easy to solve your problem. Just SET you SDK-LOCATION and JDK-LOCATION.

  • Click on Configure ( As Soon Android studio open )
  • Click Project Default
  • Click Project Structure
  • Clik Android Sdk Location

  • Select & Browse your Android SDK Location (Like: C:\Android\sdk)

  • Uncheck USE EMBEDDED JDK LOCATION

  • Set & Browse JDK Location, Like C:\Program Files\Java\jdk1.8.0_121

How to send post request to the below post method using postman rest client

  1. Open Postman.
  2. Enter URL in the URL bar http://{server:port}/json/metallica/post.
  3. Click Headers button and enter Content-Type as header and application/json in value.
  4. Select POST from the dropdown next to the URL text box.
  5. Select raw from the buttons available below URL text box.
  6. Select JSON from the following dropdown.
  7. In the textarea available below, post your request object:

    {
     "title" : "test title",
     "singer" : "some singer"
    }
    
  8. Hit Send.

  9. Refer to screenshot below: enter image description here

Cast to generic type in C#

Please see if following solution works for you. The trick is to define a base processor interface which takes a base type of message.

interface IMessage
{
}

class LoginMessage : IMessage
{
}

class LogoutMessage : IMessage
{
}

class UnknownMessage : IMessage
{
}

interface IMessageProcessor
{
    void PrcessMessageBase(IMessage msg);
}

abstract class MessageProcessor<T> : IMessageProcessor where T : IMessage
{
    public void PrcessMessageBase(IMessage msg)
    {
        ProcessMessage((T)msg);
    }

    public abstract void ProcessMessage(T msg);

}

class LoginMessageProcessor : MessageProcessor<LoginMessage>
{
    public override void ProcessMessage(LoginMessage msg)
    {
        System.Console.WriteLine("Handled by LoginMsgProcessor");
    }
}

class LogoutMessageProcessor : MessageProcessor<LogoutMessage>
{
    public override void ProcessMessage(LogoutMessage msg)
    {
        System.Console.WriteLine("Handled by LogoutMsgProcessor");
    }
}

class MessageProcessorTest
{
    /// <summary>
    /// IMessage Type and the IMessageProcessor which would process that type.
    /// It can be further optimized by keeping IMessage type hashcode
    /// </summary>
    private Dictionary<Type, IMessageProcessor> msgProcessors = 
                                new Dictionary<Type, IMessageProcessor>();
    bool processorsLoaded = false;

    public void EnsureProcessorsLoaded()
    {
        if(!processorsLoaded)
        {
            var processors =
                from processorType in Assembly.GetExecutingAssembly().GetTypes()
                where processorType.IsClass && !processorType.IsAbstract &&
                      processorType.GetInterface(typeof(IMessageProcessor).Name) != null
                select Activator.CreateInstance(processorType);

            foreach (IMessageProcessor msgProcessor in processors)
            {
                MethodInfo processMethod = msgProcessor.GetType().GetMethod("ProcessMessage");
                msgProcessors.Add(processMethod.GetParameters()[0].ParameterType, msgProcessor);
            }

            processorsLoaded = true;
        }
    }

    public void ProcessMessages()
    {
        List<IMessage> msgList = new List<IMessage>();
        msgList.Add(new LoginMessage());
        msgList.Add(new LogoutMessage());
        msgList.Add(new UnknownMessage());

        foreach (IMessage msg in msgList)
        {
            ProcessMessage(msg);
        }
    }

    public void ProcessMessage(IMessage msg)
    {
        EnsureProcessorsLoaded();
        IMessageProcessor msgProcessor = null;
        if(msgProcessors.TryGetValue(msg.GetType(), out msgProcessor))
        {
            msgProcessor.PrcessMessageBase(msg);
        }
        else
        {
            System.Console.WriteLine("Processor not found");
        }
    }

    public static void Test()
    {
        new MessageProcessorTest().ProcessMessages();
    }
}

how to make log4j to write to the console as well

This works well for console in debug mode

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.Target=System.out
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p - %m%n

Convert command line arguments into an array in Bash

Maybe this can help:

myArray=("$@") 

also you can iterate over arguments by omitting 'in':

for arg; do
   echo "$arg"
done

will be equivalent

for arg in "${myArray[@]}"; do
   echo "$arg"
done

'nuget' is not recognized but other nuget commands working

The nuget commandline tool does not come with the vsix file, it's a separate download

https://github.com/nuget/home

How to split data into training/testing sets using sample function

My solution is basically the same as dickoa's but a little easier to interpret:

data(mtcars)
n = nrow(mtcars)
trainIndex = sample(1:n, size = round(0.7*n), replace=FALSE)
train = mtcars[trainIndex ,]
test = mtcars[-trainIndex ,]

SQL Query - how do filter by null or not null

I think this could work:

select * from tbl where statusid = isnull(@statusid,statusid)

Bootstrap trying to load map file. How to disable it? Do I need to do it?

Follow that tutorial: Disable JavaScript With Chrome DevTools

Summary:

  1. Open your code Inspector (right click)
  2. Press Control+Shift+P and search "Disable JavaScript source maps"
  3. Do same for "Disable CSS source maps"
  4. Press control+F5 to clear cache and reload page.

Add empty columns to a dataframe with specified names from a vector

Maybe

df <- do.call("cbind", list(df, rep(list(NA),length(namevector))))
colnames(df)[-1*(1:(ncol(df) - length(namevector)))] <- namevector

Remove Blank option from Select Option with AngularJS

If you just want to remove the blank space use ng-show and you are done! No need to initialize value in JS.

<select ng-model="SelectedStatus" ng-options="x.caption for x in statusList">
    <option value="" ng-show="false"></option>
</select>`

The remote server returned an error: (403) Forbidden

In my case I remembered that a hole in the firewall was created for this address some time ago, so I had to set useDefaultWebProxy="false" on the binding in the config file, as if the default was to use the proxy if useDefaultWebProxy is not specified.

How do I create variable variables?

Instead of a dictionary you can also use namedtuple from the collections module, which makes access easier.

For example:

# using dictionary
variables = {}
variables["first"] = 34
variables["second"] = 45
print(variables["first"], variables["second"])

# using namedtuple
Variables = namedtuple('Variables', ['first', 'second'])
vars = Variables(34, 45)
print(vars.first, vars.second)

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

DateTime dt = DateTime.Now;

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

C#: How do you edit items and subitems in a listview?

private void listView1_MouseDown(object sender, MouseEventArgs e)
{
    li = listView1.GetItemAt(e.X, e.Y);
    X = e.X;
    Y = e.Y;
}

private void listView1_MouseUp(object sender, MouseEventArgs e)
{
    int nStart = X;
    int spos = 0;
    int epos = listView1.Columns[1].Width;
    for (int i = 0; i < listView1.Columns.Count; i++)
    {
        if (nStart > spos && nStart < epos)
        {
            subItemSelected = i;
            break;
        }

        spos = epos;
        epos += listView1.Columns[i].Width;
    }
    li.SubItems[subItemSelected].Text = "9";
}

How to convert a datetime to string in T-SQL

The following query will get the current datetime and convert into string. with the following format
yyyy-mm-dd hh:mm:ss(24h)

SELECT convert(varchar(25), getdate(), 120) 

Can we execute a java program without a main() method?

Yes You can compile and execute without main method By using static block. But after static block executed (printed) you will get an error saying no main method found.

And Latest INFO --> YOU cant Do this with JAVA 7 version. IT will not execute.

{
    static
    {
        System.out.println("Hello World!");
        System.exit(0); // prevents “main method not found” error
    }
}

But this will not execute with JAVA 7 version.

ViewPager PagerAdapter not updating the View

There are several ways to achieve this.

The first option is easier, but bit more inefficient.

Override getItemPosition in your PagerAdapter like this:

public int getItemPosition(Object object) {
    return POSITION_NONE;
}

This way, when you call notifyDataSetChanged(), the view pager will remove all views and reload them all. As so the reload effect is obtained.

The second option, suggested by Alvaro Luis Bustamante (previously alvarolb), is to setTag() method in instantiateItem() when instantiating a new view. Then instead of using notifyDataSetChanged(), you can use findViewWithTag() to find the view you want to update.

The second approach is very flexible and high performant. Kudos to alvarolb for the original research.

Fullscreen Activity in Android?

Use this method after setContentView in onCreate() and pass the Window object by getWindow().

    public void makeActivityFullScreen(Window window){
    View decorView = window.getDecorView();
    //        int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
       window.getAttributes().layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
    }
    decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
            | View.SYSTEM_UI_FLAG_FULLSCREEN
            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
    );
}

This code will work for notch screen also. To check the notch fullscreen you require android P but if You have a notch display phone then go to setting-->Display setting -->app display ratio --->select your app --->there will be two options safe are display and full screen , please select the full screen and run the app, you can see the fullscreen in notch also without having android Pie

Access a URL and read Data with R

Beside of read.csv(url("...")) you also can use read.table("http://...").

Example:

> sample <- read.table("http://www.ats.ucla.edu/stat/examples/ara/angell.txt")
> sample
                V1   V2   V3   V4 V5
1        Rochester 19.0 20.6 15.0  E
2         Syracuse 17.0 15.6 20.2  E
...
43         Atlanta  4.2 70.6 32.6  S
> 

java.lang.VerifyError: Expecting a stackmap frame at branch target JDK 1.7

This ERROR can happen when you use Mockito to mock final classes.

Consider using Mockito inline or Powermock instead.

NoClassDefFoundError for code in an Java library on Android

1)In Manifest file mention your activity name and action for it and also category . 2)In your Activity mention your starting contentview and mention your view id's in the activity.

Failed to create provisioning profile

Check these things.

1.A device is connected to your system or not.

2.Deployment target in xcode. (General->Deployment info->Deployment target) It should match with the ios version of your device.

3.Change your bundle identifier. Follow general rules of setting a unique bundle identifier for yourproject while running in device. See this what is correct format of bundle identifier in iOS?

Also be careful with the number of bundle identifiers you set in the project. Please remember all bundle identifiers or note it down somewhere. Since you are using a free account you have limited access to the number of bundle id's.

You should also disable push notifications in the "Capabilities" section of the project. Try changing "App groups" as well in the format of group.com.someString.

These things helped me run my app in real device without any errors.

Insert images to XML file

I always convert the byte data to a Base64 encoding and then insert the image.

This is also the way that Word does it, for it's XML files (not that Word is a good example on how to work with XML :P).

How to clear File Input

I have done something like this and it's working for me

$('#fileInput').val(null); 

C# - Multiple generic types in one list

Following leppie's answer, why not make MetaData an interface:

public interface IMetaData { }

public class Metadata<DataType> : IMetaData where DataType : struct
{
    private DataType mDataType;
}

Detecting EOF in C

Another issue is that you're reading with scanf("%f", &input); only. If the user types something that can't be interpreted as a C floating-point number, like "pi", the scanf() call will not assign anything to input, and won't progress from there. This means it would attempt to keep reading "pi", and failing.

Given the change to while(!feof(stdin)) which other posters are correctly recommending, if you typed "pi" in there would be an endless loop of printing out the former value of input and printing the prompt, but the program would never process any new input.

scanf() returns the number of assignments to input variables it made. If it made no assignment, that means it didn't find a floating-point number, and you should read through more input with something like char string[100];scanf("%99s", string);. This will remove the next string from the input stream (up to 99 characters, anyway - the extra char is for the null terminator on the string).

You know, this is reminding me of all the reasons I hate scanf(), and why I use fgets() instead and then maybe parse it using sscanf().

How to read pdf file and write it to outputStream

import java.io.*;


public class FileRead {


    public static void main(String[] args) throws IOException {


        File f=new File("C:\\Documents and Settings\\abc\\Desktop\\abc.pdf");

        OutputStream oos = new FileOutputStream("test.pdf");

        byte[] buf = new byte[8192];

        InputStream is = new FileInputStream(f);

        int c = 0;

        while ((c = is.read(buf, 0, buf.length)) > 0) {
            oos.write(buf, 0, c);
            oos.flush();
        }

        oos.close();
        System.out.println("stop");
        is.close();

    }

}

The easiest way so far. Hope this helps.

What is the use of DesiredCapabilities in Selenium WebDriver?

When you run selenium WebDriver, the WebDriver opens a remote server in your computer's local host. Now, this server, called the Selenium Server, is used to interpret your code into actions to run or "drive" the instance of a real browser known as either chromebrowser, ie broser, ff browser, etc.

So, the Selenium Server can interact with different browser properties and hence it has many "capabilities".

Now what capabilities do you desire? Consider a scenario where you are validating if files have been downloaded properly in your app but, however, you do not have a desktop automation tool. In the case where you click the download link and a desktop pop up shows up to ask where to save and/or if you want to download. Your next route to bypass that would be to suppress that pop up. How? Desired Capabilities.

There are other such examples. In summary, Selenium Server can do a lot, use Desired Capabilities to tailor it to your need.

DateTime group by date and hour

Using MySQL I usually do it that way:

SELECT count( id ), ...
FROM quote_data
GROUP BY date_format( your_date_column, '%Y%m%d%H' )
order by your_date_column desc;

Or in the same idea, if you need to output the date/hour:

SELECT count( id ) , date_format( your_date_column, '%Y-%m-%d %H' ) as my_date
FROM  your_table 
GROUP BY my_date
order by your_date_column desc;

If you specify an index on your date column, MySQL should be able to use it to speed up things a little.

Add space between two particular <td>s

Simple answer: give these two tds a style field.

<tr>
<td>One</td>
<td style="padding-right: 10px">Two</td>
<td>Three</td>
<td>Four</td>
</tr>

Tidy one: use class name

<tr>
<td>One</td>
<td class="more-padding-on-right">Two</td>
<td>Three</td>
<td>Four</td>
</tr>

.more-padding-on-right {
  padding-right: 10px;
}

Complex one: using nth-child selector in CSS and specify special padding values for these two, which works in modern browsers.

tr td:nth-child(2) {
  padding-right: 10px;
}?

QUERY syntax using cell reference

I found out that single quote > double quote > wrapped in ampersands did work. So, for me it looks like this:

=QUERY('Youth Conference Registration'!C:Y,"select C where Y = '"&A1&"'", 0)

Get controller and action name from within controller?

Here are some extension methods for getting that information (it also includes the ID):

public static class HtmlRequestHelper
{
    public static string Id(this HtmlHelper htmlHelper)
    {
        var routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values;

        if (routeValues.ContainsKey("id"))
            return (string)routeValues["id"];
        else if (HttpContext.Current.Request.QueryString.AllKeys.Contains("id"))
            return HttpContext.Current.Request.QueryString["id"];

        return string.Empty;
    }

    public static string Controller(this HtmlHelper htmlHelper)
    {
        var routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values;

        if (routeValues.ContainsKey("controller"))
            return (string)routeValues["controller"];

        return string.Empty;
    }

    public static string Action(this HtmlHelper htmlHelper)
    {
        var routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values;

        if (routeValues.ContainsKey("action"))
            return (string)routeValues["action"];

        return string.Empty;
    }
}

Usage:

@Html.Controller();
@Html.Action();
@Html.Id();

How to get Database Name from Connection String using SqlConnectionStringBuilder

this gives you the Xact;

System.Data.SqlClient.SqlConnectionStringBuilder connBuilder = new System.Data.SqlClient.SqlConnectionStringBuilder();

connBuilder.ConnectionString = connectionString;

string server = connBuilder.DataSource;           //-> this gives you the Server name.
string database = connBuilder.InitialCatalog;     //-> this gives you the Db name.

Google server putty connect 'Disconnected: No supported authentication methods available (server sent: publickey)

For me these was my problem, solution from https://unix.stackexchange.com/questions/282908/server-refused-public-key-signature-despite-accepting-key-putty

"Looking at the log /var/log/secure showed that it was just downright refused. I'm somewhat new to centos since I'm mainly a debian kind of guy, so I was unaware of /var/log/secure

After checking this and doing a bit of searching, it turns out PermitRootLogin no needs to be PermitRootLogin without-password if you want to specifically use just keys for root login. That did the trick. Thanks everyone for contributing."

MySQL "between" clause not inclusive?

From the MySQL-manual:

This is equivalent to the expression (min <= expr AND expr <= max)

Cannot find vcvarsall.bat when running a Python script

This cryptic error means that you don't have a C compiler installed. There was a discussion to propose a more explanative error (which is continued here, register and comment if you care about it!) but currently it is still not implemented.

To fix this issue you can either install the Visual Studio 2008 SDK which will take about a GB, or you can install the very small VCForPython27.msi but which is not well supported by distutils currently, here's the procedure:

1) install Microsoft Visual C++ Compiler for Python 2.7 from
http://www.microsoft.com/en-us/download/details.aspx?id=44266
2) Enter MSVC for Python command prompt
3) SET DISTUTILS_USE_SDK=1
4) SET MSSdk=1
5) you can then build your C extensions: python.exe setup.py ...

Steps 2 to 4 must be reproduced everytime before building your C extensions. This is because of an issue with the VCForPython27.msi which install the header files and vcvarsall.bat in folders of a different layout than the VS2008 SDK and thus confuse the compiler detection of distutils. This will get fixed in setuptools in Python 2.7.10.

Bug report and workaround by Gregory Szorc: http://bugs.python.org/issue23246

More info and a workaround for using %%cython magic inside IPython: https://github.com/cython/cython/wiki/CythonExtensionsOnWindows

/EDIT: Also, if you have another version of Python, you cannot use Microsoft Visual C++ for Python 2.7, which is a kind of mini-compiler specifically made by Microsoft for Python 2.7. In this case, you need to install the Visual Studio SDK that match your Python version, or a Windows SDK with the correct NET framework version. See here for more infos: https://github.com/cython/cython/wiki/CythonExtensionsOnWindows#using-windows-sdk-cc-compiler-works-for-all-python-versions

How to submit an HTML form without redirection

Since all current answers use jQuery or tricks with iframe, figured there is no harm to add method with just plain JavaScript:

function formSubmit(event) {
  var url = "/post/url/here";
  var request = new XMLHttpRequest();
  request.open('POST', url, true);
  request.onload = function() { // request successful
  // we can use server response to our request now
    console.log(request.responseText);
  };

  request.onerror = function() {
    // request failed
  };

  request.send(new FormData(event.target)); // create FormData from form that triggered event
  event.preventDefault();
}

// and you can attach form submit event like this for example
function attachFormSubmitEvent(formId){
  document.getElementById(formId).addEventListener("submit", formSubmit);
}

How to copy file from host to container using Dockerfile

Use COPY command like this:

COPY foo.txt /data/foo.txt
# where foo.txt is the relative path on host
# and /data/foo.txt is the absolute path in the image

read more details for COPY in the official documentation

An alternative would be to use ADD but this is not the best practise if you dont want to use some advanced features of ADD like decompression of tar.gz files.If you still want to use ADD command, do it like this:

ADD abc.txt /data/abc.txt
# where abc.txt is the relative path on host
# and /data/abc.txt is the absolute path in the image

read more details for ADD in the official documentation