Programs & Examples On #Void

An incomplete type used as syntactic place-holder for the return type of a method/function when no value is returned.

Unit testing void methods?

Use Rhino Mocks to set what calls, actions and exceptions might be expected. Assuming you can mock or stub out parts of your method. Hard to know without knowing some specifics here about the method, or even context.

What does "javascript:void(0)" mean?

void is an operator that is used to return a undefined value so the browser will not be able to load a new page.

Web browsers will try and take whatever is used as a URL and load it unless it is a JavaScript function that returns null. For example, if we click a link like this:

<a href="javascript: alert('Hello World')">Click Me</a>

then an alert message will show up without loading a new page, and that is because alert is a function that returns a null value. This means that when the browser attempts to load a new page it sees null and has nothing to load.

An important thing to note about the void operator is that it requires a value and cannot be used by itself. We should use it like this:

<a href="javascript: void(0)">I am a useless link</a>

What does the return keyword do in a void method in Java?

The Java language specification says you can have return with no expression if your method returns void.

how does int main() and void main() work

Neither main() or void main() are standard C. The former is allowed as it has an implicit int return value, making it the same as int main(). The purpose of main's return value is to return an exit status to the operating system.

In standard C, the only valid signatures for main are:

int main(void)

and

int main(int argc, char **argv)

The form you're using: int main() is an old style declaration that indicates main takes an unspecified number of arguments. Don't use it - choose one of those above.

Is it better to use C void arguments "void foo(void)" or not "void foo()"?

There are two ways for specifying parameters in C. One is using an identifier list, and the other is using a parameter type list. The identifier list can be omitted, but the type list can not. So, to say that one function takes no arguments in a function definition you do this with an (omitted) identifier list

void f() {
    /* do something ... */
}

And this with a parameter type list:

void f(void) {
    /* do something ... */
}

If in a parameter type list the only one parameter type is void (it must have no name then), then that means the function takes no arguments. But those two ways of defining a function have a difference regarding what they declare.

Identifier lists

The first defines that the function takes a specific number of arguments, but neither the count is communicated nor the types of what is needed - as with all function declarations that use identifier lists. So the caller has to know the types and the count precisely before-hand. So if the caller calls the function giving it some argument, the behavior is undefined. The stack could become corrupted for example, because the called function expects a different layout when it gains control.

Using identifier lists in function parameters is deprecated. It was used in old days and is still present in lots of production code. They can cause severe danger because of those argument promotions (if the promoted argument type do not match the parameter type of the function definition, behavior is undefined either!) and are much less safe, of course. So always use the void thingy for functions without parameters, in both only-declarations and definitions of functions.

Parameter type list

The second one defines that the function takes zero arguments and also communicates that - like with all cases where the function is declared using a parameter type list, which is called a prototype. If the caller calls the function and gives it some argument, that is an error and the compiler spits out an appropriate error.

The second way of declaring a function has plenty of benefits. One of course is that amount and types of parameters are checked. Another difference is that because the compiler knows the parameter types, it can apply implicit conversions of the arguments to the type of the parameters. If no parameter type list is present, that can't be done, and arguments are converted to promoted types (that is called the default argument promotion). char will become int, for example, while float will become double.

Composite type for functions

By the way, if a file contains both an omitted identifier list and a parameter type list, the parameter type list "wins". The type of the function at the end contains a prototype:

void f();
void f(int a) {
    printf("%d", a);
}

// f has now a prototype. 

That is because both declarations do not say anything contradictory. The second, however, had something to say in addition. Which is that one argument is accepted. The same can be done in reverse

void f(a) 
  int a;
{ 
    printf("%d", a);
}

void f(int);

The first defines a function using an identifier list, while the second then provides a prototype for it, using a declaration containing a parameter type list.

How to mock void methods with Mockito

Take a look at the Mockito API docs. As the linked document mentions (Point # 12) you can use any of the doThrow(),doAnswer(),doNothing(),doReturn() family of methods from Mockito framework to mock void methods.

For example,

Mockito.doThrow(new Exception()).when(instance).methodName();

or if you want to combine it with follow-up behavior,

Mockito.doThrow(new Exception()).doNothing().when(instance).methodName();

Presuming that you are looking at mocking the setter setState(String s) in the class World below is the code uses doAnswer method to mock the setState.

World mockWorld = mock(World.class); 
doAnswer(new Answer<Void>() {
    public Void answer(InvocationOnMock invocation) {
      Object[] args = invocation.getArguments();
      System.out.println("called with arguments: " + Arrays.toString(args));
      return null;
    }
}).when(mockWorld).setState(anyString());

What does void do in java?

When the return type is void, your method doesn't return anything.

Look again at your code: There's no return in that method. You print to the console and exit.

Returning from a void function

The only reason to have a return in a void function would be to exit early due to some conditional statement:

void foo(int y)
{
    if(y == 0) return;

    // do stuff with y
}

As unwind said: when the code ends, it ends. No need for an explicit return at the end.

variable or field declared void

It for example happens in this case here:

void initializeJSP(unknownType Experiment);

Try using std::string instead of just string (and include the <string> header). C++ Standard library classes are within the namespace std::.

Java 8 lambda Void argument

That is not possible. A function that has a non-void return type (even if it's Void) has to return a value. However you could add static methods to Action that allows you to "create" a Action:

interface Action<T, U> {
   U execute(T t);

   public static Action<Void, Void> create(Runnable r) {
       return (t) -> {r.run(); return null;};
   }

   public static <T, U> Action<T, U> create(Action<T, U> action) {
       return action;
   } 
}

That would allow you to write the following:

// create action from Runnable
Action.create(()-> System.out.println("Hello World")).execute(null);
// create normal action
System.out.println(Action.create((Integer i) -> "number: " + i).execute(100));

What's the better (cleaner) way to ignore output in PowerShell?

I just did some tests of the four options that I know about.

Measure-Command {$(1..1000) | Out-Null}

TotalMilliseconds : 76.211

Measure-Command {[Void]$(1..1000)}

TotalMilliseconds : 0.217

Measure-Command {$(1..1000) > $null}

TotalMilliseconds : 0.2478

Measure-Command {$null = $(1..1000)}

TotalMilliseconds : 0.2122

## Control, times vary from 0.21 to 0.24
Measure-Command {$(1..1000)}

TotalMilliseconds : 0.2141

So I would suggest that you use anything but Out-Null due to overhead. The next important thing, to me, would be readability. I kind of like redirecting to $null and setting equal to $null myself. I use to prefer casting to [Void], but that may not be as understandable when glancing at code or for new users.

I guess I slightly prefer redirecting output to $null.

Do-Something > $null

Edit

After stej's comment again, I decided to do some more tests with pipelines to better isolate the overhead of trashing the output.

Here are some tests with a simple 1000 object pipeline.

## Control Pipeline
Measure-Command {$(1..1000) | ?{$_ -is [int]}}

TotalMilliseconds : 119.3823

## Out-Null
Measure-Command {$(1..1000) | ?{$_ -is [int]} | Out-Null}

TotalMilliseconds : 190.2193

## Redirect to $null
Measure-Command {$(1..1000) | ?{$_ -is [int]} > $null}

TotalMilliseconds : 119.7923

In this case, Out-Null has about a 60% overhead and > $null has about a 0.3% overhead.

Addendum 2017-10-16: I originally overlooked another option with Out-Null, the use of the -inputObject parameter. Using this the overhead seems to disappear, however the syntax is different:

Out-Null -inputObject ($(1..1000) | ?{$_ -is [int]})

And now for some tests with a simple 100 object pipeline.

## Control Pipeline
Measure-Command {$(1..100) | ?{$_ -is [int]}}

TotalMilliseconds : 12.3566

## Out-Null
Measure-Command {$(1..100) | ?{$_ -is [int]} | Out-Null}

TotalMilliseconds : 19.7357

## Redirect to $null
Measure-Command {$(1..1000) | ?{$_ -is [int]} > $null}

TotalMilliseconds : 12.8527

Here again Out-Null has about a 60% overhead. While > $null has an overhead of about 4%. The numbers here varied a bit from test to test (I ran each about 5 times and picked the middle ground). But I think it shows a clear reason to not use Out-Null.

How do I mock a static method that returns void with PowerMock?

To mock a static method that return void for e.g. Fileutils.forceMKdir(File file),

Sample code:

File file =PowerMockito.mock(File.class);
PowerMockito.doNothing().when(FileUtils.class,"forceMkdir",file);

Check OS version in Swift?

Update:
Now you should use new availability checking introduced with Swift 2:
e.g. To check for iOS 9.0 or later at compile time use this:

if #available(iOS 9.0, *) {
    // use UIStackView
} else {
    // show sad face emoji
}

or can be used with whole method or class

@available(iOS 9.0, *)
func useStackView() {
    // use UIStackView
}

For more info see this.

Run time checks:

if you don't want exact version but want to check iOS 9,10 or 11 using if:

let floatVersion = (UIDevice.current.systemVersion as NSString).floatValue

EDIT: Just found another way to achieve this:

let iOS8 = floor(NSFoundationVersionNumber) > floor(NSFoundationVersionNumber_iOS_7_1)
let iOS7 = floor(NSFoundationVersionNumber) <= floor(NSFoundationVersionNumber_iOS_7_1)

Select All checkboxes using jQuery

I know its too late, but I'm posting this for the upcoming developers.

For select all checkbox we need to check three conditions, 1. on click select all checkbox every checkbox should get selected 2. if all selected then on click select all checkbox, every checkbox should get deselected 3. if we deselect or select any of the checkbox the select all checkbox also should change.

with these three things we'll get a good result.for this you can approach this link https://qawall.in/2020/05/30/select-all-or-deselect-all-checkbox-using-jquery/ I got my solution from here, they have provided solution with examples.

<table>
<tr>
    <th><input type="checkbox" id="select_all"/> Select all</th>
</tr>
<tr>
    <td><input type="checkbox" class="check" value="1"/> Check 1</td>
    <td><input type="checkbox" class="check" value="2"/> Check 2</td>
    <td><input type="checkbox" class="check" value="3"/> Check 3</td>
    <td><input type="checkbox" class="check" value="4"/> Check 4</td>
    <td><input type="checkbox" class="check" value="5"/> Check 5</td>
</tr>

<script type="text/javascript">
$(document).ready(function(){
$('#select_all').on('click',function(){
    if(this.checked){
        $('.check').each(function(){
            this.checked = true;
        });
    }else{
         $('.check').each(function(){
            this.checked = false;
        });
    }
});

$('.check').on('click',function(){
    if($('.check:checked').length == $('.check').length){
        $('#select_all').prop('checked',true);
    }else{
        $('#select_all').prop('checked',false);
    }
});

});

hope this will help anyone ...:)

Open URL in Java to get the content

If you just want to open up the webpage, I think less is more in this case:

import java.awt.Desktop;
import java.net.URI; //Note this is URI, not URL

class BrowseURL{
    public static void main(String args[]) throws Exception{
        // Create Desktop object
        Desktop d=Desktop.getDesktop();

        // Browse a URL, say google.com
        d.browse(new URI("http://google.com"));

        }
    }
}

Is there an equivalent of 'which' on the Windows command line?

If you have PowerShell installed (which I recommend), you can use the following command as a rough equivalent (substitute programName for your executable's name):

($Env:Path).Split(";") | Get-ChildItem -filter programName*

More is here: My Manwich! PowerShell Which

React won't load local images

Another way to do:

First, install these modules: url-loader, file-loader

Using npm: npm install --save-dev url-loader file-loader

Next, add this to your Webpack config:

module: {
    loaders: [
      { test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192' }
    ]
  }

limit: Byte limit to inline files as Data URL

You need to install both modules: url-loader and file-loader

Finally, you can do:

<img src={require('./my-path/images/my-image.png')}/>

You can investigate these loaders further here:

url-loader: https://www.npmjs.com/package/url-loader

file-loader: https://www.npmjs.com/package/file-loader

Hide Signs that Meteor.js was Used

The amount of hacks you would need to go through to completely hide the fact your site is built by Meteor.js is absolutely ridiculous. You would have to strip essentially all core functionality and just serve straight up html, completely defeating the purpose of using the framework anyway.

That being said, I suggest looking at buildwith.com

You enter a url, and it reveals a ton of information about a site. If you only need to "fool" engines like this, there may be simple solutions.

Why should we NOT use sys.setdefaultencoding("utf-8") in a py script?

tl;dr

The answer is NEVER! (unless you really know what you're doing)

9/10 times the solution can be resolved with a proper understanding of encoding/decoding.

1/10 people have an incorrectly defined locale or environment and need to set:

PYTHONIOENCODING="UTF-8"  

in their environment to fix console printing problems.

What does it do?

sys.setdefaultencoding("utf-8") (struck through to avoid re-use) changes the default encoding/decoding used whenever Python 2.x needs to convert a Unicode() to a str() (and vice-versa) and the encoding is not given. I.e:

str(u"\u20AC")
unicode("€")
"{}".format(u"\u20AC") 

In Python 2.x, the default encoding is set to ASCII and the above examples will fail with:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)

(My console is configured as UTF-8, so "€" = '\xe2\x82\xac', hence exception on \xe2)

or

UnicodeEncodeError: 'ascii' codec can't encode character u'\u20ac' in position 0: ordinal not in range(128)

sys.setdefaultencoding("utf-8") will allow these to work for me, but won't necessarily work for people who don't use UTF-8. The default of ASCII ensures that assumptions of encoding are not baked into code

Console

sys.setdefaultencoding("utf-8") also has a side effect of appearing to fix sys.stdout.encoding, used when printing characters to the console. Python uses the user's locale (Linux/OS X/Un*x) or codepage (Windows) to set this. Occasionally, a user's locale is broken and just requires PYTHONIOENCODING to fix the console encoding.

Example:

$ export LANG=en_GB.gibberish
$ python
>>> import sys
>>> sys.stdout.encoding
'ANSI_X3.4-1968'
>>> print u"\u20AC"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u20ac' in position 0: ordinal not in range(128)
>>> exit()

$ PYTHONIOENCODING=UTF-8 python
>>> import sys
>>> sys.stdout.encoding
'UTF-8'
>>> print u"\u20AC"
€

What's so bad with sys.setdefaultencoding("utf-8")?

People have been developing against Python 2.x for 16 years on the understanding that the default encoding is ASCII. UnicodeError exception handling methods have been written to handle string to Unicode conversions on strings that are found to contain non-ASCII.

From https://anonbadger.wordpress.com/2015/06/16/why-sys-setdefaultencoding-will-break-code/

def welcome_message(byte_string):
    try:
        return u"%s runs your business" % byte_string
    except UnicodeError:
        return u"%s runs your business" % unicode(byte_string,
            encoding=detect_encoding(byte_string))

print(welcome_message(u"Angstrom (Å®)".encode("latin-1"))

Previous to setting defaultencoding this code would be unable to decode the “Å” in the ascii encoding and then would enter the exception handler to guess the encoding and properly turn it into unicode. Printing: Angstrom (Å®) runs your business. Once you’ve set the defaultencoding to utf-8 the code will find that the byte_string can be interpreted as utf-8 and so it will mangle the data and return this instead: Angstrom (U) runs your business.

Changing what should be a constant will have dramatic effects on modules you depend upon. It's better to just fix the data coming in and out of your code.

Example problem

While the setting of defaultencoding to UTF-8 isn't the root cause in the following example, it shows how problems are masked and how, when the input encoding changes, the code breaks in an unobvious way: UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 3131: invalid start byte

jQuery: How to get the event object in an event handler function without passing it as an argument?

Write your event handler declaration like this:

<a href="#" onclick="myFunc(event,1,2,3)">click</a>

Then your "myFunc()" function can access the event.

The string value of the "onclick" attribute is converted to a function in a way that's almost exactly the same as the browser (internally) calling the Function constructor:

theAnchor.onclick = new Function("event", theOnclickString);

(except in IE). However, because "event" is a global in IE (it's a window attribute), you'll be able to pass it to the function that way in any browser.

No numeric types to aggregate - change in groupby() behaviour?

How are you generating your data?

See how the output shows that your data is of 'object' type? the groupby operations specifically check whether each column is a numeric dtype first.

In [31]: data
Out[31]: 
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 2557 entries, 2004-01-01 00:00:00 to 2010-12-31 00:00:00
Freq: <1 DateOffset>
Columns: 360 entries, -89.75 to 89.75
dtypes: object(360)

look ?


Did you initialize an empty DataFrame first and then filled it? If so that's probably why it changed with the new version as before 0.9 empty DataFrames were initialized to float type but now they are of object type. If so you can change the initialization to DataFrame(dtype=float).

You can also call frame.astype(float)

jQuery animate margin top

use 'marginTop' instead of MarginTop

$(this).find('.info').animate({ 'marginTop': '-50px', opacity: 0.5 }, 1000);

How do I run a simple bit of code in a new thread?

Here is another option:

Task.Run(()=>{
//Here is a new thread
});

Change the Blank Cells to "NA"

You can use gsub to replace multiple mutations of empty, like "" or a space, to be NA:

data= data.frame(cats=c('', ' ', 'meow'), dogs=c("woof", " ", NA))
apply(data, 2, function(x) gsub("^$|^ $", NA, x))

Using a SELECT statement within a WHERE clause

The principle of subqueries is not at all bad, but I don't think that you should use it in your example. If I understand correctly you want to get the maximum score for each date. In this case you should use a GROUP BY.

Right mime type for SVG images with fonts embedded

There's only one registered mediatype for SVG, and that's the one you listed, image/svg+xml. You can of course serve SVG as XML too, though browsers tend to behave differently in some scenarios if you do, for example I've seen cases where SVG used in CSS backgrounds fail to display unless served with the image/svg+xml mediatype.

What's the difference between F5 refresh and Shift+F5 in Google Chrome browser?

Reload the current page:
F5
or
CTRL + R


Reload the current page, ignoring cached content (i.e. JavaScript files, images, etc.):
SHIFT + F5
or
CTRL + F5
or
CTRL + SHIFT + R

Vuejs: v-model array in multiple input

You're thinking too DOM, it's a hard as hell habit to break. Vue recommends you approach it data first.

It's kind of hard to tell in your exact situation but I'd probably use a v-for and make an array of finds to push to as I need more.

Here's how I'd set up my instance:

new Vue({
  el: '#app',
  data: {
    finds: []
  },
  methods: {
    addFind: function () {
      this.finds.push({ value: '' });
    }
  }
});

And here's how I'd set up my template:

<div id="app">
  <h1>Finds</h1>
  <div v-for="(find, index) in finds">
    <input v-model="find.value" :key="index">
  </div>
  <button @click="addFind">
    New Find
  </button>
</div>

Although, I'd try to use something besides an index for the key.

Here's a demo of the above: https://jsfiddle.net/crswll/24txy506/9/

Why does the Google Play store say my Android app is incompatible with my own device?

I have experienced this problem too while developing an application for a customer that wanted to have videos offline available from their application. I have written a blogpost about why the app I worked on for months wouldn't show up in the play store for my device (post can be found here). I found the same as @Greg Hewgill found: Cache partition limitations on some devices.

The journey didn't stop for me there. The customer wanted to have these videos in the application and didn't want the quality of the video to be decreased. After some research I figured out that using expansion files was the perfect solution to our problem.

To share my knowledge with the Android community I held a talk at droidconNL 2012 about expansion files. I created a presentation and sample code to illustrate how easy it can be to start using expansion files. For any of you out there wanting to use expansion files to solve this problem feel free to check out the post containing the presentation and the sample code

How do I give text or an image a transparent background using CSS?

You can use RGBA (red, green, blue, alpha) in the CSS. Something like this:

So simply doing something like this is going to work in your case:

p {
  position: absolute;
  background-color: rgba(0, 255, 0, 0.6);
}

span {
  color: white;
}

How to fix: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

Perhaps the answer to this question is of use here too: how to find libstdc++.so.6: that contain GLIBCXX_3.4.19 for RHEL 6?

curl -O http://ftp.de.debian.org/debian/pool/main/g/gcc-4.7/libstdc++6-4.7-dbg_4.7.2-5_i386.deb
ar -x libstdc++6-4.7-dbg_4.7.2-5_i386.deb && tar xvf data.tar.gz
mkdir backup
cp /usr/lib/libstdc++.so* backup/
cp ./usr/lib/i386-linux-gnu/debug/libstdc++.so.6.0.17 /usr/lib
ln -s libstdc++.so.6.0.17 libstdc++.so.6

How do I align views at the bottom of the screen?

You can just give your top child view (the TextView @+id/TextView) an attribute: android:layout_weight="1".

This will force all other elements below it to the bottom.

cout is not a member of std

add #include <iostream> to the start of io.cpp too.

How to use regex in String.contains() method in Java

As of Java 11 one can use Pattern#asMatchPredicate which returns Predicate<String>.

String string = "stores%store%product";
String regex = "stores.*store.*product.*";
Predicate<String> matchesRegex = Pattern.compile(regex).asMatchPredicate();

boolean match = matchesRegex.test(string);                   // true

The method enables chaining with other String predicates, which is the main advantage of this method as long as the Predicate offers and, or and negate methods.

String string = "stores$store$product";
String regex = "stores.*store.*product.*";

Predicate<String> matchesRegex = Pattern.compile(regex).asMatchPredicate();
Predicate<String> hasLength = s -> s.length() > 20;

boolean match = hasLength.and(matchesRegex).test(string);    // false

How to convert an ASCII character into an int in C

As everyone else told you, you can convert it directly... UNLESS you meant something like "how can I convert an ASCII Extended character to its UTF-16 or UTF-32 value". This is a TOTALLY different question (one at least as good). And one quite difficult, if I remember correctly, if you are using only "pure" C. Then you could start here: https://stackoverflow.com/questions/114611/what-is-the-best-unicode-library-for-c/114643#114643

(for ASCII Extended I mean one of the many "extensions" to the ASCII set. The 0-127 characters of the base ASCII set are directly convertible to Unicode, while the 128-255 are not.). For example ISO_8859-1 http://en.wikipedia.org/wiki/ISO_8859-1 is an 8 bit extensions to the 7 bit ASCII set, or the (quite famous) codepages 437 and 850.

Python 3: EOF when reading a line (Sublime Text 2 is angry)

try:
    value = raw_input()
    do_stuff(value) # next line was found 
except (EOFError):
   break #end of file reached

This seems to be proper usage of raw_input when dealing with the end of the stream of input from piped input. [Refer this post][1]

Printing image with PrintDocument. how to adjust the image to fit paper size

The parameters that you are passing into the DrawImage method should be the size you want the image on the paper rather than the size of the image itself, the DrawImage command will then take care of the scaling for you. Probably the easiest way is to use the following override of the DrawImage command.

args.Graphics.DrawImage(i, args.MarginBounds);

Note: This will skew the image if the proportions of the image are not the same as the rectangle. Some simple math on the size of the image and paper size will allow you to create a new rectangle that fits in the bounds of the paper without skewing the image.

How to set the From email address for mailx command?

On debian where bsd-mailx is installed by default, the -r option does not work. However you can use mailx -s subject [email protected] -- -f [email protected] instead. According to man page, you can specify sendmail options after --.

VBA - Run Time Error 1004 'Application Defined or Object Defined Error'

Your cells object is not fully qualified. You need to add a DOT before the cells object. For example

With Worksheets("Cable Cards")
    .Range(.Cells(RangeStartRow, RangeStartColumn), _
           .Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues

Similarly, fully qualify all your Cells object.

"You may need an appropriate loader to handle this file type" with Webpack and Babel

This one throw me for a spin. Angular 7, Webpack I found this article so I want to give credit to the Article https://www.edc4it.com/blog/web/helloworld-angular2.html

What the solution is: //on your component file. use template as webpack will treat it as text template: require('./process.component.html')

for karma to interpret it npm install add html-loader --save-dev { test: /.html$/, use: "html-loader" },

Hope this helps somebody

Git - push current branch shortcut

With the help of ceztko's answer I wrote this little helper function to make my life easier:

function gpu()
{
    if git rev-parse --abbrev-ref --symbolic-full-name @{u} > /dev/null 2>&1; then
        git push origin HEAD
    else
        git push -u origin HEAD
    fi
}

It pushes the current branch to origin and also sets the remote tracking branch if it hasn't been setup yet.

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

From the current file path you could use:

os.path.join(os.path.dirname(__file__),'..','img','banner.png')

BasicHttpBinding vs WsHttpBinding vs WebHttpBinding

You're comparing apples to oranges here:

  • webHttpBinding is the REST-style binding, where you basically just hit a URL and get back a truckload of XML or JSON from the web service

  • basicHttpBinding and wsHttpBinding are two SOAP-based bindings which is quite different from REST. SOAP has the advantage of having WSDL and XSD to describe the service, its methods, and the data being passed around in great detail (REST doesn't have anything like that - yet). On the other hand, you can't just browse to a wsHttpBinding endpoint with your browser and look at XML - you have to use a SOAP client, e.g. the WcfTestClient or your own app.

So your first decision must be: REST vs. SOAP (or you can expose both types of endpoints from your service - that's possible, too).

Then, between basicHttpBinding and wsHttpBinding, there differences are as follows:

  • basicHttpBinding is the very basic binding - SOAP 1.1, not much in terms of security, not much else in terms of features - but compatible to just about any SOAP client out there --> great for interoperability, weak on features and security

  • wsHttpBinding is the full-blown binding, which supports a ton of WS-* features and standards - it has lots more security features, you can use sessionful connections, you can use reliable messaging, you can use transactional control - just a lot more stuff, but wsHttpBinding is also a lot *heavier" and adds a lot of overhead to your messages as they travel across the network

For an in-depth comparison (including a table and code examples) between the two check out this codeproject article: Differences between BasicHttpBinding and WsHttpBinding

Replace one substring for another string in shell script

For Dash all previous posts aren't working

The POSIX sh compatible solution is:

result=$(echo "$firstString" | sed "s/Suzi/$secondString/")

This will replace the first occurrence on each line of input. Add a /g flag to replace all occurrences:

result=$(echo "$firstString" | sed "s/Suzi/$secondString/g")

jQuery get the id/value of <li> element after click function

If You Have Multiple li elements inside an li element then this will definitely help you, and i have checked it and it works....

<script>
$("li").on('click', function() {
          alert(this.id);
          return false;
      });
</script>

Permission denied when launch python script via bash

Do “chmod +x script”

Now try executing

How to count number of unique values of a field in a tab-delimited text file?

You can use awk, sort & uniq to do this, for example to list all the unique values in the first column

awk < test.txt '{print $1}' | sort | uniq

As posted elsewhere, if you want to count the number of instances of something you can pipe the unique list into wc -l

Random float number generation

#include <cstdint>
#include <cstdlib>
#include <ctime>

using namespace std;

/* single precision float offers 24bit worth of linear distance from 1.0f to 0.0f */
float getval() {
    /* rand() has min 16bit, but we need a 24bit random number. */
    uint_least32_t r = (rand() & 0xffff) + ((rand() & 0x00ff) << 16);
    /* 5.9604645E-8 is (1f - 0.99999994f), 0.99999994f is the first value less than 1f. */
    return (double)r * 5.9604645E-8;
}

int main()
{
    srand(time(NULL));
...

I couldn't post two answers, so here is the second solution. log2 random numbers, massive bias towards 0.0f but it's truly a random float 1.0f to 0.0f.

#include <cstdint>
#include <cstdlib>
#include <ctime>

using namespace std;

float getval () {
    union UNION {
        uint32_t i;
        float f;
    } r;
    /* 3 because it's 0011, the first bit is the float's sign.
     * Clearing the second bit eliminates values > 1.0f.
     */
    r.i = (rand () & 0xffff) + ((rand () & 0x3fff) << 16);
    return r.f;
}

int main ()
{
    srand (time (NULL));
...

Fatal error: Call to a member function fetch_assoc() on a non-object

That's because there was an error in your query. MySQli->query() will return false on error. Change it to something like::

$result = $this->database->query($query);
if (!$result) {
    throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}

That should throw an exception if there's an error...

Extracting jar to specified directory

jars use zip compression so you can use any unzip utility.

Example:

$ unzip myJar.jar -d ./directoryToExtractTo

How to refresh a page with jQuery by passing a parameter to URL

You could simply have just done:

var varAppend = "?single";
window.location.href = window.location.href.replace(".com",".com" + varAppend);

Unlike the other answers provided, there is no needless conditional check. If you design your project properly, you'll let the interface make the decision making and calling that statement whenever an event has been triggered.

Since there will only be one ".com" in your url, it will just replace .com with .com?single. I just added varAppend just in case you want to make it easier to modify the code in the future with different kinds of url variables.

One other note: The .replace works by adding to the href since href returns a string containing the full url address information.

Error CS2001: Source file '.cs' could not be found

In my case, I add file as Link from another project and then rename file in source project that cause problem in destination project. I delete linked file in destination and add again with new name.

Get the current year in JavaScript

for current year we can use getFullYear() from Date class however there are many function which you can use as per the requirements, some functions are as,

_x000D_
_x000D_
var now = new Date()_x000D_
console.log("Current Time is: " + now);_x000D_
_x000D_
// getFullYear function will give current year _x000D_
var currentYear = now.getFullYear()_x000D_
console.log("Current year is: " + currentYear);_x000D_
_x000D_
// getYear will give you the years after 1990 i.e currentYear-1990_x000D_
var year = now.getYear()_x000D_
console.log("Current year is: " + year);_x000D_
_x000D_
// getMonth gives the month value but months starts from 0_x000D_
// add 1 to get actual month value _x000D_
var month = now.getMonth() + 1_x000D_
console.log("Current month is: " + month);_x000D_
_x000D_
// getDate gives the date value_x000D_
var day = now.getDate()_x000D_
console.log("Today's day is: " + day);
_x000D_
_x000D_
_x000D_

How do I make a matrix from a list of vectors in R?

One option is to use do.call():

 > do.call(rbind, a)
      [,1] [,2] [,3] [,4] [,5] [,6]
 [1,]    1    1    2    3    4    5
 [2,]    2    1    2    3    4    5
 [3,]    3    1    2    3    4    5
 [4,]    4    1    2    3    4    5
 [5,]    5    1    2    3    4    5
 [6,]    6    1    2    3    4    5
 [7,]    7    1    2    3    4    5
 [8,]    8    1    2    3    4    5
 [9,]    9    1    2    3    4    5
[10,]   10    1    2    3    4    5

Removing all script tags from html with JS Regular Expression

jQuery uses a regex to remove script tags in some cases and I'm pretty sure its devs had a damn good reason to do so. Probably some browser does execute scripts when inserting them using innerHTML.

Here's the regex:

/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi

And before people start crying "but regexes for HTML are evil": Yes, they are - but for script tags they are safe because of the special behaviour - a <script> section may not contain </script> at all unless it should end at this position. So matching it with a regex is easily possible. However, from a quick look the regex above does not account for trailing whitespace inside the closing tag so you'd have to test if </script    etc. will still work.

Installing Google Protocol Buffers on mac

brew install --devel protobuf

If it tells you "protobuf-2.6.1 already installed": 1. brew uninstall --devel protobuf 2. brew link libtool 3. brew install --devel protobuf

PHP Warning: Division by zero

A lot of the answers here do not work for (string)"0.00".

Try this:

if (isset($_POST['num1']) && (float)$_POST['num1'] != 0) {
  ...
}

Or even more strict:

if (isset($_POST['num1']) && is_numeric($_POST['num1']) && (float)$_POST['num1'] != 0) {
  ...
}

ExecuteNonQuery: Connection property has not been initialized.

just try this..

you need to open the connection using connection.open() on the SqlCommand.Connection object before executing ExecuteNonQuery()

How to set time to 24 hour format in Calendar

tl;dr

LocalTime.parse( "10:30" )  // Parsed as 24-hour time.

java.time

Avoid the troublesome old date-time classes such as Date and Calendar that are now supplanted by the java.time classes.

LocalTime

The java.time classes provide a way to represent the time-of-day without a date and without a time zone: LocalTime

LocalTime lt = LocalTime.of( 10 , 30 );  // 10:30 AM.
LocalTime lt = LocalTime.of( 22 , 30 );  // 22:30 is 10:30 PM.

ISO 8601

The java.time classes use standard ISO 8601 formats by default when generating and parsing strings. These formats use 24-hour time.

String output = lt.toString();

LocalTime.of( 10 , 30 ).toString() : 10:30

LocalTime.of( 22 , 30 ).toString() : 22:30

So parsing 10:30 will be interpreted as 10:30 AM.

LocalTime lt = LocalTime.parse( "10:30" );  // 10:30 AM.

DateTimeFormatter

If you need to generate or parse strings in 12-hour click format with AM/PM, use the DateTimeFormatter class. Tip: make a habit of specifying a Locale.

ASP.NET MVC Razor pass model to layout

There is another way to archive it.

  1. Just implement BaseController class for all controllers.

  2. In the BaseController class create a method that returns a Model class like for instance.

public MenuPageModel GetTopMenu() 
{    

var m = new MenuPageModel();    
// populate your model here    
return m; 

}
  1. And in the Layout page you can call that method GetTopMenu()
@using GJob.Controllers

<header class="header-wrapper border-bottom border-secondary">
  <div class="sticky-header" id="appTopMenu">
    @{
       var menuPageModel = ((BaseController)this.ViewContext.Controller).GetTopMenu();
     }
     @Html.Partial("_TopMainMenu", menuPageModel)
  </div>
</header>

PHP error: "The zip extension and unzip command are both missing, skipping."

The shortest command to fix it on Debian and Ubuntu (dependencies will be installed automatically):

sudo apt install php-zip

How to configure XAMPP to send mail from localhost?

You have to configure SMTP on your server. You can use G Suite SMTP by Google for free:

<?php

$mail = new PHPMailer(true);

// Send mail using Gmail
if($send_using_gmail){
    $mail->IsSMTP(); // telling the class to use SMTP
    $mail->SMTPAuth = true; // enable SMTP authentication
    $mail->SMTPSecure = "ssl"; // sets the prefix to the servier
    $mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
    $mail->Port = 465; // set the SMTP port for the GMAIL server
    $mail->Username = "[email protected]"; // GMAIL username
    $mail->Password = "your-gmail-password"; // GMAIL password
}

// Typical mail data
$mail->AddAddress($email, $name);
$mail->SetFrom($email_from, $name_from);
$mail->Subject = "My Subject";
$mail->Body = "Mail contents";

try{
    $mail->Send();
    echo "Success!";
} catch(Exception $e){
    // Something went bad
    echo "Fail :(";
}

?>

Read more about PHPMailer here.

How to make canvas responsive

There's a better way to do this in modern browsers using the vh and vw units.

vh is the viewport height.

So you can try something like this:

<style>
canvas {
  border: solid 2px purple;
  background-color: green;
  width: 100%;
  height: 80vh;
}
</style>

This will distort the aspect ration.

You can keep the aspect ratio by using the same unit for each. Here's an example with a 2:1 aspect ratio:

<style>
canvas {
  width: 40vh;
  height: 80vh;
}
</style>

Dynamic loading of images in WPF

You could try attaching handlers to various events of BitmapImage:

They might tell you a little about what's going on, as far as the image is concerned.

How to set Internet options for Android emulator?

It was setting the DNS that did the trick for me. If you are using the Eclipse or Netbeans plugins, you can set it through Default Emulator options, or Emulator Options respectively. You can also use set it from the command line if you start your emulator from CLI. In all cases, the option is "-dns-server x.x.x.x,x.x.x.x" without the quotes. There is no option in the ADB gui to permanently associate the option with your virtual device.

Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?

You most likely ran out of battery and your postgresql server didn't shutdown correctly.

The easiest workaround is to download the official postgresql app and launch it: it will force the server to start (http://postgresapp.com/)

Fragments onResume from back stack

onResume() for the fragment works fine...

public class listBook extends Fragment {

    private String listbook_last_subtitle;
...

    @Override
       public void onCreate(Bundle savedInstanceState) {

        String thisFragSubtitle = (String) getActivity().getActionBar().getSubtitle();
        listbook_last_subtitle = thisFragSubtitle;
       }
...

    @Override
        public void onResume(){
            super.onResume();
            getActivity().getActionBar().setSubtitle(listbook_last_subtitle);
        }
...

How to select distinct query using symfony2 doctrine query builder?

If you use the "select()" statement, you can do this:

$category = $catrep->createQueryBuilder('cc')
    ->select('DISTINCT cc.contenttype')
    ->Where('cc.contenttype = :type')
    ->setParameter('type', 'blogarticle')
    ->getQuery();

$categories = $category->getResult();

MySql Query Replace NULL with Empty String in Select

select IFNULL(`prereq`,'') as ColumnName FROM test

this query is selecting "prereq" values and if any one of the values are null it show an empty string as you like So, it shows all values but the NULL ones are showns in blank

what do these symbolic strings mean: %02d %01d?

The answer from Alexander refers to complete docs...

Your simple example from the question simply prints out these values with 2 digits - appending leading 0 if necessary.

Merge, update, and pull Git branches without using checkouts

Another way to effectively do this is:

git fetch
git branch -d branchB
git branch -t branchB origin/branchB

Because it's a lower case -d, it will only delete it if the data will still exist somewhere. It's similar to @kkoehne's answer except it doesn't force. Because of the -t it will set up the remote again.

I had a slightly different need than OP, which was to create a new feature branch off develop (or master), after merging a pull request. That can be accomplished in a one-liner without force, but it doesn't update the local develop branch. It's just a matter of checking out a new branch and having it be based off origin/develop:

git checkout -b new-feature origin/develop

How can I add (simple) tracing in C#?

I followed around five different answers as well as all the blog posts in the previous answers and still had problems. I was trying to add a listener to some existing code that was tracing using the TraceSource.TraceEvent(TraceEventType, Int32, String) method where the TraceSource object was initialised with a string making it a 'named source'.

For me the issue was not creating a valid combination of source and switch elements to target this source. Here is an example that will log to a file called tracelog.txt. For the following code:

TraceSource source = new TraceSource("sourceName");
source.TraceEvent(TraceEventType.Verbose, 1, "Trace message");

I successfully managed to log with the following diagnostics configuration:

<system.diagnostics>
    <sources>
        <source name="sourceName" switchName="switchName">
            <listeners>
                <add
                    name="textWriterTraceListener"
                    type="System.Diagnostics.TextWriterTraceListener"
                    initializeData="tracelog.txt" />
            </listeners>
        </source>
    </sources>

    <switches>
        <add name="switchName" value="Verbose" />
    </switches>
</system.diagnostics>

How to include js file in another js file?

I disagree with the document.write technique (see suggestion of Vahan Margaryan). I like document.getElementsByTagName('head')[0].appendChild(...) (see suggestion of Matt Ball), but there is one important issue: the script execution order.

Recently, I have spent a lot of time reproducing one similar issue, and even the well-known jQuery plugin uses the same technique (see src here) to load the files, but others have also reported the issue. Imagine you have JavaScript library which consists of many scripts, and one loader.js loads all the parts. Some parts are dependent on one another. Imagine you include another main.js script per <script> which uses the objects from loader.js immediately after the loader.js. The issue was that sometimes main.js is executed before all the scripts are loaded by loader.js. The usage of $(document).ready(function () {/*code here*/}); inside of main.js script does not help. The usage of cascading onload event handler in the loader.js will make the script loading sequential instead of parallel, and will make it difficult to use main.js script, which should just be an include somewhere after loader.js.

By reproducing the issue in my environment, I can see that **the order of execution of the scripts in Internet Explorer 8 can differ in the inclusion of the JavaScript*. It is a very difficult issue if you need include scripts that are dependent on one another. The issue is described in Loading Javascript files in parallel, and the suggested workaround is to use document.writeln:

document.writeln("<script type='text/javascript' src='Script1.js'></script>");
document.writeln("<script type='text/javascript' src='Script2.js'></script>");

So in the case of "the scripts are downloaded in parallel but executed in the order they're written to the page", after changing from document.getElementsByTagName('head')[0].appendChild(...) technique to document.writeln, I had not seen the issue anymore.

So I recommend that you use document.writeln.

UPDATED: If somebody is interested, they can try to load (and reload) the page in Internet Explorer (the page uses the document.getElementsByTagName('head')[0].appendChild(...) technique), and then compare with the fixed version used document.writeln. (The code of the page is relatively dirty and is not from me, but it can be used to reproduce the issue).

JavaScript: Is there a way to get Chrome to break on all errors?

I got trouble to get it so I post pictures showing different options:

Chrome 75.0.3770.142 [29 July 2018]

Very very similar UI since at least Chrome 38.0.2125.111 [11 December 2014]

In tab Sources :

enter image description here

When button is activated, you can Pause On Caught Exceptions with the checkbox below: enter image description here


Previous versions

Chrome 32.0.1700.102 [03 feb 2014]

enter image description here

enter image description here enter image description here enter image description here

Chrome 27.0.1453.93 Stable

Debug options

How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

import string 

sentence = "I     am having  a   very  nice  23!@$      day. "
# Remove all punctuations
sentence = sentence.translate(str.maketrans('', '', string.punctuation))
# Remove all numbers"
sentence = ''.join([word for word in sentence if not word.isdigit()])
count = 0;
for index in range(len(sentence)-1) :
    if sentence[index+1].isspace() and not sentence[index].isspace():
        count += 1 
print(count)

UICollectionView - dynamic cell height?

Seems like it's quite a popular question, so I will try to make my humble contribution.


The code below is Swift 4 solution for no-storyboard setup. It utilizes some approaches from previous answers, therefore it prevents Auto Layout warning caused on device rotation.

I am sorry if code samples are a bit long. I want to provide an "easy-to-use" solution fully hosted by StackOverflow. If you have any suggestions to the post - please, share the idea and I will update it accordingly.

The setup:

Two classes: ViewController.swift and MultilineLabelCell.swift - Cell containing single UILabel.

MultilineLabelCell.swift

import UIKit

class MultilineLabelCell: UICollectionViewCell {
    static let reuseId = "MultilineLabelCellReuseId"

    private let label: UILabel = UILabel(frame: .zero)

    override init(frame: CGRect) {
        super.init(frame: frame)

        layer.borderColor = UIColor.red.cgColor
        layer.borderWidth = 1.0

        label.numberOfLines = 0
        label.lineBreakMode = .byWordWrapping

        let labelInset = UIEdgeInsets(top: 10, left: 10, bottom: -10, right: -10)
        contentView.addSubview(label)
        label.translatesAutoresizingMaskIntoConstraints = false
        label.topAnchor.constraint(equalTo: contentView.layoutMarginsGuide.topAnchor, constant: labelInset.top).isActive = true
        label.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor, constant: labelInset.left).isActive = true
        label.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor, constant: labelInset.right).isActive = true
        label.bottomAnchor.constraint(equalTo: contentView.layoutMarginsGuide.bottomAnchor, constant: labelInset.bottom).isActive = true

        label.layer.borderColor = UIColor.black.cgColor
        label.layer.borderWidth = 1.0
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("Storyboards are quicker, easier, more seductive. Not stronger then Code.")
    }

    func configure(text: String?) {
        label.text = text
    }

    override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
        label.preferredMaxLayoutWidth = layoutAttributes.size.width - contentView.layoutMargins.left - contentView.layoutMargins.left
        layoutAttributes.bounds.size.height = systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
        return layoutAttributes
    }
}

ViewController.swift

import UIKit

let samuelQuotes = [
    "Samuel says", 
    "Add different length strings here for better testing"
]

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    private(set) var collectionView: UICollectionView

    // Initializers
    init() {
        // Create new `UICollectionView` and set `UICollectionViewFlowLayout` as its layout
        collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        // Create new `UICollectionView` and set `UICollectionViewFlowLayout` as its layout
        collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
        super.init(coder: aDecoder)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        title = "Dynamic size sample"

        // Register Cells
        collectionView.register(MultilineLabelCell.self, forCellWithReuseIdentifier: MultilineLabelCell.reuseId)

        // Add `coolectionView` to display hierarchy and setup its appearance
        view.addSubview(collectionView)
        collectionView.backgroundColor = .white
        collectionView.contentInsetAdjustmentBehavior = .always
        collectionView.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)

        // Setup Autolayout constraints
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
        collectionView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
        collectionView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
        collectionView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true

        // Setup `dataSource` and `delegate`
        collectionView.dataSource = self
        collectionView.delegate = self

        (collectionView.collectionViewLayout as! UICollectionViewFlowLayout).estimatedItemSize = UICollectionViewFlowLayout.automaticSize
        (collectionView.collectionViewLayout as! UICollectionViewFlowLayout).sectionInsetReference = .fromLayoutMargins
    }

    // MARK: - UICollectionViewDataSource -
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MultilineLabelCell.reuseId, for: indexPath) as! MultilineLabelCell
        cell.configure(text: samuelQuotes[indexPath.row])
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return samuelQuotes.count
    }

    // MARK: - UICollectionViewDelegateFlowLayout -
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let sectionInset = (collectionViewLayout as! UICollectionViewFlowLayout).sectionInset
        let referenceHeight: CGFloat = 100 // Approximate height of your cell
        let referenceWidth = collectionView.safeAreaLayoutGuide.layoutFrame.width
            - sectionInset.left
            - sectionInset.right
            - collectionView.contentInset.left
            - collectionView.contentInset.right
        return CGSize(width: referenceWidth, height: referenceHeight)
    }
}

To run this sample create new Xcode project, create corresponding files and replace AppDelegate contents with the following code:

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var navigationController: UINavigationController?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow(frame: UIScreen.main.bounds)

        if let window = window {
            let vc = ViewController()
            navigationController = UINavigationController(rootViewController: vc)
            window.rootViewController = navigationController
            window.makeKeyAndVisible()
        }

        return true
    }
}

Can't resolve module (not found) in React.js

I had a similar issue.

Cause:

import HomeComponent from "components/HomeComponent";

Solution:

import HomeComponent from "./components/HomeComponent";

NOTE: ./ was before components. You can read @Zac Kwan's post above on how to use import

Calling C/C++ from Python?

pybind11 minimal runnable example

pybind11 was previously mentioned at https://stackoverflow.com/a/38542539/895245 but I would like to give here a concrete usage example and some further discussion about implementation.

All and all, I highly recommend pybind11 because it is really easy to use: you just include a header and then pybind11 uses template magic to inspect the C++ class you want to expose to Python and does that transparently.

The downside of this template magic is that it slows down compilation immediately adding a few seconds to any file that uses pybind11, see for example the investigation done on this issue. PyTorch agrees. A proposal to remediate this problem has been made at: https://github.com/pybind/pybind11/pull/2445

Here is a minimal runnable example to give you a feel of how awesome pybind11 is:

class_test.cpp

#include <string>

#include <pybind11/pybind11.h>

struct ClassTest {
    ClassTest(const std::string &name) : name(name) { }
    void setName(const std::string &name_) { name = name_; }
    const std::string &getName() const { return name; }
    std::string name;
};

namespace py = pybind11;

PYBIND11_PLUGIN(class_test) {
    py::module m("my_module", "pybind11 example plugin");
    py::class_<ClassTest>(m, "ClassTest")
        .def(py::init<const std::string &>())
        .def("setName", &ClassTest::setName)
        .def("getName", &ClassTest::getName)
        .def_readwrite("name", &ClassTest::name);
    return m.ptr();
}

class_test_main.py

#!/usr/bin/env python3

import class_test

my_class_test = class_test.ClassTest("abc");
print(my_class_test.getName())
my_class_test.setName("012")
print(my_class_test.getName())
assert(my_class_test.getName() == my_class_test.name)

Compile and run:

#!/usr/bin/env bash
set -eux
g++ `python3-config --cflags` -shared -std=c++11 -fPIC class_test.cpp \
  -o class_test`python3-config --extension-suffix` `python3-config --libs`
./class_test_main.py

This example shows how pybind11 allows you to effortlessly expose the ClassTest C++ class to Python! Compilation produces a file named class_test.cpython-36m-x86_64-linux-gnu.so which class_test_main.py automatically picks up as the definition point for the class_test natively defined module.

Perhaps the realization of how awesome this is only sinks in if you try to do the same thing by hand with the native Python API, see for example this example of doing that, which has about 10x more code: https://github.com/cirosantilli/python-cheat/blob/4f676f62e87810582ad53b2fb426b74eae52aad5/py_from_c/pure.c On that example you can see how the C code has to painfully and explicitly define the Python class bit by bit with all the information it contains (members, methods, further metadata...). See also:

pybind11 claims to be similar to Boost.Python which was mentioned at https://stackoverflow.com/a/145436/895245 but more minimal because it is freed from the bloat of being inside the Boost project:

pybind11 is a lightweight header-only library that exposes C++ types in Python and vice versa, mainly to create Python bindings of existing C++ code. Its goals and syntax are similar to the excellent Boost.Python library by David Abrahams: to minimize boilerplate code in traditional extension modules by inferring type information using compile-time introspection.

The main issue with Boost.Python—and the reason for creating such a similar project—is Boost. Boost is an enormously large and complex suite of utility libraries that works with almost every C++ compiler in existence. This compatibility has its cost: arcane template tricks and workarounds are necessary to support the oldest and buggiest of compiler specimens. Now that C++11-compatible compilers are widely available, this heavy machinery has become an excessively large and unnecessary dependency.

Think of this library as a tiny self-contained version of Boost.Python with everything stripped away that isn't relevant for binding generation. Without comments, the core header files only require ~4K lines of code and depend on Python (2.7 or 3.x, or PyPy2.7 >= 5.7) and the C++ standard library. This compact implementation was possible thanks to some of the new C++11 language features (specifically: tuples, lambda functions and variadic templates). Since its creation, this library has grown beyond Boost.Python in many ways, leading to dramatically simpler binding code in many common situations.

pybind11 is also the only non-native alternative hightlighted by the current Microsoft Python C binding documentation at: https://docs.microsoft.com/en-us/visualstudio/python/working-with-c-cpp-python-in-visual-studio?view=vs-2019 (archive).

Tested on Ubuntu 18.04, pybind11 2.0.1, Python 3.6.8, GCC 7.4.0.

Remove HTML Tags in Javascript with Regex

<html>
<head>
<script type="text/javascript">
function striptag(){
var html = /(<([^>]+)>)/gi;
for (i=0; i < arguments.length; i++)
arguments[i].value=arguments[i].value.replace(html, "")
}
</script>
</head> 
<body>
       <form name="myform">
<textarea class="comment" title="comment" name=comment rows=4 cols=40></textarea><br>
<input type="button" value="Remove HTML Tags" onClick="striptag(this.form.comment)">
</form>
</body>
</html>

what is .subscribe in angular?

subscribe() -Invokes an execution of an Observable and registers Observer handlers for notifications it will emit. -Observable- representation of any set of values over any amount of time.

How a thread should close itself in Java?

If the run method ends, the thread will end.

If you use a loop, a proper way is like following:

// In your imlemented Runnable class:
private volatile boolean running = true;

public void run()
{
   while (running)
   {
      ...
   }
}


public void stopRunning()
{
    running = false;
}

Of course returning is the best way.

How to count total lines changed by a specific author in a Git repository?

Save your logs into file using:

git log --author="<authorname>" --oneline --shortstat > logs.txt

For Python lovers:

with open(r".\logs.txt", "r", encoding="utf8") as f:
    files = insertions = deletions = 0
    for line in f:
        if ' changed' in line:
            line = line.strip()
            spl = line.split(', ')
            if len(spl) > 0:
                files += int(spl[0].split(' ')[0])
            if len(spl) > 1:
                insertions += int(spl[1].split(' ')[0])
            if len(spl) > 2:
                deletions += int(spl[2].split(' ')[0])

    print(str(files).ljust(10) + ' files changed')
    print(str(insertions).ljust(10) + ' insertions')
    print(str(deletions).ljust(10) + ' deletions')

Your outputs would be like:

225        files changed
6751       insertions
1379       deletions

Perl: Use s/ (replace) and return new string

print "bla: ", $_, "\n" if ($_ = $myvar) =~ s/a/b/g or 1;

Spring Boot access static resources missing scr/main/resources

I use spring boot, so i can simple use:

File file = ResourceUtils.getFile("classpath:myfile.xml");

How to find if an array contains a string

Using the code from my answer to a very similar question:

Sub DoSomething()
Dim Mainfram(4) As String
Dim cell As Excel.Range

Mainfram(0) = "apple"
Mainfram(1) = "pear"
Mainfram(2) = "orange"
Mainfram(3) = "fruit"

For Each cell In Selection
  If IsInArray(cell.Value, MainFram) Then
    Row(cell.Row).Style = "Accent1"
  End If
Next cell

End Sub

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
  IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function

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

Your selector is missing a . and though you say you want to change the border-color - you're adding and removing a class that sets the background-color

How to show math equations in general github's markdown(not github's blog)

There is good solution for your problem - use TeXify github plugin (mentioned by Tom Hale answer - but I developed his answer in given link below) - more details about this github plugin and explanation why this is good approach you can find in that answer.

Reset all the items in a form

I recently had to do this for Textboxes and Checkboxes but using JavaScript ...

How to reset textbox and checkbox controls in an ASP.net document

Here is the code ...

<script src="http://code.jquery.com/jquery-1.7.1.js" type="text/javascript"></script>

<script type="text/javascript">
      function ResetForm() {
          //get the all the Input type elements in the document
          var AllInputsElements = document.getElementsByTagName('input');
          var TotalInputs = AllInputsElements.length;

          //we have to find the checkboxes and uncheck them
          //note: <asp:checkbox renders to <input type="checkbox" after compiling, which is why we use 'input' above
          for(var i=0;i< TotalInputs ; i++ )
          {
            if(AllInputsElements[i].type =='checkbox')
            {
                AllInputsElements[i].checked = false;
            }
          }

          //reset all textbox controls
          $('input[type=text], textarea').val('');

          Page_ClientValidateReset();
          return false;
      }

      //This function resets all the validation controls so that they don't "fire" up
      //during a post-back.
      function Page_ClientValidateReset() {
          if (typeof (Page_Validators) != "undefined") {
              for (var i = 0; i < Page_Validators.length; i++) {
                  var validator = Page_Validators[i];
                  validator.isvalid = true;
                  ValidatorUpdateDisplay(validator);
              }
          }
      }
</script>

And call it with a button or any other method ...

<asp:button id="btnRESET" runat="server" onclientclick="return ResetForm();" text="RESET" width="100px"></asp:button>

If you don't use ValidationControls on your website, just remove all the code refering to it above and the call Page_ClientValidateReset();

I am sure you can expand it for any other control using the DOM. And since there is no post to the server, it's faster and no "flashing" either.

Screenshot sizes for publishing android app on Google Play

  • We require 2 screenshots.
  • Use: Displayed on the details page for your application in Google Play.
  • You may upload up to 8 screenshots each for phone, 7” tablet and 10” tablet.
  • Specs: Minimum dimension: 320 pixels. Maximum dimension: 3840 pixels. The maximum dimension of your screenshot cannot be more than twice as long as the minimum dimension. You may use 24 bit PNG or JPEG image (no alpha). Full bleed, no border in art.
  • We recommend adding screenshots of your app running on a 7" and 10" tablet. Go to ‘Store listing’ page in your Developer Console to add tablet apps screenshots.

https://support.google.com/googleplay/android-developer/answer/1078870?hl=en&ref_topic=2897459

ASP.NET MVC Yes/No Radio Buttons with Strongly Bound Model MVC

or MVC 2.0:

<%= Html.RadioButtonFor(model => model.blah, true) %> Yes
<%= Html.RadioButtonFor(model => model.blah, false) %> No

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

Word of warning: if you put config files in your WEB-INF/classes folder, and your IDE, say Eclipse, does a clean/rebuild, it will nuke your conf files unless they were in the Java source directory. BalusC's great answer alludes to that in option 1 but I wanted to add emphasis.

I learned the hard way that if you "copy" a web project in Eclipse, it does a clean/rebuild from any source folders. In my case I had added a "linked source dir" from our POJO java library, it would compile to the WEB-INF/classes folder. Doing a clean/rebuild in that project (not the web app project) caused the same problem.

I thought about putting my confs in the POJO src folder, but these confs are all for 3rd party libs (like Quartz or URLRewrite) that are in the WEB-INF/lib folder, so that didn't make sense. I plan to test putting it in the web projects "src" folder when i get around to it, but that folder is currently empty and having conf files in it seems inelegant.

So I vote for putting conf files in WEB-INF/commonConfFolder/filename.properties, next to the classes folder, which is Balus option 2.

How to do a simple file search in cmd

Problem with DIR is that it will return wrong answers. If you are looking for DOC in a folder by using DIR *.DOC it will also give you the DOCX. Searching for *.HTM will also give the HTML and so on...

Why doesn't file_get_contents work?

Wrap your $adr in urlencode(). I was having this problem and this solved it for me.

Stop Visual Studio from launching a new browser window when starting debug?

When you first open a web/app project, do a Ctrl-F5, which is the shortcut for starting the application without debugging. Then when you subsequently hit F5 and launch the debugger, it will use that instance of IE. Then stop and start the debugging in Visual Studio instead of closing IE.

It works on my machines. I'm using the built in dev web server. Don't know if that makes a difference.

Firefox will also stay open so you can debug in either or both at the same time.

Reading value from console, interactively

I've used another API for this purpose..

var readline = require('readline');
var rl = readline.createInterface(process.stdin, process.stdout);
rl.setPrompt('guess> ');
rl.prompt();
rl.on('line', function(line) {
    if (line === "right") rl.close();
    rl.prompt();
}).on('close',function(){
    process.exit(0);
});

This allows to prompt in loop until the answer is right. Also it gives nice little console.You can find the details @ http://nodejs.org/api/readline.html#readline_example_tiny_cli

How to fast get Hardware-ID in C#?

Here is a DLL that shows:
* Hard drive ID (unique hardware serial number written in drive's IDE electronic chip)
* Partition ID (volume serial number)
* CPU ID (unique hardware ID)
* CPU vendor
* CPU running speed
* CPU theoretic speed
* Memory Load ( Total memory used in percentage (%) )
* Total Physical ( Total physical memory in bytes )
* Avail Physical ( Physical memory left in bytes )
* Total PageFile ( Total page file in bytes )
* Available PageFile( Page file left in bytes )
* Total Virtual( Total virtual memory in bytes )
* Available Virtual ( Virtual memory left in bytes )
* Bios unique identification numberBiosDate
* Bios unique identification numberBiosVersion
* Bios unique identification numberBiosProductID
* Bios unique identification numberBiosVideo

(text grabbed from original web site)
It works with C#.

How to convert string to datetime format in pandas python?

Approach: 1

Given original string format: 2019/03/04 00:08:48

you can use

updated_df = df['timestamp'].astype('datetime64[ns]')

The result will be in this datetime format: 2019-03-04 00:08:48

Approach: 2

updated_df = df.astype({'timestamp':'datetime64[ns]'})

List of remotes for a Git repository?

You can get a list of any configured remote URLs with the command git remote -v.

This will give you something like the following:

base    /home/***/htdocs/base (fetch)
base    /home/***/htdocs/base (push)
origin  [email protected]:*** (fetch)
origin  [email protected]:*** (push)

How to permanently export a variable in Linux?

A particular example: I have Java 7 and Java 6 installed, I need to run some builds with 6, others with 7. Therefore I need to dynamically alter JAVA_HOME so that maven picks up what I want for each build. I did the following:

  • created j6.sh script which simply does export JAVA_HOME=... path to j6 install...
  • then, as suggested by one of the comments above, whenever I need J6 for a build, I run source j6.sh in that respective command terminal. By default, my JAVA_HOME is set to J7.

Hope this helps.

Questions every good PHP Developer should be able to answer

"Why aren't you using something else?"

Sorry, someone had to say it :)

Bootstrap carousel multiple frames at once

Updated 2019...

Bootstrap 4

The carousel has changed in 4.x, and the multi-slide animation transitions can be overridden like this...

.carousel-inner .carousel-item-right.active,
.carousel-inner .carousel-item-next {
  transform: translateX(33.33%);
}

.carousel-inner .carousel-item-left.active, 
.carousel-inner .carousel-item-prev {
  transform: translateX(-33.33%)
}

.carousel-inner .carousel-item-right,
.carousel-inner .carousel-item-left{ 
  transform: translateX(0);
}

Bootstrap 4 Alpha.6 Demo
Bootstrap 4.0.0 (show 4, advance 1 at a time)
Bootstrap 4.1.0 (show 3, advance 1 at a time)
Bootstrap 4.1.0 (advance all 4 at once)
Bootstrap 4.3.1 responsive (show multiple, advance 1)new
Bootstrap 4.3.1 carousel with cardsnew


Another option is a responsive carousel that only shows and advances 1 slide on smaller screens, but shows multiple slides are larger screens. Instead of cloning the slides like the previous example, this one adjusts the CSS and use jQuery only to move the extra slides to allow for continuous cycling (wrap around):

Please don't just copy-and-paste this code. First, understand how it works.

Bootstrap 4 Responsive (show 3, 1 slide on mobile)

@media (min-width: 768px) {

    /* show 3 items */
    .carousel-inner .active,
    .carousel-inner .active + .carousel-item,
    .carousel-inner .active + .carousel-item + .carousel-item {
        display: block;
    }

    .carousel-inner .carousel-item.active:not(.carousel-item-right):not(.carousel-item-left),
    .carousel-inner .carousel-item.active:not(.carousel-item-right):not(.carousel-item-left) + .carousel-item,
    .carousel-inner .carousel-item.active:not(.carousel-item-right):not(.carousel-item-left) + .carousel-item + .carousel-item {
        transition: none;
    }

    .carousel-inner .carousel-item-next,
    .carousel-inner .carousel-item-prev {
      position: relative;
      transform: translate3d(0, 0, 0);
    }

    .carousel-inner .active.carousel-item + .carousel-item + .carousel-item + .carousel-item {
        position: absolute;
        top: 0;
        right: -33.3333%;
        z-index: -1;
        display: block;
        visibility: visible;
    }

    /* left or forward direction */
    .active.carousel-item-left + .carousel-item-next.carousel-item-left,
    .carousel-item-next.carousel-item-left + .carousel-item,
    .carousel-item-next.carousel-item-left + .carousel-item + .carousel-item,
    .carousel-item-next.carousel-item-left + .carousel-item + .carousel-item + .carousel-item {
        position: relative;
        transform: translate3d(-100%, 0, 0);
        visibility: visible;
    }

    /* farthest right hidden item must be abso position for animations */
    .carousel-inner .carousel-item-prev.carousel-item-right {
        position: absolute;
        top: 0;
        left: 0;
        z-index: -1;
        display: block;
        visibility: visible;
    }

    /* right or prev direction */
    .active.carousel-item-right + .carousel-item-prev.carousel-item-right,
    .carousel-item-prev.carousel-item-right + .carousel-item,
    .carousel-item-prev.carousel-item-right + .carousel-item + .carousel-item,
    .carousel-item-prev.carousel-item-right + .carousel-item + .carousel-item + .carousel-item {
        position: relative;
        transform: translate3d(100%, 0, 0);
        visibility: visible;
        display: block;
        visibility: visible;
    }

}

<div class="container-fluid">
    <div id="carouselExample" class="carousel slide" data-ride="carousel" data-interval="9000">
        <div class="carousel-inner row w-100 mx-auto" role="listbox">
            <div class="carousel-item col-md-4 active">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400/000/fff?text=1" alt="slide 1">
            </div>
            <div class="carousel-item col-md-4">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=2" alt="slide 2">
            </div>
            <div class="carousel-item col-md-4">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=3" alt="slide 3">
            </div>
            <div class="carousel-item col-md-4">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=4" alt="slide 4">
            </div>
            <div class="carousel-item col-md-4">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=5" alt="slide 5">
            </div>
            <div class="carousel-item col-md-4">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=6" alt="slide 6">
            </div>
            <div class="carousel-item col-md-4">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=7" alt="slide 7">
            </div>
            <div class="carousel-item col-md-4">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=8" alt="slide 7">
            </div>
        </div>
        <a class="carousel-control-prev" href="#carouselExample" role="button" data-slide="prev">
            <i class="fa fa-chevron-left fa-lg text-muted"></i>
            <span class="sr-only">Previous</span>
        </a>
        <a class="carousel-control-next text-faded" href="#carouselExample" role="button" data-slide="next">
            <i class="fa fa-chevron-right fa-lg text-muted"></i>
            <span class="sr-only">Next</span>
        </a>
    </div>
</div>

Example - Bootstrap 4 Responsive (show 4, 1 slide on mobile)
Example - Bootstrap 4 Responsive (show 5, 1 slide on mobile)


Bootstrap 3

Here is a 3.x example on Bootply: http://bootply.com/89193

You need to put an entire row of images in the item active. Here is another version that doesn't stack the images at smaller screen widths: http://bootply.com/92514

EDIT Alternative approach to advance one slide at a time:

Use jQuery to clone the next items..

$('.carousel .item').each(function(){
  var next = $(this).next();
  if (!next.length) {
    next = $(this).siblings(':first');
  }
  next.children(':first-child').clone().appendTo($(this));

  if (next.next().length>0) {
    next.next().children(':first-child').clone().appendTo($(this));
  }
  else {
    $(this).siblings(':first').children(':first-child').clone().appendTo($(this));
  }
});

And then CSS to position accordingly...

Before 3.3.1

.carousel-inner .active.left { left: -33%; }
.carousel-inner .next        { left:  33%; }

After 3.3.1

.carousel-inner .item.left.active {
  transform: translateX(-33%);
}
.carousel-inner .item.right.active {
  transform: translateX(33%);
}

.carousel-inner .item.next {
  transform: translateX(33%)
}
.carousel-inner .item.prev {
  transform: translateX(-33%)
}

.carousel-inner .item.right,
.carousel-inner .item.left { 
  transform: translateX(0);
}

This will show 3 at time, but only slide one at a time:

Bootstrap 3.x Demo


Please don't copy-and-paste this code. First, understand how it works. This answer is here to help you learn.

Doubling up this modified bootstrap 4 carousel only functions half correctly (scroll loop stops working)
how to make 2 bootstrap sliders in single page without mixing their css and jquery?
Bootstrap 4 Multi Carousel show 4 images instead of 3

ALTER TABLE to add a composite primary key

ALTER TABLE table_name DROP PRIMARY KEY,ADD PRIMARY KEY (col_name1, col_name2);

javascript: get a function's variable's value within another function

you need a return statement in your first function.

function first(){
    var nameContent = document.getElementById('full_name').value;
    return nameContent;
}

and then in your second function can be:

function second(){
    alert(first());
}

Install Android App Bundle on device

No, if you are debugging an app without other users use the Build > Build APK(s) menu in Android Studio or execute it in your device/emulator them the debug release apk will install automatically. If you are debugging an app with others use Build > Generate Signed APK... menu. If you want to publish the beta version use the Google Play Store. Your APK(s) will be in app\build\outputs\apk\debug and app\release folders.

FontAwesome icons not showing. Why?

Just adding some more info to the above answers in regards with update on fontawesome,

If you use font awesome 5,

a. just copy-to-paste the below HTML,

<script defer src="https://use.fontawesome.com/releases/v5.0.8/js/all.js" integrity="sha384-SlE991lGASHoBfWbelyBPLsUlwY1GwNDJo3jSJO04KZ33K2bwfV9YBauFfnzvynJ" crossorigin="anonymous"></script>

Note: Better to include all your scripts within the <body> {YOUR_SCRIPT_HERE}</body> and just before (YOUR_CLOSING_BODY)

b. And for example,

<li><a href="https://stackoverflow.com/users/{USER}" class="social-icons"><i class="fab fa-stack-overflow"></i></a></li>

Spring MVC How take the parameter value of a GET HTTP Request in my controller method?

As explained in the documentation, by using an @RequestParam annotation:

public @ResponseBody String byParameter(@RequestParam("foo") String foo) {
    return "Mapped by path + method + presence of query parameter! (MappingController) - foo = "
           + foo;
}

javax.naming.NoInitialContextException - Java

We need to specify the INITIAL_CONTEXT_FACTORY, PROVIDER_URL, USERNAME, PASSWORD etc. of JNDI to create an InitialContext.

In a standalone application, you can specify that as below

Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, 
    "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://ldap.wiz.com:389");
env.put(Context.SECURITY_PRINCIPAL, "joeuser");
env.put(Context.SECURITY_CREDENTIALS, "joepassword");

Context ctx = new InitialContext(env);

But if you are running your code in a Java EE container, these values will be fetched by the container and used to create an InitialContext as below

System.getProperty(Context.PROVIDER_URL);

and

these values will be set while starting the container as JVM arguments. So if you are running the code in a container, the following will work

InitialContext ctx = new InitialContext();

The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path

Adding below dependency in pom.xml, worked for me.

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>

Space between two divs

You can try something like the following:

h1{
   margin-bottom:<x>px;
}
div{
   margin-bottom:<y>px;
}
div:last-of-type{
   margin-bottom:0;
}

or instead of the first h1 rule:

div:first-of-type{
   margin-top:<x>px;
}

or even better use the adjacent sibling selector. With the following selector, you could cover your case in one rule:

div + div{
   margin-bottom:<y>px;
}

Respectively, h1 + div would control the first div after your header, giving you additional styling options.

Combining paste() and expression() functions in plot labels

Use substitute instead.

labNames <- c('xLab','yLab')
plot(c(1:10),
     xlab=substitute(paste(nn, x^2), list(nn=labNames[1])),
     ylab=substitute(paste(nn, y^2), list(nn=labNames[2])))

Difference between / and /* in servlet mapping url pattern

Perhaps you need to know how urls are mapped too, since I suffered 404 for hours. There are two kinds of handlers handling requests. BeanNameUrlHandlerMapping and SimpleUrlHandlerMapping. When we defined a servlet-mapping, we are using SimpleUrlHandlerMapping. One thing we need to know is these two handlers share a common property called alwaysUseFullPath which defaults to false.

false here means Spring will not use the full path to mapp a url to a controller. What does it mean? It means when you define a servlet-mapping:

<servlet-mapping>
    <servlet-name>viewServlet</servlet-name>
    <url-pattern>/perfix/*</url-pattern>
</servlet-mapping>

the handler will actually use the * part to find the controller. For example, the following controller will face a 404 error when you request it using /perfix/api/feature/doSomething

@Controller()
@RequestMapping("/perfix/api/feature")
public class MyController {
    @RequestMapping(value = "/doSomething", method = RequestMethod.GET) 
    @ResponseBody
    public String doSomething(HttpServletRequest request) {
        ....
    }
}

It is a perfect match, right? But why 404. As mentioned before, default value of alwaysUseFullPath is false, which means in your request, only /api/feature/doSomething is used to find a corresponding Controller, but there is no Controller cares about that path. You need to either change your url to /perfix/perfix/api/feature/doSomething or remove perfix from MyController base @RequestingMapping.

HTML: Image won't display?

Just to expand niko's answer:

You can reference any image via its URL. No matter where it is, as long as it's accesible you can use it as the src. Example:

Relative location:

<img src="images/image.png">

The image is sought relative to the document's location. If your document is at http://example.com/site/document.html, then your images folder should be on the same directory where your document.html file is.

Absolute location:

<img src="/site/images/image.png">
<img src="http://example.com/site/images/image.png">

or

<img src="http://another-example.com/images/image.png">

In this case, your image will be sought from the document site's root, so, if your document.html is at http://example.com/site/document.html, the root would be at http://example.com/ (or it's respective directory on the server's filesystem, commonly www/). The first two examples are the same, since both point to the same host, Think of the first / as an alias for your server's root. In the second case, the image is located in another host, so you'd have to specify the complete URL of the image.

Regarding /, . and ..:

The / symbol will always return the root of a filesystem or site.

The single point ./ points to the same directory where you are.

And the double point ../ will point to the upper directory, or the one that contains the actual working directory.

So you can build relative routes using them.

Examples given the route http://example.com/dir/one/two/three/ and your calling document being inside three/:

"./pictures/image.png"

or just

"pictures/image.png"

Will try to find a directory named pictures inside http://example.com/dir/one/two/three/.

"../pictures/image.png"

Will try to find a directory named pictures inside http://example.com/dir/one/two/.

"/pictures/image.png"

Will try to find a directory named pictures directly at / or example.com (which are the same), on the same level as directory.

This project references NuGet package(s) that are missing on this computer

If you are using TFS

Remove the NuGet.exe and NuGet.targets files from the solution's .nuget folder. Make sure the files themselves are also removed from the solution workspace. Retain the NuGet.Config file to continue to bypass adding packages to source control.

Edit each project file (e.g., .csproj, .vbproj) in the solution and remove any references to the NuGet.targets file. Open the project file(s) in the editor of your choice and remove the following settings:

<RestorePackages>true</RestorePackages>  
...
<Import Project="$(SolutionDir)\.nuget\nuget.targets" />  
...
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">  
    <PropertyGroup>
        <ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
    </PropertyGroup>
    <Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>

If you are not using TFS

Remove the .nuget folder from your solution. Make sure the folder itself is also removed from the solution workspace.

Edit each project file (e.g., .csproj, .vbproj) in the solution and remove any references to the NuGet.targets file. Open the project file(s) in the editor of your choice and remove the following settings:

<RestorePackages>true</RestorePackages>  
...
<Import Project="$(SolutionDir)\.nuget\nuget.targets" />  
...
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">  
    <PropertyGroup>
        <ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
    </PropertyGroup>
    <Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>

Reference: Migrating MSBuild-Integrated solutions to use Automatic Package Restore

How to hide a <option> in a <select> menu with CSS?

You have to implement two methods for hiding. display: none works for FF, but not Chrome or IE. So the second method is wrapping the <option> in a <span> with display: none. FF won't do it (technically invalid HTML, per the spec) but Chrome and IE will and it will hide the option.

EDIT: Oh yeah, I already implemented this in jQuery:

jQuery.fn.toggleOption = function( show ) {
    jQuery( this ).toggle( show );
    if( show ) {
        if( jQuery( this ).parent( 'span.toggleOption' ).length )
            jQuery( this ).unwrap( );
    } else {
        if( jQuery( this ).parent( 'span.toggleOption' ).length == 0 )
            jQuery( this ).wrap( '<span class="toggleOption" style="display: none;" />' );
    }
};

EDIT 2: Here's how you would use this function:

jQuery(selector).toggleOption(true); // show option
jQuery(selector).toggleOption(false); // hide option

EDIT 3: Added extra check suggested by @user1521986

java SSL and cert keystore

First of all, there're two kinds of keystores.

Individual and General

The application will use the one indicated in the startup or the default of the system.

It will be a different folder if JRE or JDK is running, or if you check the personal or the "global" one.

They are encrypted too

In short, the path will be like:

$JAVA_HOME/lib/security/cacerts for the "general one", who has all the CA for the Authorities and is quite important.

recyclerview No adapter attached; skipping layout

It happens when you are not setting the adapter during the creation phase:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    ....
}

public void onResume() {
    super.onResume();
    mRecyclerView.setAdapter(mAdapter);
    ....
}

Just move setting the adapter into onCreate with an empty data and when you have the data call:

mAdapter.notifyDataSetChanged();

Is there a way to do repetitive tasks at intervals?

How about something like

package main

import (
    "fmt"
    "time"
)

func schedule(what func(), delay time.Duration) chan bool {
    stop := make(chan bool)

    go func() {
        for {
            what()
            select {
            case <-time.After(delay):
            case <-stop:
                return
            }
        }
    }()

    return stop
}

func main() {
    ping := func() { fmt.Println("#") }

    stop := schedule(ping, 5*time.Millisecond)
    time.Sleep(25 * time.Millisecond)
    stop <- true
    time.Sleep(25 * time.Millisecond)

    fmt.Println("Done")
}

Playground

Oracle PL/SQL : remove "space characters" from a string

I'd go for regexp_replace, although I'm not 100% sure this is usable in PL/SQL

my_value := regexp_replace(my_value, '[[:space:]]*',''); 

HTML tag <a> want to add both href and onclick working

Use ng-click in place of onclick. and its as simple as that:

<a href="www.mysite.com" ng-click="return theFunction();">Item</a>

<script type="text/javascript">
function theFunction () {
    // return true or false, depending on whether you want to allow 
    // the`href` property to follow through or not
 }
</script>

Why declare unicode by string in python?

That doesn't set the format of the string; it sets the format of the file. Even with that header, "hello" is a byte string, not a Unicode string. To make it Unicode, you're going to have to use u"hello" everywhere. The header is just a hint of what format to use when reading the .py file.

How to check if a div is visible state or not?

You can use (':hidden') method to find if your div is visible or not.. Also its a good practice to cache a element if you are using it multiple times in your code..

$(".subpanel a").click(function() 
     {
        var chatterNickname = $(this).text();
        var $chatPanel = $("#singlechatpanel-1");

        if(!$chatPanel.is(':hidden'))
        {
            alert("Room 1 is filled.");
            $chatPanel.show();
            $("#singlechatpanel-1 #chatter_nickname").html("Chatting with: " + chatterNickname);
        }
});

What are the use cases for selecting CHAR over VARCHAR in SQL?

It's the classic space versus performance tradeoff.

In MS SQL 2005, Varchar (or NVarchar for lanuagues requiring two bytes per character ie Chinese) are variable length. If you add to the row after it has been written to the hard disk it will locate the data in a non-contigious location to the original row and lead to fragmentation of your data files. This will affect performance.

So, if space is not an issue then Char are better for performance but if you want to keep the database size down then varchars are better.

Check if a string is a date value

Ok, this is an old question, but I found another solution while checking the solutions here. For me works to check if the function getTime() is present at the date object:

const checkDate = new Date(dateString);

if (typeof checkDate.getTime !== 'function') {
  return;
}

How to set UICollectionViewCell Width and Height programmatically

Absolutely simple way:

class YourCollection: UIViewController,
     UICollectionViewDelegate,
     UICollectionViewDataSource {

You must add "UICollectionViewDelegateFlowLayout" or, there is no autocomplete:

class YourCollection: UIViewController,
     UICollectionViewDelegate,
     UICollectionViewDataSource,
     UICollectionViewDelegateFlowLayout {

Type "sizeForItemAt...". You're done!

class YourCollection: UIViewController,
     UICollectionViewDelegate,
     UICollectionViewDataSource,
     UICollectionViewDelegateFlowLayout {
 
     func collectionView(_ collectionView: UICollectionView,
      layout collectionViewLayout: UICollectionViewLayout,
      sizeForItemAt indexPath: IndexPath) -> CGSize {
     
     return CGSize(width: 37, height: 63)
}

That's it.

Example, if you want "each cell fills the whole collection view":

     guard let b = view.superview?.bounds else { .. }
     return CGSize(width: b.width, height: b.height)

TypeError: worker() takes 0 positional arguments but 1 was given

Check if from method with name method_a() you call method with the same name method_a(with_params) causing recursion

MySQL, update multiple tables with one query

That's usually what stored procedures are for: to implement several SQL statements in a sequence. Using rollbacks, you can ensure that they are treated as one unit of work, ie either they are all executed or none of them are, to keep data consistent.

How to manually install an artifact in Maven 2?

You need to indicate the groupId, the artifactId and the version for your artifact:

mvn install:install-file \
  -DgroupId=javax.transaction \
  -DartifactId=jta \
  -Dpackaging=jar \
  -Dversion=1.0.1B \
  -Dfile=jta-1.0.1B.jar \
  -DgeneratePom=true

MySQL Data Source not appearing in Visual Studio

Tried everything but on Visual Studio 2015 Community edition I got it working when I installed MySQL for Visual Studio 1.2.4+ from http://dev.mysql.com/downloads/windows/visualstudio/ At time of writing I could download 1.2.6 which worked for me.

enter image description here

Release notes of 1.2.4 which adds support for VS2015 can be found at http://forums.mysql.com/read.php?3,633391

Windows cannot find 'http:/.127.0.0.1:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again

I got the same error and when I search here on Stack Overflow and out I've combined what I found and it works for me. Just follow this:

  1. Go to the icon of oracle right click on it choose : open file location.
  2. Choose the get started right click on it choose properties on the URL add what is between brackets to the end of the URL (:1:405838811476023). Or just copy this URL: http://127.0.0.1:8080/apex/f?p=4950:1:1486912860795003 and put it there instead of the old one
  3. Click on apply.
  4. Go back to the first step double clicks and it will work.

What is the difference between null and undefined in JavaScript?

In JavasSript there are 5 primitive data types String , Number , Boolean , null and undefined. I will try to explain with some simple example

lets say we have a simple function

 function test(a) {

     if(a == null){
        alert("a is null");
     } else {
        alert("The value of a is " + a);
     }
  }

also in above function if(a == null) is same as if(!a)

now when we call this function without passing the parameter a

   test(); it will alert "a is null";
   test(4); it will alert "The value of a is " + 4;

also

var a;
alert(typeof a); 

this will give undefined; we have declared a variable but we have not asigned any value to this variable; but if we write

var a = null;
alert(typeof a); will give alert as object

so null is an object. in a way we have assigned a value null to 'a'

Get an element by index in jQuery

$(...)[index]      // gives you the DOM element at index
$(...).get(index)  // gives you the DOM element at index
$(...).eq(index)   // gives you the jQuery object of element at index

DOM objects don't have css function, use the last...

$('ul li').eq(index).css({'background-color':'#343434'});

docs:

.get(index) Returns: Element

.eq(index) Returns: jQuery

How can I edit a .jar file?

This is a tool to open Java class file binaries, view their internal structure, modify portions of it if required and save the class file back. It also generates readable reports similar to the javap utility. Easy to use Java Swing GUI. The user interface tries to display as much detail as possible and tries to present a structure as close as the actual Java class file structure. At the same time ease of use and class file consistency while doing modifications is also stressed. For example, when a method is deleted, the associated constant pool entry will also be deleted if it is no longer referenced. In built verifier checks changes before saving the file. This tool has been used by people learning Java class file internals. This tool has also been used to do quick modifications in class files when the source code is not available." this is a quote from the website.

http://classeditor.sourceforge.net/

Setting HttpContext.Current.Session in a unit test

Milox solution is better than the accepted one IMHO but I had some problems with this implementation when handling urls with querystring.

I made some changes to make it work properly with any urls and to avoid Reflection.

public static HttpContext FakeHttpContext(string url)
{
    var uri = new Uri(url);
    var httpRequest = new HttpRequest(string.Empty, uri.ToString(),
                                        uri.Query.TrimStart('?'));
    var stringWriter = new StringWriter();
    var httpResponse = new HttpResponse(stringWriter);
    var httpContext = new HttpContext(httpRequest, httpResponse);

    var sessionContainer = new HttpSessionStateContainer("id",
                                    new SessionStateItemCollection(),
                                    new HttpStaticObjectsCollection(),
                                    10, true, HttpCookieMode.AutoDetect,
                                    SessionStateMode.InProc, false);

    SessionStateUtility.AddHttpSessionStateToContext(
                                         httpContext, sessionContainer);

    return httpContext;
}

Check file uploaded is in csv format

simple use "accept" and "required" in and avoiding so much typical and unwanted coding.

How to undo "git commit --amend" done instead of "git commit"

What you need to do is to create a new commit with the same details as the current HEAD commit, but with the parent as the previous version of HEAD. git reset --soft will move the branch pointer so that the next commit happens on top of a different commit from where the current branch head is now.

# Move the current head so that it's pointing at the old commit
# Leave the index intact for redoing the commit.
# HEAD@{1} gives you "the commit that HEAD pointed at before 
# it was moved to where it currently points at". Note that this is
# different from HEAD~1, which gives you "the commit that is the
# parent node of the commit that HEAD is currently pointing to."
git reset --soft HEAD@{1}

# commit the current tree using the commit details of the previous
# HEAD commit. (Note that HEAD@{1} is pointing somewhere different from the
# previous command. It's now pointing at the erroneously amended commit.)
git commit -C HEAD@{1}

Format numbers in django templates

Try adding the following line in settings.py:

USE_THOUSAND_SEPARATOR = True

This should work.

Refer to documentation.


update at 2018-04-16:

There is also a python way to do this thing:

>>> '{:,}'.format(1000000)
'1,000,000'

PIG how to count a number of rows in alias

Here is a version with optimization. All the solutions above would require pig to read and write full tuple when counting, this script below just write '1'-s

DEFINE row_count(inBag, name) RETURNS result {
    X = FOREACH $inBag generate 1;
    $result = FOREACH (GROUP X ALL PARALLEL 1) GENERATE '$name', COUNT(X);
};

The use it like

xxx = row_count(rows, 'rows_count');

How do you implement a re-try-catch?

Here is my solution similar to some others can wrap a function, but allows you to get the functions return value, if it suceeds.

    /**
     * Wraps a function with retry logic allowing exceptions to be caught and retires made.
     *
     * @param function the function to retry
     * @param maxRetries maximum number of retires before failing
     * @param delay time to wait between each retry
     * @param allowedExceptionTypes exception types where if caught a retry will be performed
     * @param <V> return type of the function
     * @return the value returned by the function if successful
     * @throws Exception Either an unexpected exception from the function or a {@link RuntimeException} if maxRetries is exceeded
     */
    @SafeVarargs
    public static <V> V runWithRetriesAndDelay(Callable<V> function, int maxRetries, Duration delay, Class<? extends Exception>... allowedExceptionTypes) throws Exception {
        final Set<Class<? extends Exception>> exceptions = new HashSet<>(Arrays.asList(allowedExceptionTypes));
        for(int i = 1; i <= maxRetries; i++) {
            try {
                return function.call();
            } catch (Exception e) {
                if(exceptions.contains(e.getClass())){
                    // An exception of an expected type
                    System.out.println("Attempt [" + i + "/" + maxRetries + "] Caught exception [" + e.getClass() + "]");
                    // Pause for the delay time
                    Thread.sleep(delay.toMillis());
                }else {
                    // An unexpected exception type
                    throw e;
                }
            }
        }
        throw new RuntimeException(maxRetries + " retries exceeded");
    }

Center Triangle at Bottom of Div

Check this:

http://jsfiddle.net/SxKr5/3/

.hero1
{
    width: 90%;
    height: 200px;
    margin: auto;
    background-color: #e15915;
}

.hero2
{
    width: 0px;
    height: 0px;
    border-style: solid;
    margin: auto;
    border-width: 90px 58px 0 58px;
    border-color: #e15915 transparent transparent transparent;
    line-height: 0px;
    _border-color: #e15915 #000000 #000000 #000000;
    _filter: progid:DXImageTransform.Microsoft.Chroma(color='#000000')
}

Can we instantiate an abstract class?

Here, i'm creating instance of my class

No, you are not creating the instance of your abstract class here. Rather you are creating an instance of an anonymous subclass of your abstract class. And then you are invoking the method on your abstract class reference pointing to subclass object.

This behaviour is clearly listed in JLS - Section # 15.9.1: -

If the class instance creation expression ends in a class body, then the class being instantiated is an anonymous class. Then:

  • If T denotes a class, then an anonymous direct subclass of the class named by T is declared. It is a compile-time error if the class denoted by T is a final class.
  • If T denotes an interface, then an anonymous direct subclass of Object that implements the interface named by T is declared.
  • In either case, the body of the subclass is the ClassBody given in the class instance creation expression.
  • The class being instantiated is the anonymous subclass.

Emphasis mine.

Also, in JLS - Section # 12.5, you can read about the Object Creation Process. I'll quote one statement from that here: -

Whenever a new class instance is created, memory space is allocated for it with room for all the instance variables declared in the class type and all the instance variables declared in each superclass of the class type, including all the instance variables that may be hidden.

Just before a reference to the newly created object is returned as the result, the indicated constructor is processed to initialize the new object using the following procedure:

You can read about the complete procedure on the link I provided.


To practically see that the class being instantiated is an Anonymous SubClass, you just need to compile both your classes. Suppose you put those classes in two different files:

My.java:

abstract class My {
    public void myMethod() {
        System.out.print("Abstract");
    }
}

Poly.java:

class Poly extends My {
    public static void main(String a[]) {
        My m = new My() {};
        m.myMethod();
    }
}

Now, compile both your source files:

javac My.java Poly.java

Now in the directory where you compiled the source code, you will see the following class files:

My.class
Poly$1.class  // Class file corresponding to anonymous subclass
Poly.class

See that class - Poly$1.class. It's the class file created by the compiler corresponding to the anonymous subclass you instantiated using the below code:

new My() {};

So, it's clear that there is a different class being instantiated. It's just that, that class is given a name only after compilation by the compiler.

In general, all the anonymous subclasses in your class will be named in this fashion:

Poly$1.class, Poly$2.class, Poly$3.class, ... so on

Those numbers denote the order in which those anonymous classes appear in the enclosing class.

Copy multiple files with Ansible

- hosts: lnx
  tasks:
    - find: paths="/appl/scripts/inq" recurse=yes patterns="inq.Linux*"
      register: file_to_copy
    - copy: src={{ item.path }} dest=/usr/local/sbin/
      owner: root
      mode: 0775
      with_items: "{{ files_to_copy.files }}"

Stylesheet not loaded because of MIME-type

Make a folder just below/above the style.css file as per the Angular structure and provide a link like <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">.

Enter image description here

What does .shape[] do in "for i in range(Y.shape[0])"?

In python, Suppose you have loaded up the data in some variable train:

train = pandas.read_csv('file_name')
>>> train
train([[ 1.,  2.,  3.],
        [ 5.,  1.,  2.]],)

I want to check what are the dimensions of the 'file_name'. I have stored the file in train

>>>train.shape
(2,3)
>>>train.shape[0]              # will display number of rows
2
>>>train.shape[1]              # will display number of columns
3

How to set NODE_ENV to production/development in OS X

npm start --mode production
npm start --mode development

With process.env.NODE_ENV = 'production'

Google MAP API Uncaught TypeError: Cannot read property 'offsetWidth' of null

Year, geocodezip's answer is correct. So change your code like this: (if you still in trouble, or maybe somebody else in the future)

<script type="text/javascript">

function initialize() {
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
        zoom: 8,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),
            myOptions);
}
google.maps.event.addDomListener(window, "load", initialize);

</script>

Curl setting Content-Type incorrectly

I think you want to specify

-H "Content-Type:text/xml"

with a colon, not an equals.

Make the current commit the only (initial) commit in a Git repository?

To remove the last commit from git, you can simply run

git reset --hard HEAD^ 

If you are removing multiple commits from the top, you can run

git reset --hard HEAD~2 

to remove the last two commits. You can increase the number to remove even more commits.

More info here.

Git tutoturial here provides help on how to purge repository:

you want to remove the file from history and add it to the .gitignore to ensure it is not accidentally re-committed. For our examples, we're going to remove Rakefile from the GitHub gem repository.

git clone https://github.com/defunkt/github-gem.git

cd github-gem

git filter-branch --force --index-filter \
  'git rm --cached --ignore-unmatch Rakefile' \
  --prune-empty --tag-name-filter cat -- --all

Now that we've erased the file from history, let's ensure that we don't accidentally commit it again.

echo "Rakefile" >> .gitignore

git add .gitignore

git commit -m "Add Rakefile to .gitignore"

If you're happy with the state of the repository, you need to force-push the changes to overwrite the remote repository.

git push origin master --force

How to solve npm error "npm ERR! code ELIFECYCLE"

Delete node_modules and package-lock.json, and then run npm install. It worked perfectly here(run command below inside project root):

rm -rf node_modules && rm ./package-lock.json && npm install

How to execute an external program from within Node.js?

The simplest way is:

const { exec } = require("child_process")
exec('yourApp').unref()

unref is necessary to end your process without waiting for "yourApp"

Here are the exec docs

Page Redirect after X seconds wait using JavaScript

setTimeout('Redirect()', 1000);
function Redirect() 
{  
    window.location="https://stackoverflow.com"; 
} 

//document.write("You will be Redirect to a new page in 1000 -> 1 Seconds, 2000 -> 2 Seconds");

Creating SolidColorBrush from hex color value

Try this instead:

(SolidColorBrush)(new BrushConverter().ConvertFrom("#ffaacc"));

How do I tokenize a string in C++?

The Boost tokenizer class can make this sort of thing quite simple:

#include <iostream>
#include <string>
#include <boost/foreach.hpp>
#include <boost/tokenizer.hpp>

using namespace std;
using namespace boost;

int main(int, char**)
{
    string text = "token, test   string";

    char_separator<char> sep(", ");
    tokenizer< char_separator<char> > tokens(text, sep);
    BOOST_FOREACH (const string& t, tokens) {
        cout << t << "." << endl;
    }
}

Updated for C++11:

#include <iostream>
#include <string>
#include <boost/tokenizer.hpp>

using namespace std;
using namespace boost;

int main(int, char**)
{
    string text = "token, test   string";

    char_separator<char> sep(", ");
    tokenizer<char_separator<char>> tokens(text, sep);
    for (const auto& t : tokens) {
        cout << t << "." << endl;
    }
}

Datagridview full row selection but get single cell value

I just want to point out, you can use .selectedindex to make it a little cleaner

string value = gridview.Rows[gridview.SelectedIndex].Cells[1].Text.ToString();

libstdc++-6.dll not found

Simply removing libstdc++-6.dll.a \ libstdc++.dll.a from the mingw directory fixes this.

I tried using the flag -static-libstdc++ but this did not work for me. I found the solution in: http://ghc.haskell.org/trac/ghc/ticket/4468#

How to reload page the page with pagination in Angular 2?

This should technically be achievable using window.location.reload():

HTML:

<button (click)="refresh()">Refresh</button>

TS:

refresh(): void {
    window.location.reload();
}

Update:

Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload() is executed.

Excel VBA Open a Folder

I use this to open a workbook and then copy that workbook's data to the template.

Private Sub CommandButton24_Click()
Set Template = ActiveWorkbook
 With Application.FileDialog(msoFileDialogOpen)
    .InitialFileName = "I:\Group - Finance" ' Yu can select any folder you want
    .Filters.Clear
    .Title = "Your Title"
    If Not .Show Then
        MsgBox "No file selected.": Exit Sub
    End If
    Workbooks.OpenText .SelectedItems(1)

'The below is to copy the file into a new sheet in the workbook and paste those values in sheet 1

    Set myfile = ActiveWorkbook
    ActiveWorkbook.Sheets(1).Copy after:=ThisWorkbook.Sheets(1)
    myfile.Close
    Template.Activate
    ActiveSheet.Cells.Select
    Selection.Copy
    Sheets("Sheet1").Select
    Cells.Select
    ActiveSheet.Paste

End With

How do you compare structs for equality in C?

It depends on whether the question you are asking is:

  1. Are these two structs the same object?
  2. Do they have the same value?

To find out if they are the same object, compare pointers to the two structs for equality. If you want to find out in general if they have the same value you have to do a deep comparison. This involves comparing all the members. If the members are pointers to other structs you need to recurse into those structs too.

In the special case where the structs do not contain pointers you can do a memcmp to perform a bitwise comparison of the data contained in each without having to know what the data means.

Make sure you know what 'equals' means for each member - it is obvious for ints but more subtle when it comes to floating-point values or user-defined types.

Lollipop : draw behind statusBar with its color set to transparent

Here is the theme I use to accomplish this:

<style name="AppTheme" parent="@android:style/Theme.NoTitleBar">

    <!-- Default Background Screen -->
    <item name="android:background">@color/default_blue</item>
    <item name="android:windowTranslucentStatus">true</item>

</style>

Display TIFF image in all web browser

I found this resource that details the various methods: How to embed TIFF files in HTML documents

As mentioned, it will very much depend on browser support for the format. Viewing that page in Chrome on Windows didn't display any of the images.

It would also be helpful if you posted the code you've tried already.

JAVA - using FOR, WHILE and DO WHILE loops to sum 1 through 100

- First to me Iterating and Looping are 2 different things.

Eg: Increment a variable till 5 is Looping.

    int count = 0;

    for (int i=0 ; i<5 ; i++){

        count = count + 1;

   }

Eg: Iterate over the Array to print out its values, is about Iteration

    int[] arr = {5,10,15,20,25};

    for (int i=0 ; i<arr.length ; i++){

        System.out.println(arr[i]);

   }

Now about all the Loops:

- Its always better to use For-Loop when you know the exact nos of time you gonna Loop, and if you are not sure of it go for While-Loop. Yes out there many geniuses can say that it can be done gracefully with both of them and i don't deny with them...but these are few things which makes me execute my program flawlessly...

For Loop :

int sum = 0; 

for (int i = 1; i <= 100; i++) {

  sum += i; 

}

 System.out.println("The sum is " + sum);

The Difference between While and Do-While is as Follows :

- While is a Entry Control Loop, Condition is checked in the Beginning before entering the loop.

- Do-While is a Exit Control Loop, Atleast once the block is always executed then the Condition is checked.

While Loop :

int sum = 0; 
int i = 0;       // i is 0 Here

    while (i<100) {

      sum += i; 
      i++;

    }

  System.out.println("The sum is " + sum);

do-While :

int sum = 0; 
int i = 0;      // i is 0 Here

    do{ 

      sum += i; 
       i++
    }while(i < 100; );

     System.out.println("The sum is " + sum);

From Java 5 we also have For-Each Loop to iterate over the Collections, even its handy with Arrays.

ArrayList<String> arr = new ArrayList<String>();

arr.add("Vivek");
arr.add("Is");
arr.add("Good");
arr.add("Boy");

for (String str : arr){         // str represents the value in each index of arr

    System.out.println(str);     

 }

How to get docker-compose to always re-create containers from fresh images?

By current official documentation there is a short cut that stops and removes containers, networks, volumes, and images created by up, if they are already stopped or partially removed and so on, then it will do the trick too:

docker-compose down

Then if you have new changes on your images or Dockerfiles use:

docker-compose build --no-cache

Finally:docker-compose up

In one command: docker-compose down && docker-compose build --no-cache && docker-compose up

How do I display a decimal value to 2 decimal places?

Double Amount = 0;
string amount;
amount=string.Format("{0:F2}", Decimal.Parse(Amount.ToString()));

Extracting specific selected columns to new DataFrame as a copy

Another simpler way seems to be:

new = pd.DataFrame([old.A, old.B, old.C]).transpose()

where old.column_name will give you a series. Make a list of all the column-series you want to retain and pass it to the DataFrame constructor. We need to do a transpose to adjust the shape.

In [14]:pd.DataFrame([old.A, old.B, old.C]).transpose()
Out[14]: 
   A   B    C
0  4  10  100
1  5  20   50

How to link to apps on the app store

For Xcode 9.1 and Swift 4:

  1. Import StoreKit:
import StoreKit

2.Conform the protocol

SKStoreProductViewControllerDelegate

3.Implement the protocol

func openStoreProductWithiTunesItemIdentifier(identifier: String) {
    let storeViewController = SKStoreProductViewController()
    storeViewController.delegate = self

    let parameters = [ SKStoreProductParameterITunesItemIdentifier : identifier]
    storeViewController.loadProduct(withParameters: parameters) { [weak self] (loaded, error) -> Void in

        if loaded {
            // Parent class of self is UIViewContorller
            self?.present(storeViewController, animated: true, completion: nil)
        }
    }   
}

3.1

func productViewControllerDidFinish(_ viewController: SKStoreProductViewController) {
    viewController.dismiss(animated: true, completion: nil)
}
  1. How to use:
openStoreProductWithiTunesItemIdentifier(identifier: "here_put_your_App_id")

Note:

It is very important to enter the exact ID of your APP. Because this cause error (not show the error log, but nothing works fine because of this)

How do I accomplish an if/else in mustache.js?

This is how you do if/else in Mustache (perfectly supported):

{{#repo}}
  <b>{{name}}</b>
{{/repo}}
{{^repo}}
  No repos :(
{{/repo}}

Or in your case:

{{#author}}
  {{#avatar}}
    <img src="{{avatar}}"/>
  {{/avatar}}
  {{^avatar}}
    <img src="/images/default_avatar.png" height="75" width="75" />
  {{/avatar}}
{{/author}}

Look for inverted sections in the docs: https://github.com/janl/mustache.js

Twitter Bootstrap carousel different height images cause bouncing arrows

Here is the solution that worked for me; I did it this way as the content in the carousel was dynamically generated from user-submitted content (so we could not use a static height in the stylesheet) - This solution should also work with different sized screens:

function updateCarouselSizes(){
  jQuery(".carousel").each(function(){
    // I wanted an absolute minimum of 10 pixels
    var maxheight=10; 
    if(jQuery(this).find('.item,.carousel-item').length) {
      // We've found one or more item within the Carousel...
      jQuery(this).carousel(); // Initialise the carousel (include options as appropriate)
      // Now we iterate through each item within the carousel...
      jQuery(this).find('.item,.carousel-item').each(function(k,v){ 
        if(jQuery(this).outerHeight()>maxheight) {
          // This item is the tallest we've found so far, so store the result...
          maxheight=jQuery(this).outerHeight();
        }
      });
      // Finally we set the carousel's min-height to the value we've found to be the tallest...
      jQuery(this).css("min-height",maxheight+"px");
    }
  });
}

jQuery(function(){
  jQuery(window).on("resize",updateCarouselSizes);
  updateCarouselSizes();
}

Technically this is not responsive, but for my purposes the on window resize makes this behave responsively.

jQuery or CSS selector to select all IDs that start with some string

Normally you would select IDs using the ID selector #, but for more complex matches you can use the attribute-starts-with selector (as a jQuery selector, or as a CSS3 selector):

div[id^="player_"]

If you are able to modify that HTML, however, you should add a class to your player divs then target that class. You'll lose the additional specificity offered by ID selectors anyway, as attribute selectors share the same specificity as class selectors. Plus, just using a class makes things much simpler.

How to save Excel Workbook to Desktop regardless of user?

Not sure if this is still relevant, but I use this way

Public bEnableEvents As Boolean
Public bclickok As Boolean
Public booRestoreErrorChecking As Boolean   'put this at the top of the module

 Private Declare Function apiGetComputerName Lib "kernel32" Alias _
"GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Private Declare Function apiGetUserName Lib "advapi32.dll" Alias _
"GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long

Function GetUserID() As String
' Returns the network login name
On Error Resume Next
Dim lngLen As Long, lngX As Long
Dim strUserName As String
strUserName = String$(254, 0)
lngLen = 255
lngX = apiGetUserName(strUserName, lngLen)
If lngX <> 0 Then
    GetUserID = Left$(strUserName, lngLen - 1)
Else
    GetUserID = ""
End If
Exit Function
End Function

This next bit I save file as PDF, but can change to suit

Public Sub SaveToDesktop()
Dim LoginName As String
LoginName = UCase(GetUserID)

ChDir "C:\Users\" & LoginName & "\Desktop\"
Debug.Print LoginName
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
    "C:\Users\" & LoginName & "\Desktop\MyFileName.pdf", Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
    True
End Sub

R error "sum not meaningful for factors"

The error comes when you try to call sum(x) and x is a factor.

What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)

simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:

family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))

For a detailed explanation of why the intermediate as.character step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?

How do you set your pythonpath in an already-created virtualenv?

  1. Initialize your virtualenv
cd venv

source bin/activate
  1. Just set or change your python path by entering command following:
export PYTHONPATH='/home/django/srmvenv/lib/python3.4'
  1. for checking python path enter in python:
   python

      \>\> import sys

      \>\> sys.path

Jenkins restrict view of jobs per user

Try going to "Manage Jenkins"->"Manage Users" go to the specific user, edit his/her configuration "My Views section" default view.

How to check if a subclass is an instance of a class at runtime?

I've never actually used this, but try view.getClass().getGenericSuperclass()

How do I stop Notepad++ from showing autocomplete for all words in the file

The answer is to DISABLE "Enable auto-completion on each input". Tested and works perfectly.

Border around specific rows in a table?

Group rows together using the <tbody> tag and then apply style.

<table>
  <tr><td>No Style here</td></tr>
  <tbody class="red-outline">
    <tr><td>Style me</td></tr>
    <tr><td>And me</td></tr>
  </tbody>
  <tr><td>No Style here</td></tr>
</table>  

And the css in style.css

.red-outline {
  outline: 1px solid red;
}

How can I get a Unicode character's code?

A more complete, albeit more verbose, way of doing this would be to use the Character.codePointAt method. This will handle 'high surrogate' characters, that cannot be represented by a single integer within the range that a char can represent.

In the example you've given this is not strictly necessary - if the (Unicode) character can fit inside a single (Java) char (such as the registered local variable) then it must fall within the \u0000 to \uffff range, and you won't need to worry about surrogate pairs. But if you're looking at potentially higher code points, from within a String/char array, then calling this method is wise in order to cover the edge cases.

For example, instead of

String input = ...;
char fifthChar = input.charAt(4);
int codePoint = (int)fifthChar;

use

String input = ...;
int codePoint = Character.codePointAt(input, 4);

Not only is this slightly less code in this instance, but it will handle detection of surrogate pairs for you.

Removing path and extension from filename in PowerShell

This can be done by splitting the string a couple of times.

#Path
$Link = "http://some.url/some/path/file.name"

#Split path on "/"
#Results of split will look like this : 
# http:
#
# some.url
# some
# path
# file.name
$Split = $Link.Split("/")

#Count how many Split strings there are
#There are 6 strings that have been split in my example
$SplitCount = $Split.Count

#Select the last string
#Result of this selection : 
# file.name
$FilenameWithExtension = $Split[$SplitCount -1]

#Split filename on "."
#Result of this split : 
# file
# name
$FilenameWithExtensionSplit = $FilenameWithExtension.Split(".")

#Select the first half
#Result of this selection : 
# file
$FilenameWithoutExtension = $FilenameWithExtensionSplit[0]

#The filename without extension is in this variable now
# file
$FilenameWithoutExtension

Here is the code without comments :

$Link = "http://some.url/some/path/file.name"
$Split = $Link.Split("/")
$SplitCount = $Split.Count
$FilenameWithExtension = $Split[$SplitCount -1]
$FilenameWithExtensionSplit = $FilenameWithExtension.Split(".")
$FilenameWithoutExtension = $FilenameWithExtensionSplit[0]
$FilenameWithoutExtension

Android file chooser

EDIT (02 Jan 2012):

I created a small open source Android Library Project that streamlines this process, while also providing a built-in file explorer (in case the user does not have one present). It's extremely simple to use, requiring only a few lines of code.

You can find it at GitHub: aFileChooser.


ORIGINAL

If you want the user to be able to choose any file in the system, you will need to include your own file manager, or advise the user to download one. I believe the best you can do is look for "openable" content in an Intent.createChooser() like this:

private static final int FILE_SELECT_CODE = 0;

private void showFileChooser() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
    intent.setType("*/*"); 
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        startActivityForResult(
                Intent.createChooser(intent, "Select a File to Upload"),
                FILE_SELECT_CODE);
    } catch (android.content.ActivityNotFoundException ex) {
        // Potentially direct the user to the Market with a Dialog
        Toast.makeText(this, "Please install a File Manager.", 
                Toast.LENGTH_SHORT).show();
    }
}

You would then listen for the selected file's Uri in onActivityResult() like so:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case FILE_SELECT_CODE:
        if (resultCode == RESULT_OK) {
            // Get the Uri of the selected file 
            Uri uri = data.getData();
            Log.d(TAG, "File Uri: " + uri.toString());
            // Get the path
            String path = FileUtils.getPath(this, uri);
            Log.d(TAG, "File Path: " + path);
            // Get the file instance
            // File file = new File(path);
            // Initiate the upload
        }
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

The getPath() method in my FileUtils.java is:

public static String getPath(Context context, Uri uri) throws URISyntaxException {
    if ("content".equalsIgnoreCase(uri.getScheme())) {
        String[] projection = { "_data" };
        Cursor cursor = null;

        try {
            cursor = context.getContentResolver().query(uri, projection, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow("_data");
            if (cursor.moveToFirst()) {
                return cursor.getString(column_index);
            }
        } catch (Exception e) {
            // Eat it
        }
    }
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
} 

How to import existing *.sql files in PostgreSQL 8.4?

in command line first reach the directory where psql is present then write commands like this:

psql [database name] [username]

and then press enter psql asks for password give the user password:

then write

> \i [full path and file name with extension]

then press enter insertion done.

Resource u'tokenizers/punkt/english.pickle' not found

From the shell you can execute:

sudo python -m nltk.downloader punkt 

If you want to install the popular NLTK corpora/models:

sudo python -m nltk.downloader popular

If you want to install all NLTK corpora/models:

sudo python -m nltk.downloader all

To list the resources you have downloaded:

python -c 'import os; import nltk; print os.listdir(nltk.data.find("corpora"))'
python -c 'import os; import nltk; print os.listdir(nltk.data.find("tokenizers"))'

Difference between Pig and Hive? Why have both?

Check out this post from Alan Gates, Pig architect at Yahoo!, that compares when would use a SQL like Hive rather than Pig. He makes a very convincing case as to the usefulness of a procedural language like Pig (vs. declarative SQL) and its utility to dataflow designers.

Oracle date "Between" Query

Judging from your output it looks like you have defined START_DATE as a timestamp. If it were a regular date Oracle would be able to handle the implicit conversion. But as it isn't you need to explicitly cast those strings to be dates.

SQL> alter session set nls_date_format = 'dd-mon-yyyy hh24:mi:ss'
  2  /

Session altered.

SQL>
SQL> select * from t23
  2  where start_date between '15-JAN-10' and '17-JAN-10'
  3  /

no rows selected

SQL> select * from t23
  2  where start_date between to_date('15-JAN-10') and to_date('17-JAN-10')
  3  /

WIDGET                          START_DATE
------------------------------  ----------------------
Small Widget                    15-JAN-10 04.25.32.000    

SQL> 

But we still only get one row. This is because START_DATE has a time element. If we don't specify the time component Oracle defaults it to midnight. That is fine for the from side of the BETWEEN but not for the until side:

SQL> select * from t23
  2  where start_date between to_date('15-JAN-10') 
  3                       and to_date('17-JAN-10 23:59:59')
  4  /

WIDGET                          START_DATE
------------------------------  ----------------------
Small Widget                    15-JAN-10 04.25.32.000
Product 1                       17-JAN-10 04.31.32.000

SQL>

edit

If you cannot pass in the time component there are a couple of choices. One is to change the WHERE clause to remove the time element from the criteria:

where trunc(start_date) between to_date('15-JAN-10') 
                            and to_date('17-JAN-10')

This might have an impact on performance, because it disqualifies any b-tree index on START_DATE. You would need to build a function-based index instead.

Alternatively you could add the time element to the date in your code:

where start_date between to_date('15-JAN-10') 
                     and to_date('17-JAN-10') + (86399/86400) 

Because of these problems many people prefer to avoid the use of between by checking for date boundaries like this:

where start_date >= to_date('15-JAN-10') 
and start_date < to_date('18-JAN-10')

Can I delete a git commit but keep the changes?

You're looking for either git reset HEAD^ --soft or git reset HEAD^ --mixed.

There are 3 modes to the reset command as stated in the docs:

git reset HEAD^ --soft

undo the git commit. Changes still exist in the working tree(the project folder) + the index (--cached)

git reset HEAD^ --mixed

undo git commit + git add. Changes still exist in the working tree

git reset HEAD^ --hard

Like you never made these changes to the codebase. Changes are gone from the working tree.

Is there a short contains function for lists?

I came up with this one liner recently for getting True if a list contains any number of occurrences of an item, or False if it contains no occurrences or nothing at all. Using next(...) gives this a default return value (False) and means it should run significantly faster than running the whole list comprehension.

list_does_contain = next((True for item in list_to_test if item == test_item), False)

HSL to RGB color conversion

PHP - shortest but precise

Here I rewrite my JS answer (math details are there) to PHP - you can run it here

function hsl2rgb($h,$s,$l) 
{
  $a = $s * min($l, 1-$l);
  $k = function($n,$h) { return ($n+$h/30)%12;};
  $f = function($n) use ($h,$s,$l,$a,$k) { 
      return $l - $a * max( min($k($n,$h)-3, 9-$k($n,$h), 1),-1);
  };
  return [ $f(0), $f(8), $f(4) ];
}   

Deserialize JSON array(or list) in C#

I was having the similar issue and solved by understanding the Classes in asp.net C#

I want to read following JSON string :

[
    {
        "resultList": [
            {
                "channelType": "",
                "duration": "2:29:30",
                "episodeno": 0,
                "genre": "Drama",
                "genreList": [
                    "Drama"
                ],
                "genres": [
                    {
                        "personName": "Drama"
                    }
                ],
                "id": 1204,
                "language": "Hindi",
                "name": "The Great Target",
                "productId": 1204,
                "productMasterId": 1203,
                "productMasterName": "The Great Target",
                "productName": "The Great Target",
                "productTypeId": 1,
                "productTypeName": "Movie",
                "rating": 3,
                "releaseyear": "2005",
                "showGoodName": "Movies ",
                "views": 8333
            },
            {
                "channelType": "",
                "duration": "2:30:30",
                "episodeno": 0,
                "genre": "Romance",
                "genreList": [
                    "Romance"
                ],
                "genres": [
                    {
                        "personName": "Romance"
                    }
                ],
                "id": 1144,
                "language": "Hindi",
                "name": "Mere Sapnon Ki Rani",
                "productId": 1144,
                "productMasterId": 1143,
                "productMasterName": "Mere Sapnon Ki Rani",
                "productName": "Mere Sapnon Ki Rani",
                "productTypeId": 1,
                "productTypeName": "Movie",
                "rating": 3,
                "releaseyear": "1997",
                "showGoodName": "Movies ",
                "views": 6482
            },
            {
                "channelType": "",
                "duration": "2:34:07",
                "episodeno": 0,
                "genre": "Drama",
                "genreList": [
                    "Drama"
                ],
                "genres": [
                    {
                        "personName": "Drama"
                    }
                ],
                "id": 1520,
                "language": "Telugu",
                "name": "Satyameva Jayathe",
                "productId": 1520,
                "productMasterId": 1519,
                "productMasterName": "Satyameva Jayathe",
                "productName": "Satyameva Jayathe",
                "productTypeId": 1,
                "productTypeName": "Movie",
                "rating": 3,
                "releaseyear": "2004",
                "showGoodName": "Movies ",
                "views": 9910
            }
        ],
        "resultSize": 1171,
        "pageIndex": "1"
    }
]

My asp.net c# code looks like following

First, Class3.cs page created in APP_Code folder of Web application

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Text;
using System.IO;
using System.Web.Script.Serialization;
using System.Collections.Generic;

/// <summary>
/// Summary description for Class3
/// </summary>
public class Class3
{

    public List<ListWrapper_Main> ResultList_Main { get; set; }

    public class ListWrapper_Main
    {
        public List<ListWrapper> ResultList { get; set; }

        public string resultSize { get; set; }
        public string pageIndex { get; set; }
    }

    public class ListWrapper
    {
        public string channelType { get; set; }
        public string duration { get; set; }
        public int episodeno { get; set; }
        public string genre { get; set; }
        public string[] genreList { get; set; }
        public List<genres_cls> genres { get; set; }
        public int id { get; set; }
        public string imageUrl { get; set; }
        //public string imageurl { get; set; }
        public string language { get; set; }
        public string name { get; set; }
        public int productId { get; set; }
        public int productMasterId { get; set; }
        public string productMasterName { get; set; }
        public string productName { get; set; }
        public int productTypeId { get; set; }
        public string productTypeName { get; set; }
        public decimal rating { get; set; }
        public string releaseYear { get; set; }
        //public string releaseyear { get; set; }
        public string showGoodName { get; set; }
        public string views { get; set; }
    }
    public class genres_cls
    {
        public string personName { get; set; }
    }

}

Then, Browser page that reads the string/JSON string listed above and displays/Deserialize the JSON objects and displays the data

JavaScriptSerializer ser = new JavaScriptSerializer();


        string final_sb = sb.ToString();

        List<Class3.ListWrapper_Main> movieInfos = ser.Deserialize<List<Class3.ListWrapper_Main>>(final_sb.ToString());

        foreach (var itemdetail in movieInfos)
        {

            foreach (var itemdetail2 in itemdetail.ResultList)
            {
                Response.Write("channelType=" + itemdetail2.channelType + "<br/>");
                Response.Write("duration=" + itemdetail2.duration + "<br/>");
                Response.Write("episodeno=" + itemdetail2.episodeno + "<br/>");
                Response.Write("genre=" + itemdetail2.genre + "<br/>");

                string[] genreList_arr = itemdetail2.genreList;
                for (int i = 0; i < genreList_arr.Length; i++)
                    Response.Write("genreList1=" + genreList_arr[i].ToString() + "<br>");

                foreach (var genres1 in itemdetail2.genres)
                {
                    Response.Write("genres1=" + genres1.personName + "<br>");
                }

                Response.Write("id=" + itemdetail2.id + "<br/>");
                Response.Write("imageUrl=" + itemdetail2.imageUrl + "<br/>");
                //Response.Write("imageurl=" + itemdetail2.imageurl + "<br/>");
                Response.Write("language=" + itemdetail2.language + "<br/>");
                Response.Write("name=" + itemdetail2.name + "<br/>");
                Response.Write("productId=" + itemdetail2.productId + "<br/>");
                Response.Write("productMasterId=" + itemdetail2.productMasterId + "<br/>");
                Response.Write("productMasterName=" + itemdetail2.productMasterName + "<br/>");
                Response.Write("productName=" + itemdetail2.productName + "<br/>");
                Response.Write("productTypeId=" + itemdetail2.productTypeId + "<br/>");
                Response.Write("productTypeName=" + itemdetail2.productTypeName + "<br/>");
                Response.Write("rating=" + itemdetail2.rating + "<br/>");
                Response.Write("releaseYear=" + itemdetail2.releaseYear + "<br/>");
                //Response.Write("releaseyear=" + itemdetail2.releaseyear + "<br/>");
                Response.Write("showGoodName=" + itemdetail2.showGoodName + "<br/>");
                Response.Write("views=" + itemdetail2.views + "<br/><br>");
                //Response.Write("resultSize" + itemdetail2.resultSize + "<br/>");
                //  Response.Write("pageIndex" + itemdetail2.pageIndex + "<br/>");


            }



            Response.Write("resultSize=" + itemdetail.resultSize + "<br/><br>");
            Response.Write("pageIndex=" + itemdetail.pageIndex + "<br/><br>");

        }

'sb' is the actual string, i.e. JSON string of data mentioned very first on top of this reply

This is basically - web application asp.net c# code....

N joy...

Resetting a multi-stage form with jQuery

jQuery Plugin

I created a jQuery plugin so I can use it easily anywhere I need it:

jQuery.fn.clear = function()
{
    var $form = $(this);

    $form.find('input:text, input:password, input:file, textarea').val('');
    $form.find('select option:selected').removeAttr('selected');
    $form.find('input:checkbox, input:radio').removeAttr('checked');

    return this;
}; 

So now I can use it by calling:

$('#my-form').clear();

Find all files in a folder

First off; best practice would be to get the users Desktop folder with

string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

Then you can find all the files with something like

string[] files = Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories);

Note that with the above line you will find all files with a .txt extension in the Desktop folder of the logged in user AND all subfolders.

Then you could copy or move the files by enumerating the above collection like

// For copying...
foreach (string s in files)
{
   File.Copy(s, "C:\newFolder\newFilename.txt");
}

// ... Or for moving
foreach (string s in files)
{
   File.Move(s, "C:\newFolder\newFilename.txt");
}

Please note that you will have to include the filename in your Copy() (or Move()) operation. So you would have to find a way to determine the filename of at least the extension you are dealing with and not name all the files the same like what would happen in the above example.

With that in mind you could also check out the DirectoryInfo and FileInfo classes. These work in similair ways, but you can get information about your path-/filenames, extensions, etc. more easily

Check out these for more info:

http://msdn.microsoft.com/en-us/library/system.io.directory.aspx

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

http://msdn.microsoft.com/en-us/library/system.io.file.aspx

Crystal Reports for VS2012 - VS2013 - VS2015 - VS2017 - VS2019

There is also someone who managed to modify CR for VS.NET 2010 to install on 2012, using MS ORCA in this thread: http://scn.sap.com/thread/3235515 . I couldn't get it to work myself, though.

SQL Server Escape an Underscore

None of these worked for me in SSIS v18.0, so I would up doing something like this:

WHERE CHARINDEX('_', thingyoursearching) < 1

..where I am trying to ignore strings with an underscore in them. If you want to find things that have an underscore, just flip it around:

WHERE CHARINDEX('_', thingyoursearching) > 0

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

I use this on a daily basis to show history with files that changed:

git log --stat --pretty=short --graph

To keep it short, add an alias in your .gitconfig by doing:

git config --global alias.ls 'log --stat --pretty=short --graph'

How do you configure HttpOnly cookies in tomcat / java webapps?

For cookies that I am explicitly setting, I switched to use SimpleCookie provided by Apache Shiro. It does not inherit from javax.servlet.http.Cookie so it takes a bit more juggling to get everything to work correctly however it does provide a property set HttpOnly and it works with Servlet 2.5.

For setting a cookie on a response, rather than doing response.addCookie(cookie) you need to do cookie.saveTo(request, response).

android pinch zoom

For android 2.2+ (api level8), you can use ScaleGestureDetector.

you need a member:

private ScaleGestureDetector mScaleDetector;

in your constructor (or onCreate()) you add:

mScaleDetector = new ScaleGestureDetector(context, new OnScaleGestureListener() {
    @Override
    public void onScaleEnd(ScaleGestureDetector detector) {
    }
    @Override
    public boolean onScaleBegin(ScaleGestureDetector detector) {
        return true;
    }
    @Override
    public boolean onScale(ScaleGestureDetector detector) {
        Log.d(LOG_KEY, "zoom ongoing, scale: " + detector.getScaleFactor());
        return false;
    }
});

You override onTouchEvent:

@Override
public boolean onTouchEvent(MotionEvent event) {
    mScaleDetector.onTouchEvent(event);
    return true;
}

If you draw your View by hand, in the onScale() you probably do store the scale factor in a member, then call invalidate() and use the scale factor when drawing in your onDraw(). Otherwise you can directly modify font sizes or things like that in the onScale().

MySQL ORDER BY multiple column ASC and DESC

Ok, I THINK I understand what you want now, and let me clarify to confirm before the query. You want 1 record for each user. For each user, you want their BEST POINTS score record. Of the best points per user, you want the one with the best average time. Once you have all users "best" values, you want the final results sorted with best points first... Almost like ranking of a competition.

So now the query. If the above statement is accurate, you need to start with getting the best point/average time per person and assigning a "Rank" to that entry. This is easily done using MySQL @ variables. Then, just include a HAVING clause to only keep those records ranked 1 for each person. Finally apply the order by of best points and shortest average time.

select
      U.UserName,
      PreSortedPerUser.Point,
      PreSortedPerUser.Avg_Time,
      @UserRank := if( @lastUserID = PreSortedPerUser.User_ID, @UserRank +1, 1 ) FinalRank,
      @lastUserID := PreSortedPerUser.User_ID
   from
      ( select
              S.user_id,
              S.point,
              S.avg_time
           from
              Scores S
           order by
              S.user_id,
              S.point DESC,
              S.Avg_Time ) PreSortedPerUser
         JOIN Users U
            on PreSortedPerUser.user_ID = U.ID,
      ( select @lastUserID := 0,
               @UserRank := 0 ) sqlvars 
   having
      FinalRank = 1
   order by
      Point Desc,
      Avg_Time

Results as handled by SQLFiddle

Note, due to the inline @variables needed to get the answer, there are the two extra columns at the end of each row. These are just "left-over" and can be ignored in any actual output presentation you are trying to do... OR, you can wrap the entire thing above one more level to just get the few columns you want like

select 
      PQ.UserName,
      PQ.Point,
      PQ.Avg_Time
   from
      ( entire query above pasted here ) as PQ

setting content between div tags using javascript

Try the following:

document.getElementById("successAndErrorMessages").innerHTML="someContent"; 

msdn link for detail : innerHTML Property

Convert Mat to Array/Vector in OpenCV

Instead of getting image row by row, you can put it directly to an array. For CV_8U type image, you can use byte array, for other types check here.

Mat img; // Should be CV_8U for using byte[]
int size = (int)img.total() * img.channels();
byte[] data = new byte[size];
img.get(0, 0, data); // Gets all pixels

Is there a way to style a TextView to uppercase all of its letters?

I've come up with a solution which is similar with RacZo's in the fact that I've also created a subclass of TextView which handles making the text upper-case.

The difference is that instead of overriding one of the setText() methods, I've used a similar approach to what the TextView actually does on API 14+ (which is in my point of view a cleaner solution).

If you look into the source, you'll see the implementation of setAllCaps():

public void setAllCaps(boolean allCaps) {
    if (allCaps) {
        setTransformationMethod(new AllCapsTransformationMethod(getContext()));
    } else {
        setTransformationMethod(null);
    }
}

The AllCapsTransformationMethod class is not (currently) public, but still, the source is also available. I've simplified that class a bit (removed the setLengthChangesAllowed() method), so the complete solution is this:

public class UpperCaseTextView extends TextView {

    public UpperCaseTextView(Context context) {
        super(context);
        setTransformationMethod(upperCaseTransformation);
    }

    public UpperCaseTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setTransformationMethod(upperCaseTransformation);
    }

    public UpperCaseTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setTransformationMethod(upperCaseTransformation);
    }

    private final TransformationMethod upperCaseTransformation =
            new TransformationMethod() {

        private final Locale locale = getResources().getConfiguration().locale;

        @Override
        public CharSequence getTransformation(CharSequence source, View view) {
            return source != null ? source.toString().toUpperCase(locale) : null;
        }

        @Override
        public void onFocusChanged(View view, CharSequence sourceText,
                boolean focused, int direction, Rect previouslyFocusedRect) {}
    };
}

How to add dividers and spaces between items in RecyclerView?

Too Late but for GridLayoutManager I use this:

public class GridSpacesItemDecoration : RecyclerView.ItemDecoration
{
    private int space;

    public GridSpacesItemDecoration(int space) {
        this.space = space;
    }

    public override void GetItemOffsets(Android.Graphics.Rect outRect, View view, RecyclerView parent, RecyclerView.State state)
    {
        var position = parent.GetChildLayoutPosition(view);

        /// Only for GridLayoutManager Layouts
        var manager = parent.GetLayoutManager() as GridLayoutManager;

        if (parent.GetChildLayoutPosition(view) < manager.SpanCount)
            outRect.Top = space;

        if (position % 2 != 0) {
            outRect.Right = space;
        }

        outRect.Left = space;
        outRect.Bottom = space;
    }
}

This work for any span count you have.

Ollie.

member names cannot be the same as their enclosing type C#

As Constructor should be at the starting of the Class , you are facing the above issue . So, you can either change the name or if you want to use it as a constructor just copy the method at the beginning of the class.

Instagram API - How can I retrieve the list of people a user is following on Instagram

The REST API of Instagram has been discontinued. But you can use GraphQL to get the desired data. Here you can find an overview: https://developers.facebook.com/docs/instagram-api

oracle sql: update if exists else insert

Please refer to this question if you want to use UPSERT/MERGE command in Oracle. Otherwise, just resolve your issue on the client side by doing a count(1) first and then deciding whether to insert or update.

What does bundle exec rake mean?

I have not used bundle exec much, but am setting it up now.

I have had instances where the wrong rake was used and much time wasted tracking down the problem. This helps you avoid that.

Here's how to set up RVM so you can use bundle exec by default within a specific project directory:

https://thoughtbot.com/blog/use-bundlers-binstubs

Uploading file using POST request in Node.js

You can also use the "custom options" support from the request library. This format allows you to create a multi-part form upload, but with a combined entry for both the file and extra form information, like filename or content-type. I have found that some libraries expect to receive file uploads using this format, specifically libraries like multer.

This approach is officially documented in the forms section of the request docs - https://github.com/request/request#forms

//toUpload is the name of the input file: <input type="file" name="toUpload">

let fileToUpload = req.file;

let formData = {
    toUpload: {
      value: fs.createReadStream(path.join(__dirname, '..', '..','upload', fileToUpload.filename)),
      options: {
        filename: fileToUpload.originalname,
        contentType: fileToUpload.mimeType
      }
    }
  };
let options = {
    url: url,
    method: 'POST',
    formData: formData
  }
request(options, function (err, resp, body) {
    if (err)
      cb(err);

    if (!err && resp.statusCode == 200) {
      cb(null, body);
    }
  });

How to write a full path in a batch file having a folder name with space?

Put double quotes around the path that has spaces like this:

REGSVR32 "E:\Documents and Settings\All Users\Application Data\xyz.dll"

Cannot read property 'style' of undefined -- Uncaught Type Error

It's currently working, I've just changed the operator > in order to work in the snippet, take a look:

_x000D_
_x000D_
window.onload = function() {_x000D_
_x000D_
  if (window.location.href.indexOf("test") <= -1) {_x000D_
    var search_span = document.getElementsByClassName("securitySearchQuery");_x000D_
    search_span[0].style.color = "blue";_x000D_
    search_span[0].style.fontWeight = "bold";_x000D_
    search_span[0].style.fontSize = "40px";_x000D_
_x000D_
  }_x000D_
_x000D_
}
_x000D_
<h1 class="keyword-title">Search results for<span class="securitySearchQuery"> "hi".</span></h1>
_x000D_
_x000D_
_x000D_

horizontal scrollbar on top and bottom of table

There is one way to achieve this that I did not see anybody mentioning here.

By rotating the parent container by 180 degrees and the child-container again by 180 degrees the scrollbar will be shown at top

.parent {
  transform: rotateX(180deg);
  overflow-x: auto;
} 
.child {
  transform: rotateX(180deg);
}

For reference see the issue in the w3c repository.

How do I add button on each row in datatable?

take a look here... this was very helpfull to me https://datatables.net/examples/ajax/null_data_source.html

$(document).ready(function() {
    var table = $('#example').DataTable( {
        "ajax": "data/arrays.txt",
        "columnDefs": [ {
        "targets": -1,
        "data": null,
        "defaultContent": "<button>Click!</button>"
    } ]
} );

$('#example tbody').on( 'click', 'button', function () {
    var data = table.row( $(this).parents('tr') ).data();
    alert( data[0] +"'s salary is: "+ data[ 5 ] );
    } );
} );

Screen width in React Native

If you have a Style component that you can require from your Component, then you could have something like this at the top of the file:

const Dimensions = require('Dimensions');

const window = Dimensions.get('window');

And then you could provide fulscreen: {width: window.width, height: window.height}, in your Style component. Hope this helps

Negation in Python

The negation operator in Python is not. Therefore just replace your ! with not.

For your example, do this:

if not os.path.exists("/usr/share/sounds/blues") :
    proc = subprocess.Popen(["mkdir", "/usr/share/sounds/blues"])
    proc.wait()

For your specific example (as Neil said in the comments), you don't have to use the subprocess module, you can simply use os.mkdir() to get the result you need, with added exception handling goodness.

Example:

blues_sounds_path = "/usr/share/sounds/blues"
if not os.path.exists(blues_sounds_path):
    try:
        os.mkdir(blues_sounds_path)
    except OSError:
        # Handle the case where the directory could not be created.

How to play only the audio of a Youtube video using HTML 5?

_x000D_
_x000D_
// YouTube video ID
var videoID = "CMNry4PE93Y";

// Fetch video info (using a proxy to avoid CORS errors)
fetch('https://cors-anywhere.herokuapp.com/' + "https://www.youtube.com/get_video_info?video_id=" + videoID).then(response => {
  if (response.ok) {
    response.text().then(ytData => {
      
      // parse response to find audio info
      var ytData = parse_str(ytData);
      var getAdaptiveFormats = JSON.parse(ytData.player_response).streamingData.adaptiveFormats;
      var findAudioInfo = getAdaptiveFormats.findIndex(obj => obj.audioQuality);
      
      // get the URL for the audio file
      var audioURL = getAdaptiveFormats[findAudioInfo].url;
      
      // update the <audio> element src
      var youtubeAudio = document.getElementById('youtube');
      youtubeAudio.src = audioURL;
      
    });
  }
});

function parse_str(str) {
  return str.split('&').reduce(function(params, param) {
    var paramSplit = param.split('=').map(function(value) {
      return decodeURIComponent(value.replace('+', ' '));
    });
    params[paramSplit[0]] = paramSplit[1];
    return params;
  }, {});
}
_x000D_
<audio id="youtube" controls></audio>
_x000D_
_x000D_
_x000D_

How to read pickle file?

Pickle serializes a single object at a time, and reads back a single object - the pickled data is recorded in sequence on the file.

If you simply do pickle.load you should be reading the first object serialized into the file (not the last one as you've written).

After unserializing the first object, the file-pointer is at the beggining of the next object - if you simply call pickle.load again, it will read that next object - do that until the end of the file.

objects = []
with (open("myfile", "rb")) as openfile:
    while True:
        try:
            objects.append(pickle.load(openfile))
        except EOFError:
            break