Programs & Examples On #Bittorrent

BitTorrent is a peer-to-peer file-sharing protocol.

How does DHT in torrents work?

With trackerless/DHT torrents, peer IP addresses are stored in the DHT using the BitTorrent infohash as the key. Since all a tracker does, basically, is respond to put/get requests, this functionality corresponds exactly to the interface that a DHT (distributed hash table) provides: it allows you to look up and store IP addresses in the DHT by infohash.

So a "get" request would look up a BT infohash and return a set of IP addresses. A "put" stores an IP address for a given infohash. This corresponds to the "announce" request you would otherwise make to the tracker to receive a dictionary of peer IP addresses.

In a DHT, peers are randomly assigned to store values belonging to a small fraction of the key space; the hashing ensures that keys are distributed randomly across participating peers. The DHT protocol (Kademlia for BitTorrent) ensures that put/get requests are routed efficiently to the peers responsible for maintaining a given key's IP address lists.

Altering a column: null to not null

I had the same problem, but the field used to default to null, and now I want to default it to 0. That required adding one more line after mdb's solution:

ALTER TABLE [Table] ADD CONSTRAINT [Constraint] DEFAULT 0 FOR [Column];

How can I filter a date of a DateTimeField in Django?

Here are the results I got with ipython's timeit function:

from datetime import date
today = date.today()

timeit[Model.objects.filter(date_created__year=today.year, date_created__month=today.month, date_created__day=today.day)]
1000 loops, best of 3: 652 us per loop

timeit[Model.objects.filter(date_created__gte=today)]
1000 loops, best of 3: 631 us per loop

timeit[Model.objects.filter(date_created__startswith=today)]
1000 loops, best of 3: 541 us per loop

timeit[Model.objects.filter(date_created__contains=today)]
1000 loops, best of 3: 536 us per loop

contains seems to be faster.

rotating axis labels in R

You need to use theme() function as follows rotating x-axis labels by 90 degrees:

ggplot(...)+...+ theme(axis.text.x = element_text(angle=90, hjust=1))

How to run only one unit test class using Gradle

To run a single test class Airborn's answer is good.

With using some command line options, which found here, you can simply do something like this.

gradle test --tests org.gradle.SomeTest.someSpecificFeature
gradle test --tests *SomeTest.someSpecificFeature
gradle test --tests *SomeSpecificTest
gradle test --tests all.in.specific.package*
gradle test --tests *IntegTest
gradle test --tests *IntegTest*ui*
gradle test --tests *IntegTest.singleMethod
gradle someTestTask --tests *UiTest someOtherTestTask --tests *WebTest*ui

From version 1.10 of gradle it supports selecting tests, using a test filter. For example,

apply plugin: 'java'

test {
  filter {
    //specific test method
      includeTestsMatching "org.gradle.SomeTest.someSpecificFeature"

     //specific test method, use wildcard for packages
     includeTestsMatching "*SomeTest.someSpecificFeature"

     //specific test class
     includeTestsMatching "org.gradle.SomeTest"

     //specific test class, wildcard for packages
     includeTestsMatching "*.SomeTest"

     //all classes in package, recursively
     includeTestsMatching "com.gradle.tooling.*"

     //all integration tests, by naming convention
      includeTestsMatching "*IntegTest"

     //only ui tests from integration tests, by some naming convention
     includeTestsMatching "*IntegTest*ui"
   }
}

For multi-flavor environments (a common use-case for Android), check this answer, as the --tests argument will be unsupported and you'll get an error.

How to disable textbox from editing?

You can set the ReadOnly property to true.

Quoth the link:

When this property is set to true, the contents of the control cannot be changed by the user at runtime. With this property set to true, you can still set the value of the Text property in code. You can use this feature instead of disabling the control with the Enabled property to allow the contents to be copied and ToolTips to be shown.

get enum name from enum value

Say we have:

public enum MyEnum {
  Test1, Test2, Test3
}

To get the name of a enum variable use name():

MyEnum e = MyEnum.Test1;
String name = e.name(); // Returns "Test1"

To get the enum from a (string) name, use valueOf():

String name = "Test1";
MyEnum e = Enum.valueOf(MyEnum.class, name);

If you require integer values to match enum fields, extend the enum class:

public enum MyEnum {
  Test1(1), Test2(2), Test3(3);

  public final int value;

  MyEnum(final int value) {
     this.value = value;
  }
}

Now you can use:

MyEnum e = MyEnum.Test1;
int value = e.value; // = 1

And lookup the enum using the integer value:

MyEnum getValue(int value) {
  for(MyEnum e: MyEunm.values()) {
    if(e.value == value) {
      return e;
    }
  }
  return null;// not found
}

PHP, pass array through POST

You could put it in the session:

session_start();
$_SESSION['array_name'] = $array_name;

Or if you want to send it via a form you can serialize it:

<input type='hidden' name='input_name' value="<?php echo htmlentities(serialize($array_name)); ?>" />

$passed_array = unserialize($_POST['input_name']);

Note that to work with serialized arrays, you need to use POST as the form's transmission method, as GET has a size limit somewhere around 1024 characters.

I'd use sessions wherever possible.

How to run a shell script at startup

Many answers on starting something at boot, but often you want to start it just a little later, because your script depends on e.g. networking. Use at to just add this delay, e.g.:

at now + 1 min -f /path/yourscript

You may add this in /etc/rc.local, but also in cron like:

# crontab -e
@reboot at now + 1 min -f /path/yourscript

Isn't it fun to combine cron and at? Info is in the man page man at.

As for the comments that @reboot may not be widely supported, just try it. I found out that /etc/rc.local has become obsolete on distros that support systemd, such as ubuntu and raspbian.

Why the switch statement cannot be applied on strings?

I think the reason is that in C strings are not primitive types, as tomjen said, think in a string as a char array, so you can not do things like:

switch (char[]) { // ...
switch (int[]) { // ...

How do I hide the PHP explode delimiter from submitted form results?

You could try a different approach like read the file line by line instead of dealing with all this nl2br / explode stuff.

$fh = fopen("employees.txt", "r"); if ($fh) {     while (($line = fgets($fh)) !== false) {         $line = trim($line);         echo "<option value='".$line."'>".$line."</option>";     } } else {     // error opening the file, do something } 

Also maybe just doing a trim (remove whitespace from beginning/end of string) is your issue?

And maybe people are just misunderstanding what you mean by "submitting results to a spreadsheet" -- are you doing this with code? or a copy/paste from an HTML page into a spreadsheet? Maybe you can explain that in more detail. The delimiter for which you split the lines of the file shouldn't be displaying in the output anyway unless you have unexpected output for some other reason.

Pass request headers in a jQuery AJAX GET call

Use beforeSend:

$.ajax({
         url: "http://localhost/PlatformPortal/Buyers/Account/SignIn",
         data: { signature: authHeader },
         type: "GET",
         beforeSend: function(xhr){xhr.setRequestHeader('X-Test-Header', 'test-value');},
         success: function() { alert('Success!' + authHeader); }
      });

http://api.jquery.com/jQuery.ajax/

http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader-method

Is there a Sleep/Pause/Wait function in JavaScript?

setTimeout() function it's use to delay a process in JavaScript.

w3schools has an easy tutorial about this function.

How to set zoom level in google map

Your code below is zooming the map to fit the specified bounds:

addMarker(27.703402,85.311668,'New Road');
center = bounds.getCenter();
map.fitBounds(bounds);

If you only have 1 marker and add it to the bounds, that results in the closest zoom possible:

function addMarker(lat, lng, info) {
  var pt = new google.maps.LatLng(lat, lng);
  bounds.extend(pt);
}

If you keep track of the number of markers you have "added" to the map (or extended the bounds with), you can only call fitBounds if that number is greater than one. I usually push the markers into an array (for later use) and test the length of that array.

If you will only ever have one marker, don't use fitBounds. Call setCenter, setZoom with the marker position and your desired zoom level.

function addMarker(lat, lng, info) {
  var pt = new google.maps.LatLng(lat, lng);
  map.setCenter(pt);
  map.setZoom(your desired zoom);
}

_x000D_
_x000D_
html,
body,
#map {
  height: 100%;
  width: 100%;
  padding: 0;
  margin: 0;
}
_x000D_
<html>

<head>
  <script src="http://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk" type="text/javascript"></script>
  <script type="text/javascript">
    var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/blue.png", new google.maps.Size(32, 32), new google.maps.Point(0, 0), new google.maps.Point(16, 32));
    var center = null;
    var map = null;
    var currentPopup;
    var bounds = new google.maps.LatLngBounds();

    function addMarker(lat, lng, info) {
      var pt = new google.maps.LatLng(lat, lng);
      map.setCenter(pt);
      map.setZoom(5);
      var marker = new google.maps.Marker({
        position: pt,
        icon: icon,
        map: map
      });
      var popup = new google.maps.InfoWindow({
        content: info,
        maxWidth: 300
      });
      google.maps.event.addListener(marker, "click", function() {
        if (currentPopup != null) {
          currentPopup.close();
          currentPopup = null;
        }
        popup.open(map, marker);
        currentPopup = popup;
      });
      google.maps.event.addListener(popup, "closeclick", function() {
        map.panTo(center);
        currentPopup = null;
      });
    }

    function initMap() {
      map = new google.maps.Map(document.getElementById("map"), {
        center: new google.maps.LatLng(0, 0),
        zoom: 1,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: false,
        mapTypeControlOptions: {
          style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
        },
        navigationControl: true,
        navigationControlOptions: {
          style: google.maps.NavigationControlStyle.SMALL
        }
      });
      addMarker(27.703402, 85.311668, 'New Road');
      // center = bounds.getCenter();
      // map.fitBounds(bounds);

    }
  </script>
</head>

<body onload="initMap()" style="margin:0px; border:0px; padding:0px;">
  <div id="map"></div>
</body>

</html>
_x000D_
_x000D_
_x000D_

Getter and Setter of Model object in Angular 4

The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date') declare the date property like so: private _date: string;. Also, make sure you are instantiating the model with the new keyword. Lastly, access the property using regular dot notation.

Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :

let passcode = "secret passcode";

class Employee {
    private _fullName: string;

    get fullName(): string {
        return this._fullName;
    }

    set fullName(newName: string) {
        if (passcode && passcode == "secret passcode") {
            this._fullName = newName;
        }
        else {
            console.log("Error: Unauthorized update of employee!");
        }
    }
}

let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
    console.log(employee.fullName);
}

And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview

HTML: Image won't display?

_x000D_
_x000D_
img {_x000D_
  width: 200px;_x000D_
}
_x000D_
<img src="https://image.ibb.co/gmmneK/children_593313_340.jpg"/>_x000D_
_x000D_
<img src="https://image.ibb.co/e0RLzK/entrepreneur_1340649_340.jpg"/>_x000D_
_x000D_
<img src="https://image.ibb.co/cks4Rz/typing_849806_340.jpg"/>
_x000D_
_x000D_
_x000D_

please see the above code.

Writing Python lists to columns in csv

If you are happy to use a 3rd party library, you can do this with Pandas. The benefits include seamless access to specialized methods and row / column labeling:

import pandas as pd

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]

df = pd.DataFrame(list(zip(*[list1, list2, list3]))).add_prefix('Col')

df.to_csv('file.csv', index=False)

print(df)

   Col0  Col1  Col2
0     1     4     7
1     2     5     8
2     3     6     9

Android Studio - Gradle sync project failed

This may be helpful for some.

My problem exactly is incomplete gradle-1.12-all file download.

Below is screen shot of the Error

enter image description here

  1. I re-downloaded the file from the gradle site here and extracted it in path/to/the/gradle, in my case was in C:\Users\maneeOsman\.gradle\wrapper\dists\gradle-1.12-all\2apkk7d25miauqf1pdjp1bm0uo
  2. I closed the android studio and reopen it in administrator privilege (Run as administrator).

The android studio starts downloading the necessary files for building and debugging. You can notice that from bottom-left indicator bar.

After this, it is working fine.

See the screen shot below

enter image description here

Google Chrome Printing Page Breaks

As far as I know the only way to get the correct page breaks in tables with Google Chrome is giving it to the element <tr> the property display: inline-table (or display: inline-block but it fits better in other cases that are not tables). Also should be used the properties "page-break-after: always; page-break-inside: avoid;" as written by @Phil Ross

<table>
  <tr style="display:inline-table;page-break-after: always; page-break-inside: avoid;">
    <td></td>
    <td></td>
    ...
  </tr>
</table>

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

string formatted = date.ToString("dd-MM-yyyy");

will do it.

Here is a good reference for different formats.

Update a column value, replacing part of a string

You need the WHERE clause to replace ONLY the records that complies with the condition in the WHERE clause (as opposed to all records). You use % sign to indicate partial string: I.E.

LIKE ('...//domain1.com/images/%');

means all records that BEGIN with "...//domain1.com/images/" and have anything AFTER (that's the % for...)

Another example:

LIKE ('%http://domain1.com/images/%')

which means all records that contains "http://domain1.com/images/"

in any part of the string...

Google API authentication: Not valid origin for the client

If you are running it on localhost change the port to 5000 and it will fix it

How do I 'overwrite', rather than 'merge', a branch on another branch in Git?

The other answers gave me the right clues, but they didn't completely help.

Here's what worked for me:

$ git checkout email
$ git tag old-email-branch # This is optional
$ git reset --hard staging
$
$ # Using a custom commit message for the merge below
$ git merge -m 'Merge -s our where _ours_ is the branch staging' -s ours origin/email
$ git push origin email

Without the fourth step of merging with the ours strategy, the push is considered a non-fast-forward update and will be rejected (by GitHub).

Why can't I see the "Report Data" window when creating reports?

Open report in Report designer

Go to View menu -> Report data

File upload along with other object in Jersey restful web service

When I tried @PaulSamsotha's solution with Jersey client 2.21.1, there was 400 error. It worked when I added following in my client code:

MediaType contentType = MediaType.MULTIPART_FORM_DATA_TYPE;
contentType = Boundary.addBoundary(contentType);

Response response = t.request()
        .post(Entity.entity(multipartEntity, contentType));

instead of hardcoded MediaType.MULTIPART_FORM_DATA in POST request call.

The reason this is needed is because when you use a different Connector (like Apache) for the Jersey Client, it is unable to alter outbound headers, which is required to add a boundary to the Content-Type. This limitation is explained in the Jersey Client docs. So if you want to use a different Connector, then you need to manually create the boundary.

Why does Firebug say toFixed() is not a function?

That is because Low is a string.

.toFixed() only works with a number.


Try doing:

Low = parseFloat(Low).toFixed(..);

java.lang.ClassNotFoundException: org.eclipse.core.runtime.adaptor.EclipseStarter

I just went through this. If you want to manually move your Eclipse installation you need to find and edit relative references in the following files.

Relative to Eclipse install dir:

  • configuration/org.eclipse.equinox.source/source.info
  • configuration/org.eclipse.equinox.simpleconfigurator/bundles.info
  • configuration/config.ini
  • eclipse.ini

For me in all these files there was a ../ reference to a .p2 folder in my home directory. Found them all using a simple grep:

grep '../../../../' * -R

Then just hit it with sed or manually go change it. In my case I moved it up one folder so easy fix:

grep -rl '../../../../' * -R | xargs sed -i 's/..\/..\/..\/..\//..\/..\/..\//g'

Now Eclipse runs fine again.

Find and replace in file and overwrite file doesn't work, it empties the file

I was searching for the option where I can define the line range and found the answer. For example I want to change host1 to host2 from line 36-57.

sed '36,57 s/host1/host2/g' myfile.txt > myfile1.txt

You can use gi option as well to ignore the character case.

sed '30,40 s/version/story/gi' myfile.txt > myfile1.txt

mysql error 1364 Field doesn't have a default values

When I had this same problem with mysql5.6.20 installed with Homebrew, I solved it by going into my.cnf

nano /usr/local/Cellar/mysql/5.6.20_1/my.cnf

Find the line that looks like so:

sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

Comment above line out and restart mysql server

mysql.server restart

Error gone!

How to know a Pod's own IP address from inside a container in the Pod?

Some clarifications (not really an answer)

In kubernetes, every pod gets assigned an IP address, and every container in the pod gets assigned that same IP address. Thus, as Alex Robinson stated in his answer, you can just use hostname -i inside your container to get the pod IP address.

I tested with a pod running two dumb containers, and indeed hostname -i was outputting the same IP address inside both containers. Furthermore, that IP was equivalent to the one obtained using kubectl describe pod from outside, which validates the whole thing IMO.

However, PiersyP's answer seems more clean to me.

Sources

From kubernetes docs:

The applications in a pod all use the same network namespace (same IP and port space), and can thus “find” each other and communicate using localhost. Because of this, applications in a pod must coordinate their usage of ports. Each pod has an IP address in a flat shared networking space that has full communication with other physical computers and pods across the network.

Another piece from kubernetes docs:

Until now this document has talked about containers. In reality, Kubernetes applies IP addresses at the Pod scope - containers within a Pod share their network namespaces - including their IP address. This means that containers within a Pod can all reach each other’s ports on localhost.

Conditional HTML Attributes using Razor MVC3

Note you can do something like this(at least in MVC3):

<td align="left" @(isOddRow ? "class=TopBorder" : "style=border:0px") >

What I believed was razor adding quotes was actually the browser. As Rism pointed out when testing with MVC 4(I haven't tested with MVC 3 but I assume behavior hasn't changed), this actually produces class=TopBorder but browsers are able to parse this fine. The HTML parsers are somewhat forgiving on missing attribute quotes, but this can break if you have spaces or certain characters.

<td align="left" class="TopBorder" >

OR

<td align="left" style="border:0px" >

What goes wrong with providing your own quotes

If you try to use some of the usual C# conventions for nested quotes, you'll end up with more quotes than you bargained for because Razor is trying to safely escape them. For example:

<button type="button" @(true ? "style=\"border:0px\"" : string.Empty)>

This should evaluate to <button type="button" style="border:0px"> but Razor escapes all output from C# and thus produces:

style=&quot;border:0px&quot;

You will only see this if you view the response over the network. If you use an HTML inspector, often you are actually seeing the DOM, not the raw HTML. Browsers parse HTML into the DOM, and the after-parsing DOM representation already has some niceties applied. In this case the Browser sees there aren't quotes around the attribute value, adds them:

style="&quot;border:0px&quot;"

But in the DOM inspector HTML character codes display properly so you actually see:

style=""border:0px""

In Chrome, if you right-click and select Edit HTML, it switch back so you can see those nasty HTML character codes, making it clear you have real outer quotes, and HTML encoded inner quotes.

So the problem with trying to do the quoting yourself is Razor escapes these.

If you want complete control of quotes

Use Html.Raw to prevent quote escaping:

<td @Html.Raw( someBoolean ? "rel='tooltip' data-container='.drillDown a'" : "" )>

Renders as:

<td rel='tooltip' title='Drilldown' data-container='.drillDown a'>

The above is perfectly safe because I'm not outputting any HTML from a variable. The only variable involved is the ternary condition. However, beware that this last technique might expose you to certain security problems if building strings from user supplied data. E.g. if you built an attribute from data fields that originated from user supplied data, use of Html.Raw means that string could contain a premature ending of the attribute and tag, then begin a script tag that does something on behalf of the currently logged in user(possibly different than the logged in user). Maybe you have a page with a list of all users pictures and you are setting a tooltip to be the username of each person, and one users named himself '/><script>$.post('changepassword.php?password=123')</script> and now any other user who views this page has their password instantly changed to a password that the malicious user knows.

Change color of Label in C#

I am going to assume this is a WinForms questions (which it feels like, based on it being a "program" rather than a website/app). In which case you can simple do the following to change the text colour of a label:

myLabel.ForeColor = System.Drawing.Color.Red;

Or any other colour of your choice. If you want to be more specific you can use an RGB value like so:

myLabel.ForeColor = Color.FromArgb(0, 0, 0);//(R, G, B) (0, 0, 0 = black)

Having different colours for different users can be done a number of ways. For example, you could allow each user to specify their own RGB value colours, store these somewhere and then load them when the user "connects".

An alternative method could be to just use 2 colours - 1 for the current user (running the app) and another colour for everyone else. This would help the user quickly identify their own messages above others.

A third approach could be to generate the colour randomly - however you will likely get conflicting values that do not show well against your background, so I would suggest not taking this approach. You could have a pre-defined list of "acceptable" colours and just pop one from that list for each user that joins.

Port 443 in use by "Unable to open process" with PID 4

Similarly, I experienced this: Port 443 in use by "Unable to open process" with PID 6012! When starting XAMPP Control Panel v3.2.1 for the first time.

In Task Manager I found that PID 6012 was Apache web server. A copy of it was running in the background without the GUI, and when I invoked the GUI it was trying to start another copy. Killed the phantom copy and then XAMPP started up fine.

I didn't have to change any port settings.

Printing Lists as Tabular Data

Python actually makes this quite easy.

Something like

for i in range(10):
    print '%-12i%-12i' % (10 ** i, 20 ** i)

will have the output

1           1           
10          20          
100         400         
1000        8000        
10000       160000      
100000      3200000     
1000000     64000000    
10000000    1280000000  
100000000   25600000000
1000000000  512000000000

The % within the string is essentially an escape character and the characters following it tell python what kind of format the data should have. The % outside and after the string is telling python that you intend to use the previous string as the format string and that the following data should be put into the format specified.

In this case I used "%-12i" twice. To break down each part:

'-' (left align)
'12' (how much space to be given to this part of the output)
'i' (we are printing an integer)

From the docs: https://docs.python.org/2/library/stdtypes.html#string-formatting

Link to all Visual Studio $ variables

Ok, I finally wanted to have a pretty complete, searchable list of those variables for reference. Here is a complete (OCR-generated, as I did not easily find something akin to a printenv command) list of defined variables for a Visual C++ project on my machine. Probably not all macros are defined for others (e.g. OCTAVE_EXECUTABLE), but I wanted to err on the side of inclusiveness here.

For example, this is the first time that I see $(Language) (expanding to C++ for this project) being mentioned outside of the IDE.

$(AllowLocalNetworkLoopback)
$(ALLUSERSPROFILE)
$(AndroidTargetsPath)
$(APPDATA)
$(AppxManifestMetadataClHostArchDir)
$(AppxManifestMetadataCITargetArchDir)
$(Attach)
$(BaseIntermediateOutputPath)
$(BuildingInsideVisualStudio)
$(CharacterSet)
$(CLRSupport)
$(CommonProgramFiles)
$(CommonProgramW6432)
$(COMPUTERNAME)
$(ComSpec)
$(Configuration)
$(ConfigurationType)
$(CppWinRT_IncludePath)
$(CrtSDKReferencelnclude)
$(CrtSDKReferenceVersion)
$(CustomAfterMicrosoftCommonProps)
$(CustomBeforeMicrosoftCommonProps)
$(DebugCppRuntimeFilesPath)
$(DebuggerFlavor)
$(DebuggerLaunchApplication)
$(DebuggerRequireAuthentication)
$(DebuggerType)
$(DefaultLanguageSourceExtension)
$(DefaultPlatformToolset)
$(DefaultWindowsSDKVersion)
$(DefineExplicitDefaults)
$(DelayImplib)
$(DesignTimeBuild)
$(DevEnvDir)
$(DocumentLibraryDependencies)
$(DotNetSdk_IncludePath)
$(DotNetSdk_LibraryPath)
$(DotNetSdk_LibraryPath_arm)
$(DotNetSdk_LibraryPath_arm64)
$(DotNetSdk_LibraryPath_x64)
$(DotNetSdk_LibraryPath_x86)
$(DotNetSdkRoot)
$(DriverData)
$(EmbedManifest)
$(EnableManagedIncrementalBuild)
$(EspXtensions)
$(ExcludePath)
$(ExecutablePath)
$(ExtensionsToDeleteOnClean)
$(FPS_BROWSER_APP_PROFILE_STRING)
$(FPS_BROWSER_USER_PROFILE_STRING)
$(FrameworkDir)
$(FrameworkDir_110)
$(FrameworkSdkDir)
$(FrameworkSDKRoot)
$(FrameworkVersion)
$(GenerateManifest)
$(GPURefDebuggerBreakOnAllThreads)
$(HOMEDRIVE)
$(HOMEPATH)
$(IgnorelmportLibrary)
$(ImportByWildcardAfterMicrosoftCommonProps)
$(ImportByWildcardBeforeMicrosoftCommonProps)
$(ImportDirectoryBuildProps)
$(ImportProjectExtensionProps)
$(ImportUserLocationsByWildcardAfterMicrosoftCommonProps)
$(ImportUserLocationsByWildcardBeforeMicrosoftCommonProps)
$(IncludePath)
$(IncludeVersionInInteropName)
$(IntDir)
$(InteropOutputPath)
$(iOSTargetsPath)
$(Keyword)
$(KIT_SHARED_IncludePath)
$(LangID)
$(LangName)
$(Language)
$(LIBJABRA_TRACE_LEVEL)
$(LibraryPath)
$(LibraryWPath)
$(LinkCompiled)
$(LinkIncremental)
$(LOCALAPPDATA)
$(LocalDebuggerAttach)
$(LocalDebuggerDebuggerlType)
$(LocalDebuggerMergeEnvironment)
$(LocalDebuggerSQLDebugging)
$(LocalDebuggerWorkingDirectory)
$(LocalGPUDebuggerTargetType)
$(LOGONSERVER)
$(MicrosoftCommonPropsHasBeenImported)
$(MpiDebuggerCleanupDeployment)
$(MpiDebuggerDebuggerType)
$(MpiDebuggerDeployCommonRuntime)
$(MpiDebuggerNetworkSecurityMode)
$(MpiDebuggerSchedulerNode)
$(MpiDebuggerSchedulerTimeout)
$(MSBuild_ExecutablePath)
$(MSBuildAllProjects)
$(MSBuildAssemblyVersion)
$(MSBuildBinPath)
$(MSBuildExtensionsPath)
$(MSBuildExtensionsPath32)
$(MSBuildExtensionsPath64)
$(MSBuildFrameworkToolsPath)
$(MSBuildFrameworkToolsPath32)
$(MSBuildFrameworkToolsPath64)
$(MSBuildFrameworkToolsRoot)
$(MSBuildLoadMicrosoftTargetsReadOnly)
$(MSBuildNodeCount)
$(MSBuildProgramFiles32)
$(MSBuildProjectDefaultTargets)
$(MSBuildProjectDirectory)
$(MSBuildProjectDirectoryNoRoot)
$(MSBuildProjectExtension)
$(MSBuildProjectExtensionsPath)
$(MSBuildProjectFile)
$(MSBuildProjectFullPath)
$(MSBuildProjectName)
$(MSBuildRuntimeType)
$(MSBuildRuntimeVersion)
$(MSBuildSDKsPath)
$(MSBuildStartupDirectory)
$(MSBuildToolsPath)
$(MSBuildToolsPath32)
$(MSBuildToolsPath64)
$(MSBuildToolsRoot)
$(MSBuildToolsVersion)
$(MSBuildUserExtensionsPath)
$(MSBuildVersion)
$(MultiToolTask)
$(NETFXKitsDir)
$(NETFXSDKDir)
$(NuGetProps)
$(NUMBER_OF_PROCESSORS)
$(OCTAVE_EXECUTABLE)
$(OneDrive)
$(OneDriveCommercial)
$(OS)
$(OutDir)
$(OutDirWasSpecified)
$(OutputType)
$(Path)
$(PATHEXT)
$(PkgDefApplicationConfigFile)
$(Platform)
$(Platform_Actual)
$(PlatformArchitecture)
$(PlatformName)
$(PlatformPropsFound)
$(PlatformShortName)
$(PlatformTarget)
$(PlatformTargetsFound)
$(PlatformToolset)
$(PlatformToolsetVersion)
$(PostBuildEventUseInBuild)
$(PreBuildEventUseInBuild)
$(PreferredToolArchitecture)
$(PreLinkEventUselnBuild)
$(PROCESSOR_ARCHITECTURE)
$(PROCESSOR_ARCHITEW6432)
$(PROCESSOR_IDENTIFIER)
$(PROCESSOR_LEVEL)
$(PROCESSOR_REVISION)
$(ProgramData)
$(ProgramFiles)
$(ProgramW6432)
$(ProjectDir)
$(ProjectExt)
$(ProjectFileName)
$(ProjectGuid)
$(ProjectName)
$(ProjectPath)
$(PSExecutionPolicyPreference)
$(PSModulePath)
$(PUBLIC)
$(ReferencePath)
$(RemoteDebuggerAttach)
$(RemoteDebuggerConnection)
$(RemoteDebuggerDebuggerlype)
$(RemoteDebuggerDeployDebugCppRuntime)
$(RemoteDebuggerServerName)
$(RemoteDebuggerSQLDebugging)
$(RemoteDebuggerWorkingDirectory)
$(RemoteGPUDebuggerTargetType)
$(RetargetAlwaysSupported)
$(RootNamespace)
$(RoslynTargetsPath)
$(SDK35ToolsPath)
$(SDK40ToolsPath)
$(SDKDisplayName)
$(SDKIdentifier)
$(SDKVersion)
$(SESSIONNAME)
$(SolutionDir)
$(SolutionExt)
$(SolutionFileName)
$(SolutionName)
$(SolutionPath)
$(SourcePath)
$(SpectreMitigation)
$(SQLDebugging)
$(SystemDrive)
$(SystemRoot)
$(TargetExt)
$(TargetFrameworkVersion)
$(TargetName)
$(TargetPlatformMinVersion)
$(TargetPlatformVersion)
$(TargetPlatformWinMDLocation)
$(TargetUniversalCRTVersion)
$(TEMP)
$(TMP)
$(ToolsetPropsFound)
$(ToolsetTargetsFound)
$(UCRTContentRoot)
$(UM_IncludePath)
$(UniversalCRT_IncludePath)
$(UniversalCRT_LibraryPath_arm)
$(UniversalCRT_LibraryPath_arm64)
$(UniversalCRT_LibraryPath_x64)
$(UniversalCRT_LibraryPath_x86)
$(UniversalCRT_PropsPath)
$(UniversalCRT_SourcePath)
$(UniversalCRTSdkDir)
$(UniversalCRTSdkDir_10)
$(UseDebugLibraries)
$(UseLegacyManagedDebugger)
$(UseOfATL)
$(UseOfMfc)
$(USERDOMAIN)
$(USERDOMAIN_ROAMINGPROFILE)
$(USERNAME)
$(USERPROFILE)
$(UserRootDir)
$(VBOX_MSI_INSTALL_PATH)
$(VC_ATLMFC_IncludePath)
$(VC_ATLMFC_SourcePath)
$(VC_CRT_SourcePath)
$(VC_ExecutablePath_ARM)
$(VC_ExecutablePath_ARM64)
$(VC_ExecutablePath_x64)
$(VC_ExecutablePath_x64_ARM)
$(VC_ExecutablePath_x64_ARM64)
$(VC_ExecutablePath_x64_x64)
$(VC_ExecutablePath_x64_x86)
$(VC_ExecutablePath_x86)
$(VC_ExecutablePath_x86_ARM)
$(VC_ExecutablePath_x86_ARM64)
$(VC_ExecutablePath_x86_x64)
$(VC_ExecutablePath_x86_x86)
$(VC_IFCPath)
$(VC_IncludePath)
$(VC_LibraryPath_ARM)
$(VC_LibraryPath_ARM64)
$(VC_LibraryPath_ATL_ARM)
$(VC_LibraryPath_ATL_ARM64)
$(VC_LibraryPath_ATL_x64)
$(VC_LibraryPath_ATL_x86)
$(VC_LibraryPath_VC_ARM)
$(VC_LibraryPath_VC_ARM_Desktop)
$(VC_LibraryPath_VC_ARM_OneCore)
$(VC_LibraryPath_VC_ARM_Store)
$(VC_LibraryPath_VC_ARM64)
$(VC_LibraryPath_VC_ARM64_Desktop)
$(VC_LibraryPath_VC_ARM64_OneCore)
$(VC_LibraryPath_VC_ARM64_Store)
$(VC_LibraryPath_VC_x64)
$(VC_LibraryPath_VC_x64_Desktop)
$(VC_LibraryPath_VC_x64_OneCore)
$(VC_LibraryPath_VC_x64_Store)
$(VC_LibraryPath_VC_x86)
$(VC_LibraryPath_VC_x86_Desktop)
$(VC_LibraryPath_VC_x86_OneCore)
$(VC_LibraryPath_VC_x86_Store)
$(VC_LibraryPath_x64)
$(VC_LibraryPath_x86)
$(VC_PGO_RunTime_Dir)
$(VC_ReferencesPath_ARM)
$(VC_ReferencesPath_ARM64)
$(VC_ReferencesPath_ATL_ARM)
$(VC_ReferencesPath_ATL_ARM64)
$(VC_ReferencesPath_ATL_x64)
$(VC_ReferencesPath_ATL_x86)
$(VC_ReferencesPath_VC_ARM)
$(VC_ReferencesPath_VC_ARM64)
$(VC_ReferencesPath_VC_x64)
$(VC_ReferencesPath_VC_x86)
$(VC_ReferencesPath_x64)
$(VC_ReferencesPath_x86)
$(VC_SourcePath)
$(VC_VC_IncludePath)
$(VC_VS_IncludePath)
$(VC_VS_LibraryPath_VC_VS_ARM)
$(VC_VS_LibraryPath_VC_VS_x64)
$(VC_VS_LibraryPath_VC_VS_x86)
$(VC_VS_SourcePath)
$(VCIDEInstallDir)
$(VCIDEInstallDir_150)
$(VCInstallDir)
$(VCInstallDir_150)
$(VCLibPackagePath)
$(VCProjectVersion)
$(VCTargetsPath)
$(VCTargetsPath10)
$(VCTargetsPath11)
$(VCTargetsPath12)
$(VCTargetsPath14)
$(VCTargetsPath15)
$(VCTargetsPathActual)
$(VCTargetsPathEffective)
$(VCToolArchitecture)
$(VCToolsInstallDir)
$(VCToolsInstallDir_150)
$(VCToolsVersion)
$(VisualStudioDir)
$(VisualStudioEdition)
$(VisualStudioVersion)
$(VS_ExecutablePath)
$(VS140COMNTOOLS)
$(VSAPPIDDIR)
$(VSAPPIDNAME)
$(VSInstallDir)
$(VSInstallDir_150)
$(VsInstallRoot)
$(VSLANG)
$(VSSKUEDITION)
$(VSVersion)
$(WDKBinRoot)
$(WebBrowserDebuggerDebuggerlype)
$(WebServiceDebuggerDebuggerlype)
$(WebServiceDebuggerSQLDebugging)
$(WholeProgramOptimization)
$(WholeProgramOptimizationAvailabilityInstrument)
$(WholeProgramOptimizationAvailabilityOptimize)
$(WholeProgramOptimizationAvailabilityTrue)
$(WholeProgramOptimizationAvailabilityUpdate)
$(windir)
$(Windows81SdkInstalled)
$(WindowsAppContainer)
$(WindowsSDK_ExecutablePath)
$(WindowsSDK_ExecutablePath_arm)
$(WindowsSDK_ExecutablePath_arm64)
$(WindowsSDK_ExecutablePath_x64)
$(WindowsSDK_LibraryPath_x86)
$(WindowsSDK_MetadataFoundationPath)
$(WindowsSDK_MetadataPath)
$(WindowsSDK_MetadataPathVersioned)
$(WindowsSDK_PlatformPath)
$(WindowsSDK_SupportedAPIs_arm)
$(WindowsSDK_SupportedAPIs_x64)
$(WindowsSDK_SupportedAPIs_x86)
$(WindowsSDK_UnionMetadataPath)
$(WindowsSDK80Path)
$(WindowsSdkDir)
$(WindowsSdkDir_10)
$(WindowsSdkDir_81)
$(WindowsSdkDir_81A)
$(WindowsSDKToolArchitecture)
$(WindowsTargetPlatformVersion)
$(WinRT_IncludePath)
$(WMSISProject)
$(WMSISProjectDirectory)

Where to find this list within Visual Studio:

  1. Open your C++ project's dialogue Property Pages
  2. Select any textual field that can use a configuration variable. (in the screenshot, I use Target Name)
  3. On the right side of the text box, click the small combobox button and select option <Edit...>.
  4. In the new window (here, title is Target Name), click on button Macros>>.
  5. Scroll through the giant list of environment/linker/macro variables.

Motivational screenshot:

Visual Studio project Property Pages with exemplary Macro variable list

How do I remove a submodule?

  • A submodule can be deleted by running git rm <submodule path> && git commit. This can be undone using git revert.
    • The deletion removes the superproject's tracking data, which are both the gitlink entry and the section in the .gitmodules file.
    • The submodule's working directory is removed from the file system, but the Git directory is kept around as it to make it possible to checkout past commits without requiring fetching from another repository.
  • To completely remove a submodule, additionally manually delete $GIT_DIR/modules/<name>/.

Source: git help submodules

Access Session attribute on jstl

You don't need the jsp:useBean to set the model if you already have a controller which prepared the model.

Just access it plain by EL:

<p>${Questions.questionPaperID}</p>
<p>${Questions.question}</p>

or by JSTL <c:out> tag if you'd like to HTML-escape the values or when you're still working on legacy Servlet 2.3 containers or older when EL wasn't supported in template text yet:

<p><c:out value="${Questions.questionPaperID}" /></p>
<p><c:out value="${Questions.question}" /></p>

See also:


Unrelated to the problem, the normal practice is by the way to start attribute name with a lowercase, like you do with normal variable names.

session.setAttribute("questions", questions);

and alter EL accordingly to use ${questions}.

Also note that you don't have any JSTL tag in your code. It's all plain JSP.

What is the difference between Collection and List in Java?

Collection is the root interface to the java Collections hierarchy. List is one sub interface which defines an ordered Collection, other sub interfaces are Queue which typically will store elements ready for processing (e.g. stack).

The following diagram demonstrates the relationship between the different java collection types:

java collections

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.

setAttribute('display','none') not working

Try this:

setAttribute("hidden", true);

Excel - Combine multiple columns into one column

You can combine the columns without using macros. Type the following function in the formula bar:

=IF(ROW()<=COUNTA(A:A),INDEX(A:A,ROW()),IF(ROW()<=COUNTA(A:B),INDEX(B:B,ROW()-COUNTA(A:A)),IF(ROW()>COUNTA(A:C),"",INDEX(C:C,ROW()-COUNTA(A:B)))))

The statement uses 3 IF functions, because it needs to combine 3 columns:

  • For column A, the function compares the row number of a cell with the total number of cells in A column that are not empty. If the result is true, the function returns the value of the cell from column A that is at row(). If the result is false, the function moves on to the next IF statement.
  • For column B, the function compares the row number of a cell with the total number of cells in A:B range that are not empty. If the result is true, the function returns the value of the first cell that is not empty in column B. If false, the function moves on to the next IF statement.
  • For column C, the function compares the row number of a cell with the total number of cells in A:C range that are not empty. If the result is true, the function returns a blank cell and doesn't do any more calculation. If false, the function returns the value of the first cell that is not empty in column C.

TestNG ERROR Cannot find class in classpath

Check the class hierarchy. If the package is missing in your class you'll get this error. So, try to create a new testing class by selecting the package.

Restrict SQL Server Login access to only one database

For anyone else out there wondering how to do this, I have the following solution for SQL Server 2008 R2 and later:

USE master
go
DENY VIEW ANY DATABASE TO [user]
go

This will address exactly the requirement outlined above..

Disable all Database related auto configuration in Spring Boot

Way out for me was to add

@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})

annotation to class running Spring boot (marked with `@SpringBootApplication).

Finally, it looks like:

@SpringBootApplication
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class Application{

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
 }

How to pass variables from one php page to another without form?

You want sessions if you have data you want to have the data held for longer than one page.

$_GET for just one page.

<a href='page.php?var=data'>Data link</a>

on page.php

<?php
echo $_GET['var'];
?>

will output: data

Android Intent Cannot resolve constructor

You may use this:

Intent intent = new Intent(getApplicationContext(), ClassName.class);

Usage of sys.stdout.flush() method

You can see the differences b/w these two

import sys

for i in range(1,10 ):
    sys.stdout.write(str(i))
    sys.stdout.flush()

for i in range(1,10 ):
    print i

How to display an alert box from C# in ASP.NET?

You can use Message box to show success message. This works great for me.

MessageBox.Show("Data inserted successfully");

Removing items from a ListBox in VB.net

Here's the code I came up with to remove items selected by a user from a listbox It seems to work ok in a multiselect listbox (selectionmode prop is set to multiextended).:

Private Sub cmdRemoveList_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdRemoveList.Click
    Dim knt As Integer = lstwhatever.SelectedIndices.Count
    Dim i As Integer
    For i = 0 To knt - 1
        lstwhatever.Items.RemoveAt(lstwhatever.SelectedIndex)
    Next
End Sub

Ternary operation in CoffeeScript

In almost any language this should work instead:

a = true  && 5 || 10
a = false && 5 || 10

"Application tried to present modally an active controller"?

Assume you have three view controllers instantiated like so:

UIViewController* vc1 = [[UIViewController alloc] init];
UIViewController* vc2 = [[UIViewController alloc] init];
UIViewController* vc3 = [[UIViewController alloc] init];

You have added them to a tab bar like this:

UITabBarController* tabBarController = [[UITabBarController alloc] init];
[tabBarController setViewControllers:[NSArray arrayWithObjects:vc1, vc2, vc3, nil]];

Now you are trying to do something like this:

[tabBarController presentModalViewController:vc3];

This will give you an error because that Tab Bar Controller has a death grip on the view controller that you gave it. You can either not add it to the array of view controllers on the tab bar, or you can not present it modally.

Apple expects you to treat their UI elements in a certain way. This is probably buried in the Human Interface Guidelines somewhere as a "don't do this because we aren't expecting you to ever want to do this".

Export HTML table to pdf using jspdf

Use get(0) instead of html(). In other words, replace

doc.fromHTML($('#htmlTableId').html(), 15, 15, {
    'width': 170,'elementHandlers': specialElementHandlers
});

with

doc.fromHTML($('#htmlTableId').get(0), 15, 15, {
    'width': 170,'elementHandlers': specialElementHandlers
});

How to find list of possible words from a letter matrix [Boggle Solver]

I suggest making a tree of letters based on words. The tree would be composed of a letter structs, like this:

letter: char
isWord: boolean

Then you build up the tree, with each depth adding a new letter. In other words, on the first level there'd be the alphabet; then from each of those trees, there'd be another another 26 entries, and so on, until you've spelled out all the words. Hang onto this parsed tree, and it'll make all possible answers faster to look up.

With this parsed tree, you can very quickly find solutions. Here's the pseudo-code:

BEGIN: 
    For each letter:
        if the struct representing it on the current depth has isWord == true, enter it as an answer.
        Cycle through all its neighbors; if there is a child of the current node corresponding to the letter, recursively call BEGIN on it.

This could be sped up with a bit of dynamic programming. For example, in your sample, the two 'A's are both next to an 'E' and a 'W', which (from the point they hit them on) would be identical. I don't have enough time to really spell out the code for this, but I think you can gather the idea.

Also, I'm sure you'll find other solutions if you Google for "Boggle solver".

Opening new window in HTML for target="_blank"

You can't influence neither type (tab/window) nor dimensions that way. You'll have to use JavaScript's window.open() for that.

Regular expression to match a word or its prefix

Use this live online example to test your pattern:

enter image description here

Above screenshot taken from this live example: https://regex101.com/r/cU5lC2/1

Matching any whole word on the commandline.

I'll be using the phpsh interactive shell on Ubuntu 12.10 to demonstrate the PCRE regex engine through the method known as preg_match

Start phpsh, put some content into a variable, match on word.

el@apollo:~/foo$ phpsh

php> $content1 = 'badger'
php> $content2 = '1234'
php> $content3 = '$%^&'

php> echo preg_match('(\w+)', $content1);
1

php> echo preg_match('(\w+)', $content2);
1

php> echo preg_match('(\w+)', $content3);
0

The preg_match method used the PCRE engine within the PHP language to analyze variables: $content1, $content2 and $content3 with the (\w)+ pattern.

$content1 and $content2 contain at least one word, $content3 does not.

Match a specific words on the commandline without word bountaries

el@apollo:~/foo$ phpsh

php> $gun1 = 'dart gun';
php> $gun2 = 'fart gun';
php> $gun3 = 'darty gun';
php> $gun4 = 'unicorn gun';

php> echo preg_match('(dart|fart)', $gun1);
1

php> echo preg_match('(dart|fart)', $gun2);
1

php> echo preg_match('(dart|fart)', $gun3);
1

php> echo preg_match('(dart|fart)', $gun4);
0

Variables gun1 and gun2 contain the string dart or fart which is correct, but gun3 contains darty and still matches, that is the problem. So onto the next example.

Match specific words on the commandline with word boundaries:

Word Boundaries can be force matched with \b, see: Visual analysis of what wordboundary is doing from jex.im/regulex

Regex Visual Image acquired from http://jex.im/regulex and https://github.com/JexCheng/regulex Example:

el@apollo:~/foo$ phpsh

php> $gun1 = 'dart gun';
php> $gun2 = 'fart gun';
php> $gun3 = 'darty gun';
php> $gun4 = 'unicorn gun';

php> echo preg_match('(\bdart\b|\bfart\b)', $gun1);
1

php> echo preg_match('(\bdart\b|\bfart\b)', $gun2);
1

php> echo preg_match('(\bdart\b|\bfart\b)', $gun3);
0

php> echo preg_match('(\bdart\b|\bfart\b)', $gun4);
0

The \b asserts that we have a word boundary, making sure " dart " is matched, but " darty " isn't.

Your content must have a ListView whose id attribute is 'android.R.id.list'

Rename the id of your ListView like this,

<ListView android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"/>

Since you are using ListActivity your xml file must specify the keyword android while mentioning to a ID.

If you need a custom ListView then instead of Extending a ListActivity, you have to simply extend an Activity and should have the same id without the keyword android.

Load different application.yml in SpringBoot Test

We can use @SpringBootTest annotation which loads the yml file from src\main\java\com...hence when we execute the unit test, all of the properties are already there in the config properties class.

@RunWith(SpringRunner.class)
@SpringBootTest
public class AddressFieldsTest {

    @InjectMocks
    AddressFieldsValidator addressFieldsValidator;

    @Autowired
    AddressFieldsConfig addressFieldsConfig;
    ...........

    @Before
    public void setUp() throws Exception{
        MockitoAnnotations.initMocks(this);
        ReflectionTestUtils.setField(addressFieldsValidator,"addressFieldsConfig", addressFieldsConfig);
    }

}

We can use @Value annotation if you have few configs or other wise we can use a config properties class. For e.g

@Data
@Component
@RefreshScope
@ConfigurationProperties(prefix = "address.fields.regex")
public class AddressFieldsConfig {

    private int firstName;
    private int lastName;
    .........

How to change indentation in Visual Studio Code?

In my case "EditorConfig for VS Code" extention is overriding VSCode settings. If you have it installed, then check .editorconfig file in the root folder of the project.

Here is an example config. The "indent_size" sets the number of spaces for a tab.

# editorconfig.org
root = true

[*]
indent_style = space
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
trim_trailing_whitespace = false

private constructor

private constructor are useful when you don't want your class to be instantiated by user. To instantiate such classes, you need to declare a static method, which does the 'new' and returns the pointer.

A class with private ctors can not be put in the STL containers, as they require a copy ctor.

Add CSS class to a div in code behind

Here are two extension methods you can use. They ensure any existing classes are preserved and do not duplicate classes being added.

public static void RemoveCssClass(this WebControl control, String css) {
  control.CssClass = String.Join(" ", control.CssClass.Split(' ').Where(x => x != css).ToArray());
}

public static void AddCssClass(this WebControl control, String css) {
  control.RemoveCssClass(css);
  css += " " + control.CssClass;
  control.CssClass = css;
}

Usage: hlCreateNew.AddCssClass("disabled");

Usage: hlCreateNew.RemoveCssClass("disabled");

res.sendFile absolute path

Based on the other answers, this is a simple example of how to accomplish the most common requirement:

const app = express()
app.use(express.static('public')) // relative path of client-side code
app.get('*', function(req, res) {
    res.sendFile('index.html', { root: __dirname })
})
app.listen(process.env.PORT)

This also doubles as a simple way to respond with index.html on every request, because I'm using a star * to catch all files that weren't found in your static (public) directory; which is the most common use case for web-apps. Change to / to return the index only in the root path.

Android: how to refresh ListView contents?

Another easy way:

//In your ListViewActivity:
public void refreshListView() {
    listAdapter = new ListAdapter(this);
    setListAdapter(listAdapter);
}

Export and import table dump (.sql) using pgAdmin

If you have Git bash installed, you can do something like this:

/c/Program\ Files\ \(x86\)/PostgreSQL/9.3/bin/psql -U <pg_role_name> -d <pg_database_name> < <path_to_your>.sql

How to find encoding of a file via script on Linux?

I am using the following script to

  1. Find all files that match FILTER with SRC_ENCODING
  2. Create a backup of them
  3. Convert them to DST_ENCODING
  4. (optional) Remove the backups

.

#!/bin/bash -xe

SRC_ENCODING="iso-8859-1"
DST_ENCODING="utf-8"
FILTER="*.java"

echo "Find all files that match the encoding $SRC_ENCODING and filter $FILTER"
FOUND_FILES=$(find . -iname "$FILTER" -exec file -i {} \; | grep "$SRC_ENCODING" | grep -Eo '^.*\.java')

for FILE in $FOUND_FILES ; do
    ORIGINAL_FILE="$FILE.$SRC_ENCODING.bkp"
    echo "Backup original file to $ORIGINAL_FILE"
    mv "$FILE" "$ORIGINAL_FILE"

    echo "converting $FILE from $SRC_ENCODING to $DST_ENCODING"
    iconv -f "$SRC_ENCODING" -t "$DST_ENCODING" "$ORIGINAL_FILE" -o "$FILE"
done

echo "Deleting backups"
find . -iname "*.$SRC_ENCODING.bkp" -exec rm {} \;

Disable color change of anchor tag when visited

I think if I set a color for a:visited it is not good: you must know the default color of tag a and every time synchronize it with a:visited.

I don't want know about the default color (it can be set in common.css of your application, or you can using outside styles).

I think it's nice solution:

HTML:

<body>
    <a class="absolute">Test of URL</a>
    <a class="unvisited absolute" target="_blank" href="google.ru">Test of URL</a>
</body>

CSS:

.absolute{
    position: absolute;
}
a.unvisited, a.unvisited:visited, a.unvisited:active{
    text-decoration: none;
    color: transparent;
}

Convert JSON string to array of JSON objects in Javascript

Using jQuery:

var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}';
var jsonObj = $.parseJSON('[' + str + ']');

jsonObj is your JSON object.

What is the easiest way to encrypt a password when I save it to the registry?

If you need more than this, for example securing a connection string (for connection to a database), check this article, as it provides the best "option" for this.

Oli's answer is also good, as it shows how you can create a hash for a string.

SELECT * WHERE NOT EXISTS

SELECT * from employees
WHERE NOT EXISTS (SELECT name FROM eotm_dyn)

Never returns any records unless eotm_dyn is empty. You need to some kind of criteria on SELECT name FROM eotm_dyn like

SELECT * from employees
WHERE NOT EXISTS (
    SELECT name FROM eotm_dyn WHERE eotm_dyn.employeeid = employees.employeeid
)

assuming that the two tables are linked by a foreign key relationship. At this point you could use a variety of other options including a LEFT JOIN. The optimizer will typically handle them the same in most cases, however.

Difference between View and ViewGroup in Android

ViewGroup is itself a View that works as a container for other views. It extends the functionality of View class in order to provide efficient ways to layout the child views.

For example, LinearLayout is a ViewGroup that lets you define the orientation in which you want child views to be laid, that's all you need to do and LinearLayout will take care of the rest.

What's an easy way to read random line from a file in Unix command line?

Here's a simple Python script that will do the job:

import random, sys
lines = open(sys.argv[1]).readlines()
print(lines[random.randrange(len(lines))])

Usage:

python randline.py file_to_get_random_line_from

How to delete/unset the properties of a javascript object?

To blank it:

myObject["myVar"]=null;

To remove it:

delete myObject["myVar"]

as you can see in duplicate answers

Convert double to string

Try c.ToString("F6");

(For a full explanation of numeric formatting, see MSDN)

Why do I have to run "composer dump-autoload" command to make migrations work in laravel?

Short answer: classmaps are static while PSR autoloading is dynamic.

If you don't want to use classmaps, use PSR autoloading instead.

Fastest way to find second (third...) highest/lowest value in vector or column

This will find the index of the N'th smallest or largest value in the input numeric vector x. Set bottom=TRUE in the arguments if you want the N'th from the bottom, or bottom=FALSE if you want the N'th from the top. N=1 and bottom=TRUE is equivalent to which.min, N=1 and bottom=FALSE is equivalent to which.max.

FindIndicesBottomTopN <- function(x=c(4,-2,5,-77,99),N=1,bottom=FALSE)
{

  k1 <- rank(x)
  if(bottom==TRUE){
    Nindex <- which(k1==N)
    Nindex <- Nindex[1]
  }

  if(bottom==FALSE){
    Nindex <- which(k1==(length(x)+1-N))
    Nindex <- Nindex[1]
  }

  return(Nindex)
}

Does Python support short-circuiting?

Yes. Try the following in your python interpreter:

and

>>>False and 3/0
False
>>>True and 3/0
ZeroDivisionError: integer division or modulo by zero

or

>>>True or 3/0
True
>>>False or 3/0
ZeroDivisionError: integer division or modulo by zero

Replace all elements of Python NumPy Array that are greater than some value

Lets us assume you have a numpy array that has contains the value from 0 all the way up to 20 and you want to replace numbers greater than 10 with 0

_x000D_
_x000D_
import numpy as np

my_arr = np.arange(0,21) # creates an array
my_arr[my_arr > 10] = 0 # modifies the value
_x000D_
_x000D_
_x000D_

Note this will however modify the original array to avoid overwriting the original array try using arr.copy() to create a new detached copy of the original array and modify that instead.

_x000D_
_x000D_
import numpy as np

my_arr = np.arange(0,21)
my_arr_copy = my_arr.copy() # creates copy of the orignal array

my_arr_copy[my_arr_copy > 10] = 0 
_x000D_
_x000D_
_x000D_

How to ignore certain files in Git

First create a .gitignore file where we have to store the names of files and directories to be ignored. To ignore a directory;

name_of_directory/

To ignore a file;

name_of_file

We don't need to provide the complete path of the file or directory to be ignored, we just have to provide its name.

If you want to ignore all files with same extention;

*.pyc  #will ignore all files with pyc extention

Conditionally hide CommandField or ButtonField in Gridview

Allow me to share my approach for what it's worth. For me converting the commandfield to a templatefield control is not an option, as the commandfield comes with built-in functionality that I would otherwise have to create myself, for example the fact that it changes to "Update Cancel" when Edit is clicked, and that when Edit is clicked, all the cells in the row which are labels become textboxes, etc.

In my approach, you can leave the commandfield as is, then you can hide it as needed via code behind. In this example, I am hiding it if the field "Scenario" of the grid shows the text "Actual" for the relevant row of the RowDataBound event.

protected void gridDetail_RowDataBound(object sender, GridViewRowEventArgs e)
    {   
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (((Label)e.Row.FindControl("lblScenario")).Text == "Actual")
            {
                LinkButton cmdField= (LinkButton)e.Row.Cells[0].Controls[0];
                cmdField.Visible = false;
            }
    }}

overlay opaque div over youtube iframe

I spent a day messing with CSS before I found anataliocs tip. Add wmode=transparent as a parameter to the YouTube URL:

<iframe title=<your frame title goes here> 
    src="http://www.youtube.com/embed/K3j9taoTd0E?wmode=transparent"  
    scrolling="no" 
    frameborder="0" 
    width="640" 
    height="390" 
    style="border:none;">
</iframe>

This allows the iframe to inherit the z-index of its container so your opaque <div> would be in front of the iframe.

Difference between HashSet and HashMap?

A HashSet is implemented in terms of a HashMap. It's a mapping between the key and a PRESENT object.

Insert default value when parameter is null

With enough defaults on a table, you can simply say:

INSERT t DEFAULT VALUES

Note that this is quite an unlikely case, however.

I've only had to use it once in a production environment. We had two closely related tables, and needed to guarantee that neither table had the same UniqueID, so we had a separate table which just had an identity column, and the best way to insert into it was with the syntax above.

Android Studio - How to Change Android SDK Path

For projects default:

  1. Close current Project (File->Close project)

You'll get a Welcome to Android Studio Dialog. In that:

  1. Click on Configure -> Project Defaults -> Project Structure

  2. Click on SDK Location in the left column

  3. Put the path to the Android SDK in "Android SDK location" field.

(Example SDK location: C:\android-sdk; I have sub-folders like add-ons, platforms etc under C:\android-sdk)

  1. Click OK to save changes

  2. Have fun!

Following steps were for older versions(<1.0) of Android Studio

  1. In the middle column Click on Android SDK (with Android icon) OR click + on the top if you don't see an entry with Android icon.

  2. Change SDK Home Path and select valid Target.

Custom "confirm" dialog in JavaScript?

One other way would be using colorbox

function createConfirm(message, okHandler) {
    var confirm = '<p id="confirmMessage">'+message+'</p><div class="clearfix dropbig">'+
            '<input type="button" id="confirmYes" class="alignleft ui-button ui-widget ui-state-default" value="Yes" />' +
            '<input type="button" id="confirmNo" class="ui-button ui-widget ui-state-default" value="No" /></div>';

    $.fn.colorbox({html:confirm, 
        onComplete: function(){
            $("#confirmYes").click(function(){
                okHandler();
                $.fn.colorbox.close();
            });
            $("#confirmNo").click(function(){
                $.fn.colorbox.close();
            });
    }});
}

How does Go update third-party packages?

go get will install the package in the first directory listed at GOPATH (an environment variable which might contain a colon separated list of directories). You can use go get -u to update existing packages.

You can also use go get -u all to update all packages in your GOPATH

For larger projects, it might be reasonable to create different GOPATHs for each project, so that updating a library in project A wont cause issues in project B.

Type go help gopath to find out more about the GOPATH environment variable.

Node.js - How to send data from html to express

Using http.createServer is very low-level and really not useful for creating web applications as-is.

A good framework to use on top of it is Express, and I would seriously suggest using it. You can install it using npm install express.

When you have, you can create a basic application to handle your form:

var express = require('express');
var bodyParser = require('body-parser');
var app     = express();

//Note that in version 4 of express, express.bodyParser() was
//deprecated in favor of a separate 'body-parser' module.
app.use(bodyParser.urlencoded({ extended: true })); 

//app.use(express.bodyParser());

app.post('/myaction', function(req, res) {
  res.send('You sent the name "' + req.body.name + '".');
});

app.listen(8080, function() {
  console.log('Server running at http://127.0.0.1:8080/');
});

You can make your form point to it using:

<form action="http://127.0.0.1:8080/myaction" method="post">

The reason you can't run Node on port 80 is because there's already a process running on that port (which is serving your index.html). You could use Express to also serve static content, like index.html, using the express.static middleware.

how to include js file in php?

Pekka has the correct answer (hence my making this answer a Community Wiki): Use src, not href, to specify the file.

Regarding:

When i try it this way:

<script type="text/javascript">
    document.write('<script type="text/javascript" src="datetimepicker_css.js"></script>');
</script>

the first tag in the document.write function closes
what is the correct way to do this?

You don't want or need document.write for this, but just in case you ever do need to put the characters </script> inside a script tag for some other reason: You do that by ensuring that the HTML parser (which doesn't understand JavaScript) doesn't see a literal </script>. There are a couple of ways of doing that. One way is to escape the / even though you don't need to:

<script type='text/javascript'>
alert("<\/script>"); // Works, HTML parser doesn't see this as a closing script tag
//      ^--- note the seemingly-unnecessary backslash
</script>

Or if you're feeling more paranoid:

<script type='text/javascript'>
alert("</scr" + "ipt>"); // Works, HTML parser doesn't see this as a closing script tag
</script>

...since in each case, JavaScript sees the string as </script> but the HTML parser doesn't.

SQL Server ORDER BY date and nulls last

A bit late, but maybe someone finds it useful.

For me, ISNULL was out of question due to the table scan. UNION ALL would need me to repeat a complex query, and due to me selecting only the TOP X it would not have been very efficient.

If you are able to change the table design, you can:

  1. Add another field, just for sorting, such as Next_Contact_Date_Sort.

  2. Create a trigger that fills that field with a large (or small) value, depending on what you need:

    CREATE TRIGGER FILL_SORTABLE_DATE ON YOUR_TABLE AFTER INSERT,UPDATE AS 
    BEGIN
        SET NOCOUNT ON;
        IF (update(Next_Contact_Date)) BEGIN
        UPDATE YOUR_TABLE SET Next_Contact_Date_Sort=IIF(YOUR_TABLE.Next_Contact_Date IS NULL, 99/99/9999, YOUR_TABLE.Next_Contact_Date_Sort) FROM inserted i WHERE YOUR_TABLE.key1=i.key1 AND YOUR_TABLE.key2=i.key2
        END
    END
    

Running Java Program from Command Line Linux

(This is the KISS answer.)

Let's say you have several .java files in the current directory:

$ ls -1 *.java
javaFileName1.java
javaFileName2.java

Let's say each of them have a main() method (so they are programs, not libs), then to compile them do:

javac *.java -d .

This will generate as many subfolders as "packages" the .java files are associated to. In my case all java files where inside under the same package name packageName, so only one folder was generated with that name, so to execute each of them:

java -cp . packageName.javaFileName1
java -cp . packageName.javaFileName2

Do Java arrays have a maximum size?

Yes, there limit on java array. Java uses an integer as an index to the array and the maximum integer store by JVM is 2^32. so you can store 2,147,483,647 elements in the array.

In case you need more than max-length you can use two different arrays but the recommended method is store data into a file. because storing data in the file has no limit. because files stored in your storage drivers but array are stored in JVM. JVM provides limited space for program execution.

Eclipse change project files location

There is now a plugin (since end of 2012) that can take care of this: gensth/ProjectLocationUpdater on GitHub.

Check whether a variable is a string in Ruby

I think you are looking for instance_of?. is_a? and kind_of? will return true for instances from derived classes.

class X < String
end

foo = X.new

foo.is_a? String         # true
foo.kind_of? String      # true
foo.instance_of? String  # false
foo.instance_of? X       # true

How do I delete specific lines in Notepad++?

Here is a way that removes the lines containing "YOURTEXT" completely:

  • Open the Replace dialog
  • Enter the following search string: .*YOURTEXT.*[\r]?[\n] (replace YOURTEXT with your text)
  • Enable "Regular expression"
  • Disable ". matches newline"

The given regular expression matches both Windows and Unix end of lines.

If your text contains characters that have a special meaning for regular expression, like the backslash, you will need to escape them.

Bootstrap 3 grid with no gap

Simple you can use bellow class.

_x000D_
_x000D_
.nopadmar {_x000D_
   padding: 0 !important;_x000D_
   margin: 0 !important;_x000D_
}
_x000D_
<div class="container-fluid">_x000D_
  <div class="row">_x000D_
    <div class="col-md-6 nopadmar">Your Content<div>_x000D_
       <div class="col-md-6 nopadmar">Your Content<div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jquery .on() method with load event

I'm not sure what you're going for here--by the time jQuery(document).ready() has executed, it has already loaded, and thus document's load event will already have been called. Attaching the load event handler at this point will have no effect and it will never be called. If you're attempting to alert "started" once the document has loaded, just put it right in the (document).ready() call, like this:

jQuery(document).ready(function() {
    var x = $('#initial').html();
    $('#add').click(function() {
        $('body').append(x);
    });

    alert('started');

});?

If, as your code also appears to insinuate, you want to fire the alert when .abc has loaded, put it in an individual .load handler:

jQuery(document).ready(function() {
    var x = $('#initial').html();
    $('#add').click(function() {
        $('body').append(x);
    });

    $(".abc").on("load", function() {
        alert('started');
    }
});?

Finally, I see little point in using jQuery in one place and $ in another. It's generally better to keep your code consistent, and either use jQuery everywhere or $ everywhere, as the two are generally interchangeable.

Visual Studio: How to show Overloads in IntelliSense?

Tested only on Visual Studio 2010.

Place your cursor within the (), press Ctrl+K, then P.

Now navigate by pressing the  ?  / ?   arrow keys.

Change package name for Android in React Native

Go to Android Studio, open app, right click on java and choose New and then Package.

Give the name you want (e.g. com.something).

Move the files from the other package (you want to rename) to the new Package. Delete the old package.

Go to your project in your editor and use the shortcut for searching in all the files (on mac is shift cmd F). Type in the name of your old package. Change all the references to the new package name.

Go to Android Studio, Build, Clean Project, Rebuild Project.

Done!

Happy coding :)

What is the most accurate way to retrieve a user's correct IP address in PHP?

Here is a shorter, cleaner way to get the IP address:

function get_ip_address(){
    foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key){
        if (array_key_exists($key, $_SERVER) === true){
            foreach (explode(',', $_SERVER[$key]) as $ip){
                $ip = trim($ip); // just to be safe

                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){
                    return $ip;
                }
            }
        }
    }
}

Your code seems to be pretty complete already, I cannot see any possible bugs in it (aside from the usual IP caveats), I would change the validate_ip() function to rely on the filter extension though:

public function validate_ip($ip)
{
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false)
    {
        return false;
    }

    self::$ip = sprintf('%u', ip2long($ip)); // you seem to want this

    return true;
}

Also your HTTP_X_FORWARDED_FOR snippet can be simplified from this:

// check for IPs passing through proxies
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
    // check if multiple ips exist in var
    if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ',') !== false)
    {
        $iplist = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        
        foreach ($iplist as $ip)
        {
            if ($this->validate_ip($ip))
                return $ip;
        }
    }
    
    else
    {
        if ($this->validate_ip($_SERVER['HTTP_X_FORWARDED_FOR']))
            return $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
}

To this:

// check for IPs passing through proxies
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
    $iplist = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        
    foreach ($iplist as $ip)
    {
        if ($this->validate_ip($ip))
            return $ip;
    }
}

You may also want to validate IPv6 addresses.

How to replace part of string by position?

Use String.Substring() (details here) to cut left part, then your replacement, then right part. Play with indexes until you get it right :)

Something like:

string replacement=original.Substring(0,start)+
    rep+original.Substring(start+rep.Length);

Gradle project refresh failed after Android Studio update

Most people do not read the comments so to summarize (Thanks to @Industrial-antidepressant and @wrecker):

As suggested in a bug ticket you should try the following:

  1. Close Android Studio
  2. go to android-studio/plugins/gradle/lib
  3. Delete (or better move them somewhere to have a backup) all gradle-*-1.8 files
  4. Start Android Studio again and rebuild/refresh.

It should work. Make sure to star the above bug ticket to get informed.

Little tip: Try the new compile setting Settings -> Compiler -> Gradle and activate the third in-process build for a speed up. Depending on your project setting you might want to select the first one as well. With that my project build time reduced to 2-4 seconds (before 20+ seconds).

How to set timeout in Retrofit library?

I am using Retrofit 1.9 to obtain a XML.

public class ServicioConexionRetrofitXML {

    public static final String API_BASE_URL = new GestorPreferencias().getPreferencias().getHost();
    public static final long tiempoMaximoRespuestaSegundos = 60;
    public static final long tiempoMaximoLecturaSegundos = 100;
    public static final OkHttpClient clienteOkHttp = new OkHttpClient();


    private static RestAdapter.Builder builder = new RestAdapter.Builder().
            setEndpoint(API_BASE_URL).
            setClient(new OkClient(clienteOkHttp)).setConverter(new SimpleXMLConverter());


    public static <S> S createService(Class<S> serviceClass) {
        clienteOkHttp.setConnectTimeout(tiempoMaximoRespuestaSegundos, TimeUnit.SECONDS);
        clienteOkHttp.setReadTimeout(tiempoMaximoLecturaSegundos, TimeUnit.SECONDS);
        RestAdapter adapter = builder.build();
        return adapter.create(serviceClass);
    }

}

If you are using Retrofit 1.9.0 and okhttp 2.6.0, add to your Gradle file.

    compile 'com.squareup.retrofit:retrofit:1.9.0'
    compile 'com.squareup.okhttp:okhttp:2.6.0'
    // Librería de retrofit para XML converter (Simple) Se excluyen grupos para que no entre
    // en conflicto.
    compile('com.squareup.retrofit:converter-simplexml:1.9.0') {
        exclude group: 'xpp3', module: 'xpp3'
        exclude group: 'stax', module: 'stax-api'
        exclude group: 'stax', module: 'stax'
    }

Note: If you need to fetch a JSON, just remove from code above.

.setConverter(new SimpleXMLConverter())

CSS root directory

I use a relative path solution,

./../../../../../images/img.png

every ../ will take you one folder up towards the root. Hope this helps..

How to add headers to OkHttp request interceptor?

client = new OkHttpClient();

        Request request = new Request.Builder().header("authorization", token).url(url).build();
        MyWebSocketListener wsListener = new MyWebSocketListener(LudoRoomActivity.this);
        client.newWebSocket(request, wsListener);
        client.dispatcher().executorService().shutdown();

Android Studio and android.support.v4.app.Fragment: cannot resolve symbol

I was facing the same issue. As it turns out in my build.gradle file there was this :

configurations {
    all*.exclude group: 'com.android.support'
}

Removing that fixed my issue. So guys, if doing all that and still your issue is not fixed, look for any exclude keywords in your gradle file.

OwinStartup not firing

I had same problem when I added Owin to an existing web project. I eventually found the problem was due to the following in the web.config file.

<assemblies>
  <remove assembly="*" />
  <add assembly="System.Web.Mvc" />
  <add assembly="System.Web.WebPages" />

   ...

</assemblies>

The remove assembly="*" was causing the problem. When I remove this line the Owin startup code ran. I eventually change it to the following and it worked perfectly

<assemblies>
  <remove assembly="*" />
  <add assembly="Microsoft.Owin.Host.SystemWeb" />
  <add assembly="System.Web.Mvc" />
  <add assembly="System.Web.WebPages" />
  <add assembly="System.Web.Helpers" />
...
</assemblies>

Substitute a comma with a line break in a cell

You can also do this without VBA from the find/replace dialogue box. My answer was at https://stackoverflow.com/a/6116681/509840 .

How to run a shell script on a Unix console or Mac terminal?

First, give permission for execution:-
chmod +x script_name

  1. If script is not executable:-
    For running sh script file:-
    sh script_name
    For running bash script file:-
    bash script_name
  2. If script is executable:-
    ./script_name

NOTE:-you can check if the file is executable or not by using 'ls -a'

check if a key exists in a bucket in s3 using boto3

If you seek a key that is equivalent to a directory then you might want this approach

session = boto3.session.Session()
resource = session.resource("s3")
bucket = resource.Bucket('mybucket')

key = 'dir-like-or-file-like-key'
objects = [o for o in bucket.objects.filter(Prefix=key).limit(1)]    
has_key = len(objects) > 0

This works for a parent key or a key that equates to file or a key that does not exist. I tried the favored approach above and failed on parent keys.

How to see remote tags?

Even without cloning or fetching, you can check the list of tags on the upstream repo with git ls-remote:

git ls-remote --tags /url/to/upstream/repo

(as illustrated in "When listing git-ls-remote why there's “^{}” after the tag name?")

xbmono illustrates in the comments that quotes are needed:

git ls-remote --tags /some/url/to/repo "refs/tags/MyTag^{}"

Note that you can always push your commits and tags in one command with (git 1.8.3+, April 2013):

git push --follow-tags

See Push git commits & tags simultaneously.


Regarding Atlassian SourceTree specifically:

Note that, from this thread, SourceTree ONLY shows local tags.

There is an RFE (Request for Enhancement) logged in SRCTREEWIN-4015 since Dec. 2015.

A simple workaround:

see a list of only unpushed tags?

git push --tags

or check the "Push all tags" box on the "Push" dialog box, all tags will be pushed to your remote.

https://community.atlassian.com/tnckb94959/attachments/tnckb94959/sourcetree-questions/10923/1/Screen%20Shot%202015-12-15%20at%208.49.48%20AM.png

That way, you will be "sure that they are present in remote so that other developers can pull them".

Sorting dropdown alphabetically in AngularJS

You should be able to use filter: orderBy

orderBy can accept a third option for the reverse flag.

<select ng-option="item.name for item in items | orderBy:'name':true"></select>

Here item is sorted by 'name' property in a reversed order. The 2nd argument can be any order function, so you can sort in any rule.

@see http://docs.angularjs.org/api/ng.filter:orderBy

How to convert between bytes and strings in Python 3?

TRY THIS:

StringVariable=ByteVariable.decode('UTF-8','ignore')

TO TEST TYPE:

print(type(StringVariable))

Here 'StringVariable' represented as a string. 'ByteVariable' represent as Byte. Its not relevent to question Variables..

How can I check if string contains characters & whitespace, not just whitespace?

The regular expression I ended up using for when I want to allow spaces in the middle of my string, but not at the beginning or end was this:

[\S]+(\s[\S]+)*

or

^[\S]+(\s[\S]+)*$

So, I know this is an old question, but you could do something like:

if (/^\s+$/.test(myString)) {
    //string contains characters and white spaces
}

or you can do what nickf said and use:

if (/\S/.test(myString)) {
    // string is not empty and not just whitespace
}

How to open specific tab of bootstrap nav tabs on click of a particuler link using jQuery?

I wrote this snippet, that I've been using for handling this exact case.

It's in plain javascript, making it also suitable in cases like with bootsrap5 without jQuery.

<script type='text/javascript'>
    window.onhashchange=hashTriggerTab;
    window.onload=hashTriggerTab;
    
    function hashTriggerTab(){
        var current_hash=window.location.hash;
        if(current_hash.substring(0,1)=='#')current_hash=current_hash.substring(1);
        if(current_hash!=''){
            var trigger=document.querySelector('.nav-tabs a[href="#'+current_hash+'"]');
            if(trigger)trigger.click();
        }
    }
</script>

With that in place, you could link both on the same page, like:

<a href='#tabId'>Link Any Tab</a>

Or from external page like:

<a href='newpage.php#tabId'>Link From External</a>

Ternary operator (?:) in Bash

If the condition is merely checking if a variable is set, there's even a shorter form:

a=${VAR:-20}

will assign to a the value of VAR if VAR is set, otherwise it will assign it the default value 20 -- this can also be a result of an expression.

This approach is technically called "Parameter Expansion".

org.xml.sax.SAXParseException: Content is not allowed in prolog

I was also getting the same

XML reader error: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,2] Message: Reference is not allowed in prolog.

, when my application was creating a XML response for a RestFull Webservice call. While creating the XML format String I replaced the &lt and &gt with < and > then the error went off, and I was getting proper response. Not sure how it worked but it worked.

sample:

String body = "<ns:addNumbersResponse xmlns:ns=\"http://java.duke.org\"><ns:return>"
            +sum
            +"</ns:return></ns:addNumbersResponse>";

how to select rows based on distinct values of A COLUMN only

I am not sure about your DBMS. So, I created a temporary table in Redshift and from my experience, I think this query should return what you are looking for:

select min(Id), distinct MailId, EmailAddress, Name
    from yourTableName
    group by MailId, EmailAddress, Name

I see that I am using a GROUP BY clause but you still won't have two rows against any particular MailId.

What are Java command line options to set to allow JVM to be remotely debugged?

-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=PORT_NUMBER

Here we just use a Socket Attaching Connector, which is enabled by default when the dt_socket transport is configured and the VM is running in the server debugging mode.

For more details u can refer to : https://stackify.com/java-remote-debugging/

How to call a function in shell Scripting?

The functions need to be defined before being used. There is no mechanism is sh to pre-declare functions, but a common technique is to do something like:

main() {
  case "$choice" in
    true)  process_install;;
    false) process_exit;;
  esac
}

process_install()
{
  commands...
  commands...
}

process_exit()
{
  commands...
  commands...
}

main()

How do I list the symbols in a .so file

For shared libraries libNAME.so the -D switch was necessary to see symbols in my Linux

nm -D libNAME.so

and for static library as reported by others

nm -g libNAME.a

What are the rules about using an underscore in a C++ identifier?

The rules to avoid collision of names are both in the C++ standard (see Stroustrup book) and mentioned by C++ gurus (Sutter, etc.).

Personal rule

Because I did not want to deal with cases, and wanted a simple rule, I have designed a personal one that is both simple and correct:

When naming a symbol, you will avoid collision with compiler/OS/standard libraries if you:

  • never start a symbol with an underscore
  • never name a symbol with two consecutive underscores inside.

Of course, putting your code in an unique namespace helps to avoid collision, too (but won't protect against evil macros)

Some examples

(I use macros because they are the more code-polluting of C/C++ symbols, but it could be anything from variable name to class name)

#define _WRONG
#define __WRONG_AGAIN
#define RIGHT_
#define WRONG__WRONG
#define RIGHT_RIGHT
#define RIGHT_x_RIGHT

Extracts from C++0x draft

From the n3242.pdf file (I expect the final standard text to be similar):

17.6.3.3.2 Global names [global.names]

Certain sets of names and function signatures are always reserved to the implementation:

— Each name that contains a double underscore _ _ or begins with an underscore followed by an uppercase letter (2.12) is reserved to the implementation for any use.

— Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.

But also:

17.6.3.3.5 User-defined literal suffixes [usrlit.suffix]

Literal suffix identifiers that do not start with an underscore are reserved for future standardization.

This last clause is confusing, unless you consider that a name starting with one underscore and followed by a lowercase letter would be Ok if not defined in the global namespace...

Vertical align text in block element

with thanks to Vlad's answer for inspiration; tested & working on IE11, FF49, Opera40, Chrome53

li > a {
  height: 100px;
  width: 300px;
  display: table-cell;
  text-align: center; /* H align */
  vertical-align: middle;
}

centers in all directions nicely even with text wrapping, line breaks, images, etc.

I got fancy and made a snippet

_x000D_
_x000D_
li > a {_x000D_
  height: 100px;_x000D_
  width: 300px;_x000D_
  display: table-cell;_x000D_
  /*H align*/_x000D_
  text-align: center;_x000D_
  /*V align*/_x000D_
  vertical-align: middle;_x000D_
}_x000D_
a.thin {_x000D_
  width: 40px;_x000D_
}_x000D_
a.break {_x000D_
  /*force text wrap, otherwise `width` is treated as `min-width` when encountering a long word*/_x000D_
  word-break: break-all;_x000D_
}_x000D_
/*more css so you can see this easier*/_x000D_
_x000D_
li {_x000D_
  display: inline-block;_x000D_
}_x000D_
li > a {_x000D_
  padding: 10px;_x000D_
  margin: 30px;_x000D_
  background: aliceblue;_x000D_
}_x000D_
li > a:hover {_x000D_
  padding: 10px;_x000D_
  margin: 30px;_x000D_
  background: aqua;_x000D_
}
_x000D_
<li><a href="">My menu item</a>_x000D_
</li>_x000D_
<li><a href="">My menu <br> break item</a>_x000D_
</li>_x000D_
<li><a href="">My menu item that is really long and unweildly</a>_x000D_
</li>_x000D_
<li><a href="" class="thin">Good<br>Menu<br>Item</a>_x000D_
</li>_x000D_
<li><a href="" class="thin">Fantastically Menu Item</a>_x000D_
</li>_x000D_
<li><a href="" class="thin break">Fantastically Menu Item</a>_x000D_
</li>_x000D_
<br>_x000D_
note: if using "break-all" need to also use "&lt;br>" or suffer the consequences
_x000D_
_x000D_
_x000D_

Angular JS: Full example of GET/POST/DELETE/PUT client for a REST/CRUD backend?

You can implement this way

$resource('http://localhost\\:3000/realmen/:entryId', {entryId: '@entryId'}, {
        UPDATE: {method: 'PUT', url: 'http://localhost\\:3000/realmen/:entryId' },
        ACTION: {method: 'PUT', url: 'http://localhost\\:3000/realmen/:entryId/action' }
    })

RealMen.query() //GET  /realmen/
RealMen.save({entryId: 1},{post data}) // POST /realmen/1
RealMen.delete({entryId: 1}) //DELETE /realmen/1

//any optional method
RealMen.UPDATE({entryId:1}, {post data}) // PUT /realmen/1

//query string
RealMen.query({name:'john'}) //GET /realmen?name=john

Documentation: https://docs.angularjs.org/api/ngResource/service/$resource

Hope it helps

form_for with nested resources

Travis R is correct. (I wish I could upvote ya.) I just got this working myself. With these routes:

resources :articles do
  resources :comments
end

You get paths like:

/articles/42
/articles/42/comments/99

routed to controllers at

app/controllers/articles_controller.rb
app/controllers/comments_controller.rb

just as it says at http://guides.rubyonrails.org/routing.html#nested-resources, with no special namespaces.

But partials and forms become tricky. Note the square brackets:

<%= form_for [@article, @comment] do |f| %>

Most important, if you want a URI, you may need something like this:

article_comment_path(@article, @comment)

Alternatively:

[@article, @comment]

as described at http://edgeguides.rubyonrails.org/routing.html#creating-paths-and-urls-from-objects

For example, inside a collections partial with comment_item supplied for iteration,

<%= link_to "delete", article_comment_path(@article, comment_item),
      :method => :delete, :confirm => "Really?" %>

What jamuraa says may work in the context of Article, but it did not work for me in various other ways.

There is a lot of discussion related to nested resources, e.g. http://weblog.jamisbuck.org/2007/2/5/nesting-resources

Interestingly, I just learned that most people's unit-tests are not actually testing all paths. When people follow jamisbuck's suggestion, they end up with two ways to get at nested resources. Their unit-tests will generally get/post to the simplest:

# POST /comments
post :create, :comment => {:article_id=>42, ...}

In order to test the route that they may prefer, they need to do it this way:

# POST /articles/42/comments
post :create, :article_id => 42, :comment => {...}

I learned this because my unit-tests started failing when I switched from this:

resources :comments
resources :articles do
  resources :comments
end

to this:

resources :comments, :only => [:destroy, :show, :edit, :update]
resources :articles do
  resources :comments, :only => [:create, :index, :new]
end

I guess it's ok to have duplicate routes, and to miss a few unit-tests. (Why test? Because even if the user never sees the duplicates, your forms may refer to them, either implicitly or via named routes.) Still, to minimize needless duplication, I recommend this:

resources :comments
resources :articles do
  resources :comments, :only => [:create, :index, :new]
end

Sorry for the long answer. Not many people are aware of the subtleties, I think.

Get the first element of each tuple in a list in Python

Use a list comprehension:

res_list = [x[0] for x in rows]

Below is a demonstration:

>>> rows = [(1, 2), (3, 4), (5, 6)]
>>> [x[0] for x in rows]
[1, 3, 5]
>>>

Alternately, you could use unpacking instead of x[0]:

res_list = [x for x,_ in rows]

Below is a demonstration:

>>> lst = [(1, 2), (3, 4), (5, 6)]
>>> [x for x,_ in lst]
[1, 3, 5]
>>>

Both methods practically do the same thing, so you can choose whichever you like.

Unknown column in 'field list' error on MySQL Update query

Enclose any string to be passed to the mysql server inside single quotes; e.g.:

$name = "my name"
$query = " INSERT INTO mytable VALUES ( 1 , '$name') "

Note that although the query is enclosed between double quotes, you must enclose any string in single quotes.

Remove the last character in a string in T-SQL?

select left('TEST STRING', len('TEST STRING')-1)

How do the likely/unlikely macros in the Linux kernel work and what is their benefit?

They are hint to the compiler to emit instructions that will cause branch prediction to favour the "likely" side of a jump instruction. This can be a big win, if the prediction is correct it means that the jump instruction is basically free and will take zero cycles. On the other hand if the prediction is wrong, then it means the processor pipeline needs to be flushed and it can cost several cycles. So long as the prediction is correct most of the time, this will tend to be good for performance.

Like all such performance optimisations you should only do it after extensive profiling to ensure the code really is in a bottleneck, and probably given the micro nature, that it is being run in a tight loop. Generally the Linux developers are pretty experienced so I would imagine they would have done that. They don't really care too much about portability as they only target gcc, and they have a very close idea of the assembly they want it to generate.

Cannot open include file: 'unistd.h': No such file or directory

The "uni" in unistd stands for "UNIX" - you won't find it on a Windows system.

Most widely used, portable libraries should offer alternative builds or detect the platform and only try to use headers/functions that will be provided, so it's worth checking documentation to see if you've missed some build step - e.g. perhaps running "make" instead of loading a ".sln" Visual C++ solution file.

If you need to fix it yourself, remove the include and see which functions are actually needed, then try to find a Windows equivalent.

Get Selected value from Multi-Value Select Boxes by jquery-select2?

Please, ckeck this simple example. You can get values in select2 multi.

var values = $('#id-select2-multi').val();
console.log(values);

Get java.nio.file.Path object from java.io.File

Yes, you can get it from the File object by using File.toPath(). Keep in mind that this is only for Java 7+. Java versions 6 and below do not have it.

CSS body background image fixed to full screen even when zooming in/out

Add this in your css file:

.custom_class
 {
    background-image: url(../img/beach.jpg);
    -moz-background-size: cover;
    -webkit-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
 }

and then, in your .html (or .php) file call this class like that:

<div class="custom_class">
   ...
</div>

How to edit hosts file via CMD?

echo 0.0.0.0 websitename.com >> %WINDIR%\System32\Drivers\Etc\Hosts

the >> appends the output of echo to the file.

Note that there are two reasons this might not work like you want it to. You may be aware of these, but I mention them just in case.

First, it won't affect a web browser, for example, that already has the current, "real" IP address resolved. So, it won't always take effect right away.

Second, it requires you to add an entry for every host name on a domain; just adding websitename.com will not block www.websitename.com, for example.

Cannot make a static reference to the non-static method

You can either make your variable non static

public final String TTT =  (String) getText(R.string.TTT);

or make the "getText" method static (if at all possible)

SQL NVARCHAR and VARCHAR Limits

The accepted answer helped me but I got tripped up while doing concatenation of varchars involving case statements. I know the OP's question does not involve case statements but I thought this would be helpful to post here for others like me who ended up here while struggling to build long dynamic SQL statements involving case statements.

When using case statements with string concatenation the rules mentioned in the accepted answer apply to each section of the case statement independently.

declare @l_sql varchar(max) = ''

set @l_sql = @l_sql +
case when 1=1 then
    --without this correction the result is truncated
    --CONVERT(VARCHAR(MAX), '')
 +REPLICATE('1', 8000)
 +REPLICATE('1', 8000)
end

print len(@l_sql)

Node.js connect only works on localhost

Fedora or Centos distro check your selinux and firewalld in my case firewalld prevented the connection:

Selinux: $sestatus
SELinux status:                 enabled
SELinuxfs mount:                /sys/fs/selinux
SELinux root directory:         /etc/selinux
Loaded policy name:             targeted
Current mode:                   {{checkmode}}
Mode from config file:          {{checkconfig}}
Policy MLS status:              enabled
Policy deny_unknown status:     allowed
Max kernel policy version:      30

Firewalld status: $systemctl status firewalld

How to choose multiple files using File Upload Control?

        aspx code

            <asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" />
            <asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick ="UploadMultipleFiles" accept ="image/gif, image/jpeg" />
            <hr />
            <asp:Label ID="lblSuccess" runat="server" ForeColor ="Green" />


    Code Behind:

protected void UploadMultipleFiles(object sender, EventArgs e)
{
     foreach (HttpPostedFile postedFile in FileUpload1.PostedFiles)
     {
          string fileName = Path.GetFileName(postedFile.FileName);
          postedFile.SaveAs(Server.MapPath("~/Uploads/") + fileName);
     }
     lblSuccess.Text = string.Format("{0} files have been uploaded successfully.", FileUpload1.PostedFiles.Count);
}

Breaking out of nested loops

for x in xrange(10):
    for y in xrange(10):
        print x*y
        if x*y > 50:
            break
    else:
        continue  # only executed if the inner loop did NOT break
    break  # only executed if the inner loop DID break

The same works for deeper loops:

for x in xrange(10):
    for y in xrange(10):
        for z in xrange(10):
            print x,y,z
            if x*y*z == 30:
                break
        else:
            continue
        break
    else:
        continue
    break

Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails

you can try this exapmple

 START TRANSACTION;
 SET foreign_key_checks = 0;
 ALTER TABLE `job_definers` ADD CONSTRAINT `job_cities_foreign` FOREIGN KEY 
 (`job_cities`) REFERENCES `drop_down_lists`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
 SET foreign_key_checks = 1;
 COMMIT;

Note : if you are using phpmyadmin just uncheck Enable foreign key checks

as example enter image description here

hope this soloution fix your problem :)

What is the easiest way to ignore a JPA field during persistence?

Sometimes you want to:

  1. Serialize a column
  2. Ignore column from being persisted:

Use @Column(name = "columnName", insertable = false, updatable = false)

A good scenario is when a certain column is automatically calculated by using other column values

JavaScript listener, "keypress" doesn't detect backspace?

Try keydown instead of keypress.

The keyboard events occur in this order: keydown, keyup, keypress

The problem with backspace probably is, that the browser will navigate back on keyup and thus your page will not see the keypress event.

How to get current date time in milliseconds in android

Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
int mSec = calendar.get(Calendar.MILLISECOND);

How to unescape HTML character entities in Java?

This did the job for me,

import org.apache.commons.lang.StringEscapeUtils;
...
String decodedXML= StringEscapeUtils.unescapeHtml(encodedXML);

or

import org.apache.commons.lang3.StringEscapeUtils;
...
String decodedXML= StringEscapeUtils.unescapeHtml4(encodedXML);

I guess its always better to use the lang3 for obvious reasons. Hope this helps :)

Can we make unsigned byte in Java

There is no unsigned byte in Java, but if you want to display a byte, you can do,

int myInt = 144;

byte myByte = (byte) myInt;

char myChar = (char) (myByte & 0xFF);

System.out.println("myChar :" + Integer.toHexString(myChar));

Output:

myChar : 90

For more information, please check, How to display a hex/byte value in Java.

How can I turn a JSONArray into a JSONObject?

I have JSONObject like this: {"status":[{"Response":"success"}]}.

If I want to convert the JSONObject value, which is a JSONArray into JSONObject automatically without using any static value, here is the code for that.

JSONArray array=new JSONArray();
JSONObject obj2=new JSONObject();
obj2.put("Response", "success");
array.put(obj2);
JSONObject obj=new JSONObject();
obj.put("status",array);

Converting the JSONArray to JSON Object:

Iterator<String> it=obj.keys();
        while(it.hasNext()){
String keys=it.next();
JSONObject innerJson=new JSONObject(obj.toString());
JSONArray innerArray=innerJson.getJSONArray(keys);
for(int i=0;i<innerArray.length();i++){
JSONObject innInnerObj=innerArray.getJSONObject(i);
Iterator<String> InnerIterator=innInnerObj.keys();
while(InnerIterator.hasNext()){
System.out.println("InnInnerObject value is :"+innInnerObj.get(InnerIterator.next()));


 }
}

Create comma separated strings C#?

You can use the string.Join method to do something like string.Join(",", o.Number, o.Id, o.whatever, ...).

edit: As digEmAll said, string.Join is faster than StringBuilder. They use an external implementation for the string.Join.

Profiling code (of course run in release without debug symbols):

class Program
{
    static void Main(string[] args)
    {
        Stopwatch sw = new Stopwatch();
        string r;
        int iter = 10000;

        string[] values = { "a", "b", "c", "d", "a little bit longer please", "one more time" };

        sw.Restart();
        for (int i = 0; i < iter; i++)
            r = Program.StringJoin(",", values);
        sw.Stop();
        Console.WriteLine("string.Join ({0} times): {1}ms", iter, sw.ElapsedMilliseconds);

        sw.Restart();
        for (int i = 0; i < iter; i++)
            r = Program.StringBuilderAppend(",", values);
        sw.Stop();
        Console.WriteLine("StringBuilder.Append ({0} times): {1}ms", iter, sw.ElapsedMilliseconds);
        Console.ReadLine();
    }

    static string StringJoin(string seperator, params string[] values)
    {
        return string.Join(seperator, values);
    }

    static string StringBuilderAppend(string seperator, params string[] values)
    {
        StringBuilder builder = new StringBuilder();
        builder.Append(values[0]);
        for (int i = 1; i < values.Length; i++)
        {
            builder.Append(seperator);
            builder.Append(values[i]);
        }
        return builder.ToString();
    }
}

string.Join took 2ms on my machine and StringBuilder.Append 5ms. So there is noteworthy difference. Thanks to digAmAll for the hint.

Change collations of all columns of all tables in SQL Server

Following script will work with table schema along with latest Types like (MAX), IMAGE, and etc. change your collation type according to your need on this line (SET @collate = 'DATABASE_DEFAULT';)

SQL SCRIPT HERE:

BEGIN
DECLARE @collate nvarchar(100);
declare @schema nvarchar(255);
DECLARE @table nvarchar(255);
DECLARE @column_name nvarchar(255);
DECLARE @column_id int;
DECLARE @data_type nvarchar(255);
DECLARE @max_length varchar(100);
DECLARE @row_id int;
DECLARE @sql nvarchar(max);
DECLARE @sql_column nvarchar(max);

SET @collate = 'DATABASE_DEFAULT';

DECLARE tbl_cursor CURSOR FOR SELECT (s.[name])schemaName, (o.[name])[tableName]
FROM sysobjects sy 
INNER JOIN sys.objects  o on o.name = sy.name
INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
WHERE OBJECTPROPERTY(sy.id, N'IsUserTable') = 1

OPEN tbl_cursor FETCH NEXT FROM tbl_cursor INTO @schema,@table

WHILE @@FETCH_STATUS = 0
BEGIN
    DECLARE tbl_cursor_changed CURSOR FOR
        SELECT ROW_NUMBER() OVER (ORDER BY c.column_id) AS row_id
            , c.name column_name
            , t.Name data_type
            , c.max_length
            , c.column_id
        FROM sys.columns c
        JOIN sys.types t ON c.system_type_id = t.system_type_id
        LEFT OUTER JOIN sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
        LEFT OUTER JOIN sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
    WHERE c.object_id like OBJECT_ID(@schema+'.'+@table)
    ORDER BY c.column_id


    OPEN tbl_cursor_changed 
     FETCH NEXT FROM tbl_cursor_changed
    INTO @row_id, @column_name, @data_type, @max_length, @column_id



    WHILE @@FETCH_STATUS = 0
    BEGIN
    IF (@max_length = -1) SET @max_length = 'MAX';
        IF (@data_type LIKE '%char%')
        BEGIN TRY
            SET @sql = 'ALTER TABLE ' +@schema+'.'+ @table + ' ALTER COLUMN ' + @column_name + ' ' + @data_type + '(' + CAST(@max_length AS nvarchar(100)) + ') COLLATE ' + @collate
            print @sql
            EXEC sp_executesql @sql
        END TRY
        BEGIN CATCH
          PRINT 'ERROR:'
          PRINT @sql
        END CATCH

        FETCH NEXT FROM tbl_cursor_changed
        INTO @row_id, @column_name, @data_type, @max_length, @column_id

    END

    CLOSE tbl_cursor_changed
    DEALLOCATE tbl_cursor_changed

    FETCH NEXT FROM tbl_cursor
    INTO @schema, @table

END

CLOSE tbl_cursor
DEALLOCATE tbl_cursor

PRINT 'Collation For All Tables Done!'
END

How to use Git Revert

The reason reset and revert tend to come up a lot in the same conversations is because different version control systems use them to mean different things.

In particular, people who are used to SVN or P4 who want to throw away uncommitted changes to a file will often reach for revert before being told that they actually want reset.

Similarly, the revert equivalent in other VCSes is often called rollback or something similar - but "rollback" can also mean "I want to completely discard the last few commits", which is appropriate for reset but not revert. So, there's a lot of confusion where people know what they want to do, but aren't clear on which command they should be using for it.

As for your actual questions about revert...

Okay, you're going to use git revert but how?

git revert first-bad-commit..last-bad-commit

And after running git revert do you have to do something else after? Do you have to commit the changes revert made or does revert directly commit to the repo or what??

By default, git revert prompts you for a commit message and then commits the results. This can be overridden. I quote the man page:

--edit

With this option, git revert will let you edit the commit message prior to committing the revert. This is the default if you run the command from a terminal.

--no-commit

Usually the command automatically creates some commits with commit log messages stating which commits were reverted. This flag applies the changes necessary to revert the named commits to your working tree and the index, but does not make the commits. In addition, when this option is used, your index does not have to match the HEAD commit. The revert is done against the beginning state of your index.

This is useful when reverting more than one commits' effect to your index in a row.

In particular, by default it creates a new commit for each commit you're reverting. You can use revert --no-commit to create changes reverting all of them without committing those changes as individual commits, then commit at your leisure.

Nginx serves .php files as downloads, instead of executing them

The answer above seemed to comment out too much for the solution I reached. This is what my file looked like:

/etc/nginx/sites-available/default

location ~ \.php$ {
# fastcgi_split_path_info ^(.+\.php)(/.+)$;
# # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
#
# # With php5-cgi alone:
# fastcgi_pass 127.0.0.1:9000;
# With php5-fpm:
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}

Hope this helps some folks who are frustrated on a sunday afternoon (c:

How do I run a Python script from C#?

If you're willing to use IronPython, you can execute scripts directly in C#:

using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

private static void doPython()
{
    ScriptEngine engine = Python.CreateEngine();
    engine.ExecuteFile(@"test.py");
}

Get IronPython here.

Angular2 *ngIf check object array length in template

This article helped me alot figuring out why it wasn't working for me either. It give me a lesson to think of the webpage loading and how angular 2 interacts as a timeline and not just the point in time i'm thinking of. I didn't see anyone else mention this point, so I will...

The reason the *ngIf is needed because it will try to check the length of that variable before the rest of the OnInit stuff happens, and throw the "length undefined" error. So thats why you add the ? because it won't exist yet, but it will soon.

Missing Maven dependencies in Eclipse project

For the following steps worked in my case:

1 On eclipse, right click on the desired project Maven -> Disable Maven Nature

2 Right click again then go to Properties. Delete every evidence of external Maven dependency leaving only JRE System Library.

3 Right click one more time on the project then go to Configure -> Convert to Maven Project

How do I define the name of image built with docker-compose

Option 1: Hinting default image name

The name of the image generated by docker-compose depends on the folder name by default but you can override it by using --project-name argument:

$ docker-compose --project-name foo build bar
$ docker images foo_bar

Option 2: Specifying image name

Once docker-compose 1.6.0 is out, you may specify build: and image: to have an explicit image name (see arulraj.net's answer).

Option 3: Create image from container

A third is to create an image from the container:

$ docker-compose up -d bar
$ docker commit $(docker-compose ps -q bar) foo_bar
$ docker-compose rm -f bar

How can I send large messages with Kafka (over 15MB)?

You need to adjust three (or four) properties:

  • Consumer side:fetch.message.max.bytes - this will determine the largest size of a message that can be fetched by the consumer.
  • Broker side: replica.fetch.max.bytes - this will allow for the replicas in the brokers to send messages within the cluster and make sure the messages are replicated correctly. If this is too small, then the message will never be replicated, and therefore, the consumer will never see the message because the message will never be committed (fully replicated).
  • Broker side: message.max.bytes - this is the largest size of the message that can be received by the broker from a producer.
  • Broker side (per topic): max.message.bytes - this is the largest size of the message the broker will allow to be appended to the topic. This size is validated pre-compression. (Defaults to broker's message.max.bytes.)

I found out the hard way about number 2 - you don't get ANY exceptions, messages, or warnings from Kafka, so be sure to consider this when you are sending large messages.

how to sync windows time from a ntp time server in command

Use net time net time \\timesrv /set /yes

after your comment try this one in evelated prompt :

w32tm /config /update /manualpeerlist:yourtimerserver

Android Studio - Failed to notify project evaluation listener error

With the new google support gradle plugin (com.google.gms.google-services) this can be caused by some dependency version problems with your com.google.android.gms.* modules.

You can probably see the root cause by running the build command with the --stacktrace parameter. i.e.:

./gradlew :app:dependencies --stacktrace

which might output the cause of the problem:

Caused by: org.gradle.api.GradleException: The library com.google.android.gms:play-services-measurement-base is being requested by various other libraries at [[15.0.2,15.0.2], [16.0.0,16.0.0]], but resolves to 16.0.0. Disable the plugin and check your dependencies tree using ./gradlew :app:dependencies. at com.google.gms.googleservices.GoogleServicesPlugin$1$_afterResolve_closure1.doCall(GoogleServicesPlugin.groovy:328) at org.gradle.api.internal.ClosureBackedAction.execute(ClosureBackedAction.java:71)

Recover sa password

The best way is to simply reset the password by connecting with a domain/local admin (so you may need help from your system administrators), but this only works if SQL Server was set up to allow local admins (these are now left off the default admin group during setup).

If you can't use this or other existing methods to recover / reset the SA password, some of which are explained here:

Then you could always backup your important databases, uninstall SQL Server, and install a fresh instance.

You can also search for less scrupulous ways to do it (e.g. there are password crackers that I am not enthusiastic about sharing).

As an aside, the login properties for sa would never say Windows Authentication. This is by design as this is a SQL Authentication account. This does not mean that Windows Authentication is disabled at the instance level (in fact it is not possible to do so), it just doesn't apply for a SQL auth account.

I wrote a tip on using PSExec to connect to an instance using the NT AUTHORITY\SYSTEM account (which works < SQL Server 2012), and a follow-up that shows how to hack the SqlWriter service (which can work on more modern versions):

And some other resources:

identifier "string" undefined?

Because string is defined in the namespace std. Replace string with std::string, or add

using std::string;

below your include lines.

It probably works in main.cpp because some other header has this using line in it (or something similar).

Is there a no-duplicate List implementation out there?

Off the top of my head, lists allow duplicates. You could quickly implement a UniqueArrayList and override all the add / insert functions to check for contains() before you call the inherited methods. For personal use, you could only implement the add method you use, and override the others to throw an exception in case future programmers try to use the list in a different manner.

Plot two histograms on single chart with matplotlib

As a completion to Gustavo Bezerra's answer:

If you want each histogram to be normalized (normed for mpl<=2.1 and density for mpl>=3.1) you cannot just use normed/density=True, you need to set the weights for each value instead:

import numpy as np
import matplotlib.pyplot as plt

x = np.random.normal(1, 2, 5000)
y = np.random.normal(-1, 3, 2000)
x_w = np.empty(x.shape)
x_w.fill(1/x.shape[0])
y_w = np.empty(y.shape)
y_w.fill(1/y.shape[0])
bins = np.linspace(-10, 10, 30)

plt.hist([x, y], bins, weights=[x_w, y_w], label=['x', 'y'])
plt.legend(loc='upper right')
plt.show()

enter image description here

As a comparison, the exact same x and y vectors with default weights and density=True:

enter image description here

Postgresql Select rows where column = array

For dynamic SQL use:

'IN(' ||array_to_string(some_array, ',')||')'

Example

DO LANGUAGE PLPGSQL $$

DECLARE
    some_array bigint[];
    sql_statement text;

BEGIN

    SELECT array[1, 2] INTO some_array;
    RAISE NOTICE '%', some_array;

    sql_statement := 'SELECT * FROM my_table WHERE my_column IN(' ||array_to_string(some_array, ',')||')';
    RAISE NOTICE '%', sql_statement;

END;

$$;

Result: NOTICE: {1,2} NOTICE: SELECT * FROM my_table WHERE my_column IN(1,2)

How to change border color of textarea on :focus

.input:focus {
    outline: none !important;
    border:1px solid red;
    box-shadow: 0 0 10px #719ECE;
}

How to read file using NPOI

If you don't want to use NPOI.Mapper, then I'd advise you to check out this solution - it handles reading excel cell into various type and also has a simple import helper: https://github.com/hidegh/NPOI.Extensions

var data = sheet.MapTo<OrderDetails>(true, rowMapper =>
{
  // map singleItem
  return new OrderDetails()
  {
    Date = rowMapper.GetValue<DateTime>(SheetColumnTitles.Date),

    // use reusable mapper for re-curring scenarios
    Region = regionMapper(rowMapper.GetValue<string>(SheetColumnTitles.Region)),

    Representative = rowMapper.GetValue<string>(SheetColumnTitles.Representative),
    Item = rowMapper.GetValue<string>(SheetColumnTitles.Item),
    Units = rowMapper.GetValue<int>(SheetColumnTitles.Units),
    UnitCost = rowMapper.GetValue<decimal>(SheetColumnTitles.UnitCost),
    Total = rowMapper.GetValue<decimal>(SheetColumnTitles.Total),

    // read date and total as string, as they're displayed/formatted on the excel
    DateFormatted = rowMapper.GetValue<string>(SheetColumnTitles.Date),
    TotalFormatted = rowMapper.GetValue<string>(SheetColumnTitles.Total)
  };
});

Run bash script as daemon

A Daemon is just program that runs as a background process, rather than being under the direct control of an interactive user...

[The below bash code is for Debian systems - Ubuntu, Linux Mint distros and so on]

The simple way:

The simple way would be to edit your /etc/rc.local file and then just have your script run from there (i.e. everytime you boot up the system):

sudo nano /etc/rc.local

Add the following and save:

#For a BASH script
/bin/sh TheNameOfYourScript.sh > /dev/null &

The better way to do this would be to create a Daemon via Upstart:

sudo nano /etc/init/TheNameOfYourDaemon.conf

add the following:

description "My Daemon Job"
author "Your Name"
start on runlevel [2345]    

pre-start script
  echo "[`date`] My Daemon Starting" >> /var/log/TheNameOfYourDaemonJobLog.log
end script

exec /bin/sh TheNameOfYourScript.sh > /dev/null &

Save this.

Confirm that it looks ok:

init-checkconf /etc/init/TheNameOfYourDaemon.conf

Now reboot the machine:

sudo reboot

Now when you boot up your system, you can see the log file stating that your Daemon is running:

cat  /var/log/TheNameOfYourDaemonJobLog.log

• Now you may start/stop/restart/get the status of your Daemon via:

restart: this will stop, then start a service

sudo service TheNameOfYourDaemonrestart restart

start: this will start a service, if it's not running

sudo service TheNameOfYourDaemonstart start

stop: this will stop a service, if it's running

sudo service TheNameOfYourDaemonstop stop

status: this will display the status of a service

sudo service TheNameOfYourDaemonstatus status

Oracle: How to filter by date and time in a where clause

In the example that you have provided there is nothing that would throw a SQL command not properly formed error. How are you executing this query? What are you not showing us?

This example script works fine:

create table tableName
(session_start_date_time DATE);

insert into tableName (session_start_date_time) 
values (sysdate+1);

select * from tableName
where session_start_date_time > to_date('12-Jan-2012 16:00', 'DD-MON-YYYY hh24:mi');

As does this example:

create table tableName2
(session_start_date_time TIMESTAMP);

insert into tableName2 (session_start_date_time) 
values (to_timestamp('01/12/2012 16:01:02.345678','mm/dd/yyyy hh24:mi:ss.ff'));

select * from tableName2
where session_start_date_time > to_date('12-Jan-2012 16:00', 'DD-MON-YYYY hh24:mi');

select * from tableName2
where session_start_date_time > to_timestamp('01/12/2012 14:01:02.345678','mm/dd/yyyy hh24:mi:ss.ff');

So there must be something else that is wrong.

What does the 'static' keyword do in a class?

The static keyword means that something (a field, method or nested class) is related to the type rather than any particular instance of the type. So for example, one calls Math.sin(...) without any instance of the Math class, and indeed you can't create an instance of the Math class.

For more information, see the relevant bit of Oracle's Java Tutorial.


Sidenote

Java unfortunately allows you to access static members as if they were instance members, e.g.

// Bad code!
Thread.currentThread().sleep(5000);
someOtherThread.sleep(5000);

That makes it look as if sleep is an instance method, but it's actually a static method - it always makes the current thread sleep. It's better practice to make this clear in the calling code:

// Clearer
Thread.sleep(5000);

How to generate xsd from wsdl

(WHEN .wsdl is referring to .xsd/schemas using import) If you're using the WMB Tooklit (v8.0.0.4 WMB) then you can find .xsd using following steps :

Create library (optional) > Right Click , New Message Model File > Select SOAP XML > Choose Option 'I already have WSDL for my data' > 'Select file outside workspace' > 'Select the WSDL bindings to Import' (if there are multiple) > Finish.

This will give you the .xsd and .wsdl files in your Workspace (Application Perspective).

Is there a “not in” operator in JavaScript for checking object properties?

As already said by Jordão, just negate it:

if (!(id in tutorTimes)) { ... }

Note: The above test if tutorTimes has a property with the name specified in id, anywhere in the prototype chain. For example "valueOf" in tutorTimes returns true because it is defined in Object.prototype.

If you want to test if a property doesn't exist in the current object, use hasOwnProperty:

if (!tutorTimes.hasOwnProperty(id)) { ... }

Or if you might have a key that is hasOwnPropery you can use this:

if (!Object.prototype.hasOwnProperty.call(tutorTimes,id)) { ... }

Passing multiple variables to another page in url

Pretty simple but another said you dont pass session variables through the url bar 1.You dont need to because a session is passed throughout the whole website from header when you put in header file 2.security risks
Here is first page code

$url = "http://localhost/main.php?email=" . urlencode($email_address) . "&eventid=" . urlencode($event_id);

2nd page when getting the variables from the url bar is:

if(isset($_GET['email']) && !empty($_GET['email']) AND isset($_GET['eventid']) && !empty($_GET['eventid'])){ ////do whatever here }

Now if you want to do it the proper way of using the session you created then ignore my above code and call the session variables on the second page for instance create a session on the first page lets say for example:

 $_SESSION['WEB_SES'] = $email_address . "^" . $event_id;

obvious that you would have already assigned values to the session variables in the code above, you can call the session name whatever you want to i just used the example web_ses , the second page all you need to do is start a session and see if the session is there and check the variables and do whatever with them, example:

 session_start();
 if (isset($_SESSION['WEB_SES'])){
 $Array = explode("^", $_SESSION['WEB_SES']);
 $email = $Array[0];
 $event_id = $Array[1]
 echo "$email";
 echo "$event_id";
 }

Like I said before the good thing about sessions are they can be carried throughout the entire website if this type of code in put in the header file that gets called upon on all pages that load, you can simple use the variable wherever and whenever. Hope this helps :)

I cannot access tomcat admin console?

If you are running tomcat from eclipse (probably problem exists with another IDEs), it could have a different configuration- not based on files .

The solution is to edit tomcat users file, as you wrote, and then start tomcat from command prompt with

{tomcat-directory}/bin/startup

How do I escape ampersands in XML so they are rendered as entities in HTML?

When your XML contains &amp;amp;, this will result in the text &amp;.

When you use that in HTML, that will be rendered as &.

How to change my Git username in terminal?

there are 3 ways we can fix this issue

method-1 (command line)

To set your account's default identity globally run below commands

git config --global user.email "[email protected]"
git config --global user.name "Your Name"
git config --global user.password "your password"

To set the identity only in current repository , remove --global and run below commands in your Project/Repo root directory

git config user.email "[email protected]"
git config user.name "Your Name"
git config user.password "your password"

Example:

email -> organization email Id
name  -> mostly <employee Id> or <FirstName, LastName> 

**Note: ** you can check these values in your GitHub profile or Bitbucket profile

method-2 (.gitconfig)

create a .gitconfig file in your home folder if it doesn't exist. and paste the following lines in .gitconfig

[user]
    name = FirstName, LastName
    email = [email protected]
[http]
    sslVerify = false
    proxy = 
[https]
    sslverify = false
    proxy = https://corp\\<uname>:<password>@<proxyhost>:<proxy-port>
[push]
    default = simple
[credential]
    helper = cache --timeout=360000000
[core]
    autocrlf = false

Note: you can remove the proxy lines from the above , if you are not behind the proxy

Home directory to create .gitconfig file:

windows : c/users/< username or empID >

Mac or Linux : run this command to go to home directory cd ~

or simply run the following commands one after the other

git config --global --edit
git commit --amend --reset-author

method-3 (git credential pop up)

windows :

Control Panel >> User Account >> Credential Manager >> Windows Credential >> Generic Credential 
>> look for any github cert/credential and delete it.

then running any git command will prompt to enter new user name and password.

Mac :

command+space >> search for "keychain Access" and click ok >> 
search for any certificate/file with gitHub >> delete it.

then running any git command will prompt to enter new user name and password.

WSDL vs REST Pros and Cons

SOAP: It can be transported via SMTP also, means we can invoke the service using Email simple text format also

It needs additional framework/engine should be in web service consumer machine to convert SOAP message to respective objects structure in various languages.

REST: Now WSDL2.0 supports to describe REST web service also

We can use when you want to make your service as lightweight, example calling from mobile devices like cell phone, pda etc...

Remove all constraints affecting a UIView

I use the following method to remove all constraints from a view:

.h file:

+ (void)RemoveContraintsFromView:(UIView*)view 
    removeParentConstraints:(bool)parent 
    removeChildConstraints:(bool)child;

.m file:

+ (void)RemoveContraintsFromView:(UIView *)view 
    removeParentConstraints:(bool)parent 
    removeChildConstraints:(bool)child
{
    if (parent) {
        // Remove constraints between view and its parent.
        UIView *superview = view.superview;
        [view removeFromSuperview];
        [superview addSubview:view];
    }

    if (child) {
        // Remove constraints between view and its children.
        [view removeConstraints:[view constraints]];
    }
}

You can also read this post on my blog to better understand how it works behind the hood.

If you need more granular control, I'd strongly advise switching to Masonry, a powerful framework class you could use whenever you need to properly handle constraints programmatically.

jQuery .slideRight effect

If you're willing to include the jQuery UI library, in addition to jQuery itself, then you can simply use hide(), with additional arguments, as follows:

$(document).ready(
    function(){
        $('#slider').click(
            function(){
                $(this).hide('slide',{direction:'right'},1000);

            });
    });

JS Fiddle demo.


Without using jQuery UI, you could achieve your aim just using animate():

$(document).ready(
    function(){
        $('#slider').click(
            function(){
                $(this)
                    .animate(
                        {
                            'margin-left':'1000px'
                            // to move it towards the right and, probably, off-screen.
                        },1000,
                        function(){
                            $(this).slideUp('fast');
                            // once it's finished moving to the right, just 
                            // removes the the element from the display, you could use
                            // `remove()` instead, or whatever.
                        }
                        );

            });
    });

JS Fiddle demo

If you do choose to use jQuery UI, then I'd recommend linking to the Google-hosted code, at: https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js

How to set custom ActionBar color / style?

For Android 3.0 and higher only

When supporting Android 3.0 and higher only, you can define the action bar's background like this:

res/values/themes.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- the theme applied to the application or activity -->
    <style name="CustomActionBarTheme" parent="@style/Theme.Holo.Light.DarkActionBar">
       <item name="android:actionBarStyle">@style/MyActionBar</item>
    </style>

<!-- ActionBar styles -->
  <style name="MyActionBar" parent="@style/Widget.Holo.Light.ActionBar.Solid.Inverse">
       <item name="android:background">#ff0000</item>
  </style>
</resources>

For Android 2.1 and higher

When using the Support Library, your style XML file might look like this:

<?xml version="1.0" encoding="utf-8"?>
  <resources>
  <!-- the theme applied to the application or activity -->
 <style name="CustomActionBarTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
    <item name="android:actionBarStyle">@style/MyActionBar</item>

    <!-- Support library compatibility -->
    <item name="actionBarStyle">@style/MyActionBar</item>
</style>

<!-- ActionBar styles -->
<style name="MyActionBar"
       parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
    <item name="android:background">@drawable/actionbar_background</item>

    <!-- Support library compatibility -->
    <item name="background">@drawable/actionbar_background</item>
  </style>
 </resources>

Then apply your theme to your entire app or individual activities:

for more details Documentaion

What does "while True" mean in Python?

Formally, True is a Python built-in constant of bool type.

You can use Boolean operations on bool types (at the interactive python prompt for example) and convert numbers into bool types:

>>> print not True
False
>>> print not False
True
>>> print True or False
True
>>> print True and False
False
>>> a=bool(9)
>>> print a
True
>>> b=bool(0)
>>> print b
False
>>> b=bool(0.000000000000000000000000000000000001)
>>> print b
True

And there are "gotcha's" potentially with what you see and what the Python compiler sees:

>>> n=0
>>> print bool(n)
False
>>> n='0'
>>> print bool(n)
True
>>> n=0.0
>>> print bool(n)
False
>>> n="0.0"
>>> print bool(n)
True

As a hint of how Python stores bool types internally, you can cast bool types to integers and True will come out to be 1 and False 0:

>>> print True+0
1
>>> print True+1
2
>>> print False+0
0
>>> print False+1
1

In fact, Python bool type is a subclass of Python's int type:

>>> type(True)
<type 'bool'>
>>> isinstance(True, int)
True

The more important part of your question is "What is while True?" is 'what is True', and an important corollary: What is false?

First, for every language you are learning, learn what the language considers 'truthy' and 'falsey'. Python considers Truth slightly differently than Perl Truth for example. Other languages have slightly different concepts of true / false. Know what your language considers to be True and False for different operations and flow control to avoid many headaches later!

There are many algorithms where you want to process something until you find what you are looking for. Hence the infinite loop or indefinite loop. Each language tend to have its own idiom for these constructs. Here are common C infinite loops, which also work for Perl:

for(;;) { /* loop until break */ }

/* or */

while (1) {
   return if (function(arg) > 3);
}

The while True: form is common in Python for indefinite loops with some way of breaking out of the loop. Learn Python flow control to understand how you break out of while True loops. Unlike most languages, for example, Python can have an else clause on a loop. There is an example in the last link.

Where is a log file with logs from a container?

To see how much space each container's log is taking up, use this:

docker ps -qa | xargs docker inspect --format='{{.LogPath}}' | xargs ls -hl

(you might need a sudo before ls).

To add server using sp_addlinkedserver

I had the same issue to connect an SQL_server 2008 to an SQL_server 2016 hosted in a remote server. @Domnic answer didn't worked for me straightforward. I write my tweaked solution here as I think it may be useful for someone else.

An extended answer for remote IP db connections:

Step 1: Link servers

EXEC sp_addlinkedserver @server='SRV_NAME',
   @srvproduct=N'',
   @provider=N'SQLNCLI',   
   @datasrc=N'aaa.bbb.ccc.ddd';

EXEC sp_addlinkedsrvlogin 'SRV_NAME', 'false', NULL, 'your_remote_db_login_user', 'your_remote_db_login_password'

...where SRV_NAME is an invented name. We will use it to refer to the remote server from our queries. aaa.bbb.ccc.ddd is the ip address of the remote server hosting your SQLserver DB.

Step 2: Run your queries For instance:

SELECT * FROM [SRV_NAME].your_remote_db_name.dbo.your_table

...and that's it!

Syntax details: sp_addlinkedserver and sp_addlinkedsrvlogin

How do I send email with JavaScript without opening the mail client?

Well, PHP can do this easily.

It can be done with the PHP mail() function. Here's what a simple function would look like:

<?php     
$to_email = '[email protected]';
$subject = 'Testing PHP Mail';
$message = 'This mail is sent using the PHP mail function';
$headers = 'From: [email protected]';
mail($to_email,$subject,$message,$headers);
?>

This will send a background e-mail to the recipient specified in the $to_email.

The above example uses hard coded values in the source code for the email address and other details for simplicity.

Let’s assume you have to create a contact us form for users fill in the details and then submit.

  1. Users can accidently or intentional inject code in the headers which can result in sending spam mail
  2. To protect your system from such attacks, you can create a custom function that sanitizes and validates the values before the mail is sent.

Let’s create a custom function that validates and sanitizes the email address using the filter_var() built in function.

Here's an example code:

<?php 
function sanitize_my_email($field) {
    $field = filter_var($field, FILTER_SANITIZE_EMAIL);
    if (filter_var($field, FILTER_VALIDATE_EMAIL)) {
        return true;
    } else {
        return false;
    }
}
$to_email = '[email protected]';
$subject = 'Testing PHP Mail';
$message = 'This mail is sent using the PHP mail ';
$headers = 'From: [email protected]';
//check if the email address is invalid $secure_check
$secure_check = sanitize_my_email($to_email);
if ($secure_check == false) {
    echo "Invalid input";
} else { //send email 
    mail($to_email, $subject, $message, $headers);
    echo "This email is sent using PHP Mail";
}
?>

We will now let this be a separate PHP file, for example sendmail.php.

Then, will use this file on form submission, using the action attribute of the form, like:

<form action="sendmail.php" method="post">
   <input type="text" value="Your Name: ">
   <input type="password" value="Set Up A Passworrd">
   <input type="submit" value="Signup">
   <input type="reset" value="Reset Form">
</form>

Hope I could help

Convert JSON String To C# Object

You probably don't want to just declare routes_list as an object type. It doesn't have a .test property, so you really aren't going to get a nice object back. This is one of those places where you would be better off defining a class or a struct, or make use of the dynamic keyword.

If you really want this code to work as you have it, you'll need to know that the object returned by DeserializeObject is a generic dictionary of string,object. Here's the code to do it that way:

var json_serializer = new JavaScriptSerializer();
var routes_list = (IDictionary<string, object>)json_serializer.DeserializeObject("{ \"test\":\"some data\" }");
Console.WriteLine(routes_list["test"]);

If you want to use the dynamic keyword, you can read how here.

If you declare a class or struct, you can call Deserialize instead of DeserializeObject like so:

class MyProgram {
    struct MyObj {
        public string test { get; set; }
    }

    static void Main(string[] args) {
        var json_serializer = new JavaScriptSerializer();
        MyObj routes_list = json_serializer.Deserialize<MyObj>("{ \"test\":\"some data\" }");
        Console.WriteLine(routes_list.test);

        Console.WriteLine("Done...");
        Console.ReadKey(true);
    }
}

Installation error: INSTALL_FAILED_OLDER_SDK

Ionic Android emulator error INSTALL_FAILED_OLDER_SDK

So, basically it means that the installation has failed due to having an older SDK version than the targetSdkVersion specified in your app (it's a Gradle issue). Just edit the AndroidManifest.xml file and add the following code:

_x000D_
_x000D_
<uses-sdk android:minSdkVersion="19" android:targetSdkVersion="14"/>
_x000D_
_x000D_
_x000D_

After days looking for the solution, that's it.

Works fine for me!

Cannot declare instance members in a static class in C#

I know this post is old but...

I was able to do this, my problem was that I forgot to make my property static.

public static class MyStaticClass
{
    private static NonStaticObject _myObject = new NonStaticObject();

    //property
    public static NonStaticObject MyObject
    {
        get { return _myObject; }
        set { _myObject = value; }
    }
}

How often should you use git-gc?

Drop it in a cron job that runs every night (afternoon?) when you're sleeping.

Get current application physical path within Application_Start

There is also the static HostingEnvironment.MapPath

Select all where [first letter starts with B]

SELECT author FROM lyrics WHERE author LIKE 'B%';

Make sure you have an index on author, though!

How can I make XSLT work in chrome?

The problem based on Chrome is not about the xml namespace which is xmlns="http://www.w3.org/1999/xhtml". Without the namesspace attribute, it won't work with IE either.

Because of the security restriction, you have to add the --allow-file-access-from-files flag when you start the chrome. I think linux/*nix users can do that easily via the terminal but for windows users, you have to open the properties of the Chrome shortcut and add it in the target destination as below;

Right-Click -> Properties -> Target

enter image description here

Here is a sample full path with the flags which I use on my machine;

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files

I hope showing this step-by-step will help windows users for the problem, this is why I've added this post.

How can I stop a running MySQL query?

Use mysqladmin to kill the runaway query:

Run the following commands:

mysqladmin -uusername -ppassword pr

Then note down the process id.

mysqladmin -uusername -ppassword kill pid

The runaway query should no longer be consuming resources.

Change background color on mouseover and remove it after mouseout

HTML:

<div id="id">
</div>
<div id="hiddenDiv" style="display:none;"></div>

jQuery:

$('#id').hover(function(){
    $("#hiddenDiv").css('display','block');
  },
  function(){
    $("#hiddenDiv").css('display','none');
  }
);

Must JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards?

Doesn't matter if Connection is poolable or not. Even poolable connection has to clean before returning to the pool.

"Clean" usually means closing resultsets & rolling back any pending transactions but not closing the connection. Otherwise pooling looses its sense.

How to determine the current iPhone/device model?

There are some problems with the accepted answer when you're using Swift 3! This answer (inspired from NAZIK) works with Swift 3 and the new iPhone models:

import UIKit


public extension UIDevice {
var modelName: String {
    #if (arch(i386) || arch(x86_64)) && os(iOS)
        let DEVICE_IS_SIMULATOR = true
    #else
        let DEVICE_IS_SIMULATOR = false
    #endif

    var machineString = String()

    if DEVICE_IS_SIMULATOR == true
    {
        if let dir = ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] {
            machineString = dir
        }
    }
    else {
        var systemInfo = utsname()
        uname(&systemInfo)
        let machineMirror = Mirror(reflecting: systemInfo.machine)
        machineString = machineMirror.children.reduce("") { identifier, element in
            guard let value = element.value as? Int8 , value != 0 else { return identifier }
            return identifier + String(UnicodeScalar(UInt8(value)))
        }
    }
    switch machineString {
    case "iPod4,1":                                 return "iPod Touch 4G"
    case "iPod5,1":                                 return "iPod Touch 5G"
    case "iPod7,1":                                 return "iPod Touch 6G"
    case "iPhone3,1", "iPhone3,2", "iPhone3,3":     return "iPhone 4"
    case "iPhone4,1":                               return "iPhone 4s"
    case "iPhone5,1", "iPhone5,2":                  return "iPhone 5"
    case "iPhone5,3", "iPhone5,4":                  return "iPhone 5c"
    case "iPhone6,1", "iPhone6,2":                  return "iPhone 5s"
    case "iPhone7,2":                               return "iPhone 6"
    case "iPhone7,1":                               return "iPhone 6 Plus"
    case "iPhone8,1":                               return "iPhone 6s"
    case "iPhone8,2":                               return "iPhone 6s Plus"
    case "iPhone8,4":                               return "iPhone SE"
    case "iPhone9,1", "iPhone9,3":                  return "iPhone 7"
    case "iPhone9,2", "iPhone 9,4":                 return "iPhone 7 Plus"
    case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
    case "iPad3,1", "iPad3,2", "iPad3,3":           return "iPad 3"
    case "iPad3,4", "iPad3,5", "iPad3,6":           return "iPad 4"
    case "iPad4,1", "iPad4,2", "iPad4,3":           return "iPad Air"
    case "iPad5,3", "iPad5,4":                      return "iPad Air 2"
    case "iPad2,5", "iPad2,6", "iPad2,7":           return "iPad Mini"
    case "iPad4,4", "iPad4,5", "iPad4,6":           return "iPad Mini 2"
    case "iPad4,7", "iPad4,8", "iPad4,9":           return "iPad Mini 3"
    case "iPad5,1", "iPad5,2":                      return "iPad Mini 4"
    case "iPad6,3", "iPad6,4":                      return "iPad Pro (9.7 inch)"
    case "iPad6,7", "iPad6,8":                      return "iPad Pro (12.9 inch)"
    case "AppleTV5,3":                              return "Apple TV"
    default:                                        return machineString
    }
}
}

Check if user is using IE

I just wanted to check if the browser was IE11 or older, because well, they're crap.

function isCrappyIE() {
    var ua = window.navigator.userAgent;
    var crappyIE = false;
    var msie = ua.indexOf('MSIE ');
    if (msie > 0) {// IE 10 or older => return version number        
        crappyIE = true;
    }
    var trident = ua.indexOf('Trident/');
    if (trident > 0) {// IE 11 => return version number        
        crappyIE = true;
    }
    return crappyIE;
}   

if(!isCrappyIE()){console.table('not a crappy browser);}

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse

In the project into the folder Libraries-->right click --> Add Library --> Mysqlconnector 5.1

Which selector do I need to select an option by its text?

You can use the :contains() selector to select elements that contain specific text.
For example:

$('#mySelect option:contains(abc)')

To check whether a given <select> element has such an option, use the .has() method:

if (mySelect.has('option:contains(abc)').length)

To find all <select>s that contain such an option, use the :has() selector:

$('select:has(option:contains(abc))')