Programs & Examples On #Qtscript

QtScript is an ECMA262-compatible implementation of JavaScript. It is the successor of QSA (Qt Script For Applications), but is being phased out in recent Qt versions in favour of Google's V8 engine.

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 .

How to resolve a Java Rounding Double issue

It's quite simple.

Use the %.2f operator for output. Problem solved!

For example:

int a = 877.8499999999999;
System.out.printf("Formatted Output is: %.2f", a);

The above code results in a print output of: 877.85

The %.2f operator defines that only TWO decimal places should be used.

100% Min Height CSS layout

Here is another solution based on vh, or viewpoint height, for details visit CSS units. It is based on this solution, which uses flex instead.

_x000D_
_x000D_
* {_x000D_
    /* personal preference */_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
}_x000D_
html {_x000D_
    /* make sure we use up the whole viewport */_x000D_
    width: 100%;_x000D_
    min-height: 100vh;_x000D_
    /* for debugging, a red background lets us see any seams */_x000D_
    background-color: red;_x000D_
}_x000D_
body {_x000D_
    /* make sure we use the full width but allow for more height */_x000D_
    width: 100%;_x000D_
    min-height: 100vh; /* this helps with the sticky footer */_x000D_
}_x000D_
main {_x000D_
    /* for debugging, a blue background lets us see the content */_x000D_
    background-color: skyblue;_x000D_
 min-height: calc(100vh - 2.5em); /* this leaves space for the sticky footer */_x000D_
}_x000D_
footer {_x000D_
    /* for debugging, a gray background lets us see the footer */_x000D_
    background-color: gray;_x000D_
 min-height:2.5em;_x000D_
}
_x000D_
<main>_x000D_
    <p>This is the content. Resize the viewport vertically to see how the footer behaves.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
</main>_x000D_
<footer>_x000D_
    <p>This is the footer. Resize the viewport horizontally to see how the height behaves when text wraps.</p>_x000D_
    <p>This is the footer.</p>_x000D_
</footer>
_x000D_
_x000D_
_x000D_

The units are vw , vh, vmax, vmin. Basically, each unit is equal to 1% of viewport size. So, as the viewport changes, the browser computes that value and adjusts accordingly.

You may find more information here:

Specifically:

1vw (viewport width) = 1% of viewport width
1vh (viewport height) = 1% of viewport height
1vmin (viewport minimum) = 1vw or 1vh, whatever is smallest
1vmax (viewport minimum) = 1vw or 1vh, whatever is largest

Efficient method to generate UUID String in JAVA (UUID.randomUUID().toString() without the dashes)

Well, since an UUID gets added the hyphens (dashes) on toString() we can steal the implementation from Java's own implementation, shorting the byte array to 32 and adjusting the offset.

        public static String special() {
            UUID uuid = UUID.randomUUID();
            return fastUUID(uuid.getLeastSignificantBits(), uuid.getMostSignificantBits());
        }

        private static String fastUUID(long lsb, long msb) {
            byte[] buf = new byte[32];
            formatUnsignedLong0(lsb,        4, buf, 20, 12);
            formatUnsignedLong0(lsb >>> 48, 4, buf, 16, 4);

            formatUnsignedLong0(msb,        4, buf, 12, 4);
            formatUnsignedLong0(msb >>> 16, 4, buf, 8,  4);
            formatUnsignedLong0(msb >>> 32, 4, buf, 0,  8);

            return new String(buf, 0);
        }

        private static final char[] digits = {
                '0' , '1' , '2' , '3' , '4' , '5' ,
                '6' , '7' , '8' , '9' , 'a' , 'b' ,
                'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
                'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
                'o' , 'p' , 'q' , 'r' , 's' , 't' ,
                'u' , 'v' , 'w' , 'x' , 'y' , 'z'
        };
        private static void formatUnsignedLong0(long val, int shift, byte[] buf, int offset, int len) {
            int charPos = offset + len;
            int radix = 1 << shift;
            int mask = radix - 1;
            do {
                buf[--charPos] = (byte)digits[((int) val) & mask];
                val >>>= shift;
            } while (charPos > offset);
        }

Running it:

        public static void main(String[] args) {
            IntStream.range(0, 100).forEach(i-> {
                System.out.println(special());
            });
        }

Generates:

23f57da8a2784bb5acca553030f82e61
a14427efd8d147fdae315c1cf20fc53c
ee972aa1cf85414ca364bef5c74a7e57
6877ef35eab94b9485c5dd7c8c5a8a56
578721476629422381c0f625e22564a8
dbf60f068b5443d7bc6e5280696fed9f
dd611e870700480d81d394dd2125316c
04d71b9379ef4db49c28e113485ea76d
fd4e8cf3f85a45ae8c1b9bfe3e489a4a
858c4e8297f849b784b65b6096dec4d4
b30a8ca318a349b486b5693814422555
351c2fab9bc1426fa3bb512484628f12
9ce59e01db38405aab82d46f2a236880
5ffb5acb547a4f15a4621b406391bc0d
541b5fba8ddb4f1ebbd59cdcd5f59f7c
77f9460c4baa43a7bbaaf7f2aff205bd
85fa5254305b4c72b1b7c0103aaee269
062d45aa86694b06aad841236b839341
7a265293560f4223ab8248fda502c89b
b748c13ac45747b99aead4b0a2d7d179
cbcbf623c75d407fa3c88cfc89a90ed4
da263eed8771496faebb6290527f77fa
22231088dec04cffa40fb79ff56c6453
594a66de4b874b3491649c5d033917f6
4f6802ebd0cc4a39b25a67191c3af09d
8878b7ab8aa445cdadbef0f7c70d3deb
2c3ed0154f0c4ddbad498b7ae928b9bc
cac1dcaa80e54e2db3248987d2dbda4a
f9a3567e6dd54bf5900444c8b1c03815
f0d25d7b615a4495b51c01ab15093a88
243e45926311437c8b26cede2dc7de25
e4738c50e4cd448fbac252571c0907df
261d3593cc054569bcd645885d22c2ee
64a4796356a04cc4a09506aeb6f5b8fd
9aeebcbdde074ed69738589ca9bde0f1
ec040c956861466b84ed7f7cec601be0
18bd233781e44e7cb152800db4c4edc7
1b7b251df1244e8db46a45c186aada2b
3e32f644c9074cb3bbb15c5be1d9b95e
625309e3ffd14a90bfbd6d48142ac60e
664f0cf347ce4767add576da584526e7
fe3893fd376849fe9fed00e328e61470
254ce1441bbf4a7eae1cdf8d288e61e8
90896c6b309a49f48cc3b7a1570e1846
5f47acd1319245648098c1aec9b95f23
f798033052614b9eae8da7eba4ba3475
3471c4320e4e431eb1fa9f5eb5cb21e0
855f473fed034b1fa17f4f65b850e03b
1245de826d0d4373bdd4cf2157792954
543a8b16efca4fa2b5263315e8b21660
2dc186d699274257922853d783c0ec13
a92e6b1783db4b49a4aaa424b9e1b03f
16773feb48054cf0942a2a27204b3572
1e58da2107ac4ee39e28a93b32e1df1d
67622c19498d4178a1bab6b19087f2c2
412b6b4474fc43ccbeb1e7707b6420ee
7d0fd632913c425eb5f087600ccea870
439687baddb44852a43048b04d38427c
8b2dcc4e50464429a18b11e4aacf51a2
2fccb1c832894fe6b0b61bbdf175cd39
6d224b3d6e8747319fcf01b0309d8a0f
b4982e3b4b594cb4b334c95c2c96355e
c47fbaf90d1d4e9caf211f93b742631f
9440271e8ba6447d9a008e89a93016a6
8d24274b6a3f436a88362438aa6a221d
60452bd3f71747ed8c3706abb2235bd5
6fa93f2ee30740b89496439dd7227a4f
cc17504cf80641f882c8665ae166ba44
743efe8eac6e47a789928da4fb5b6f70
4c4d2df3461448c4a3e934cf4a7ea74f
b231eb3fb46240d38157764e8906aa7b
a234ae65f7ed48f6b1887644eed36cc2
c9cd5ed3df3f4a27957b45498f0c48ef
3eb2fbbb0a714bb7986aef3ee34f0254
d15968e605f0440c9e740e3f4e498a9f
63a8d50e8db24b91a13d4ac2fb6f7d5b
5377df9296154c57926672ca8b3c9478
a4db4a3a9d5148648a23aa7f4f77f1e0
d0aee355a2ba42de89d659385514b0fa
e92e7702481a4575a66d59c061459c5b
1b6c542d8f994d85a1312ab2cf4545ce
88e347a515474ec59013673e5402b97f
2187d9b2dc2b4d96baceade5ae99db44
4d641e69ca5b4acf90f8afe238d8a940
9c0f4c101c434831b928114c5fc0c401
140e16f6cf134785a98ae9baee5b9e7b
4dac5910f4d047e1b213c058e2230bf3
fb50a7e6333f49e4b469234426d5002f
c96c5f2fa167458eaa6d01997d90a980
1e79721e587c4a92aa55cdf8195c8c55
0da27fc5d8384ce299197b4e06cda1d4
a5e32d9cf5834e86b3fe02bc0e3104d6
2dc1826647594b1fb728de67d3df363c
0276371815254198bd22cc76f901b332
bf9d77b7b4a64e7a97ade2a62af1f8e0
268cce3249f64895b6b47e86cf296e5b
d523201fc950435f803bf89d5f042c45
607a4306b90b467f8b19c2c943bc92ef
adfa9fb63a874ca1ad746ff573f03f28
fe88132c70d141e8839ce9e7f0308750

Should be just as efficient (more effecient) than Javas actually.

nvm is not compatible with the npm config "prefix" option:

enter image description hereI had the same problem and it was really annoying each time with the terminal. I run the command to the terminal and it was fixed

For those try to remove nvm from brew

it may not be enough to just brew uninstall nvm

if you see npm prefix is still /usr/local, run this command

sudo rm -rf /usr/local/{lib/node{,/.npm,_modules},bin,share/man}/{npm*,node*,man1/node*}

How do I wrap text in a pre tag?

The Best Cross Browser Way worked for me to get line breaks and shows exact code or text: (chrome, internet explorer, Firefox)

CSS:

xmp{ white-space:pre-wrap; word-wrap:break-word; }

HTML:

<xmp> your text or code </xmp>

Switch case: can I use a range instead of a one number

A bit late to the game for this question, but in recent changes introduced in C# 7 (Available by default in Visual Studio 2017/.NET Framework 4.6.2), range-based switching is now possible with the switch statement.

Example:

int i = 63;

switch (i)
{
    case int n when (n >= 100):
        Console.WriteLine($"I am 100 or above: {n}");
        break;

    case int n when (n < 100 && n >= 50 ):
        Console.WriteLine($"I am between 99 and 50: {n}");
        break;

    case int n when (n < 50):
        Console.WriteLine($"I am less than 50: {n}");
        break;
}

Notes:

  • The parentheses ( and ) are not required in the when condition, but are used in this example to highlight the comparison(s).
  • var may also be used in lieu of int. For example: case var n when n >= 100:.

How to select rows that have current day's timestamp?

Or you could use the CURRENT_DATE alternative, with the same result:

SELECT * FROM yourtable WHERE created >= CURRENT_DATE

Examples from database.guide

PHP: How to handle <![CDATA[ with SimpleXMLElement?

This did the trick for me:

echo trim($entry->title);

Tomcat started in Eclipse but unable to connect to http://localhost:8085/

You can change the port number:

Open the server tab in eclipse -> right click open click on open---->you can change the port number.

Run the application with http://localhost:8080/Applicationname it will give output and also check http://localhost:8080/Applicationname/index.jsp

Select records from today, this week, this month php mysql

Nathan's answer will give you jokes from last 24, 168, and 744 hours, NOT the jokes from today, this week, this month. If that's what you want, great, but I think you might be looking for something different.

Using his code, at noon, you will get the jokes beginning yesterday at noon, and ending today at noon. If you really want today's jokes, try the following:

SELECT * FROM jokes WHERE date >= CURRENT_DATE() ORDER BY score DESC;  

You would have to do something a little different from current week, month, etc., but you get the idea.

How to grab substring before a specified character jQuery or JavaScript

almost the same thing as David G's answer but without the anonymous function, if you don't feel like including one.

s = s.substr(0, s.indexOf(',') === -1 ? s.length : s.indexOf(','));

in this case we make use of the fact that the second argument of substr is a length, and that we know our substring is starting at 0.

the top answer is not a generic solution because of the undesirable behavior if the string doesn't contain the character you are looking for.

if you want correct behavior in a generic case, use this method or David G's method, not the top answer

regex and split methods will also work, but may be somewhat slower / overkill for this specific problem.

Is there a "standard" format for command line/shell help text?

I would follow official projects like tar as an example. In my opinion help msg. needs to be simple and descriptive as possible. Examples of use are good too. There is no real need for "standard help".

comparing elements of the same array in java

Try this or purpose will solve with lesser no of steps

for (int i = 0; i < a.length; i++) 
{
    for (int k = i+1; k < a.length; k++) 
    {
        if (a[i] != a[k]) 
         {
            System.out.println(a[i]+"not the same with"+a[k]+"\n");
        }
    }
}

AWS : The config profile (MyName) could not be found

I think there is something missing from the AWS documentation in http://docs.aws.amazon.com/lambda/latest/dg/setup-awscli.html, it did not mention that you should edit the file ~/.aws/config to add your username profile. There are two ways to do this:

  1. edit ~/.aws/config or

  2. aws configure --profile "your username"

How do I escape double quotes in attributes in an XML String in T-SQL?

tSql escapes a double quote with another double quote. So if you wanted it to be part of your sql string literal you would do this:

declare @xml xml 
set @xml = "<transaction><item value=""hi"" /></transaction>"

If you want to include a quote inside a value in the xml itself, you use an entity, which would look like this:

declare @xml xml
set @xml = "<transaction><item value=""hi &quot;mom&quot; lol"" /></transaction>"

C++ printing spaces or tabs given a user input integer

Simply add spaces for { 2 3 4 5 6 } like these:

cout<<"{";

for(){
    cout<<" "<<n;    //n is the element to print !
}

cout<<" }";

Using XPATH to search text containing &nbsp;

I cannot get a match using Xpather, but the following worked for me with plain XML and XSL files in Microsoft's XML Notepad:

<xsl:value-of select="count(//td[text()='&nbsp;'])" />

The value returned is 1, which is the correct value in my test case.

However, I did have to declare nbsp as an entity within my XML and XSL using the following:

<!DOCTYPE xsl:stylesheet [ <!ENTITY nbsp "&#160;"> ]>

I'm not sure if that helps you, but I was able to actually find nbsp using an XPath expression.

Edit: My code sample actually contains the characters '&nbsp;' but the JavaScript syntax highlight converts it to the space character. Don't be mislead!

What is the best way to know if all the variables in a Class are null?

This can be done fairly easily using a Lombok generated equals and a static EMPTY object:

import lombok.Data;

public class EmptyCheck {
    public static void main(String[] args) {
        User user1 = new User();

        User user2 = new User();
        user2.setName("name");

        System.out.println(user1.isEmpty()); // prints true
        System.out.println(user2.isEmpty()); // prints false
    }

    @Data
    public static class User {
        private static final User EMPTY = new User();

        private String id;
        private String name;
        private int age;

        public boolean isEmpty() {
            return this.equals(EMPTY);
        }
    }
}

Prerequisites:

  • Default constructor should not be implemented with custom behavior as that is used to create the EMPTY object
  • All fields of the class should have an implemented equals (built-in Java types are usually not a problem, in case of custom types you can use Lombok)

Advantages:

  • No reflection involved
  • As new fields added to the class, this does not require any maintenance as due to Lombok they will be automatically checked in the equals implementation
  • Unlike some other answers this works not just for null checks but also for primitive types which have a non-null default value (e.g. if field is int it checks for 0, in case of boolean for false, etc.)

How to add "class" to host element?

This way you don't need to add the CSS outside of the component:

@Component({
   selector: 'body',
   template: 'app-element',
   // prefer decorators (see below)
   // host:     {'[class.someClass]':'someField'}
})
export class App implements OnInit {
  constructor(private cdRef:ChangeDetectorRef) {}
  
  someField: boolean = false;
  // alternatively also the host parameter in the @Component()` decorator can be used
  @HostBinding('class.someClass') someField: boolean = false;

  ngOnInit() {
    this.someField = true; // set class `someClass` on `<body>`
    //this.cdRef.detectChanges(); 
  }
}

Plunker example

This CSS is defined inside the component and the selector is only applied if the class someClass is set on the host element (from outside):

:host(.someClass) {
  background-color: red;
}

Reading *.wav files in Python

if its just two files and the sample rate is significantly high, you could just interleave them.

from scipy.io import wavfile
rate1,dat1 = wavfile.read(File1)
rate2,dat2 = wavfile.read(File2)

if len(dat2) > len(dat1):#swap shortest
    temp = dat2
    dat2 = dat1
    dat1 = temp

output = dat1
for i in range(len(dat2)/2): output[i*2]=dat2[i*2]

wavfile.write(OUTPUT,rate,dat)

Angular 2 - Using 'this' inside setTimeout

You need to use Arrow function ()=> ES6 feature to preserve this context within setTimeout.

// var that = this;                             // no need of this line
this.messageSuccess = true;

setTimeout(()=>{                           //<<<---using ()=> syntax
      this.messageSuccess = false;
 }, 3000);

How to convert an iterator to a stream?

Great suggestion! Here's my reusable take on it:

public class StreamUtils {

    public static <T> Stream<T> asStream(Iterator<T> sourceIterator) {
        return asStream(sourceIterator, false);
    }

    public static <T> Stream<T> asStream(Iterator<T> sourceIterator, boolean parallel) {
        Iterable<T> iterable = () -> sourceIterator;
        return StreamSupport.stream(iterable.spliterator(), parallel);
    }
}

And usage (make sure to statically import asStream):

List<String> aPrefixedStrings = asStream(sourceIterator)
                .filter(t -> t.startsWith("A"))
                .collect(toList());

Zooming MKMapView to fit annotation pins?

Based on answers above you can use universal method to zoom map to fit all annotations and overlays at the same time.

-(MKMapRect)getZoomingRectOnMap:(MKMapView*)map toFitAllOverlays:(BOOL)overlays andAnnotations:(BOOL)annotations includeUserLocation:(BOOL)userLocation {
    if (!map) {
        return MKMapRectNull;
    }

    NSMutableArray* overlaysAndAnnotationsCoordinateArray = [[NSMutableArray alloc]init];        
    if (overlays) {
        for (id <MKOverlay> overlay in map.overlays) {
            MKMapPoint overlayPoint = MKMapPointForCoordinate(overlay.coordinate);
            NSArray* coordinate = @[[NSNumber numberWithDouble:overlayPoint.x], [NSNumber numberWithDouble:overlayPoint.y]];
            [overlaysAndAnnotationsCoordinateArray addObject:coordinate];
        }
    }

    if (annotations) {
        for (id <MKAnnotation> annotation in map.annotations) {
            MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
            NSArray* coordinate = @[[NSNumber numberWithDouble:annotationPoint.x], [NSNumber numberWithDouble:annotationPoint.y]];
            [overlaysAndAnnotationsCoordinateArray addObject:coordinate];
        }
    }

    MKMapRect zoomRect = MKMapRectNull;
    if (userLocation) {
        MKMapPoint annotationPoint = MKMapPointForCoordinate(map.userLocation.coordinate);
        zoomRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.1, 0.1);
    }

    for (NSArray* coordinate in overlaysAndAnnotationsCoordinateArray) {
        MKMapRect pointRect = MKMapRectMake([coordinate[0] doubleValue], [coordinate[1] doubleValue], 0.1, 0.1);
        zoomRect = MKMapRectUnion(zoomRect, pointRect);
    }

    return zoomRect;
}

And then:

MKMapRect mapRect = [self getZoomingRectOnMap:mapView toFitAllOverlays:YES andAnnotations:YES includeUserLocation:NO];
[mapView setVisibleMapRect:mapRect edgePadding:UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0) animated:YES];

How do I clear a search box with an 'x' in bootstrap 3?

Place the image (cancel icon) with position absolute, adjust top and left properties and call method onclick event which clears the input field.

<div class="form-control">
    <input type="text" id="inputField" />
</div>
<span id="iconSpan"><img src="icon.png" onclick="clearInputField()"/></span>

In css position the span accordingly,

#iconSpan {
 position : absolute;
 top:1%;
 left :14%;
}

How to prevent long words from breaking my div?

HYPHENATOR is the right answer (given above). The real problem behind your question is that web browsers are still (in 2008) extremely primitive that they do not have a hyphenation-feature. Look, we are still on the early beginnings of computer usage - we have to be patient. As long as designers rule the web world we will have a hard time waiting for some real useful new features.

UPDATE: As of December, 2011, we now have another option, with the emerging support of these tags in FF and Safari:

p {
    -webkit-hyphens: auto;
    -moz-hyphens: auto;
    hyphens: auto;
}

I've done some basic testing and it seems to work on a recent version of Mobile Safari and Safari 5.1.1.

Compatibility table: https://developer.mozilla.org/en/CSS/hyphens#AutoCompatibilityTable

How to get a substring between two strings in PHP?

I had some problems with the get_string_between() function, used here. So I came with my own version. Maybe it could help people in the same case as mine.

protected function string_between($string, $start, $end, $inclusive = false) { 
   $fragments = explode($start, $string, 2);
   if (isset($fragments[1])) {
      $fragments = explode($end, $fragments[1], 2);
      if ($inclusive) {
         return $start.$fragments[0].$end;
      } else {
         return $fragments[0];
      }
   }
   return false;
}

How to check if a table exists in a given schema

Perhaps use information_schema:

SELECT EXISTS(
    SELECT * 
    FROM information_schema.tables 
    WHERE 
      table_schema = 'company3' AND 
      table_name = 'tableincompany3schema'
);

Is there a way to override class variables in Java?

Why would you want to override variables when you could easily reassign them in the subClasses.

I follow this pattern to work around the language design. Assume a case where you have a weighty service class in your framework which needs be used in different flavours in multiple derived applications.In that case , the best way to configure the super class logic is by reassigning its 'defining' variables.

public interface ExtensibleService{
void init();
}

public class WeightyLogicService implements ExtensibleService{
    private String directoryPath="c:\hello";

    public void doLogic(){
         //never forget to call init() before invocation or build safeguards
         init();
       //some logic goes here
   }

   public void init(){}    

}

public class WeightyLogicService_myAdaptation extends WeightyLogicService {
   @Override
   public void init(){
    directoryPath="c:\my_hello";
   }

}

IIS7 Cache-Control

That's not true Jeff.

You simply have to select a folder within your IIS 7 Manager UI (e.g. Images or event the Default Web Application folder) and then click on "HTTP Response Headers". Then you have to click on "Set Common Header.." in the right pane and select the "Expire Web content". There you can easily configure a max-age of 24 hours by choosing "After:", entering "24" in the Textbox and choose "Hours" in the combobox.

Your first paragraph regarding the web.config entry is right. I'd add the cacheControlCustom-attribute to set the cache control header to "public" or whatever is needed in that case.

You can, of course, achieve the same by providing web.config entries (or files) as needed.

Edit: removed a confusing sentence :)

Arrow operator (->) usage in C

a->b is just short for (*a).b in every way (same for functions: a->b() is short for (*a).b()).

Parameter binding on left joins with array in Laravel Query Builder

You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw(), ensure that you binding the parameters.

Try the following:

$array = array(1,2,3);       $query = DB::table('offers');             $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used');             $query->leftJoin('user_offer_collection', function ($join) use ($array)             {                 $join->on('user_offer_collection.offers_id', '=', 'offers.id')                       ->whereIn('user_offer_collection.user_id', $array);             });       $query->get(); 

Saving lists to txt file

@Jon's answer is great and will get you where you need to go. So why is your code printing out what it is. The answer: You're not writing out the contents of your list, but the String representation of your list itself, by an implicit call to Lists.verbList.ToString(). Object.ToString() defines the default behavior you're seeing here.

php search array key and get value

Here is an example straight from PHP.net

$a = array(
    "one" => 1,
    "two" => 2,
    "three" => 3,
    "seventeen" => 17
);

foreach ($a as $k => $v) {
    echo "\$a[$k] => $v.\n";
}

in the foreach you can do a comparison of each key to something that you are looking for

"Field has incomplete type" error

You are using a forward declaration for the type MainWindowClass. That's fine, but it also means that you can only declare a pointer or reference to that type. Otherwise the compiler has no idea how to allocate the parent object as it doesn't know the size of the forward declared type (or if it actually has a parameterless constructor, etc.)

So, you either want:

// forward declaration, details unknown
class A;

class B {
  A *a;  // pointer to A, ok
};

Or, if you can't use a pointer or reference....

// declaration of A
#include "A.h"

class B {
  A a;  // ok, declaration of A is known
};

At some point, the compiler needs to know the details of A.

If you are only storing a pointer to A then it doesn't need those details when you declare B. It needs them at some point (whenever you actually dereference the pointer to A), which will likely be in the implementation file, where you will need to include the header which contains the declaration of the class A.

// B.h
// header file

// forward declaration, details unknown
class A;

class B {
public: 
    void foo();
private:
  A *a;  // pointer to A, ok
};

// B.cpp
// implementation file

#include "B.h"
#include "A.h"  // declaration of A

B::foo() {
    // here we need to know the declaration of A
    a->whatever();
}

Capturing a single image from my webcam in Java or Python

@thebjorn has given a good answer. But if you want more options, you can try OpenCV, SimpleCV.

using SimpleCV (not supported in python3.x):

from SimpleCV import Image, Camera

cam = Camera()
img = cam.getImage()
img.save("filename.jpg")

using OpenCV:

from cv2 import *
# initialize the camera
cam = VideoCapture(0)   # 0 -> index of camera
s, img = cam.read()
if s:    # frame captured without any errors
    namedWindow("cam-test",CV_WINDOW_AUTOSIZE)
    imshow("cam-test",img)
    waitKey(0)
    destroyWindow("cam-test")
    imwrite("filename.jpg",img) #save image

using pygame:

import pygame
import pygame.camera

pygame.camera.init()
pygame.camera.list_cameras() #Camera detected or not
cam = pygame.camera.Camera("/dev/video0",(640,480))
cam.start()
img = cam.get_image()
pygame.image.save(img,"filename.jpg")

Install OpenCV:

install python-opencv bindings, numpy

Install SimpleCV:

install python-opencv, pygame, numpy, scipy, simplecv

get latest version of SimpleCV

Install pygame:

install pygame

How to extract Month from date in R

Without the need of an external package:

if your date is in the following format:

myDate = as.POSIXct("2013-01-01")

Then to get the month number:

format(myDate,"%m")

And to get the month string:

format(myDate,"%B")

How to print a linebreak in a python function?

You have your slash backwards, it should be "\n"

node.js require() cache - possible to invalidate?

You can always safely delete an entry in require.cache without a problem, even when there are circular dependencies. Because when you delete, you just delete a reference to the cached module object, not the module object itself, the module object will not be GCed because in case of circular dependencies, there is still a object referencing this module object.

Suppose you have:

script a.js:

var b=require('./b.js').b;
exports.a='a from a.js';
exports.b=b;

and script b.js:

var a=require('./a.js').a;
exports.b='b from b.js';
exports.a=a;

when you do:

var a=require('./a.js')
var b=require('./b.js')

you will get:

> a
{ a: 'a from a.js', b: 'b from b.js' }
> b
{ b: 'b from b.js', a: undefined }

now if you edit your b.js:

var a=require('./a.js').a;
exports.b='b from b.js. changed value';
exports.a=a;

and do:

delete require.cache[require.resolve('./b.js')]
b=require('./b.js')

you will get:

> a
{ a: 'a from a.js', b: 'b from b.js' }
> b
{ b: 'b from b.js. changed value',
  a: 'a from a.js' }

===

The above is valid if directly running node.js. However, if using tools that have their own module caching system, such as jest, the correct statement would be:

jest.resetModules();

how to add <script>alert('test');</script> inside a text box?

JQuery version:

$('yourInputSelectorHere').val("<script>alert('test');<\/script>")

How to return rows from left table not found in right table?

This is an example from real life work, I was asked to supply a list of users that bought from our site in the last 6 months but not in the last 3 months.

For me, the most understandable way I can think of is like so:

--Users that bought from us 6 months ago and between 3 months ago.
DECLARE @6To3MonthsUsers table (UserID int,OrderDate datetime)
INSERT @6To3MonthsUsers
    select u.ID,opd.OrderDate
        from OrdersPaid opd
        inner join Orders o
        on opd.OrderID = o.ID
        inner join Users u
        on o.BuyerID = u.ID
        where 1=1 
        and opd.OrderDate BETWEEN DATEADD(m,-6,GETDATE()) and DATEADD(m,-3,GETDATE())

--Users that bought from us in the last 3 months
DECLARE @Last3MonthsUsers table (UserID int,OrderDate datetime)
INSERT @Last3MonthsUsers
    select u.ID,opd.OrderDate
        from OrdersPaid opd
        inner join Orders o
        on opd.OrderID = o.ID
        inner join Users u
        on o.BuyerID = u.ID
        where 1=1 
        and opd.OrderDate BETWEEN DATEADD(m,-3,GETDATE()) and GETDATE()

Now, with these 2 tables in my hands I need to get only the users from the table @6To3MonthsUsers that are not in @Last3MonthsUsers table.

There are 2 simple ways to achieve that:

  1. Using Left Join:

    select distinct a.UserID
    from @6To3MonthsUsers a
    left join @Last3MonthsUsers b
    on a.UserID = b.UserID
    where b.UserID is null
    
  2. Not in:

    select distinct a.UserID
    from @6To3MonthsUsers a
    where a.UserID not in (select b.UserID from @Last3MonthsUsers b)
    

Both ways will get me the same result, I personally prefer the second way because it's more readable.

Make a div fill the height of the remaining screen space

There really isn't a sound, cross-browser way to do this in CSS. Assuming your layout has complexities, you need to use JavaScript to set the element's height. The essence of what you need to do is:

Element Height = Viewport height - element.offset.top - desired bottom margin

Once you can get this value and set the element's height, you need to attach event handlers to both the window onload and onresize so that you can fire your resize function.

Also, assuming your content could be larger than the viewport, you will need to set overflow-y to scroll.

Smooth scroll to div id jQuery

This is the simplest.Source-https://www.w3schools.com/jsref/met_element_scrollintoview.asp

var elmnt = document.getElementById("content");
elmnt.scrollIntoView();

How can I create a table with borders in Android?

What I wanted is a table like this

table image with vertical dividers

I added this in my styles.xml :

      <style name="Divider">
        <item name="android:layout_width">1dip</item>
        <item name="android:layout_height">match_parent</item>
        <item name="android:background">@color/divider_color</item>
    </style>

    <style name="Divider_invisible">
        <item name="android:layout_width">1dip</item>
        <item name="android:layout_height">match_parent</item>
    </style>

Then in my table layout :

 <TableLayout
            android:id="@+id/table"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:stretchColumns="*" >

            <TableRow
                android:id="@+id/tableRow1"
                android:layout_width="fill_parent"
                android:layout_height="match_parent"
                android:background="#92C94A" >

                <TextView
                    android:id="@+id/textView11"
                    android:paddingBottom="10dp"
                    android:paddingLeft="5dp"
                    android:paddingRight="5dp"
                    android:paddingTop="10dp" />

                <LinearLayout
                    android:layout_width="1dp"
                    android:layout_height="match_parent" >

                    <View style="@style/Divider_invisible" />
                </LinearLayout>

                <TextView
                    android:id="@+id/textView12"
                    android:paddingBottom="10dp"
                    android:paddingLeft="5dp"
                    android:paddingRight="5dp"
                    android:paddingTop="10dp"
                    android:text="@string/main_wo_colon"
                    android:textColor="@color/white"
                    android:textSize="16sp" />

                <LinearLayout
                    android:layout_width="1dp"
                    android:layout_height="match_parent" >

                    <View style="@style/Divider" />
                </LinearLayout>

                <TextView
                    android:id="@+id/textView13"
                    android:paddingBottom="10dp"
                    android:paddingLeft="5dp"
                    android:paddingRight="5dp"
                    android:paddingTop="10dp"
                    android:text="@string/side_wo_colon"
                    android:textColor="@color/white"
                    android:textSize="16sp" />

                <LinearLayout
                    android:layout_width="1dp"
                    android:layout_height="match_parent" >

                    <View style="@style/Divider" />
                </LinearLayout>

                <TextView
                    android:id="@+id/textView14"
                    android:paddingBottom="10dp"
                    android:paddingLeft="5dp"
                    android:paddingRight="5dp"
                    android:paddingTop="10dp"
                    android:text="@string/total"
                    android:textColor="@color/white"
                    android:textSize="16sp" />
            </TableRow>

            <!-- display this button in 3rd column via layout_column(zero based) -->

            <TableRow
                android:id="@+id/tableRow2"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="#6F9C33" >

                <TextView
                    android:id="@+id/textView21"
                    android:padding="5dp"
                    android:text="@string/servings"
                    android:textColor="@color/white"
                    android:textSize="16sp" />

                <LinearLayout
                    android:layout_width="1dp"
                    android:layout_height="match_parent" >

                    <View style="@style/Divider" />
                </LinearLayout>

..........
.......
......

How to check if a variable is null or empty string or all whitespace in JavaScript?

When checking for white space the c# method uses the Unicode standard. White space includes spaces, tabs, carriage returns and many other non-printing character codes. So you are better of using:

function isNullOrWhiteSpace(str){
    return str == null || str.replace(/\s/g, '').length < 1;
}

Return a `struct` from a function in C

struct emp {
    int id;
    char *name;
};

struct emp get() {
    char *name = "John";

    struct emp e1 = {100, name};

    return (e1);
}

int main() {

    struct emp e2 = get();

    printf("%s\n", e2.name);
}

works fine with newer versions of compilers. Just like id, content of the name gets copied to the assigned structure variable.

Java Wait for thread to finish

The join() method allows one thread to wait for the completion of another.However, as with sleep, join is dependent on the OS for timing, so you should not assume that join will wait exactly as long as you specify.

Using "word-wrap: break-word" within a table

You can try this:

td p {word-break:break-all;}

This, however, makes it appear like this when there's enough space, unless you add a <br> tag:

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

So, I would then suggest adding <br> tags where there are newlines, if possible.

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

http://jsfiddle.net/LLyH3/3/

Also, if this doesn't solve your problem, there's a similar thread here.

node-request - Getting error "SSL23_GET_SERVER_HELLO:unknown protocol"

I got this error because I was using require('https') where I should have been using require('http').

How to add a vertical Separator?

In the past I've used the style found here

<Style x:Key="VerticalSeparatorStyle" 
       TargetType="{x:Type Separator}"
       BasedOn="{StaticResource {x:Type Separator}}">
    <Setter Property="Margin" Value="6,0,6,0"/>
    <Setter Property="LayoutTransform">
        <Setter.Value>
            <TransformGroup>
                <TransformGroup.Children>
                    <TransformCollection>
                        <RotateTransform Angle="90"/>
                    </TransformCollection>
                </TransformGroup.Children>
            </TransformGroup>
        </Setter.Value>
    </Setter>
</Style>

<Separator Style="{DynamicResource VerticalSeparatorStyle}" />

You need to set the transformation in LayoutTransform instead of RenderTransform so the transformation occurs during the Layout pass, not during the Render pass. The Layout pass occurs when WPF is trying to layout controls and figure out how much space each control takes up, while the Render pass occurs after the layout pass when WPF is trying to render controls.

You can read more about the difference between LayoutTransform and RenderTransform here or here

Getting all types in a namespace via reflection

Namespaces are actually rather passive in the design of the runtime and serve primarily as organizational tools. The Full Name of a type in .NET consists of the Namespace and Class/Enum/Etc. combined. If you only wish to go through a specific assembly, you would simply loop through the types returned by assembly.GetExportedTypes() checking the value of type.Namespace. If you were trying to go through all assemblies loaded in the current AppDomain it would involve using AppDomain.CurrentDomain.GetAssemblies()

SQL WHERE ID IN (id1, id2, ..., idn)

In most database systems, IN (val1, val2, …) and a series of OR are optimized to the same plan.

The third way would be importing the list of values into a temporary table and join it which is more efficient in most systems, if there are lots of values.

You may want to read this articles:

One DbContext per web request... why?

What I like about it is that it aligns the unit-of-work (as the user sees it - i.e. a page submit) with the unit-of-work in the ORM sense.

Therefore, you can make the entire page submission transactional, which you could not do if you were exposing CRUD methods with each creating a new context.

How to include "zero" / "0" results in COUNT aggregate?

if you do the outer join (with the count), and then use this result as a sub-table, you can get 0 as expected (thanks to the nvl function)

Ex:

select P.person_id, nvl(A.nb_apptmts, 0) from 
(SELECT person.person_id
FROM person) P
LEFT JOIN 
(select person_id, count(*) as nb_apptmts
from appointment 
group by person_id) A
ON P.person_id = A.person_id

How can I create an array with key value pairs?

You can create the single value array key-value as

$new_row = array($row["datasource_id"]=>$row["title"]);

inside while loop, and then use array_merge function in loop to combine the each new $new_row array.

How do I delete virtual interface in Linux?

Have you tried:

ifconfig 10:35978f0 down

As the physical interface is 10 and the virtual aspect is after the colon :.

See also https://www.cyberciti.biz/faq/linux-command-to-remove-virtual-interfaces-or-network-aliases/

How to connect from windows command prompt to mysql command line

To make it easier to invoke MySQL programs, you can add the path name of the MySQL bin directory to your Windows system PATH environment variable:

On the Windows desktop, right-click the My Computer icon, and select Properties.

Next select the Advanced tab from the System Properties menu that appears, and click the Environment Variables button.

Under System Variables, select Path, and then click the Edit button. The Edit System Variable dialogue should appear.

Place your cursor at the end of the text appearing in the space marked Variable Value. (Use the End key to ensure that your cursor is positioned at the very end of the text in this space.) Then enter the complete path name of your MySQL bin directory (for example, C:\Program Files\MySQL\MySQL Server 8.0\bin).

Open a different terminal and if you are using root as user run mysql -u root -p else use the a different username you created.

Ping a site in Python?

Use this it's tested on python 2.7 and works fine it returns ping time in milliseconds if success and return False on fail.

import platform,subproccess,re
def Ping(hostname,timeout):
    if platform.system() == "Windows":
        command="ping "+hostname+" -n 1 -w "+str(timeout*1000)
    else:
        command="ping -i "+str(timeout)+" -c 1 " + hostname
    proccess = subprocess.Popen(command, stdout=subprocess.PIPE)
    matches=re.match('.*time=([0-9]+)ms.*', proccess.stdout.read(),re.DOTALL)
    if matches:
        return matches.group(1)
    else: 
        return False

Invert "if" statement to reduce nesting

My idea is that the return "in the middle of a function" shouldn't be so "subjective". The reason is quite simple, take this code:

    function do_something( data ){

      if (!is_valid_data( data )) 
            return false;


       do_something_that_take_an_hour( data );

       istance = new object_with_very_painful_constructor( data );

          if ( istance is not valid ) {
               error_message( );
                return ;

          }
       connect_to_database ( );
       get_some_other_data( );
       return;
    }

Maybe the first "return" it's not SO intuitive, but that's really saving. There are too many "ideas" about clean codes, that simply need more practise to lose their "subjective" bad ideas.

How to set cookie in node js using express framework?

Not exactly answering your question, but I came across your question, while looking for an answer to an issue that I had. Maybe it will help somebody else.

My issue was that cookies were set in server response, but were not saved by the browser.

The server response came back with cookies set:

Set-Cookie:my_cookie=HelloWorld; Path=/; Expires=Wed, 15 Mar 2017 15:59:59 GMT 

This is how I solved it.

I used fetch in the client-side code. If you do not specify credentials: 'include' in the fetch options, cookies are neither sent to server nor saved by the browser, even though the server response sets cookies.

Example:

var headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');

return fetch('/your/server_endpoint', {
    method: 'POST',
    mode: 'same-origin',
    redirect: 'follow',
    credentials: 'include', // Don't forget to specify this if you need cookies
    headers: headers,
    body: JSON.stringify({
        first_name: 'John',
        last_name: 'Doe'
    })
})

I hope this helps somebody.

Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource

Its a CORS issue, your api cannot be accessed directly from remote or different origin, In order to allow other ip address or other origins from accessing you api, you should add the 'Access-Control-Allow-Origin' on the api's header, you can set its value to '*' if you want it to be accessible to all, or you can set specific domain or ips like 'http://siteA.com' or 'http://192. ip address ';

Include this on your api's header, it may vary depending on how you are displaying json data,

if your using ajax, to retrieve and display data your header would look like this,

$.ajax({
   url: '',
   headers: {  'Access-Control-Allow-Origin': 'http://The web site allowed to access' },
   data: data,
   type: 'dataType',
   /* etc */
   success: function(jsondata){

   }
})

What is Scala's yield?

Yes, as Earwicker said, it's pretty much the equivalent to LINQ's select and has very little to do with Ruby's and Python's yield. Basically, where in C# you would write

from ... select ??? 

in Scala you have instead

for ... yield ???

It's also important to understand that for-comprehensions don't just work with sequences, but with any type which defines certain methods, just like LINQ:

  • If your type defines just map, it allows for-expressions consisting of a single generator.
  • If it defines flatMap as well as map, it allows for-expressions consisting of several generators.
  • If it defines foreach, it allows for-loops without yield (both with single and multiple generators).
  • If it defines filter, it allows for-filter expressions starting with an if in the for expression.

DataTables: Cannot read property 'length' of undefined

you can try checking out your fields as you are rendering email field which is not available in your ajax

_x000D_
_x000D_
$.ajax({_x000D_
  url: "url",_x000D_
  type: 'GET',_x000D_
  success: function(data) {_x000D_
    var new_data = {_x000D_
      "data": data_x000D_
    };_x000D_
    console.log(new_data);_x000D_
  }_x000D_
});
_x000D_
_x000D_
_x000D_

How to get everything after a certain character?

I use strrchr(). For instance to find the extension of a file I use this function:

$string = 'filename.jpg';
$extension = strrchr( $string, '.'); //returns ".jpg"

Tools: replace not replacing in Android manifest

FIXED IT HAD THE EXACT ERROR, Just add this tools:replace="android:icon,android:theme"

into your application tag in your manifest, it works just fine,

Which is the best library for XML parsing in java

You don't need an external library for parsing XML in Java. Java has come with built-in implementations for SAX and DOM for ages.

How do I install the Nuget provider for PowerShell on a unconnected machine so I can install a nuget package from the PS command line?

Although I've tried all the previous answers, only the following one worked out:

1 - Open Powershell (as Admin)

2 - Run:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

3 - Run:

Install-PackageProvider -Name NuGet

The author is Niels Weistra: Microsoft Forum

How to assert two list contain the same elements in Python?

Converting your lists to sets will tell you that they contain the same elements. But this method cannot confirm that they contain the same number of all elements. For example, your method will fail in this case:

L1 = [1,2,2,3]
L2 = [1,2,3,3]

You are likely better off sorting the two lists and comparing them:

def checkEqual(L1, L2):
    if sorted(L1) == sorted(L2):
        print "the two lists are the same"
        return True
    else:
        print "the two lists are not the same"
        return False

Note that this does not alter the structure/contents of the two lists. Rather, the sorting creates two new lists

How to center HTML5 Videos?

.center { width:500px; margin-right:auto; margin-left:auto; }

Passing javascript variable to html textbox

You could also use to localStorage feature of HTML5 to store your test value and then access it at any other point in your website by using the localStorage.getItem() method. To see how this works you should look at the w3schools explanation or the explanation from the Opera Developer website. Hope this helps.

403 Forbidden error when making an ajax Post request in Django framework

Make sure you aren't caching the page/view that your form is showing up on. It could be caching your CSRF_TOKEN. Happened to me!

Hashmap holding different data types as values for instance Integer, String and Object

You have some variables that are different types in Java language like that:

 message of type string
 timestamp of type time
 count of type integer
 version of type integer

If you use a HashMap like:

HashMap<String,Object> yourHash = new HashMap<String,Object>();
yourHash.put("message","message");
yourHash.put("timestamp",timestamp);
yourHash.put("count ",count);
yourHash.put("version ",version);

If you want to use the yourHash:

for(String key : yourHash.keySet()){
  String message = (String) yourHash.get(key);
  Datetime timestamp= (Datetime) yourHash.get(key);
  int timestamp= (int) yourHash.get(key);
}

How to check if a text field is empty or not in swift

Easy way to Check

if TextField.stringValue.isEmpty {

}

Visual Studio setup problem - 'A problem has been encountered while loading the setup components. Canceling setup.'

I have Visual Studio Team System 2008 Development Edition, and had to remove all updates and Hotfixes:

  • Update KB972221
  • Hotfix KB973674
  • Hotfix KB971091

Reboot, then the following Hotfix appeared, which I then removed as per @riaraos' answer:

  • Hotfix KB952241

Before the Change/Remove would work!

Hope that helps someone else.

Center/Set Zoom of Map to cover all visible Markers?

To extend the given answer with few useful tricks:

var markers = //some array;
var bounds = new google.maps.LatLngBounds();
for(i=0;i<markers.length;i++) {
   bounds.extend(markers[i].getPosition());
}

//center the map to a specific spot (city)
map.setCenter(center); 

//center the map to the geometric center of all markers
map.setCenter(bounds.getCenter());

map.fitBounds(bounds);

//remove one zoom level to ensure no marker is on the edge.
map.setZoom(map.getZoom()-1); 

// set a minimum zoom 
// if you got only 1 marker or all markers are on the same address map will be zoomed too much.
if(map.getZoom()> 15){
  map.setZoom(15);
}

//Alternatively this code can be used to set the zoom for just 1 marker and to skip redrawing.
//Note that this will not cover the case if you have 2 markers on the same address.
if(count(markers) == 1){
    map.setMaxZoom(15);
    map.fitBounds(bounds);
    map.setMaxZoom(Null)
}

UPDATE:
Further research in the topic show that fitBounds() is a asynchronic and it is best to make Zoom manipulation with a listener defined before calling Fit Bounds.
Thanks @Tim, @xr280xr, more examples on the topic : SO:setzoom-after-fitbounds

google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
  this.setZoom(map.getZoom()-1);

  if (this.getZoom() > 15) {
    this.setZoom(15);
  }
});
map.fitBounds(bounds);

Pandas timeseries plot setting x-axis major and minor ticks and labels

Both pandas and matplotlib.dates use matplotlib.units for locating the ticks.

But while matplotlib.dates has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).

So for the moment it seems more reasonable to use matplotlib.dates (as mentioned by @BrenBarn in his comment).

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt 
import matplotlib.dates as dates

idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)

fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
                                                interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()

pandas_like_date_fomatting

(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])

JavaScript - onClick to get the ID of the clicked button

This is improvement of Prateek answer - event is pass by parameter so reply_click not need to use global variable (and as far no body presents this variant)

_x000D_
_x000D_
function reply_click(e) {
  console.log(e.target.id);
}
_x000D_
<button id="1" onClick="reply_click(event)">B1</button>
<button id="2" onClick="reply_click(event)">B2</button>
<button id="3" onClick="reply_click(event)">B3</button>
_x000D_
_x000D_
_x000D_

Browser: Identifier X has already been declared

The problem solved when I don't use any declaration like var, let or const

How do I set the proxy to be used by the JVM

This is a minor update, but since Java 7, proxy connections can now be created programmatically rather than through system properties. This may be useful if:

  1. Proxy needs to be dynamically rotated during the program's runtime
  2. Multiple parallel proxies need to be used
  3. Or just make your code cleaner :)

Here's a contrived example in groovy:

// proxy configuration read from file resource under "proxyFileName"
String proxyFileName = "proxy.txt"
String proxyPort = "1234"
String url = "http://www.promised.land"
File testProxyFile = new File(proxyFileName)
URLConnection connection

if (!testProxyFile.exists()) {

    logger.debug "proxyFileName doesn't exist.  Bypassing connection via proxy."
    connection = url.toURL().openConnection()

} else {
    String proxyAddress = testProxyFile.text
    connection = url.toURL().openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddress, proxyPort)))
}

try {
    connection.connect()
}
catch (Exception e) {
    logger.error e.printStackTrace()
}

Full Reference: http://docs.oracle.com/javase/7/docs/technotes/guides/net/proxies.html

How to turn off word wrapping in HTML?

white-space: nowrap;: Will never break text, will keep other defaults

white-space: pre;: Will never break text, will keep multiple spaces after one another as multiple spaces, will break if explicitly written to break(pressing enter in html etc)

How to break line in JavaScript?

Here you are ;-)

<script type="text/javascript">
    alert("Hello there.\nI am on a second line ;-)")
</script>

AttributeError: 'DataFrame' object has no attribute

To get all the counts for all the columns in a dataframe, it's just df.count()

Jquery UI datepicker. Disable array of Dates

IE 8 doesn't have indexOf function, so I used jQuery inArray instead.

$('input').datepicker({
    beforeShowDay: function(date){
        var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
        return [$.inArray(string, array) == -1];
    }
});

Best way to track onchange as-you-type in input type="text"?

Update:

See Another answer (2015).


Original 2009 Answer:

So, you want the onchange event to fire on keydown, blur, and paste? That's magic.

If you want to track changes as they type, use "onkeydown". If you need to trap paste operations with the mouse, use "onpaste" (IE, FF3) and "oninput" (FF, Opera, Chrome, Safari1).

1Broken for <textarea> on Safari. Use textInput instead

Setting std=c99 flag in GCC

Instead of calling /usr/bin/gcc, use /usr/bin/c99. This is the Single-Unix-approved way of invoking a C99 compiler. On an Ubuntu system, this points to a script which invokes gcc after having added the -std=c99 flag, which is precisely what you want.

Test if element is present using Selenium WebDriver?

This should do it:

try {
    driver.findElement(By.id(id));
} catch (NoSuchElementException e) {
    //do what you need here if you were expecting
    //the element wouldn't exist
}

How to join on multiple columns in Pyspark?

You should use & / | operators and be careful about operator precedence (== has lower precedence than bitwise AND and OR):

df1 = sqlContext.createDataFrame(
    [(1, "a", 2.0), (2, "b", 3.0), (3, "c", 3.0)],
    ("x1", "x2", "x3"))

df2 = sqlContext.createDataFrame(
    [(1, "f", -1.0), (2, "b", 0.0)], ("x1", "x2", "x3"))

df = df1.join(df2, (df1.x1 == df2.x1) & (df1.x2 == df2.x2))
df.show()

## +---+---+---+---+---+---+
## | x1| x2| x3| x1| x2| x3|
## +---+---+---+---+---+---+
## |  2|  b|3.0|  2|  b|0.0|
## +---+---+---+---+---+---+

How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field?

If you're running SQL Server 2005, you can write a custom CLR aggregate function to handle this.

C# version:

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Text;
using Microsoft.SqlServer.Server;
[Serializable]
[Microsoft.SqlServer.Server.SqlUserDefinedAggregate(Format.UserDefined,MaxByteSize=8000)]
public class CSV:IBinarySerialize
{
    private StringBuilder Result;
    public void Init() {
        this.Result = new StringBuilder();
    }

    public void Accumulate(SqlString Value) {
        if (Value.IsNull) return;
        this.Result.Append(Value.Value).Append(",");
    }
    public void Merge(CSV Group) {
        this.Result.Append(Group.Result);
    }
    public SqlString Terminate() {
        return new SqlString(this.Result.ToString());
    }
    public void Read(System.IO.BinaryReader r) {
        this.Result = new StringBuilder(r.ReadString());
    }
    public void Write(System.IO.BinaryWriter w) {
        w.Write(this.Result.ToString());
    }
}

Draggable div without jQuery UI

Here's my contribution:

http://jsfiddle.net/g6m5t8co/1/

<!doctype html>
<html>
    <head>
        <style>
            #container {
                position:absolute;
                background-color: blue;
                }
            #elem{
                position: absolute;
                background-color: green;
                -webkit-user-select: none;
                -moz-user-select: none;
                -o-user-select: none;
                -ms-user-select: none;
                -khtml-user-select: none;     
                user-select: none;
            }
        </style>
        <script>
            var mydragg = function(){
                return {
                    move : function(divid,xpos,ypos){
                        divid.style.left = xpos + 'px';
                        divid.style.top = ypos + 'px';
                    },
                    startMoving : function(divid,container,evt){
                        evt = evt || window.event;
                        var posX = evt.clientX,
                            posY = evt.clientY,
                        divTop = divid.style.top,
                        divLeft = divid.style.left,
                        eWi = parseInt(divid.style.width),
                        eHe = parseInt(divid.style.height),
                        cWi = parseInt(document.getElementById(container).style.width),
                        cHe = parseInt(document.getElementById(container).style.height);
                        document.getElementById(container).style.cursor='move';
                        divTop = divTop.replace('px','');
                        divLeft = divLeft.replace('px','');
                        var diffX = posX - divLeft,
                            diffY = posY - divTop;
                        document.onmousemove = function(evt){
                            evt = evt || window.event;
                            var posX = evt.clientX,
                                posY = evt.clientY,
                                aX = posX - diffX,
                                aY = posY - diffY;
                                if (aX < 0) aX = 0;
                                if (aY < 0) aY = 0;
                                if (aX + eWi > cWi) aX = cWi - eWi;
                                if (aY + eHe > cHe) aY = cHe -eHe;
                            mydragg.move(divid,aX,aY);
                        }
                    },
                    stopMoving : function(container){
                        var a = document.createElement('script');
                        document.getElementById(container).style.cursor='default';
                        document.onmousemove = function(){}
                    },
                }
            }();

        </script>
    </head>
    <body>
        <div id='container' style="width: 600px;height: 400px;top:50px;left:50px;">     
            <div id="elem" onmousedown='mydragg.startMoving(this,"container",event);' onmouseup='mydragg.stopMoving("container");' style="width: 200px;height: 100px;">
                <div style='width:100%;height:100%;padding:10px'>
                <select id=test>
                    <option value=1>first
                    <option value=2>second
                </select>
                <INPUT TYPE=text value="123">
                </div>
            </div>
        </div>  
    </body>
</html>

How do I add records to a DataGridView in VB.Net?

The function you're looking for is 'Insert'. It takes as its parameters the index you want to insert at, and an array of values to use for the new row values. Typical usage might include:

myDataGridView.Rows.Insert(4,new object[]{value1,value2,value3});

or something to that effect.

INSERT with SELECT

Yes, it is. You can write :

INSERT INTO courses (name, location, gid) 
SELECT name, location, 'whatever you want' 
FROM courses 
WHERE cid = $ci

or you can get values from another join of the select ...

Remove credentials from Git

If your credentials are stored in the credential helper (generally the case), the portable way to remove a password persisted for a specific host is to call git credential reject:

  • in one line:

    $ echo "url=https://appharbor.com" | git credential reject
    
  • or interactively:

    $ git credential reject
    protocol=https
    host=gitlab.com
    [email protected]
    ?
    
    • ? is the Enter symbol, just hit Enter key twice at the end of input, don't copy/paste it
    • The username doesn't seem recognized by wincred, so avoid to filter by username on Windows

After that, to enter your new password, type git fetch.

https://git-scm.com/docs/git-credential

Android: Vertical alignment for multi line EditText (Text area)

U can use this Edittext....This will help you.

<EditText
android:id="@+id/EditText02"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:lines="5"
android:gravity="top|left"
android:inputType="textMultiLine" />

Can constructors be async?

I was just wondering why we can't call await from within a constructor directly.

I believe the short answer is simply: Because the .Net team has not programmed this feature.

I believe with the right syntax this could be implemented and shouldn't be too confusing or error prone. I think Stephen Cleary's blog post and several other answers here have implicitly pointed out that there is no fundamental reason against it, and more than that - solved that lack with workarounds. The existence of these relatively simple workarounds is probably one of the reasons why this feature has not (yet) been implemented.

Attaching click event to a JQuery object not yet added to the DOM

You have to append it. Create the element with:

var $div = $("<div>my div</div>");
$div.click(function(){alert("clicked")})
return $div;

Then if you append it will work.

Take a look at your example here and a simple version here.

Is there a JSON equivalent of XQuery/XPath?

Just to add to the choices, there's also XPath. XPath 3.1 handles JSON as well as XML. In XPath 3.1 your required query is ?0?Objects?*[?id=3]

How to populate a dropdownlist with json data in jquery?

var listItems= "";
var jsonData = jsonObj.d;
    for (var i = 0; i < jsonData.Table.length; i++){
      listItems+= "<option value='" + jsonData.Table[i].stateid + "'>" + jsonData.Table[i].statename + "</option>";
    }
    $("#<%=DLState.ClientID%>").html(listItems);

Example

   <html>
    <head></head>
    <body>
      <select id="DLState">
      </select>
    </body>
    </html>

    /*javascript*/
    var jsonList = {"Table" : [{"stateid" : "2","statename" : "Tamilnadu"},
                {"stateid" : "3","statename" : "Karnataka"},
                {"stateid" : "4","statename" : "Andaman and Nicobar"},
                 {"stateid" : "5","statename" : "Andhra Pradesh"},
                 {"stateid" : "6","statename" : "Arunachal Pradesh"}]}

    $(document).ready(function(){
      var listItems= "";
      for (var i = 0; i < jsonList.Table.length; i++){
        listItems+= "<option value='" + jsonList.Table[i].stateid + "'>" + jsonList.Table[i].statename + "</option>";
      }
      $("#DLState").html(listItems);
    });    

how to show alternate image if source image is not found? (onerror working in IE but not in mozilla)

If you're open to a PHP solution:

<td><img src='<?PHP
  $path1 = "path/to/your/image.jpg";
  $path2 = "alternate/path/to/another/image.jpg";

  echo file_exists($path1) ? $path1 : $path2; 
  ?>' alt='' />
</td>

////EDIT OK, here's a JS version:

<table><tr>
<td><img src='' id='myImage' /></td>
</tr></table>

<script type='text/javascript'>
  document.getElementById('myImage').src = "newImage.png";

  document.getElementById('myImage').onload = function() { 
    alert("done"); 
  }

  document.getElementById('myImage').onerror = function() { 
    alert("Inserting alternate");
    document.getElementById('myImage').src = "alternate.png"; 
  }
</script>

Can't access 127.0.0.1

Just one command did the work

netsh http add iplisten 127.0.0.1

How to comment in Vim's config files: ".vimrc"?

"This is a comment in vimrc. It does not have a closing quote 

Source: http://vim.wikia.com/wiki/Backing_up_and_commenting_vimrc

Simple dictionary in C++

BASEPAIRS = { "T": "A", "A": "T", "G": "C", "C": "G" } What would you use?

Maybe:

static const char basepairs[] = "ATAGCG";
// lookup:
if (const char* p = strchr(basepairs, c))
    // use p[1]

;-)

Text in HTML Field to disappear when clicked?

This is as simple I think the solution that should solve all your problems:

<input name="myvalue" id="valueText" type="text" value="ENTER VALUE">

This is your submit button:

<input type="submit" id= "submitBtn" value="Submit">

then put this small jQuery in a js file:

//this will submit only if the value is not default
$("#submitBtn").click(function () {
    if ($("#valueText").val() === "ENTER VALUE")
    {
        alert("please insert a valid value");
        return false;
    }
});

//this will put default value if the field is empty
$("#valueText").blur(function () {
    if(this.value == ''){ 
        this.value = 'ENTER VALUE';
    }
}); 

 //this will empty the field is the value is the default one
 $("#valueText").focus(function () {
    if (this.value == 'ENTER VALUE') {
        this.value = ''; 
    }
});

And it works also in older browsers. Plus it can easily be converted to normal javascript if you need.

How to assign pointer address manually in C programming language?

Your code would be like this:

int *p = (int *)0x28ff44;

int needs to be the type of the object that you are referencing or it can be void.

But be careful so that you don't try to access something that doesn't belong to your program.

How can I view all historical changes to a file in SVN

As far as I know there is no built in svn command to accomplish this. You would need to write a script to run several commands to build all the diffs. A simpler approach would be to use a GUI svn client if that is an option. Many of them such as the subversive plugin for Eclipse will list the history of a file as well as allow you to view the diff of each revision.

Why use a READ UNCOMMITTED isolation level?

Regarding reporting, we use it on all of our reporting queries to prevent a query from bogging down databases. We can do that because we're pulling historical data, not up-to-the-microsecond data.

Correct way to create rounded corners in Twitter Bootstrap

With bootstrap4 you can easily do it like this :-

class="rounded" 

or

class="rounded-circle"

Shell script to get the process ID on Linux

As a start there is no need to do a ps -aux | grep... The command pidof is far better to use. And almost never ever do kill -9 see here

to get the output from a command in bash, use something like

pid=$(pidof ruby)

or use pkill directly.

How to align two elements on the same line without changing HTML

By using display: inline-block; And more generally when you have a parent (always there is a parent except for html) use display: inline-block; for the inner elements. and to force them to stay in the same line even when the window get shrunk (contracted). Add for the parent the two property:

    white-space: nowrap;
    overflow-x: auto;

here a more formatted example to make it clear:

.parent {
    white-space: nowrap;
    overflow-x: auto;
}

.children {
   display: inline-block;
   margin-left: 20px; 
}

For this example particularly, you can apply the above as fellow (i'm supposing the parent is body. if not you put the right parent), you can also like change the html and add a parent for them if it's possible.

body { /*body may pose problem depend on you context, there is no better then have a specific parent*/
        white-space: nowrap;
        overflow-x: auto;
 }

#element1, #element2{ /*you can like put each one separately, if the margin for the first element is not wanted*/
   display: inline-block;
   margin-left: 10px; 
}

keep in mind that white-space: nowrap; and overlow-x: auto; is what you need to force them to be in one line. white-space: nowrap; disable wrapping. And overlow-x:auto; to activate scrolling, when the element get over the frame limit.

Check if a specific value exists at a specific key in any subarray of a multidimensional array

If you have to make a lot of "id" lookups and it should be really fast you should use a second array containing all the "ids" as keys:

$lookup_array=array();

foreach($my_array as $arr){
    $lookup_array[$arr['id']]=1;
}

Now you can check for an existing id very fast, for example:

echo (isset($lookup_array[152]))?'yes':'no';

Difference between a class and a module

The first answer is good and gives some structural answers, but another approach is to think about what you're doing. Modules are about providing methods that you can use across multiple classes - think about them as "libraries" (as you would see in a Rails app). Classes are about objects; modules are about functions.

For example, authentication and authorization systems are good examples of modules. Authentication systems work across multiple app-level classes (users are authenticated, sessions manage authentication, lots of other classes will act differently based on the auth state), so authentication systems act as shared APIs.

You might also use a module when you have shared methods across multiple apps (again, the library model is good here).

How to download videos from youtube on java?

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

public class JavaYoutubeDownloader {

 public static String newline = System.getProperty("line.separator");
 private static final Logger log = Logger.getLogger(JavaYoutubeDownloader.class.getCanonicalName());
 private static final Level defaultLogLevelSelf = Level.FINER;
 private static final Level defaultLogLevel = Level.WARNING;
 private static final Logger rootlog = Logger.getLogger("");
 private static final String scheme = "http";
 private static final String host = "www.youtube.com";
 private static final Pattern commaPattern = Pattern.compile(",");
 private static final Pattern pipePattern = Pattern.compile("\\|");
 private static final char[] ILLEGAL_FILENAME_CHARACTERS = { '/', '\n', '\r', '\t', '\0', '\f', '`', '?', '*', '\\', '<', '>', '|', '\"', ':' };

 private static void usage(String error) {
  if (error != null) {
   System.err.println("Error: " + error);
  }
  System.err.println("usage: JavaYoutubeDownload VIDEO_ID DESTINATION_DIRECTORY");
  System.exit(-1);
 }

 public static void main(String[] args) {
  if (args == null || args.length == 0) {
   usage("Missing video id. Extract from http://www.youtube.com/watch?v=VIDEO_ID");
  }
  try {
   setupLogging();

   log.fine("Starting");
   String videoId = null;
   String outdir = ".";
   // TODO Ghetto command line parsing
   if (args.length == 1) {
    videoId = args[0];
   } else if (args.length == 2) {
    videoId = args[0];
    outdir = args[1];
   }

   int format = 18; // http://en.wikipedia.org/wiki/YouTube#Quality_and_codecs
   String encoding = "UTF-8";
   String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13";
   File outputDir = new File(outdir);
   String extension = getExtension(format);

   play(videoId, format, encoding, userAgent, outputDir, extension);

  } catch (Throwable t) {
   t.printStackTrace();
  }
  log.fine("Finished");
 }

 private static String getExtension(int format) {
  // TODO
  return "mp4";
 }

 private static void play(String videoId, int format, String encoding, String userAgent, File outputdir, String extension) throws Throwable {
  log.fine("Retrieving " + videoId);
  List<NameValuePair> qparams = new ArrayList<NameValuePair>();
  qparams.add(new BasicNameValuePair("video_id", videoId));
  qparams.add(new BasicNameValuePair("fmt", "" + format));
  URI uri = getUri("get_video_info", qparams);

  CookieStore cookieStore = new BasicCookieStore();
  HttpContext localContext = new BasicHttpContext();
  localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

  HttpClient httpclient = new DefaultHttpClient();
  HttpGet httpget = new HttpGet(uri);
  httpget.setHeader("User-Agent", userAgent);

  log.finer("Executing " + uri);
  HttpResponse response = httpclient.execute(httpget, localContext);
  HttpEntity entity = response.getEntity();
  if (entity != null && response.getStatusLine().getStatusCode() == 200) {
   InputStream instream = entity.getContent();
   String videoInfo = getStringFromInputStream(encoding, instream);
   if (videoInfo != null && videoInfo.length() > 0) {
    List<NameValuePair> infoMap = new ArrayList<NameValuePair>();
    URLEncodedUtils.parse(infoMap, new Scanner(videoInfo), encoding);
    String token = null;
    String downloadUrl = null;
    String filename = videoId;

    for (NameValuePair pair : infoMap) {
     String key = pair.getName();
     String val = pair.getValue();
     log.finest(key + "=" + val);
     if (key.equals("token")) {
      token = val;
     } else if (key.equals("title")) {
      filename = val;
     } else if (key.equals("fmt_url_map")) {
      String[] formats = commaPattern.split(val);
      for (String fmt : formats) {
       String[] fmtPieces = pipePattern.split(fmt);
       if (fmtPieces.length == 2) {
        // in the end, download somethin!
        downloadUrl = fmtPieces[1];
        int pieceFormat = Integer.parseInt(fmtPieces[0]);
        if (pieceFormat == format) {
         // found what we want
         downloadUrl = fmtPieces[1];
         break;
        }
       }
      }
     }
    }

    filename = cleanFilename(filename);
    if (filename.length() == 0) {
     filename = videoId;
    } else {
     filename += "_" + videoId;
    }
    filename += "." + extension;
    File outputfile = new File(outputdir, filename);

    if (downloadUrl != null) {
     downloadWithHttpClient(userAgent, downloadUrl, outputfile);
    }
   }
  }
 }

 private static void downloadWithHttpClient(String userAgent, String downloadUrl, File outputfile) throws Throwable {
  HttpGet httpget2 = new HttpGet(downloadUrl);
  httpget2.setHeader("User-Agent", userAgent);

  log.finer("Executing " + httpget2.getURI());
  HttpClient httpclient2 = new DefaultHttpClient();
  HttpResponse response2 = httpclient2.execute(httpget2);
  HttpEntity entity2 = response2.getEntity();
  if (entity2 != null && response2.getStatusLine().getStatusCode() == 200) {
   long length = entity2.getContentLength();
   InputStream instream2 = entity2.getContent();
   log.finer("Writing " + length + " bytes to " + outputfile);
   if (outputfile.exists()) {
    outputfile.delete();
   }
   FileOutputStream outstream = new FileOutputStream(outputfile);
   try {
    byte[] buffer = new byte[2048];
    int count = -1;
    while ((count = instream2.read(buffer)) != -1) {
     outstream.write(buffer, 0, count);
    }
    outstream.flush();
   } finally {
    outstream.close();
   }
  }
 }

 private static String cleanFilename(String filename) {
  for (char c : ILLEGAL_FILENAME_CHARACTERS) {
   filename = filename.replace(c, '_');
  }
  return filename;
 }

 private static URI getUri(String path, List<NameValuePair> qparams) throws URISyntaxException {
  URI uri = URIUtils.createURI(scheme, host, -1, "/" + path, URLEncodedUtils.format(qparams, "UTF-8"), null);
  return uri;
 }

 private static void setupLogging() {
  changeFormatter(new Formatter() {
   @Override
   public String format(LogRecord arg0) {
    return arg0.getMessage() + newline;
   }
  });
  explicitlySetAllLogging(Level.FINER);
 }

 private static void changeFormatter(Formatter formatter) {
  Handler[] handlers = rootlog.getHandlers();
  for (Handler handler : handlers) {
   handler.setFormatter(formatter);
  }
 }

 private static void explicitlySetAllLogging(Level level) {
  rootlog.setLevel(Level.ALL);
  for (Handler handler : rootlog.getHandlers()) {
   handler.setLevel(defaultLogLevelSelf);
  }
  log.setLevel(level);
  rootlog.setLevel(defaultLogLevel);
 }

 private static String getStringFromInputStream(String encoding, InputStream instream) throws UnsupportedEncodingException, IOException {
  Writer writer = new StringWriter();

  char[] buffer = new char[1024];
  try {
   Reader reader = new BufferedReader(new InputStreamReader(instream, encoding));
   int n;
   while ((n = reader.read(buffer)) != -1) {
    writer.write(buffer, 0, n);
   }
  } finally {
   instream.close();
  }
  String result = writer.toString();
  return result;
 }
}

/**
 * <pre>
 * Exploded results from get_video_info:
 * 
 * fexp=90...
 * allow_embed=1
 * fmt_stream_map=35|http://v9.lscache8...
 * fmt_url_map=35|http://v9.lscache8...
 * allow_ratings=1
 * keywords=Stefan Molyneux,Luke Bessey,anarchy,stateless society,giant stone cow,the story of our unenslavement,market anarchy,voluntaryism,anarcho capitalism
 * track_embed=0
 * fmt_list=35/854x480/9/0/115,34/640x360/9/0/115,18/640x360/9/0/115,5/320x240/7/0/0
 * author=lukebessey
 * muted=0
 * length_seconds=390
 * plid=AA...
 * ftoken=null
 * status=ok
 * watermark=http://s.ytimg.com/yt/swf/logo-vfl_bP6ud.swf,http://s.ytimg.com/yt/swf/hdlogo-vfloR6wva.swf
 * timestamp=12...
 * has_cc=False
 * fmt_map=35/854x480/9/0/115,34/640x360/9/0/115,18/640x360/9/0/115,5/320x240/7/0/0
 * leanback_module=http://s.ytimg.com/yt/swfbin/leanback_module-vflJYyeZN.swf
 * hl=en_US
 * endscreen_module=http://s.ytimg.com/yt/swfbin/endscreen-vflk19iTq.swf
 * vq=auto
 * avg_rating=5.0
 * video_id=S6IZP3yRJ9I
 * token=vPpcFNh...
 * thumbnail_url=http://i4.ytimg.com/vi/S6IZP3yRJ9I/default.jpg
 * title=The Story of Our Unenslavement - Animated
 * </pre>
 */

How to pass optional parameters while omitting some other optional parameters?

You can do this without an interface.

class myClass{
  public error(message: string, title?: string, autoHideAfter? : number){
    //....
  }
}

use the ? operator as an optional parameter.

How do you connect to a MySQL database using Oracle SQL Developer?

Under Tools > Preferences > Databases there is a third party JDBC driver path that must be setup. Once the driver path is setup a separate 'MySQL' tab should appear on the New Connections dialog.

Note: This is the same jdbc connector that is available as a JAR download from the MySQL website.

How to extend a class in python?

Use:

import color

class Color(color.Color):
    ...

If this were Python 2.x, you would also want to derive color.Color from object, to make it a new-style class:

class Color(object):
    ...

This is not necessary in Python 3.x.

VBScript How can I Format Date?

Suggest calling 'Now' only once in the function to guard against the minute, or even the day, changing during the execution of the function.

Thus:

Function timeStamp()
    Dim t 
    t = Now
    timeStamp = Year(t) & "-" & _
    Right("0" & Month(t),2)  & "-" & _
    Right("0" & Day(t),2)  & "_" & _  
    Right("0" & Hour(t),2) & _
    Right("0" & Minute(t),2) '    '& _    Right("0" & Second(t),2) 
End Function

Make an Android button change background on click through XML

To change image by using code

public void onClick(View v) {
   if(v == ButtonName) {
     ButtonName.setImageResource(R.drawable.ImageName);
   }
}

Or, using an XML file:

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_pressed="true"
   android:drawable="@drawable/login_selected" /> <!-- pressed -->
  <item android:state_focused="true"
   android:drawable="@drawable/login_mouse_over" /> <!-- focused -->
  <item android:drawable="@drawable/login" /> <!-- default -->
</selector>

In OnClick, just add this code:

ButtonName.setBackgroundDrawable(getResources().getDrawable(R.drawable.ImageName));

How do I clone a subdirectory only of a Git repository?

Here's a shell script I wrote for the use case of a single subdirectory sparse checkout

coSubDir.sh

localRepo=$1
remoteRepo=$2
subDir=$3


# Create local repository for subdirectory checkout, make it hidden to avoid having to drill down to the subfolder
mkdir ./.$localRepo
cd ./.$localRepo
git init
git remote add -f origin $remoteRepo
git config core.sparseCheckout true

# Add the subdirectory of interest to the sparse checkout.
echo $subDir >> .git/info/sparse-checkout

git pull origin master

# Create convenience symlink to the subdirectory of interest
cd ..
ln -s ./.$localRepo/$subDir $localRepo

Difference between `npm start` & `node app.js`, when starting app?

From the man page, npm start:

runs a package's "start" script, if one was provided. If no version is specified, then it starts the "active" version.

Admittedly, that description is completely unhelpful, and that's all it says. At least it's more documented than socket.io.

Anyhow, what really happens is that npm looks in your package.json file, and if you have something like

"scripts": { "start": "coffee server.coffee" }

then it will do that. If npm can't find your start script, it defaults to:

node server.js

 

How to ignore a particular directory or file for tslint?

Currently using Visual Studio Code and the command to disable tslint is

/* tslint:disable */

Something to note. The disable above disables ALL tslint rules on that page. If you want to disable a specific rule you can specify one/multiple rules.

/* tslint:disable comment-format */
/* tslint:disable:rule1 rule2 rule3 etc.. */

Or enable a rule

/* tslint:enable comment-format */

More in depth on TSLint rule flags

What is ROWS UNBOUNDED PRECEDING used for in Teradata?

ROWS UNBOUNDED PRECEDING is no Teradata-specific syntax, it's Standard SQL. Together with the ORDER BY it defines the window on which the result is calculated.

Logically a Windowed Aggregate Function is newly calculated for each row within the PARTITION based on all ROWS between a starting row and an ending row.

Starting and ending rows might be fixed or relative to the current row based on the following keywords:

  • CURRENT ROW, the current row
  • UNBOUNDED PRECEDING, all rows before the current row -> fixed
  • UNBOUNDED FOLLOWING, all rows after the current row -> fixed
  • x PRECEDING, x rows before the current row -> relative
  • y FOLLOWING, y rows after the current row -> relative

Possible kinds of calculation include:

  • Both starting and ending row are fixed, the window consists of all rows of a partition, e.g. a Group Sum, i.e. aggregate plus detail rows
  • One end is fixed, the other relative to current row, the number of rows increases or decreases, e.g. a Running Total, Remaining Sum
  • Starting and ending row are relative to current row, the number of rows within a window is fixed, e.g. a Moving Average over n rows

So SUM(x) OVER (ORDER BY col ROWS UNBOUNDED PRECEDING) results in a Cumulative Sum or Running Total

11 -> 11
 2 -> 11 +  2                = 13
 3 -> 13 +  3 (or 11+2+3)    = 16
44 -> 16 + 44 (or 11+2+3+44) = 60

How to print Unicode character in Python?

Replace '+' with '000'. For example, 'U+1F600' will become 'U0001F600' and prepend the Unicode code with "\" and print. Example:

>>> print("Learning : ", "\U0001F40D")
Learning :  
>>> 

Check this maybe it will help python unicode emoji

"While .. End While" doesn't work in VBA?

While constructs are terminated not with an End While but with a Wend.

While counter < 20
    counter = counter + 1
Wend

Note that this information is readily available in the documentation; just press F1. The page you link to deals with Visual Basic .NET, not VBA. While (no pun intended) there is some degree of overlap in syntax between VBA and VB.NET, one can't just assume that the documentation for the one can be applied directly to the other.

Also in the VBA help file:

Tip The Do...Loop statement provides a more structured and flexible way to perform looping.

Find the unique values in a column and then sort them

Came across the question myself today. I think the reason that your code returns 'None' (exactly what I got by using the same method) is that

a.sort()

is calling the sort function to mutate the list a. In my understanding, this is a modification command. To see the result you have to use print(a).

My solution, as I tried to keep everything in pandas:

pd.Series(df['A'].unique()).sort_values()

jQuery Date Picker - disable past dates

Just to add to this:

If you also need to prevent the user to manually type a date in the past, this is a possible solution. This is what we ended up doing (based on @Nicola Peluchetti's answer)

var dateToday = new Date();

$("#myDatePickerInput").change(function () {
    var updatedDate = $(this).val();
    var instance = $(this).data("datepicker");
    var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, updatedDate, instance.settings);

    if (date < dateToday) {
        $(this).datepicker("setDate", dateToday);
    }
});

What this does is to change the value to today's date if the user manually types a date in the past.

Finding modified date of a file/folder

PowerShell code to find all document library files modified from last 2 days.

$web = Get-SPWeb -Identity http://siteName:9090/ 
        $list = $web.GetList("http://siteName:9090/Style Library/")
        $folderquery =  New-Object Microsoft.SharePoint.SPQuery  
        $foldercamlQuery =  
        '<Where>   <Eq> 
                <FieldRef Name="ContentType" />  <Value Type="text">Folder</Value> 
            </Eq> </Where>' 
        $folderquery.Query = $foldercamlQuery 
        $folders = $list.GetItems($folderquery) 
        foreach($folderItem in $folders) 
        { 
            $folder = $folderItem.Folder
            if($folder.ItemCount -gt 0){ 
            Write-Host " find Item count " $folder.ItemCount
                $oldest = $null
                $files = $folder.Files

                $date = (Get-Date).AddDays(-2).ToString(“MM/dd/yyyy”)
                foreach ($file in $files){ 
                    if($file.Item["Modified"]-Ge $date)
                    {
                        Write-Host "Last 2 days modified folder name:"   $folder   " File Name: "  $file.Item["Name"]   " Date of midified: "  $file.Item["Modified"] 
                    } 
                } 
            } 
            else
             { 
                Write-Warning "$folder['Name'] is empty" 
            } 
        }

How do I convert a String to a BigInteger?

Instead of using valueOf(long) and parse(), you can directly use the BigInteger constructor that takes a string argument:

BigInteger numBig = new BigInteger("8599825996872482982482982252524684268426846846846846849848418418414141841841984219848941984218942894298421984286289228927948728929829");

That should give you the desired value.

How to change indentation mode in Atom?

Late to the party, but a clean way to do this on a per-project basis, is to add a .editorconfig file to the root of the project. Saves you from having to change Atom's settings when you're working on several projects simultaneously.

This is a sample of a very basic setup I'm currently using. Works for Atom, ST, etc...

http://editorconfig.org/

# Automatically add new line to end of all files on save.
[*]
insert_final_newline = true

# 2 space indentation for SASS/CSS
[*.{scss,sass,css}]
indent_style = space
indent_size = 2

# Set all JS to tab => space*2
[js/**.js]
indent_style = space
indent_size = 2

How can I check that JButton is pressed? If the isEnable() is not work?

Use this Command

if(JButton.getModel().isArmed()){
    //your code here.
    //your code will be only executed if JButton is clicked.
}

Answer is short. But it worked for me. Use the variable name of your button instead of "JButton".

Run javascript script (.js file) in mongodb including another file inside js

Use Load function

load(filename)

You can directly call any .js file from the mongo shell, and mongo will execute the JavaScript.

Example : mongo localhost:27017/mydb myfile.js

This executes the myfile.js script in mongo shell connecting to mydb database with port 27017 in localhost.

For loading external js you can write

load("/data/db/scripts/myloadjs.js")

Suppose we have two js file myFileOne.js and myFileTwo.js

myFileOne.js

print('From file 1');
load('myFileTwo.js');     // Load other js file .

myFileTwo.js

print('From file 2');

MongoShell

>mongo myFileOne.js

Output

From file 1
From file 2

How to prevent a dialog from closing when a button is clicked

This code will work for you, because i had a simmilar problem and this worked for me. :)

1- Override Onstart() method in your fragment-dialog class.

@Override
public void onStart() {
    super.onStart();
    final AlertDialog D = (AlertDialog) getDialog();
    if (D != null) {
        Button positive = (Button) D.getButton(Dialog.BUTTON_POSITIVE);
        positive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (edittext.equals("")) {
   Toast.makeText(getActivity(), "EditText empty",Toast.LENGTH_SHORT).show();
                } else {
                D.dismiss(); //dissmiss dialog
                }
            }
        });
    }
}

Why is this jQuery click function not working?

You have to wrap your Javascript-Code with $(document).ready(function(){});Look this JSfiddle.

JS Code:

$(document).ready(function() {

    $("#clicker").click(function () {
        alert("Hello!");
        $(".hide_div").hide();    
    });
});

ORA-01861: literal does not match format string

The error means that you tried to enter a literal with a format string, but the length of the format string was not the same length as the literal.

One of these formats is incorrect:

TO_CHAR(t.alarm_datetime, 'YYYY-MM-DD HH24:MI:SS')
TO_DATE(alarm_datetime, 'DD.MM.YYYY HH24:MI:SS')

"column not allowed here" error in INSERT statement

You're missing quotes around the first value, it should be

INSERT INTO LOCATION VALUES('PQ95VM', 'HAPPY_STREET', 'FRANCE');

Incidentally, you'd be well-advised to specify the column names explicitly in the INSERT, for reasons of readability, maintainability and robustness, i.e.

INSERT INTO LOCATION (POSTCODE, STREET_NAME, CITY) VALUES ('PQ95VM', 'HAPPY_STREET', 'FRANCE');

Writing String to Stream and reading it back does not work

You need to reset the stream to the beginning:

stringAsStream.Seek(0, SeekOrigin.Begin);
Console.WriteLine("Differs from:\t" + (char)stringAsStream.ReadByte());

This can also be done by setting the Position property to 0:

stringAsStream.Position = 0

Can vue-router open a link in a new tab?

I think the best way is to simply use:

window.open("yourURL", '_blank');

* flies away *

How to change line color in EditText

You can change the color with tinting the background <EditText android:backgroundTint="@color/red"/>

Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop

You need to add an event, before call your handleFunction like this:

function SingInContainer() {
..
..
handleClose = () => {
}

return (
    <SnackBar
        open={open}
        handleClose={() => handleClose}
        variant={variant}
        message={message}
        />
    <SignInForm/>
)

}

jQuery: How can I show an image popup onclick of the thumbnail?

This is the most popular (9500 stars) and light weight (20KB minify, 7.5KB minify+gzip) popup gallery I think: Magnific-Popup

removing html element styles via javascript

In JavaScript:

document.getElementById("id").style.display = null;

In jQuery:

$("#id").css('display',null);

Java: Calculating the angle between two points in degrees

Why is everyone complicating this?

The only problem is Math.atan2( x , y)

The corret answer is Math.atan2( y, x)

All they did was mix the variable order for Atan2 causing it to reverse the degree of rotation.

All you had to do was look up the syntax https://www.google.com/amp/s/www.geeksforgeeks.org/java-lang-math-atan2-java/amp/

How does one remove a Docker image?

Image:

  1. List images

    docker images

  2. Remove one image

    docker rmi image_name

  3. Force remove one image

    docker rmi -f image_name

Container:

  1. List all containers

    docker ps -a

  2. Remove one container

    docker rm container_id

  3. Force remove one container

    docker rm -f container_id

Get selected text from a drop-down list (select box) using jQuery

This works for me:

$('#yourdropdownid').find('option:selected').text();

jQuery version: 1.9.1

How Connect to remote host from Aptana Studio 3

There's also an option to Auto Sync built-in in Aptana.

step 1

step 2

C/C++ NaN constant (literal)?

In C, NAN is declared in <math.h>.

In C++, std::numeric_limits<double>::quiet_NaN() is declared in <limits>.

But for checking whether a value is NaN, you can't compare it with another NaN value. Instead use isnan() from <math.h> in C, or std::isnan() from <cmath> in C++.

How can I enable the MySQLi extension in PHP 7?

Let's use

mysqli_connect

instead of

mysql_connect

because mysql_connect isn't supported in PHP 7.

Set default format of datetimepicker as dd-MM-yyyy

Try this,

string Date = datePicker1.SelectedDate.Value.ToString("dd-MMM-yyyy");

It worked for me the output format will be '02-May-2016'

I'm getting an error "invalid use of incomplete type 'class map'

I am just providing another case where you can get this error message. The solution will be the same as Adam has mentioned above. This is from a real code and I renamed the class name.

class FooReader {
  public:
     /** Constructor */
     FooReader() : d(new FooReaderPrivate(this)) { }  // will not compile here
     .......
  private:
     FooReaderPrivate* d;
};

====== In a separate file =====
class FooReaderPrivate {
  public:
     FooReaderPrivate(FooReader*) : parent(p) { }
  private:
     FooReader* parent;
};

The above will no pass the compiler and get error: invalid use of incomplete type FooReaderPrivate. You basically have to put the inline portion into the *.cpp implementation file. This is OK. What I am trying to say here is that you may have a design issue. Cross reference of two classes may be necessary some cases, but I would say it is better to avoid them at the start of the design. I would be wrong, but please comment then I will update my posting.

How to remove rows with any zero value

Well, you could swap your 0's for NA and then use one of those solutions, but for sake of a difference, you could notice that a number will only have a finite logarithm if it is greater than 0, so that rowSums of the log will only be finite if there are no zeros in a row.

dfr[is.finite(rowSums(log(dfr[-1]))),]

function is not defined error in Python

In python functions aren't accessible magically from everywhere (like they are in say, php). They have to be declared first. So this will work:

def pyth_test (x1, x2):
    print x1 + x2

pyth_test(1, 2)

But this won't:

pyth_test(1, 2)

def pyth_test (x1, x2):
    print x1 + x2

Does an HTTP Status code of 0 have any meaning?

Yes, some how the ajax call aborted. The cause may be following.

  1. Before completion of ajax request, user navigated to other page.
  2. Ajax request have timeout.
  3. Server is not able to return any response.

Babel command not found

There are two problems here. First, you need a package.json file. Telling npm to install without one will throw the npm WARN enoent ENOENT: no such file or directory error. In your project directory, run npm init to generate a package.json file for the project.

Second, local binaries probably aren't found because the local ./node_modules/.bin is not in $PATH. There are some solutions in How to use package installed locally in node_modules?, but it might be easier to just wrap your babel-cli commands in npm scripts. This works because npm run adds the output of npm bin (node_modules/.bin) to the PATH provided to scripts.

Here's a stripped-down example package.json which returns the locally installed babel-cli version:

{
  "scripts": {
    "babel-version": "babel --version"
  },
  "devDependencies": {
    "babel-cli": "^6.6.5"
  }
}

Call the script with this command: npm run babel-version.

Putting scripts in package.json is quite useful but often overlooked. Much more in the docs: How npm handles the "scripts" field

Ruby objects and JSON serialization (without Rails)

For the JSON library to be available, you may have to install libjson-ruby from your package manager.

To use the 'json' library:

require 'json'

To convert an object to JSON (these 3 ways are equivalent):

JSON.dump object #returns a JSON string
JSON.generate object #returns a JSON string
object.to_json #returns a JSON string

To convert JSON text to an object (these 2 ways are equivalent):

JSON.load string #returns an object
JSON.parse string #returns an object

It will be a bit more difficult for objects from your own classes. For the following class, to_json will produce something like "\"#<A:0xb76e5728>\"".

class A
    def initialize a=[1,2,3], b='hello'
        @a = a
        @b = b
    end
end

This probably isn't desirable. To effectively serialise your object as JSON, you should create your own to_json method. To go with this, a from_json class method would be useful. You could extend your class like so:

class A
    def to_json
        {'a' => @a, 'b' => @b}.to_json
    end
    def self.from_json string
        data = JSON.load string
        self.new data['a'], data['b']
    end
end

You could automate this by inheriting from a 'JSONable' class:

class JSONable
    def to_json
        hash = {}
        self.instance_variables.each do |var|
            hash[var] = self.instance_variable_get var
        end
        hash.to_json
    end
    def from_json! string
        JSON.load(string).each do |var, val|
            self.instance_variable_set var, val
        end
    end
end

Then you can use object.to_json to serialise to JSON and object.from_json! string to copy the saved state that was saved as the JSON string to the object.

JQuery post JSON object to a server

It is also possible to use FormData(). But you need to set contentType as false:

var data = new FormData();
data.append('name', 'Bob'); 

function sendData() {
    $.ajax({
        url: '/helloworld',
        type: 'POST',
        contentType: false,
        data: data,
        dataType: 'json'
    });
}

How to remove non UTF-8 characters from text file

cat foo.txt | strings -n 8 > bar.txt

will do the job.

Fire event on enter key press for a textbox

<input type="text" id="txtCode" name="name" class="text_cs">

and js:

<script type="text/javascript">
$('.text_cs').on('change', function () {
var pid = $(this).val();
console.log("Value text: " + pid);
});
</script>

How do you strip a character out of a column in SQL Server?

Take a look at the following function - REPLACE():

select replace(DataColumn, StringToReplace, NewStringValue)

//example to replace the s in test with the number 1
select replace('test', 's', '1')
//yields te1t

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

EDIT
If you want to remove a string, simple use the replace function with an empty string as the third parameter like:

select replace(DataColumn, 'StringToRemove', '')

std::string length() and size() member functions

Ruby's just the same, btw, offering both #length and #size as synonyms for the number of items in arrays and hashes (C++ only does it for strings).

Minimalists and people who believe "there ought to be one, and ideally only one, obvious way to do it" (as the Zen of Python recites) will, I guess, mostly agree with your doubts, @Naveen, while fans of Perl's "There's more than one way to do it" (or SQL's syntax with a bazillion optional "noise words" giving umpteen identically equivalent syntactic forms to express one concept) will no doubt be complaining that Ruby, and especially C++, just don't go far enough in offering such synonymical redundancy;-).

How do I read a specified line in a text file?

No unfortunately there is not. At the raw level files do not work on a line number basis. Instead they work at a position / offset basis. The root filesystem has no concept of lines. It's a concept added by higher level components.

So there is no way to tell the operating system, please open file at line blah. Instead you have to open the file and skip around counting new lines until you've passed the specified number. Then store the next set of bytes into an array until you hit the next new line.

python: after installing anaconda, how to import pandas

  1. Another alternative is to use Pycharm IDE. For each project, you can set the Project Interpreter in Settings.

  2. For example, if anaconda is installed in /home/user/anaconda2/bin/python, you can select the Project Interpreter and set to this folder.

  3. Since the whole project is set to Anaconda's path, you can import any module which is packaged within Anaconda.

Floating point comparison functions for C#

Here is a much-expanded version of Simon Hewitt's class:

/// <summary>
/// Safely converts a <see cref="float"/> to an <see cref="int"/> for floating-point comparisons.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
public struct FloatToInt : IEquatable<FloatToInt>, IEquatable<float>, IEquatable<int>, IComparable<FloatToInt>, IComparable<float>, IComparable<int>
{
    /// <summary>
    /// Initializes a new instance of the <see cref="FloatToInt"/> class.
    /// </summary>
    /// <param name="floatValue">The <see cref="float"/> value to be converted to an <see cref="int"/>.</param>
    public FloatToInt(float floatValue)
        : this()
    {
        FloatValue = floatValue;
    }

    /// <summary>
    /// Gets the floating-point value as an integer.
    /// </summary>
    [FieldOffset(0)]
    public readonly int IntValue;

    /// <summary>
    /// Gets the floating-point value.
    /// </summary>
    [FieldOffset(0)]
    public readonly float FloatValue;

    /// <summary>
    /// Indicates whether the current object is equal to another object of the same type.
    /// </summary>
    /// <returns>
    /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
    /// </returns>
    /// <param name="other">An object to compare with this object.</param>
    public bool Equals(FloatToInt other)
    {
        return other.IntValue == IntValue;
    }

    /// <summary>
    /// Indicates whether the current object is equal to another object of the same type.
    /// </summary>
    /// <returns>
    /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
    /// </returns>
    /// <param name="other">An object to compare with this object.</param>
    public bool Equals(float other)
    {
        return IntValue == new FloatToInt(other).IntValue;
    }

    /// <summary>
    /// Indicates whether the current object is equal to another object of the same type.
    /// </summary>
    /// <returns>
    /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
    /// </returns>
    /// <param name="other">An object to compare with this object.</param>
    public bool Equals(int other)
    {
        return IntValue == other;
    }

    /// <summary>
    /// Compares the current object with another object of the same type.
    /// </summary>
    /// <returns>
    /// A value that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the <paramref name="other"/> parameter.Zero This object is equal to <paramref name="other"/>. Greater than zero This object is greater than <paramref name="other"/>. 
    /// </returns>
    /// <param name="other">An object to compare with this object.</param>
    public int CompareTo(FloatToInt other)
    {
        return IntValue.CompareTo(other.IntValue);
    }

    /// <summary>
    /// Compares the current object with another object of the same type.
    /// </summary>
    /// <returns>
    /// A value that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the <paramref name="other"/> parameter.Zero This object is equal to <paramref name="other"/>. Greater than zero This object is greater than <paramref name="other"/>. 
    /// </returns>
    /// <param name="other">An object to compare with this object.</param>
    public int CompareTo(float other)
    {
        return IntValue.CompareTo(new FloatToInt(other).IntValue);
    }

    /// <summary>
    /// Compares the current object with another object of the same type.
    /// </summary>
    /// <returns>
    /// A value that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the <paramref name="other"/> parameter.Zero This object is equal to <paramref name="other"/>. Greater than zero This object is greater than <paramref name="other"/>. 
    /// </returns>
    /// <param name="other">An object to compare with this object.</param>
    public int CompareTo(int other)
    {
        return IntValue.CompareTo(other);
    }

    /// <summary>
    /// Indicates whether this instance and a specified object are equal.
    /// </summary>
    /// <returns>
    /// true if <paramref name="obj"/> and this instance are the same type and represent the same value; otherwise, false.
    /// </returns>
    /// <param name="obj">Another object to compare to. </param><filterpriority>2</filterpriority>
    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj))
        {
            return false;
        }
        if (obj.GetType() != typeof(FloatToInt))
        {
            return false;
        }
        return Equals((FloatToInt)obj);
    }

    /// <summary>
    /// Returns the hash code for this instance.
    /// </summary>
    /// <returns>
    /// A 32-bit signed integer that is the hash code for this instance.
    /// </returns>
    /// <filterpriority>2</filterpriority>
    public override int GetHashCode()
    {
        return IntValue;
    }

    /// <summary>
    /// Implicitly converts from a <see cref="FloatToInt"/> to an <see cref="int"/>.
    /// </summary>
    /// <param name="value">A <see cref="FloatToInt"/>.</param>
    /// <returns>An integer representation of the floating-point value.</returns>
    public static implicit operator int(FloatToInt value)
    {
        return value.IntValue;
    }

    /// <summary>
    /// Implicitly converts from a <see cref="FloatToInt"/> to a <see cref="float"/>.
    /// </summary>
    /// <param name="value">A <see cref="FloatToInt"/>.</param>
    /// <returns>The floating-point value.</returns>
    public static implicit operator float(FloatToInt value)
    {
        return value.FloatValue;
    }

    /// <summary>
    /// Determines if two <see cref="FloatToInt"/> instances have the same integer representation.
    /// </summary>
    /// <param name="left">A <see cref="FloatToInt"/>.</param>
    /// <param name="right">A <see cref="FloatToInt"/>.</param>
    /// <returns>true if the two <see cref="FloatToInt"/> have the same integer representation; otherwise, false.</returns>
    public static bool operator ==(FloatToInt left, FloatToInt right)
    {
        return left.IntValue == right.IntValue;
    }

    /// <summary>
    /// Determines if two <see cref="FloatToInt"/> instances have different integer representations.
    /// </summary>
    /// <param name="left">A <see cref="FloatToInt"/>.</param>
    /// <param name="right">A <see cref="FloatToInt"/>.</param>
    /// <returns>true if the two <see cref="FloatToInt"/> have different integer representations; otherwise, false.</returns>
    public static bool operator !=(FloatToInt left, FloatToInt right)
    {
        return !(left == right);
    }
}

How to easily get network path to the file you are working on?

Answer to my own question. The only way I have found that works consistently and instantaneously is to:

1) Create a link in my "Favorites" to the directory I use

2) Update the properties on that favorite to be an absolute path (\\ads\IT-DEPT-DFS\Data\MAILROOM)

3) When saving a new file, I navigate to that directory only via the Favorites directory created above (or you can use any Shortcut with an absolute path)

4) After saving, go to the File tab and the full path can be copied from the top of the Info (default) section

Passing parameters to JavaScript files

I think it is far more better and modern solution to just use localStorage on the page where the javascript is included and then just re-use it inside the javascript itself. Set it in localStorage with:

localStorage.setItem("nameOfVariable", "some text value");

and refer to it inside javascript file like:

localStorage.getItem("nameOfVariable");

How do I mock a class without an interface?

If you cannot change the class under test, then the only option I can suggest is using MS Fakes https://msdn.microsoft.com/en-us/library/hh549175.aspx. However, MS Fakes works only in a few editions of Visual Studio.

Difference between dates in JavaScript

    // This is for first date
    first = new Date(2010, 03, 08, 15, 30, 10); // Get the first date epoch object
    document.write((first.getTime())/1000); // get the actual epoch values
    second = new Date(2012, 03, 08, 15, 30, 10); // Get the first date epoch object
    document.write((second.getTime())/1000); // get the actual epoch values
    diff= second - first ;
    one_day_epoch = 24*60*60 ;  // calculating one epoch
    if ( diff/ one_day_epoch > 365 ) // check , is it exceei
    {
    alert( 'date is exceeding one year');
    }

How to apply two CSS classes to a single element

Separate 'em with a space.

<div class="c1 c2"></div>

Docker can't connect to docker daemon

If you are running on OS X using Docker tool, follow this.

Restart the daemon and configure your environment:

docker-machine restart

And then

docker-machine env

Finally,

eval $(docker-machine env)

To test the daemon is running:

docker ps -a or docker-machine ls. This will list all containers.

Uncaught TypeError: Cannot read property 'value' of undefined

Either document.getElementById('i1'), document.getElementById('i2'), or document.getElementsByName("username")[0] is returning no element. Check, that all elements exist.

JavaScript Array splice vs slice

The slice() method returns a copy of a portion of an array into a new array object.

$scope.participantForms.slice(index, 1);

This does NOT change the participantForms array but returns a new array containing the single element found at the index position in the original array.

The splice() method changes the content of an array by removing existing elements and/or adding new elements.

$scope.participantForms.splice(index, 1);

This will remove one element from the participantForms array at the index position.

These are the Javascript native functions, AngularJS has nothing to do with them.

Why do I keep getting Delete 'cr' [prettier/prettier]?

I am using git+vscode+windows+vue, and after read the eslint document: https://eslint.org/docs/rules/linebreak-style

Finally fix it by:

add *.js text eol=lf to .gitattributes

then run vue-cli-service lint --fix

Check if an array is empty or exists

if (typeof image_array !== 'undefined' && image_array.length > 0) {
    // the array is defined and has at least one element
}

Your problem may be happening due to a mix of implicit global variables and variable hoisting. Make sure you use var whenever declaring a variable:

<?php echo "var image_array = ".json_encode($images);?>
// add var  ^^^ here

And then make sure you never accidently redeclare that variable later:

else {
    ...
    image_array = []; // no var here
}

execute function after complete page load

you can try like this without using jquery

_x000D_
_x000D_
window.addEventListener("load", afterLoaded,false);
function afterLoaded(){
alert("after load")
}
_x000D_
_x000D_
_x000D_

How to insert a new key value pair in array in php?

To add:

$arr["key"] = "value";

Then simply return $arr

Can't return directly like this way return $arr["key"] = "value";

How do I use $rootScope in Angular to store variables?

http://astutejs.blogspot.in/2015/07/angularjs-what-is-rootscope.html

 app.controller('AppCtrl2', function ($scope, $rootScope) {
     $scope.msg = 'SCOPE';
     $rootScope.name = 'ROOT SCOPE';
 });

How to find out what type of a Mat object is with Mat::type() in OpenCV

I've added some usability to the function from the answer by @Octopus, for debugging purposes.

void MatType( Mat inputMat )
{
    int inttype = inputMat.type();

    string r, a;
    uchar depth = inttype & CV_MAT_DEPTH_MASK;
    uchar chans = 1 + (inttype >> CV_CN_SHIFT);
    switch ( depth ) {
        case CV_8U:  r = "8U";   a = "Mat.at<uchar>(y,x)"; break;  
        case CV_8S:  r = "8S";   a = "Mat.at<schar>(y,x)"; break;  
        case CV_16U: r = "16U";  a = "Mat.at<ushort>(y,x)"; break; 
        case CV_16S: r = "16S";  a = "Mat.at<short>(y,x)"; break; 
        case CV_32S: r = "32S";  a = "Mat.at<int>(y,x)"; break; 
        case CV_32F: r = "32F";  a = "Mat.at<float>(y,x)"; break; 
        case CV_64F: r = "64F";  a = "Mat.at<double>(y,x)"; break; 
        default:     r = "User"; a = "Mat.at<UKNOWN>(y,x)"; break; 
    }   
    r += "C";
    r += (chans+'0');
    cout << "Mat is of type " << r << " and should be accessed with " << a << endl;

}

LINQ's Distinct() on a particular property

If you don't want to add the MoreLinq library to your project just to get the DistinctBy functionality then you can get the same end result using the overload of Linq's Distinct method that takes in an IEqualityComparer argument.

You begin by creating a generic custom equality comparer class that uses lambda syntax to perform custom comparison of two instances of a generic class:

public class CustomEqualityComparer<T> : IEqualityComparer<T>
{
    Func<T, T, bool> _comparison;
    Func<T, int> _hashCodeFactory;

    public CustomEqualityComparer(Func<T, T, bool> comparison, Func<T, int> hashCodeFactory)
    {
        _comparison = comparison;
        _hashCodeFactory = hashCodeFactory;
    }

    public bool Equals(T x, T y)
    {
        return _comparison(x, y);
    }

    public int GetHashCode(T obj)
    {
        return _hashCodeFactory(obj);
    }
}

Then in your main code you use it like so:

Func<Person, Person, bool> areEqual = (p1, p2) => int.Equals(p1.Id, p2.Id);

Func<Person, int> getHashCode = (p) => p.Id.GetHashCode();

var query = people.Distinct(new CustomEqualityComparer<Person>(areEqual, getHashCode));

Voila! :)

The above assumes the following:

  • Property Person.Id is of type int
  • The people collection does not contain any null elements

If the collection could contain nulls then simply rewrite the lambdas to check for null, e.g.:

Func<Person, Person, bool> areEqual = (p1, p2) => 
{
    return (p1 != null && p2 != null) ? int.Equals(p1.Id, p2.Id) : false;
};

EDIT

This approach is similar to the one in Vladimir Nesterovsky's answer but simpler.

It is also similar to the one in Joel's answer but allows for complex comparison logic involving multiple properties.

However, if your objects can only ever differ by Id then another user gave the correct answer that all you need to do is override the default implementations of GetHashCode() and Equals() in your Person class and then just use the out-of-the-box Distinct() method of Linq to filter out any duplicates.

What is causing this error - "Fatal error: Unable to find local grunt"

Being new to grunt and setting it up, I am running (perhaps foolishly) my grunt project/folder from a Google Drive so I can access the same code/builds from either my laptop or workstation.

There is a fair bit of synchronisation of the nodes_modules folders back to Google Drive and there seemed to be a conflict at some point, and the /nodes_modules/grunt folder was renamed to /nodes_modules/grunt (1)

Renaming it back by removing the (1) seemed to fix it for me.

Dropdownlist width in IE

Based on the solution posted by Sai, this is how to do it with jQuery.

$(document).ready(function() {
    if ($.browser.msie) $('select.wide')
        .bind('onmousedown', function() { $(this).css({position:'absolute',width:'auto'}); })
        .bind('blur', function() { $(this).css({position:'static',width:''}); });
});

Spring Boot - How to log all requests and responses with exceptions in single place?

the code pasted below works with my tests and can be downloaded from my [github project][1], sharing after applying a solution based on that on a production project.

@Configuration
public class LoggingFilter extends GenericFilterBean {

    /**
     * It's important that you actually register your filter this way rather then just annotating it
     * as @Component as you need to be able to set for which "DispatcherType"s to enable the filter
     * (see point *1*)
     * 
     * @return
     */
    @Bean
    public FilterRegistrationBean<LoggingFilter> initFilter() {
        FilterRegistrationBean<LoggingFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new LoggingFilter());

        // *1* make sure you sett all dispatcher types if you want the filter to log upon
        registrationBean.setDispatcherTypes(EnumSet.allOf(DispatcherType.class));

        // *2* this should put your filter above any other filter
        registrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);

        return registrationBean;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        ContentCachingRequestWrapper wreq = 
            new ContentCachingRequestWrapper(
                (HttpServletRequest) request);

        ContentCachingResponseWrapper wres = 
            new ContentCachingResponseWrapper(
                (HttpServletResponse) response);

        try {

            // let it be ...
            chain.doFilter(wreq, wres);

            // makes sure that the input is read (e.g. in 404 it may not be)
            while (wreq.getInputStream().read() >= 0);

            System.out.printf("=== REQUEST%n%s%n=== end request%n",
                    new String(wreq.getContentAsByteArray()));

            // Do whatever logging you wish here, in this case I'm writing request 
            // and response to system out which is probably not what you wish to do
            System.out.printf("=== RESPONSE%n%s%n=== end response%n",
                    new String(wres.getContentAsByteArray()));

            // this is specific of the "ContentCachingResponseWrapper" we are relying on, 
            // make sure you call it after you read the content from the response
            wres.copyBodyToResponse();

            // One more point, in case of redirect this will be called twice! beware to handle that
            // somewhat

        } catch (Throwable t) {
            // Do whatever logging you whish here, too
            // here you should also be logging the error!!!
            throw t;
        }

    }
}

File Upload In Angular?

I've upload file using reference. No package is required to upload file this way.

// code to be written in .ts file

@ViewChild("fileInput") fileInput;

addFile(): void {
let fi = this.fileInput.nativeElement;
if (fi.files && fi.files[0]) {
  let fileToUpload = fi.files[0];
    this.admin.addQuestionApi(fileToUpload)
      .subscribe(
        success => {
          this.loading = false;
          this.flashMessagesService.show('Uploaded successfully', {
            classes: ['alert', 'alert-success'],
            timeout: 1000,
          });
        },
        error => {
          this.loading = false;
          if(error.statusCode==401) this.router.navigate(['']);
          else
            this.flashMessagesService.show(error.message, {
              classes: ['alert', 'alert-danger'],
              timeout: 1000,
            });
        });
  }

}

// code to be written in service.ts file

addQuestionApi(fileToUpload: any){
var headers = this.getHeadersForMultipart();
let input = new FormData();
input.append("file", fileToUpload);

return this.http.post(this.baseUrl+'addQuestions', input, {headers:headers})
      .map(response => response.json())
      .catch(this.errorHandler);

}

// code to be written in html

<input type="file" #fileInput>

How to check the input is an integer or not in Java?

        String input = "";
        int inputInteger = 0;
        BufferedReader br    = new BufferedReader(new InputStreamReader (System.in));

        System.out.println("Enter the radious: ");
        try {
            input = br.readLine();
            inputInteger = Integer.parseInt(input);
        } catch (NumberFormatException e) {
            System.out.println("Please Enter An Integer");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        float area = (float) (3.14*inputInteger*inputInteger);
        System.out.println("Area = "+area);

Unsupported operand type(s) for +: 'int' and 'str'

You're trying to concatenate a string and an integer, which is incorrect.

Change print(numlist.pop(2)+" has been removed") to any of these:

Explicit int to str conversion:

print(str(numlist.pop(2)) + " has been removed")

Use , instead of +:

print(numlist.pop(2), "has been removed")

String formatting:

print("{} has been removed".format(numlist.pop(2)))

Change File Extension Using C#

The method GetFileNameWithoutExtension, as the name implies, does not return the extension on the file. In your case, it would only return "a". You want to append your ".Jpeg" to that result. However, at a different level, this seems strange, as image files have different metadata and cannot be converted so easily.

How do I add 24 hours to a unix timestamp in php?

You could use the DateTime class as well:

$timestamp = mktime(15, 30, 00, 3, 28, 2015);

$d = new DateTime();
$d->setTimestamp($timestamp);

Add a Period of 1 Day:

$d->add(new DateInterval('P1D'));
echo $d->format('c');

See DateInterval for more details.

Return in Scala

I don't program Scala, but I use another language with implicit returns (Ruby). You have code after your if (elem.isEmpty) block -- the last line of code is what's returned, which is why you're not getting what you're expecting.

EDIT: Here's a simpler way to write your function too. Just use the boolean value of isEmpty and count to return true or false automatically:

def balanceMain(elem: List[Char]): Boolean =
{
    elem.isEmpty && count == 0
}

How do I exit the Vim editor?

Vim has three modes of operation: Input mode, Command mode & Ex mode.

Input mode - everything that you type, all keystrokes are echoed on the screen.

Command mode or Escape mode - everything that you type in this mode is interpreted as a command.

Ex mode - this is another editor, ex. It is a line editor. It works per line or based on a range of lines. In this mode, a : appears at the bottom of the screen. This is the ex editor.

In order to exit Vim, you can exit while you are in either the ex mode or in the command mode. You cannot exit Vim when you are in input mode.

Exiting from ex mode

  1. You need to be sure that you are in the Command mode. To do that, simply press the Esc key.

  2. Go to the ex mode by pressing the : key

  3. Use any of the following combinations in ex mode to exit:

    :q - quit :q! - quit without saving :wq - save & quit or write & quit :wq! - same as wq, but force write in case file permissions are readonly :x - write & quit :qa - quit all. useful when multiple files are opened like: vim abc.txt xyz.txt

Exiting from command mode

  1. Press the escape key. You probably have done this already if you are in command mode.

  2. Press capital ZZ (shift zz) - save & exit

  3. Press capital ZQ (shift zq) - exit without saving.

How to decode JWT Token?

I found the solution, I just forgot to Cast the result:

var stream ="[encoded jwt]";  
var handler = new JwtSecurityTokenHandler();
var jsonToken = handler.ReadToken(stream);
var tokenS = handler.ReadToken(stream) as JwtSecurityToken;

I can get Claims using:

var jti = tokenS.Claims.First(claim => claim.Type == "jti").Value;

UIView Hide/Show with animation

Swift 4 Transition

    UIView.transition(with: view, duration: 3, options: .transitionCurlDown,
                      animations: {
                        // Animations
                        view.isHidden = hidden
    },
                      completion: { finished in
                        // Compeleted
    })

If you use the approach for older swift versions you'll get an error :

Cannot convert value of type '(_) -> ()' to expected argument type '(() -> Void)?'

Useful reference.

window.history.pushState refreshing the browser

The short answer is that history.pushState (not History.pushState, which would throw an exception, the window part is optional) will never do what you suggest.

If pages are refreshing, then it is caused by other things that you are doing (for example, you might have code running that goes to a new location in the case of the address bar changing).

history.pushState({urlPath:'/page2.php'},"",'/page2.php') works exactly like it is supposed to in the latest versions of Chrome, IE and Firefox for me and my colleagues.

In fact you can put whatever you like into the function: history.pushState({}, '', 'So long and thanks for all the fish.not a real file').

If you post some more code (with special attention for code nearby the history.pushState and anywhere document.location is used), then we'll be more than happy to help you figure out where exactly this issue is coming from.

If you post more code, I'll update this answer (I have your question favourited) :).

PHP mail function doesn't complete sending of e-mail

Although there are portions of this answer that apply to only to the usage of themail() function itself, many of these troubleshooting steps can be applied to any PHP mailing system.

There are a variety of reasons your script appears to not be sending emails. It's difficult to diagnose these things unless there is an obvious syntax error. Without one you need to run through the checklist below to find any potential pitfalls you may be encountering.

Make sure error reporting is enabled and set to report all errors

Error reporting is essential to rooting out bugs in your code and general errors that PHP encounters. Error reporting needs to be enabled to receive these errors. Placing the following code at the top of your PHP files (or in a master configuration file) will enable error reporting.

error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");

See How can I get useful error messages in PHP?this answer for more details on this.

Make sure the mail() function is called

It may seem silly but a common error is to forget to actually place the mail() function in your code. Make sure it is there and not commented out.

Make sure the mail() function is called correctly

bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )

The mail function takes three required parameters and optionally a fourth and fifth one. If your call to mail() does not have at least three parameters it will fail.

If your call to mail() does not have the correct parameters in the correct order it will also fail.

Check the server's mail logs

Your web server should be logging all attempts to send emails through it. The location of these logs will vary (you may need to ask your server administrator where they are located) but they can commonly be found in a user's root directory under logs. Inside will be error messages the server reported, if any, related to your attempts to send emails.

Check for Port connection failure

Port block is a very common problem which most developers face while integrating their code to deliver emails using SMTP. And, this can be easily traced at the server maillogs (the location of server of mail log can vary from server to server, as explained above). In case you are on a shared hosting server, the ports 25 and 587 remain blocked by default. This block is been purposely done by your hosting provider. This is true even for some of the dedicated servers. When these ports are blocked, try to connect using port 2525. If you find that port is also blocked, then the only solution is to contact your hosting provider to unblock these ports.

Most of the hosting providers block these email ports to protect their network from sending any spam emails.

Use ports 25 or 587 for plain/TLS connections and port 465 for SSL connections. For most users, it is suggested to use port 587 to avoid rate limits set by some hosting providers.

Don't use the error suppression operator

When the error suppression operator @ is prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored. There are circumstances where using this operator is necessary but sending mail is not one of them.

If your code contains @mail(...) then you may be hiding important error messages that will help you debug this. Remove the @ and see if any errors are reported.

It's only advisable when you check with error_get_last() right afterwards for concrete failures.

Check the mail() return value

The mail() function:

Returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise. It is important to note that just because the mail was accepted for delivery, it does NOT mean the mail will actually reach the intended destination.

This is important to note because:

  • If you receive a FALSE return value you know the error lies with your server accepting your mail. This probably isn't a coding issue but a server configuration issue. You need to speak to your system administrator to find out why this is happening.
  • If you receive a TRUE return value it does not mean your email will definitely be sent. It just means the email was sent to its respective handler on the server successfully by PHP. There are still more points of failure outside of PHP's control that can cause the email to not be sent.

So FALSE will help point you in the right direction whereas TRUE does not necessarily mean your email was sent successfully. This is important to note!

Make sure your hosting provider allows you to send emails and does not limit mail sending

Many shared webhosts, especially free webhosting providers, either do not allow emails to be sent from their servers or limit the amount that can be sent during any given time period. This is due to their efforts to limit spammers from taking advantage of their cheaper services.

If you think your host has emailing limits or blocks the sending of emails, check their FAQs to see if they list any such limitations. Otherwise, you may need to reach out to their support to verify if there are any restrictions in place around the sending of emails.

Check spam folders; prevent emails from being flagged as spam

Oftentimes, for various reasons, emails sent through PHP (and other server-side programming languages) end up in a recipient's spam folder. Always check there before troubleshooting your code.

To avoid mail sent through PHP from being sent to a recipient's spam folder, there are various things you can do, both in your PHP code and otherwise, to minimize the chances your emails are marked as spam. Good tips from Michiel de Mare include:

  • Use email authentication methods, such as SPF, and DKIM to prove that your emails and your domain name belong together, and to prevent spoofing of your domain name. The SPF website includes a wizard to generate the DNS information for your site.
  • Check your reverse DNS to make sure the IP address of your mail server points to the domain name that you use for sending mail.
  • Make sure that the IP-address that you're using is not on a blacklist
  • Make sure that the reply-to address is a valid, existing address.
  • Use the full, real name of the addressee in the To field, not just the email-address (e.g. "John Smith" <[email protected]> ).
  • Monitor your abuse accounts, such as [email protected] and [email protected]. That means - make sure that these accounts exist, read what's sent to them, and act on complaints.
  • Finally, make it really easy to unsubscribe. Otherwise, your users will unsubscribe by pressing the spam button, and that will affect your reputation.

See How do you make sure email you send programmatically is not automatically marked as spam? for more on this topic.

Make sure all mail headers are supplied

Some spam software will reject mail if it is missing common headers such as "From" and "Reply-to":

$headers = array("From: [email protected]",
    "Reply-To: [email protected]",
    "X-Mailer: PHP/" . PHP_VERSION
);
$headers = implode("\r\n", $headers);
mail($to, $subject, $message, $headers);

Make sure mail headers have no syntax errors

Invalid headers are just as bad as having no headers. One incorrect character could be all it takes to derail your email. Double-check to make sure your syntax is correct as PHP will not catch these errors for you.

$headers = array("From [email protected]", // missing colon
    "Reply To: [email protected]",      // missing hyphen
    "X-Mailer: "PHP"/" . PHP_VERSION      // bad quotes
);

Don't use a faux From: sender

While the mail must have a From: sender, you may not just use any value. In particular user-supplied sender addresses are a surefire way to get mails blocked:

$headers = array("From: $_POST[contactform_sender_email]"); // No!

Reason: your web or sending mail server is not SPF/DKIM-whitelisted to pretend being responsible for @hotmail or @gmail addresses. It may even silently drop mails with From: sender domains it's not configured for.

Make sure the recipient value is correct

Sometimes the problem is as simple as having an incorrect value for the recipient of the email. This can be due to using an incorrect variable.

$to = '[email protected]';
// other variables ....
mail($recipient, $subject, $message, $headers); // $recipient should be $to

Another way to test this is to hard code the recipient value into the mail() function call:

mail('[email protected]', $subject, $message, $headers); 

This can apply to all of the mail() parameters.

Send to multiple accounts

To help rule out email account issues, send your email to multiple email accounts at different email providers. If your emails are not arriving at a user's Gmail account, send the same emails to a Yahoo account, a Hotmail account, and a regular POP3 account (like your ISP-provided email account).

If the emails arrive at all or some of the other email accounts, you know your code is sending emails but it is likely that the email account provider is blocking them for some reason. If the email does not arrive at any email account, the problem is more likely to be related to your code.

Make sure the code matches the form method

If you have set your form method to POST, make sure you are using $_POST to look for your form values. If you have set it to GET or didn't set it at all, make sure you use $_GET to look for your form values.

Make sure your form action value points to the correct location

Make sure your form action attribute contains a value that points to your PHP mailing code.

<form action="send_email.php" method="POST">

Make sure the Web host supports sending email

Some Web hosting providers do not allow or enable the sending of emails through their servers. The reasons for this may vary but if they have disabled the sending of mail you will need to use an alternative method that uses a third party to send those emails for you.

An email to their technical support (after a trip to their online support or FAQ) should clarify if email capabilities are available on your server.

Make sure the localhost mail server is configured

If you are developing on your local workstation using WAMP, MAMP, or XAMPP, an email server is probably not installed on your workstation. Without one, PHP cannot send mail by default.

You can overcome this by installing a basic mail server. For Windows you can use the free Mercury Mail.

You can also use SMTP to send your emails. See this great answer from Vikas Dwivedi to learn how to do this.

Enable PHP's custom mail.log

In addition to your MTA's and PHP's log file, you can enable logging for the mail() function specifically. It doesn't record the complete SMTP interaction, but at least function call parameters and invocation script.

ini_set("mail.log", "/tmp/mail.log");
ini_set("mail.add_x_header", TRUE);

See http://php.net/manual/en/mail.configuration.php for details. (It's best to enable these options in the php.ini or .user.ini or .htaccess perhaps.)

Check with a mail testing service

There are various delivery and spamminess checking services you can utilize to test your MTA/webserver setup. Typically you send a mail probe To: their address, then get a delivery report and more concrete failures or analyzations later:

Use a different mailer

PHP's built-in mail() function is handy and often gets the job done but it has its shortcomings. Fortunately, there are alternatives that offer more power and flexibility including handling a lot of the issues outlined above:

All of which can be combined with a professional SMTP server/service provider. (Because typical 08/15 shared webhosting plans are hit or miss when it comes to email setup/configurability.)

JavaScript for detecting browser language preference

Dan Singerman's answer has an issue that the header fetched has to be used right away, due to the asynchronous nature of jQuery's ajax. However, with his google app server, I wrote the following, such that the header is set as part of the initial set up and can be used at later time.

<html>
<head>
<script>

    var bLocale='raw'; // can be used at any other place

    function processHeaders(headers){
        bLocale=headers['Accept-Language'];
        comma=bLocale.indexOf(',');
        if(comma>0) bLocale=bLocale.substring(0, comma);
    }

</script>

<script src="jquery-1.11.0.js"></script>

<script type="application/javascript" src="http://ajaxhttpheaders.appspot.com?callback=processHeaders"></script>

</head>
<body>

<h1 id="bLocale">Should be the browser locale here</h1>

</body>

<script>

    $("#bLocale").text(bLocale);

</script>
</html>

Convert base64 string to image

In the server, do something like this:

Suppose

String data = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAYAAAA+VemSAAAgAEl...=='

Then:

String base64Image = data.split(",")[1];
byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image);

Then you can do whatever you like with the bytes like:

BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageBytes));

Which equals operator (== vs ===) should be used in JavaScript comparisons?

I tested this in Firefox with Firebug using code like this:

_x000D_
_x000D_
console.time("testEquality");
var n = 0;
while (true) {
  n++;
  if (n == 100000)
    break;
}
console.timeEnd("testEquality");
_x000D_
_x000D_
_x000D_

and

_x000D_
_x000D_
console.time("testTypeEquality");
var n = 0;
while (true) {
  n++;
  if (n === 100000)
    break;
}
console.timeEnd("testTypeEquality");
_x000D_
_x000D_
_x000D_

My results (tested five times each and averaged):

==: 115.2
===: 114.4

So I'd say that the miniscule difference (this is over 100000 iterations, remember) is negligible. Performance isn't a reason to do ===. Type safety (well, as safe as you're going to get in JavaScript), and code quality is.

Searching for UUIDs in text with regex

Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B. e.g. f47ac10b-58cc-4372-a567-0e02b2c3d479.

source: http://en.wikipedia.org/wiki/Uuid#Definition

Therefore, this is technically more correct:

/[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}/

Xml serialization - Hide null values

You can define some default values and it prevents the fields from being serialized.

    [XmlElement, DefaultValue("")]
    string data;

    [XmlArray, DefaultValue(null)]
    List<string> data;

Disable beep of Linux Bash on Windows 10

Uncommenting set bell-style none in /etc/inputrc and creating a .bash_profile with setterm -blength 0 didn't stop vim from beeping.

What worked for me was creating a .vimrc file in my home directory with set visualbell.

Source: https://linuxconfig.org/turn-off-beep-bell-on-linux-terminal

Write in body request with HttpClient

If your xml is written by java.lang.String you can just using HttpClient in this way

    public void post() throws Exception{
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://www.baidu.com");
        String xml = "<xml>xxxx</xml>";
        HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        String result = EntityUtils.toString(response.getEntity());
    }

pay attention to the Exceptions.

BTW, the example is written by the httpclient version 4.x

Sum of Numbers C++

The loop is great; it's what's inside the loop that's wrong. You need a variable named sum, and at each step, add i+1 to sum. At the end of the loop, sum will have the right value, so print it.

Pandas df.to_csv("file.csv" encode="utf-8") still gives trash characters for minus sign

Your "bad" output is UTF-8 displayed as CP1252.

On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:

df.to_csv('file.csv',encoding='utf-8-sig')

That encoder will add the BOM.

How to get Chrome to allow mixed content?

On OSX the following works from the command line:

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --allow-running-insecure-content