Programs & Examples On #Scala collections

Collection library for Scala Programming Language

Is the Scala 2.8 collections library a case of "the longest suicide note in history"?

Is this going to put people off coming to Scala?

Yes, but it will also prevent people from being put off. I've considered the lack of collections that use higher-kinded types to be a major weakness ever since Scala gained support for higher-kinded types. It make the API docs more complicated, but it really makes usage more natural.

Is this going to give scala a bad name in the commercial world as an academic plaything that only dedicated PhD students can understand? Are CTOs and heads of software going to get scared off?

Some probably will. I don't think Scala is accessible to many "professional" developers, partially due to the complexity of Scala and partly due to the unwillingness of many developers to learn. The CTOs who employ such developers will rightly be scared off.

Was the library re-design a sensible idea?

Absolutely. It makes collections fit much better with the rest of the language and the type system, even if it still has some rough edges.

If you're using scala commercially, are you worried about this? Are you planning to adopt 2.8 immediately or wait to see what happens?

I'm not using it commercially. I'll probably wait until at least a couple revs into the 2.8.x series before even trying to introduce it so that the bugs can be flushed out. I'll also wait to see how much success EPFL has in improving its development a release processes. What I'm seeing looks hopeful, but I work for a conservative company.

One the more general topic of "is Scala too complicated for mainstream developers?"...

Most developers, mainstream or otherwise, are maintaining or extending existing systems. This means that most of what they use is dictated by decisions made long ago. There are still plenty of people writing COBOL.

Tomorrow's mainstream developer will work maintaining and extending the applications that are being built today. Many of these applications are not being built by mainstream developers. Tomorrow's mainstream developers will use the language that is being used by today's most successful developers of new applications.

How to read files from resources folder in Scala?

The required file can be accessed as below from resource folder in scala

val file = scala.io.Source.fromFile(s"src/main/resources/app.config").getLines().mkString

Scala best way of turning a Collection into a Map-by-key?

Scala 2.13+

instead of "breakOut"

c.map(t => (t.getP, t)).to(Mat)

Scroll to "View": https://www.scala-lang.org/blog/2017/02/28/collections-rework.html

Using a string variable as a variable name

You can use setattr

name  = 'varname'
value = 'something'

setattr(self, name, value) #equivalent to: self.varname= 'something'

print (self.varname)
#will print 'something'

But, since you should inform an object to receive the new variable, this only works inside classes or modules.

How to enable or disable an anchor using jQuery?

$("a").click(function(){
                alert('disabled');
                return false;

}); 

SVG gradient using CSS

Building on top of what Finesse wrote, here is a simpler way to target the svg and change it's gradient.

This is what you need to do:

  1. Assign classes to each color stop defined in the gradient element.
  2. Target the css and change the stop-color for each of those stops using plain classes.
  3. Win!

Some benefits of using classes instead of :nth-child is that it'll not be affected if you reorder your stops. Also, it makes the intent of each class clear - you'll be left wondering whether you needed a blue color on the first child or the second one.

I've tested it on all Chrome, Firefox and IE11:

_x000D_
_x000D_
.main-stop {_x000D_
  stop-color: red;_x000D_
}_x000D_
.alt-stop {_x000D_
  stop-color: green;_x000D_
}
_x000D_
<svg class="green" width="100" height="50" version="1.1" xmlns="http://www.w3.org/2000/svg">_x000D_
  <linearGradient id="gradient">_x000D_
    <stop class="main-stop" offset="0%" />_x000D_
    <stop class="alt-stop" offset="100%" />_x000D_
  </linearGradient>_x000D_
  <rect width="100" height="50" fill="url(#gradient)" />_x000D_
</svg>
_x000D_
_x000D_
_x000D_

See an editable example here: https://jsbin.com/gabuvisuhe/edit?html,css,output

Query EC2 tags from within instance

Jq + ec2metadata makes it a little nicer. I'm using cf and have access to the region. Otherwise you can grab it in bash.

aws ec2 describe-tags --region $REGION \
--filters "Name=resource-id,Values=`ec2metadata --instance-id`" | jq --raw-output \
'.Tags[] | select(.Key=="TAG_NAME") | .Value'

No jq.

aws ec2 describe-tags --region us-west-2 \
--filters "Name=resource-id,Values=`ec2-metadata --instance-id | cut -d " " -f 2`" \
--query 'Tags[?Key==`Name`].Value' \
--output text

How to get the path of current worksheet in VBA?

If you want to get the path of the workbook from where the macro is being executed - use Application.ThisWorkbook.Path.
Application.ActiveWorkbook.Path can sometimes produce unexpected results (e.g. if your macro switches between multiple workbooks).

Force the origin to start at 0

Simply add these to your ggplot:

+ scale_x_continuous(expand = c(0, 0), limits = c(0, NA)) + 
  scale_y_continuous(expand = c(0, 0), limits = c(0, NA))

Example

df <- data.frame(x = 1:5, y = 1:5)
p <- ggplot(df, aes(x, y)) + geom_point()
p <- p + expand_limits(x = 0, y = 0)
p # not what you are looking for


p + scale_x_continuous(expand = c(0, 0), limits = c(0,NA)) + 
  scale_y_continuous(expand = c(0, 0), limits = c(0, NA))

enter image description here

Lastly, take great care not to unintentionally exclude data off your chart. For example, a position = 'dodge' could cause a bar to get left off the chart entirely (e.g. if its value is zero and you start the axis at zero), so you may not see it and may not even know it's there. I recommend plotting data in full first, inspect, then use the above tip to improve the plot's aesthetics.

Collection was modified; enumeration operation may not execute in ArrayList

I agree with several of the points I've read in this post and I've incorporated them into my solution to solve the exact same issue as the original posting.

That said, the comments I appreciated are:

  • "unless you are using .NET 1.0 or 1.1, use List<T> instead of ArrayList. "

  • "Also, add the item(s) to be deleted to a new list. Then go through and delete those items." .. in my case I just created a new List and the populated it with the valid data values.

e.g.

private List<string> managedLocationIDList = new List<string>();
string managedLocationIDs = ";1321;1235;;" // user input, should be semicolon seperated list of values

managedLocationIDList.AddRange(managedLocationIDs.Split(new char[] { ';' }));
List<string> checkLocationIDs = new List<string>();

// Remove any duplicate ID's and cleanup the string holding the list if ID's
Functions helper = new Functions();
checkLocationIDs = helper.ParseList(managedLocationIDList);

...
public List<string> ParseList(List<string> checkList)
{
    List<string> verifiedList = new List<string>();

    foreach (string listItem in checkList)
    if (!verifiedList.Contains(listItem.Trim()) && listItem != string.Empty)
        verifiedList.Add(listItem.Trim());

    verifiedList.Sort();
    return verifiedList;
}        

Angularjs simple file download causes router to redirect

in template

<md-button class="md-fab md-mini md-warn md-ink-ripple" ng-click="export()" aria-label="Export">
<md-icon class="material-icons" alt="Export" title="Export" aria-label="Export">
    system_update_alt
</md-icon></md-button>

in controller

     $scope.export = function(){ $window.location.href = $scope.export; };

Automatic exit from Bash shell script on error

An alternative to the accepted answer that fits in the first line:

#!/bin/bash -e

cd some_dir  

./configure --some-flags  

make  

make install

Can I use return value of INSERT...RETURNING in another INSERT?

The best practice for this situation. Use RETURNING … INTO.

INSERT INTO teams VALUES (...) RETURNING id INTO last_id;

Note this is for PLPGSQL

React Native: Possible unhandled promise rejection

catch function in your api should either return some data which could be handled by Api call in React class or throw new error which should be caught using a catch function in your React class code. Latter approach should be something like:

return fetch(url)
.then(function(response){
  return response.json();
})
.then(function(json){
  return {
    city: json.name,
    temperature: kelvinToF(json.main.temp),
    description: _.capitalize(json.weather[0].description)
  }
})
.catch(function(error) {
console.log('There has been a problem with your fetch operation: ' + error.message);
 // ADD THIS THROW error
  throw error;
});

Then in your React Class:

Api(region.latitude, region.longitude)
  .then((data) => {
    console.log(data);
    this.setState(data);
  }).catch((error)=>{
     console.log("Api call error");
     alert(error.message);
  });

Swift apply .uppercaseString to only the first letter of a string

Here's the way I did it in small steps, its similar to @Kirsteins.

func capitalizedPhrase(phrase:String) -> String {
    let firstCharIndex = advance(phrase.startIndex, 1)
    let firstChar = phrase.substringToIndex(firstCharIndex).uppercaseString
    let firstCharRange = phrase.startIndex..<firstCharIndex
    return phrase.stringByReplacingCharactersInRange(firstCharRange, withString: firstChar)
}

Cannot construct instance of - Jackson

In your concrete example the problem is that you don't use this construct correctly:

@JsonSubTypes({ @JsonSubTypes.Type(value = MyAbstractClass.class, name = "MyAbstractClass") })

@JsonSubTypes.Type should contain the actual non-abstract subtypes of your abstract class.

Therefore if you have:

abstract class Parent and the concrete subclasses

Ch1 extends Parent and Ch2 extends Parent

Then your annotation should look like:

@JsonSubTypes({ 
          @JsonSubTypes.Type(value = Ch1.class, name = "ch1"),
          @JsonSubTypes.Type(value = Ch2.class, name = "ch2")
})

Here name should match the value of your 'discriminator':

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, 
include = JsonTypeInfo.As.WRAPPER_OBJECT, 
property = "type")

in the property field, here it is equal to type. So type will be the key and the value you set in name will be the value.

Therefore, when the json string comes if it has this form:

{
 "type": "ch1",
 "other":"fields"
}

Jackson will automatically convert this to a Ch1 class.

If you send this:

{
 "type": "ch2",
 "other":"fields"
}

You would get a Ch2 instance.

Writing numerical values on the plot with Matplotlib

You can use the annotate command to place text annotations at any x and y values you want. To place them exactly at the data points you could do this

import numpy
from matplotlib import pyplot

x = numpy.arange(10)
y = numpy.array([5,3,4,2,7,5,4,6,3,2])

fig = pyplot.figure()
ax = fig.add_subplot(111)
ax.set_ylim(0,10)
pyplot.plot(x,y)
for i,j in zip(x,y):
    ax.annotate(str(j),xy=(i,j))

pyplot.show()

If you want the annotations offset a little, you could change the annotate line to something like

ax.annotate(str(j),xy=(i,j+0.5))

Pass C# ASP.NET array to Javascript array

This is to supplement zerkms's answer.

To pass data across language barriers, you would need a way to represent the data as a string by serializing the data. One of the serialization methods for JavaScript is JSON. In zerkms's example, the code would be placed inside of an aspx page. To combine his example and yours together on one aspx page, you would have,

<%
    int[] numbers = new int[5];
    // Fill up numbers...

    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
%>

somewhere later on the aspx page

<script type="text/javascript">
    var jsVariable = <%= serializer.Serialize(numbers) %>;
</script>

This answer though, assumes that you are generating JavaScript from the initial page load. As per the comments in your post, this could have been done via AJAX. In that case, you would have the server respond with the result of the serialization and then deserialize it in JavaScript using your favorite framework.

Note: Also do not mark this as an answer since I wanted the syntax highlighting to make another answer more clear.

How to map with index in Ruby?

If you're using ruby 1.8.7 or 1.9, you can use the fact that iterator methods like each_with_index, when called without a block, return an Enumerator object, which you can call Enumerable methods like map on. So you can do:

arr.each_with_index.map { |x,i| [x, i+2] }

In 1.8.6 you can do:

require 'enumerator'
arr.enum_for(:each_with_index).map { |x,i| [x, i+2] }

Validate phone number using angular js

You can also use ng-pattern ,[7-9] = > mobile number must start with 7 or 8 or 9 ,[0-9] = mobile number accepts digits ,{9} mobile number should be 10 digits.

_x000D_
_x000D_
function form($scope){_x000D_
    $scope.onSubmit = function(){_x000D_
        alert("form submitted");_x000D_
    }_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>_x000D_
<div ng-app ng-controller="form">_x000D_
<form name="myForm" ng-submit="onSubmit()">_x000D_
    <input type="number" ng-model="mobile_number" name="mobile_number" ng-pattern="/^[7-9][0-9]{9}$/" required>_x000D_
    <span ng-show="myForm.mobile_number.$error.pattern">Please enter valid number!</span>_x000D_
    <input type="submit" value="submit"/>_x000D_
</form>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to mock void methods with Mockito

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

For example,

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

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

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

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

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

YAML: Do I need quotes for strings in YAML?

I had this concern when working on a Rails application with Docker.

My most preferred approach is to generally not use quotes. This includes not using quotes for:

  • variables like ${RAILS_ENV}
  • values separated by a colon (:) like postgres-log:/var/log/postgresql
  • other strings values

I, however, use double-quotes for integer values that need to be converted to strings like:

  • docker-compose version like version: "3.8"
  • port numbers like "8080:8080"

However, for special cases like booleans, floats, integers, and other cases, where using double-quotes for the entry values could be interpreted as strings, please do not use double-quotes.

Here's a sample docker-compose.yml file to explain this concept:

version: "3"

services:
  traefik:
    image: traefik:v2.2.1
    command:
      - --api.insecure=true # Don't do that in production
      - --providers.docker=true
      - --providers.docker.exposedbydefault=false
      - --entrypoints.web.address=:80
    ports:
      - "80:80"
      - "8080:8080"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro

That's all.

I hope this helps

how to refresh my datagridview after I add new data

In the code of the button that saves the changes to the database eg the update button, add the following lines of code:

MyDataGridView.DataSource = MyTableBindingSource

MyDataGridView.Update()

MyDataGridView.RefreshEdit()

What is the difference between g++ and gcc?

GCC: GNU Compiler Collection

  • Referrers to all the different languages that are supported by the GNU compiler.

gcc: GNU C      Compiler
g++: GNU C++ Compiler

The main differences:

  1. gcc will compile: *.c\*.cpp files as C and C++ respectively.
  2. g++ will compile: *.c\*.cpp files but they will all be treated as C++ files.
  3. Also if you use g++ to link the object files it automatically links in the std C++ libraries (gcc does not do this).
  4. gcc compiling C files has fewer predefined macros.
  5. gcc compiling *.cpp and g++ compiling *.c\*.cpp files has a few extra macros.

Extra Macros when compiling *.cpp files:

#define __GXX_WEAK__ 1
#define __cplusplus 1
#define __DEPRECATED 1
#define __GNUG__ 4
#define __EXCEPTIONS 1
#define __private_extern__ extern

Twig for loop for arrays with keys

These are extended operations (e.g., sort, reverse) for one dimensional and two dimensional arrays in Twig framework:

1D Array

Without Key Sort and Reverse

{% for key, value in array_one_dimension %}
    <div>{{ key }}</div>
    <div>{{ value }}</div>
{% endfor %}

Key Sort

{% for key, value in array_one_dimension|keys|sort %}
    <div>{{ key }}</div>
    <div>{{ value }}</div>
{% endfor %}

Key Sort and Reverse

{% for key, value in array_one_dimension|keys|sort|reverse %}
    <div>{{ key }}</div>
    <div>{{ value }}</div>
{% endfor %}

2D Arrays

Without Key Sort and Reverse

{% for key_a, value_a in array_two_dimension %}
    {% for key_b, value_b in array_two_dimension[key_a] %}
        <div>{{ key_b }}</div>
        <div>{{ value_b }}</div>
    {% endfor %}
{% endfor %}

Key Sort on Outer Array

{% for key_a, value_a in array_two_dimension|keys|sort %}
    {% for key_b, value_b in array_two_dimension[key_a] %}
        <div>{{ key_b }}</div>
        <div>{{ value_b }}</div>
    {% endfor %}
{% endfor %}

Key Sort on Both Outer and Inner Arrays

{% for key_a, value_a in array_two_dimension|keys|sort %}
    {% for key_b, value_b in array_two_dimension[key_a]|keys|sort %}
        <div>{{ key_b }}</div>
        <div>{{ value_b }}</div>
    {% endfor %}
{% endfor %}

Key Sort on Outer Array & Key Sort and Reverse on Inner Array

{% for key_a, value_a in array_two_dimension|keys|sort %}
    {% for key_b, value_b in array_two_dimension[key_a]|keys|sort|reverse %}
        <div>{{ key_b }}</div>
        <div>{{ value_b }}</div>
    {% endfor %}
{% endfor %}

Key Sort and Reverse on Outer Array & Key Sort on Inner Array

{% for key_a, value_a in array_two_dimension|keys|sort|reverse %}
    {% for key_b, value_b in array_two_dimension[key_a]|keys|sort %}
        <div>{{ key_b }}</div>
        <div>{{ value_b }}</div>
    {% endfor %}
{% endfor %}

Key Sort and Reverse on Both Outer and Inner Array

{% for key_a, value_a in array_two_dimension|keys|sort|reverse %}
    {% for key_b, value_b in array_two_dimension[key_a]|keys|sort|reverse %}
        <div>{{ key_b }}</div>
        <div>{{ value_b }}</div>
    {% endfor %}
{% endfor %}

How do you use the ? : (conditional) operator in JavaScript?

x = 9
y = 8

unary

++x
--x

Binary

z = x + y

Ternary

2>3 ? true : false;
2<3 ? true : false;
2<3 ? "2 is lesser than 3" : "2 is greater than 3";

MS-DOS Batch file pause with enter key

Depending on which OS you're using, if you are flexible, then CHOICE can be used to wait on almost any key EXCEPT enter

If you are really referring to what Microsoft insists on calling "Command Prompt" which is simply an MS-DOS emulator, then perhaps TIMEOUT may suit your purpose (timeout /t -1 waits on any key, not just ENTER) and of course CHOICE is available again in recent WIN editions.

And a warning on SET /P - whereas set /p DUMMY=Hit ENTER to continue... will work,

set "dummy="
set /p DUMMY=Hit ENTER to continue...
if defined dummy (echo not just ENTER was pressed) else (echo just ENTER was pressed)

will detect whether just ENTER or something else, ending in ENTER was keyed in.

How do I copy the contents of a String to the clipboard in C#?

You can use System.Windows.Forms.Clipboard.SetText(...).

How do I add an "Add to Favorites" button or link on my website?

This code is the corrected version of iambriansreed's answer:

<script type="text/javascript">
    $(function() {
        $("#bookmarkme").click(function() {
            // Mozilla Firefox Bookmark
            if ('sidebar' in window && 'addPanel' in window.sidebar) { 
                window.sidebar.addPanel(location.href,document.title,"");
            } else if( /*@cc_on!@*/false) { // IE Favorite
                window.external.AddFavorite(location.href,document.title); 
            } else { // webkit - safari/chrome
                alert('Press ' + (navigator.userAgent.toLowerCase().indexOf('mac') != - 1 ? 'Command/Cmd' : 'CTRL') + ' + D to bookmark this page.');
            }
        });
    });
</script>

How to "git show" a merge commit with combined diff output even when every changed file agrees with one of the parents?

I think you just need 'git show -c $ref'. Trying this on the git repository on a8e4a59 shows a combined diff (plus/minus chars in one of 2 columns). As the git-show manual mentions, it pretty much delegates to 'git diff-tree' so those options look useful.

Get file name from URL

If you are using Spring, there is a helper to handle URIs. Here is the solution:

List<String> pathSegments = UriComponentsBuilder.fromUriString(url).build().getPathSegments();
String filename = pathSegments.get(pathSegments.size()-1);

get one item from an array of name,value JSON

I know this question is old, but no one has mentioned a native solution yet. If you're not trying to support archaic browsers (which you shouldn't be at this point), you can use array.filter:

_x000D_
_x000D_
var arr = [];_x000D_
arr.push({name:"k1", value:"abc"});_x000D_
arr.push({name:"k2", value:"hi"});_x000D_
arr.push({name:"k3", value:"oa"});_x000D_
_x000D_
var found = arr.filter(function(item) { return item.name === 'k1'; });_x000D_
_x000D_
console.log('found', found[0]);
_x000D_
Check the console.
_x000D_
_x000D_
_x000D_

You can see a list of supported browsers here.

In the future with ES6, you'll be able to use array.find.

python pandas dataframe columns convert to dict key and value

If lakes is your DataFrame, you can do something like

area_dict = dict(zip(lakes.area, lakes.count))

Getting an odd error, SQL Server query using `WITH` clause

;WITH 
    CteProductLookup(ProductId, oid) 
    AS 
...

How can I change eclipse's Internal Browser from IE to Firefox on Windows XP?

In Preferences -> General -> Web Browser, there is the option "Use internal web browser". Select "Use external web browser" instead and check "Firefox".

Run/install/debug Android applications over Wi-Fi?

  1. make sure your pc and android is on same wifi connection.

  2. start adb server from your phone... download any wireless adb app from playstore...here is what I am using WiFi ADB - Debug Over Air

  3. on your computer start cmd and run: Code (csharp): adb connect 192.168.1.100:5555 Be sure to replace 192.168.1.100 with the IP address that is actually assigned to your device.

check if it is connected by : Code (csharp): adb devices 4. start unity or restart if it is already running and hit play..

  1. tadaa...........:eek:

Difference between two dates in years, months, days in JavaScript

Time span in full Days, Hours, Minutes, Seconds, Milliseconds:

// Extension for Date
Date.difference = function (dateFrom, dateTo) {
  var diff = { TotalMs: dateTo - dateFrom };
  diff.Days = Math.floor(diff.TotalMs / 86400000);

  var remHrs = diff.TotalMs % 86400000;
  var remMin = remHrs % 3600000;
  var remS   = remMin % 60000;

  diff.Hours        = Math.floor(remHrs / 3600000);
  diff.Minutes      = Math.floor(remMin / 60000);
  diff.Seconds      = Math.floor(remS   / 1000);
  diff.Milliseconds = Math.floor(remS % 1000);
  return diff;
};

// Usage
var a = new Date(2014, 05, 12, 00, 5, 45, 30); //a: Thu Jun 12 2014 00:05:45 GMT+0400 
var b = new Date(2014, 02, 12, 00, 0, 25, 0);  //b: Wed Mar 12 2014 00:00:25 GMT+0400
var diff = Date.difference(b, a);
/* diff: {
  Days: 92
  Hours: 0
  Minutes: 5
  Seconds: 20
  Milliseconds: 30
  TotalMs: 7949120030
} */

Android WebView progress bar

here is the easiest way to add progress bar in android Web View.

Add a boolean field in your activity/fragment

private boolean isRedirected;

This boolean will prevent redirection of web pages cause of dead links.Now you can just pass your WebView object and web Url into this method.

private void startWebView(WebView webView,String url) {

    webView.setWebViewClient(new WebViewClient() {
        ProgressDialog progressDialog;

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            isRedirected = true;
            return false;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            isRedirected = false;
        }

        public void onLoadResource (WebView view, String url) {
            if (!isRedirected) {
                if (progressDialog == null) {
                    progressDialog = new ProgressDialog(SponceredDetailsActivity.this);
                    progressDialog.setMessage("Loading...");
                    progressDialog.show();
                }
            }

        }
        public void onPageFinished(WebView view, String url) {
            try{
                isRedirected=true;

                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                    progressDialog = null;
                }



            }catch(Exception exception){
                exception.printStackTrace();
            }
        }

    });

    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl(url);
}

Here when start loading it will call onPageStarted. Here i setting Boolean field is false. But when page load finish it will come to onPageFinished method and here Boolean field is set to true. Sometimes if url is dead it will redirected and it will come to onLoadResource() before onPageFinished method. For this reason it will not hiding the progress bar. To prevent this i am checking if (!isRedirected) in onLoadResource()

in onPageFinished() method before dismissing the Progress Dialog you can write your 10 second time delay code

That's it. Happy coding :)

Twitter Bootstrap 3: How to center a block

You have to use style="width:value" with center block class

MySql server startup error 'The server quit without updating PID file '

I tried remove all the *.err but still getting the same error. I got one of the error in error log.

[ERROR] InnoDB: Attempted to open a previously opened tablespace. Previous tablespace erp/brand uses space ID : 7 at filepath: ./erp/brand.ibd. Cannot open tablespace webdb1/system_user which uses space ID: 7 at filepath: ./webdb1/system_ user.ibd

so I delete all the ib* files and it works.

rm -f *.err ib*

How to set up datasource with Spring for HikariCP?

I have recently migrated from C3P0 to HikariCP in a Spring and Hibernate based project and it was not as easy as I had imagined and here I am sharing my findings.

For Spring Boot see my answer here

I have the following setup

  • Spring 4.3.8+
  • Hiberante 4.3.8+
  • Gradle 2.x
  • PostgreSQL 9.5

Some of the below configs are similar to some of the answers above but, there are differences.

Gradle stuff

In order to pull in the right jars, I needed to pull in the following jars

//latest driver because *brettw* see https://github.com/pgjdbc/pgjdbc/pull/849
compile 'org.postgresql:postgresql:42.2.0'
compile('com.zaxxer:HikariCP:2.7.6') {
    //they are pulled in separately elsewhere
    exclude group: 'org.hibernate', module: 'hibernate-core'
}

// Recommended to use HikariCPConnectionProvider by Hibernate in 4.3.6+    
compile('org.hibernate:hibernate-hikaricp:4.3.8.Final') {
        //they are pulled in separately elsewhere, to avoid version conflicts
        exclude group: 'org.hibernate', module: 'hibernate-core'
        exclude group: 'com.zaxxer', module: 'HikariCP'
}

// Needed for HikariCP logging if you use log4j
compile('org.slf4j:slf4j-simple:1.7.25')  
compile('org.slf4j:slf4j-log4j12:1.7.25') {
    //log4j pulled in separately, exclude to avoid version conflict
    exclude group: 'log4j', module: 'log4j'
}

Spring/Hibernate based configs

In order to get Spring & Hibernate to make use of Hikari Connection pool, you need to define the HikariDataSource and feed it into sessionFactory bean as shown below.

<!-- HikariCP Database bean -->
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
    <constructor-arg ref="hikariConfig" />
</bean>

<!-- HikariConfig config that is fed to above dataSource -->
<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
        <property name="poolName" value="SpringHikariPool" />
        <property name="dataSourceClassName" value="org.postgresql.ds.PGSimpleDataSource" />
        <property name="maximumPoolSize" value="20" />
        <property name="idleTimeout" value="30000" />

        <property name="dataSourceProperties">
            <props>
                <prop key="serverName">localhost</prop>
                <prop key="portNumber">5432</prop>
                <prop key="databaseName">dbname</prop>
                <prop key="user">dbuser</prop>
                <prop key="password">dbpassword</prop>
            </props>
        </property>
</bean>

<bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" id="sessionFactory">
        <!-- Your Hikari dataSource below -->
        <property name="dataSource" ref="dataSource"/>
        <!-- your other configs go here -->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.connection.provider_class">org.hibernate.hikaricp.internal.HikariCPConnectionProvider</prop>
                <!-- Remaining props goes here -->
            </props>
        </property>
 </bean>

Once the above are setup then, you need to add an entry to your log4j or logback and set the level to DEBUG to see Hikari Connection Pool start up.

Log4j1.2

<!-- Keep additivity=false to avoid duplicate lines -->
<logger additivity="false" name="com.zaxxer.hikari">
    <level value="debug"/>
    <!-- Your appenders goes here -->
</logger>

Logback

Via application.properties in Spring Boot

debug=true
logging.level.com.zaxxer.hikari.HikariConfig=DEBUG 

Using logback.xml

<logger name="com.zaxxer.hikari" level="DEBUG" additivity="false">
    <appender-ref ref="STDOUT" />
</logger>

With the above you should be all good to go! Obviously you need to customize the HikariCP pool configs in order to get the performance that it promises.

Generate a unique id

Why not just use ToString?

public string generateID()
{
    return Guid.NewGuid().ToString("N");
}

If you would like it to be based on a URL, you could simply do the following:

public string generateID(string sourceUrl)
{
    return string.Format("{0}_{1:N}", sourceUrl, Guid.NewGuid());
}

If you want to hide the URL, you could use some form of SHA1 on the sourceURL, but I'm not sure what that might achieve.

MongoDB Data directory /data/db not found

MongoDB needs data directory to store data. Default path is /data/db

When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx permission to user.

If you want to change the path of your data directory then you should specify it while starting mongod server like,

mongod --dbpath /data/<path> --port <port no> 

This should help you start your mongod server with custom path and port.

No value accessor for form control with name: 'recipient'

Make sure you import MaterialModule as well since you are using md-input which does not belong to FormsModule

Property 'map' does not exist on type 'Observable<Response>'

Just write this command in the VS Code terminal of your project and restart the project.

npm install rxjs-compat

You need to import the map operator by adding this:

import 'rxjs/add/operator/map';

How to switch Python versions in Terminal?

I have followed the below steps in Macbook.

  1. Open terminal
  2. type nano ~/.bash_profile and enter
  3. Now add the line alias python=python3
  4. Press CTRL + o to save it.
  5. It will prompt for file name Just hit enter and then press CTRL + x.
  6. Now check python version by using the command : python --version

Best way to implement multi-language/globalization in large .NET project

I've seen projects implemented using a number of different approaches, each have their merits and drawbacks.

  • One did it in the config file (not my favourite)
  • One did it using a database - this worked pretty well, but was a pain in the you know what to maintain.
  • One used resource files the way you're suggesting and I have to say it was my favourite approach.
  • The most basic one did it using an include file full of strings - ugly.

I'd say the resource method you've chosen makes a lot of sense. It would be interesting to see other people's answers too as I often wonder if there's a better way of doing things like this. I've seen numerous resources that all point to the using resources method, including one right here on SO.

How to truncate a foreign key constrained table?

Yes you can:

SET FOREIGN_KEY_CHECKS = 0;

TRUNCATE table1;
TRUNCATE table2;

SET FOREIGN_KEY_CHECKS = 1;

With these statements, you risk letting in rows into your tables that do not adhere to the FOREIGN KEY constraints.

"%%" and "%/%" for the remainder and the quotient

In R, you can assign your own operators using %[characters]%. A trivial example:

'%p%' <- function(x, y){x^2 + y}

2 %p% 3 # result: 7

While I agree with BlueTrin that %% is pretty standard, I have a suspicion %/% may have something to do with the sort of operator definitions I showed above - perhaps it was easier to implement, and makes sense: %/% means do a special sort of division (integer division)

Fixed height and width for bootstrap carousel

Because some images could have less than 500px of height, it's better to keep the auto-adjust, so i recommend the following:

<div class="carousel-inner" role="listbox" style="max-width:900px; max-height:600px !important;">`

This Activity already has an action bar supplied by the window decor

It could also be because you have a style without a parent specified:

<style name="DarkModeTheme" >
    <item name="searchBarBgColor">#D6D6D6</item>
</style>

Remove it, and it should fix the problem.

Omitting the second expression when using the if-else shorthand

Probably shortest (based on OR operator and its precedence)

x-2||dosomething()

_x000D_
_x000D_
let x=1, y=2;_x000D_
let dosomething = s=>console.log(s); _x000D_
_x000D_
x-2||dosomething('x do something');_x000D_
y-2||dosomething('y do something');
_x000D_
_x000D_
_x000D_

How do I pipe a subprocess call to a text file?

You could also just call the script from the terminal, outputting everything to a file, if that helps. This way:

$ /path/to/the/script.py > output.txt

This will overwrite the file. You can use >> to append to it.

If you want errors to be logged in the file as well, use &>> or &>.

What is the difference between Step Into and Step Over in a debugger

step into will dig into method calls
step over will just execute the line and go to the next one

Put buttons at bottom of screen with LinearLayout?

first create file name it as footer.xml put this code inside it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="78dp"
    android:layout_gravity="bottom"
    android:gravity="bottom"
 android:layout_weight=".15"
    android:orientation="horizontal"
    android:background="@drawable/actionbar_dark_background_tile" >
    <ImageView
        android:id="@+id/lborder"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".14"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/overlay" />
    <ImageView
        android:id="@+id/unknown"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".14"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/notcolor" />
    <ImageView
        android:id="@+id/open"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".14"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/openit"
        />
    <ImageView
        android:id="@+id/color"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".14"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/colored" />
        <ImageView
        android:id="@+id/rborder"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/frames"
        android:layout_weight=".14" />


</LinearLayout>  

then create header.xml and put this code inside it.:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="@dimen/action_bar_height"
    android:layout_gravity="top"
    android:baselineAligned="true"
    android:orientation="horizontal"
    android:background="@drawable/actionbar_dark_background_tile" >
    <ImageView
        android:id="@+id/contact"
        android:layout_width="37dp"
        android:layout_height="wrap_content"
        android:layout_gravity="start"
        android:layout_weight=".18"
        android:scaleType="fitCenter"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/logo"/>

    <ImageView
        android:id="@+id/share"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="start"
        android:layout_weight=".14"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/share" />

    <ImageView
        android:id="@+id/save"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".14"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/save" />

    <ImageView
        android:id="@+id/set"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".14"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/set" />

    <ImageView
        android:id="@+id/fix"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".14"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/light" />

    <ImageView
        android:id="@+id/rotate"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".14"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/ic_menu_rotate" />

    <ImageView
        android:id="@+id/stock"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".14"
        android:background="@drawable/action_bar_left_button"
        android:src="@drawable/stock" />

</LinearLayout>

and then in your main_activity.xml and put this code inside it :-

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity"
android:id="@+id/relt"
android:background="@drawable/background" >

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="78dp"
    android:id="@+id/down"
    android:layout_alignParentBottom="true" >

    <include
        android:layout_width="fill_parent"
        android:layout_height="78dp"
        layout="@layout/footer" >
    </include>
</LinearLayout>
<ImageView
    android:id="@+id/view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@+id/down"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/inc"
   >  
    </ImageView> 
    <include layout="@layout/header"
        android:id="@+id/inc"
        android:layout_width="fill_parent"
        android:layout_height="50dp"></include> 

happy coding :)

How to set default values for Angular 2 component properties?

Here is the best solution for this. (ANGULAR All Version)

Addressing solution: To set a default value for @Input variable. If no value passed to that input variable then It will take the default value.

I have provided solution for this kind of similar question. You can find the full solution from here

export class CarComponent implements OnInit {
  private _defaultCar: car = {
    // default isCar is true
    isCar: true,
    // default wheels  will be 4
    wheels: 4
  };

  @Input() newCar: car = {};

  constructor() {}

  ngOnInit(): void {

   // this will concate both the objects and the object declared later (ie.. ...this.newCar )
   // will overwrite the default value. ONLY AND ONLY IF DEFAULT VALUE IS PRESENT

    this.newCar = { ...this._defaultCar, ...this.newCar };
   //  console.log(this.newCar);
  }
}

Stripping everything but alphanumeric chars from a string in Python

How about:

def ExtractAlphanumeric(InputString):
    from string import ascii_letters, digits
    return "".join([ch for ch in InputString if ch in (ascii_letters + digits)])

This works by using list comprehension to produce a list of the characters in InputString if they are present in the combined ascii_letters and digits strings. It then joins the list together into a string.

How to name variables on the fly?

Don't make data frames. Keep the list, name its elements but do not attach it.

The biggest reason for this is that if you make variables on the go, almost always you will later on have to iterate through each one of them to perform something useful. There you will again be forced to iterate through each one of the names that you have created on the fly.

It is far easier to name the elements of the list and iterate through the names.

As far as attach is concerned, its really bad programming practice in R and can lead to a lot of trouble if you are not careful.

Xcode project not showing list of simulators

Solution: Build Settings -> Architectures -> Supported Platforms: changed from iphoneos to iOS

Confirmed works in Xcode Version 9.0 (9A235)

Override and reset CSS style: auto or none don't work

Well, display: none; will not display the table at all, try display: inline-block; with the width and min-width declarations remaining 'auto'.

Best way to "negate" an instanceof

ok just my two cents, use a is string method:

public static boolean isString(Object thing) {
    return thing instanceof String;
}

public void someMethod(Object thing){
    if (!isString(thing)) {
        return null;
    }
    log.debug("my thing is valid");
}

CSS list-style-image size

Thanks to Chris for the starting point here is a improvement which addresses the resizing of the images used, the use of first-child is just to indicate you could use a variety of icons within the list to give you full control.

ul li:first-child:before {
    content: '';
    display: inline-block;
    height: 25px;
    width: 35px;
    background-image: url('../images/Money.png');
    background-size: contain;
    background-repeat: no-repeat;
    margin-left: -35px;
}

This seems to work well in all modern browsers, you will need to ensure that the width and the negative margin left have the same value, hope it helps

Replacing Pandas or Numpy Nan with a None to use with MysqlDB

After stumbling around, this worked for me:

df = df.astype(object).where(pd.notnull(df),None)

Convert an array to string

You can join your array using the following:

string.Join(",", Client);

Then you can output anyway you want. You can change the comma to what ever you want, a space, a pipe, or whatever.

Do subclasses inherit private fields?

A private class member or constructor is accessible only within the body of the top level class (§7.6) that encloses the declaration of the member or constructor. It is not inherited by subclasses. https://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6

Class is not abstract and does not override abstract method

Both classes Rectangle and Ellipse need to override both of the abstract methods.

To work around this, you have 3 options:

  • Add the two methods
  • Make each class that extends Shape abstract
  • Have a single method that does the function of the classes that will extend Shape, and override that method in Rectangle and Ellipse, for example:

    abstract class Shape {
        // ...
        void draw(Graphics g);
    }
    

And

    class Rectangle extends Shape {
        void draw(Graphics g) {
            // ...
        }
    }

Finally

    class Ellipse extends Shape {
        void draw(Graphics g) {
            // ...
        }
    }

And you can switch in between them, like so:

    Shape shape = new Ellipse();
    shape.draw(/* ... */);

    shape = new Rectangle();
    shape.draw(/* ... */);

Again, just an example.

jQuery selector to get form by name

    // this will give all the forms on the page.

    $('form')

   // If you know the name of form then.

    $('form[name="myFormName"]')

  //  If you don't know know the name but the position (starts with 0)

    $('form:eq(1)')  // 2nd form will be fetched.

How do I get my C# program to sleep for 50 msec?

Starting with .NET Framework 4.5, you can use:

using System.Threading.Tasks;

Task.Delay(50).Wait();   // wait 50ms

iPad Safari scrolling causes HTML elements to disappear and reappear with a delay

This is the complete answer to my question. I had originally marked @Colin Williams' answer as the correct answer, as it helped me get to the complete solution. A community member, @Slipp D. Thompson edited my question, after about 2.5 years of me having asked it, and told me I was abusing SO's Q & A format. He also told me to separately post this as the answer. So here's the complete answer that solved my problem:

@Colin Williams, thank you! Your answer and the article you linked out to gave me a lead to try something with CSS.

So, I was using translate3d before. It produced unwanted results. Basically, it would chop off and NOT RENDER elements that were offscreen, until I interacted with them. So, basically, in landscape orientation, half of my site that was offscreen was not being shown. This is a iPad web app, owing to which I was in a fix.

Applying translate3d to relatively positioned elements solved the problem for those elements, but other elements stopped rendering, once offscreen. The elements that I couldn't interact with (artwork) would never render again, unless I reloaded the page.

The complete solution:

*:not(html) {
    -webkit-transform: translate3d(0, 0, 0);
}

Now, although this might not be the most "efficient" solution, it was the only one that works. Mobile Safari does not render the elements that are offscreen, or sometimes renders erratically, when using -webkit-overflow-scrolling: touch. Unless a translate3d is applied to all other elements that might go offscreen owing to that scroll, those elements will be chopped off after scrolling.

So, thanks again, and hope this helps some other lost soul. This surely helped me big time!

How to parse JSON data with jQuery / JavaScript?

var jsonP = "person" : [ { "id" : "1", "name" : "test1" },
  { "id" : "2", "name" : "test2" },
  { "id" : "3", "name" : "test3" },
  { "id" : "4", "name" : "test4" },
  { "id" : "5", "name" : "test5" } ];

var cand = document.getElementById("cand");
var json_arr = [];
$.each(jsonP.person,function(key,value){
    json_arr.push(key+' . '+value.name  + '<br>');
    cand.innerHTML = json_arr;
});

<div id="cand">
</div>

How to get the selected index of a RadioGroup in Android

Here is a Kotlin extension to get the correct position even if your group contains a TextView or any non-RadioButton.

fun RadioGroup.getCheckedRadioButtonPosition(): Int {
    val radioButtonId = checkedRadioButtonId
    return children.filter { it is RadioButton }
        .mapIndexed { index: Int, view: View ->
            index to view
        }.firstOrNull {
            it.second.id == radioButtonId
        }?.first ?: -1
}

How to update record using Entity Framework Core?

According to Microsoft docs:

the read-first approach requires an extra database read, and can result in more complex code for handling concurrency conflict

However, you should know that using Update method on DbContext will mark all the fields as modified and will include all of them in the query. If you want to update a subset of fields you should use the Attach method and then mark the desired field as modified manually.

context.Attach(person);
context.Entry(person).Property(p => p.Name).IsModified = true;
context.SaveChanges();

javax vs java package

Some packages like javax.swing were not included in java standard library at first. Sun company decided to consider them official and included them into the early versions of java as standard libraries or standard extensions.

By convention, all the standard extensions start with an X while they can get promoted to first-class over time like what happened for javax.swing.

get launchable activity name of package from adb

You don't need root to pull the apk files from /data/app. Sure, you might not have permissions to list the contents of that directory, but you can find the file locations of APKs with:

adb shell pm list packages -f

Then you can use adb pull:

adb pull <APK path from previous command>

and then aapt to get the information you want:

aapt dump badging <pulledfile.apk>

how to convert .java file to a .class file

To get a .class file you have to compile the .java file.

The command for this is javac. The manual for this is found here (Windows)

In short:

javac File.java

Chrome's remote debugging (USB debugging) not working for Samsung Galaxy S3 running android 4.3

For me the solution was to download the Android SDK and launch adb devices which started the adb daemon.

How to disable submit button once it has been clicked?

tested on IE11, FF53, GC58 :

onclick="var e=this;setTimeout(function(){e.disabled=true;},0);return true;"

Which @NotNull Java annotation should I use?

I use the IntelliJ one, because I'm mostly concerned with IntelliJ flagging things that might produce a NPE. I agree that it's frustrating not having a standard annotation in the JDK. There's talk of adding it, it might make it into Java 7. In which case there will be one more to choose from!

CSS Circle with border

You forgot to set the width of the border! Change border: red; to border:1px solid red;

Here the full code to get the circle:

_x000D_
_x000D_
.circle {_x000D_
    background-color:#fff;_x000D_
    border:1px solid red;    _x000D_
    height:100px;_x000D_
    border-radius:50%;_x000D_
    -moz-border-radius:50%;_x000D_
    -webkit-border-radius:50%;_x000D_
    width:100px;_x000D_
}
_x000D_
<div class="circle"></div>
_x000D_
_x000D_
_x000D_

Laravel - Form Input - Multiple select for a one to many relationship

@SamMonk your technique is great. But you can use laravel form helper to do so. I have a customer and dogs relationship.

On your controller

$dogs = Dog::lists('name', 'id');

On customer create view you can use.

{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, null, ['id' => 'dogs', 'multiple' => 'multiple']) }}

Third parameter accepts a list of array a well. If you define a relationship on your model you can do this:

{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, $customer->dogs->lists('id'), ['id' => 'dogs', 'multiple' => 'multiple']) }}

Update For Laravel 5.1

The lists method now returns a Collection. Upgrading To 5.1.0

{!! Form::label('dogs', 'Dogs') !!}
{!! Form::select('dogs[]', $dogs, $customer->dogs->lists('id')->all(), ['id' => 'dogs', 'multiple' => 'multiple']) !!}

Include PHP inside JavaScript (.js) files

You can't include server side PHP in your client side javascript, you will have to port it over to javascript. If you wish, you can use php.js, which ports all PHP functions over to javascript. You can also create a new php file that returns the results of calling your PHP function, and then call that file using AJAX to get the results.

Detecting input change in jQuery?

There are jQuery events like keyup and keypress which you can use with input HTML Elements. You could additionally use the blur() event.

How to make HTML open a hyperlink in another window or tab?

Since web is evolving quickly, some things changes with time. For security issues, you might want to use the rel="noopener" attribute in conjuncture with your target="_blank".

Like stated in Google Dev Documentation, the other page can access your window object with the window.opener property. Your external link should looks like this now:

<a href="http://www.starfall.com/" target="_blank" rel="noopener">Starfall</a>

Why isn't this code to plot a histogram on a continuous value Pandas column working?

EDIT:

After your comments this actually makes perfect sense why you don't get a histogram of each different value. There are 1.4 million rows, and ten discrete buckets. So apparently each bucket is exactly 10% (to within what you can see in the plot).


A quick rerun of your data:

In [25]: df.hist(column='Trip_distance')

enter image description here

Prints out absolutely fine.

The df.hist function comes with an optional keyword argument bins=10 which buckets the data into discrete bins. With only 10 discrete bins and a more or less homogeneous distribution of hundreds of thousands of rows, you might not be able to see the difference in the ten different bins in your low resolution plot:

In [34]: df.hist(column='Trip_distance', bins=50)

enter image description here

Gem Command not found

The following command will give you the list of files that the gem package installed:

dpkg -L gem

that should help you troubleshoot.

Fetch API request timeout?

there's no timeout support in the fetch API yet. But it could be achieved by wrapping it in a promise.

for eg.

  function fetchWrapper(url, options, timeout) {
    return new Promise((resolve, reject) => {
      fetch(url, options).then(resolve, reject);

      if (timeout) {
        const e = new Error("Connection timed out");
        setTimeout(reject, timeout, e);
      }
    });
  }

Node.js global proxy setting

I finally created a module to get this question (partially) resolved. Basically this module rewrites http.request function, added the proxy setting then fire. Check my blog post: https://web.archive.org/web/20160110023732/http://blog.shaunxu.me:80/archive/2013/09/05/semi-global-proxy-setting-for-node.js.aspx

java.io.FileNotFoundException: /storage/emulated/0/New file.txt: open failed: EACCES (Permission denied)

For SDK 29 :

String str1 = "";
folder1 = new File(String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)));
if (folder1.exists()) {str1 = folder1.toString() + File.separator;}

public static void createTextFile(String sBody, String FileName, String Where) {
    try {
        File gpxfile = new File(Where, FileName);
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(sBody);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Then you can save your file like this :

createTextFile("This is Content","file.txt",str1);

Print page numbers on pages when printing html

Try to use https://www.pagedjs.org/. It polyfills page counter, header-/footer-functionality for all major browsers.

@page {
  @bottom-left {
    content: counter(page) ' of ' counter(pages);
  }
}

It's so much more comfortable compared to alternatives like PrinceXML, Antennahouse, WeasyPrince, PDFReactor, etc ...

And it is totally free! No pricing or whatever. It really saved my life!

jQuery append text inside of an existing paragraph tag

Try this...

$('p').append('<span id="add_here">new-dynamic-text</span>');

OR if there is an existing span, do this.

$('p').children('span').text('new-dynamic-text');

DEMO

How to set width and height dynamically using jQuery

I tried all of the suggestions above and none of them worked for me, they changed the clientWidth and clientHeight not the actual width and height.

The jQuery docs for $().width and height methods says: "Note that .width("value") sets the content width of the box regardless of the value of the CSS box-sizing property."

The css approach did the same thing so I had to use the $().attr() methods instead.

_canvas.attr('width', 100);
_canvas.attr('height', 200);

I don't know is this affect me because I was trying to resize a element and it is some how different or not.

How to set environment variable or system property in spring tests?

If you want your variables to be valid for all tests, you can have an application.properties file in your test resources directory (by default: src/test/resources) which will look something like this:

MYPROPERTY=foo

This will then be loaded and used unless you have definitions via @TestPropertySource or a similar method - the exact order in which properties are loaded can be found in the Spring documentation chapter 24. Externalized Configuration.

Facebook API - How do I get a Facebook user's profile image through the Facebook API (without requiring the user to "Allow" the application)

Simple one-line code to save FULL size profile image on your server.

<?php

copy("https://graph.facebook.com/FACEBOOKID/picture?width=9999&height=9999", "picture.jpg");

?>

This will only work if openssl is enabled in php.ini.

What is the difference between an abstract function and a virtual function?

explanation: with analogies. hopefully it will help you.

Context

I work on the 21 st floor of a building. And I'm paranoid about fire. Every now and again, somewhere in the world, a fire is burning down a sky scraper. But luckily we have an instruction manual somewhere here on what to do in case of fire:

FireEscape()

  1. Don't collect belongings
  2. Walk to fire escape
  3. Walk out of building

This is basically a virtual method called FireEscape()

Virtual Method

This plan is pretty good for 99% of the circumstances. It's a basic plan which works. But there is a 1% chance that the fire escape is blocked or damaged in which case you are completely screwed and you'll become toast unless you take some drastic action. With virtual methods you can do just that: you can override the basic FireEscape() plan with your own version of the plan:

  1. Run to window
  2. Jump out the window
  3. Parachute safely to the bottom

In other words virtual methods provide a basic plan, which can be overriden if you need to. Subclasses can override the parent class' virtual method if the programmer deems it appropriate.

Abstract methods

Not all organisations are well drilled. Some organisations don't do fire drills. They don't have an overall escape policy. Every man is for himself. Management are only interested in such a policy existing.

In other words, each person is forced to develop his own FireEscape() method. One guy will walk out the fire escape. Another guy will parachute. Another guy will use rocket propulsion technology to fly away from the building. Another guy will abseil out. Management don't care how you escape, so long as you have a basic FireEscape() plan - if they don't you can be guaranteed OHS will come down on the organisation like a tonne of bricks. This is what is meant by an abstract method.

What's the difference between the two again?

Abstract method: sub classes are forced to implement their own FireEscape method. With a virtual method, you have a basic plan waiting for you, but can choose to implement your own if it's not good enough.

Now that wasn't so hard was it?

Java parsing XML document gives "Content not allowed in prolog." error

Check any syntax problem in the XMl file. I've found this error when working on xsl/xsp with Cocoon and I define a variable using a non-existing node or something like that. Check the whole XML.

python pip on Windows - command 'cl.exe' failed

In my case I need to install more tools from Visual Studio (I'm using VS 2017 Community and Python 3.6.4). I installed those tools (see installer screenshot here):

  1. Desktop development with C++: I included all defaulted items and the next ones:

    • Windows XP support for C++
    • Support for C++/CLI
    • VC++ 2015.3 v140 toolset
  2. Linux development with C++

Then I opened the Windows PowerShell as Administrator privilegies (Right click to open) and move folder of Visual Studio installation and find that path:

cd [Visual Studio Path]\VC\Auxiliary\Build

Then I executed this file:

.\vcvars32.bat

After that I use pip as normal, for instance, I wanted to install Mayavi:

pip install mayavi

I hope that it helps someone too.

How to achieve function overloading in C?

I hope the below code will help you to understand function overloading

#include <stdio.h>
#include<stdarg.h>

int fun(int a, ...);
int main(int argc, char *argv[]){
   fun(1,10);
   fun(2,"cquestionbank");
   return 0;
}
int fun(int a, ...){
  va_list vl;
  va_start(vl,a);

  if(a==1)
      printf("%d",va_arg(vl,int));
   else
      printf("\n%s",va_arg(vl,char *));
}

how to run vibrate continuously in iphone?

Thankfully, it's not possible to change the duration of the vibration. The only way to trigger the vibration is to play the kSystemSoundID_Vibrate as you have. If you really want to though, what you can do is to repeat the vibration indefinitely, resulting in a pulsing vibration effect instead of a long continuous one. To do this, you need to register a callback function that will get called when the vibration sound that you play is complete:

 AudioServicesAddSystemSoundCompletion (
        kSystemSoundID_Vibrate,
        NULL,
        NULL,
        MyAudioServicesSystemSoundCompletionProc,
        NULL
    );
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

Then you define your callback function to replay the vibrate sound again:

#pragma mark AudioService callback function prototypes
void MyAudioServicesSystemSoundCompletionProc (
   SystemSoundID  ssID,
   void           *clientData
);

#pragma mark AudioService callback function implementation

// Callback that gets called after we finish buzzing, so we 
// can buzz a second time.
void MyAudioServicesSystemSoundCompletionProc (
   SystemSoundID  ssID,
   void           *clientData
) {
  if (iShouldKeepBuzzing) { // Your logic here...
      AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); 
  } else {
      //Unregister, so we don't get called again...
      AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate);
  }  
}

Download File to server from URL

  1. Create a folder called "downloads" in destination server
  2. Save [this code] into .php file and run in destination server

Downloader :

<html>
<form method="post">
<input name="url" size="50" />
<input name="submit" type="submit" />
</form>
<?php
    // maximum execution time in seconds
    set_time_limit (24 * 60 * 60);

    if (!isset($_POST['submit'])) die();

    // folder to save downloaded files to. must end with slash
    $destination_folder = 'downloads/';

    $url = $_POST['url'];
    $newfname = $destination_folder . basename($url);

    $file = fopen ($url, "rb");
    if ($file) {
      $newf = fopen ($newfname, "wb");

      if ($newf)
      while(!feof($file)) {
        fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
      }
    }

    if ($file) {
      fclose($file);
    }

    if ($newf) {
      fclose($newf);
    }
?>
</html> 

Do you need to dispose of objects and set them to null?

Always call dispose. It is not worth the risk. Big managed enterprise applications should be treated with respect. No assumptions can be made or else it will come back to bite you.

Don't listen to leppie.

A lot of objects don't actually implement IDisposable, so you don't have to worry about them. If they genuinely go out of scope they will be freed automatically. Also I have never come across the situation where I have had to set something to null.

One thing that can happen is that a lot of objects can be held open. This can greatly increase the memory usage of your application. Sometimes it is hard to work out whether this is actually a memory leak, or whether your application is just doing a lot of stuff.

Memory profile tools can help with things like that, but it can be tricky.

In addition always unsubscribe from events that are not needed. Also be careful with WPF binding and controls. Not a usual situation, but I came across a situation where I had a WPF control that was being bound to an underlying object. The underlying object was large and took up a large amount of memory. The WPF control was being replaced with a new instance, and the old one was still hanging around for some reason. This caused a large memory leak.

In hindsite the code was poorly written, but the point is that you want to make sure that things that are not used go out of scope. That one took a long time to find with a memory profiler as it is hard to know what stuff in memory is valid, and what shouldn't be there.

What is the C# Using block and why should I use it?

It is really just some syntatic sugar that does not require you to explicity call Dispose on members that implement IDisposable.

How to loop over files in directory and change path and add suffix to filename

Sorry for necromancing the thread, but whenever you iterate over files by globbing, it's good practice to avoid the corner case where the glob does not match (which makes the loop variable expand to the (un-matching) glob pattern string itself).

For example:

for filename in Data/*.txt; do
    [ -e "$filename" ] || continue
    # ... rest of the loop body
done

Reference: Bash Pitfalls

Show hide divs on click in HTML and CSS without jQuery

Using display:none is not SEO-friendly. The following way allows the hidden content to be searchable. Adding the transition-delay ensures any links included in the hidden content is clickable.

.collapse > p{
cursor: pointer;
display: block;
}

.collapse:focus{
outline: none;
}

.collapse > div {
height: 0;
width: 0;
overflow: hidden;
transition-delay: 0.3s;
}

.collapse:focus div{
display: block; 
height: 100%;
width: 100%;
overflow: auto;
}

<div class="collapse" tabindex="1">
<p>Question 1</p>
<div>
  <p>Visit <a href="https://stackoverflow.com/">Stack Overflow</a></p>
</div>
</div>
<div class="collapse" tabindex="2">
<p>Question 2</p>
<div>
  <p>Visit <a href="https://stackoverflow.com/">Stack Overflow</a></p>
</div>
</div> 

HTML/CSS Making a textbox with text that is grayed out, and disappears when I click to enter info, how?

This is an elaborate version, to help you understand

function setVolatileBehavior(elem, onColor, offColor, promptText){ //changed spelling of function name to be the same as name used at invocation below
elem.addEventListener("change", function(){
    if (document.activeElement == elem && elem.value==promptText){
        elem.value='';
        elem.style.color = onColor;
    }
    else if (elem.value==''){
        elem.value=promptText;
        elem.style.color = offColor;
    }
});
elem.addEventListener("blur", function(){
    if (document.activeElement == elem && elem.value==promptText){
        elem.value='';
        elem.style.color = onColor;
    }
    else if (elem.value==''){
        elem.value=promptText;
        elem.style.color = offColor;
    }
});
elem.addEventListener("focus", function(){
    if (document.activeElement == elem && elem.value==promptText){
        elem.value='';
        elem.style.color = onColor;
    }
    else if (elem.value==''){
        elem.value=promptText;
        elem.style.color = offColor;
    }
});
elem.value=promptText;
elem.style.color=offColor;
}

Use like this:

setVolatileBehavior(document.getElementById('yourElementID'),'black','gray','Name');

CSS center content inside div

To center a div, set it's width to some value and add margin: auto.

#partners .wrap {
    width: 655px;
    margin: auto;
}

EDIT, you want to center the div contents, not the div itself. You need to change display property of h2, ul and li to inline, and remove the float: left.

#partners li, ul, h2 {
    display: inline;
    float: none;
}

Then, they will be layed out like normal text elements, and aligned according to text-align property of their container, which is what you want.

How can I configure my makefile for debug and release builds?

If by configure release/build, you mean you only need one config per makefile, then it is simply a matter and decoupling CC and CFLAGS:

CFLAGS=-DDEBUG
#CFLAGS=-O2 -DNDEBUG
CC=g++ -g3 -gdwarf2 $(CFLAGS)

Depending on whether you can use gnu makefile, you can use conditional to make this a bit fancier, and control it from the command line:

DEBUG ?= 1
ifeq ($(DEBUG), 1)
    CFLAGS =-DDEBUG
else
    CFLAGS=-DNDEBUG
endif

.o: .c
    $(CC) -c $< -o $@ $(CFLAGS)

and then use:

make DEBUG=0
make DEBUG=1

If you need to control both configurations at the same time, I think it is better to have build directories, and one build directory / config.

Why not use tables for layout in HTML?

I'd like to add that div-based layouts are easer to mantain, evolve, and refactor. Just some changes in the CSS to reorder elements and it is done. From my experience, redesign a layout that uses tables is a nightmare (more if there are nested tables).

Your code also has a meaning from a semantic point of view.

Change default text in input type="file"?

<button class="styleClass" onclick="document.getElementById('getFile').click()">Your text here</button>
<input type='file' id="getFile" style="display:none">

This is still the best so far

jquery function setInterval

try this declare the function outside the ready event.

    $(document).ready(function(){    
       setInterval(swapImages(),1000); 
    });


    function swapImages(){

    var active = $('.active'); 
    var next = ($('.active').next().length > 0) ? $('.active').next() :         $('#siteNewsHead img:first');
    active.removeClass('active');
    next.addClass('active');
}

How to see indexes for a database or table in MySQL?

To check all disabled indexes on db

SELECT INDEX_SCHEMA, COLUMN_NAME, COMMENT 
FROM information_schema.statistics
WHERE table_schema = 'mydb'
AND COMMENT = 'disabled'

equals vs Arrays.equals in Java

Look inside the implementation of the two methods to understand them deeply:

array1.equals(array2);
/**
 * Indicates whether some other object is "equal to" this one.
 * <p>
 * The {@code equals} method implements an equivalence relation
 * on non-null object references:
 * <ul>
 * <li>It is <i>reflexive</i>: for any non-null reference value
 *     {@code x}, {@code x.equals(x)} should return
 *     {@code true}.
 * <li>It is <i>symmetric</i>: for any non-null reference values
 *     {@code x} and {@code y}, {@code x.equals(y)}
 *     should return {@code true} if and only if
 *     {@code y.equals(x)} returns {@code true}.
 * <li>It is <i>transitive</i>: for any non-null reference values
 *     {@code x}, {@code y}, and {@code z}, if
 *     {@code x.equals(y)} returns {@code true} and
 *     {@code y.equals(z)} returns {@code true}, then
 *     {@code x.equals(z)} should return {@code true}.
 * <li>It is <i>consistent</i>: for any non-null reference values
 *     {@code x} and {@code y}, multiple invocations of
 *     {@code x.equals(y)} consistently return {@code true}
 *     or consistently return {@code false}, provided no
 *     information used in {@code equals} comparisons on the
 *     objects is modified.
 * <li>For any non-null reference value {@code x},
 *     {@code x.equals(null)} should return {@code false}.
 * </ul>
 * <p>
 * The {@code equals} method for class {@code Object} implements
 * the most discriminating possible equivalence relation on objects;
 * that is, for any non-null reference values {@code x} and
 * {@code y}, this method returns {@code true} if and only
 * if {@code x} and {@code y} refer to the same object
 * ({@code x == y} has the value {@code true}).
 * <p>
 * Note that it is generally necessary to override the {@code hashCode}
 * method whenever this method is overridden, so as to maintain the
 * general contract for the {@code hashCode} method, which states
 * that equal objects must have equal hash codes.
 *
 * @param   obj   the reference object with which to compare.
 * @return  {@code true} if this object is the same as the obj
 *          argument; {@code false} otherwise.
 * @see     #hashCode()
 * @see     java.util.HashMap
 */
public boolean equals(Object obj) {
    return (this == obj);
}

while:

Arrays.equals(array1, array2);
/**
 * Returns <tt>true</tt> if the two specified arrays of Objects are
 * <i>equal</i> to one another.  The two arrays are considered equal if
 * both arrays contain the same number of elements, and all corresponding
 * pairs of elements in the two arrays are equal.  Two objects <tt>e1</tt>
 * and <tt>e2</tt> are considered <i>equal</i> if <tt>(e1==null ? e2==null
 * : e1.equals(e2))</tt>.  In other words, the two arrays are equal if
 * they contain the same elements in the same order.  Also, two array
 * references are considered equal if both are <tt>null</tt>.<p>
 *
 * @param a one array to be tested for equality
 * @param a2 the other array to be tested for equality
 * @return <tt>true</tt> if the two arrays are equal
 */
public static boolean equals(Object[] a, Object[] a2) {
    if (a==a2)
        return true;
    if (a==null || a2==null)
        return false;

    int length = a.length;
    if (a2.length != length)
        return false;

    for (int i=0; i<length; i++) {
        Object o1 = a[i];
        Object o2 = a2[i];
        if (!(o1==null ? o2==null : o1.equals(o2)))
            return false;
    }

    return true;
}

Tesseract running error

No previous solution worked for me.

I've installed both by apt-get and manually downloading the tessdata, moved around /usr and so on and no one worked even if i exported the variable thousand times.

Finally, on a last try before start to cry i've tried to pass the path directly to the instance of Tesseract().

In Python: tr = Tesseract("/usr/local/share/tesseract-ocr/") and now it works. To clarify, im using tesserwrap module.

How to .gitignore all files/folder in a folder, but not the folder itself?

Put this .gitignore into the folder, then git add .gitignore.

*
*/
!.gitignore

The * line tells git to ignore all files in the folder, but !.gitignore tells git to still include the .gitignore file. This way, your local repository and any other clones of the repository all get both the empty folder and the .gitignore it needs.

Edit: May be obvious but also add */ to the .gitignore to also ignore subfolders.

AngularJS : When to use service instead of factory

Factory and Service are the most commonly used method. The only difference between them is that the Service method works better for objects that need inheritance hierarchy, while the Factory can produce JavaScript primitives and functions.

The Provider function is the core method and all the other ones are just syntactic sugar on it. You need it only if you are building a reusable piece of code that needs global configuration.

There are five methods to create services: Value, Factory, Service, Provider and Constant. You can learn more about this here angular service, this article explain all this methods with practical demo examples.

.

TypeError: 'NoneType' object is not iterable in Python

Explanation of error: 'NoneType' object is not iterable

In python2, NoneType is the type of None. In Python3 NoneType is the class of None, for example:

>>> print(type(None))     #Python2
<type 'NoneType'>         #In Python2 the type of None is the 'NoneType' type.

>>> print(type(None))     #Python3
<class 'NoneType'>        #In Python3, the type of None is the 'NoneType' class.

Iterating over a variable that has value None fails:

for a in None:
    print("k")     #TypeError: 'NoneType' object is not iterable

Python methods return NoneType if they don't return a value:

def foo():
    print("k")
a, b = foo()      #TypeError: 'NoneType' object is not iterable

You need to check your looping constructs for NoneType like this:

a = None 
print(a is None)              #prints True
print(a is not None)          #prints False
print(a == None)              #prints True
print(a != None)              #prints False
print(isinstance(a, object))  #prints True
print(isinstance(a, str))     #prints False

Guido says only use is to check for None because is is more robust to identity checking. Don't use equality operations because those can spit bubble-up implementationitis of their own. Python's Coding Style Guidelines - PEP-008

NoneTypes are Sneaky, and can sneak in from lambdas:

import sys
b = lambda x : sys.stdout.write("k") 
for a in b(10): 
    pass            #TypeError: 'NoneType' object is not iterable 

NoneType is not a valid keyword:

a = NoneType     #NameError: name 'NoneType' is not defined

Concatenation of None and a string:

bar = "something"
foo = None
print foo + bar    #TypeError: cannot concatenate 'str' and 'NoneType' objects

What's going on here?

Python's interpreter converted your code to pyc bytecode. The Python virtual machine processed the bytecode, it encountered a looping construct which said iterate over a variable containing None. The operation was performed by invoking the __iter__ method on the None.

None has no __iter__ method defined, so Python's virtual machine tells you what it sees: that NoneType has no __iter__ method.

This is why Python's duck-typing ideology is considered bad. The programmer does something completely reasonable with a variable and at runtime it gets contaminated by None, the python virtual machine attempts to soldier on, and pukes up a bunch of unrelated nonsense all over the carpet.

Java or C++ doesn't have these problems because such a program wouldn't be allowed to compile since you haven't defined what to do when None occurs. Python gives the programmer lots of rope to hang himself by allowing you to do lots of things that should cannot be expected to work under exceptional circumstances. Python is a yes-man, saying yes-sir when it out to be stopping you from harming yourself, like Java and C++ does.

How to solve this java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream?

You will have to download file from here https://commons.apache.org/proper/commons-io/download_io.cgi and select https://prnt.sc/tk5ewt

Now, Next add this downloaded files into your project:

Right click to your project ->Build path->Configure BuidPath -> https://prnt.sc/tk5d93

How to change a <select> value from JavaScript

document.getElementById("select").selectedIndex = 0 will work

When are you supposed to use escape instead of encodeURI / encodeURIComponent?

encodeURIComponent doesn't encode -_.!~*'(), causing problem in posting data to php in xml string.

For example:
<xml><text x="100" y="150" value="It's a value with single quote" /> </xml>

General escape with encodeURI
%3Cxml%3E%3Ctext%20x=%22100%22%20y=%22150%22%20value=%22It's%20a%20value%20with%20single%20quote%22%20/%3E%20%3C/xml%3E

You can see, single quote is not encoded. To resolve issue I created two functions to solve issue in my project, for Encoding URL:

function encodeData(s:String):String{
    return encodeURIComponent(s).replace(/\-/g, "%2D").replace(/\_/g, "%5F").replace(/\./g, "%2E").replace(/\!/g, "%21").replace(/\~/g, "%7E").replace(/\*/g, "%2A").replace(/\'/g, "%27").replace(/\(/g, "%28").replace(/\)/g, "%29");
}

For Decoding URL:

function decodeData(s:String):String{
    try{
        return decodeURIComponent(s.replace(/\%2D/g, "-").replace(/\%5F/g, "_").replace(/\%2E/g, ".").replace(/\%21/g, "!").replace(/\%7E/g, "~").replace(/\%2A/g, "*").replace(/\%27/g, "'").replace(/\%28/g, "(").replace(/\%29/g, ")"));
    }catch (e:Error) {
    }
    return "";
}

Failed to instantiate module error in Angular js

For me the solution was fixing a syntax error:

removing a unwanted semi colon in the angular.module function

Oracle Convert Seconds to Hours:Minutes:Seconds

For greater than 24 hours you can include days with the following query. The returned format is days:hh24:mi:ss

Query:
select trunc(trunc(sysdate) + numtodsinterval(9999999, 'second')) - trunc(sysdate) || ':' || to_char(trunc(sysdate) + numtodsinterval(9999999, 'second'), 'hh24:mi:ss') from dual;

Output:
115:17:46:39

Creating java date object from year,month,day

That's my favorite way prior to Java 8:

Date date = new GregorianCalendar(year, month - 1, day).getTime();

I'd say this is a cleaner approach than:

calendar.set(year, month - 1, day, 0, 0);

How to list all the available keyspaces in Cassandra?

Apart from above method, if you have opscenter installed,

  1. Go to data tab > there you will see all keyspcaces created by you and some system keyspaces.
  2. You can see all tables under individual keyspaces and also replicator factor for keyspace.

for more details check below link. https://docs.datastax.com/en/opscenter/6.1/opsc/online_help/opscDataModelingManagingKeyspace_t.html

How to get selected option using Selenium WebDriver with Java

var option = driver.FindElement(By.Id("employmentType"));
        var selectElement = new SelectElement(option);
        Task.Delay(3000).Wait();
        selectElement.SelectByIndex(2);
        Console.Read();

jQuery select change event get selected option

See official API documentation https://api.jquery.com/selected-selector/

This good works:

$( "select" ).on('change',function() {
  var str = "";
  // For multiple choice
  $( "select option:selected" ).each(function() {
    str += $( this ).val() + " "; 
  });
});

and

$( "select" ).on('change',function() {
  // For unique choice
  var selVal = $( "select option:selected" ).val(); 
});

and be easy for unique choice

var SelVal = $( "#idSelect option:selected" ).val();

Is there a CSS selector for text nodes?

You cannot target text nodes with CSS. I'm with you; I wish you could... but you can't :(

If you don't wrap the text node in a <span> like @Jacob suggests, you could instead give the surrounding element padding as opposed to margin:

HTML

<p id="theParagraph">The text node!</p>

CSS

p#theParagraph
{
    border: 1px solid red;
    padding-bottom: 10px;
}

How to align flexbox columns left and right?

Another option is to add another tag with flex: auto style in between your tags that you want to fill in the remaining space.

https://jsfiddle.net/tsey5qu4/

The HTML:

<div class="parent">
  <div class="left">Left</div>
  <div class="fill-remaining-space"></div>
  <div class="right">Right</div>
</div>

The CSS:

.fill-remaining-space {
  flex: auto;
}

This is equivalent to flex: 1 1 auto, which absorbs any extra space along the main axis.

Using the Underscore module with Node.js

Note: The following only works for the next line of code, and only due to a coincidence.

With Lodash,

require('lodash');
_.isArray([]); // true

No var _ = require('lodash') since Lodash mysteriously sets this value globally when required.

File count from a folder

Try following code to get count of files in the folder

string strDocPath = Server.MapPath('Enter your path here'); 
int docCount = Directory.GetFiles(strDocPath, "*", 
SearchOption.TopDirectoryOnly).Length;

How can I use interface as a C# generic type constraint?

If possible, I went with a solution like this. It only works if you want several specific interfaces (e.g. those you have source access to) to be passed as a generic parameter, not any.

  • I let my interfaces, which came into question, inherit an empty interface IInterface.
  • I constrained the generic T parameter to be of IInterface

In source, it looks like this:

  • Any interface you want to be passed as the generic parameter:

    public interface IWhatever : IInterface
    {
        // IWhatever specific declarations
    }
    
  • IInterface:

    public interface IInterface
    {
        // Nothing in here, keep moving
    }
    
  • The class on which you want to put the type constraint:

    public class WorldPeaceGenerator<T> where T : IInterface
    {
        // Actual world peace generating code
    }
    

How do I get the current time zone of MySQL?

You just need to restart mysqld after altering timezone of System..

The Global time zone of MySQL takes timezone of System. When you change any such attribute of system, you just need a restart of Mysqld.

Get MAC address using shell script

You can do as follows

ifconfig <Interface ex:eth0,eth1> | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'

Also you can get MAC for all interface as follows

cat /sys/class/net/*/address

For particular interface like for eth0

cat /sys/class/net/eth0/address

Finding the next available id in MySQL

I don't think you can ever be sure on the next id, because someone might insert a new row just after you asked for the next id. You would at least need a transaction, and if I'm not mistaken you can only get the actual id used after inserting it, at least that is the common way of handling it -- see http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html

Quick Way to Implement Dictionary in C

Additionally, you can use Google CityHash:

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

#include <byteswap.h>

#include "city.h"

void swap(uint32* a, uint32* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

#define PERMUTE3(a, b, c) swap(&a, &b); swap(&a, &c);

// Magic numbers for 32-bit hashing.  Copied from Murmur3.
static const uint32 c1 = 0xcc9e2d51;
static const uint32 c2 = 0x1b873593;

static uint32 UNALIGNED_LOAD32(const char *p) {
  uint32 result;
  memcpy(&result, p, sizeof(result));
  return result;
}

static uint32 Fetch32(const char *p) {
  return UNALIGNED_LOAD32(p);
}

// A 32-bit to 32-bit integer hash copied from Murmur3.
static uint32 fmix(uint32 h)
{
  h ^= h >> 16;
  h *= 0x85ebca6b;
  h ^= h >> 13;
  h *= 0xc2b2ae35;
  h ^= h >> 16;
  return h;
}

static uint32 Rotate32(uint32 val, int shift) {
  // Avoid shifting by 32: doing so yields an undefined result.
  return shift == 0 ? val : ((val >> shift) | (val << (32 - shift)));
}

static uint32 Mur(uint32 a, uint32 h) {
  // Helper from Murmur3 for combining two 32-bit values.
  a *= c1;
  a = Rotate32(a, 17);
  a *= c2;
  h ^= a;
  h = Rotate32(h, 19);
  return h * 5 + 0xe6546b64;
}

static uint32 Hash32Len13to24(const char *s, size_t len) {
  uint32 a = Fetch32(s - 4 + (len >> 1));
  uint32 b = Fetch32(s + 4);
  uint32 c = Fetch32(s + len - 8);
  uint32 d = Fetch32(s + (len >> 1));
  uint32 e = Fetch32(s);
  uint32 f = Fetch32(s + len - 4);
  uint32 h = len;

  return fmix(Mur(f, Mur(e, Mur(d, Mur(c, Mur(b, Mur(a, h)))))));
}

static uint32 Hash32Len0to4(const char *s, size_t len) {
  uint32 b = 0;
  uint32 c = 9;
  for (size_t i = 0; i < len; i++) {
    signed char v = s[i];
    b = b * c1 + v;
    c ^= b;
  }
  return fmix(Mur(b, Mur(len, c)));
}

static uint32 Hash32Len5to12(const char *s, size_t len) {
  uint32 a = len, b = len * 5, c = 9, d = b;
  a += Fetch32(s);
  b += Fetch32(s + len - 4);
  c += Fetch32(s + ((len >> 1) & 4));
  return fmix(Mur(c, Mur(b, Mur(a, d))));
}

uint32 CityHash32(const char *s, size_t len) {
  if (len <= 24) {
    return len <= 12 ?
        (len <= 4 ? Hash32Len0to4(s, len) : Hash32Len5to12(s, len)) :
        Hash32Len13to24(s, len);
  }

  // len > 24
  uint32 h = len, g = c1 * len, f = g;
  uint32 a0 = Rotate32(Fetch32(s + len - 4) * c1, 17) * c2;
  uint32 a1 = Rotate32(Fetch32(s + len - 8) * c1, 17) * c2;
  uint32 a2 = Rotate32(Fetch32(s + len - 16) * c1, 17) * c2;
  uint32 a3 = Rotate32(Fetch32(s + len - 12) * c1, 17) * c2;
  uint32 a4 = Rotate32(Fetch32(s + len - 20) * c1, 17) * c2;
  h ^= a0;
  h = Rotate32(h, 19);
  h = h * 5 + 0xe6546b64;
  h ^= a2;
  h = Rotate32(h, 19);
  h = h * 5 + 0xe6546b64;
  g ^= a1;
  g = Rotate32(g, 19);
  g = g * 5 + 0xe6546b64;
  g ^= a3;
  g = Rotate32(g, 19);
  g = g * 5 + 0xe6546b64;
  f += a4;
  f = Rotate32(f, 19);
  f = f * 5 + 0xe6546b64;
  size_t iters = (len - 1) / 20;
  do {
    uint32 a0 = Rotate32(Fetch32(s) * c1, 17) * c2;
    uint32 a1 = Fetch32(s + 4);
    uint32 a2 = Rotate32(Fetch32(s + 8) * c1, 17) * c2;
    uint32 a3 = Rotate32(Fetch32(s + 12) * c1, 17) * c2;
    uint32 a4 = Fetch32(s + 16);
    h ^= a0;
    h = Rotate32(h, 18);
    h = h * 5 + 0xe6546b64;
    f += a1;
    f = Rotate32(f, 19);
    f = f * c1;
    g += a2;
    g = Rotate32(g, 18);
    g = g * 5 + 0xe6546b64;
    h ^= a3 + a1;
    h = Rotate32(h, 19);
    h = h * 5 + 0xe6546b64;
    g ^= a4;
    g = bswap_32(g) * 5;
    h += a4 * 5;
    h = bswap_32(h);
    f += a0;
    PERMUTE3(f, h, g);
    s += 20;
  } while (--iters != 0);
  g = Rotate32(g, 11) * c1;
  g = Rotate32(g, 17) * c1;
  f = Rotate32(f, 11) * c1;
  f = Rotate32(f, 17) * c1;
  h = Rotate32(h + g, 19);
  h = h * 5 + 0xe6546b64;
  h = Rotate32(h, 17) * c1;
  h = Rotate32(h + f, 19);
  h = h * 5 + 0xe6546b64;
  h = Rotate32(h, 17) * c1;
  return h;
}

Updating the value of data attribute using jQuery

$('.toggle img').each(function(index) { 
    if($(this).attr('data-id') == '4')
    {
        $(this).attr('data-block', 'something');
        $(this).attr('src', 'something.jpg');
    }
});

or

$('.toggle img[data-id="4"]').attr('data-block', 'something');
$('.toggle img[data-id="4"]').attr('src', 'something.jpg');

Replace new line/return with space using regex

I found this.

String newString = string.replaceAll("\n", " ");

Although, as you have a double line, you will get a double space. I guess you could then do another replace all to replace double spaces with a single one.

If that doesn't work try doing:

string.replaceAll(System.getProperty("line.separator"), " ");

If I create lines in "string" by using "\n" I had to use "\n" in the regex. If I used System.getProperty() I had to use that.

What is the difference between Linear search and Binary search?

For a clear understanding, please take a look at my codepen implementations https://codepen.io/serdarsenay/pen/XELWqN

Biggest difference is the need to sort your sample before applying binary search, therefore for most "normal sized" (meaning to be argued) samples will be quicker to search with a linear search algorithm.

Here is the javascript code, for html and css and full running example please refer to above codepen link.

var unsortedhaystack = [];
var haystack = [];
function init() {
  unsortedhaystack = document.getElementById("haystack").value.split(' ');
}
function sortHaystack() {
  var t = timer('sort benchmark');
  haystack = unsortedhaystack.sort();
  t.stop();
}

var timer = function(name) {
    var start = new Date();
    return {
        stop: function() {
            var end  = new Date();
            var time = end.getTime() - start.getTime();
            console.log('Timer:', name, 'finished in', time, 'ms');
        }
    }
};

function lineerSearch() {
  init();
  var t = timer('lineerSearch benchmark');
  var input = this.event.target.value;
  for(var i = 0;i<unsortedhaystack.length - 1;i++) {
    if (unsortedhaystack[i] === input) {
      document.getElementById('result').innerHTML = 'result is... "' + unsortedhaystack[i] + '", on index: ' + i + ' of the unsorted array. Found' + ' within ' + i + ' iterations';
      console.log(document.getElementById('result').innerHTML);
      t.stop(); 
      return unsortedhaystack[i]; 
    }
  }
}

function binarySearch () {
  init();
  sortHaystack();
  var t = timer('binarySearch benchmark');
  var firstIndex = 0;
  var lastIndex = haystack.length-1;
  var input = this.event.target.value;

  //currently point in the half of the array
  var currentIndex = (haystack.length-1)/2 | 0;
  var iterations = 0;

  while (firstIndex <= lastIndex) {
    currentIndex = (firstIndex + lastIndex)/2 | 0;
    iterations++;
    if (haystack[currentIndex]  < input) {
      firstIndex = currentIndex + 1;
      //console.log(currentIndex + " added, fI:"+firstIndex+", lI: "+lastIndex);
    } else if (haystack[currentIndex] > input) {
      lastIndex = currentIndex - 1;
      //console.log(currentIndex + " substracted, fI:"+firstIndex+", lI: "+lastIndex);
    } else {
      document.getElementById('result').innerHTML = 'result is... "' + haystack[currentIndex] + '", on index: ' + currentIndex + ' of the sorted array. Found' + ' within ' + iterations + ' iterations';
      console.log(document.getElementById('result').innerHTML);
      t.stop(); 
      return true;
    }
  }
}

How to dynamically build a JSON object with Python?

  myjson={}
  myjson["Country"]= {"KR": { "id": "220", "name": "South Korea"}}
  myjson["Creative"]= {
                    "1067405": {
                        "id": "1067405",
                        "url": "https://cdn.gowadogo.com/559d1ba1-8d50-4c7f-b3f5-d80f918006e0.jpg"
                    },
                    "1067406": {
                        "id": "1067406",
                        "url": "https://cdn.gowadogo.com/3799a70d-339c-4ecb-bc1f-a959dde675b8.jpg"
                    },
                    "1067407": {
                        "id": "1067407",
                        "url": "https://cdn.gowadogo.com/180af6a5-251d-4aa9-9cd9-51b2fc77d0c6.jpg"
                    }
                }
   myjson["Offer"]= {
                    "advanced_targeting_enabled": "f",
                    "category_name": "E-commerce/ Shopping",
                    "click_lifespan": "168",
                    "conversion_cap": "50",
                    "currency": "USD",
                    "default_payout": "1.5"
                }

   json_data = json.dumps(myjson)

   #reverse back into a json

   paths=[]
   def walk_the_tree(inputDict,suffix=None):
       for key, value in inputDict.items():
            if isinstance(value, dict):
                if suffix==None:
                    suffix=key
                else:
                    suffix+=":"+key

                walk_the_tree(value,suffix)
            else:
                paths.append(suffix+":"+key+":"+value)
 walk_the_tree(myjson)
 print(paths)  

 #split and build your nested dictionary
 json_specs = {}
 for path in paths:
     parts=path.split(':')
     value=(parts[-1])
     d=json_specs
     for p in parts[:-1]:
         if p==parts[-2]:
             d = d.setdefault(p,value)
         else:
             d = d.setdefault(p,{})
    
 print(json_specs)        

 Paths:
 ['Country:KR:id:220', 'Country:KR:name:South Korea', 'Country:Creative:1067405:id:1067405', 'Country:Creative:1067405:url:https://cdn.gowadogo.com/559d1ba1-8d50-4c7f-b3f5-d80f918006e0.jpg', 'Country:Creative:1067405:1067406:id:1067406', 'Country:Creative:1067405:1067406:url:https://cdn.gowadogo.com/3799a70d-339c-4ecb-bc1f-a959dde675b8.jpg', 'Country:Creative:1067405:1067406:1067407:id:1067407', 'Country:Creative:1067405:1067406:1067407:url:https://cdn.gowadogo.com/180af6a5-251d-4aa9-9cd9-51b2fc77d0c6.jpg', 'Country:Creative:Offer:advanced_targeting_enabled:f', 'Country:Creative:Offer:category_name:E-commerce/ Shopping', 'Country:Creative:Offer:click_lifespan:168', 'Country:Creative:Offer:conversion_cap:50', 'Country:Creative:Offer:currency:USD', 'Country:Creative:Offer:default_payout:1.5']

<meta charset="utf-8"> vs <meta http-equiv="Content-Type">

Use <meta charset="utf-8" /> for web browsers when using HTML5.

Use <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> when using HTML4 or XHTML, or for outdated dom parsers, like DOMDocument in php 5.3

Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'

updating web.config with the following assembly binding resolved the issue 
<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">     
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed"
                culture="neutral" />
        <bindingRedirect oldVersion="4.5.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>

With jQuery, how do I capitalize the first letter of a text field while the user is still editing that field?

    .first-character{
        font-weight:bold;
        color:#F00;
        text-transform:capitalize;
   }
.capital-text{
    text-transform:uppercase;
    }

JavaScript property access: dot notation vs. brackets?

Let me add some more use case of the square-bracket notation. If you want to access a property say x-proxy in a object, then - will be interpreted wrongly. Their are some other cases too like space, dot, etc., where dot operation will not help you. Also if u have the key in a variable then only way to access the value of the key in a object is by bracket notation. Hope you get some more context.

PDF to image using Java

In Ghost4J library (http://ghost4j.sourceforge.net), since version 0.4.0 you can use a SimpleRenderer to do the job with few lines of code:

  1. Load PDF or PS file (use PSDocument class for that):

        PDFDocument document = new PDFDocument();
        document.load(new File("input.pdf"));
    
  2. Create the renderer

        SimpleRenderer renderer = new SimpleRenderer();
    
        // set resolution (in DPI)
        renderer.setResolution(300);
    
  3. Render

        List<Image> images = renderer.render(document);
    

Then you can do what you want with your image objects, for example, you can write them as PNG like this:

            for (int i = 0; i < images.size(); i++) {
                ImageIO.write((RenderedImage) images.get(i), "png", new File((i + 1) + ".png"));
            }

Note: Ghost4J uses the native Ghostscript C API so you need to have a Ghostscript installed on your box.

I hope it will help you :)

failed to load ad : 3

Your ad units are not displaying ads because you haven't yet verified your address (PIN).

Maybe it helps to others, i received this notification on my AdSense account. enter image description here

Omitting one Setter/Getter in Lombok

User the below code for omit/excludes from creating setter and getter. value key should use inside @Getter and @Setter.

@Getter(value = AccessLevel.NONE)
@Setter(value = AccessLevel.NONE)
private int mySecret;

Spring boot 2.3 version, this is working well.

Effective method to hide email from spam bots

Here is my working version:


Create somewhere a container with a fallback text:

<div id="knock_knock">Activate JavaScript, please.</div>

And add at the bottom of the DOM (w.r.t. the rendering) the following snippet:

<script>
  (function(d,id,lhs,rhs){
    d.getElementById(id).innerHTML = "<a rel=\"nofollow\" href=\"mailto"+":"+lhs+"@"+rhs+"\">"+"Mail"+"<\/a>";
  })(window.document, "knock_knock", "your.name", "example.com");
</script>

It adds the generated hyperlink to the specified container:

<div id="knock_knock"><a rel="nofollow" href="[email protected]">Mail</a></div>

In addition here is a minified version:

<script>(function(d,i,l,r){d.getElementById(i).innerHTML="<a rel=\"nofollow\" href=\"mailto"+":"+l+"@"+r+"\">"+"Mail"+"<\/a>";})(window.document,"knock_knock","your.name","example.com");</script>

href image link download on click

<a download="custom-filename.jpg" href="/path/to/image" title="ImageName">
    <img alt="ImageName" src="/path/to/image">
</a>

It's not yet fully supported caniuse, but you can use with modernizr (under Non-core detects) to check the support of the browser.

Round a divided number in Bash

To round up you can use modulus.

The second part of the equation will add to True if there's a remainder. (True = 1; False = 0)

ex: 3/2

answer=$(((3 / 2) + (3 % 2 > 0)))
echo $answer
2

ex: 100 / 2

answer=$(((100 / 2) + (100 % 2 > 0)))
echo $answer
50

ex: 100 / 3

answer=$(((100 / 3) + (100 % 3 > 0)))
echo $answer
34

How do I execute .js files locally in my browser?

If you're using Google Chrome you can use the Chrome Dev Editor: https://github.com/dart-lang/chromedeveditor

Sequence contains no elements?

This will solve the problem,

var blogPosts = (from p in dc.BlogPosts
             where p.BlogPostID == ID
             select p);
if(blogPosts.Any())
{
  var post = post.Single();
}

How to get the current date without the time?

DateTime.Now.ToString("dd/MM/yyyy");

Add a pipe separator after items in an unordered list unless that item is the last on a line

Slightly modified SCSS version which gives you control of the pipe | size and will eliminate padding from first and last list items while respects borders.


$pipe-list-height: 20px;
$pipe-list-padding: 15px;

.pipe-list {
    position: relative;
    overflow: hidden;
    height: $pipe-list-height;

    > ul {
        display: flex;
        flex-direction: row;

        > li {
            position: relative;
            padding: 0 $pipe-list-padding;

            &:after {
                content: " ";
                position: absolute;
                border-right: 1px solid gray;
                top: 10%;
                right: 0;
                height: 75%;
                margin-top: auto;
                margin-bottom: auto;
            }

            &:first-child {
                padding-left: 0;
            }

            &:last-child {
                padding-right: 0;

                &:after {
                    border-right: none;
                }
            }
        }
    }
}
<div class="pipe-list">
  <ul>
    <li>Link</li>
    <li>Link</li>
    <li>Link</li>
  </ul>
</div>

undefined reference to WinMain@16 (codeblocks)

You should create a new project in Code::Blocks, and make sure it's 'Console Application'.

Add your .cpp files into the project so they are all compiled and linked together.

jQuery UI " $("#datepicker").datepicker is not a function"

If you think that there is a conflict you can use jQuery.noConflict() in your code. Details are in the docs.

REFERENCING MAGIC - SHORTCUTS FOR JQUERY

If you don't like typing the full "jQuery" all the time, there are some alternative shortcuts:

Reassign jQuery to another shortcut var $j = jQuery; (This might be the best approach if you wish to use different libraries) Use the following technique, which allows you to use $ inside of a block of code without permanently overwriting $:

(function($) { /* some code that uses $ */ })(jQuery)

Note: If you use this technique, you will not be able to use Prototype methods inside this capsuled function that expect $ to be Prototype's $, so you're making a choice to use only jQuery in that block. Use the argument to the DOM ready event:

jQuery(function($) { /*some code that uses $ */ });

Note: Again, inside that block you can't use Prototype methods

Thats from the end of the docs and might be useful to you

Java: Add elements to arraylist with FOR loop where element name has increasing number

There's always some reflection hacks that you can adapt. Here is some example, but using a collection would be the solution to your problem (the integers you stick on your variables name is a good hint telling us you should use a collection!).

public class TheClass {

    private int theField= 42;

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

        TheClass c= new TheClass();

        System.out.println(c.getClass().getDeclaredField("theField").get(c));
    }
}

How to Auto resize HTML table cell to fit the text size

You can try this:

HTML

<table>
    <tr>
        <td class="shrink">element1</td>
        <td class="shrink">data</td>
        <td class="shrink">junk here</td>
        <td class="expand">last column</td>
    </tr>
    <tr>
        <td class="shrink">elem</td>
        <td class="shrink">more data</td>
        <td class="shrink">other stuff</td>
        <td class="expand">again, last column</td>
    </tr>
    <tr>
        <td class="shrink">more</td>
        <td class="shrink">of </td>
        <td class="shrink">these</td>
        <td class="expand">rows</td>
    </tr>
</table>

CSS

table {
    border: 1px solid green;
    border-collapse: collapse;
    width:100%;
}

table td {
    border: 1px solid green;
}

table td.shrink {
    white-space:nowrap
}
table td.expand {
    width: 99%
}

Auto height of div

div's will naturally resize in accordance with their content.

If you set no height on your div, it will expand to contain its conent.

An exception to this rule is when the div contains floating elements. If this is the case you'll need to do a bit extra to ensure that the containing div (wrapper) clears the floats.

Here's some ways to do this:

#wrapper{
overflow:hidden;
}

Or

#wrapper:after
{
content:".";
display:block;
clear:both;
visibility:hidden;
}

PHP - Indirect modification of overloaded property

I have run into the same problem as w00, but I didn't had the freedom to rewrite the base functionality of the component in which this problem (E_NOTICE) occured. I've been able to fix the issue using an ArrayObject in stead of the basic type array(). This will return an object, which will defaulty be returned by reference.

regex with space and letters only?

use this expression

var RegExpression = /^[a-zA-Z\s]*$/;  

for more refer this http://tools.netshiftmedia.com

Check if one list contains element from the other

If you want to check if an element exists in a list, use the contains method.

if (list1.contains(Object o))
{
   //do this
}

How can you profile a Python script?

Simplest and quickest way to find where all the time is going.

1. pip install snakeviz

2. python -m cProfile -o temp.dat <PROGRAM>.py

3. snakeviz temp.dat

Draws a pie chart in a browser. Biggest piece is the problem function. Very simple.

CSS media queries: max-width OR max-height

Use a comma to specify two (or more) different rules:

@media screen and (max-width: 995px), 
       screen and (max-height: 700px) {
  ...
}

From https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries

Commas are used to combine multiple media queries into a single rule. Each query in a comma-separated list is treated separately from the others. Thus, if any of the queries in a list is true, the entire media statement returns true. In other words, lists behave like a logical or operator.

calculating number of days between 2 columns of dates in data frame

You could find the difference between dates in columns in a data frame by using the function difftime as follows:

df$diff_in_days<- difftime(df$datevar1 ,df$datevar2 , units = c("days"))

Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock

@jk1 answer is perfect, since @igor Ganapolsky asked, why can't we use Mockito.mock here? i post this answer.

For that we have provide one setter method for myobj and set the myobj value with mocked object.

class MyClass {
    MyInterface myObj;

    public void abc() {
        myObj.myMethodToBeVerified (new String("a"), new String("b"));
    }

    public void setMyObj(MyInterface obj)
    {
        this.myObj=obj;
    }
}

In our Test class, we have to write below code

class MyClassTest {

MyClass myClass = new MyClass();

    @Mock
    MyInterface myInterface;

    @test
    testAbc() {
        myclass.setMyObj(myInterface); //it is good to have in @before method
        myClass.abc();
        verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
     }
}

A TypeScript GUID class?

There is an implementation in my TypeScript utilities based on JavaScript GUID generators.

Here is the code:

_x000D_
_x000D_
class Guid {_x000D_
  static newGuid() {_x000D_
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {_x000D_
      var r = Math.random() * 16 | 0,_x000D_
        v = c == 'x' ? r : (r & 0x3 | 0x8);_x000D_
      return v.toString(16);_x000D_
    });_x000D_
  }_x000D_
}_x000D_
_x000D_
// Example of a bunch of GUIDs_x000D_
for (var i = 0; i < 100; i++) {_x000D_
  var id = Guid.newGuid();_x000D_
  console.log(id);_x000D_
}
_x000D_
_x000D_
_x000D_

Please note the following:

C# GUIDs are guaranteed to be unique. This solution is very likely to be unique. There is a huge gap between "very likely" and "guaranteed" and you don't want to fall through this gap.

JavaScript-generated GUIDs are great to use as a temporary key that you use while waiting for a server to respond, but I wouldn't necessarily trust them as the primary key in a database. If you are going to rely on a JavaScript-generated GUID, I would be tempted to check a register each time a GUID is created to ensure you haven't got a duplicate (an issue that has come up in the Chrome browser in some cases).

Adding a new entry to the PATH variable in ZSH

Actually, using ZSH allows you to use special mapping of environment variables. So you can simply do:

# append
path+=('/home/david/pear/bin')
# or prepend
path=('/home/david/pear/bin' $path)
# export to sub-processes (make it inherited by child processes)
export PATH

For me that's a very neat feature which can be propagated to other variables. Example:

typeset -T LD_LIBRARY_PATH ld_library_path :

How to close a Tkinter window by pressing a Button?

With minimal editing to your code (Not sure if they've taught classes or not in your course), change:

def close_window(root): 
    root.destroy()

to

def close_window(): 
    window.destroy()

and it should work.


Explanation:

Your version of close_window is defined to expect a single argument, namely root. Subsequently, any calls to your version of close_window need to have that argument, or Python will give you a run-time error.

When you created a Button, you told the button to run close_window when it is clicked. However, the source code for Button widget is something like:

# class constructor
def __init__(self, some_args, command, more_args):
    #...
    self.command = command
    #...

# this method is called when the user clicks the button
def clicked(self):
    #...
    self.command() # Button calls your function with no arguments.
    #...

As my code states, the Button class will call your function with no arguments. However your function is expecting an argument. Thus you had an error. So, if we take out that argument, so that the function call will execute inside the Button class, we're left with:

def close_window(): 
    root.destroy()

That's not right, though, either, because root is never assigned a value. It would be like typing in print(x) when you haven't defined x, yet.

Looking at your code, I figured you wanted to call destroy on window, so I changed root to window.

How to hash a string into 8 digits?

Just to complete JJC answer, in python 3.5.3 the behavior is correct if you use hashlib this way:

$ python3 -c '
import hashlib
hash_object = hashlib.sha256(b"Caroline")
hex_dig = hash_object.hexdigest()
print(hex_dig)
'
739061d73d65dcdeb755aa28da4fea16a02b9c99b4c2735f2ebfa016f3e7fded
$ python3 -c '
import hashlib
hash_object = hashlib.sha256(b"Caroline")
hex_dig = hash_object.hexdigest()
print(hex_dig)
'
739061d73d65dcdeb755aa28da4fea16a02b9c99b4c2735f2ebfa016f3e7fded

$ python3 -V
Python 3.5.3

git push: permission denied (public key)

This error happened while using Ubuntu Bash on Windows.

I switched to standard windows cmd prompt, and it worked no error.

This is a workaround as it means you probably need to load the ssh private key in ubuntu environment if you want to use ubuntu.

Is it possible to use a div as content for Twitter's Popover

Another alternate method if you wish to just have look and feel of pop over. Following is the method. Offcourse this is a manual thing, but nicely workable :)

HTML - button

<button class="btn btn-info btn-small" style="margin-right:5px;" id="bg" data-placement='bottom' rel="tooltip" title="Background Image"><i class="icon-picture icon-white"></i></button>

HTML - popover

<div class="bgform popover fade bottom in">
            <div class="arrow"></div>
             ..... your code here .......
</div>

JS

$("#bg").click(function(){
        $('.bgform').slideToggle();
});

String comparison in Objective-C

Use the -isEqualToString: method to compare the value of two strings. Using the C == operator will simply compare the addresses of the objects.

if ([category isEqualToString:@"Some String"])
{
    // Do stuff...
}

$(document).on("click"... not working?

Your code should work, but I'm aware that answer doesn't help you. You can see a working example here (jsfiddle).

Jquery:

$(document).on('click','#test-element',function(){
    alert("You clicked the element with and ID of 'test-element'");
});

As someone already pointed out, you are using an ID instead of a class. If you have more that one element on the page with an ID, then jquery will return only the first element with that ID. There won't be any errors because that's how it works. If this is the problem, then you'll notice that the click event works for the first test-element but not for any that follow.

If this does not accurately describe the symptoms of the problem, then perhaps your selector is wrong. Your update leads me to believe this is the case because of inspecting an element then clicking the page again and triggering the click. What could be causing this is if you put the event listener on the actual document instead of test-element. If so, when you click off the document and back on (like from the developer window back to the document) the event will trigger. If this is the case, you'll also notice the click event is triggered if you click between two different tabs (because they are two different documents and therefore you are clicking the document.

If neither of these are the answer, posting HTML will go a long way toward figuring it out.

Combine two columns and add into one new column

Generally, I agree with @kgrittn's advice. Go for it.

But to address your basic question about concat(): The new function concat() is useful if you need to deal with null values - and null has neither been ruled out in your question nor in the one you refer to.

If you can rule out null values, the good old (SQL standard) concatenation operator || is still the best choice, and @luis' answer is just fine:

SELECT col_a || col_b;

If either of your columns can be null, the result would be null in that case. You could defend with COALESCE:

SELECT COALESCE(col_a, '') || COALESCE(col_b, '');

But that get tedious quickly with more arguments. That's where concat() comes in, which never returns null, not even if all arguments are null. Per documentation:

NULL arguments are ignored.

SELECT concat(col_a, col_b);

The remaining corner case for both alternatives is where all input columns are null in which case we still get an empty string '', but one might want null instead (at least I would). One possible way:

SELECT CASE
          WHEN col_a IS NULL THEN col_b
          WHEN col_b IS NULL THEN col_a
          ELSE col_a || col_b
       END;

This gets more complex with more columns quickly. Again, use concat() but add a check for the special condition:

SELECT CASE WHEN (col_a, col_b) IS NULL THEN NULL
            ELSE concat(col_a, col_b) END;

How does this work?
(col_a, col_b) is shorthand notation for a row type expression ROW (col_a, col_b). And a row type is only null if all columns are null. Detailed explanation:

Also, use concat_ws() to add separators between elements (ws for "with separator").


An expression like the one in Kevin's answer:

SELECT $1.zipcode || ' - ' || $1.city || ', ' || $1.state;

is tedious to prepare for null values in PostgreSQL 8.3 (without concat()). One way (of many):

SELECT COALESCE(
         CASE
            WHEN $1.zipcode IS NULL THEN $1.city
            WHEN $1.city    IS NULL THEN $1.zipcode
            ELSE $1.zipcode || ' - ' || $1.city
         END, '')
       || COALESCE(', ' || $1.state, '');

Function volatility is only STABLE

concat() and concat_ws() are STABLE functions, not IMMUTABLE because they can invoke datatype output functions (like timestamptz_out) that depend on locale settings.
Explanation by Tom Lane.

This prohibits their direct use in index expressions. If you know that the result is actually immutable in your case, you can work around this with an IMMUTABLE function wrapper. Example here:

Getting the value of an attribute in XML

This is more of an xpath question, but like this, assuming the context is the parent element:

<xsl:value-of select="name/@attribute1" />

Convert 4 bytes to int

Converting a 4-byte array into integer:

//Explictly declaring anInt=-4, byte-by-byte
byte[] anInt = {(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xfc}; // Equals -4
//And now you have a 4-byte array with an integer equaling -4...
//Converting back to integer from 4-bytes...
result = (int) ( anInt[0]<<24 | ( (anInt[1]<<24)>>>8 ) | ( (anInt[2]<<24)>>>16) | ( (anInt[3]<<24)>>>24) );

Find all files in a folder

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

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

Then you can find all the files with something like

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

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

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

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

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

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

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

Check out these for more info:

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

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

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

Return Type for jdbcTemplate.queryForList(sql, object, classType)

A complete solution for JdbcTemplate, NamedParameterJdbcTemplate with or without RowMapper Example.

// Create a Employee table

create table employee(  
id number(10),  
name varchar2(100),  
salary number(10)  
);

======================================================================= //Employee.java

public class Employee {
private int id;  
private String name;  
private float salary;  

//no-arg and parameterized constructors  

public Employee(){};

public Employee(int  id, String name, float salary){
    this.id=id;
    this.name=name;
    this.salary=salary;
}

//getters and setters  
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public float getSalary() {
    return salary;
}
public void setSalary(float salary) {
    this.salary = salary;
}
public String toString(){  
   return id+" "+name+" "+salary;  
}   

}

========================================================================= //EmployeeDao.java

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

public class EmployeeDao {  
  private JdbcTemplate jdbcTemplate;  
  private NamedParameterJdbcTemplate nameTemplate;  

  public void setnameTemplate(NamedParameterJdbcTemplate template) {  
    this.nameTemplate = template;  
 }   

 public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {  
  this.jdbcTemplate = jdbcTemplate;  
 }  

 // BY using JdbcTemplate
 public int saveEmployee(Employee e){  
 int id = e.getId();
 String name = e.getName();
 float salary = e.getSalary();
 Object p[] = {id, name, salary};
    String query="insert into employee values(?,?,?)";
      return jdbcTemplate.update(query, p);
    /*String query="insert into employee     values('"+e.getId()+"','"+e.getName()+"','"+e.getSalary()+"')"; 
      return jdbcTemplate.update(query);
    */

}  

//By using NameParameterTemplate
public void insertEmploye(Employee e) {  
String query="insert into employee values (:id,:name,:salary)";  
Map<String,Object> map=new HashMap<String,Object>();  
map.put("id",e.getId());  
map.put("name",e.getName());  
map.put("salary",e.getSalary());  

nameTemplate.execute(query,map,new MyPreparedStatement());

 }
// Updating Employee
public int updateEmployee(Employee e){  
String query="update employee set  name='"+e.getName()+"',salary='"+e.getSalary()+"' where id='"+e.getId()+"' ";  
  return jdbcTemplate.update(query);  
 }
 // Deleting a Employee row
 public int deleteEmployee(Employee e){  
 String query="delete from employee where id='"+e.getId()+"' ";  
 return jdbcTemplate.update(query);  
 }  
 //Selecting Single row with condition and also all rows
    public int selectEmployee(Employee e){  
     //String query="select * from employee where id='"+e.getId()+"' ";
      String query="select * from employee";
      List<Map<String, Object>> rows = jdbcTemplate.queryForList(query);
       for(Map<String, Object> row : rows){
          String id = row.get("id").toString();
          String name = (String)row.get("name");
          String salary = row.get("salary").toString();
          System.out.println(id + " " + name + " " + salary );
        }

      return 1;
   }  

   // Can use MyrowMapper class an implementation class for RowMapper interface
    public void getAllEmployee()
    {

    String query="select * from employee";
    List<Employee> l = jdbcTemplate.query(query, new MyrowMapper());

    Iterator it=l.iterator();
    while(it.hasNext())
    {
      Employee e=(Employee)it.next();
      System.out.println(e.getId()+" "+e.getName()+" "+e.getSalary());
    }
   }  

  //Can use directly a RowMapper implementation class without an object creation
  public List<Employee> getAllEmployee1(){
    return jdbcTemplate.query("select * from employee",new RowMapper<Employee>(){  
      @Override  
      public Employee mapRow(ResultSet rs, int rownumber) throws  SQLException    {  
            Employee e=new Employee();  
            e.setId(rs.getInt(1));  
            e.setName(rs.getString(2));  
            e.setSalary(rs.getFloat(3));  
            return e;  
          }  
      });  
      }
     // End of all the function

     }

================================================================ //MyrowMapper.java

 import java.sql.ResultSet;
 import java.sql.SQLException;
 import org.springframework.jdbc.core.RowMapper;

 public class MyrowMapper implements RowMapper<Employee> {

  @Override  
  public Employee mapRow(ResultSet rs, int rownumber) throws SQLException 
   {  
    System.out.println("mapRow()====:"+rownumber);
    Employee e=new Employee();  
     e.setId(rs.getInt("id"));  
     e.setName(rs.getString("name"));  
     e.setSalary(rs.getFloat("salary"));  
     return e;  
      }
    } 

========================================================== //MyPreparedStatement.java

import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.PreparedStatementCallback;


 public class MyPreparedStatement implements  PreparedStatementCallback<Object> {

 @Override
 public Object doInPreparedStatement(PreparedStatement ps)
        throws SQLException, DataAccessException {

     return ps.executeUpdate(); 
  } 

 } 

===================================================================== //Test.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {  

public static void main(String[] args) {  
 ApplicationContext ctx=new     ClassPathXmlApplicationContext("applicationContext.xml");  

 EmployeeDao dao=(EmployeeDao)ctx.getBean("edao"); 

  // By calling constructor for insert
 /* 
    int status=dao.saveEmployee(new Employee(103,"Ajay",35000));  
    System.out.println(status);  
 */
 // By calling PreparedStatement
  dao.insertEmploye(new Employee(103,"Roh",25000));


 // By calling setter-getter for update
 /* 
    Employee e=new Employee(); 
    e.setId(102);
    e.setName("Rohit");
    e.setSalary(8000000);
    int status=dao.updateEmployee(e);
*/
 // By calling constructor for update
 /*
    int status=dao.updateEmployee(new Employee(102,"Sadhan",15000)); 
    System.out.println(status); 
 */ 
 // Deleting a record 
 /*      
    Employee e=new Employee(); 
    e.setId(102); 
    int status=dao.deleteEmployee(e); 
    System.out.println(status);
 */
 // Selecting single or all rows
 /*
    Employee e=new Employee(); 
    e.setId(102);
    int status=dao.selectEmployee(e);
    System.out.println(status);
*/
// Can use MyrowMapper class an implementation class for RowMapper interface

    dao.getAllEmployee();

// Can use directly a RowMapper implementation class without an object creation
 /*
    List<Employee> list=dao.getAllEmployee1();  
    for(Employee e1:list)  
    System.out.println(e1);  
  */   
   }  

 } 

================================================================== //applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans  
 xmlns="http://www.springframework.org/schema/beans"  
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
 xmlns:p="http://www.springframework.org/schema/p"  
 xsi:schemaLocation="http://www.springframework.org/schema/beans   
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  

<bean id="ds"        class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
 <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />  
 <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />  
 <property name="username" value="hr" />  
 <property name="password" value="hr" />  
 </bean>  

 <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
 <property name="dataSource" ref="ds"></property>  
 </bean>  

<bean id="nameTemplate"   
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">  
<constructor-arg ref="ds"></constructor-arg>  
</bean>  

<bean id="edao" class="EmployeeDao"> 
<!-- Can use both --> 
<property name="nameTemplate" ref="nameTemplate"></property>
<property name="jdbcTemplate" ref="jdbcTemplate"></property> 
</bean>  

===================================================================

How do I output the results of a HiveQL query to CSV?

In case you are doing it from Windows you can use Python script hivehoney to extract table data to local CSV file.

It will:

  1. Login to bastion host.
  2. pbrun.
  3. kinit.
  4. beeline (with your query).
  5. Save echo from beeline to a file on Windows.

Execute it like this:

set PROXY_HOST=your_bastion_host

set SERVICE_USER=you_func_user

set LINUX_USER=your_SOID

set LINUX_PWD=your_pwd

python hh.py --query_file=query.sql

How can I plot a confusion matrix?

@bninopaul 's answer is not completely for beginners

here is the code you can "copy and run"

import seaborn as sn
import pandas as pd
import matplotlib.pyplot as plt

array = [[13,1,1,0,2,0],
         [3,9,6,0,1,0],
         [0,0,16,2,0,0],
         [0,0,0,13,0,0],
         [0,0,0,0,15,0],
         [0,0,1,0,0,15]]

df_cm = pd.DataFrame(array, range(6), range(6))
# plt.figure(figsize=(10,7))
sn.set(font_scale=1.4) # for label size
sn.heatmap(df_cm, annot=True, annot_kws={"size": 16}) # font size

plt.show()

result

How to update a menu item shown in the ActionBar?

Option #1: Try invalidateOptionsMenu(). I don't know if this will force an immediate redraw of the action bar or not.

Option #2: See if getActionView() returns anything for the affected MenuItem. It is possible that showAsAction simply automatically creates action views for you. If so, you can presumably enable/disable that View.

I can't seem to find a way to get the currently set Menu to manipulate it except for in onPrepareOptionMenu.

You can hang onto the Menu object you were handed in onCreateOptionsMenu(). Quoting the docs:

You can safely hold on to menu (and any items created from it), making modifications to it as desired, until the next time onCreateOptionsMenu() is called.

PHP CURL & HTTPS

Quick fix, add this in your options:

curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false)

Now you have no idea what host you're actually connecting to, because cURL will not verify the certificate in any way. Hope you enjoy man-in-the-middle attacks!

Or just add it to your current function:

/**
 * Get a web file (HTML, XHTML, XML, image, etc.) from a URL.  Return an
 * array containing the HTTP server response header fields and content.
 */
function get_web_page( $url )
{
    $options = array(
        CURLOPT_RETURNTRANSFER => true,     // return web page
        CURLOPT_HEADER         => false,    // don't return headers
        CURLOPT_FOLLOWLOCATION => true,     // follow redirects
        CURLOPT_ENCODING       => "",       // handle all encodings
        CURLOPT_USERAGENT      => "spider", // who am i
        CURLOPT_AUTOREFERER    => true,     // set referer on redirect
        CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
        CURLOPT_TIMEOUT        => 120,      // timeout on response
        CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
        CURLOPT_SSL_VERIFYPEER => false     // Disabled SSL Cert checks
    );

    $ch      = curl_init( $url );
    curl_setopt_array( $ch, $options );
    $content = curl_exec( $ch );
    $err     = curl_errno( $ch );
    $errmsg  = curl_error( $ch );
    $header  = curl_getinfo( $ch );
    curl_close( $ch );

    $header['errno']   = $err;
    $header['errmsg']  = $errmsg;
    $header['content'] = $content;
    return $header;
}

jquery, domain, get URL

var part = location.hostname.split('.');
var subdomains = part.shift();
var upperleveldomains = part.join('.');

second-level-domain, you might use

var sleveldomain = parts.slice(-2).join('.');

How to create a stacked bar chart for my DataFrame using seaborn?

You could use pandas plot as @Bharath suggest:

import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)

Output:

enter image description here

Updated:

from matplotlib.colors import ListedColormap df.set_index('App')\ .reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\ .T.plot(kind='bar', stacked=True, colormap=ListedColormap(sns.color_palette("GnBu", 10)), figsize=(12,6))

Updated Pandas 0.21.0+ reindex_axis is deprecated, use reindex

from matplotlib.colors import ListedColormap

df.set_index('App')\
  .reindex(df.set_index('App').sum().sort_values().index, axis=1)\
  .T.plot(kind='bar', stacked=True,
          colormap=ListedColormap(sns.color_palette("GnBu", 10)), 
          figsize=(12,6))

Output:

enter image description here

Pandas: ValueError: cannot convert float NaN to integer

I know this has been answered but wanted to provide alternate solution for anyone in the future:

You can use .loc to subset the dataframe by only values that are notnull(), and then subset out the 'x' column only. Take that same vector, and apply(int) to it.

If column x is float:

df.loc[df['x'].notnull(), 'x'] = df.loc[df['x'].notnull(), 'x'].apply(int)

Using getResources() in non-activity class

This always works for me:

import android.app.Activity;
import android.content.Context;

public class yourClass {

 Context ctx;

 public yourClass (Handler handler, Context context) {
 super(handler);
    ctx = context;
 }

 //Use context (ctx) in your code like this:
 XmlPullParser xpp = ctx.getResources().getXml(R.xml.samplexml);
 //OR
 final Intent intent = new Intent(ctx, MainActivity.class);
 //OR
 NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
 //ETC...

}

Not related to this question but example using a Fragment to access system resources/activity like this:

public boolean onQueryTextChange(String newText) {
 Activity activity = getActivity();
 Context context = activity.getApplicationContext();
 returnSomething(newText);
 return false;
}

View customerInfo = getActivity().getLayoutInflater().inflate(R.layout.main_layout_items, itemsLayout, false);
 itemsLayout.addView(customerInfo);

SQL Query - Change date format in query to DD/MM/YYYY

If you have a Date (or Datetime) column, look at http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format

 SELECT DATE_FORMAT(datecolumn,'%d/%m/%Y') FROM ...

Should do the job for MySQL, for SqlServer I'm sure there is an analog function. If you have a VARCHAR column, you might have at first to convert it to a date, see STR_TO_DATE for MySQL.

SQL - Select first 10 rows only?

SELECT* from <table name> WHERE rownum <= 10;

Converting from IEnumerable to List

You can do this very simply using LINQ.

Make sure this using is at the top of your C# file:

using System.Linq;

Then use the ToList extension method.

Example:

IEnumerable<int> enumerable = Enumerable.Range(1, 300);
List<int> asList = enumerable.ToList();

How to resolve "could not execute statement; SQL [n/a]; constraint [numbering];"?

I have got the same error but I have resolved the issue in the following ways:

  1. Provide all the mandatory filed of your bean/model class
  2. Don't violet the concept of the unique constraint, Provide unique value in Unique constraints.

Is there a way to remove unused imports and declarations from Angular 2+?

If you're a heavy visual studio user, you can simply open your preference settings and add the following to your settings.json:

...
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
  "source.organizeImports": true
}
....

Hopefully this can be helpful!

How do I make entire div a link?

You need to assign display: block; property to the wrapping anchor. Otherwise it won't wrap correctly.

<a style="display:block" href="http://justinbieber.com">
  <div class="xyz">My div contents</div>
</a>

Xcode 4 - "Archive" is greyed out?

see the picture. but I have to type enough chars to post the picture.:)

enter image description here

What does on_delete do on Django models?

This is the behaviour to adopt when the referenced object is deleted. It is not specific to Django; this is an SQL standard. Although Django has its own implementation on top of SQL. (1)

There are seven possible actions to take when such event occurs:

  • CASCADE: When the referenced object is deleted, also delete the objects that have references to it (when you remove a blog post for instance, you might want to delete comments as well). SQL equivalent: CASCADE.
  • PROTECT: Forbid the deletion of the referenced object. To delete it you will have to delete all objects that reference it manually. SQL equivalent: RESTRICT.
  • RESTRICT: (introduced in Django 3.1) Similar behavior as PROTECT that matches SQL's RESTRICT more accurately. (See django documentation example)
  • SET_NULL: Set the reference to NULL (requires the field to be nullable). For instance, when you delete a User, you might want to keep the comments he posted on blog posts, but say it was posted by an anonymous (or deleted) user. SQL equivalent: SET NULL.
  • SET_DEFAULT: Set the default value. SQL equivalent: SET DEFAULT.
  • SET(...): Set a given value. This one is not part of the SQL standard and is entirely handled by Django.
  • DO_NOTHING: Probably a very bad idea since this would create integrity issues in your database (referencing an object that actually doesn't exist). SQL equivalent: NO ACTION. (2)

Source: Django documentation

See also the documentation of PostgreSQL for instance.

In most cases, CASCADE is the expected behaviour, but for every ForeignKey, you should always ask yourself what is the expected behaviour in this situation. PROTECT and SET_NULL are often useful. Setting CASCADE where it should not, can potentially delete all of your database in cascade, by simply deleting a single user.


Additional note to clarify cascade direction

It's funny to notice that the direction of the CASCADE action is not clear to many people. Actually, it's funny to notice that only the CASCADE action is not clear. I understand the cascade behavior might be confusing, however you must think that it is the same direction as any other action. Thus, if you feel that CASCADE direction is not clear to you, it actually means that on_delete behavior is not clear to you.

In your database, a foreign key is basically represented by an integer field which value is the primary key of the foreign object. Let's say you have an entry comment_A, which has a foreign key to an entry article_B. If you delete the entry comment_A, everything is fine. article_B used to live without comment_A and don't bother if it's deleted. However, if you delete article_B, then comment_A panics! It never lived without article_B and needs it, and it's part of its attributes (article=article_B, but what is article_B???). This is where on_delete steps in, to determine how to resolve this integrity error, either by saying:

  • "No! Please! Don't! I can't live without you!" (which is said PROTECT or RESTRICT in Django/SQL)
  • "All right, if I'm not yours, then I'm nobody's" (which is said SET_NULL)
  • "Good bye world, I can't live without article_B" and commit suicide (this is the CASCADE behavior).
  • "It's OK, I've got spare lover, and I'll reference article_C from now" (SET_DEFAULT, or even SET(...)).
  • "I can't face reality, and I'll keep calling your name even if that's the only thing left to me!" (DO_NOTHING)

I hope it makes cascade direction clearer. :)


Footnotes

(1) Django has its own implementation on top of SQL. And, as mentioned by @JoeMjr2 in the comments below, Django will not create the SQL constraints. If you want the constraints to be ensured by your database (for instance, if your database is used by another application, or if you hang in the database console from time to time), you might want to set the related constraints manually yourself. There is an open ticket to add support for database-level on delete constrains in Django.

(2) Actually, there is one case where DO_NOTHING can be useful: If you want to skip Django's implementation and implement the constraint yourself at the database-level.

How do I change db schema to dbo

Move table from dbo schema to MySchema:

 ALTER SCHEMA MySchema TRANSFER dbo.MyTable


Move table from MySchema to dbo schema:

 ALTER SCHEMA dbo TRANSFER MySchema.MyTable

CSS Always On Top

Ensure position is on your element and set the z-index to a value higher than the elements you want to cover.

element {
    position: fixed;
    z-index: 999;
}

div {
    position: relative;
    z-index: 99;
}

It will probably require some more work than that but it's a start since you didn't post any code.

Spring CORS No 'Access-Control-Allow-Origin' header is present

Omkar's answer is quite comprehensive.

But some part of the Global config part has changed.

According to the spring boot 2.0.2.RELEASE reference

As of version 4.2, Spring MVC supports CORS. Using controller method CORS configuration with @CrossOrigin annotations in your Spring Boot application does not require any specific configuration. Global CORS configuration can be defined by registering a WebMvcConfigurer bean with a customized addCorsMappings(CorsRegistry) method, as shown in the following example:

@Configuration
public class MyConfiguration {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**");
            }
        };
    }
}

Most answer in this post using WebMvcConfigurerAdapter, however

The type WebMvcConfigurerAdapter is deprecated

Since Spring 5 you just need to implement the interface WebMvcConfigurer:

public class MvcConfig implements WebMvcConfigurer {

This is because Java 8 introduced default methods on interfaces which cover the functionality of the WebMvcConfigurerAdapter class

How to parse a string to an int in C++?

You can use stringstream's

int str2int (const string &str) {
  stringstream ss(str);
  int num;
  ss >> num;
  return num;
}