Programs & Examples On #Udid

Unique Device ID. A unique identifying number in any iOS device.

Is there a way since (iOS 7's release) to get the UDID without using iTunes on a PC/Mac?

If any of your users are running linux they can use this from a terminal:

lsusb -v 2> /dev/null | grep -e "Apple Inc" -A 2

This gets the all the information for your connected usb devices and prints lines with "Apple Inc" including the next 2 lines.

The result looks like this:

iManufacturer           1 Apple Inc.
iProduct                2 iPad
iSerial                 3 7ddf32e17a6ac5ce04a8ecbf782ca509...

This has worked for me on iOS5 -> iOS7, I haven’t tried on any iOS4 devices though.

IMO this is faster then any Win/Mac/Browser solution I have found and requires no "software" installation.

Click a button programmatically - JS

window.onload = function() {
    var userImage = document.getElementById('imageOtherUser');
    var hangoutButton = document.getElementById("hangoutButtonId");
    userImage.onclick = function() {
       hangoutButton.click(); // this will trigger the click event
    };
};

this will do the trick

OpenCV NoneType object has no attribute shape

I have also met this issue and wasted a lot of time debugging it.

First, make sure that the path you provide is valid, i.e., there is an image in that path.

Next, you should be aware that Opencv doesn't support image paths which contain unicode characters (see ref). If your image path contains Unicode characters, you can use the following code to read the image:

import numpy as np
import cv2

# img is in BGR format if the underlying image is a color image
img = cv2.imdecode(np.fromfile(im_path, dtype=np.uint8), cv2.IMREAD_UNCHANGED)

How can get the text of a div tag using only javascript (no jQuery)

Because textContent is not supported in IE8 and older, here is a workaround:

var node = document.getElementById('test'),
var text  = node.textContent || node.innerText;
alert(text);

innerText does work in IE.

How to insert a line break in a SQL Server VARCHAR/NVARCHAR string

I'd say

concat('This is line 1.', 0xd0a, 'This is line 2.')

or

concat(N'This is line 1.', 0xd000a, N'This is line 2.')

Why use getters and setters/accessors?

Code evolves. private is great for when you need data member protection. Eventually all classes should be sort of "miniprograms" that have a well-defined interface that you can't just screw with the internals of.

That said, software development isn't about setting down that final version of the class as if you're pressing some cast iron statue on the first try. While you're working with it, code is more like clay. It evolves as you develop it and learn more about the problem domain you are solving. During development classes may interact with each other than they should (dependency you plan to factor out), merge together, or split apart. So I think the debate boils down to people not wanting to religiously write

int getVar() const { return var ; }

So you have:

doSomething( obj->getVar() ) ;

Instead of

doSomething( obj->var ) ;

Not only is getVar() visually noisy, it gives this illusion that gettingVar() is somehow a more complex process than it really is. How you (as the class writer) regard the sanctity of var is particularly confusing to a user of your class if it has a passthru setter -- then it looks like you're putting up these gates to "protect" something you insist is valuable, (the sanctity of var) but yet even you concede var's protection isn't worth much by the ability for anyone to just come in and set var to whatever value they want, without you even peeking at what they are doing.

So I program as follows (assuming an "agile" type approach -- ie when I write code not knowing exactly what it will be doing/don't have time or experience to plan an elaborate waterfall style interface set):

1) Start with all public members for basic objects with data and behavior. This is why in all my C++ "example" code you'll notice me using struct instead of class everywhere.

2) When an object's internal behavior for a data member becomes complex enough, (for example, it likes to keep an internal std::list in some kind of order), accessor type functions are written. Because I'm programming by myself, I don't always set the member private right away, but somewhere down the evolution of the class the member will be "promoted" to either protected or private.

3) Classes that are fully fleshed out and have strict rules about their internals (ie they know exactly what they are doing, and you are not to "fuck" (technical term) with its internals) are given the class designation, default private members, and only a select few members are allowed to be public.

I find this approach allows me to avoid sitting there and religiously writing getter/setters when a lot of data members get migrated out, shifted around, etc. during the early stages of a class's evolution.

Sending and receiving UDP packets?

The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.

If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.

Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.

In the sender you set:

 byte [] IP= { (byte)192, (byte)168, 1, 106 };
 InetAddress address = InetAddress.getByAddress(IP);

but might be simpler to use the address in string form:

 InetAddress address = InetAddress.getByName("192.168.1.106");

In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.

Here's a simple UDP Receiver that works :

import java.io.IOException;
import java.net.*;

public class Receiver {

    public static void main(String[] args) {
        int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
        new Receiver().run(port);
    }

    public void run(int port) {    
      try {
        DatagramSocket serverSocket = new DatagramSocket(port);
        byte[] receiveData = new byte[8];
        String sendString = "polo";
        byte[] sendData = sendString.getBytes("UTF-8");

        System.out.printf("Listening on udp:%s:%d%n",
                InetAddress.getLocalHost().getHostAddress(), port);     
        DatagramPacket receivePacket = new DatagramPacket(receiveData,
                           receiveData.length);

        while(true)
        {
              serverSocket.receive(receivePacket);
              String sentence = new String( receivePacket.getData(), 0,
                                 receivePacket.getLength() );
              System.out.println("RECEIVED: " + sentence);
              // now send acknowledgement packet back to sender     
              DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                   receivePacket.getAddress(), receivePacket.getPort());
              serverSocket.send(sendPacket);
        }
      } catch (IOException e) {
              System.out.println(e);
      }
      // should close serverSocket in finally block
    }
}

jQuery Mobile how to check if button is disabled?

Faced with the same issue when trying to check if a button is disabled. I've tried a variety of approaches, such as btn.disabled, .is(':disabled'), .attr('disabled'), .prop('disabled'). But no one works for me.

Some, for example .disabled or .is(':disabled') returned undefined and other like .attr('disabled') returned the wrong result - false when the button was actually disabled.

But only one technique works for me: .is('[disabled]') (with square brackets).

So to determine if a button is disabled try this:

$("#myButton").is('[disabled]');

How do I close an Android alertdialog

If you already use positive and negative button (like I do in my project) you can use Neutral Button to close the dialog.

I also noticed that in Android version >5 the dialog is closed by clicking outside of dialog window but in older version this is not happening.

ad.setNeutralButton("CLOSE", new DialogInterface.OnClickListener(){
    @Override
    public void onClick(DialogInterface dialog, int which) {
        // close dialog
    }
});

How to load property file from classpath?

final Properties properties = new Properties();
try (final InputStream stream =
           this.getClass().getResourceAsStream("foo.properties")) {
    properties.load(stream);
    /* or properties.loadFromXML(...) */
}

Check if an excel cell exists on another worksheet in a column - and return the contents of a different column

You can use following formulas.

For Excel 2007 or later:

=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")

For Excel 2003:

=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))

Note, that

  • I'm using List!A:C in VLOOKUP and returns value from column ? 3
  • I'm using 4th argument for VLOOKUP equals to FALSE, in that case VLOOKUP will only find an exact match, and the values in the first column of List!A:C do not need to be sorted (opposite to case when you're using TRUE).

What is the difference between private and protected members of C++ classes?

Protected members can only be accessed by descendants of the class, and by code in the same module. Private members can only be accessed by the class they're declared in, and by code in the same module.

Of course friend functions throw this out the window, but oh well.

Setting graph figure size

The properties that can be set for a figure is referenced here.

You could then use:

figure_number = 1;
x      = 0;   % Screen position
y      = 0;   % Screen position
width  = 600; % Width of figure
height = 400; % Height of figure (by default in pixels)

figure(figure_number, 'Position', [x y width height]);

Oracle SQL query for Date format

to_date() returns a date at 00:00:00, so you need to "remove" the minutes from the date you are comparing to:

select * 
from table
where trunc(es_date) = TO_DATE('27-APR-12','dd-MON-yy')

You probably want to create an index on trunc(es_date) if that is something you are doing on a regular basis.

The literal '27-APR-12' can fail very easily if the default date format is changed to anything different. So make sure you you always use to_date() with a proper format mask (or an ANSI literal: date '2012-04-27')

Although you did right in using to_date() and not relying on implict data type conversion, your usage of to_date() still has a subtle pitfall because of the format 'dd-MON-yy'.

With a different language setting this might easily fail e.g. TO_DATE('27-MAY-12','dd-MON-yy') when NLS_LANG is set to german. Avoid anything in the format that might be different in a different language. Using a four digit year and only numbers e.g. 'dd-mm-yyyy' or 'yyyy-mm-dd'

How to pass a vector to a function?

If you use random instead of * random your code not give any error

NameError: global name 'unicode' is not defined - in Python 3

You can use the six library to support both Python 2 and 3:

import six
if isinstance(value, six.string_types):
    handle_string(value)

Should IBOutlets be strong or weak under ARC?

I don't see any problem with that. Pre-ARC, I've always made my IBOutlets assign, as they're already retained by their superviews. If you make them weak, you shouldn't have to nil them out in viewDidUnload, as you point out.

One caveat: You can support iOS 4.x in an ARC project, but if you do, you can't use weak, so you'd have to make them assign, in which case you'd still want to nil the reference in viewDidUnload to avoid a dangling pointer. Here's an example of a dangling pointer bug I've experienced:

A UIViewController has a UITextField for zip code. It uses CLLocationManager to reverse geocode the user's location and set the zip code. Here's the delegate callback:

-(void)locationManager:(CLLocationManager *)manager
   didUpdateToLocation:(CLLocation *)newLocation
          fromLocation:(CLLocation *)oldLocation {
    Class geocoderClass = NSClassFromString(@"CLGeocoder");
    if (geocoderClass && IsEmpty(self.zip.text)) {
        id geocoder = [[geocoderClass alloc] init];
        [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
            if (self.zip && IsEmpty(self.zip.text)) {
                self.zip.text = [[placemarks objectAtIndex:0] postalCode];
            }
        }];    
    }
    [self.locationManager stopUpdatingLocation];
}

I found that if I dismissed this view at the right time and didn't nil self.zip in viewDidUnload, the delegate callback could throw a bad access exception on self.zip.text.

How to add a button dynamically using jquery

Try this

function test()
{
   $("body").append("<input type='button' id='field' />");
}

How to make a text box have rounded corners?

You could use CSS to do that, but it wouldn't be supported in IE8-. You can use some site like http://borderradius.com to come up with actual CSS you'd use, which would look something like this (again, depending on how many browsers you're trying to support):

-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;

HTTP Status 404 - The requested resource (/) is not available

What are you expecting? The default Tomcat homepage? If so, you'll need to configure Eclipse to take control over from Tomcat.

Doubleclick the Tomcat server entry in the Servers tab, you'll get the server configuration. At the left column, under Server Locations, select Use Tomcat installation (note, when it is grayed out, read the section leading text! ;) ). This way Eclipse will take full control over Tomcat, this way you'll also be able to access the default Tomcat homepage with the Tomcat Manager when running from inside Eclipse. I only don't see how that's useful while developing using Eclipse.

enter image description here

The port number is not the problem. You would otherwise have gotten an exception in Tomcat's startup log and the browser would show a browser-specific "Connection timed out" error page (and thus not a Tomcat-specific error page which would impossibly be served when Tomcat was not up and running!)

How do I trim() a string in angularjs?

I insert this code in my tag and it works correctly:

ng-show="!Contract.BuyerName.trim()" >

Is it possible to center text in select box?

I have always gotten away with the following hack to get it to work with css only.

padding-left: 45%;
font-size: 50px;

padding will center the text and can be tweaked for the text size :)

This is obviously not 100% correct from a validation point of view I guess but it does the job :)

How to open a Bootstrap modal window using jQuery?

Try

$("#myModal").modal("toggle")

To open or close the modal with id myModal.

If the above is not working then it means bootstrap.js has been overridden by some other js file. Here is a solution

1:- Move bootstrap.js to the bottom so that it will override other js files.

2:- Make sure the order is like below

<script src="plugins/jQuery/jquery-2.2.3.min.js"></script>
<!-- Other js files -->
<script src="plugins/jQuery/bootstrap.min.js"></script>

Can I get "&&" or "-and" to work in PowerShell?

Very old question, but for the newcomers: maybe the PowerShell version (similar but not equivalent) that the question is looking for, is to use -and as follows:

(build_command) -and (run_tests_command)

MySQL server has gone away - in exactly 60 seconds

I have the same problem with mysqli. My solution is https://www.php.net/manual/en/mysqli.configuration.php

mysqli.reconnect = On

Fatal error: Call to undefined function mysql_connect() in C:\Apache\htdocs\test.php on line 2

Change the database.php file from

$db['default']['dbdriver'] = 'mysql';

to

$db['default']['dbdriver'] = 'mysqli';

How to watch for form changes in Angular

To complete a bit more previous great answers, you need to be aware that forms leverage observables to detect and handle value changes. It's something really important and powerful. Both Mark and dfsq described this aspect in their answers.

Observables allow not only to use the subscribe method (something similar to the then method of promises in Angular 1). You can go further if needed to implement some processing chains for updated data in forms.

I mean you can specify at this level the debounce time with the debounceTime method. This allows you to wait for an amount of time before handling the change and correctly handle several inputs:

this.form.valueChanges
    .debounceTime(500)
    .subscribe(data => console.log('form changes', data));

You can also directly plug the processing you want to trigger (some asynchronous one for example) when values are updated. For example, if you want to handle a text value to filter a list based on an AJAX request, you can leverage the switchMap method:

this.textValue.valueChanges
    .debounceTime(500)
    .switchMap(data => this.httpService.getListValues(data))
    .subscribe(data => console.log('new list values', data));

You even go further by linking the returned observable directly to a property of your component:

this.list = this.textValue.valueChanges
    .debounceTime(500)
    .switchMap(data => this.httpService.getListValues(data))
    .subscribe(data => console.log('new list values', data));

and display it using the async pipe:

<ul>
  <li *ngFor="#elt of (list | async)">{{elt.name}}</li>
</ul>

Just to say that you need to think the way to handle forms differently in Angular2 (a much more powerful way ;-)).

Hope it helps you, Thierry

New Intent() starts new instance with Android: launchMode="singleTop"

This should do the trick.

<activity ... android:launchMode="singleTop" />

When you create an intent to start the app use:

Intent intent= new Intent(context, YourActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);

This is that should be needed.

How to limit the number of selected checkboxes?

Try like this.

On change event,

$('input[type=checkbox]').on('change', function (e) {
    if ($('input[type=checkbox]:checked').length > 3) {
        $(this).prop('checked', false);
        alert("allowed only 3");
    }
});

Check this in JSFiddle

How can I change the color of a Google Maps marker?

enter image description here enter image description here Material Design

EDITED MARCH 2019 now with programmatic pin color,

PURE JAVASCRIPT, NO IMAGES, SUPPORTS LABELS

no longer relies on deprecated Charts API

    var pinColor = "#FFFFFF";
    var pinLabel = "A";

    // Pick your pin (hole or no hole)
    var pinSVGHole = "M12,11.5A2.5,2.5 0 0,1 9.5,9A2.5,2.5 0 0,1 12,6.5A2.5,2.5 0 0,1 14.5,9A2.5,2.5 0 0,1 12,11.5M12,2A7,7 0 0,0 5,9C5,14.25 12,22 12,22C12,22 19,14.25 19,9A7,7 0 0,0 12,2Z";
    var labelOriginHole = new google.maps.Point(12,15);
    var pinSVGFilled = "M 12,2 C 8.1340068,2 5,5.1340068 5,9 c 0,5.25 7,13 7,13 0,0 7,-7.75 7,-13 0,-3.8659932 -3.134007,-7 -7,-7 z";
    var labelOriginFilled =  new google.maps.Point(12,9);


    var markerImage = {  // https://developers.google.com/maps/documentation/javascript/reference/marker#MarkerLabel
        path: pinSVGFilled,
        anchor: new google.maps.Point(12,17),
        fillOpacity: 1,
        fillColor: pinColor,
        strokeWeight: 2,
        strokeColor: "white",
        scale: 2,
        labelOrigin: labelOriginFilled
    };
    var label = {
        text: pinLabel,
        color: "white",
        fontSize: "12px",
    }; // https://developers.google.com/maps/documentation/javascript/reference/marker#Symbol
    this.marker        = new google.maps.Marker({
        map: map.MapObject,
        //OPTIONAL: label: label,
        position: this.geographicCoordinates,
        icon: markerImage,
        //OPTIONAL: animation: google.maps.Animation.DROP,
    });

Format Float to n decimal places

public static double roundToDouble(float d, int decimalPlace) {
        BigDecimal bd = new BigDecimal(Float.toString(d));
        bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
        return bd.doubleValue();
    }

How can I run dos2unix on an entire directory?

As I happened to be poorly satisfied by dos2unix, I rolled out my own simple utility. Apart of a few advantages in speed and predictability, the syntax is also a bit simpler :

endlines unix *

And if you want it to go down into subdirectories (skipping hidden dirs and non-text files) :

endlines unix -r .

endlines is available here https://github.com/mdolidon/endlines

Compare two files and write it to "match" and "nomatch" files

I had used JCL about 2 years back so cannot write a code for you but here is the idea;

  1. Have 2 steps
  2. First step will have ICETOOl where you can write the matching records to matched file.
  3. Second you can write a file for mismatched by using SORT/ICETOOl or by just file operations.

again i apologize for solution without code, but i am out of touch by 2 yrs+

Hiding the R code in Rmarkdown/knit and just showing the results

Just aggregating the answers and expanding on the basics. Here are three options:

1) Hide Code (individual chunk)

We can include echo=FALSE in the chunk header:

```{r echo=FALSE}
plot(cars)
```

2) Hide Chunks (globally).

We can change the default behaviour of knitr using the knitr::opts_chunk$set function. We call this at the start of the document and include include=FALSE in the chunk header to suppress any output:

---
output: html_document
---

```{r include = FALSE}
knitr::opts_chunk$set(echo=FALSE)
```

```{r}
plot(cars)
```

3) Collapsed Code Chunks

For HTML outputs, we can use code folding to hide the code in the output file. It will still include the code but can only be seen once a user clicks on this. You can read about this further here.

---
output:
  html_document:
    code_folding: "hide"
---


```{r}
plot(cars)
```

enter image description here

VB.NET - Remove a characters from a String

The String class has a Replace method that will do that.

Dim clean as String
clean = myString.Replace(",", "")

Difference between Parameters.Add(string, object) and Parameters.AddWithValue

The difference is the implicit conversion when using AddWithValue. If you know that your executing SQL query (stored procedure) is accepting a value of type int, nvarchar, etc, there's no reason in re-declaring it in your code.

For complex type scenarios (example would be DateTime, float), I'll probably use Add since it's more explicit but AddWithValue for more straight-forward type scenarios (Int to Int).

show loading icon until the page is load?

Element making ajax call can call loading(targetElementId) method as below to put loading/icon in target div and it'll get over written by ajax results when ready. This works great for me.

<div style='display:none;'><div id="loading" class="divLoading"><p>Loading... <img src="loading_image.gif" /></p></div></div>
<script type="text/javascript">
function loading(id) {
    jQuery("#" + id).html(jQuery("#loading").html());
    jQuery("#" + id).show();
}

"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

I've been having the same issue for days now with an integration that also just "used to work before".

Out of sheer depression, I just tried

 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;

This solved it for me..even though the integration strictly only makes use of SSLv3.

I came to the realization that something if off since Fiddler reported saying that there is an "empty TLS negotiation cipher" or something of the like.

Hopefully it works!

Concept of void pointer in C programming

Is it possible to dereference the void pointer without type-casting in C programming language...

No, void indicates the absence of type, it is not something you can dereference or assign to.

is there is any way of generalizing a function which can receive pointer and store it in void pointer and by using that void pointer we can make a generalized function..

You cannot just dereference it in a portable way, as it may not be properly aligned. It may be an issue on some architectures like ARM, where pointer to a data type must be aligned at boundary of the size of data type (e.g. pointer to 32-bit integer must be aligned at 4-byte boundary to be dereferenced).

For example, reading uint16_t from void*:

/* may receive wrong value if ptr is not 2-byte aligned */
uint16_t value = *(uint16_t*)ptr;
/* portable way of reading a little-endian value */
uint16_t value = *(uint8_t*)ptr
                | ((*((uint8_t*)ptr+1))<<8);

Also, is pointer arithmetic with void pointers possible...

Pointer arithmetic is not possible on pointers of void due to lack of concrete value underneath the pointer and hence the size.

void* p = ...
void *p2 = p + 1; /* what exactly is the size of void?? */

The value violated the integrity constraints for the column

Delete empty rows from Excel after your last row of data!

Some times empty rows in Excel are still considered as data, therefore trying to import them in a table with one or more non nullable columns violates the constrains of the column.

Solution: select all of the empty rows on your sheet, even those after your last row of data, and click delete rows.

Obviously, if some of your data really does vioalte any of your table's constraints, then just fix your data to match the rules of your database..

PHP split alternative?

Had the same issue, but my code must work on both PHP 5 & PHP 7..

Here is my piece of code, which solved this.. Input a date in dmY format with one of delimiters "/ . -"

<?php
function DateToEN($date){
  if ($date!=""){
    list($d, $m, $y) = function_exists("split") ?  split("[/.-]", $date) : preg_split("/[\/\.\-]+/", $date);
    return $y."-".$m."-".$d;
  }else{
    return false;
  }
}
?>

How do I sort a Set to a List in Java?

I am using this code, which I find more practical than the accepted answer above:

List<Thing> thingList = new ArrayList<>(thingSet);
thingList.sort((thing1, thing2) -> thing1.getName().compareToIgnoreCase(thing2.getName()));

how to update the multiple rows at a time using linq to sql?

This is what I did:

EF:

using (var context = new SomeDBContext())
{
    foreach (var item in model.ShopItems)  // ShopItems is a posted list with values 
    {    
        var feature = context.Shop
                             .Where(h => h.ShopID == 123 && h.Type == item.Type).ToList();

        feature.ForEach(a => a.SortOrder = item.SortOrder);
    }

    context.SaveChanges();
}

Hope helps someone.

Python datetime strptime() and strftime(): how to preserve the timezone information

Try this:

import pytz
import datetime

fmt = '%Y-%m-%d %H:%M:%S %Z'

d = datetime.datetime.now(pytz.timezone("America/New_York"))
d_string = d.strftime(fmt)
d2 = pytz.timezone('America/New_York').localize(d.strptime(d_string,fmt), is_dst=None)
print(d_string)
print(d2.strftime(fmt))

Should 'using' directives be inside or outside the namespace?

According the to StyleCop Documentation:

SA1200: UsingDirectivesMustBePlacedWithinNamespace

Cause A C# using directive is placed outside of a namespace element.

Rule Description A violation of this rule occurs when a using directive or a using-alias directive is placed outside of a namespace element, unless the file does not contain any namespace elements.

For example, the following code would result in two violations of this rule.

using System;
using Guid = System.Guid;

namespace Microsoft.Sample
{
    public class Program
    {
    }
}

The following code, however, would not result in any violations of this rule:

namespace Microsoft.Sample
{
    using System;
    using Guid = System.Guid;

    public class Program
    {
    }
}

This code will compile cleanly, without any compiler errors. However, it is unclear which version of the Guid type is being allocated. If the using directive is moved inside of the namespace, as shown below, a compiler error will occur:

namespace Microsoft.Sample
{
    using Guid = System.Guid;
    public class Guid
    {
        public Guid(string s)
        {
        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            Guid g = new Guid("hello");
        }
    }
}

The code fails on the following compiler error, found on the line containing Guid g = new Guid("hello");

CS0576: Namespace 'Microsoft.Sample' contains a definition conflicting with alias 'Guid'

The code creates an alias to the System.Guid type called Guid, and also creates its own type called Guid with a matching constructor interface. Later, the code creates an instance of the type Guid. To create this instance, the compiler must choose between the two different definitions of Guid. When the using-alias directive is placed outside of the namespace element, the compiler will choose the local definition of Guid defined within the local namespace, and completely ignore the using-alias directive defined outside of the namespace. This, unfortunately, is not obvious when reading the code.

When the using-alias directive is positioned within the namespace, however, the compiler has to choose between two different, conflicting Guid types both defined within the same namespace. Both of these types provide a matching constructor. The compiler is unable to make a decision, so it flags the compiler error.

Placing the using-alias directive outside of the namespace is a bad practice because it can lead to confusion in situations such as this, where it is not obvious which version of the type is actually being used. This can potentially lead to a bug which might be difficult to diagnose.

Placing using-alias directives within the namespace element eliminates this as a source of bugs.

  1. Multiple Namespaces

Placing multiple namespace elements within a single file is generally a bad idea, but if and when this is done, it is a good idea to place all using directives within each of the namespace elements, rather than globally at the top of the file. This will scope the namespaces tightly, and will also help to avoid the kind of behavior described above.

It is important to note that when code has been written with using directives placed outside of the namespace, care should be taken when moving these directives within the namespace, to ensure that this is not changing the semantics of the code. As explained above, placing using-alias directives within the namespace element allows the compiler to choose between conflicting types in ways that will not happen when the directives are placed outside of the namespace.

How to Fix Violations To fix a violation of this rule, move all using directives and using-alias directives within the namespace element.

How to dock "Tool Options" to "Toolbox"?

In the detached window (Tool Options), the name of the view (Paintbrush) is a grab-bar.

Put your cursor over the grab-bar, click and drag it to the dock area in the main window in order to reattach it to the main window.

100% width table overflowing div container

Add display: block; and overflow: auto; to .my-table. This will simply cut off anything past the 280px limit you enforced. There's no way to make it "look pretty" with that requirement due to words like pélagosthrough which are wider than 280px.

Multiple inputs on one line

Yes, you can.

From cplusplus.com:

Because these functions are operator overloading functions, the usual way in which they are called is:

   strm >> variable;

Where strm is the identifier of a istream object and variable is an object of any type supported as right parameter. It is also possible to call a succession of extraction operations as:

   strm >> variable1 >> variable2 >> variable3; //...

which is the same as performing successive extractions from the same object strm.

Just replace strm with cin.

Insert data into hive table

If you already have a table pre_loaded_tbl with some data. You can use a trick to load the data into your table with following query

INSERT INTO TABLE tweet_table 
  SELECT  "my_data" AS my_column 
    FROM   pre_loaded_tbl 
   LIMIT   5;

Also please note that "my_data" is independent of any data in the pre_loaded_tbl. You can select any data and write any column name (here my_data and my_column). Hive does not require it to have same column name. However structure of select statement should be same as that of your tweet_table. You can use limit to determine how many times you can insert into the tweet_table.

However if you haven't' created any table, you will have to load the data using file copy or load data commands in above answers.

Which terminal command to get just IP address and nothing else?

On latest Ubuntu versions (14.04 - 16.04), this command did the trick for me.

hostname -I | awk '{print $1}'

How to get a resource id with a known resource name?

In Kotlin following works fine for me:

val id = resources.getIdentifier("your_resource_name", "drawable", context?.getPackageName())

If resource is place in mipmap folder, you can use parameter "mipmap" instead of "drawable".

Is there a typescript List<> and/or Map<> class/library?

Did they add a runtime List<> and/or Map<> type class to typepad 1.0

No, providing a runtime is not the focus of the TypeScript team.

is there a solid library out there someone wrote that provides this functionality?

I wrote (really just ported over buckets to typescript): https://github.com/basarat/typescript-collections

Update

JavaScript / TypeScript now support this natively and you can enable them with lib.d.ts : https://basarat.gitbooks.io/typescript/docs/types/lib.d.ts.html along with a polyfill if you want

Change bar plot colour in geom_bar with ggplot2 in r

If you want all the bars to get the same color (fill), you can easily add it inside geom_bar.

ggplot(data=df, aes(x=c1+c2/2, y=c3)) + 
geom_bar(stat="identity", width=c2, fill = "#FF6666")

enter image description here

Add fill = the_name_of_your_var inside aes to change the colors depending of the variable :

c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2)

enter image description here

Use scale_fill_manual() if you want to manually the change of colors.

ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2) + 
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))

enter image description here

How to check if the request is an AJAX request with PHP

There is no sure-fire way of knowing that a request was made via Ajax. You can never trust data coming from the client. You could use a couple of different methods but they can be easily overcome by spoofing.

JavaScript: filter() for Objects

Plain ES6:

var foo = {
    bar: "Yes"
};

const res = Object.keys(foo).filter(i => foo[i] === 'Yes')

console.log(res)
// ["bar"]

MySQL: Can't create/write to file '/tmp/#sql_3c6_0.MYI' (Errcode: 2) - What does it even mean?

Often this means your /tmp partition has run out of space and the file can't be created, or for whatever reason the mysqld process cannot write to that directory because of permission problems. Sometimes this is the case when selinux rains on your parade.

Any operation that requites a "temp file" will go into the /tmp directory by default. The name you're seeing is just some internal random name.

How to use document.getElementByName and getElementByTag?

If you have given same text name for both of your Id and Name properties you can give like document.getElementByName('frmMain')[index] other wise object required error will come.And if you have only one table in your page you can use document.getElementBytag('table')[index].

EDIT:

You can replace the index according to your form, if its first form place 0 for index.

java.io.IOException: Invalid Keystore format

Your keystore is broken, and you will have to restore or regenerate it.

Trim spaces from end of a NSString

Another solution involves creating mutable string:

//make mutable string
NSMutableString *stringToTrim = [@" i needz trim " mutableCopy];

//pass it by reference to CFStringTrimSpace
CFStringTrimWhiteSpace((__bridge CFMutableStringRef) stringToTrim);

//stringToTrim is now "i needz trim"

Convert object string to JSON

I put my answer for someone who are interested in this old thread.

I created the HTML5 data-* parser for jQuery plugin and demo which convert a malformed JSON string into a JavaScript object without using eval().

It can pass the HTML5 data-* attributes bellow:

<div data-object='{"hello":"world"}'></div>
<div data-object="{hello:'world'}"></div>
<div data-object="hello:world"></div>

into the object:

{
    hello: "world"
}

How to convert JSON data into a Python object

Since noone provided an answer quite like mine, I am going to post it here.

It is a robust class that can easily convert back and forth between json str and dict that I have copied from my answer to another question:

import json

class PyJSON(object):
    def __init__(self, d):
        if type(d) is str:
            d = json.loads(d)

        self.from_dict(d)

    def from_dict(self, d):
        self.__dict__ = {}
        for key, value in d.items():
            if type(value) is dict:
                value = PyJSON(value)
            self.__dict__[key] = value

    def to_dict(self):
        d = {}
        for key, value in self.__dict__.items():
            if type(value) is PyJSON:
                value = value.to_dict()
            d[key] = value
        return d

    def __repr__(self):
        return str(self.to_dict())

    def __setitem__(self, key, value):
        self.__dict__[key] = value

    def __getitem__(self, key):
        return self.__dict__[key]

json_str = """... json string ..."""

py_json = PyJSON(json_str)

How do I keep the screen on in my App?

You need to use Power Manager to acquire a wake lock in your application.

Most probably you are interested in a FULL_WAKE_LOCK:

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag");
wl.acquire();
....
wl.release();

How do you generate a random double uniformly distributed between 0 and 1 from C++?

This is what I ended up using for my needs:

int range_upper_bound = 12345;
int random_number =((double)rand()/(double)range_upper_bound);

Create normal zip file programmatically

This can be done by adding a reference to System.IO.Compression and System.IO.Compression.Filesystem.

A sample createZipFile() method may look as following:

public static void createZipFile(string inputfile, string outputfile, CompressionLevel compressionlevel)
        {
            try
            {
                using (ZipArchive za = ZipFile.Open(outputfile, ZipArchiveMode.Update))
                {
                    //using the same file name as entry name
                    za.CreateEntryFromFile(inputfile, inputfile);
                }
            }
            catch (ArgumentException)
            {
                Console.WriteLine("Invalid input/output file.");
                Environment.Exit(-1);
            }
}

where

  • inputfile= string with the file name to be compressed (for this example, you have to add the extension)
  • outputfile= string with the destination zip file name

More details about ZipFile Class in MSDN

MySQL combine two columns into one column

I have used this way and Its a best forever. In this code null also handled

SELECT Title,
FirstName,
lastName, 
ISNULL(Title,'') + ' ' + ISNULL(FirstName,'') + ' ' + ISNULL(LastName,'') as FullName 
FROM Customer

Try this...

Java JDBC connection status

The low-cost method, regardless of the vendor implementation, would be to select something from the process memory or the server memory, like the DB version or the name of the current database. IsClosed is very poorly implemented.

Example:

java.sql.Connection conn = <connect procedure>;
conn.close();
try {
  conn.getMetaData();
} catch (Exception e) {
  System.out.println("Connection is closed");
}

Chrome dev tools fails to show response even the content returned has header Content-Type:text/html; charset=UTF-8

another possibility is that the server does not handle the OPTIONS request.

How do I keep Python print from adding newlines or spaces?

In python 2.6:

>>> print 'h','m','h'
h m h
>>> from __future__ import print_function
>>> print('h',end='')
h>>> print('h',end='');print('m',end='');print('h',end='')
hmh>>>
>>> print('h','m','h',sep='');
hmh
>>>

So using print_function from __future__ you can set explicitly the sep and end parameteres of print function.

What's the best way to determine the location of the current PowerShell script?

function func1() 
{
   $inv = (Get-Variable MyInvocation -Scope 1).Value
   #$inv.MyCommand | Format-List *   
   $Path1 = Split-Path $inv.scriptname
   Write-Host $Path1
}

function Main()
{
    func1
}

Main

Redirect stdout to a file in Python?

import sys
sys.stdout = open('stdout.txt', 'w')

Java path..Error of jvm.cfg

I had same problem - when I tried to run a Java program from command line the error message appeared: "Error: could not open jvm.cfg". My Path environment variable included following path:

C:\ProgramData\Oracle\Java\javapath 

In the folder there were 3 exe files:

java.exe
javaw.exe
javaws.exe

When I removed the the entry

C:\ProgramData\Oracle\Java\javapath

from the Path environment variable and restarted cmd, I could run the program as usual (java MyProg). Obviously I have corrupted the path pointing to correct java jre installation

C:\Program Files\Java\jre1.8.0_151

somehow previously when I played with my settings.

'POCO' definition

"Plain Old C# Object"

Just a normal class, no attributes describing infrastructure concerns or other responsibilities that your domain objects shouldn't have.

EDIT - as other answers have stated, it is technically "Plain Old CLR Object" but I, like David Arno comments, prefer "Plain Old Class Object" to avoid ties to specific languages or technologies.

TO CLARIFY: In other words, they don’t derive from some special base class, nor do they return any special types for their properties.

See below for an example of each.

Example of a POCO:

public class Person
{
    public string Name { get; set; }

    public int Age { get; set; }
}

Example of something that isn’t a POCO:

public class PersonComponent : System.ComponentModel.Component
{
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    public string Name { get; set; }

    public int Age { get; set; }
}

The example above both inherits from a special class to give it additional behavior as well as uses a custom attribute to change behavior… the same properties exist on both classes, but one is not just a plain old object anymore.

How to read json file into java with simple JSON library

your json file look like this

enter image description here

import java.io.*;
import java.util.*;
import org.json.simple.*;
import org.json.simple.parser.*;
public class JSONReadFromTheFileTest {
   public static void main(String[] args) {
      JSONParser parser = new JSONParser();
      try {
         Object obj = parser.parse(new FileReader("/Users/User/Desktop/course.json"));
         JSONObject jsonObject = (JSONObject)obj;
         String name = (String)jsonObject.get("Name");
         String course = (String)jsonObject.get("Course");
         JSONArray subjects = (JSONArray)jsonObject.get("Subjects");
         System.out.println("Name: " + name);
         System.out.println("Course: " + course);
         System.out.println("Subjects:");
         Iterator iterator = subjects.iterator();
         while (iterator.hasNext()) {
            System.out.println(iterator.next());
         }
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}

the output is

Name: Raja
Course: MCA
Subjects:
subject1: MIS
subject2: DBMS
subject3: UML

took it from here

undefined reference to WinMain@16 (codeblocks)

Well I know this answer is not an experienced programmer's approach and of an Old It consultant , but it worked for me .

the answer is "TRY TURNING IT ON AND OFF" . restart codeblocks and it works well reminds me of the 2006 comedy show It Crowd .

Common HTTPclient and proxy

Starting from Apache HTTPComponents 4.3.x HttpClientBuilder class sets the proxy defaults from System properties http.proxyHost and http.proxyPort or else you can override them using setProxy method.

Using ZXing to create an Android barcode scanning app

I had a problem with implementing the code until I found some website (I can't find it again right now) that explained that you need to include the package name in the name of the intent.putExtra.

It would pull up the application, but it wouldn't recognize any barcodes, and when I changed it from.

intent.putExtra("SCAN_MODE", "QR_CODE_MODE");

to

intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE");

It worked great. Just a tip for any other novice Android programmers.

Catch checked change event of a checkbox

For JQuery 1.7+ use:

$('input[type=checkbox]').on('change', function() {
  ...
});

How to use clock() in C++

#include <iostream>
#include <cstdio>
#include <ctime>

int main() {
    std::clock_t start;
    double duration;

    start = std::clock();

    /* Your algorithm here */

    duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;

    std::cout<<"printf: "<< duration <<'\n';
}

Iterating over every property of an object in javascript using Prototype?

You have to first convert your object literal to a Prototype Hash:

// Store your object literal
var obj = {foo: 1, bar: 2, barobj: {75: true, 76: false, 85: true}}

// Iterate like so.  The $H() construct creates a prototype-extended Hash.
$H(obj).each(function(pair){
  alert(pair.key);
  alert(pair.value);
});

Switch to another Git tag

As of Git v2.23.0 (August 2019), git switch is preferred over git checkout when you’re simply switching branches/tags. I’m guessing they did this since git checkout had two functions: for switching branches and for restoring files. So in v2.23.0, they added two new commands, git switch, and git restore, to separate those concerns. I would predict at some point in the future, git checkout will be deprecated.

To switch to a normal branch, use git switch <branch-name>. To switch to a commit-like object, including single commits and tags, use git switch --detach <commitish>, where <commitish> is the tag name or commit number.

The --detach option forces you to recognize that you’re in a mode of “inspection and discardable experiments”. To create a new branch from the commitish you’re switching to, use git switch -c <new-branch> <start-point>.

Checkout Jenkins Pipeline Git SCM with credentials?

For what it's worth adding to the discussion... what I did that ended up helping me... Since the pipeline is run within a workspace within a docker image that is cleaned up each time it runs. I grabbed the credentials needed to perform necessary operations on the repo within my pipeline and stored them in a .netrc file. this allowed me to authorize the git repo operations successfully.

withCredentials([usernamePassword(credentialsId: '<credentials-id>', passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {
    sh '''
        printf "machine github.com\nlogin $GIT_USERNAME\n password $GIT_PASSWORD" >> ~/.netrc
        // continue script as necessary working with git repo...
    '''
}

Macro to Auto Fill Down to last adjacent cell

Untested....but should work.

Dim lastrow as long

lastrow = range("D65000").end(xlup).Row

ActiveCell.FormulaR1C1 = _
        "=IF(MONTH(RC[-1])>3,"" ""&YEAR(RC[-1])&""-""&RIGHT(YEAR(RC[-1])+1,2),"" ""&YEAR(RC[-1])-1&""-""&RIGHT(YEAR(RC[-1]),2))"
    Selection.AutoFill Destination:=Range("E2:E" & lastrow)
    'Selection.AutoFill Destination:=Range("E2:E"& lastrow)
    Range("E2:E1344").Select

Only exception being are you sure your Autofill code is perfect...

How to align content of a div to the bottom

Relative+absolute positioning is your best bet:

_x000D_
_x000D_
#header {_x000D_
  position: relative;_x000D_
  min-height: 150px;_x000D_
}_x000D_
_x000D_
#header-content {_x000D_
  position: absolute;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
}_x000D_
_x000D_
#header, #header * {_x000D_
  background: rgba(40, 40, 100, 0.25);_x000D_
}
_x000D_
<div id="header">_x000D_
  <h1>Title</h1>_x000D_
  <div id="header-content">Some content</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

But you may run into issues with that. When I tried it I had problems with dropdown menus appearing below the content. It's just not pretty.

Honestly, for vertical centering issues and, well, any vertical alignment issues with the items aren't fixed height, it's easier just to use tables.

Example: Can you do this HTML layout without using tables?

How do I get the type of a variable?

You can use the typeid operator:

#include <typeinfo>
...
cout << typeid(variable).name() << endl;

c# - approach for saving user settings in a WPF application?

Update: Nowadays I would use JSON.

I also prefer to go with serialization to file. XML files fits mostly all requirements. You can use the ApplicationSettings build in but those have some restrictions and a defined but (for me) very strange behavior where they stored. I used them a lot and they work. But if you want to have full control how and where they stored I use another approach.

  1. Make a class Somewhere with all your settings. I named it MySettings
  2. Implement Save and Read for persistence
  3. Use them in you application-code

Advantages:

  • Very Simple approach.
  • One Class for Settings. Load. Save.
  • All your Settings are type safe.
  • You can simplify or extend the logic to your needs (Versioning, many Profiles per User, etc.)
  • It works very well in any case (Database, WinForms, WPF, Service, etc...)
  • You can define where to store the XML files.
  • You can find them and manipulate them either by code or manual
  • It works for any deployment method I can imagine.

Disadvantages: - You have to think about where to store your settings files. (But you can just use your installation folder)

Here is a simple example (not tested)-

public class MySettings
{
    public string Setting1 { get; set; }
    public List<string> Setting2 { get; set; }

    public void Save(string filename)
    {
        using (StreamWriter sw = new StreamWriter(filename))
        {
            XmlSerializer xmls = new XmlSerializer(typeof(MySettings));
            xmls.Serialize(sw, this);
        }
    }
    public MySettings Read(string filename)
    {
        using (StreamReader sw = new StreamReader(filename))
        {
            XmlSerializer xmls = new XmlSerializer(typeof(MySettings));
            return xmls.Deserialize(sw) as MySettings;
        }
    }
}

And here is how to use it. It's possible to load default values or override them with the user's settings by just checking if user settings exist:

public class MyApplicationLogic
{
    public const string UserSettingsFilename = "settings.xml";
    public string _DefaultSettingspath = 
        Assembly.GetEntryAssembly().Location + 
        "\\Settings\\" + UserSettingsFilename;

    public string _UserSettingsPath = 
        Assembly.GetEntryAssembly().Location + 
        "\\Settings\\UserSettings\\" + 
        UserSettingsFilename;

    public MyApplicationLogic()
    {
        // if default settings exist
        if (File.Exists(_UserSettingsPath))
            this.Settings = Settings.Read(_UserSettingsPath);
        else
            this.Settings = Settings.Read(_DefaultSettingspath);
    }
    public MySettings Settings { get; private set; }

    public void SaveUserSettings()
    {
        Settings.Save(_UserSettingsPath);
    }
}

maybe someone get's inspired by this approach. This is how I do it now for many years and I'm quite happy with that.

How do I resolve "Cannot find module" error using Node.js?

npm install --save module_name

For example, if the error is:

{ [Error: Cannot find module '/root/.npm/form-data'] code: 'MODULE_NOT_FOUND' }

then you can resolve this issue by executing the command npm install --save form-data.

Python error "ImportError: No module named"

I solved my own problem, and I will write a summary of the things that were wrong and the solution:

The file needs to be called exactly __init__.py. If the extension is different such as in my case .py.bin then Python cannot move through the directories and then it cannot find the modules. To edit the files you need to use a Linux editor, such as vi or nano. If you use a Windows editor this will write some hidden characters.

Another problem that was affecting it was that I had another Python version installed by the root, so if someone is working with a local installation of python, be sure that the Python installation that is running the programs is the local Python. To check this, just do which python, and see if the executable is the one that is in your local directory. If not, change the path, but be sure that the local Python directory is before than the other Python.

CodeIgniter: Create new helper?

Well for me only works adding the text "_helper" after in the php file like:

Codeiginiter Helpers

And to load automatically the helper in the folder aplication -> file autoload.php add in the array helper's the name without "_helper" like:

$autoload['helper'] = array('comunes');

And with that I can use all the helper's functions

Are parameters in strings.xml possible?

Yes, just format your strings in the standard String.format() way.

See the method Context.getString(int, Object...) and the Android or Java Formatter documentation.

In your case, the string definition would be:

<string name="timeFormat">%1$d minutes ago</string>

Change DIV content using ajax, php and jQuery

<script>

function getSummary(id)
{
   $.ajax({

     type: "GET",
     url: 'Your URL',
     data: "id=" + id, // appears as $_GET['id'] @ your backend side
     success: function(data) {
           // data is ur summary
          $('#summary').html(data);
     }

   });

}
</script>

And add onclick event in your lists

<a onclick="getSummary('1')">View Text</a>
<div id="#summary">This text will be replaced when the onclick event (link is clicked) is triggered.</div>

Load CSV file with Spark

Now, there's also another option for any general csv file: https://github.com/seahboonsiew/pyspark-csv as follows:

Assume we have the following context

sc = SparkContext
sqlCtx = SQLContext or HiveContext

First, distribute pyspark-csv.py to executors using SparkContext

import pyspark_csv as pycsv
sc.addPyFile('pyspark_csv.py')

Read csv data via SparkContext and convert it to DataFrame

plaintext_rdd = sc.textFile('hdfs://x.x.x.x/blah.csv')
dataframe = pycsv.csvToDataFrame(sqlCtx, plaintext_rdd)

Show space, tab, CRLF characters in editor of Visual Studio

The shortcut didn't work for me in Visual Studio 2015, also it was not in the edit menu.

Download and install the Productivity Power Tools for VS2015 and than you can find these options in the edit > advanced menu.

The best way to remove duplicate values from NSMutableArray in Objective-C?

need order

NSArray *yourarray = @[@"a",@"b",@"c"];
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:yourarray];
NSArray *arrayWithoutDuplicates = [orderedSet array];
NSLog(@"%@",arrayWithoutDuplicates);

or don't need order

NSSet *set = [NSSet setWithArray:yourarray];
NSArray *arrayWithoutOrder = [set allObjects];
NSLog(@"%@",arrayWithoutOrder);

How do you make websites with Java?

Also be advised, that while Java is in general very beginner friendly, getting into JavaEE, Servlets, Facelets, Eclipse integration, JSP and getting everything in Tomcat up and running is not. Certainly not the easiest way to build a website and probably way overkill for most things.

On top of that you may need to host your website yourself, because most webspace providers don't provide Servlet Containers. If you just want to check it out for fun, I would try Ruby or Python, which are much more cooler things to fiddle around with. But anyway, to provide at least something relevant to the question, here's a nice Servlet tutorial: link

How to send file contents as body entity using cURL

I believe you're looking for the @filename syntax, e.g.:

strip new lines

curl --data "@/path/to/filename" http://...

keep new lines

curl --data-binary "@/path/to/filename" http://...

curl will strip all newlines from the file. If you want to send the file with newlines intact, use --data-binary in place of --data

How do I find out what all symbols are exported from a shared object?

see man nm

GNU nm lists the symbols from object files objfile.... If no object files are listed as arguments, nm assumes the file a.out.

How to get the list of files in a directory in a shell script?

Just enter this simple command:

ls -d */

Select distinct rows from datatable in Linq

Like this: (Assuming a typed dataset)

someTable.Select(r => new { r.attribute1_name, r.attribute2_name }).Distinct();

When saving, how can you check if a field has changed?

If you are using a form, you can use Form's changed_data (docs):

class AliasForm(ModelForm):

    def save(self, commit=True):
        if 'remote_image' in self.changed_data:
            # do things
            remote_image = self.cleaned_data['remote_image']
            do_things(remote_image)
        super(AliasForm, self).save(commit)

    class Meta:
        model = Alias

Two statements next to curly brace in an equation

You can try the cases env in amsmath.

\documentclass{article}
\usepackage{amsmath}

\begin{document}

\begin{equation}
  f(x)=\begin{cases}
    1, & \text{if $x<0$}.\\
    0, & \text{otherwise}.
  \end{cases}
\end{equation}

\end{document}

amsmath cases

How does paintComponent work?

Two things you can do here:

  1. Read Painting in AWT and Swing
  2. Use a debugger and put a breakpoint in the paintComponent method. Then travel up the stacktrace and see how provides the Graphics parameter.

Just for info, here is the stacktrace that I got from the example of code I posted at the end:

Thread [AWT-EventQueue-0] (Suspended (breakpoint at line 15 in TestPaint))  
    TestPaint.paintComponent(Graphics) line: 15 
    TestPaint(JComponent).paint(Graphics) line: 1054    
    JPanel(JComponent).paintChildren(Graphics) line: 887    
    JPanel(JComponent).paint(Graphics) line: 1063   
    JLayeredPane(JComponent).paintChildren(Graphics) line: 887  
    JLayeredPane(JComponent).paint(Graphics) line: 1063 
    JLayeredPane.paint(Graphics) line: 585  
    JRootPane(JComponent).paintChildren(Graphics) line: 887 
    JRootPane(JComponent).paintToOffscreen(Graphics, int, int, int, int, int, int) line: 5228   
    RepaintManager$PaintManager.paintDoubleBuffered(JComponent, Image, Graphics, int, int, int, int) line: 1482 
    RepaintManager$PaintManager.paint(JComponent, JComponent, Graphics, int, int, int, int) line: 1413  
    RepaintManager.paint(JComponent, JComponent, Graphics, int, int, int, int) line: 1206   
    JRootPane(JComponent).paint(Graphics) line: 1040    
    GraphicsCallback$PaintCallback.run(Component, Graphics) line: 39    
    GraphicsCallback$PaintCallback(SunGraphicsCallback).runOneComponent(Component, Rectangle, Graphics, Shape, int) line: 78    
    GraphicsCallback$PaintCallback(SunGraphicsCallback).runComponents(Component[], Graphics, int) line: 115 
    JFrame(Container).paint(Graphics) line: 1967    
    JFrame(Window).paint(Graphics) line: 3867   
    RepaintManager.paintDirtyRegions(Map<Component,Rectangle>) line: 781    
    RepaintManager.paintDirtyRegions() line: 728    
    RepaintManager.prePaintDirtyRegions() line: 677 
    RepaintManager.access$700(RepaintManager) line: 59  
    RepaintManager$ProcessingRunnable.run() line: 1621  
    InvocationEvent.dispatch() line: 251    
    EventQueue.dispatchEventImpl(AWTEvent, Object) line: 705    
    EventQueue.access$000(EventQueue, AWTEvent, Object) line: 101   
    EventQueue$3.run() line: 666    
    EventQueue$3.run() line: 664    
    AccessController.doPrivileged(PrivilegedAction<T>, AccessControlContext) line: not available [native method]    
    ProtectionDomain$1.doIntersectionPrivilege(PrivilegedAction<T>, AccessControlContext, AccessControlContext) line: 76    
    EventQueue.dispatchEvent(AWTEvent) line: 675    
    EventDispatchThread.pumpOneEventForFilters(int) line: 211   
    EventDispatchThread.pumpEventsForFilter(int, Conditional, EventFilter) line: 128    
    EventDispatchThread.pumpEventsForHierarchy(int, Conditional, Component) line: 117   
    EventDispatchThread.pumpEvents(int, Conditional) line: 113  
    EventDispatchThread.pumpEvents(Conditional) line: 105   
    EventDispatchThread.run() line: 90  

The Graphics parameter comes from here:

RepaintManager.paintDirtyRegions(Map) line: 781 

The snippet involved is the following:

Graphics g = JComponent.safelyGetGraphics(
                        dirtyComponent, dirtyComponent);
                // If the Graphics goes away, it means someone disposed of
                // the window, don't do anything.
                if (g != null) {
                    g.setClip(rect.x, rect.y, rect.width, rect.height);
                    try {
                        dirtyComponent.paint(g); // This will eventually call paintComponent()
                    } finally {
                        g.dispose();
                    }
                }

If you take a look at it, you will see that it retrieve the graphics from the JComponent itself (indirectly with javax.swing.JComponent.safelyGetGraphics(Component, Component)) which itself takes it eventually from its first "Heavyweight parent" (clipped to the component bounds) which it self takes it from its corresponding native resource.

Regarding the fact that you have to cast the Graphics to a Graphics2D, it just happens that when working with the Window Toolkit, the Graphics actually extends Graphics2D, yet you could use other Graphics which do "not have to" extends Graphics2D (it does not happen very often but AWT/Swing allows you to do that).

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

class TestPaint extends JPanel {

    public TestPaint() {
        setBackground(Color.WHITE);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawOval(0, 0, getWidth(), getHeight());
    }

    public static void main(String[] args) {
        JFrame jFrame = new JFrame();
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jFrame.setSize(300, 300);
        jFrame.add(new TestPaint());
        jFrame.setVisible(true);
    }
}

How to return a file using Web API?

Better to return HttpResponseMessage with StreamContent inside of it.

Here is example:

public HttpResponseMessage GetFile(string id)
{
    if (String.IsNullOrEmpty(id))
        return Request.CreateResponse(HttpStatusCode.BadRequest);

    string fileName;
    string localFilePath;
    int fileSize;

    localFilePath = getFileFromID(id, out fileName, out fileSize);

    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
    response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
    response.Content.Headers.ContentDisposition.FileName = fileName;
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

    return response;
}

UPD from comment by patridge: Should anyone else get here looking to send out a response from a byte array instead of an actual file, you're going to want to use new ByteArrayContent(someData) instead of StreamContent (see here).

Remove table row after clicking table row delete button

As @gaurang171 mentioned, we can use .closest() which will return the first ancestor, or the closest to our delete button, and use .remove() to remove it.

This is how we can implement it using jQuery click event instead of using JavaScript onclick.

HTML:

<table id="myTable">
<tr>
  <th width="30%" style="color:red;">ID</th>
  <th width="25%" style="color:red;">Name</th>
  <th width="25%" style="color:red;">Age</th>
  <th width="1%"></th>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-001</td>
  <td width="25%" style="color:red;">Ben</td>
  <td width="25%" style="color:red;">25</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-002</td>
  <td width="25%" style="color:red;">Anderson</td>
  <td width="25%" style="color:red;">47</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-003</td>
  <td width="25%" style="color:red;">Rocky</td>
  <td width="25%" style="color:red;">32</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-004</td>
  <td width="25%" style="color:red;">Lee</td>
  <td width="25%" style="color:red;">15</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>
                            

jQuery

 $(document).ready(function(){
     $("#myTable").on('click','.btnDelete',function(){
         $(this).closest('tr').remove();
      });
  });

Try in JSFiddle: click here.

What is the relative performance difference of if/else versus switch statement in Java?

That's micro optimization and premature optimization, which are evil. Rather worry about readabililty and maintainability of the code in question. If there are more than two if/else blocks glued together or its size is unpredictable, then you may highly consider a switch statement.

Alternatively, you can also grab Polymorphism. First create some interface:

public interface Action { 
    void execute(String input);
}

And get hold of all implementations in some Map. You can do this either statically or dynamically:

Map<String, Action> actions = new HashMap<String, Action>();

Finally replace the if/else or switch by something like this (leaving trivial checks like nullpointers aside):

actions.get(name).execute(input);

It might be microslower than if/else or switch, but the code is at least far better maintainable.

As you're talking about webapplications, you can make use of HttpServletRequest#getPathInfo() as action key (eventually write some more code to split the last part of pathinfo away in a loop until an action is found). You can find here similar answers:

If you're worrying about Java EE webapplication performance in general, then you may find this article useful as well. There are other areas which gives a much more performance gain than only (micro)optimizing the raw Java code.

getDate with Jquery Datepicker

Instead of parsing day, month and year you can specify date formats directly using datepicker's formatDate function. In my example I am using "yy-mm-dd", but you can use any format of your choice.

$("#datepicker").datepicker({
    dateFormat: 'yy-mm-dd',
    inline: true,
    minDate: new Date(2010, 1 - 1, 1),
    maxDate: new Date(2010, 12 - 1, 31),
    altField: '#datepicker_value',
    onSelect: function(){
        var fullDate = $.datepicker.formatDate("yy-mm-dd", $(this).datepicker('getDate'));
        var str_output = "<h1><center><img src=\"/images/a" + fullDate +".png\"></center></h1><br/><br>";
        $('#page_output').html(str_output);
    }
});

Remove Android App Title Bar

in the graphical layout, you can choose the theme on the toolbar. (the one that looks like a star).

choose the NoTitleBar and have fun.

Better way to call javascript function in a tag

Some advantages to the second option:

  1. You can use this inside onclick to reference the anchor itself (doing the same in option 1 will give you window instead).

  2. You can set the href to a non-JS compatible URL to support older browsers (or those that have JS disabled); browsers that support JavaScript will execute the function instead (to stay on the page you have to use onclick="return someFunction();" and return false from inside the function or onclick="return someFunction(); return false;" to prevent default action).

  3. I've seen weird stuff happen when using href="javascript:someFunction()" and the function returns a value; the whole page would get replaced by just that value.

Pitfalls

Inline code:

  1. Runs in document scope as opposed to code defined inside <script> tags which runs in window scope; therefore, symbols may be resolved based on an element's name or id attribute, causing the unintended effect of attempting to treat an element as a function.

  2. Is harder to reuse; delicate copy-paste is required to move it from one project to another.

  3. Adds weight to your pages, whereas external code files can be cached by the browser.

Calculating distance between two points (Latitude, Longitude)

Create Function [dbo].[DistanceKM] 
( 
      @Lat1 Float(18),  
      @Lat2 Float(18), 
      @Long1 Float(18), 
      @Long2 Float(18)
)
Returns Float(18)
AS
Begin
      Declare @R Float(8); 
      Declare @dLat Float(18); 
      Declare @dLon Float(18); 
      Declare @a Float(18); 
      Declare @c Float(18); 
      Declare @d Float(18);
      Set @R =  6367.45
            --Miles 3956.55  
            --Kilometers 6367.45 
            --Feet 20890584 
            --Meters 6367450 


      Set @dLat = Radians(@lat2 - @lat1);
      Set @dLon = Radians(@long2 - @long1);
      Set @a = Sin(@dLat / 2)  
                 * Sin(@dLat / 2)  
                 + Cos(Radians(@lat1)) 
                 * Cos(Radians(@lat2))  
                 * Sin(@dLon / 2)  
                 * Sin(@dLon / 2); 
      Set @c = 2 * Asin(Min(Sqrt(@a))); 

      Set @d = @R * @c; 
      Return @d; 

End
GO

Usage:

select dbo.DistanceKM(37.848832506474, 37.848732506474, 27.83935546875, 27.83905546875)

Outputs:

0,02849639

You can change @R parameter with commented floats.

git: Switch branch and ignore any changes without committing

None of these answers helped me because I still had untracked files even after reset and stash. I had to do:

git reset --hard HEAD
git clean -d -f

Generic type conversion FROM string

public class TypedProperty<T> : Property
{
    public T TypedValue
    {
        get { return (T)(object)base.Value; }
        set { base.Value = value.ToString();}
    }
}

I using converting via an object. It is a little bit simpler.

Capture the Screen into a Bitmap

If using the .NET 2.0 (or later) framework you can use the CopyFromScreen() method detailed here:

http://www.geekpedia.com/tutorial181_Capturing-screenshots-using-Csharp.html

//Create a new bitmap.
var bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
                               Screen.PrimaryScreen.Bounds.Height,
                               PixelFormat.Format32bppArgb);

// Create a graphics object from the bitmap.
var gfxScreenshot = Graphics.FromImage(bmpScreenshot);

// Take the screenshot from the upper left corner to the right bottom corner.
gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
                            Screen.PrimaryScreen.Bounds.Y,
                            0,
                            0,
                            Screen.PrimaryScreen.Bounds.Size,
                            CopyPixelOperation.SourceCopy);

// Save the screenshot to the specified path that the user has chosen.
bmpScreenshot.Save("Screenshot.png", ImageFormat.Png);

I am getting an "Invalid Host header" message when connecting to webpack-dev-server remotely

I found out, that I need to set the public property of devServer, to my request's host value. Being that it will be displayed at that external address.

So I needed this in my webpack.config.js

devServer: {
  compress: true,
  public: 'store-client-nestroia1.c9users.io' // That solved it
}

Another solution is using it on the CLI:

webpack-dev-server --public $C9_HOSTNAME <-- var for Cloud9 external IP

Regular expression to extract URL from an HTML link

John Gruber (who wrote Markdown, which is made of regular expressions and is used right here on Stack Overflow) had a go at producing a regular expression that recognises URLs in text:

http://daringfireball.net/2009/11/liberal_regex_for_matching_urls

If you just want to grab the URL (i.e. you’re not really trying to parse the HTML), this might be more lightweight than an HTML parser.

What is the use of static synchronized method in java?

Suppose there are multiple static synchronized methods (m1, m2, m3, m4) in a class, and suppose one thread is accessing m1, then no other thread at the same time can access any other static synchronized methods.

.datepicker('setdate') issues, in jQuery

function calenderEdit(dob) {
    var date= $('#'+dob).val();
    $("#dob").datepicker({
        changeMonth: true,
        changeYear: true, yearRange: '1950:+10'
    }).datepicker("setDate", date);
}

Command line tool to dump Windows DLL version?

Use Microsoft Sysinternals Sigcheck. This sample outputs just the version:

sigcheck -q -n foo.dll

Unpacked sigcheck.exe is only 228 KB.

Adding Python Path on Windows 7

You can set the path from the current cmd window using the PATH = command. That will only add it for the current cmd instance. if you want to add it permanently, you should add it to system variables. (Computer > Advanced System Settings > Environment Variables)

You would goto your cmd instance, and put in PATH=C:/Python27/;%PATH%.

Android: How to open a specific folder via Intent and show its content in a file browser?

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, DocumentsContract.Document.MIME_TYPE_DIR);
startActivity(intent);

Will open files app home screen enter image description here

How to call servlet through a JSP page

You can submit your jsp page to servlet. For this use <form> tag.

And to redirect use:

response.sendRedirect("servleturl")

Very Simple Image Slider/Slideshow with left and right button. No autoplay

After reading your comment on my previous answer I thought I might put this as a separate answer.

Although I appreciate your approach of trying to do it manually to get a better grasp on jQuery I do still emphasise the merit in using existing frameworks.

That said, here is a solution. I've modified some of your css and and HTML just to make it easier for me to work with

WORKING JS FIDDLE - http://jsfiddle.net/HsEne/15/

This is the jQuery

$(document).ready(function(){
$('.sp').first().addClass('active');
$('.sp').hide();    
$('.active').show();

    $('#button-next').click(function(){

    $('.active').removeClass('active').addClass('oldActive');    
                   if ( $('.oldActive').is(':last-child')) {
        $('.sp').first().addClass('active');
        }
        else{
        $('.oldActive').next().addClass('active');
        }
    $('.oldActive').removeClass('oldActive');
    $('.sp').fadeOut();
    $('.active').fadeIn();


    });

       $('#button-previous').click(function(){
    $('.active').removeClass('active').addClass('oldActive');    
           if ( $('.oldActive').is(':first-child')) {
        $('.sp').last().addClass('active');
        }
           else{
    $('.oldActive').prev().addClass('active');
           }
    $('.oldActive').removeClass('oldActive');
    $('.sp').fadeOut();
    $('.active').fadeIn();
    });




});

So now the explanation.
Stage 1
1) Load the script on document ready.

2) Grab the first slide and add a class 'active' to it so we know which slide we are dealing with.

3) Hide all slides and show active slide. So now slide #1 is display block and all the rest are display:none;

Stage 2 Working with the button-next click event.
1) Remove the current active class from the slide that will be disappearing and give it the class oldActive so we know that it is on it's way out.

2) Next is an if statement to check if we are at the end of the slideshow and need to return to the start again. It checks if oldActive (i.e. the outgoing slide) is the last child. If it is, then go back to the first child and make it 'active'. If it's not the last child, then just grab the next element (using .next() ) and give it class active.

3) We remove the class oldActive because it's no longer needed.

4) fadeOut all of the slides

5) fade In the active slides

Step 3

Same as in step two but using some reverse logic for traversing through the elements backwards.

It's important to note there are thousands of ways you can achieve this. This is merely my take on the situation.

What is the difference between functional and non-functional requirements?

FUNCTIONAL REQUIREMENTS the activities the system must perform

  • business uses functions the users carry out
  • use cases example if you are developing a payroll system required functions
  • generate electronic fund transfers
  • calculation commission amounts
  • calculate payroll taxes
  • report tax deduction to the IRS

What is the Maximum Size that an Array can hold?

I think if you don't consider the VM, it is Integer.MaxValue

Understanding the order() function

(I thought it might be helpful to lay out the ideas very simply here to summarize the good material posted by @doug, & linked by @duffymo; +1 to each,btw.)

?order tells you which element of the original vector needs to be put first, second, etc., so as to sort the original vector, whereas ?rank tell you which element has the lowest, second lowest, etc., value. For example:

> a <- c(45, 50, 10, 96)
> order(a)  
[1] 3 1 2 4  
> rank(a)  
[1] 2 3 1 4  

So order(a) is saying, 'put the third element first when you sort... ', whereas rank(a) is saying, 'the first element is the second lowest... '. (Note that they both agree on which element is lowest, etc.; they just present the information differently.) Thus we see that we can use order() to sort, but we can't use rank() that way:

> a[order(a)]  
[1] 10 45 50 96  
> sort(a)  
[1] 10 45 50 96  
> a[rank(a)]  
[1] 50 10 45 96  

In general, order() will not equal rank() unless the vector has been sorted already:

> b <- sort(a)  
> order(b)==rank(b)  
[1] TRUE TRUE TRUE TRUE  

Also, since order() is (essentially) operating over ranks of the data, you could compose them without affecting the information, but the other way around produces gibberish:

> order(rank(a))==order(a)  
[1] TRUE TRUE TRUE TRUE  
> rank(order(a))==rank(a)  
[1] FALSE FALSE FALSE  TRUE  

Angular ng-repeat Error "Duplicates in a repeater are not allowed."

For those who expect JSON and still getting the same error, make sure that you parse your data:

$scope.customers = JSON.parse(data)

How to replace text of a cell based on condition in excel

You can use the Conditional Formatting to replace text and NOT effect any formulas. Simply go to the Rule's format where you will see Number, Font, Border and Fill.
Go to the Number tab and select CUSTOM. Then simply type where it says TYPE: what you want to say in QUOTES.

Example.. "OTHER"

How to toggle (hide / show) sidebar div using jQuery

$(document).ready(function () {
    $(".trigger").click(function () {
        $("#sidebar").toggle("fast");
        $("#sidebar").toggleClass("active");
        return false;
    });
});


<div>
    <a class="trigger" href="#">
        <img id="icon-menu" alt='menu' height='50' src="Images/Push Pin.png" width='50' />
    </a>
</div>
<div id="sidebar">
</div>

Instead #sidebar give the id of ur div.

VB.NET Connection string (Web.Config, App.Config)

If it's a .mdf database and the connection string was saved when it was created, you should be able to access it via:

    Dim cn As SqlConnection = New SqlConnection(My.Settings.DatabaseNameConnectionString)

Hope that helps someone.

Animation CSS3: display + opacity

I used this to achieve it. They fade on hover but take no space when hidden, perfect!

.child {
    height: 0px;
    opacity: 0;
    visibility: hidden;
    transition: all .5s ease-in-out;
}

.parent:hover .child {
    height: auto;
    opacity: 1;
    visibility: visible;
}

How do I add a custom script to my package.json file that runs a javascript file?

Example:

  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build --prod",
    "build_c": "ng build --prod && del \"../../server/front-end/*.*\" /s /q & xcopy /s dist \"../../server/front-end\"",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },

As you can see, the script "build_c" is building the angular application, then deletes all old files from a directory, then finally copies the result build files.

Error: "setFile(null,false) call failed" when using log4j

This is your config :

log4j.appender.FILE.File=logs/${file.name}

And this error happened :

java.io.FileNotFoundException: logs (Access is denied)

So it seems that the variable file.name is not set, and java tries to write to the directory logs.


You can force the value of your variable ${file.name} calling maven with this option -D :

mvn clean test -Dfile.name=logfile.log

invalid new-expression of abstract class type

invalid new-expression of abstract class type 'box'

There is nothing unclear about the error message. Your class box has at least one member that is not implemented, which means it is abstract. You cannot instantiate an abstract class.

If this is a bug, fix your box class by implementing the missing member(s).

If it's by design, derive from box, implement the missing member(s) and use the derived class.

c# - How to get sum of the values from List?

Use Sum()

 List<string> foo = new List<string>();
 foo.Add("1");
 foo.Add("2");
 foo.Add("3");
 foo.Add("4");

 Console.Write(foo.Sum(x => Convert.ToInt32(x)));

Prints:

10

Android Studio - Device is connected but 'offline'

  • Restart adb by issuing these commands in cmd

    adb kill-server to kill existing adb session

    followed by adb start-server to start a new adb session
  • Disable and re-enable USB debugging on the phone and accept RSA fingerprints if asked by phone
  • Rebooting the phone if it still doesn't work.

If all above don't solve your problem, you may try delete environment variable named "ANDROID_SDK_HOME". It really solved my problem. Hope it Help you!

conversion from infix to prefix

Maybe you're talking about the Reverse Polish Notation? If yes you can find on wikipedia a very detailed step-to-step example for the conversion; if not I have no idea what you're asking :(

You might also want to read my answer to another question where I provided such an implementation: C++ simple operations (+,-,/,*) evaluation class

E: Unable to locate package mongodb-org

This worked on Ubuntu 17.04

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 2930ADAE8CAF5059EE73BB4B58712A2291FA4AD5

echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.6 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list

sudo apt-get update

sudo apt-get install -y mongodb-org

If you see a failure like:

dpkg: error processing archive /var/cache/apt/archives/mongodb-org-tools_3.6.2_amd64.deb (--unpack):
trying to overwrite '/usr/bin/bsondump', which is also in package mongo-tools 3.2.11-1
dpkg-deb: error: subprocess paste was killed by signal (Broken pipe)

Then run this command:

echo "deb [ arch=amd64,arm64 ] http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.6 multiverse" |

sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list

and

sudo apt update
sudo apt install mongodb-org

References:

MySQL: Get column name or alias from query

You can also do this to just get the field titles:

table = cursor.description
check = 0
for fields in table:
    for name in fields:
        if check < 1:
            print(name),
        check +=1
    check =0

How to add a string to a string[] array? There's no .Add function

to clear the array and make the number of it's elements = 0 at the same time, use this..

System.Array.Resize(ref arrayName, 0);

Moving up one directory in Python

Use the os module:

import os
os.chdir('..')

should work

Returning multiple values from a C++ function

rather than returning multiple values,just return one of them and make a reference of others in the required function for eg:

int divide(int a,int b,int quo,int &rem)

Is there a way to use two CSS3 box shadows on one element?

You can comma-separate shadows:

box-shadow: inset 0 2px 0px #dcffa6, 0 2px 5px #000;

How to read values from the querystring with ASP.NET Core?

  1. Startup.cs add this service services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  2. Your view add inject @inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
  3. get your value

Code

@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
@{
    var id = HttpContextAccessor.HttpContext.Request.RouteValues["id"];

    if (id != null)
    {
        // parameter exist in your URL 
    }

    string navigation = await Navigation.WebNavigation(activeTab);
}

Python not working in command prompt?

If you are working with command prompt and if you are facing the issue even after adding python path to system variable PATH.

Remember to restart the command prompt (cmde.exe).

How do I put my website's logo to be the icon image in browser tabs?

That image is called 'favicon' and it's a small square shaped .ico file, which is the standard file type for favicons. You could use .png or .gif too, but you should follow the standard for better compatibility.

To set one for your website you should:

  1. Make a square image of your logo (preferably 32x32 or 16x16 pixels, as far as I know there's no max size*), and transform it into an .ico file. You can do this on Gimp, Photoshop (with help of a plugin) or a website like Favicon.cc or RealFaviconGenerator.

  2. Then, you have two ways of setting it up:

    A) Placing it on the root folder/directory of your website (next to index.html) with the name favicon.ico.

    or

    B) Link to it between the <head></head> tags of every .html file on your site, like this:

    <head>
      <link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
    </head>
    

If you want to see the favicon from any website, just write www.url.com/favicon.ico and you'll (probably) see it. Stackoverflow's favicon is 16x16 pixels and Wikipedia is 32x32.

*: There's even a browser problem with no filesize limit. You could easily crash a browser with an exceedingly large favicon, more info here

Getting JavaScript object key list

var keys = new Array();
for(var key in obj)
{
   keys[keys.length] = key;
}

var keyLength = keys.length;

to access any value from the object, you can use obj[key];

pip3: command not found

its possible if you already have a python installed (pip) you could do a upgrade on mac by

brew upgrade python

Where is the <conio.h> header file on Linux? Why can't I find <conio.h>?

conio.h is a C header file used in old MS-DOS compilers to create text user interfaces. Compilers that targeted non-DOS operating systems, such as Linux, Win32 and OS/2, provided different implementations of these functions.

The #include <curses.h> will give you almost all the functionalities that was provided in conio.h

nucurses need to be installed at the first place

In deb based Distros use

sudo apt-get install libncurses5-dev libncursesw5-dev

And in rpm based distros use

sudo yum install ncurses-devel ncurses

For getch() class of functions, you can try this

How do I determine file encoding in OS X?

Which LaTeX are you using? When I was using teTeX, I had to manually download the unicode package and add this to my .tex files:

% UTF-8 stuff
\usepackage[notipa]{ucs}
\usepackage[utf8x]{inputenc}
\usepackage[T1]{fontenc}

Now, I've switched over to XeTeX from the TeXlive 2008 package (here), it is even more simple:

% UTF-8 stuff
\usepackage{fontspec}
\usepackage{xunicode}

As for detection of a file's encoding, you could play with file(1) (but it is rather limited) but like someone else said, it is difficult.

jquery to validate phone number

Your code:

rules: {
    phoneNumber: {
        matches: "[0-9]+",  // <-- no such method called "matches"!
        minlength:10,
        maxlength:10
    }
}

There is no such callback function, option, method, or rule called matches anywhere within the jQuery Validate plugin. (EDIT: OP failed to mention that matches is his custom method.)

However, within the additional-methods.js file, there are several phone number validation methods you can use. The one called phoneUS should satisfy your pattern. Since the rule already validates the length, minlength and maxlength are redundantly unnecessary. It's also much more comprehensive in that area codes and prefixes can not start with a 1.

rules: {
    phoneNumber: {
        phoneUS: true
    }
}

DEMO: http://jsfiddle.net/eWhkv/


If, for whatever reason, you just need the regex for use in another method, you can take it from here...

jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
    phone_number = phone_number.replace(/\s+/g, "");
    return this.optional(element) || phone_number.length > 9 && 
    phone_number.match(/^(\+?1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");

How to change text color of simple list item

I realize this question is a bit old but here's a really simple solution that was missing. You don't need to create a custom ListView or even a custom layout.

Just create an anonymous subclass of ArrayAdapter and override getView(). Let super.getView() handle all the heavy lifting. Since simple_list_item_1 is just a text view you can customize it (e.g. set textColor) and then return it.

Here's an example from one of my apps. I'm displaying a list of recent locations and I want all occurrences of "Current Location" to be blue and the rest white.

ListView listView = (ListView) this.findViewById(R.id.listView);
listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, MobileMuni.getBookmarkStore().getRecentLocations()) {
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView textView = (TextView) super.getView(position, convertView, parent);

        String currentLocation = RouteFinderBookmarksActivity.this.getResources().getString(R.string.Current_Location);
        int textColor = textView.getText().toString().equals(currentLocation) ? R.color.holo_blue : R.color.text_color_btn_holo_dark;
        textView.setTextColor(RouteFinderBookmarksActivity.this.getResources().getColor(textColor));

        return textView;
    }
});

Algorithm: efficient way to remove duplicate integers from an array

The return value of the function should be the number of unique elements and they are all stored at the front of the array. Without this additional information, you won't even know if there were any duplicates.

Each iteration of the outer loop processes one element of the array. If it is unique, it stays in the front of the array and if it is a duplicate, it is overwritten by the last unprocessed element in the array. This solution runs in O(n^2) time.

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

size_t rmdup(int *arr, size_t len)
{
  size_t prev = 0;
  size_t curr = 1;
  size_t last = len - 1;
  while (curr <= last) {
    for (prev = 0; prev < curr && arr[curr] != arr[prev]; ++prev);
    if (prev == curr) {
      ++curr;
    } else {
      arr[curr] = arr[last];
      --last;
    }
  }
  return curr;
}

void print_array(int *arr, size_t len)
{
  printf("{");
  size_t curr = 0;
  for (curr = 0; curr < len; ++curr) {
    if (curr > 0) printf(", ");
    printf("%d", arr[curr]);
  }
  printf("}");
}

int main()
{
  int arr[] = {4, 8, 4, 1, 1, 2, 9};
  printf("Before: ");
  size_t len = sizeof (arr) / sizeof (arr[0]);
  print_array(arr, len);
  len = rmdup(arr, len);
  printf("\nAfter: ");
  print_array(arr, len);
  printf("\n");
  return 0;
}

Eclipse: All my projects disappeared from Project Explorer

Click on Windows > Open Perspectives > java , Press Ok. Project Explore will come back on screen..

Screenshot sizes for publishing android app on Google Play

It has to be any one of the given sizes and a minimum of 2 but up to 8 screenshots are accepted in Google Playstore.

Single controller with multiple GET methods in ASP.NET Web API

With the newer Web Api 2 it has become easier to have multiple get methods.

If the parameter passed to the GET methods are different enough for the attribute routing system to distinguish their types as is the case with ints and Guids you can specify the expected type in the [Route...] attribute

For example -

[RoutePrefix("api/values")]
public class ValuesController : ApiController
{

    // GET api/values/7
    [Route("{id:int}")]
    public string Get(int id)
    {
       return $"You entered an int - {id}";
    }

    // GET api/values/AAC1FB7B-978B-4C39-A90D-271A031BFE5D
    [Route("{id:Guid}")]
    public string Get(Guid id)
    {
       return $"You entered a GUID - {id}";
    }
} 

For more details about this approach, see here http://nodogmablog.bryanhogan.net/2017/02/web-api-2-controller-with-multiple-get-methods-part-2/

Another options is to give the GET methods different routes.

    [RoutePrefix("api/values")]
    public class ValuesController : ApiController
    {
        public string Get()
        {
            return "simple get";
        }

        [Route("geta")]
        public string GetA()
        {
            return "A";
        }

        [Route("getb")]
        public string GetB()
        {
            return "B";
        }
   }

See here for more details - http://nodogmablog.bryanhogan.net/2016/10/web-api-2-controller-with-multiple-get-methods/

Reset the database (purge all), then seed a database

You can use rake db:reset when you want to drop the local database and start fresh with data loaded from db/seeds.rb. This is a useful command when you are still figuring out your schema, and often need to add fields to existing models.

Once the reset command is used it will do the following: Drop the database: rake db:drop Load the schema: rake db:schema:load Seed the data: rake db:seed

But if you want to completely drop your database you can use rake db:drop. Dropping the database will also remove any schema conflicts or bad data. If you want to keep the data you have, be sure to back it up before running this command.

This is a detailed article about the most important rake database commands.

How To Auto-Format / Indent XML/HTML in Notepad++

I had to update the proxy settings under Plugins -> Plugin Manager -> Show Plugin Manager -> Settings to see any PlugIns in the "Available" list.

After that, installing "XML Tools" was easy and did the requested job as described above.

How to justify a single flexbox item (override justify-content)

To expand on Pavlo's answer https://stackoverflow.com/a/34063808/1069914, you can have multiple child items justify-content: flex-start in their behavior but have the last item justify-content: flex-end

_x000D_
_x000D_
.container {
  height: 100px;
  border: solid 10px skyblue;
  display: flex;
  justify-content: flex-end;
}

.container > *:not(:last-child) {
    margin-right: 0;
    margin-left: 0;
}

/* set the second to last-child */
.container > :nth-last-child(2) {
    margin-right: auto;
    margin-left: 0;
}

.block {
  width: 50px;
  background: tomato;
  border: 1px solid black;
}
_x000D_
<div class="container">
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
    <div class="block" style="width:150px">I should be at the end of the flex container (i.e. justify-content: flex-end)</div>
</div>
_x000D_
_x000D_
_x000D_

Serving favicon.ico in ASP.NET MVC

Placing favicon.ico in the root of your domain only really affects IE5, IIRC. For more modern browsers you should be able to include a link tag to point to another directory:

<link rel="SHORTCUT ICON" href="http://www.mydomain.com/content/favicon.ico"/>

You can also use non-ico files for browsers other than IE, for which I'd maybe use the following conditional statement to serve a PNG to FF,etc, and an ICO to IE:

<link rel="icon" type="image/png" href="http://www.mydomain.com/content/favicon.png" />
<!--[if IE]>
<link rel="shortcut icon" href="http://www.mydomain.com/content/favicon.ico" type="image/vnd.microsoft.icon" />
<![endif]-->

Initializing default values in a struct

Yes. bar.a and bar.b are set to true, but bar.c is undefined. However, certain compilers will set it to false.

See a live example here: struct demo

According to C++ standard Section 8.5.12:

if no initialization is performed, an object with automatic or dynamic storage duration has indeterminate value

For primitive built-in data types (bool, char, wchar_t, short, int, long, float, double, long double), only global variables (all static storage variables) get default value of zero if they are not explicitly initialized.

If you don't really want undefined bar.c to start with, you should also initialize it like you did for bar.a and bar.b.

file_get_contents("php://input") or $HTTP_RAW_POST_DATA, which one is better to get the body of JSON request?

For JSON data, it's much easier to POST it as "application/json" content-type. If you use GET, you have to URL-encode the JSON in a parameter and it's kind of messy. Also, there is no size limit when you do POST. GET's size if very limited (4K at most).

What is %0|%0 and how does it work?

This is the Windows version of a fork bomb.

%0 is the name of the currently executing batch file. A batch file that contains just this line:

%0|%0

Is going to recursively execute itself forever, quickly creating many processes and slowing the system down.

This is not a bug in windows, it is just a very stupid thing to do in a batch file.

How to plot ROC curve in Python

Here is python code for computing the ROC curve (as a scatter plot):

import matplotlib.pyplot as plt
import numpy as np

score = np.array([0.9, 0.8, 0.7, 0.6, 0.55, 0.54, 0.53, 0.52, 0.51, 0.505, 0.4, 0.39, 0.38, 0.37, 0.36, 0.35, 0.34, 0.33, 0.30, 0.1])
y = np.array([1,1,0, 1, 1, 1, 0, 0, 1, 0, 1,0, 1, 0, 0, 0, 1 , 0, 1, 0])

# false positive rate
fpr = []
# true positive rate
tpr = []
# Iterate thresholds from 0.0, 0.01, ... 1.0
thresholds = np.arange(0.0, 1.01, .01)

# get number of positive and negative examples in the dataset
P = sum(y)
N = len(y) - P

# iterate through all thresholds and determine fraction of true positives
# and false positives found at this threshold
for thresh in thresholds:
    FP=0
    TP=0
    for i in range(len(score)):
        if (score[i] > thresh):
            if y[i] == 1:
                TP = TP + 1
            if y[i] == 0:
                FP = FP + 1
    fpr.append(FP/float(N))
    tpr.append(TP/float(P))

plt.scatter(fpr, tpr)
plt.show()

How to declare Global Variables in Excel VBA to be visible across the Workbook

You can do the following to learn/test the concept:

  1. Open new Excel Workbook and in Excel VBA editor right-click on Modules->Insert->Module

  2. In newly added Module1 add the declaration; Public Global1 As String

  3. in Worksheet VBA Module Sheet1(Sheet1) put the code snippet:

Sub setMe()
      Global1 = "Hello"
End Sub
  1. in Worksheet VBA Module Sheet2(Sheet2) put the code snippet:
Sub showMe()
    Debug.Print (Global1)
End Sub
  1. Run in sequence Sub setMe() and then Sub showMe() to test the global visibility/accessibility of the var Global1

Hope this will help.

UIImageView - How to get the file name of the image assigned?

The code is work in swift3 - write code inside didFinishPickingMediaWithInfo delegate method:

if let referenceUrl = info[UIImagePickerControllerReferenceURL] as? NSURL {
  ALAssetsLibrary().asset(for: referenceUrl as URL!, resultBlock: { asset in

  let fileName = asset?.defaultRepresentation().filename()
  print(fileName!)

  //do whatever with your file name            
  }, failureBlock: nil)
}

Replace last occurrence of a string in a string

This will also work:

function str_lreplace($search, $replace, $subject)
{
    return preg_replace('~(.*)' . preg_quote($search, '~') . '(.*?)~', '$1' . $replace . '$2', $subject, 1);
}

UPDATE Slightly more concise version (http://ideone.com/B8i4o):

function str_lreplace($search, $replace, $subject)
{
    return preg_replace('~(.*)' . preg_quote($search, '~') . '~', '$1' . $replace, $subject, 1);
}

Mysql - delete from multiple tables with one query

You can use following query to delete rows from multiple tables,

DELETE table1, table2, table3 FROM table1 INNER JOIN table2 INNER JOIN table3 WHERE table1.userid = table2.userid AND table2.userid = table3.userid AND table1.userid=3

How can I extract audio from video with ffmpeg?

Use -b:a instead of -ab as -ab is outdated now, also make sure your input file path is correct.

To extract audio from a video I have used below command and its working fine.

String[] complexCommand = {"-y", "-i", inputFileAbsolutePath, "-vn", "-ar", "44100", "-ac", "2", "-b:a", "256k", "-f", "mp3", outputFileAbsolutePath};

Here,

  • -y - Overwrite output files without asking.
  • -i - FFmpeg reads from an arbitrary number of input “files” specified by the -i option
  • -vn - Disable video recording
  • -ar - sets the sampling rate for audio streams if encoded
  • -ac - Set the number of audio channels.
  • -b:a - Set the audio bitrate
  • -f - format

Check out this for my complete sample FFmpeg android project on GitHub.

CSS filter: make color image with transparency white

To my knowledge, there is sadly no CSS filter to colorise an element (perhaps with the use of some SVG filter magic, but I'm somewhat unfamiliar with that) and even if that wasn't the case, filters are basically only supported by webkit browsers.

With that said, you could still work around this and use a canvas to modify your image. Basically, you can draw an image element onto a canvas and then loop through the pixels, modifying the respective RGBA values to the colour you want.

However, canvases do come with some restrictions. Most importantly, you have to make sure that the image src comes from the same domain as the page. Otherwise the browser won't allow you to read or modify the pixel data of the canvas.

Here's a JSFiddle changing the colour of the JSFiddle logo.

_x000D_
_x000D_
//Base64 source, but any local source will work_x000D_
var src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC0AAAAgCAYAAACGhPFEAAAABGdBTUEAALGPC/xhBQAABzhJREFUWAnNWAtwXFUZ/v9zs4GUJJu+k7tb5DFAGWO1aal1sJUiY3FQQaWidqgPLAMqYzd9CB073VodhCa7KziiFgWhzvAYQCiCD5yK4gOTDnZK2ymdZoruppu0afbu0pBs7p7f7yy96W662aw2QO/Mzj2P//Gd/5z/+89dprfzubnTN332Re+xiKawllxWucm+9O4eCi9xT8ctn45yKd3AXX1BPsu3XIiuY+K5kDmrUA7jORb5m2baLm7uscNrJr9eOF9Je8JAz9ySnFHlq9nEpG6CYx+RdJDQDtKymxT1iWZLFDUy0/kkfDUxzYVzV0hvHZLs946Gph+uBLCRmRDQdjTVwmw9DZCNMPi4KzqWbPX/sxwIu71vlrKq10HnZizwTSFZngj5f1NOx5s7bdB2LHWDEusBOD487LrX9qyd8qpnvJL3zGjqAh+pR4W4RVhu715Vv2U8PTWeQLn5YHvms4qsR4TpH/ImLfhfARvbPaGGrrjTtwjH5hFFfHcgkv5SOZ9mbvxIgwGaZl+8ULGcJ8zOsJa9R1r9B2d8v2eGb1KNieqBhLNz8ekyAoV3VAX985+FvSXEenF8lf9lA7DUUxa0HUl/RTG1EfOUQmUwwCtggDewiHmc1R+Ir/MfKJz/f9tTwn31Nf7qVxlHLR6qXwg7cHXqU/p4hPdUB6Lp55TiXwDYTsrpG12dbdY5t0WLrCSRSVjIItG0dqIAG2jHwlPTmvQdsL3Ajjg3nAq3zIgdS98ZiGV0MJZeWVJs2WNWIJK5hcLh0osuqVTxIAdi6X3w/0LFGoa+AtFMzo5kflix0gQLBiLOZmAYro84RcfSc3NKpFAcliM9eYDdjZ7QO/1mRc+CTapqFX+4lO9TQEPoUpz//anQ5FQphXdizB1QXXk/moOl/JUC7aLMDpQSHj02PdxbG9xybM60u47UjZ4bq290Zm451ky3HSi6kxTKJ9fXHQVvZJm1XTjutYsozw53T1L+2ufBGPMTe/c30M/mD3uChW+c+6tQttthuBnbqMBLKGbydI54/eFQ3b5CWa/dGMl8xFJ0D/rvg1Pjdxil+2XK5b6ZWD15lyfnvYOxTBYs9TrY5NbuUENRUo5EGtGyVUNtBwBfDjA/IDtTkiNRsdYD8O+NcVN2KUfXo3UnukvA6Z3I+mWeY++NpNoAwDvAv1Uiss7oiNBmYD+XraoO0NvnPVnvrbUsA4CcYusPgajzY2/cvN+KtOFl/6w/IWrvdTV/Ktla92KhkNcOxpwPCqm/IgLbEvteW1m4E2/d8iY9AZOXQ/7WxKq6nxq9YNT5OLF6DmAfTHT13EL3XjTk2csXk4bqX2OXWiQ73Jz49tS4N5d/oxoHLr14EzPfAf1IIlS/2oznIx1omLURhL5Qa1oxFuC8EeHb8U6I88bXCwGbuZ61jb2Jgz1XYUHb0b0vEHNWmHE9lNsjWrcmnMhNhYDNnCkmNJSFHFdzte82M1b04HgC6HrYbAPw1pFdNOc4GE334wz9qkihRAdK/0HBub/E1MkhJBiq6V8gq7Htm05OjN2C/z/jCP1xbAlCwcnsAsbdkGHF/trPIcoNrtbjFRNmoama6EgZ42SimRG5FjLHWakNwWjmirLyZpLpKH7TysghZ00OUHNTxFmK2yDNQSKlx7u0Q0GQeLtQdy4rY5zMzqVb/ccoJ/OQMEmoPWW3988to4NY8DxYf6WMDCW6ktuRvFqxmqewgguhdLCcwsic0DMA8lE7kvrYyFhBw446X2B/nRNo739/YnX9azKUXYCg9CtlvdAUyywuEB1p4gh9AzbPZc0mF8Z+sINgn0MIwiVgKcAG6rGlT86AMdqw2n8ppR63o+mveQXCFAxzX2BWD0P6pcT+g3uNlmEDV3JX4iOh1xICdWU2gGXOMXN5HfRhK4IoPxlfXQfmKf+Ajh1I+MEeHMcKzqvoxoZsHsoOXgP+fEkxbw1e2JhB0h2q9tc4OL/fAVdsdd3jnyhklmRo8qGBQXchIvMMKPW7Pt85/SM66CNmDw1mh75cHu6JWZFZxNLNSJTPIM5PuJquKEt3o6zmqyJZH4LTC7CIfTonO5Jr/B2jxIq6jW3OZVYVX4edDSD6e1BAXqwgl/I2miKp+ZayOkT0CjaJww21/2bhznio7uoiL2dQB8HdhoV++ri4AdUdtgfw789mRHspzulXzyCcI1BMVQXgL5LodnP7zFfE+N9/9yOUyedxTn/SFHWWj0ifAY1ANHUleOJRlPqdCUmbO85J1jjxUfkUkgVCsg1/uGw0n/fvFm67LT2NLTLfi98Cke8dpMGl3r9QxVRnPuPrWzaIUmsAtgas0okd6ETh7AYt5d7+BeCbhfKVcQ6CtwgJjjoiP3fdgVbcbY57/otBnxidfndvo6/67BtxUf4kztJsbMg0CJaU9QxN2FskhePQBWr7La6wvzRFarTtyoBgB4hm5M//aAMT2+/Vlfzp81/vywLMWSBN1QAAAABJRU5ErkJggg==";_x000D_
var canvas = document.getElementById("theCanvas");_x000D_
var ctx = canvas.getContext("2d");_x000D_
var img = new Image;_x000D_
_x000D_
//wait for the image to load_x000D_
img.onload = function() {_x000D_
    //Draw the original image so that you can fetch the colour data_x000D_
    ctx.drawImage(img,0,0);_x000D_
    var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);_x000D_
    _x000D_
    /*_x000D_
    imgData.data is a one-dimensional array which contains _x000D_
    the respective RGBA values for every pixel _x000D_
    in the selected region of the context _x000D_
    (note i+=4 in the loop)_x000D_
    */_x000D_
    _x000D_
    for (var i = 0; i < imgData.data.length; i+=4) {_x000D_
   imgData.data[i] = 255; //Red, 0-255_x000D_
   imgData.data[i+1] = 255; //Green, 0-255_x000D_
   imgData.data[i+2] = 255; //Blue, 0-255_x000D_
   /* _x000D_
   imgData.data[i+3] contains the alpha value_x000D_
   which we are going to ignore and leave_x000D_
   alone with its original value_x000D_
   */_x000D_
    }_x000D_
    ctx.clearRect(0, 0, canvas.width, canvas.height); //clear the original image_x000D_
    ctx.putImageData(imgData, 0, 0); //paint the new colorised image_x000D_
}_x000D_
_x000D_
//Load the image!_x000D_
img.src = src;
_x000D_
body {_x000D_
    background: green;_x000D_
}
_x000D_
<canvas id="theCanvas"></canvas>
_x000D_
_x000D_
_x000D_

Maven does not find JUnit tests to run

If your test class name does not follow the standard naming convention (as highlighted by @axtavt above), you need to add the pattern/class name in the pom.xml in order to Maven pick the test -

...
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <includes>
                    <include>**/*_UT.java</include>
                </includes>
            </configuration>
        </plugin>
    </plugins>
</build> 
...

How to create permanent PowerShell Aliases

2018, Windows 10

You can link to any file or directory with the help of a simple PowerShell script.

Writing a file shortcut script

Open Windows PowerShell ISE. In the script pane write:

New-Alias ${shortcutName} ${fullFileLocation}

Then head to the command-line pane. Find your PowerShell user profile address with echo $profile. Save the script in this address.

enter image description here

The script in PowerShell's profile address will run each time you open powershell. The shortcut should work with every new PowerShell window.

Writing a directory shortcut script

It requires another line in our script.

function ${nameOfFunction} {set-location ${directory_location}}
New-Alias ${shortcut} ${nameOfFunction} 

The rest is exactly the same.

enter image description here

Enable PowerShell Scripts

By default PowerShell scripts are blocked. To enable them, open settings -> Update & Security -> For developers. Select Developer Mode (might require restart). Selecting Developer Mode Windows 10.

Scroll down to the PowerShell section, tick the "Change execution policy ..." option, and apply.

Enabling PowerShell scripts

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

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

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

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

zero width space made visible

Retrieving the first digit of a number

int number = 534;
int firstDigit = number/100; 

( / ) operator in java divide the numbers without considering the reminder so when we divide 534 by 100 , it gives us (5) .

but if you want to get the last number , you can use (%) operator

    int lastDigit = number%10; 

which gives us the reminder of the division , so 534%10 , will yield the number 4 .

Convert XML String to Object

Another way with an Advanced xsd to c# classes generation Tools : xsd2code.com. This tool is very handy and powerfull. It has a lot more customisation than the xsd.exe tool from Visual Studio. Xsd2Code++ can be customised to use Lists or Arrays and supports large schemas with a lot of Import statements.

Note of some features,

  • Generates business objects from XSD Schema or XML file to flexible C# or Visual Basic code.
  • Support Framework 2.0 to 4.x
  • Support strong typed collection (List, ObservableCollection, MyCustomCollection).
  • Support automatic properties.
  • Generate XML read and write methods (serialization/deserialization).
  • Databinding support (WPF, Xamarin).
  • WCF (DataMember attribute).
  • XML Encoding support (UTF-8/32, ASCII, Unicode, Custom).
  • Camel case / Pascal Case support.
  • restriction support ([StringLengthAttribute=true/false], [RegularExpressionAttribute=true/false], [RangeAttribute=true/false]).
  • Support large and complex XSD file.
  • Support of DotNet Core & standard

Append TimeStamp to a File Name

For Current date and time as the name for a file on the file system. Now call the string.Format method, and combine it with DateTime.Now, for a method that outputs the correct string based on the date and time.

using System;
using System.IO;

class Program
{
    static void Main()
    {
        //
        // Write file containing the date with BIN extension
        //
        string n = string.Format("text-{0:yyyy-MM-dd_hh-mm-ss-tt}.bin",
            DateTime.Now);
        File.WriteAllText(n, "abc");
    }
}

Output :

C:\Users\Fez\Documents\text-2020-01-08_05-23-13-PM.bin

"text-{0:yyyy-MM-dd_hh-mm-ss-tt}.bin"

text- The first part of the output required Files will all start with text-

{0: Indicates that this is a string placeholder The zero indicates the index of the parameters inserted here

yyyy- Prints the year in four digits followed by a dash This has a "year 10000" problem

MM- Prints the month in two digits

dd_ Prints the day in two digits followed by an underscore

hh- Prints the hour in two digits

mm- Prints the minute, also in two digits

ss- As expected, it prints the seconds

tt Prints AM or PM depending on the time of day

the getSource() and getActionCommand()

The getActionCommand() method returns an String associated with that Component set through the setActionCommand() , whereas the getSource() method returns an Object of the Object class specifying the source of the event.

CSS center content inside div

There are many ways to center any element. I listed some

  1. Set it's width to some value and add margin: 0 auto.

_x000D_
_x000D_
.partners {_x000D_
    width: 80%;_x000D_
    margin: 0 auto;_x000D_
}
_x000D_
_x000D_
_x000D_


  1. Split into 3 column layout

_x000D_
_x000D_
.partners {_x000D_
    width: 80%;_x000D_
    margin-left: 10%;_x000D_
}
_x000D_
_x000D_
_x000D_


  1. Use bootstrap layout

_x000D_
_x000D_
<div class="row">_x000D_
    <div class="col-sm-4"></div>_x000D_
    <div class="col-sm-4">Your Content / Image here</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

There was no endpoint listening at (url) that could accept the message

If you are using custom binding, please make sure that you are putting the same name for both custom binding (Server and Client)in config files

<bindings>
<customBinding>
 <binding name="BufferedHttpServerNoAuth" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00">
          <gzipMessageEncoding innerMessageEncoding="textMessageEncoding" MaxArrayLength="10485760" MaxBytesPerRead="31457280" MaxStringContentLength="102400000" />
          <httpsTransport hostNameComparisonMode="StrongWildcard" manualAddressing="False" maxReceivedMessageSize="31457280" authenticationScheme="Anonymous" bypassProxyOnLocal="True" realm="" useDefaultWebProxy="False" />
</binding>
</customBinding>
</bindings>

the binding name "BufferedHttpServerNoAuth" should be same in both.

Hope this would help someone

SQL Inner join 2 tables with multiple column conditions and update

UPDATE T1,T2 
INNER JOIN T1 ON  T1.Brands = T2.Brands
SET 
T1.Inci = T2.Inci
WHERE
    T1.Category= T2.Category
AND
    T1.Date = T2.Date

How to debug PDO database queries?

Here's a function to see what the effective SQL will be, adpated from a comment by "Mark" at php.net:

function sql_debug($sql_string, array $params = null) {
    if (!empty($params)) {
        $indexed = $params == array_values($params);
        foreach($params as $k=>$v) {
            if (is_object($v)) {
                if ($v instanceof \DateTime) $v = $v->format('Y-m-d H:i:s');
                else continue;
            }
            elseif (is_string($v)) $v="'$v'";
            elseif ($v === null) $v='NULL';
            elseif (is_array($v)) $v = implode(',', $v);

            if ($indexed) {
                $sql_string = preg_replace('/\?/', $v, $sql_string, 1);
            }
            else {
                if ($k[0] != ':') $k = ':'.$k; //add leading colon if it was left out
                $sql_string = str_replace($k,$v,$sql_string);
            }
        }
    }
    return $sql_string;
}

How to switch activity without animation in Android?

If your context is an activity you can call overridePendingTransition:

Call immediately after one of the flavors of startActivity(Intent) or finish to specify an explicit transition animation to perform next.

So, programmatically:

this.startActivity(new Intent(v.getContext(), newactivity.class));
this.overridePendingTransition(0, 0);

An attempt was made to access a socket in a way forbidden by its access permissions

I had a similar issue with Docker for Windows and Hyper-V having reserved ports for its own use- in my case, it was port 3001 that couldn't be accessed.

  • The port wasn't be used by another process- running netstat -ano | findstr 3001 in an Administrator Powershell prompt showed nothing.
  • However, netsh interface ipv4 show excludedportrange protocol=tcp showed that the port was in one of the exclusion ranges.

I was able to follow the solution described in Docker for Windows issue #3171 (Unable to bind ports: Docker-for-Windows & Hyper-V excluding but not using important port ranges):

  1. Disable Hyper-V:

    dism.exe /Online /Disable-Feature:Microsoft-Hyper-V
    
  2. After the required restarts, reserve the port you want so Hyper-V doesn't reserve it back:

    netsh int ipv4 add excludedportrange protocol=tcp startport=3001 numberofports=1
    
  3. Reenable Hyper-V:

    dism.exe /Online /Enable-Feature:Microsoft-Hyper-V /All
    

After this, I was able to start my docker container.

How to define constants in ReactJS

You don't need to use anything but plain React and ES6 to achieve what you want. As per Jim's answer, just define the constant in the right place. I like the idea of keeping the constant local to the component if not needed externally. The below is an example of possible usage.

import React from "react";

const sizeToLetterMap = {
  small_square: 's',
  large_square: 'q',
  thumbnail: 't',
  small_240: 'm',
  small_320: 'n',
  medium_640: 'z',
  medium_800: 'c',
  large_1024: 'b',
  large_1600: 'h',
  large_2048: 'k',
  original: 'o'
};

class PhotoComponent extends React.Component {
  constructor(args) {
    super(args);
  }

  photoUrl(image, size_text) {
    return (<span>
      Image: {image}, Size Letter: {sizeToLetterMap[size_text]}
    </span>);
  }

  render() {
    return (
      <div className="photo-wrapper">
        The url is: {this.photoUrl(this.props.image, this.props.size_text)}
      </div>
    )
  }
}

export default PhotoComponent;

// Call this with <PhotoComponent image="abc.png" size_text="thumbnail" />
// Of course the component must first be imported where used, example:
// import PhotoComponent from "./photo_component.jsx";

Mongoose (mongodb) batch insert?

Indeed, you can use the "create" method of Mongoose, it can contain an array of documents, see this example:

Candy.create({ candy: 'jelly bean' }, { candy: 'snickers' }, function (err, jellybean, snickers) {
});

The callback function contains the inserted documents. You do not always know how many items has to be inserted (fixed argument length like above) so you can loop through them:

var insertedDocs = [];
for (var i=1; i<arguments.length; ++i) {
    insertedDocs.push(arguments[i]);
}

Update: A better solution

A better solution would to use Candy.collection.insert() instead of Candy.create() - used in the example above - because it's faster (create() is calling Model.save() on each item so it's slower).

See the Mongo documentation for more information: http://docs.mongodb.org/manual/reference/method/db.collection.insert/

(thanks to arcseldon for pointing this out)

How can I use nohup to run process as a background process in linux?

  • Use screen: Start screen, start your script, press Ctrl+A, D. Reattach with screen -r.

  • Make a script that takes your "1" as a parameter, run nohup yourscript:

    #!/bin/bash
    (time bash executeScript $1 input fileOutput $> scrOutput) &> timeUse.txt
    

Getting "Lock wait timeout exceeded; try restarting transaction" even though I'm not using a transaction

Late to the party (as usual) however my issue was the fact that I wrote some bad SQL (being a novice) and several processes had a lock on the record(s) <-- not sure the appropriate verbiage. I ended up having to just: SHOW PROCESSLIST and then kill the IDs using KILL <id>

How to embed images in html email

You have to encode your email as multipart mime and then you can attach emails as attachments basically. You reference them by cid in the email.

Alternatively you could not attach them to the email and use URLs directly but most mail programs will block this as spammers use the trick to detect the liveness of email addresses.

You don't say what language but here is one example.

Import/Index a JSON file into Elasticsearch

As of Elasticsearch 7.7, you have to specify the content type also:

curl -s -H "Content-Type: application/json" -XPOST localhost:9200/_bulk --data-binary @<absolute path to JSON file>

Convert a SQL Server datetime to a shorter date format

Try this:

print cast(getdate() as date )

Check a collection size with JSTL

You can use like this

${fn:length(numList)}

Is null reference possible?

The answer depends on your view point:


If you judge by the C++ standard, you cannot get a null reference because you get undefined behavior first. After that first incidence of undefined behavior, the standard allows anything to happen. So, if you write *(int*)0, you already have undefined behavior as you are, from a language standard point of view, dereferencing a null pointer. The rest of the program is irrelevant, once this expression is executed, you are out of the game.


However, in practice, null references can easily be created from null pointers, and you won't notice until you actually try to access the value behind the null reference. Your example may be a bit too simple, as any good optimizing compiler will see the undefined behavior, and simply optimize away anything that depends on it (the null reference won't even be created, it will be optimized away).

Yet, that optimizing away depends on the compiler to prove the undefined behavior, which may not be possible to do. Consider this simple function inside a file converter.cpp:

int& toReference(int* pointer) {
    return *pointer;
}

When the compiler sees this function, it does not know whether the pointer is a null pointer or not. So it just generates code that turns any pointer into the corresponding reference. (Btw: This is a noop since pointers and references are the exact same beast in assembler.) Now, if you have another file user.cpp with the code

#include "converter.h"

void foo() {
    int& nullRef = toReference(nullptr);
    cout << nullRef;    //crash happens here
}

the compiler does not know that toReference() will dereference the passed pointer, and assume that it returns a valid reference, which will happen to be a null reference in practice. The call succeeds, but when you try to use the reference, the program crashes. Hopefully. The standard allows for anything to happen, including the appearance of pink elephants.

You may ask why this is relevant, after all, the undefined behavior was already triggered inside toReference(). The answer is debugging: Null references may propagate and proliferate just as null pointers do. If you are not aware that null references can exist, and learn to avoid creating them, you may spend quite some time trying to figure out why your member function seems to crash when it's just trying to read a plain old int member (answer: the instance in the call of the member was a null reference, so this is a null pointer, and your member is computed to be located as address 8).


So how about checking for null references? You gave the line

if( & nullReference == 0 ) // null reference

in your question. Well, that won't work: According to the standard, you have undefined behavior if you dereference a null pointer, and you cannot create a null reference without dereferencing a null pointer, so null references exist only inside the realm of undefined behavior. Since your compiler may assume that you are not triggering undefined behavior, it can assume that there is no such thing as a null reference (even though it will readily emit code that generates null references!). As such, it sees the if() condition, concludes that it cannot be true, and just throw away the entire if() statement. With the introduction of link time optimizations, it has become plain impossible to check for null references in a robust way.


TL;DR:

Null references are somewhat of a ghastly existence:

Their existence seems impossible (= by the standard),
but they exist (= by the generated machine code),
but you cannot see them if they exist (= your attempts will be optimized away),
but they may kill you unaware anyway (= your program crashes at weird points, or worse).
Your only hope is that they don't exist (= write your program to not create them).

I do hope that will not come to haunt you!

jQuery: How to detect window width on the fly?

Changing a variable doesn't magically execute code within the if-block. Place the common code in a function, then bind the event, and call the function:

$(document).ready(function() {
    // Optimalisation: Store the references outside the event handler:
    var $window = $(window);
    var $pane = $('#pane1');

    function checkWidth() {
        var windowsize = $window.width();
        if (windowsize > 440) {
            //if the window is greater than 440px wide then turn on jScrollPane..
            $pane.jScrollPane({
               scrollbarWidth:15, 
               scrollbarMargin:52
            });
        }
    }
    // Execute on load
    checkWidth();
    // Bind event listener
    $(window).resize(checkWidth);
});

How to export a Hive table into a CSV file?

I had a similar issue and this is how I was able to address it.

Step 1 - Loaded the data from hive table into another table as follows

DROP TABLE IF EXISTS TestHiveTableCSV; CREATE TABLE TestHiveTableCSV ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' AS SELECT Column List FROM TestHiveTable;

Step 2 - Copied the blob from hive warehouse to the new location with appropriate extension

Start-AzureStorageBlobCopy -DestContext $destContext -SrcContainer "Source Container" -SrcBlob "hive/warehouse/TestHiveTableCSV/000000_0" -DestContainer "Destination Container" ` -DestBlob "CSV/TestHiveTable.csv"

Hope this helps!

Best Regards, Dattatrey Sindol (Datta) http://dattatreysindol.com

Oracle: SQL select date with timestamp

Answer provided by Nicholas Krasnov

SELECT *
FROM BOOKING_SESSION
WHERE TO_CHAR(T_SESSION_DATETIME, 'DD-MM-YYYY') ='20-03-2012';

How to generate a QR Code for an Android application?

with zxing this is my code for create QR

 QRCodeWriter writer = new QRCodeWriter();
    try {
        BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, 512, 512);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                bmp.setPixel(x, y, bitMatrix.get(x, y) ? Color.BLACK : Color.WHITE);
            }
        }
        ((ImageView) findViewById(R.id.img_result_qr)).setImageBitmap(bmp);

    } catch (WriterException e) {
        e.printStackTrace();
    }

What is the difference between Google App Engine and Google Compute Engine?

Or to make it even simpler (since at times we fail to differentiate between GAE Standard and GAE Flex):

Compute Engine is analogous to a virtual PC, where you'd deploy a small website + database, for instance. You manage everything, including control of installed disk drives. If you deploy a website, you're in charge of setting up DNS etc.

Google App Engine (Standard) is like a read-only sandboxed folder where you upload code to execute from and don't worry about the rest (yes: read-only - there are a fixed set of libraries installed for you and you cannot deploy 3rd party libraries at will). DNS / Sub-domains etc is so much easier to map.

Google App Engine (Flexible) is in fact like a whole file-system (not just a locked down folder), where you have more power than the Standard engine, e.g. you have read/write permissions, (but less compared to a Compute Engine). In GAE standard you have a fixed set of libraries installed for you and you cannot deploy 3rd party libraries at will. In the Flexible environment you can install whatever library your app depends on, including custom build environments (such as Python 3).

Although GAE Standard is very cumbersome to deal with (although Google makes it sound simple), it scales really well when put under pressure. It's cumbersome because you need to test and ensure compatibility with the locked-down environment and ensure any 3rd party library you use does not use any other 3rd party library you're unaware of which may not work on GAE standard. It takes longer to set it up in practice but can be more rewarding in the longer run for simple deployments.

How to get only filenames within a directory using c#?

You can simply use linq

Directory.EnumerateFiles(LoanFolder).Select(file => Path.GetFileName(file));

Note: EnumeratesFiles is more efficient compared to Directory.GetFiles as you can start enumerating the collection of names before the whole collection is returned.

How to pass data to all views in Laravel 5?

Inside your config folder you can create a php file name it for example "variable.php" with content below:

<?php

  return [
    'versionNumber' => '122231',
  ];

Now inside all the views you can use it like

config('variable.versionNumber')

How do I get the Session Object in Spring?

Your friend here is org.springframework.web.context.request.RequestContextHolder

// example usage
public static HttpSession session() {
    ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    return attr.getRequest().getSession(true); // true == allow create
}

This will be populated by the standard spring mvc dispatch servlet, but if you are using a different web framework you have add org.springframework.web.filter.RequestContextFilter as a filter in your web.xml to manage the holder.

EDIT: just as a side issue what are you actually trying to do, I'm not sure you should need access to the HttpSession in the retieveUser method of a UserDetailsService. Spring security will put the UserDetails object in the session for you any how. It can be retrieved by accessing the SecurityContextHolder:

public static UserDetails currentUserDetails(){
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();
    if (authentication != null) {
        Object principal = authentication.getPrincipal();
        return principal instanceof UserDetails ? (UserDetails) principal : null;
    }
    return null;
}