Programs & Examples On #Twitter4j

Twitter4J is a library enabling calls to the Twitter API from Java. With Twitter4J, you can easily integrate your Java application with the Twitter service. Twitter4J is an unofficial library.

ERROR Source option 1.5 is no longer supported. Use 1.6 or later

Make sure you have following configuration in your pom.xml file.

<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

"PKIX path building failed" and "unable to find valid certification path to requested target"

I ran into same issue but updating wrong jre on my linux machine. It is highly likely that tomcat is using different jre and your cli prompt is configured to use a different jre.

Make sure you are picking up the correct jre.

Step #1:

ps -ef | grep tomcat

You will see some thing like:

root     29855     1  3 17:54 pts/3    00:00:42 /usr/java/jdk1.7.0_79/jre/bin/java 

Now use this:

keytool -import -alias example -keystore  /usr/java/jdk1.7.0_79/jre/lib/security/cacerts -file cert.cer
PWD: changeit

*.cer file can be geneated as shown below: (or you can use your own)

openssl x509 -in cert.pem -outform pem -outform der -out cert.cer

Android Studio says "cannot resolve symbol" but project compiles

For mine was caused by the imported library project, type something in build.gradle and delete it again and press sync now, the error gone.

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile)

Actually, if you do not want to delete your local .m2/repository/... and you are have a downloaded copy of Maven from Apache, you can have Eclipse /STS use that external Maven and you can edit the {maven}\conf\settings.xml to point your localRepository to a new empty location.

<localRepository>C:\java\repository</localRepository>

Of course, you will have a new repository with all of the maven source downloads in addition to your previous .m2 location.

enter image description here

jQuery - how to check if an element exists?

Assuming you are trying to find if a div exists

$('div').length ? alert('div found') : alert('Div not found')

Check working example at http://jsfiddle.net/Qr86J/1/

How do I add a newline to a TextView in Android?

try System.getProperty("line.separator");

Is quitting an application frowned upon?

As an Application in an Android context is just a bunch of vaguely related Activities, quitting an Application doesn't really make much sense. You can finish() an Activity, and the view of the previous Activity in the Activity stack will be drawn.

How do I change a PictureBox's image?

Assign a new Image object to your PictureBox's Image property. To load an Image from a file, you may use the Image.FromFile method. In your particular case, assuming the current directory is one under bin, this should load the image bin/Pics/image1.jpg, for example:

pictureBox1.Image = Image.FromFile("../Pics/image1.jpg");

Additionally, if these images are static and to be used only as resources in your application, resources would be a much better fit than files.

AngularJS ui-router login authentication

I'm in the process of making a nicer demo as well as cleaning up some of these services into a usable module, but here's what I've come up with. This is a complex process to work around some caveats, so hang in there. You'll need to break this down into several pieces.

Take a look at this plunk.

First, you need a service to store the user's identity. I call this principal. It can be checked to see if the user is logged in, and upon request, it can resolve an object that represents the essential information about the user's identity. This can be whatever you need, but the essentials would be a display name, a username, possibly an email, and the roles a user belongs to (if this applies to your app). Principal also has methods to do role checks.

.factory('principal', ['$q', '$http', '$timeout',
  function($q, $http, $timeout) {
    var _identity = undefined,
      _authenticated = false;

    return {
      isIdentityResolved: function() {
        return angular.isDefined(_identity);
      },
      isAuthenticated: function() {
        return _authenticated;
      },
      isInRole: function(role) {
        if (!_authenticated || !_identity.roles) return false;

        return _identity.roles.indexOf(role) != -1;
      },
      isInAnyRole: function(roles) {
        if (!_authenticated || !_identity.roles) return false;

        for (var i = 0; i < roles.length; i++) {
          if (this.isInRole(roles[i])) return true;
        }

        return false;
      },
      authenticate: function(identity) {
        _identity = identity;
        _authenticated = identity != null;
      },
      identity: function(force) {
        var deferred = $q.defer();

        if (force === true) _identity = undefined;

        // check and see if we have retrieved the 
        // identity data from the server. if we have, 
        // reuse it by immediately resolving
        if (angular.isDefined(_identity)) {
          deferred.resolve(_identity);

          return deferred.promise;
        }

        // otherwise, retrieve the identity data from the
        // server, update the identity object, and then 
        // resolve.
        //           $http.get('/svc/account/identity', 
        //                     { ignoreErrors: true })
        //                .success(function(data) {
        //                    _identity = data;
        //                    _authenticated = true;
        //                    deferred.resolve(_identity);
        //                })
        //                .error(function () {
        //                    _identity = null;
        //                    _authenticated = false;
        //                    deferred.resolve(_identity);
        //                });

        // for the sake of the demo, fake the lookup
        // by using a timeout to create a valid
        // fake identity. in reality,  you'll want 
        // something more like the $http request
        // commented out above. in this example, we fake 
        // looking up to find the user is
        // not logged in
        var self = this;
        $timeout(function() {
          self.authenticate(null);
          deferred.resolve(_identity);
        }, 1000);

        return deferred.promise;
      }
    };
  }
])

Second, you need a service that checks the state the user wants to go to, makes sure they're logged in (if necessary; not necessary for signin, password reset, etc.), and then does a role check (if your app needs this). If they are not authenticated, send them to the sign-in page. If they are authenticated, but fail a role check, send them to an access denied page. I call this service authorization.

.factory('authorization', ['$rootScope', '$state', 'principal',
  function($rootScope, $state, principal) {
    return {
      authorize: function() {
        return principal.identity()
          .then(function() {
            var isAuthenticated = principal.isAuthenticated();

            if ($rootScope.toState.data.roles
                && $rootScope.toState
                             .data.roles.length > 0 
                && !principal.isInAnyRole(
                   $rootScope.toState.data.roles))
            {
              if (isAuthenticated) {
                  // user is signed in but not
                  // authorized for desired state
                  $state.go('accessdenied');
              } else {
                // user is not authenticated. Stow
                // the state they wanted before you
                // send them to the sign-in state, so
                // you can return them when you're done
                $rootScope.returnToState
                    = $rootScope.toState;
                $rootScope.returnToStateParams
                    = $rootScope.toStateParams;

                // now, send them to the signin state
                // so they can log in
                $state.go('signin');
              }
            }
          });
      }
    };
  }
])

Now all you need to do is listen in on ui-router's $stateChangeStart. This gives you a chance to examine the current state, the state they want to go to, and insert your authorization check. If it fails, you can cancel the route transition, or change to a different route.

.run(['$rootScope', '$state', '$stateParams', 
      'authorization', 'principal',
    function($rootScope, $state, $stateParams, 
             authorization, principal)
{
      $rootScope.$on('$stateChangeStart', 
          function(event, toState, toStateParams)
      {
        // track the state the user wants to go to; 
        // authorization service needs this
        $rootScope.toState = toState;
        $rootScope.toStateParams = toStateParams;
        // if the principal is resolved, do an 
        // authorization check immediately. otherwise,
        // it'll be done when the state it resolved.
        if (principal.isIdentityResolved()) 
            authorization.authorize();
      });
    }
  ]);

The tricky part about tracking a user's identity is looking it up if you've already authenticated (say, you're visiting the page after a previous session, and saved an auth token in a cookie, or maybe you hard refreshed a page, or dropped onto a URL from a link). Because of the way ui-router works, you need to do your identity resolve once, before your auth checks. You can do this using the resolve option in your state config. I have one parent state for the site that all states inherit from, which forces the principal to be resolved before anything else happens.

$stateProvider.state('site', {
  'abstract': true,
  resolve: {
    authorize: ['authorization',
      function(authorization) {
        return authorization.authorize();
      }
    ]
  },
  template: '<div ui-view />'
})

There's another problem here... resolve only gets called once. Once your promise for identity lookup completes, it won't run the resolve delegate again. So we have to do your auth checks in two places: once pursuant to your identity promise resolving in resolve, which covers the first time your app loads, and once in $stateChangeStart if the resolution has been done, which covers any time you navigate around states.

OK, so what have we done so far?

  1. We check to see when the app loads if the user is logged in.
  2. We track info about the logged in user.
  3. We redirect them to sign in state for states that require the user to be logged in.
  4. We redirect them to an access denied state if they do not have authorization to access it.
  5. We have a mechanism to redirect users back to the original state they requested, if we needed them to log in.
  6. We can sign a user out (needs to be wired up in concert with any client or server code that manages your auth ticket).
  7. We don't need to send users back to the sign-in page every time they reload their browser or drop on a link.

Where do we go from here? Well, you can organize your states into regions that require sign in. You can require authenticated/authorized users by adding data with roles to these states (or a parent of them, if you want to use inheritance). Here, we restrict a resource to Admins:

.state('restricted', {
    parent: 'site',
    url: '/restricted',
    data: {
      roles: ['Admin']
    },
    views: {
      'content@': {
        templateUrl: 'restricted.html'
      }
    }
  })

Now you can control state-by-state what users can access a route. Any other concerns? Maybe varying only part of a view based on whether or not they are logged in? No problem. Use the principal.isAuthenticated() or even principal.isInRole() with any of the numerous ways you can conditionally display a template or an element.

First, inject principal into a controller or whatever, and stick it to the scope so you can use it easily in your view:

.scope('HomeCtrl', ['$scope', 'principal', 
    function($scope, principal)
{
  $scope.principal = principal;
});

Show or hide an element:

<div ng-show="principal.isAuthenticated()">
   I'm logged in
</div>
<div ng-hide="principal.isAuthenticated()">
  I'm not logged in
</div>

Etc., so on, so forth. Anyways, in your example app, you would have a state for home page that would let unauthenticated users drop by. They could have links to the sign-in or sign-up states, or have those forms built into that page. Whatever suits you.

The dashboard pages could all inherit from a state that requires the users to be logged in and, say, be a User role member. All the authorization stuff we've discussed would flow from there.

Force DOM redraw/refresh on Chrome/Mac

I ran into this challenge today in OSX El Capitan with Chrome v51. The page in question worked fine in Safari. I tried nearly every suggestion on this page - none worked right - all had side-effects... I ended up implementing the code below - super simple - no side-effects (still works as before in Safari).

Solution: Toggle a class on the problematic element as needed. Each toggle will force a redraw. (I used jQuery for convenience, but vanilla JavaScript should be no problem...)

jQuery Class Toggle

$('.slide.force').toggleClass('force-redraw');

CSS Class

.force-redraw::before { content: "" }

And that's it...

NOTE: You have to run the snippet below "Full Page" in order to see the effect.

_x000D_
_x000D_
$(window).resize(function() {_x000D_
  $('.slide.force').toggleClass('force-redraw');_x000D_
});
_x000D_
.force-redraw::before {_x000D_
  content: "";_x000D_
}_x000D_
html,_x000D_
body {_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  overflow: hidden;_x000D_
}_x000D_
.slide-container {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  overflow-x: scroll;_x000D_
  overflow-y: hidden;_x000D_
  white-space: nowrap;_x000D_
  padding-left: 10%;_x000D_
  padding-right: 5%;_x000D_
}_x000D_
.slide {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  height: 30%;_x000D_
  border: 1px solid green;_x000D_
}_x000D_
.slide-sizer {_x000D_
  height: 160%;_x000D_
  pointer-events: none;_x000D_
  //border: 1px solid red;_x000D_
_x000D_
}_x000D_
.slide-contents {_x000D_
  position: absolute;_x000D_
  top: 10%;_x000D_
  left: 10%;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p>_x000D_
  This sample code is a simple style-based solution to maintain aspect ratio of an element based on a dynamic height.  As you increase and decrease the window height, the elements should follow and the width should follow in turn to maintain the aspect ratio.  You will notice that in Chrome on OSX (at least), the "Not Forced" element does not maintain a proper ratio._x000D_
</p>_x000D_
<div class="slide-container">_x000D_
  <div class="slide">_x000D_
    <img class="slide-sizer" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">_x000D_
    <div class="slide-contents">_x000D_
      Not Forced_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="slide force">_x000D_
    <img class="slide-sizer" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">_x000D_
    <div class="slide-contents">_x000D_
      Forced_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Center a button in a Linear layout

Did you try this?

  <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mainlayout" android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5px"
android:background="#303030"
>
    <RelativeLayout
    android:id="@+id/widget42"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    >
    <ImageButton
    android:id="@+id/map"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="map"
    android:src="@drawable/outbox_pressed"
    android:background="@null"
    android:layout_toRightOf="@+id/location"
    />
    <ImageButton
    android:id="@+id/location"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="location"
    android:src="@drawable/inbox_pressed"
    android:background="@null"
    />
    </RelativeLayout>
    <ImageButton
    android:id="@+id/home"
    android:src="@drawable/button_back"
    android:background="@null"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    />
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5px"
android:orientation="horizontal"
android:background="#252525"
>
    <EditText
    android:id="@+id/searchfield"
    android:layout_width="fill_parent"
    android:layout_weight="1"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:background="@drawable/customshape"
    />
    <ImageButton
    android:id="@+id/search_button"
    android:src="@drawable/search_press"
    android:background="@null"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    />
</LinearLayout>
<com.google.android.maps.MapView
    android:id="@+id/mapview" 
    android:layout_weight="1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" 
    android:clickable="true"
    android:apiKey="apikey" />

</TableLayout>

How to vertical align an inline-block in a line of text?

display: inline-block is your friend you just need all three parts of the construct - before, the "block", after - to be one, then you can vertically align them all to the middle:

Working Example

(it looks like your picture anyway ;))

CSS:

p, div {
  display: inline-block; 
  vertical-align: middle;
}
p, div {
  display: inline !ie7; /* hack for IE7 and below */
}

table {
  background: #000; 
  color: #fff; 
  font-size: 16px; 
  font-weight: bold; margin: 0 10px;
}

td {
  padding: 5px; 
  text-align: center;
}

HTML:

<p>some text</p> 
<div>
  <table summary="">
  <tr><td>A</td></tr>
  <tr><td>B</td></tr>
  <tr><td>C</td></tr>
  <tr><td>D</td></tr>
  </table>
</div> 
<p>continues afterwards</p>

How to install the current version of Go in Ubuntu Precise

These days according to the golang github with for Ubuntu, it's possible to install the latest version of Go easily via a snap:

Using snaps also works quite well:

# This will give you the latest version of go
$ sudo snap install --classic go

Potentially preferable to fussing with outdated and/or 3rd party PPAs

How to put labels over geom_bar in R with ggplot2

Another solution is to use stat_count() when dealing with discrete variables (and stat_bin() with continuous ones).

ggplot(data = df, aes(x = x)) +
geom_bar(stat = "count") + 
stat_count(geom = "text", colour = "white", size = 3.5,
aes(label = ..count..),position=position_stack(vjust=0.5))

enter image description here

How to change Status Bar text color in iOS

In Info.plist set 'View controller-based status bar appearance' as NO

In AppDelegate add

[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

scp copy directory to another server with private key auth

or you can also do ( for pem file )

 scp -r -i file.pem [email protected]:/home/backup /home/user/Desktop/

Detect if an element is visible with jQuery

if($('#testElement').is(':visible')){
    //what you want to do when is visible
}

Xcode couldn't find any provisioning profiles matching

I opened XCode -> Preferences -> Accounts and clicked on Download certificate. That fixed my problem

Python: Checking if a 'Dictionary' is empty doesn't seem to work

use 'any'

dict = {}

if any(dict) :

     # true
     # dictionary is not empty 

else :

     # false 
     # dictionary is empty

How to add anything in <head> through jquery/javascript?

You can use innerHTML to just concat the extra field string;

document.head.innerHTML = document.head.innerHTML + '<link rel="stylesheet>...'

However, you can't guarantee that the extra things you add to the head will be recognised by the browser after the first load, and it's possible you will get a FOUC (flash of unstyled content) as the extra stylesheets are loaded.

I haven't looked at the API in years, but you could also use document.write, which is what was designed for this sort of action. However, this would require you to block the page from rendering until your initial AJAX request has completed.

Parse JSON String into a Particular Object Prototype in JavaScript

For the sake of completeness, here's a simple one-liner I ended up with (I had no need checking for non-Foo-properties):

var Foo = function(){ this.bar = 1; };

// angular version
var foo = angular.extend(new Foo(), angular.fromJson('{ "bar" : 2 }'));

// jquery version
var foo = jQuery.extend(new Foo(), jQuery.parseJSON('{ "bar" : 3 }'));

How to convert a date to milliseconds

You don't have a Date, you have a String representation of a date. You should convert the String into a Date and then obtain the milliseconds. To convert a String into a Date and vice versa you should use SimpleDateFormat class.

Here's an example of what you want/need to do (assuming time zone is not involved here):

String myDate = "2014/10/29 18:10:45";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = sdf.parse(myDate);
long millis = date.getTime();

Still, be careful because in Java the milliseconds obtained are the milliseconds between the desired epoch and 1970-01-01 00:00:00.


Using the new Date/Time API available since Java 8:

String myDate = "2014/10/29 18:10:45";
LocalDateTime localDateTime = LocalDateTime.parse(myDate,
    DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss") );
/*
  With this new Date/Time API, when using a date, you need to
  specify the Zone where the date/time will be used. For your case,
  seems that you want/need to use the default zone of your system.
  Check which zone you need to use for specific behaviour e.g.
  CET or America/Lima
*/
long millis = localDateTime
    .atZone(ZoneId.systemDefault())
    .toInstant().toEpochMilli();

How to wrap async function calls into a sync function in Node.js or Javascript?

Nowadays this generator pattern can be a solution in many situations.

Here an example of sequential console prompts in nodejs using async readline.question function:

var main = (function* () {

  // just import and initialize 'readline' in nodejs
  var r = require('readline')
  var rl = r.createInterface({input: process.stdin, output: process.stdout })

  // magic here, the callback is the iterator.next
  var answerA = yield rl.question('do you want this? ', r=>main.next(r))    

  // and again, in a sync fashion
  var answerB = yield rl.question('are you sure? ', r=>main.next(r))        

  // readline boilerplate
  rl.close()

  console.log(answerA, answerB)

})()  // <-- executed: iterator created from generator
main.next()     // kick off the iterator, 
                // runs until the first 'yield', including rightmost code
                // and waits until another main.next() happens

Getting the "real" Facebook profile picture URL from graph API

I realize this is late, but there is another way to obtain the URL of the profile image.

To your original url, you can add the parameter redirect=false to obtain the actual URL of the image you'd normally be redirected to.

So, the new request would look like http://graph.facebook.com/517267866/picture?type=large&redirect=false. This will return a JSON object containing the URL of the picture and a boolean is_silhouette (true if the picture is the default Facebook picture).

The picture will be of the size you specified, as well. You can test this additionally by adding dimensions: http://graph.facebook.com/517267866/picture?type=large&redirect=false&width=400&height=400

how to open a url in python

I think this is the easy way to open a URL using this function

webbrowser.open_new_tab(url)

Compare given date with today

One caution based on my experience, if your purpose only involves date then be careful to include the timestamp. For example, say today is "2016-11-09". Comparison involving timestamp will nullify the logic here. Example,

//  input
$var = "2016-11-09 00:00:00.0";

//  check if date is today or in the future
if ( time() <= strtotime($var) ) 
{
    //  This seems right, but if it's ONLY date you are after
    //  then the code might treat $var as past depending on
    //  the time.
}

The code above seems right, but if it's ONLY the date you want to compare, then, the above code is not the right logic. Why? Because, time() and strtotime() will provide include timestamp. That is, even though both dates fall on the same day, but difference in time will matter. Consider the example below:

//  plain date string
$input = "2016-11-09";

Because the input is plain date string, using strtotime() on $input will assume that it's the midnight of 2016-11-09. So, running time() anytime after midnight will always treat $input as past, even though they are on the same day.

To fix this, you can simply code, like this:

if (date("Y-m-d") <= $input)
{
    echo "Input date is equal to or greater than today.";
}

Stuck while installing Visual Studio 2015 (Update for Microsoft Windows (KB2999226))

Just kill wusa.exe and install KB2999226 manually. Installation will continue without any problems.

How can I get new selection in "select" in Angular 2?

You can pass the value back into the component by creating a reference variable on the select tag #device and passing it into the change handler onChange($event, device.value) should have the new value

<select [(ng-model)]="selectedDevice" #device (change)="onChange($event, device.value)">
    <option *ng-for="#i of devices">{{i}}</option>
</select>

onChange($event, deviceValue) {
    console.log(deviceValue);
}

Get startup type of Windows service using PowerShell

In PowerShell you can use the command Set-Service:

Set-Service -Name Winmgmt -StartupType Manual

I haven't found a PowerShell command to view the startup type though. One would assume that the command Get-Service would provide that, but it doesn't seem to.

Is it possible to clone html element objects in JavaScript / JQuery?

In one line:

$('#selector').clone().attr('id','newid').appendTo('#newPlace');

Most Pythonic way to provide global configuration variables in config.py?

please check out the IPython configuration system, implemented via traitlets for the type enforcement you are doing manually.

Cut and pasted here to comply with SO guidelines for not just dropping links as the content of links changes over time.

traitlets documentation

Here are the main requirements we wanted our configuration system to have:

Support for hierarchical configuration information.

Full integration with command line option parsers. Often, you want to read a configuration file, but then override some of the values with command line options. Our configuration system automates this process and allows each command line option to be linked to a particular attribute in the configuration hierarchy that it will override.

Configuration files that are themselves valid Python code. This accomplishes many things. First, it becomes possible to put logic in your configuration files that sets attributes based on your operating system, network setup, Python version, etc. Second, Python has a super simple syntax for accessing hierarchical data structures, namely regular attribute access (Foo.Bar.Bam.name). Third, using Python makes it easy for users to import configuration attributes from one configuration file to another. Fourth, even though Python is dynamically typed, it does have types that can be checked at runtime. Thus, a 1 in a config file is the integer ‘1’, while a '1' is a string.

A fully automated method for getting the configuration information to the classes that need it at runtime. Writing code that walks a configuration hierarchy to extract a particular attribute is painful. When you have complex configuration information with hundreds of attributes, this makes you want to cry.

Type checking and validation that doesn’t require the entire configuration hierarchy to be specified statically before runtime. Python is a very dynamic language and you don’t always know everything that needs to be configured when a program starts.

To acheive this they basically define 3 object classes and their relations to each other:

1) Configuration - basically a ChainMap / basic dict with some enhancements for merging.

2) Configurable - base class to subclass all things you'd wish to configure.

3) Application - object that is instantiated to perform a specific application function, or your main application for single purpose software.

In their words:

Application: Application

An application is a process that does a specific job. The most obvious application is the ipython command line program. Each application reads one or more configuration files and a single set of command line options and then produces a master configuration object for the application. This configuration object is then passed to the configurable objects that the application creates. These configurable objects implement the actual logic of the application and know how to configure themselves given the configuration object.

Applications always have a log attribute that is a configured Logger. This allows centralized logging configuration per-application. Configurable: Configurable

A configurable is a regular Python class that serves as a base class for all main classes in an application. The Configurable base class is lightweight and only does one things.

This Configurable is a subclass of HasTraits that knows how to configure itself. Class level traits with the metadata config=True become values that can be configured from the command line and configuration files.

Developers create Configurable subclasses that implement all of the logic in the application. Each of these subclasses has its own configuration information that controls how instances are created.

How can I get the content of CKEditor using JQuery?

Easy way to get the text inside of the editor or the length of it :)

 var editorText = CKEDITOR.instances['<%= your_editor.ClientID %>'].getData();
 alert(editorText);

 var editorTextLength = CKEDITOR.instances['<%= your_editor.ClientID %>'].getData().length;
 alert(editorTextLength);

How to know if other threads have finished?

Do you want to wait for them to finish? If so, use the Join method.

There is also the isAlive property if you just want to check it.

Decode Base64 data in Java

Here's my own implementation, if it could be useful to someone :

public class Base64Coder {

    // The line separator string of the operating system.
    private static final String systemLineSeparator = System.getProperty("line.separator");

    // Mapping table from 6-bit nibbles to Base64 characters.
    private static final char[] map1 = new char[64];
       static {
          int i=0;
          for (char c='A'; c<='Z'; c++) map1[i++] = c;
          for (char c='a'; c<='z'; c++) map1[i++] = c;
          for (char c='0'; c<='9'; c++) map1[i++] = c;
          map1[i++] = '+'; map1[i++] = '/'; }

    // Mapping table from Base64 characters to 6-bit nibbles.
    private static final byte[] map2 = new byte[128];
       static {
          for (int i=0; i<map2.length; i++) map2[i] = -1;
          for (int i=0; i<64; i++) map2[map1[i]] = (byte)i; }

    /**
    * Encodes a string into Base64 format.
    * No blanks or line breaks are inserted.
    * @param s  A String to be encoded.
    * @return   A String containing the Base64 encoded data.
    */
    public static String encodeString (String s) {
       return new String(encode(s.getBytes())); }

    /**
    * Encodes a byte array into Base 64 format and breaks the output into lines of 76 characters.
    * This method is compatible with <code>sun.misc.BASE64Encoder.encodeBuffer(byte[])</code>.
    * @param in  An array containing the data bytes to be encoded.
    * @return    A String containing the Base64 encoded data, broken into lines.
    */
    public static String encodeLines (byte[] in) {
       return encodeLines(in, 0, in.length, 76, systemLineSeparator); }

    /**
    * Encodes a byte array into Base 64 format and breaks the output into lines.
    * @param in            An array containing the data bytes to be encoded.
    * @param iOff          Offset of the first byte in <code>in</code> to be processed.
    * @param iLen          Number of bytes to be processed in <code>in</code>, starting at <code>iOff</code>.
    * @param lineLen       Line length for the output data. Should be a multiple of 4.
    * @param lineSeparator The line separator to be used to separate the output lines.
    * @return              A String containing the Base64 encoded data, broken into lines.
    */
    public static String encodeLines (byte[] in, int iOff, int iLen, int lineLen, String lineSeparator) {
       int blockLen = (lineLen*3) / 4;
       if (blockLen <= 0) throw new IllegalArgumentException();
       int lines = (iLen+blockLen-1) / blockLen;
       int bufLen = ((iLen+2)/3)*4 + lines*lineSeparator.length();
       StringBuilder buf = new StringBuilder(bufLen);
       int ip = 0;
       while (ip < iLen) {
          int l = Math.min(iLen-ip, blockLen);
          buf.append (encode(in, iOff+ip, l));
          buf.append (lineSeparator);
          ip += l; }
       return buf.toString(); }

    /**
    * Encodes a byte array into Base64 format.
    * No blanks or line breaks are inserted in the output.
    * @param in  An array containing the data bytes to be encoded.
    * @return    A character array containing the Base64 encoded data.
    */
    public static char[] encode (byte[] in) {
       return encode(in, 0, in.length); }

    /**
    * Encodes a byte array into Base64 format.
    * No blanks or line breaks are inserted in the output.
    * @param in    An array containing the data bytes to be encoded.
    * @param iLen  Number of bytes to process in <code>in</code>.
    * @return      A character array containing the Base64 encoded data.
    */
    public static char[] encode (byte[] in, int iLen) {
       return encode(in, 0, iLen); }

    /**
    * Encodes a byte array into Base64 format.
    * No blanks or line breaks are inserted in the output.
    * @param in    An array containing the data bytes to be encoded.
    * @param iOff  Offset of the first byte in <code>in</code> to be processed.
    * @param iLen  Number of bytes to process in <code>in</code>, starting at <code>iOff</code>.
    * @return      A character array containing the Base64 encoded data.
    */
    public static char[] encode (byte[] in, int iOff, int iLen) {
       int oDataLen = (iLen*4+2)/3;       // output length without padding
       int oLen = ((iLen+2)/3)*4;         // output length including padding
       char[] out = new char[oLen];
       int ip = iOff;
       int iEnd = iOff + iLen;
       int op = 0;
       while (ip < iEnd) {
          int i0 = in[ip++] & 0xff;
          int i1 = ip < iEnd ? in[ip++] & 0xff : 0;
          int i2 = ip < iEnd ? in[ip++] & 0xff : 0;
          int o0 = i0 >>> 2;
          int o1 = ((i0 &   3) << 4) | (i1 >>> 4);
          int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6);
          int o3 = i2 & 0x3F;
          out[op++] = map1[o0];
          out[op++] = map1[o1];
          out[op] = op < oDataLen ? map1[o2] : '='; op++;
          out[op] = op < oDataLen ? map1[o3] : '='; op++; }
       return out; }

    /**
    * Decodes a string from Base64 format.
    * No blanks or line breaks are allowed within the Base64 encoded input data.
    * @param s  A Base64 String to be decoded.
    * @return   A String containing the decoded data.
    * @throws   IllegalArgumentException If the input is not valid Base64 encoded data.
    */
    public static String decodeString (String s) {
       return new String(decode(s)); }

    /**
    * Decodes a byte array from Base64 format and ignores line separators, tabs and blanks.
    * CR, LF, Tab and Space characters are ignored in the input data.
    * This method is compatible with <code>sun.misc.BASE64Decoder.decodeBuffer(String)</code>.
    * @param s  A Base64 String to be decoded.
    * @return   An array containing the decoded data bytes.
    * @throws   IllegalArgumentException If the input is not valid Base64 encoded data.
    */
    public static byte[] decodeLines (String s) {
       char[] buf = new char[s.length()];
       int p = 0;
       for (int ip = 0; ip < s.length(); ip++) {
          char c = s.charAt(ip);
          if (c != ' ' && c != '\r' && c != '\n' && c != '\t')
             buf[p++] = c; }
       return decode(buf, 0, p); }

    /**
    * Decodes a byte array from Base64 format.
    * No blanks or line breaks are allowed within the Base64 encoded input data.
    * @param s  A Base64 String to be decoded.
    * @return   An array containing the decoded data bytes.
    * @throws   IllegalArgumentException If the input is not valid Base64 encoded data.
    */
    public static byte[] decode (String s) {
       return decode(s.toCharArray()); }

    /**
    * Decodes a byte array from Base64 format.
    * No blanks or line breaks are allowed within the Base64 encoded input data.
    * @param in  A character array containing the Base64 encoded data.
    * @return    An array containing the decoded data bytes.
    * @throws    IllegalArgumentException If the input is not valid Base64 encoded data.
    */
    public static byte[] decode (char[] in) {
       return decode(in, 0, in.length); }

    /**
    * Decodes a byte array from Base64 format.
    * No blanks or line breaks are allowed within the Base64 encoded input data.
    * @param in    A character array containing the Base64 encoded data.
    * @param iOff  Offset of the first character in <code>in</code> to be processed.
    * @param iLen  Number of characters to process in <code>in</code>, starting at <code>iOff</code>.
    * @return      An array containing the decoded data bytes.
    * @throws      IllegalArgumentException If the input is not valid Base64 encoded data.
    */
    public static byte[] decode (char[] in, int iOff, int iLen) {
       if (iLen%4 != 0) throw new IllegalArgumentException ("Length of Base64 encoded input string is not a multiple of 4.");
       while (iLen > 0 && in[iOff+iLen-1] == '=') iLen--;
       int oLen = (iLen*3) / 4;
       byte[] out = new byte[oLen];
       int ip = iOff;
       int iEnd = iOff + iLen;
       int op = 0;
       while (ip < iEnd) {
          int i0 = in[ip++];
          int i1 = in[ip++];
          int i2 = ip < iEnd ? in[ip++] : 'A';
          int i3 = ip < iEnd ? in[ip++] : 'A';
          if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127)
             throw new IllegalArgumentException ("Illegal character in Base64 encoded data.");
          int b0 = map2[i0];
          int b1 = map2[i1];
          int b2 = map2[i2];
          int b3 = map2[i3];
          if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0)
             throw new IllegalArgumentException ("Illegal character in Base64 encoded data.");
          int o0 = ( b0       <<2) | (b1>>>4);
          int o1 = ((b1 & 0xf)<<4) | (b2>>>2);
          int o2 = ((b2 &   3)<<6) |  b3;
          out[op++] = (byte)o0;
          if (op<oLen) out[op++] = (byte)o1;
          if (op<oLen) out[op++] = (byte)o2; }
       return out; }

    // Dummy constructor.
    private Base64Coder() {}
}

getting error while updating Composer

for php7 you can do that:

sudo apt-get install php-gd php-xml php7.0-mbstring

Remove characters from C# string

Here's a method I wrote that takes a slightly different approach. Rather than specifying the characters to remove, I tell my method which characters I want to keep -- it will remove all other characters.

In the OP's example, he only wants to keep alphabetical characters and spaces. Here's what a call to my method would look like (C# demo):

var str = "My name @is ,Wan.;'; Wan";

// "My name is Wan Wan"
var result = RemoveExcept(str, alphas: true, spaces: true);

Here's my method:

/// <summary>
/// Returns a copy of the original string containing only the set of whitelisted characters.
/// </summary>
/// <param name="value">The string that will be copied and scrubbed.</param>
/// <param name="alphas">If true, all alphabetical characters (a-zA-Z) will be preserved; otherwise, they will be removed.</param>
/// <param name="numerics">If true, all alphabetical characters (a-zA-Z) will be preserved; otherwise, they will be removed.</param>
/// <param name="dashes">If true, all alphabetical characters (a-zA-Z) will be preserved; otherwise, they will be removed.</param>
/// <param name="underlines">If true, all alphabetical characters (a-zA-Z) will be preserved; otherwise, they will be removed.</param>
/// <param name="spaces">If true, all alphabetical characters (a-zA-Z) will be preserved; otherwise, they will be removed.</param>
/// <param name="periods">If true, all decimal characters (".") will be preserved; otherwise, they will be removed.</param>
public static string RemoveExcept(string value, bool alphas = false, bool numerics = false, bool dashes = false, bool underlines = false, bool spaces = false, bool periods = false) {
    if (string.IsNullOrWhiteSpace(value)) return value;
    if (new[] { alphas, numerics, dashes, underlines, spaces, periods }.All(x => x == false)) return value;

    var whitelistChars = new HashSet<char>(string.Concat(
        alphas ? "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" : "",
        numerics ? "0123456789" : "",
        dashes ? "-" : "",
        underlines ? "_" : "",
        periods ? "." : "",
        spaces ? " " : ""
    ).ToCharArray());

    var scrubbedValue = value.Aggregate(new StringBuilder(), (sb, @char) => {
        if (whitelistChars.Contains(@char)) sb.Append(@char);
        return sb;
    }).ToString();

    return scrubbedValue;
}

Why is access to the path denied?

I was trying to use System.IO.File.OpenWrite(path)

and it did not work because I was only passing OpenWrite() a path to a directory, but it requires a path all the way to the file you want to write. So a full path including the filename.extension at the end needs to be passed into OpenWrite to avoid UnauthorizedAccessException

#pragma pack effect

#pragma pack instructs the compiler to pack structure members with particular alignment. Most compilers, when you declare a struct, will insert padding between members to ensure that they are aligned to appropriate addresses in memory (usually a multiple of the type's size). This avoids the performance penalty (or outright error) on some architectures associated with accessing variables that are not aligned properly. For example, given 4-byte integers and the following struct:

struct Test
{
   char AA;
   int BB;
   char CC;
};

The compiler could choose to lay the struct out in memory like this:

|   1   |   2   |   3   |   4   |  

| AA(1) | pad.................. |
| BB(1) | BB(2) | BB(3) | BB(4) | 
| CC(1) | pad.................. |

and sizeof(Test) would be 4 × 3 = 12, even though it only contains 6 bytes of data. The most common use case for the #pragma (to my knowledge) is when working with hardware devices where you need to ensure that the compiler does not insert padding into the data and each member follows the previous one. With #pragma pack(1), the struct above would be laid out like this:

|   1   |

| AA(1) |
| BB(1) |
| BB(2) |
| BB(3) |
| BB(4) |
| CC(1) |

And sizeof(Test) would be 1 × 6 = 6.

With #pragma pack(2), the struct above would be laid out like this:

|   1   |   2   | 

| AA(1) | pad.. |
| BB(1) | BB(2) |
| BB(3) | BB(4) |
| CC(1) | pad.. |

And sizeof(Test) would be 2 × 4 = 8.

Order of variables in struct is also important. With variables ordered like following:

struct Test
{
   char AA;
   char CC;
   int BB;
};

and with #pragma pack(2), the struct would be laid out like this:

|   1   |   2   | 

| AA(1) | CC(1) |
| BB(1) | BB(2) |
| BB(3) | BB(4) |

and sizeOf(Test) would be 3 × 2 = 6.

Switch focus between editor and integrated terminal in Visual Studio Code

Here is my approach, which provides a consistent way of navigating between active terminals as well as jumping between the terminal and editor panes without closing the terminal view. You can try adding this to your keybindings.json directly but I would recommend you go through the keybinding UI (cmd+K cmd+S on a Mac) so you can review/manage conflicts etc.

With this I can use ctrl+x <arrow direction> to navigate to any visible editor or terminal. Once the cursor is in the terminal section you can use ctrl+x ctrl+up or ctrl+x ctrl+down to cycle through the active terminals.

cmd-J is still used to hide/show the terminal pane.

    {
        "key": "ctrl+x right",
        "command": "workbench.action.terminal.focusNextPane",
        "when": "terminalFocus"
    },
    {
        "key": "ctrl+x left",
        "command": "workbench.action.terminal.focusPreviousPane",
        "when": "terminalFocus"
    },
    {
        "key": "ctrl+x ctrl+down",
        "command": "workbench.action.terminal.focusNext",
        "when": "terminalFocus"
    },
    {
        "key": "ctrl+x ctrl+up",
        "command": "workbench.action.terminal.focusPrevious",
        "when": "terminalFocus"
    },
    {
        "key": "ctrl+x up",
        "command": "workbench.action.navigateUp"
    },
    {
        "key": "ctrl+x down",
        "command": "workbench.action.navigateDown"
    },
    {
        "key": "ctrl+x left",
        "command": "workbench.action.navigateLeft",
        "when": "!terminalFocus"
    },
    {
        "key": "ctrl+x right",
        "command": "workbench.action.navigateRight",
        "when": "!terminalFocus"
    },

How can I parse a JSON file with PHP?

The quickest way to echo all json values is using loop in loop, the first loop is going to get all the objects and the second one the values...

foreach($data as $object) {

        foreach($object as $value) {

            echo $value;

        }

    }

Turn off enclosing <p> tags in CKEditor 3.0

Found it!

ckeditor.js line #91 ... search for

B.config.enterMode==3?'div':'p'

change to

B.config.enterMode==3?'div':'' (NO P!)

Dump your cache and BAM!

Android XXHDPI resources

A set of four generalized sizes: small, normal, large, and xlarge Note: Beginning with Android 3.2 (API level 13), these size groups are deprecated in favor of a new technique for managing screen sizes based on the available screen width. If you're developing for Android 3.2 and greater, see Declaring Tablet Layouts for Android 3.2 for more information.

A set of six generalized densities:

ldpi (low) ~120dpi

mdpi (medium) ~160dpi

hdpi (high) ~240dpi

xhdpi (extra-high) ~320dpi

xxhdpi (extra-extra-high) ~480dpi

xxxhdpi (extra-extra-extra-high) ~640dpi

From developer.android.com : http://developer.android.com/guide/practices/screens_support.html

PHP call Class method / function

Create object for the class and call, if you want to call it from other pages.

$obj = new Functions();

$var = $obj->filter($_GET['params']);

Or inside the same class instances [ methods ], try this.

$var = $this->filter($_GET['params']);

What is duck typing?

I think it's confused to mix up dynamic typing, static typing and duck typing. Duck typing is an independent concept and even static typed language like Go, could have a type checking system which implements duck typing. If a type system will check the methods of a (declared) object but not the type, it could be called a duck typing language.

T-SQL datetime rounded to nearest minute and nearest hours with using functions

I realize this question is ancient and there is an accepted and an alternate answer. I also realize that my answer will only answer half of the question, but for anyone wanting to round to the nearest minute and still have a datetime compatible value using only a single function:

CAST(YourValueHere as smalldatetime);

For hours or seconds, use Jeff Ogata's answer (the accepted answer) above.

Is there an easy way to check the .NET Framework version?

Update with .NET 4.6.2. Check Release value in the same registry as in previous responses:

RegistryKey registry_key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full");
if (registry_key == null)
    return false;
var val = registry_key.GetValue("Release", 0);
UInt32 Release = Convert.ToUInt32(val);

if (Release >= 394806) // 4.6.2 installed on all other Windows (different than Windows 10)
                return true;
if (Release >= 394802) // 4.6.2 installed on Windows 10 or later
                return true;

how do I change text in a label with swift?

use a simple formula: WHO.WHAT = VALUE

where,

WHO is the element in the storyboard you want to make changes to for eg. label

WHAT is the property of that element you wish to change for eg. text

VALUE is the change that you wish to be displayed

for eg. if I want to change the text from story text to You see a fork in the road in the label as shown in screenshot 1

In this case, our WHO is the label (element in the storyboard), WHAT is the text (property of element) and VALUE will be You see a fork in the road

so our final code will be as follows: Final code

screenshot 1 changes to screenshot 2 once the above code is executed.

I hope this solution helps you solve your issue. Thank you!

What is the difference between JDK and JRE?

enter image description here

JDK is a superset of JRE, and contains everything that is in JRE, plus tools such as the compilers and debuggers necessary for developing applets and applications. JRE provides the libraries, the Java Virtual Machine (JVM), and other components to run applets and applications written in the Java programming language.

Read input from console in Ruby?

There are many ways to take input from the users. I personally like using the method gets. When you use gets, it gets the string that you typed, and that includes the ENTER key that you pressed to end your input.

name = gets
"mukesh\n"

You can see this in irb; type this and you will see the \n, which is the “newline” character that the ENTER key produces: Type name = gets you will see somethings like "mukesh\n" You can get rid of pesky newline character using chomp method.

The chomp method gives you back the string, but without the terminating newline. Beautiful chomp method life saviour.

name = gets.chomp
"mukesh"

You can also use terminal to read the input. ARGV is a constant defined in the Object class. It is an instance of the Array class and has access to all the array methods. Since it’s an array, even though it’s a constant, its elements can be modified and cleared with no trouble. By default, Ruby captures all the command line arguments passed to a Ruby program (split by spaces) when the command-line binary is invoked and stores them as strings in the ARGV array.

When written inside your Ruby program, ARGV will take take a command line command that looks like this:

test.rb hi my name is mukesh

and create an array that looks like this:

["hi", "my", "name", "is", "mukesh"]

But, if I want to passed limited input then we can use something like this.

test.rb 12 23

and use those input like this in your program:

a = ARGV[0]
b = ARGV[1]

Detect change to ngModel on a select tag (Angular 2)

I have stumbled across this question and I will submit my answer that I used and worked pretty well. I had a search box that filtered and array of objects and on my search box I used the (ngModelChange)="onChange($event)"

in my .html

<input type="text" [(ngModel)]="searchText" (ngModelChange)="reSearch(newValue)" placeholder="Search">

then in my component.ts

reSearch(newValue: string) {
    //this.searchText would equal the new value
    //handle my filtering with the new value
}

How to get IP address of the device from code?

In your activity, the following function getIpAddress(context) returns the phone's IP address:

public static String getIpAddress(Context context) {
    WifiManager wifiManager = (WifiManager) context.getApplicationContext()
                .getSystemService(WIFI_SERVICE);

    String ipAddress = intToInetAddress(wifiManager.getDhcpInfo().ipAddress).toString();

    ipAddress = ipAddress.substring(1);

    return ipAddress;
}

public static InetAddress intToInetAddress(int hostAddress) {
    byte[] addressBytes = { (byte)(0xff & hostAddress),
                (byte)(0xff & (hostAddress >> 8)),
                (byte)(0xff & (hostAddress >> 16)),
                (byte)(0xff & (hostAddress >> 24)) };

    try {
        return InetAddress.getByAddress(addressBytes);
    } catch (UnknownHostException e) {
        throw new AssertionError();
    }
}

Unsupported operation :not writeable python

file = open('ValidEmails.txt','wb')
file.write(email.encode('utf-8', 'ignore'))

This is solve your encode error also.

Delete specific line from a text file?

This can be done in three steps:

// 1. Read the content of the file
string[] readText = File.ReadAllLines(path);

// 2. Empty the file
File.WriteAllText(path, String.Empty);

// 3. Fill up again, but without the deleted line
using (StreamWriter writer = new StreamWriter(path))
{
    foreach (string s in readText)
    {
        if (!s.Equals(lineToBeRemoved))
        {
            writer.WriteLine(s);
        }
    }
}

Fully backup a git repo?

You can backup the git repo with git-copy at minimum storage size.

git copy /path/to/project /backup/project.repo.backup

Then you can restore your project with git clone

git clone /backup/project.repo.backup project

Getting Exception(org.apache.poi.openxml4j.exception - no content type [M1.13]) when reading xlsx file using Apache POI?

Cleaned up the code (commented out the logger mostly) to make it run in my Eclipse environment.

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.*;

public class ReadXLSX {
private String filepath;
private XSSFWorkbook workbook;
// private static Logger logger=null;
private InputStream resourceAsStream;

public ReadXLSX(String filePath) {
    // logger=LoggerFactory.getLogger("ReadXLSX");
    this.filepath = filePath;
    resourceAsStream = ClassLoader.getSystemResourceAsStream(filepath);
}

public ReadXLSX(InputStream fileStream) {
    // logger=LoggerFactory.getLogger("ReadXLSX");
    this.resourceAsStream = fileStream;
}

private void loadFile() throws FileNotFoundException,
        NullObjectFoundException {

    if (resourceAsStream == null)
        throw new FileNotFoundException("Unable to locate give file..");
    else {
        try {
            workbook = new XSSFWorkbook(resourceAsStream);

        } catch (IOException ex) {

        }

    }
}// end loadxlsFile

public String[] getSheetsName() {
    int totalsheet = 0;
    int i = 0;
    String[] sheetName = null;

    try {
        loadFile();
        totalsheet = workbook.getNumberOfSheets();
        sheetName = new String[totalsheet];
        while (i < totalsheet) {
            sheetName[i] = workbook.getSheetName(i);
            i++;
        }

    } catch (FileNotFoundException ex) {
        // logger.error(ex);
    } catch (NullObjectFoundException ex) {
        // logger.error(ex);
    }

    return sheetName;
}

public int[] getSheetsIndex() {
    int totalsheet = 0;
    int i = 0;
    int[] sheetIndex = null;
    String[] sheetname = getSheetsName();
    try {
        loadFile();
        totalsheet = workbook.getNumberOfSheets();
        sheetIndex = new int[totalsheet];
        while (i < totalsheet) {
            sheetIndex[i] = workbook.getSheetIndex(sheetname[i]);
            i++;
        }

    } catch (FileNotFoundException ex) {
        // logger.error(ex);
    } catch (NullObjectFoundException ex) {
        // logger.error(ex);
    }

    return sheetIndex;
}

private boolean validateIndex(int index) {
    if (index < getSheetsIndex().length && index >= 0)
        return true;
    else
        return false;
}

public int getNumberOfSheet() {
    int totalsheet = 0;
    try {
        loadFile();
        totalsheet = workbook.getNumberOfSheets();

    } catch (FileNotFoundException ex) {
        // logger.error(ex.getMessage());
    } catch (NullObjectFoundException ex) {
        // logger.error(ex.getMessage());
    }

    return totalsheet;
}

public int getNumberOfColumns(int SheetIndex) {
    int NO_OF_Column = 0;
    @SuppressWarnings("unused")
    XSSFCell cell = null;
    XSSFSheet sheet = null;
    try {
        loadFile(); // load give Excel
        if (validateIndex(SheetIndex)) {
            sheet = workbook.getSheetAt(SheetIndex);
            Iterator<Row> rowIter = sheet.rowIterator();
            XSSFRow firstRow = (XSSFRow) rowIter.next();
            Iterator<Cell> cellIter = firstRow.cellIterator();
            while (cellIter.hasNext()) {
                cell = (XSSFCell) cellIter.next();
                NO_OF_Column++;
            }
        } else
            throw new InvalidSheetIndexException("Invalid sheet index.");
    } catch (Exception ex) {
        // logger.error(ex.getMessage());

    }

    return NO_OF_Column;
}

public int getNumberOfRows(int SheetIndex) {
    int NO_OF_ROW = 0;
    XSSFSheet sheet = null;

    try {
        loadFile(); // load give Excel
        if (validateIndex(SheetIndex)) {
            sheet = workbook.getSheetAt(SheetIndex);
            NO_OF_ROW = sheet.getLastRowNum();
        } else
            throw new InvalidSheetIndexException("Invalid sheet index.");
    } catch (Exception ex) {
        // logger.error(ex);
    }

    return NO_OF_ROW;
}

public String[] getSheetHeader(int SheetIndex) {
    int noOfColumns = 0;
    XSSFCell cell = null;
    int i = 0;
    String columns[] = null;
    XSSFSheet sheet = null;

    try {
        loadFile(); // load give Excel
        if (validateIndex(SheetIndex)) {
            sheet = workbook.getSheetAt(SheetIndex);
            noOfColumns = getNumberOfColumns(SheetIndex);
            columns = new String[noOfColumns];
            Iterator<Row> rowIter = sheet.rowIterator();
            XSSFRow Row = (XSSFRow) rowIter.next();
            Iterator<Cell> cellIter = Row.cellIterator();

            while (cellIter.hasNext()) {
                cell = (XSSFCell) cellIter.next();
                columns[i] = cell.getStringCellValue();
                i++;
            }
        } else
            throw new InvalidSheetIndexException("Invalid sheet index.");
    }

    catch (Exception ex) {
        // logger.error(ex);
    }

    return columns;
}// end of method

public String[][] getSheetData(int SheetIndex) {
    int noOfColumns = 0;
    XSSFRow row = null;
    XSSFCell cell = null;
    int i = 0;
    int noOfRows = 0;
    int j = 0;
    String[][] data = null;
    XSSFSheet sheet = null;

    try {
        loadFile(); // load give Excel
        if (validateIndex(SheetIndex)) {
            sheet = workbook.getSheetAt(SheetIndex);
            noOfColumns = getNumberOfColumns(SheetIndex);
            noOfRows = getNumberOfRows(SheetIndex) + 1;
            data = new String[noOfRows][noOfColumns];
            Iterator<Row> rowIter = sheet.rowIterator();
            while (rowIter.hasNext()) {
                row = (XSSFRow) rowIter.next();
                Iterator<Cell> cellIter = row.cellIterator();
                j = 0;
                while (cellIter.hasNext()) {
                    cell = (XSSFCell) cellIter.next();
                    if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
                        data[i][j] = cell.getStringCellValue();
                    } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                        if (HSSFDateUtil.isCellDateFormatted(cell)) {
                            String formatCellValue = new DataFormatter()
                                    .formatCellValue(cell);
                            data[i][j] = formatCellValue;
                        } else {
                            data[i][j] = Double.toString(cell
                                    .getNumericCellValue());
                        }

                    } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
                        data[i][j] = Boolean.toString(cell
                                .getBooleanCellValue());
                    }

                    else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
                        data[i][j] = cell.getCellFormula().toString();
                    }

                    j++;
                }

                i++;
            } // outer while

        } else
            throw new InvalidSheetIndexException("Invalid sheet index.");

    } catch (Exception ex) {
        // logger.error(ex);
    }
    return data;
}

public String[][] getSheetData(int SheetIndex, int noOfRows) {
    int noOfColumns = 0;
    XSSFRow row = null;
    XSSFCell cell = null;
    int i = 0;
    int j = 0;
    String[][] data = null;
    XSSFSheet sheet = null;

    try {
        loadFile(); // load give Excel

        if (validateIndex(SheetIndex)) {
            sheet = workbook.getSheetAt(SheetIndex);
            noOfColumns = getNumberOfColumns(SheetIndex);
            data = new String[noOfRows][noOfColumns];
            Iterator<Row> rowIter = sheet.rowIterator();
            while (i < noOfRows) {

                row = (XSSFRow) rowIter.next();
                Iterator<Cell> cellIter = row.cellIterator();
                j = 0;
                while (cellIter.hasNext()) {
                    cell = (XSSFCell) cellIter.next();
                    if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
                        data[i][j] = cell.getStringCellValue();
                    } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                        if (HSSFDateUtil.isCellDateFormatted(cell)) {
                            String formatCellValue = new DataFormatter()
                                    .formatCellValue(cell);
                            data[i][j] = formatCellValue;
                        } else {
                            data[i][j] = Double.toString(cell
                                    .getNumericCellValue());
                        }
                    }

                    j++;
                }

                i++;
            } // outer while
        } else
            throw new InvalidSheetIndexException("Invalid sheet index.");
    } catch (Exception ex) {
        // logger.error(ex);
    }

    return data;
}
}

Created this little testcode:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;


public class ReadXLSXTest {

/**
 * @param args
 * @throws FileNotFoundException 
 */
public static void main(String[] args) throws FileNotFoundException {
    // TODO Auto-generated method stub


    ReadXLSX test = new ReadXLSX(new FileInputStream(new File("./sample.xlsx")));

    System.out.println(test.getSheetsName());
    System.out.println(test.getNumberOfSheet());


}

}

All this ran like a charm, so my guess is you have an XLSX file that is 'corrupt' in one way or another. Try testing with other data.

Cheers, Wim

Converting A String To Hexadecimal In Java

Here's a short way to convert it to hex:

public String toHex(String arg) {
    return String.format("%040x", new BigInteger(1, arg.getBytes(/*YOUR_CHARSET?*/)));
}

How to adjust text font size to fit textview

I wrote a short helper class that makes a textview fit within a certain width and adds ellipsize "..." at the end if the minimum textsize cannot be achieved.

Keep in mind that it only makes the text smaller until it fits or until the minimum text size is reached. To test with large sizes, set the textsize to a large number before calling the help method.

It takes Pixels, so if you are using values from dimen, you can call it like this:


float minTextSizePx = getResources().getDimensionPixelSize(R.dimen.min_text_size);
float maxTextWidthPx = getResources().getDimensionPixelSize(R.dimen.max_text_width);
WidgetUtils.fitText(textView, text, minTextSizePx, maxTextWidthPx);

This is the class I use:


public class WidgetUtils {

    public static void fitText(TextView textView, String text, float minTextSizePx, float maxWidthPx) {
        textView.setEllipsize(null);
        int size = (int)textView.getTextSize();
        while (true) {
            Rect bounds = new Rect();
            Paint textPaint = textView.getPaint();
            textPaint.getTextBounds(text, 0, text.length(), bounds);
            if(bounds.width() < maxWidthPx){
                break;
            }
            if (size <= minTextSizePx) {
                textView.setEllipsize(TextUtils.TruncateAt.END);
                break;
            }
            size -= 1;
            textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
        }
    }
}

Sort an array of objects in React and render them

this.state.data.sort((a, b) => a.item.timeM > b.item.timeM).map(
    (item, i) => <div key={i}> {item.matchID} {item.timeM} {item.description}</div>
)

How to dynamically create CSS class in JavaScript and apply?

Although I'm not sure why you want to create CSS classes with JavaScript, here is an option:

var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.cssClass { color: #F00; }';
document.getElementsByTagName('head')[0].appendChild(style);

document.getElementById('someElementId').className = 'cssClass';

How can you float: right in React Native?

<View style={{ flex: 1, flexDirection: 'row', justifyContent: 'flex-end' }}>
  <Text>
  Some Text
  </Text>
</View>

flexDirection: If you want to move horizontally (row) or vertically (column)

justifyContent: the direction you want to move.

How do I add a simple jQuery script to WordPress?

In WordPress, the correct way to include the scripts in your website is by using the following functions.

wp_register_script( $handle, $src )
wp_enqueue_script( $handle, $src )

These functions are called inside the hook wp_enqueue_script.

For more details and examples, you can check Adding JS files in Wordpress using wp_register_script & wp_enqueue_script

Example:

function webolute_theme_scripts() {
    wp_register_script( 'script-name', get_template_directory_uri() . '/js/example.js', array('jquery'), '1.0.0', true );
    wp_enqueue_script( 'script-name' );
}
add_action( 'wp_enqueue_scripts', 'webolute_theme_scripts' );

create a trusted self-signed SSL cert for localhost (for use with Express/Node)

The answers above were partial. I've spent so much time getting this working, it's insane. Note to my future self, here is what you need to do:

I'm working on Windows 10, with Chrome 65. Firefox is behaving nicely - just confirm localhost as a security exception and it will work. Chrome doesn't:

Step 1. in your backend, create a folder called security. we will work inside it.

Step 2. create a request config file named req.cnf with the following content (credit goes to: @Anshul)

req.cnf :

[req]
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no
[req_distinguished_name]
C = Country initials like US, RO, GE
ST = State
L = Location
O = Organization Name
OU = Organizational Unit 
CN = www.localhost.com
[v3_req]
keyUsage = critical, digitalSignature, keyAgreement
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
[alt_names]
DNS.1 = www.localhost.com
DNS.2 = localhost.com
DNS.3 = localhost

An explanation of this fields is here.

Step 3. navigate to the security folder in the terminal and type the following command :

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout cert.key -out cert.pem -config req.cnf -sha256

Step 4. then outside of security folder, in your express app do something like this: (credit goes to @Diego Mello)

backend 
 /security
 /server.js

server.js:

const express = require('express')
const app = express()
const https = require('https')
const fs = require('fs')
const port = 3000

app.get('/', (req, res) => {
    res.send("IT'S WORKING!")
})

const httpsOptions = {
    key: fs.readFileSync('./security/cert.key'),
    cert: fs.readFileSync('./security/cert.pem')
}
const server = https.createServer(httpsOptions, app)
    .listen(port, () => {
        console.log('server running at ' + port)
    })

Step 5. start the server, node server.js, and go to https://localhost:3000.

At this point we have the server setup. But the browser should show a warning message.

We need to register our self-signed certificate, as a CA trusted Certificate Authority, in the chrome/windows certificates store. (chrome also saves this in windows,)

Step 6. open Dev Tools in chrome, go to Security panel, then click on View Certificate. enter image description here

Step 7. go to Details panel, click Copy File, then when the Certificate Export Wizard appears, click Next as below:

go to details - copy file - next on export wizard

Step 8. leave DER encoding, click next, choose Browse, put it on a easy to access folder like Desktop, and name the certificate localhost.cer, then click Save and then Finish.. You should be able to see your certificate on Desktop.

Step 9. Open chrome://settings/ by inserting it in the url box. Down below, click on Advanced / Advanced Options, then scroll down to find Manage Certificates.

choose manage certificates

Step 10. Go to Trusted Root Certification Authorities panel, and click import.

Go to Trusted Root Certification Authorities panel, and click import

We will import the localhost.cer certificate we just finished exporting in step 8.

Step 11. click browse, find the localhost.cer, leave the default values click next a bunch of times - until this warning appears, click yes.

confirm security exception

Step 12. close everything, and restart chrome. Then, when going to https://localhost:3000 you should see: gotta love the green

How to display pdf in php

Simple way to display pdf files from database and we can download it.
$resume is pdf file name which comes from database.
../resume/filename is path of folder where your file is stored.

<a href="../resumes/<?php echo $resume; ?>"/><?php echo $resume; ?></a>

How to drop all tables in a SQL Server database?

The fasted way is:

  1. New Database Diagrams
  2. Add all table
  3. Ctrl + A to select all
  4. Right Click "Remove from Database"
  5. Ctrl + S to save
  6. Enjoy

Delete rows from multiple tables using a single query (SQL Express 2005) with a WHERE condition

$qry = "DELETE lg., l. FROM lessons_game lg RIGHT JOIN lessons l ON lg.lesson_id = l.id WHERE l.id = ?";

lessons is Main table and lessons_game is subtable so Right Join

Initialize a vector array of strings

same as @Moo-Juice:

const char* args[] = {"01", "02", "03", "04"};
std::vector<std::string> v(args, args + sizeof(args)/sizeof(args[0])); //get array size

Two inline-block, width 50% elements wrap to second line

It is because display:inline-block takes into account white-space in the html. If you remove the white-space between the div's it works as expected. Live Example: http://jsfiddle.net/XCDsu/4/

<div id="col1">content</div><div id="col2">content</div>

How to capture the android device screen content?

Framebuffer seems the way to go, it will not always contain 2+ frames like mentioned by Ryan Conrad. In my case it contained only one. I guess it depends on the frame/display size.

I tried to read the framebuffer continuously but it seems to return for a fixed amount of bytes read. In my case that is (3 410 432) bytes, which is enough to store a display frame of 854*480 RGBA (3 279 360 bytes). Yes, the frame in binary outputed from fb0 is RGBA in my device. This will most likely depend from device to device. This will be important for you to decode it =)

In my device /dev/graphics/fb0 permissions are so that only root and users from group graphics can read the fb0. graphics is a restricted group so you will probably only access fb0 with a rooted phone using su command.

Android apps have the user id (uid) app_## and group id (guid) app_## .

adb shell has uid shell and guid shell, which has much more permissions than an app. You can actually check those permissions at /system/permissions/platform.xml

This means you will be able to read fb0 in the adb shell without root but you will not read it within the app without root.

Also, giving READ_FRAME_BUFFER and/or ACCESS_SURFACE_FLINGER permissions on AndroidManifest.xml will do nothing for a regular app because these will only work for 'signature' apps.

How can I create a border around an Android LinearLayout?

This solution will only add the border, the body of the LinearLayout will be transparent.

First, Create this border drawable in the drawable folder, border.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android= "http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <stroke android:width="2dp" android:color="#ec0606"/>
    <corners android:radius="10dp"/>
</shape>

Then, in your LinearLayout View, add the border.xml as the background like this

<LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@drawable/border">

How do I include image files in Django templates?

Another way to do it:

MEDIA_ROOT = '/home/USER/Projects/REPO/src/PROJECT/APP/static/media/'
MEDIA_URL = '/static/media/'

This would require you to move your media folder to a sub directory of a static folder.

Then in your template you can use:

<img class="scale-with-grid" src="{{object.photo.url}}"/>

How to insert an item into an array at a specific index (JavaScript)?

Taking profit of reduce method as following:

function insert(arr, val, index) {
    return index >= arr.length 
        ? arr.concat(val)
        : arr.reduce((prev, x, i) => prev.concat(i === index ? [val, x] : x), []);
}

So at this way we can return a new array (will be a cool functional way - more much better than use push or splice) with the element inserted at index, and if the index is greater than the length of the array it will be inserted at the end.

Difference between web reference and service reference?

Service references deal with endpoints and bindings, which are completely configurable. They let you point your client proxy to a WCF via any transport protocol (HTTP, TCP, Shared Memory, etc)

They are designed to work with WCF.

If you use a WebProxy, you are pretty much binding yourself to using WCF over HTTP

Returning a regex match in VBA (excel)

You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).

For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.

Function ExtractSDI(ByVal text As String) As String

Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)

If allMatches.count <> 0 Then
    result = allMatches.Item(0).submatches.Item(0)
End If

ExtractSDI = result

End Function

If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:

Ex) =RegexExtract(A1, "(sdi \d+)", ", ")

Here is:

Function RegexExtract(ByVal text As String, _
                      ByVal extract_what As String, _
                      Optional seperator As String = "") As String

Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)

For i = 0 To allMatches.count - 1
    For j = 0 To allMatches.Item(i).submatches.count - 1
        result = result & seperator & allMatches.Item(i).submatches.Item(j)
    Next
Next

If Len(result) <> 0 Then
    result = Right(result, Len(result) - Len(seperator))
End If

RegexExtract = result

End Function

*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.

How to display Woocommerce Category image?

To display the category image for the currently displayed category in archive-product.php, use the current category term_id when is_product_category() is true:

// verify that this is a product category page
if ( is_product_category() ){
    global $wp_query;

    // get the query object
    $cat = $wp_query->get_queried_object();

    // get the thumbnail id using the queried category term_id
    $thumbnail_id = get_term_meta( $cat->term_id, 'thumbnail_id', true ); 

    // get the image URL
    $image = wp_get_attachment_url( $thumbnail_id ); 

    // print the IMG HTML
    echo "<img src='{$image}' alt='' width='762' height='365' />";
}

Elastic Search: how to see the indexed data

Following @JanKlimo example, on terminal all you have to do is:

to see all the Index: $ curl -XGET 'http://127.0.0.1:9200/_cat/indices?v'

to see content of Index products_development_20160517164519304: $ curl -XGET 'http://127.0.0.1:9200/products_development_20160517164519304/_search?pretty=1'

Read .mat files in Python

An import is required, import scipy.io...

import scipy.io
mat = scipy.io.loadmat('file.mat')

How to call Stored Procedure in Entity Framework 6 (Code-First)?

if you wanna pass table params into stored procedure, you must necessary set TypeName property for your table params.

SqlParameter codesParam = new SqlParameter(CODES_PARAM, SqlDbType.Structured);
            SqlParameter factoriesParam = new SqlParameter(FACTORIES_PARAM, SqlDbType.Structured);

            codesParam.Value = tbCodes;
            codesParam.TypeName = "[dbo].[MES_CodesType]";
            factoriesParam.Value = tbfactories;
            factoriesParam.TypeName = "[dbo].[MES_FactoriesType]";


            var list = _context.Database.SqlQuery<MESGoodsRemain>($"{SP_NAME} {CODES_PARAM}, {FACTORIES_PARAM}"
                , new SqlParameter[] {
                   codesParam,
                   factoriesParam
                }
                ).ToList();

Inserting multiple rows in a single SQL query?

In SQL Server 2008 you can insert multiple rows using a single SQL INSERT statement.

INSERT INTO MyTable ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )

For reference to this have a look at MOC Course 2778A - Writing SQL Queries in SQL Server 2008.

For example:

INSERT INTO MyTable
  ( Column1, Column2, Column3 )
VALUES
  ('John', 123, 'Lloyds Office'), 
  ('Jane', 124, 'Lloyds Office'), 
  ('Billy', 125, 'London Office'),
  ('Miranda', 126, 'Bristol Office');

Under what circumstances can I call findViewById with an Options Menu / Action Bar item?

I am trying to obtain a handle on one of the views in the Action Bar

I will assume that you mean something established via android:actionLayout in your <item> element of your <menu> resource.

I have tried calling findViewById(R.id.menu_item)

To retrieve the View associated with your android:actionLayout, call findItem() on the Menu to retrieve the MenuItem, then call getActionView() on the MenuItem. This can be done any time after you have inflated the menu resource.

Python variables as keys to dict

for i in ('apple', 'banana', 'carrot'):
    fruitdict[i] = locals()[i]

How to list the tables in a SQLite database file that was opened with ATTACH?

As of the latest versions of SQLite 3 you can issue:

.fullschema

to see all of your create statements.

Jquery: Checking to see if div contains text, then action

Why not simply

var item = $('.field-item');
for (var i = 0; i <= item.length; i++) {
       if ($(item[i]).text() == 'someText') {
             $(item[i]).addClass('thisClass');
             //do some other stuff here
          }
     }

Javascript: Fetch DELETE and PUT requests

Ok, here is a fetch DELETE example too:

fetch('https://example.com/delete-item/' + id, {
  method: 'DELETE',
})
.then(res => res.text()) // or res.json()
.then(res => console.log(res))

How do I sort strings alphabetically while accounting for value when a string is numeric?

Expanding on Jeff Paulsen answer. I wanted to make sure it didn't matter how many number or char groups were in the strings:

public class SemiNumericComparer : IComparer<string>
{
    public int Compare(string s1, string s2)
    {
        if (int.TryParse(s1, out var i1) && int.TryParse(s2, out var i2))
        {
            if (i1 > i2)
            {
                return 1;
            }

            if (i1 < i2)
            {
                return -1;
            }

            if (i1 == i2)
            {
                return 0;
            }
        }

        var text1 = SplitCharsAndNums(s1);
        var text2 = SplitCharsAndNums(s2);

        if (text1.Length > 1 && text2.Length > 1)
        {

            for (var i = 0; i < Math.Max(text1.Length, text2.Length); i++)
            {

                if (text1[i] != null && text2[i] != null)
                {
                    var pos = Compare(text1[i], text2[i]);
                    if (pos != 0)
                    {
                        return pos;
                    }
                }
                else
                {
                    //text1[i] is null there for the string is shorter and comes before a longer string.
                    if (text1[i] == null)
                    {
                        return -1;
                    }
                    if (text2[i] == null)
                    {
                        return 1;
                    }
                }
            }
        }

        return string.Compare(s1, s2, true);
    }

    private string[] SplitCharsAndNums(string text)
    {
        var sb = new StringBuilder();
        for (var i = 0; i < text.Length - 1; i++)
        {
            if ((!char.IsDigit(text[i]) && char.IsDigit(text[i + 1])) ||
                (char.IsDigit(text[i]) && !char.IsDigit(text[i + 1])))
            {
                sb.Append(text[i]);
                sb.Append(" ");
            }
            else
            {
                sb.Append(text[i]);
            }
        }

        sb.Append(text[text.Length - 1]);

        return sb.ToString().Split(' ');
    }
}

I also took SplitCharsAndNums from an SO Page after amending it to deal with file names.

No more data to read from socket error

We were facing same problem, we resolved it by increasing initialSize and maxActive size of connection pool.

You can check this link

Maybe this helps someone.

gnuplot - adjust size of key/legend

To adjust the length of the samples:

set key samplen X

(default is 4)

To adjust the vertical spacing of the samples:

set key spacing X

(default is 1.25)

and (for completeness), to adjust the fontsize:

set key font "<face>,<size>"

(default depends on the terminal)

And of course, all these can be combined into one line:

set key samplen 2 spacing .5 font ",8"

Note that you can also change the position of the key using set key at <position> or any one of the pre-defined positions (which I'll just defer to help key at this point)

commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated

Got stuck with this issue myself and found one more cause for this problem. If you don't have setter methods in your backing bean for the properties used in your *.xhtml , then the action is simply not invoked.

How can I convert NSDictionary to NSData and vice versa?

Use NSJSONSerialization:

NSDictionary *dict;
NSData *dataFromDict = [NSJSONSerialization dataWithJSONObject:dict
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];

NSDictionary *dictFromData = [NSJSONSerialization JSONObjectWithData:dataFromDict
                                                             options:NSJSONReadingAllowFragments
                                                               error:&error];

The latest returns id, so its a good idea to check the returned object type after you cast (here i casted to NSDictionary).

How to query a CLOB column in Oracle

For big CLOB selects also can be used:

SELECT dbms_lob.substr( column_name, dbms_lob.getlength(column_name), 1) FROM foo

How to efficiently count the number of keys/properties of an object in JavaScript?

as answered above: Object.keys(obj).length

But: as we have now a real Map class in ES6, I would suggest to use it instead of using the properties of an object.

const map = new Map();
map.set("key", "value");
map.size; // THE fastest way

C++ correct way to return pointer to array from function

In a real app, the way you returned the array is called using an out parameter. Of course you don't actually have to return a pointer to the array, because the caller already has it, you just need to fill in the array. It's also common to pass another argument specifying the size of the array so as to not overflow it.

Using an out parameter has the disadvantage that the caller may not know how large the array needs to be to store the result. In that case, you can return a std::vector or similar array class instance.

Should I use <i> tag for icons instead of <span>?

I thought this looked pretty bad - because I was working on a Joomla template recently and I kept getting the template failing W3C because it was using the <i> tag and that had deprecated, as it's original use was to italicize something, which is now done through CSS not HTML any more.

It does make really bad practice because when I saw it I went through the template and changed all the <i> tags to <span style="font-style:italic"> instead and then wondered why the entire template looked strange.

This is the main reason it is a bad idea to use the <i> tag in this way - you never know who is going to look at your work afterwards and "assume" that what you were really trying to do is italicize the text rather than display an icon. I've just put some icons in a website and I did it with the following code

<img class="icon" src="electricity.jpg" alt="Electricity" title="Electricity">

that way I've got all my icons in one class so any changes I make affects all the icons (say I wanted them larger or smaller, or rounded borders, etc), the alt text gives screen readers the chance to tell the person what the icon is rather than possibly getting just "text in italics, end of italics" (I don't exactly know how screen readers read screens but I guess it's something like that), and the title also gives the user a chance to mouse over the image and get a tooltip telling them what the icon is in case they can't figure it out. Much better than using <i> - and also it passes W3C standard.

How to Convert Boolean to String

The other solutions here all have caveats (though they address the question at hand). If you are (1) looping over mixed-types or (2) want a generic solution that you can export as a function or include in your utilities, none of the other solutions here will work.

The simplest and most self-explanatory solution is:

// simplest, most-readable
if (is_bool($res) {
    $res = $res ? 'true' : 'false';
}

// same as above but written more tersely
$res = is_bool($res) ? ($res ? 'true' : 'false') : $res;

// Terser still, but completely unnecessary  function call and must be
// commented due to poor readability. What is var_export? What is its
// second arg? Why are we exporting stuff?
$res = is_bool($res) ? var_export($res, 1) : $res;

But most developers reading your code will require a trip to http://php.net/var_export to understand what the var_export does and what the second param is.

1. var_export

Works for boolean input but converts everything else to a string as well.

// OK
var_export(false, 1); // 'false'
// OK
var_export(true, 1);  // 'true'
// NOT OK
var_export('', 1);  // '\'\''
// NOT OK
var_export(1, 1);  // '1'

2. ($res) ? 'true' : 'false';

Works for boolean input but converts everything else (ints, strings) to true/false.

// OK
true ? 'true' : 'false' // 'true'
// OK
false ? 'true' : 'false' // 'false'
// NOT OK
'' ? 'true' : 'false' // 'false'
// NOT OK
0 ? 'true' : 'false' // 'false'

3. json_encode()

Same issues as var_export and probably worse since json_encode cannot know if the string true was intended a string or a boolean.

php stdClass to array

Just googled it, and found here a handy function that is useful for converting stdClass object to array recursively.

<?php
function object_to_array($object) {
 if (is_object($object)) {
  return array_map(__FUNCTION__, get_object_vars($object));
 } else if (is_array($object)) {
  return array_map(__FUNCTION__, $object);
 } else {
  return $object;
 }
}
?>

EDIT: I updated this answer with content from linked source (which is also changed now), thanks to mason81 for suggesting me.

How to resolve : Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

This should work

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

and moreover please let us know why are you importing all these class

<%@ page import="com.library.controller.*"%> 
<%@ page import="com.library.dao.*" %> 
<%@ page import="java.util.*" %> 
<%@ page import="java.lang.*" %> 
<%@ page import="java.util.Date" %>

We don't need to include java.lang as it is the default package.

How to change the ROOT application?

In Tomcat 7 (under Windows server) I didn't add or edit anything to any configuration file. I just renamed the ROOT folder to something else and renamed my application folder to ROOT and it worked fine.

Wi-Fi Direct and iOS Support

It took me a while to find out what is going on, but here is the summary. I hope this save people a lot of time.

Apple are not playing nice with Wi-Fi Direct, not in the same way that Android is. The Multipeer Connectivity Framework that Apple provides combines both BLE and WiFi Direct together and will only work with Apple devices and not any device that is using Wi-Fi Direct.

https://developer.apple.com/library/ios/documentation/MultipeerConnectivity/Reference/MultipeerConnectivityFramework/index.html

It states the following in this documentation - "The Multipeer Connectivity framework provides support for discovering services provided by nearby iOS devices using infrastructure Wi-Fi networks, peer-to-peer Wi-Fi, and Bluetooth personal area networks and subsequently communicating with those services by sending message-based data, streaming data, and resources (such as files)."

Additionally, Wi-Fi direct in this mode between i-Devices will need iPhone 5 and above.

There are apps that use a form of Wi-Fi Direct on the App Store, but these are using their own libraries.

Laravel: Validation unique on update

Test below code:

'email' => 'required|email|unique:users,email_address,'. $id .'ID'

Where ID is the primary id of the table

How to add 30 minutes to a JavaScript Date object?

Using a Library

If you are doing a lot of date work, you may want to look into JavaScript date libraries like Datejs or Moment.js. For example, with Moment.js, this is simply:

var newDateObj = moment(oldDateObj).add(30, 'm').toDate();

Vanilla Javascript

This is like chaos's answer, but in one line:

var newDateObj = new Date(oldDateObj.getTime() + diff*60000);

Where diff is the difference in minutes you want from oldDateObj's time. It can even be negative.

Or as a reusable function, if you need to do this in multiple places:

function addMinutes(date, minutes) {
    return new Date(date.getTime() + minutes*60000);
}

And just in case this is not obvious, the reason we multiply minutes by 60000 is to convert minutes to milliseconds.

Be Careful with Vanilla Javascript. Dates Are Hard!

You may think you can add 24 hours to a date to get tomorrow's date, right? Wrong!

addMinutes(myDate, 60*24); //DO NOT DO THIS

It turns out, if the user observes daylight saving time, a day is not necessarily 24 hours long. There is one day a year that is only 23 hours long, and one day a year that is 25 hours long. For example, in most of the United States and Canada, 24 hours after midnight, Nov 2, 2014, is still Nov 2:

const NOV = 10; //because JS months are off by one...
addMinutes(new Date(2014, NOV, 2), 60*24); //In USA, prints 11pm on Nov 2, not 12am Nov 3!

This is why using one of the afore-mentioned libraries is a safer bet if you have to do a lot of work with this.

Below is a more generic version of this function that I wrote. I'd still recommend using a library, but that may be overkill/impossible for your project. The syntax is modeled after MySQL DATE_ADD function.

/**
 * Adds time to a date. Modelled after MySQL DATE_ADD function.
 * Example: dateAdd(new Date(), 'minute', 30)  //returns 30 minutes from now.
 * https://stackoverflow.com/a/1214753/18511
 * 
 * @param date  Date to start with
 * @param interval  One of: year, quarter, month, week, day, hour, minute, second
 * @param units  Number of units of the given interval to add.
 */
function dateAdd(date, interval, units) {
  if(!(date instanceof Date))
    return undefined;
  var ret = new Date(date); //don't change original date
  var checkRollover = function() { if(ret.getDate() != date.getDate()) ret.setDate(0);};
  switch(String(interval).toLowerCase()) {
    case 'year'   :  ret.setFullYear(ret.getFullYear() + units); checkRollover();  break;
    case 'quarter':  ret.setMonth(ret.getMonth() + 3*units); checkRollover();  break;
    case 'month'  :  ret.setMonth(ret.getMonth() + units); checkRollover();  break;
    case 'week'   :  ret.setDate(ret.getDate() + 7*units);  break;
    case 'day'    :  ret.setDate(ret.getDate() + units);  break;
    case 'hour'   :  ret.setTime(ret.getTime() + units*3600000);  break;
    case 'minute' :  ret.setTime(ret.getTime() + units*60000);  break;
    case 'second' :  ret.setTime(ret.getTime() + units*1000);  break;
    default       :  ret = undefined;  break;
  }
  return ret;
}

Working jsFiddle demo.

Prevent redirect after form is submitted

If you can run javascript, which seems like you can, create a new iframe, and post to that iframe instead. You can do <form target="iframe-id" ...> That way all the redirects happen in the iframe and you still have control of the page.

The other solution is to also do a post via ajax. But that's a little more tricky if the page needs to error check or something.

Here is an example:

$("<iframe id='test' />").appendTo(document.body);
$("form").attr("target", "test");

Obtain smallest value from array in Javascript?

Possibly an easier way?

Let's say justPrices is mixed up in terms of value, so you don't know where the smallest value is.

justPrices[0] = 4.5
justPrices[1] = 9.9
justPrices[2] = 1.5

Use sort.

justPrices.sort();

It would then put them in order for you. (Can also be done alphabetically.) The array then would be put in ascending order.

justPrices[0] = 1.5
justPrices[1] = 4.5
justPrices[2] = 9.9

You can then easily grab by the first index.

justPrices[0]

I find this is a bit more useful than what's proposed above because what if you need the lowest 3 numbers as an example? You can also switch which order they're arranged, more info at http://www.w3schools.com/jsref/jsref_sort.asp

Can you append strings to variables in PHP?

In PHP use .= to append strings, and not +=.

Why does this output 0? [...] Does PHP not like += with strings?

+= is an arithmetic operator to add a number to another number. Using that operator with strings leads to an automatic type conversion. In the OP's case the strings have been converted to integers of the value 0.


More about operators in PHP:

Foreign key constraints: When to use ON UPDATE and ON DELETE

Addition to @MarkR answer - one thing to note would be that many PHP frameworks with ORMs would not recognize or use advanced DB setup (foreign keys, cascading delete, unique constraints), and this may result in unexpected behaviour.

For example if you delete a record using ORM, and your DELETE CASCADE will delete records in related tables, ORM's attempt to delete these related records (often automatic) will result in error.

Select a dummy column with a dummy value in SQL?

Try this:

select col1, col2, 'ABC' as col3 from Table1 where col1 = 0;

How to make an element width: 100% minus padding?

Move the input box' padding to a wrapper element.

<style>
div.outer{ background: red; padding: 10px; }
div.inner { border: 1px solid #888; padding: 5px 10px; background: white; }
input { width: 100%; border: none }
</style>

<div class="outer">
    <div class="inner">
       <input/>
    </div>
</div>

See example here: http://jsfiddle.net/L7wYD/1/

How do I create delegates in Objective-C?

Answer is actually answered, but I would like to give you a "cheat sheet" for creating a delegate:

DELEGATE SCRIPT

CLASS A - Where delegate is calling function

@protocol <#Protocol Name#> <NSObject>

-(void)delegateMethod;

@end

@interface <#Some ViewController#> : <#UIViewController#> 

@property (nonatomic, assign) id <<#Protocol Name#>> delegate;

@end


@implementation <#Some ViewController#> 

-(void)someMethod {
    [self.delegate methodName];
}

@end




CLASS B - Where delegate is called 

@interface <#Other ViewController#> (<#Delegate Name#>) {}
@end

@implementation <#Other ViewController#> 

-(void)otherMethod {
    CLASSA *classA = [[CLASSA alloc] init];

    [classA setDelegate:self];
}

-delegateMethod() {

}

@end

What is the purpose of the single underscore "_" variable in Python?

_ has 3 main conventional uses in Python:

  1. To hold the result of the last executed expression(/statement) in an interactive interpreter session (see docs). This precedent was set by the standard CPython interpreter, and other interpreters have followed suit

  2. For translation lookup in i18n (see the gettext documentation for example), as in code like

    raise forms.ValidationError(_("Please enter a correct username"))
    
  3. As a general purpose "throwaway" variable name:

    1. To indicate that part of a function result is being deliberately ignored (Conceptually, it is being discarded.), as in code like:

      label, has_label, _ = text.partition(':')
      
    2. As part of a function definition (using either def or lambda), where the signature is fixed (e.g. by a callback or parent class API), but this particular function implementation doesn't need all of the parameters, as in code like:

      def callback(_):
          return True
      

      [For a long time this answer didn't list this use case, but it came up often enough, as noted here, to be worth listing explicitly.]

    This use case can conflict with the translation lookup use case, so it is necessary to avoid using _ as a throwaway variable in any code block that also uses it for i18n translation (many folks prefer a double-underscore, __, as their throwaway variable for exactly this reason).

    Linters often recognize this use case. For example year, month, day = date() will raise a lint warning if day is not used later in the code. The fix, if day is truly not needed, is to write year, month, _ = date(). Same with lambda functions, lambda arg: 1.0 creates a function requiring one argument but not using it, which will be caught by lint. The fix is to write lambda _: 1.0. An unused variable is often hiding a bug/typo (e.g. set day but use dya in the next line).

Xcode: failed to get the task for process

To anyone who comes across this: After reading this, I attempted to solve the problem by setting the Debug signing to my Development certificate only to find that deployment was still failing.

Turns out my target was Release and therefore still signing with the distribution certificate - either go back to Debug target or change the release signing to Development temporarily.

What is the meaning of "__attribute__((packed, aligned(4))) "

Before answering, I would like to give you some data from Wiki


Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: data alignment and data structure padding.

When a modern computer reads from or writes to a memory address, it will do this in word sized chunks (e.g. 4 byte chunks on a 32-bit system). Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory.

To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.


gcc provides functionality to disable structure padding. i.e to avoid these meaningless bytes in some cases. Consider the following structure:

typedef struct
{
     char Data1;
     int Data2;
     unsigned short Data3;
     char Data4;

}sSampleStruct;

sizeof(sSampleStruct) will be 12 rather than 8. Because of structure padding. By default, In X86, structures will be padded to 4-byte alignment:

typedef struct
{
     char Data1;
     //3-Bytes Added here.
     int Data2;
     unsigned short Data3;
     char Data4;
     //1-byte Added here.

}sSampleStruct;

We can use __attribute__((packed, aligned(X))) to insist particular(X) sized padding. X should be powers of two. Refer here

typedef struct
{
     char Data1;
     int Data2;
     unsigned short Data3;
     char Data4;

}__attribute__((packed, aligned(1))) sSampleStruct;  

so the above specified gcc attribute does not allow the structure padding. so the size will be 8 bytes.

If you wish to do the same for all the structures, simply we can push the alignment value to stack using #pragma

#pragma pack(push, 1)

//Structure 1
......

//Structure 2
......

#pragma pack(pop)

Java AES encryption and decryption

If for a block cipher you're not going to use a Cipher transformation that includes a padding scheme, you need to have the number of bytes in the plaintext be an integral multiple of the block size of the cipher.

So either pad out your plaintext to a multiple of 16 bytes (which is the AES block size), or specify a padding scheme when you create your Cipher objects. For example, you could use:

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

Unless you have a good reason not to, use a padding scheme that's already part of the JCE implementation. They've thought out a number of subtleties and corner cases you'll have to realize and deal with on your own otherwise.


Ok, your second problem is that you are using String to hold the ciphertext.

In general,

String s = new String(someBytes);
byte[] retrievedBytes = s.getBytes();

will not have someBytes and retrievedBytes being identical.

If you want/have to hold the ciphertext in a String, base64-encode the ciphertext bytes first and construct the String from the base64-encoded bytes. Then when you decrypt you'll getBytes() to get the base64-encoded bytes out of the String, then base64-decode them to get the real ciphertext, then decrypt that.

The reason for this problem is that most (all?) character encodings are not capable of mapping arbitrary bytes to valid characters. So when you create your String from the ciphertext, the String constructor (which applies a character encoding to turn the bytes into characters) essentially has to throw away some of the bytes because it can make no sense of them. Thus, when you get bytes out of the string, they are not the same bytes you put into the string.

In Java (and in modern programming in general), you cannot assume that one character = one byte, unless you know absolutely you're dealing with ASCII. This is why you need to use base64 (or something like it) if you want to build strings from arbitrary bytes.

Recursively find files with a specific extension

As a script you can use:

find "${2:-.}" -iregex ".*${1:-Robert}\.\(h\|cpp\)$" -print
  • save it as findcc
  • chmod 755 findcc

and use it as

findcc [name] [[search_direcory]]

e.g.

findcc                 # default name 'Robert' and directory .
findcc Joe             # default directory '.'
findcc Joe /somewhere  # no defaults

note you cant use

findcc /some/where    #eg without the name...

also as alternative, you can use

find "$1" -print | grep "$@" 

and

findcc directory grep_options

like

findcc . -P '/Robert\.(h|cpp)$'

Remove file from SVN repository without deleting local copy

When you want to remove one xxx.java file from SVN:

  1. Go to workspace path where the file is located.
  2. Delete that file from the folder (xxx.java)
  3. Right click and commit, then a window will open.
  4. Select the file you deleted (xxx.java) from the folder, and again right click and delete.. it will remove the file from SVN.

Why can't I duplicate a slice with `copy()`?

If your slices were of the same size, it would work:

arr := []int{1, 2, 3}
tmp := []int{0, 0, 0}
i := copy(tmp, arr)
fmt.Println(i)
fmt.Println(tmp)
fmt.Println(arr)

Would give:

3
[1 2 3]
[1 2 3]

From "Go Slices: usage and internals":

The copy function supports copying between slices of different lengths (it will copy only up to the smaller number of elements)

The usual example is:

t := make([]byte, len(s), (cap(s)+1)*2)
copy(t, s)
s = t

What does the keyword "transient" mean in Java?

Google is your friend - first hit - also you might first have a look at what serialization is.

It marks a member variable not to be serialized when it is persisted to streams of bytes. When an object is transferred through the network, the object needs to be 'serialized'. Serialization converts the object state to serial bytes. Those bytes are sent over the network and the object is recreated from those bytes. Member variables marked by the java transient keyword are not transferred, they are lost intentionally.

Example from there, slightly modified (thanks @pgras):

public class Foo implements Serializable
 {
   private String saveMe;
   private transient String dontSaveMe;
   private transient String password;
   //...
 }

Jquery Value match Regex

Change it to this:

var email = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;

This is a regular expression literal that is passed the i flag which means to be case insensitive.

Keep in mind that email address validation is hard (there is a 4 or 5 page regular expression at the end of Mastering Regular Expressions demonstrating this) and your expression certainly will not capture all valid e-mail addresses.

Shell Script — Get all files modified after <date>

You can do this directly with tar and even better:

tar -N '2014-02-01 18:00:00' -jcvf archive.tar.bz2 files

This instructs tar to compress files newer than 1st of January 2014, 18:00:00.

how to remove the first two columns in a file using shell (awk, sed, whatever)

perl:

perl -lane 'print join(' ',@F[2..$#F])' File

awk:

awk '{$1=$2=""}1' File

JavaScript - Get Browser Height

JavaScript version in case if jQuery is not an option.

window.screen.availHeight

What is the difference between screenX/Y, clientX/Y and pageX/Y?

The difference between those will depend largely on what browser you are currently referring to. Each one implements these properties differently, or not at all. Quirksmode has great documentation regarding browser differences in regards to W3C standards like the DOM and JavaScript Events.

How to add custom validation to an AngularJS form?

You can use ng-required for your validation scenario ("if these 3 fields are filled in, then this field is required":

<div ng-app>
    <input type="text" ng-model="field1" placeholder="Field1">
    <input type="text" ng-model="field2" placeholder="Field2">
    <input type="text" ng-model="field3" placeholder="Field3">
    <input type="text" ng-model="dependentField" placeholder="Custom validation"
        ng-required="field1 && field2 && field3">
</div>

how to add picasso library in android studio

Add this to your dependencies in build.gradle:

enter image description here

dependencies {
 implementation 'com.squareup.picasso:picasso:2.71828'
  ...

The latest version can be found here

Make sure you are connected to the Internet. When you sync Gradle, all related files will be added to your project

Take a look at your libraries folder, the library you just added should be in there.

enter image description here

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

It should be legal to put a semicolon directly before the WITH keyword.

Serialize an object to string

public static string SerializeObject<T>(T objectToSerialize)
        {
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            MemoryStream memStr = new MemoryStream();

            try
            {
                bf.Serialize(memStr, objectToSerialize);
                memStr.Position = 0;

                return Convert.ToBase64String(memStr.ToArray());
            }
            finally
            {
                memStr.Close();
            }
        }

        public static T DerializeObject<T>(string objectToDerialize)
        {
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            byte[] byteArray = Convert.FromBase64String(objectToDerialize);
            MemoryStream memStr = new MemoryStream(byteArray);

            try
            {
                return (T)bf.Deserialize(memStr);
            }
            finally
            {
                memStr.Close();
            }
        }

How to watch for form changes in Angular

For angular 5+ version. Putting version helps as angular makes lot of changes.

ngOnInit() {

 this.myForm = formBuilder.group({
      firstName: 'Thomas',
      lastName: 'Mann'
    })
this.formControlValueChanged() // Note if you are doing an edit/fetching data from an observer this must be called only after your form is properly initialized otherwise you will get error.
}

formControlValueChanged(): void {       
        this.myForm.valueChanges.subscribe(value => {
            console.log('value changed', value)
        })
}

How to create a custom attribute in C#

While the code to create a custom Attribute is fairly simple, it's very important that you understand what attributes are:

Attributes are metadata compiled into your program. Attributes themselves do not add any functionality to a class, property or module - just data. However, using reflection, one can leverage those attributes in order to create functionality.

So, for instance, let's look at the Validation Application Block, from Microsoft's Enterprise Library. If you look at a code example, you'll see:

    /// <summary>
    /// blah blah code.
    /// </summary>
    [DataMember]
    [StringLengthValidator(8, RangeBoundaryType.Inclusive, 8, RangeBoundaryType.Inclusive, MessageTemplate = "\"{1}\" must always have \"{4}\" characters.")]
    public string Code { get; set; }

From the snippet above, one might guess that the code will always be validated, whenever changed, accordingly to the rules of the Validator (in the example, have at least 8 characters and at most 8 characters). But the truth is that the Attribute does nothing; as mentioned previously, it only adds metadata to the property.

However, the Enterprise Library has a Validation.Validate method that will look into your object, and for each property, it'll check if the contents violate the rule informed by the attribute.

So, that's how you should think about attributes -- a way to add data to your code that might be later used by other methods/classes/etc.

Convert string (without any separator) to list

You can use the re module:

import re
re.sub(r'\D', '', '+123-456-7890')

This will replace all non-digits with ''.

What is MATLAB good for? Why is it so used by universities? When is it better than Python?

Seems to be pure inertia. Where it is in use, everyone is too busy to learn IDL or numpy in sufficient detail to switch, and don't want to rewrite good working programs. Luckily that's not strictly true, but true enough in enough places that Matlab will be around a long time. Like Fortran (in active use where i work!)

How to select the nth row in a SQL database table?

PostgreSQL supports windowing functions as defined by the SQL standard, but they're awkward, so most people use (the non-standard) LIMIT / OFFSET:

SELECT
    *
FROM
    mytable
ORDER BY
    somefield
LIMIT 1 OFFSET 20;

This example selects the 21st row. OFFSET 20 is telling Postgres to skip the first 20 records. If you don't specify an ORDER BY clause, there's no guarantee which record you will get back, which is rarely useful.

Inserting Image Into BLOB Oracle 10g

You cannot access a local directory from pl/sql. If you use bfile, you will setup a directory (create directory) on the server where Oracle is running where you will need to put your images.

If you want to insert a handful of images from your local machine, you'll need a client side app to do this. You can write your own, but I typically use Toad for this. In schema browser, click onto the table. Click the data tab, and hit + sign to add a row. Double click the BLOB column, and a wizard opens. The far left icon will load an image into the blob:

enter image description here

SQL Developer has a similar feature. See the "Load" link below:

enter image description here

If you need to pull images over the wire, you can do it using pl/sql, but its not straight forward. First, you'll need to setup ACL list access (for security reasons) to allow a user to pull over the wire. See this article for more on ACL setup.

Assuming ACL is complete, you'd pull the image like this:

declare
    l_url varchar2(4000) := 'http://www.oracleimg.com/us/assets/12_c_navbnr.jpg';
    l_http_request   UTL_HTTP.req;
    l_http_response  UTL_HTTP.resp;
    l_raw RAW(2000);
    l_blob BLOB;
begin
   -- Important: setup ACL access list first!

    DBMS_LOB.createtemporary(l_blob, FALSE);

    l_http_request  := UTL_HTTP.begin_request(l_url);
    l_http_response := UTL_HTTP.get_response(l_http_request);

  -- Copy the response into the BLOB.
  BEGIN
    LOOP
      UTL_HTTP.read_raw(l_http_response, l_raw, 2000);
      DBMS_LOB.writeappend (l_blob, UTL_RAW.length(l_raw), l_raw);
    END LOOP;
  EXCEPTION
    WHEN UTL_HTTP.end_of_body THEN
      UTL_HTTP.end_response(l_http_response);
  END;

  insert into my_pics (pic_id, pic) values (102, l_blob);
  commit;

  DBMS_LOB.freetemporary(l_blob); 
end;

Hope that helps.

Swift: Testing optionals for nil

From swift programming guide

If Statements and Forced Unwrapping

You can use an if statement to find out whether an optional contains a value. If an optional does have a value, it evaluates to true; if it has no value at all, it evaluates to false.

So the best way to do this is

// swift > 3
if xyz != nil {}

and if you are using the xyz in if statement.Than you can unwrap xyz in if statement in constant variable .So you do not need to unwrap every place in if statement where xyz is used.

if let yourConstant = xyz{
      //use youtConstant you do not need to unwrap `xyz`
}

This convention is suggested by apple and it will be followed by devlopers.

What function is to replace a substring from a string in C?

DWORD ReplaceString(__inout PCHAR source, __in DWORD dwSourceLen, __in const char* pszTextToReplace, __in const char* pszReplaceWith)
{
    DWORD dwRC = NO_ERROR;
    PCHAR foundSeq = NULL;
    PCHAR restOfString = NULL;
    PCHAR searchStart = source;
    size_t szReplStrcLen = strlen(pszReplaceWith), szRestOfStringLen = 0, sztextToReplaceLen = strlen(pszTextToReplace), remainingSpace = 0, dwSpaceRequired = 0;
    if (strcmp(pszTextToReplace, "") == 0)
        dwRC = ERROR_INVALID_PARAMETER;
    else if (strcmp(pszTextToReplace, pszReplaceWith) != 0)
    {
        do
        {
            foundSeq = strstr(searchStart, pszTextToReplace);
            if (foundSeq)
            {
                szRestOfStringLen = (strlen(foundSeq) - sztextToReplaceLen) + 1;
                remainingSpace = dwSourceLen - (foundSeq - source);
                dwSpaceRequired = szReplStrcLen + (szRestOfStringLen);
                if (dwSpaceRequired > remainingSpace)
                {
                    dwRC = ERROR_MORE_DATA;
                }

                else
                {
                    restOfString = CMNUTIL_calloc(szRestOfStringLen, sizeof(CHAR));
                    strcpy_s(restOfString, szRestOfStringLen, foundSeq + sztextToReplaceLen);

                    strcpy_s(foundSeq, remainingSpace, pszReplaceWith);
                    strcat_s(foundSeq, remainingSpace, restOfString);
                }

                CMNUTIL_free(restOfString);
                searchStart = foundSeq + szReplStrcLen; //search in the remaining str. (avoid loops when replWith contains textToRepl 
            }
        } while (foundSeq && dwRC == NO_ERROR);
    }
    return dwRC;
}

How to use LINQ Distinct() with multiple fields

Distinct method returns distinct elements from a sequence.

If you take a look on its implementation with Reflector, you'll see that it creates DistinctIterator for your anonymous type. Distinct iterator adds elements to Set when enumerating over collection. This enumerator skips all elements which are already in Set. Set uses GetHashCode and Equals methods for defining if element already exists in Set.

How GetHashCode and Equals implemented for anonymous type? As it stated on msdn:

Equals and GetHashCode methods on anonymous types are defined in terms of the Equals and GetHashcode methods of the properties, two instances of the same anonymous type are equal only if all their properties are equal.

So, you definitely should have distinct anonymous objects, when iterating on distinct collection. And result does not depend on how many fields you use for your anonymous type.

Simple way to count character occurrences in a string

I believe the "one liner" that you expected to get is this:

"abdsd3$asda$asasdd$sadas".replaceAll( "[^$]*($)?", "$1" ).length();

Remember that the requirements are:

(instead of traversing manually all the string, or loop for indexOf)

and let me add: that at the heart of this question it sounds like "any loop" is not wanted and there is no requirement for speed. I believe the subtext of this question is coolness factor.

Datetime BETWEEN statement not working in SQL Server

Does the second query return any results from the 17th, or just from the 18th?

The first query will only return results from the 17th, or midnight on the 18th.

Try this instead

select * 
from LOGS 
where check_in >= CONVERT(datetime,'2013-10-17') 
and check_in< CONVERT(datetime,'2013-10-19')

How can I select all children of an element except the last child?

Make it simple:

You can apply your style to all the div and re-initialize the last one with :last-child:

for example in CSS:

.yourclass{
    border: 1px solid blue;
}
.yourclass:last-child{
    border: 0;
}

or in SCSS:

.yourclass{
    border: 1px solid rgba(255, 255, 255, 1);
    &:last-child{
        border: 0;
    }
}
  • easy to read/remember
  • fast to execute
  • browser compatible (IE9+ since it's still CSS3)

ValueError: math domain error

You may also use math.log1p.

According to the official documentation :

math.log1p(x)

Return the natural logarithm of 1+x (base e). The result is calculated in a way which is accurate for x near zero.

You may convert back to the original value using math.expm1 which returns e raised to the power x, minus 1.

RuntimeError: module compiled against API version a but this version of numpy is 9

The below command worked for me :

conda install -c anaconda numpy

How to join two tables by multiple columns in SQL?

Yes: You can use Inner Join to join on multiple columns.

SELECT E.CaseNum, E.FileNum, E.ActivityNum, E.Grade, V.Score from Evaluation E
INNER JOIN Value V
ON E.CaseNum = V.CaseNum AND
    E.FileNum = V.FileNum AND 
    E.ActivityNum = V.ActivityNum

Create table

CREATE TABLE MyNewTab(CaseNum int, FileNum int,
    ActivityNum int, Grade int, Score varchar(100))

Insert values

INSERT INTO MyNewTab Values(CaseNum, FileNum, ActivityNum, Grade, Score)
SELECT E.CaseNum, E.FileNum, E.ActivityNum, E.Grade, V.Score from Evaluation E
INNER JOIN Value V
ON E.CaseNum = V.CaseNum AND
    E.FileNum = V.FileNum AND 
    E.ActivityNum = V.ActivityNum

Elasticsearch difference between MUST and SHOULD bool query

As said in the documentation:

Must: The clause (query) must appear in matching documents.

Should: The clause (query) should appear in the matching document. In a boolean query with no must clauses, one or more should clauses must match a document. The minimum number of should clauses to match can be set using the minimum_should_match parameter.

In other words, results will have to be matched by all the queries present in the must clause ( or match at least one of the should clauses if there is no must clause.

Since you want your results to satisfy all the queries, you should use must.


You can indeed use filters inside a boolean query.

Why does Maven have such a bad rep?

Maven does not easily support non-standard operations. The number of useful plugins is though constantly growing. Neither Maven, nor Ant easily/intrinsically support the file dependency concept of Make.

SQL Server: the maximum number of rows in table

It's hard to give a generic answer to this. It really depends on number of factors:

  • what size your row is
  • what kind of data you store (strings, blobs, numbers)
  • what do you do with your data (just keep it as archive, query it regularly)
  • do you have indexes on your table - how many
  • what's your server specs

etc.

As answered elsewhere here, 100,000 a day and thus per table is overkill - I'd suggest monthly or weekly perhaps even quarterly. The more tables you have the bigger maintenance/query nightmare it will become.

Can I add a custom attribute to an HTML tag?

Here is the example:

document.getElementsByTagName("html").foo="bar"

Here is another example how to set custom attributes into body tag element:

document.getElementsByTagName('body')[0].dataset.attr1 = "foo";
document.getElementsByTagName('body')[0].dataset.attr2 = "bar";

Then read the attribute by:

attr1 = document.getElementsByTagName('body')[0].dataset.attr1
attr2 = document.getElementsByTagName('body')[0].dataset.attr2

You can test above code in Console in DevTools, e.g.

JS Console, DevTools in Chrome

Use table row coloring for cells in Bootstrap

You can override the default css rules with this:

.table tbody tr > td.success {
  background-color: #dff0d8 !important;
}

.table tbody tr > td.error {
  background-color: #f2dede !important;
}

.table tbody tr > td.warning {
  background-color: #fcf8e3 !important;
}

.table tbody tr > td.info {
  background-color: #d9edf7 !important;
}

.table-hover tbody tr:hover > td.success {
  background-color: #d0e9c6 !important;
}

.table-hover tbody tr:hover > td.error {
  background-color: #ebcccc !important;
}

.table-hover tbody tr:hover > td.warning {
  background-color: #faf2cc !important;
}

.table-hover tbody tr:hover > td.info {
  background-color: #c4e3f3 !important;
}

!important is needed as bootstrap actually colours the cells individually (afaik it's not possible to just apply background-color to a tr). I couldn't find any colour variables in my version of bootstrap but that's the basic idea anyway.

AngularJS: ng-repeat list is not updated when a model element is spliced from the model array

Remove "track by index" from the ng-repeat and it would refresh the DOM

What are the ways to sum matrix elements in MATLAB?

1)

total = 0;
for i=1:size(A,1)
  for j=1:size(A,2)
    total = total + A(i,j);
  end
end

2)

total = sum(A(:));

fix java.net.SocketTimeoutException: Read timed out

Here are few pointers/suggestions for investigation

  1. I see that every time you vote, you call vote method which creates a fresh HTTP connection.
  2. This might be a problem. I would suggest to use a single HttpClient instance to post to the server. This way it wont create too many connections from the client side.
  3. At the end of everything, HttpClient needs to be shut and hence call httpclient.getConnectionManager().shutdown(); to release the resources used by the connections.

How to respond to clicks on a checkbox in an AngularJS directive?

This is the way I've been doing this sort of stuff. Angular tends to favor declarative manipulation of the dom rather than a imperative one(at least that's the way I've been playing with it).

The markup

<table class="table">
  <thead>
    <tr>
      <th>
        <input type="checkbox" 
          ng-click="selectAll($event)"
          ng-checked="isSelectedAll()">
      </th>
      <th>Title</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="e in entities" ng-class="getSelectedClass(e)">
      <td>
        <input type="checkbox" name="selected"
          ng-checked="isSelected(e.id)"
          ng-click="updateSelection($event, e.id)">
      </td>
      <td>{{e.title}}</td>
    </tr>
  </tbody>
</table>

And in the controller

var updateSelected = function(action, id) {
  if (action === 'add' && $scope.selected.indexOf(id) === -1) {
    $scope.selected.push(id);
  }
  if (action === 'remove' && $scope.selected.indexOf(id) !== -1) {
    $scope.selected.splice($scope.selected.indexOf(id), 1);
  }
};

$scope.updateSelection = function($event, id) {
  var checkbox = $event.target;
  var action = (checkbox.checked ? 'add' : 'remove');
  updateSelected(action, id);
};

$scope.selectAll = function($event) {
  var checkbox = $event.target;
  var action = (checkbox.checked ? 'add' : 'remove');
  for ( var i = 0; i < $scope.entities.length; i++) {
    var entity = $scope.entities[i];
    updateSelected(action, entity.id);
  }
};

$scope.getSelectedClass = function(entity) {
  return $scope.isSelected(entity.id) ? 'selected' : '';
};

$scope.isSelected = function(id) {
  return $scope.selected.indexOf(id) >= 0;
};

//something extra I couldn't resist adding :)
$scope.isSelectedAll = function() {
  return $scope.selected.length === $scope.entities.length;
};

EDIT: getSelectedClass() expects the entire entity but it was being called with the id of the entity only, which is now corrected

How to check if MySQL returns null/empty?

Use empty() and/or is_null()

http://www.php.net/empty http://www.php.net/is_null

Empty alone will achieve your current usage, is_null would just make more control possible if you wanted to distinguish between a field that is null and a field that is empty.

How to start up spring-boot application via command line?

To run the spring-boot application, need to follow some step.

  1. Maven setup (ignore if already setup):

    a. Install maven from https://maven.apache.org/download.cgi

    b. Unzip maven and keep in C drive (you can keep any location. Path location will be changed accordingly).

    c. Set MAVEN_HOME in system variable. enter image description here

    d. Set path for maven

enter image description here

  1. Add Maven Plugin to POM.XML

    <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>

  2. Build Spring Boot Project with Maven

       maven package
    

    or

         mvn install / mvn clean install
    
  3. Run Spring Boot app using Maven:

        mvn spring-boot:run
    
  4. [optional] Run Spring Boot app with java -jar command

         java -jar target/mywebserviceapp-0.0.1-SNAPSHOT.jar
    

How to use SortedMap interface in Java?

You can use TreeMap which internally implements the SortedMap below is the example

Sorting by ascending ordering :

  Map<Float, String> ascsortedMAP = new TreeMap<Float, String>();

  ascsortedMAP.put(8f, "name8");
  ascsortedMAP.put(5f, "name5");
  ascsortedMAP.put(15f, "name15");
  ascsortedMAP.put(35f, "name35");
  ascsortedMAP.put(44f, "name44");
  ascsortedMAP.put(7f, "name7");
  ascsortedMAP.put(6f, "name6");

  for (Entry<Float, String> mapData : ascsortedMAP.entrySet()) {
    System.out.println("Key : " + mapData.getKey() + "Value : " + mapData.getValue());
  }

Sorting by descending ordering :

If you always want this create the map to use descending order in general, if you only need it once create a TreeMap with descending order and put all the data from the original map in.

  // Create the map and provide the comparator as a argument
  Map<Float, String> dscsortedMAP = new TreeMap<Float, String>(new Comparator<Float>() {
    @Override
    public int compare(Float o1, Float o2) {
      return o2.compareTo(o1);
    }
  });
  dscsortedMAP.putAll(ascsortedMAP);

for further information about SortedMAP read http://examples.javacodegeeks.com/core-java/util/treemap/java-sorted-map-example/

webpack: Module not found: Error: Can't resolve (with relative path)

Your file structure says that folder name is Container with a capital C. But you are trying to import it by container with a lowercase c. You will need to change the import or the folder name because the paths are case sensitive.

How can I view an object with an alert()

This is what I use:

var result = [];
for (var l in someObject){
  if (someObject.hasOwnProperty(l){
    result.push(l+': '+someObject[l]);
  }
}
alert(result.join('\n'));

If you want to show nested objects too, you could use something recursive:

function alertObject(obj){
 var result = [];
 function traverse(obj){
 for (var l in obj){
   if (obj.hasOwnProperty(l)){
     if (obj[l] instanceof Object){
       result.push(l+'=>[object]');
       traverse(obj[l]);
     } else {
       result.push(l+': '+obj[l]);
     }
   }
  }
 }
 traverse(obj);
 return result;
}

PHP foreach change original array values

function checkForm(& $fields){
    foreach($fields as $field){
        if($field['required'] && strlen($_POST[$field['name']]) <= 0){
            $fields[$field]['value'] = "Some error";
        }
    }
    return $fields;
}

This is what I would Suggest pass by reference

Which characters need to be escaped in HTML?

Basically, there are three main characters which should be always escaped in your HTML and XML files, so they don't interact with the rest of the markups, so as you probably expect, two of them gonna be the syntax wrappers, which are <>, they are listed as below:

 1)  &lt; (<)
    
 2)  &gt; (>)
    
 3)  &amp; (&)

Also we may use double-quote (") as " and the single quote (') as &apos

Avoid putting dynamic content in <script> and <style>.These rules are not for applied for them. For example, if you have to include JSON in a , replace < with \x3c, the U+2028 character with \u2028, and U+2029 with \u2029 after JSON serialisation.)

HTML Escape Characters: Complete List: http://www.theukwebdesigncompany.com/articles/entity-escape-characters.php

So you need to escape <, or & when followed by anything that could begin a character reference. Also The rule on ampersands is the only such rule for quoted attributes, as the matching quotation mark is the only thing that will terminate one. But if you don’t want to terminate the attribute value there, escape the quotation mark.

Changing to UTF-8 means re-saving your file:

Using the character encoding UTF-8 for your page means that you can avoid the need for most escapes and just work with characters. Note, however, that to change the encoding of your document, it is not enough to just change the encoding declaration at the top of the page or on the server. You need to re-save your document in that encoding. For help understanding how to do that with your application read Setting encoding in web authoring applications.

Invisible or ambiguous characters:

A particularly useful role for escapes is to represent characters that are invisible or ambiguous in presentation.

One example would be Unicode character U+200F RIGHT-TO-LEFT MARK. This character can be used to clarify directionality in bidirectional text (eg. when using the Arabic or Hebrew scripts). It has no graphic form, however, so it is difficult to see where these characters are in the text, and if they are lost or forgotten they could create unexpected results during later editing. Using ? (or its numeric character reference equivalent ?) instead makes it very easy to spot these characters.

An example of an ambiguous character is U+00A0 NO-BREAK SPACE. This type of space prevents line breaking, but it looks just like any other space when used as a character. Using   makes it quite clear where such spaces appear in the text.

CSS Font Border?

Here's what I'm using :

.text_with_1px_border
{
    text-shadow: 
        -1px -1px 0px #000,
         0px -1px 0px #000,
         1px -1px 0px #000,
        -1px  0px 0px #000,
         1px  0px 0px #000,
        -1px  1px 0px #000,
         0px  1px 0px #000,
         1px  1px 0px #000;
}

.text_with_2px_border
{
    text-shadow: 
        /* first layer at 1px */
        -1px -1px 0px #000,
         0px -1px 0px #000,
         1px -1px 0px #000,
        -1px  0px 0px #000,
         1px  0px 0px #000,
        -1px  1px 0px #000,
         0px  1px 0px #000,
         1px  1px 0px #000,
        /* second layer at 2px */
        -2px -2px 0px #000,
        -1px -2px 0px #000,
         0px -2px 0px #000,
         1px -2px 0px #000,
         2px -2px 0px #000,
         2px -1px 0px #000,
         2px  0px 0px #000,
         2px  1px 0px #000,
         2px  2px 0px #000,
         1px  2px 0px #000,
         0px  2px 0px #000,
        -1px  2px 0px #000,
        -2px  2px 0px #000,
        -2px  1px 0px #000,
        -2px  0px 0px #000,
        -2px -1px 0px #000;
}

jQuery trigger event when click outside the element

try these..

$(document).click(function(evt) {
    var target = evt.target.className;
    var inside = $(".menuWraper");
    //alert($(target).html());
    if ($.trim(target) != '') {
        if ($("." + target) != inside) {
            alert("bleep");
        }
    }
});

How to set proper codeigniter base url?

Base URL should be absolute, including the protocol:

$config['base_url'] = "http://".$_SERVER['SERVER_NAME']."/mysite/";

This configuration will work in both localhost and server.

Don't forget to enable on autoload:

$autoload['helper'] = array('url','file');

Then base_url() will output as below

echo base_url('assets/style.css'); //http://yoursite.com/mysite/assets/style.css

How to use Elasticsearch with MongoDB?

River is a good solution once you want to have a almost real time synchronization and general solution.

If you have data in MongoDB already and want to ship it very easily to Elasticsearch like "one-shot" you can try my package in Node.js https://github.com/itemsapi/elasticbulk.

It's using Node.js streams so you can import data from everything what is supporting streams (i.e. MongoDB, PostgreSQL, MySQL, JSON files, etc)

Example for MongoDB to Elasticsearch:

Install packages:

npm install elasticbulk
npm install mongoose
npm install bluebird

Create script i.e. script.js:

const elasticbulk = require('elasticbulk');
const mongoose = require('mongoose');
const Promise = require('bluebird');
mongoose.connect('mongodb://localhost/your_database_name', {
  useMongoClient: true
});

mongoose.Promise = Promise;

var Page = mongoose.model('Page', new mongoose.Schema({
  title: String,
  categories: Array
}), 'your_collection_name');

// stream query 
var stream = Page.find({
}, {title: 1, _id: 0, categories: 1}).limit(1500000).skip(0).batchSize(500).stream();

elasticbulk.import(stream, {
  index: 'my_index_name',
  type: 'my_type_name',
  host: 'localhost:9200',
})
.then(function(res) {
  console.log('Importing finished');
})

Ship your data:

node script.js

It's not extremely fast but it's working for millions of records (thanks to streams).

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

Please update your IP address in /etc/mysql/my.cnf file

bind-address  = 0.0.0.0

Restart mysql deamon and mysql services.

Promise Error: Objects are not valid as a React child

You can't do this: {this.state.arrayFromJson} As your error suggests what you are trying to do is not valid. You are trying to render the whole array as a React child. This is not valid. You should iterate through the array and render each element. I use .map to do that.

I am pasting a link from where you can learn how to render elements from an array with React.

http://jasonjl.me/blog/2015/04/18/rendering-list-of-elements-in-react-with-jsx/

Hope it helps!

Best way to simulate "group by" from bash?

I feel awk associative array is also handy in this case

$ awk '{count[$1]++}END{for(j in count) print j,count[j]}' ips.txt

A group by post here

What are the most-used vim commands/keypresses?

Have you run through Vim's built-in tutorial? If not, drop to the command-line and type vimtutor. It's a great way to learn the initial commands.

Vim has an incredible amount of flexibility and power and, if you're like most vim users, you'll learn a lot of new commands and forget old ones, then relearn them. The built-in help is good and worthy of periodic browsing to learn new stuff.

There are several good FAQs and cheatsheets for vim on the internet. I'd recommend searching for vim + faq and vim + cheatsheet. Cheat-Sheets.org#vim is a good source, as is Vim Tips wiki.

How to remove all of the data in a table using Django

As per the latest documentation, the correct method to call would be:

Reporter.objects.all().delete()

How to add calendar events in Android?

you have to add flag:

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

or you will cause error with:

startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK

Search for all files in project containing the text 'querystring' in Eclipse

Just noticed that quick search has been included into eclipse 4.13 as a built-in function by typing Ctrl+Alt+Shift+L (or Cmd+Alt+Shift+L on Mac)

https://www.eclipse.org/eclipse/news/4.13/platform.php#quick-text-search

Mail multipart/alternative vs multipart/mixed

Great Answer Lain!

There were a couple things I did to make this work in a broader set of devices. At the end I will list the clients I tested on.

  1. I added a new build constructor that did not contain the parameter attachments and did not use MimeMultipart("mixed"). There is no need for mixed if you are sending only inline images.

    public Multipart build(String messageText, String messageHtml, List<URL> messageHtmlInline) throws MessagingException {
    
        final Multipart mpAlternative = new MimeMultipart("alternative");
        {
            //  Note: MUST RENDER HTML LAST otherwise iPad mail client only renders 
            //  the last image and no email
                addTextVersion(mpAlternative,messageText);
                addHtmlVersion(mpAlternative,messageHtml, messageHtmlInline);
        }
    
        return mpAlternative;
    }
    
  2. In addTextVersion method I added charset when adding content this probably could/should be passed in, but I just added it statically.

    textPart.setContent(messageText, "text/plain");
    to
    textPart.setContent(messageText, "text/plain; charset=UTF-8");
    
  3. The last item was adding to the addImagesInline method. I added setting the image filename to the header by the following code. If you don't do this then at least on Android default mail client it will have inline images that have a name of Unknown and will not automatically download them and present in email.

    for (URL img : embeded) {
        final MimeBodyPart htmlPartImg = new MimeBodyPart();
        DataSource htmlPartImgDs = new URLDataSource(img);
        htmlPartImg.setDataHandler(new DataHandler(htmlPartImgDs));
        String fileName = img.getFile();
        fileName = getFileName(fileName);
        String newFileName = cids.get(fileName);
        boolean imageNotReferencedInHtml = newFileName == null;
        if (imageNotReferencedInHtml) continue;
        htmlPartImg.setHeader("Content-ID", "<"+newFileName+">");
        htmlPartImg.setDisposition(BodyPart.INLINE);
        **htmlPartImg.setFileName(newFileName);**
        parent.addBodyPart(htmlPartImg);
    }
    

So finally, this is the list of clients I tested on. Outlook 2010, Outlook Web App, Internet Explorer 11, Firefox, Chrome, Outlook using Apple’s native app, Email going through Gmail - Browser mail client, Internet Explorer 11, Firefox, Chrome, Android default mail client, osx IPhone default mail client, Gmail mail client on Android, Gmail mail client on IPhone, Email going through Yahoo - Browser mail client, Internet Explorer 11, Firefox, Chrome, Android default mail client, osx IPhone default mail client.

Hope that helps anyone else.

Is there a way to specify a max height or width for an image?

If you only specify either the height or the width, but not both, most browsers will honor the aspect ratio.

Because you are working with an ASP.NET server control, you may consider executing logic on the server side prior to rendering to decide which (height or width) attribute you want to specify; that is, if you want a fixed height under one condition or a fixed width under another.

How to check if a service is running via batch file and start it, if it is not running?

@echo off

color 1F


@sc query >%COMPUTERNAME%_START.TXT


find /I "AcPrfMgrSvc" %COMPUTERNAME%_START.TXT >nul

IF ERRORLEVEL 0 EXIT

IF ERRORLEVEL 1 NET START "AcPrfMgrSvc"

How to add title to seaborn boxplot

sns.boxplot() function returns Axes(matplotlib.axes.Axes) object. please refer the documentation you can add title using 'set' method as below:

sns.boxplot('Day', 'Count', data=gg).set(title='lalala')

you can also add other parameters like xlabel, ylabel to the set method.

sns.boxplot('Day', 'Count', data=gg).set(title='lalala', xlabel='its x_label', ylabel='its y_label')

There are some other methods as mentioned in the matplotlib.axes.Axes documentaion to add tile, legend and labels.

Check box size change with CSS

You might want to do this.

input[type=checkbox] {

 -ms-transform: scale(2); /* IE */
 -moz-transform: scale(2); /* FF */
 -webkit-transform: scale(2); /* Safari and Chrome */
 -o-transform: scale(2); /* Opera */
  padding: 10px;
}

Showing/Hiding Table Rows with Javascript - can do with ID - how to do with Class?

JQuery 10.1.2 has a nice show and hide functions that encapsulate the behavior you are talking about. This would save you having to write a new function or keep track of css classes.

$("new").show();

$("new").hide();

w3cSchool link to JQuery show and hide

How to vertically align text inside a flexbox?

_x000D_
_x000D_
* {_x000D_
  padding: 0;_x000D_
  margin: 0;_x000D_
}_x000D_
html, body {_x000D_
  height: 100%;_x000D_
}_x000D_
ul {_x000D_
  height: 100%;_x000D_
}_x000D_
li {_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
  align-items:center;_x000D_
  background: silver;_x000D_
  width: 100%;_x000D_
  height: 20%;_x000D_
}
_x000D_
<ul>_x000D_
  <li>This is the text</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

summing two columns in a pandas dataframe

You could also use the .add() function:

 df.loc[:,'variance'] = df.loc[:,'budget'].add(df.loc[:,'actual'])

Why should text files end with a newline?

Each line should be terminated in a newline character, including the last one. Some programs have problems processing the last line of a file if it isn't newline terminated.

GCC warns about it not because it can't process the file, but because it has to as part of the standard.

The C language standard says A source file that is not empty shall end in a new-line character, which shall not be immediately preceded by a backslash character.

Since this is a "shall" clause, we must emit a diagnostic message for a violation of this rule.

This is in section 2.1.1.2 of the ANSI C 1989 standard. Section 5.1.1.2 of the ISO C 1999 standard (and probably also the ISO C 1990 standard).

Reference: The GCC/GNU mail archive.

XPath: How to select elements based on their value?

//Element[@attribute1="abc" and @attribute2="xyz" and .="Data"]

The reason why I add this answer is that I want to explain the relationship of . and text() .

The first thing is when using [], there are only two types of data:

  1. [number] to select a node from node-set
  2. [bool] to filter a node-set from node-set

In this case, the value is evaluated to boolean by function boolean(), and there is a rule:

Filters are always evaluated with respect to a context.

When you need to compare text() or . with a string "Data", it first uses string() function to transform those to string type, than gets a boolean result.

There are two important rule about string():

  1. The string() function converts a node-set to a string by returning the string value of the first node in the node-set, which in some instances may yield unexpected results.

    text() is relative path that return a node-set contains all the text node of current node(context node), like ["Data"]. When it is evaluated by string(["Data"]), it will return the first node of node-set, so you get "Data" only when there is only one text node in the node-set.

  2. If you want the string() function to concatenate all child text, you must then pass a single node instead of a node-set.

    For example, we get a node-set ['a', 'b'], you can pass there parent node to string(parent), this will return 'ab', and of cause string(.) in you case will return an concatenated string "Data".

Both way will get same result only when there is a text node.

Custom header to HttpClient request

I have found the answer to my question.

client.DefaultRequestHeaders.Add("X-Version","1");

That should add a custom header to your request

How to save username and password in Git?

After reading the thread in full and experimenting with most of the answers to this question, I eventually found the procedure that works for me. I want to share it in case someone has to deal with a complex use case but still do not want to go through the full thread and the gitcredentials, gitcredentials-store etc. man pages, as I did.

Find below the procedure I suggest IF you (like me) have to deal with several repositories from several providers (GitLab, GitHub, Bitbucket, etc.) using several different username / password combinations. If you instead have only a single account to work with, then you might be better off employing the git config --global credential.helper store or git config --global user.name "your username" etc. solutions that have been very well explained in previous answers.

My solution:

  1. unset global credentials helper, in case some former experimentation gets in the way :)

> git config --global --unset credentials.helper

  1. move to the root directory of your repo and disable the local credential helper (if needed)

> cd /path/to/my/repo

> git config --unset credential.helper

  1. create a file to store your repo's credentials into

> git config credential.helper 'store --file ~/.git_repo_credentials'

Note: this command creates a new file named ".git_repo_credentials" into your home directory, to which Git stores your credentials. If you do not specify a file name, Git uses the default ".git_credentials". In this case simply issuing the following command will do:

> git config credential.helper store

  1. set your username

git config credential.*.username my_user_name

Note: using "*" is usually ok if your repositories are from the same provider (e.g. GitLab). If instead your repositories are hosted by different providers then I suggest to explicitly set the link to the provider for every repository, like in the following example (for GitLab):

git config credential.https://gitlab.com.username my_user_name

At this point if you issue a command requiring your credentials (e.g. git pull) you will be asked for the password corresponding to "my_user_name". This is only required once because git stores the credentials to ".git_repo_credentials" and automatically uses the same data at subsequent accesses.

How do I position a div at the bottom center of the screen

If you aren't comfortable with using negative margins, check this out.

div {
  position: fixed;
  left: 50%;
  bottom: 20px;
  transform: translate(-50%, -50%);
  margin: 0 auto;
}
<div>
  Your Text
</div>

Especially useful when you don't know the width of the div.


align="center" has no effect.

Since you have position:absolute, I would recommend positioning it 50% from the left and then subtracting half of its width from its left margin.

#manipulate {
    position:absolute;
    width:300px;
    height:300px;
    background:#063;
    bottom:0px;
    right:25%;
    left:50%;
    margin-left:-150px;
}

IntelliJ IDEA "cannot resolve symbol" and "cannot resolve method"

First check if you have configured JDK correctly:

  • Go to File->Project Structure -> SDKs
  • your JDK home path should be something like this: /Library/Java/JavaVirtualMachine/jdk.1.7.0_79.jdk/Contents/Home
  • Hit Apply and then OK

Secondly check if you have provided in path in Library's section

  • Go to File->Project Structure -> Libraries
  • Hit the + button
  • Add the path to your src folder
  • Hit Apply and then OK

This should fix the problem

Error - Unable to access the IIS metabase

In Visual Studio 2015: I changed UseIIS in .csproj file to false and it worked for me.

<UseIIS>False</UseIIS>

Run jQuery function onclick

Using obtrusive JavaScript (i.e. inline code) as in your example, you can attach the click event handler to the div element with the onclick attribute like so:

 <div id="some-id" class="some-class" onclick="slideonlyone('sms_box');">
     ...
 </div>

However, the best practice is unobtrusive JavaScript which you can easily achieve by using jQuery's on() method or its shorthand click(). For example:

 $(document).ready( function() {
     $('.some-class').on('click', slideonlyone('sms_box'));
     // OR //
     $('.some-class').click(slideonlyone('sms_box'));
 });

Inside your handler function (e.g. slideonlyone() in this case) you can reference the element that triggered the event (e.g. the div in this case) with the $(this) object. For example, if you need its ID, you can access it with $(this).attr('id').


EDIT

After reading your comment to @fmsf below, I see you also need to dynamically reference the target element to be toggled. As @fmsf suggests, you can add this information to the div with a data-attribute like so:

<div id="some-id" class="some-class" data-target="sms_box">
    ...
</div>

To access the element's data-attribute you can use the attr() method as in @fmsf's example, but the best practice is to use jQuery's data() method like so:

 function slideonlyone() {
     var trigger_id = $(this).attr('id'); // This would be 'some-id' in our example
     var target_id  = $(this).data('target'); // This would be 'sms_box'
     ...
 }

Note how data-target is accessed with data('target'), without the data- prefix. Using data-attributes you can attach all sorts of information to an element and jQuery would automatically add them to the element's data object.

Failure [INSTALL_FAILED_INVALID_APK]

Navigate to Run/Debug Configurations

Click Run from the top Tab > Edit Configurations

  • Module: Select your App
  • Installation Options: Deploy Default APK
  • Ok

enter image description here

How much data / information can we save / store in a QR code?

See this table.

A 101x101 QR code, with high level error correction, can hold 3248 bits, or 406 bytes. Probably not enough for any meaningful SVG/XML data.

A 177x177 grid, depending on desired level of error correction, can store between 1273 and 2953 bytes. Maybe enough to store something small.

enter image description here

Are iframes considered 'bad practice'?

They're not bad practice, they're just another tool and they add flexibility.

For use as a standard page element... they're good, because they're a simple and reliable way to separate content onto several pages. Especially for user-generated content, it may be useful to "sandbox" internal pages into an iframe so poor markup doesn't affect the main page. The downside is that if you introduce multiple layers of scrolling (one for the browser, one for the iframe) your users will get frustrated. Like adzm said, you don't want to use an iframe for primary navigation, but think about them as a text/markup equivalent to the way a video or another media file would be embedded.

For scripting background events, the choice is generally between a hidden iframe and XmlHttpRequest to load content for the current page. The difference there is that an iframe generates a page load, so you can move back and forward in browser cache with most browsers. Notice that Google, who uses XmlHttpRequest all over the place, also uses iframes in certain cases to allow a user to move back and forward in browser history.

Return an empty Observable

Yes, there is am Empty operator

Rx.Observable.empty();

For typescript, you can use from:

Rx.Observable<Response>.from([])

CSS text-align: center; is not centering things

I don't Know you use any Bootstrap version but the useful helper class for centering and block an element in center it is .center-block because this class contain margin and display CSS properties but the .text-center class only contain the text-align property

Bootstrap Helper Class center-block

How to use youtube-dl from a python program?

If youtube-dl is a terminal program, you can use the subprocess module to access the data you want.

Check out this link for more details: Calling an external command in Python

Launching Spring application Address already in use

Spring Boot uses embedded Tomcat by default, but it handles it differently without using tomcat-maven-plugin. To change the port use --server.port parameter for example:

java -jar target/gs-serving-web-content-0.1.0.jar --server.port=8181

Update. Alternatively put server.port=8181 into application.properties (or application.yml).

Specify path to node_modules in package.json

I'm not sure if this is what you had in mind, but I ended up on this question because I was unable to install node_modules inside my project dir as it was mounted on a filesystem that did not support symlinks (a VM "shared" folder).

I found the following workaround:

  1. Copy the package.json file to a temp folder on a different filesystem
  2. Run npm install there
  3. Copy the resulting node_modules directory back into the project dir, using cp -r --dereference to expand symlinks into copies.

I hope this helps someone else who ends up on this question when looking for a way to move node_modules to a different filesystem.

Other options

There is another workaround, which I found on the github issue that @Charminbear linked to, but this doesn't work with grunt because it does not support NODE_PATH as per https://github.com/browserify/resolve/issues/136:

lets say you have /media/sf_shared and you can't install symlinks in there, which means you can't actually npm install from /media/sf_shared/myproject because some modules use symlinks.

  • $ mkdir /home/dan/myproject && cd /home/dan/myproject
  • $ ln -s /media/sf_shared/myproject/package.json (you can symlink in this direction, just can't create one inside of /media/sf_shared)
  • $ npm install
  • $ cd /media/sf_shared/myproject
  • $ NODE_PATH=/home/dan/myproject/node_modules node index.js

Default instance name of SQL Server Express

If you navigate to where you have installed SQLExpress, e.g.

C:\Program Files\Microsoft SQL Server\110\Tools\Binn

You can run SQLLocalDB.exe and get a list of the all instances installed on your machine.

C:\Program Files\Microsoft SQL Server\110\Tools\Binn>SqlLocalDB.exe info
MSSQLLocalDB
ProjectsV12
v11.0

Then you can get further information on the instance.

C:\Program Files\Microsoft SQL Server\110\Tools\Binn>SqlLocalDB.exe info MSSQLLocalDB Name: MSSQLLocalDB
Version: 13.0.1601.5
Shared name:
Owner: Domain\User
Auto-create: Yes
State: Stopped
Last start time: 22/09/2016 10:19:33
Instance pipe name:

What are native methods in Java and where should they be used?

I like to know where does we use Native Methods

Ideally, not at all. In reality some functionality is not available in Java and you have to call some C code.

The methods are implemented in C code.

Minimal web server using netcat

LOL, a super lame hack, but at least curl and firefox accepts it:

while true ; do (dd if=/dev/zero count=10000;echo -e "HTTP/1.1\n\n $(date)") | nc -l  1500  ; done

You better replace it soon with something proper!

Ah yes, my nc were not exactly the same as yours, it did not like the -p option.

In Excel, how do I extract last four letters of a ten letter string?

No need to use a macro. Supposing your first string is in A1.

=RIGHT(A1, 4)

Drag this down and you will get your four last characters.

Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()

=RIGHT(TRIMSPACES(A1), 4)

Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:

=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))

Using routes in Express-js

So, after I created my question, I got this related list on the right with a similar issue: Organize routes in Node.js.

The answer in that post linked to the Express repo on GitHub and suggests to look at the 'route-separation' example.

This helped me change my code, and I now have it working. - Thanks for your comments.

My implementation ended up looking like this;

I require my routes in the app.js:

var express = require('express')
  , site = require('./site')
  , wiki = require('./wiki');

And I add my routes like this:

app.get('/', site.index);
app.get('/wiki/:id', wiki.show);
app.get('/wiki/:id/edit', wiki.edit);

I have two files called wiki.js and site.js in the root of my app, containing this:

exports.edit = function(req, res) {

    var wiki_entry = req.params.id;

    res.render('wiki/edit', {
        title: 'Editing Wiki',
        wiki: wiki_entry
    })
}

Guzzle 6: no more json() method for responses

I use json_decode($response->getBody()) now instead of $response->json().

I suspect this might be a casualty of PSR-7 compliance.

How can I change Eclipse theme?

enter image description here My Theme plugin provide full featured customization for Eclipse 4. Try it. Visit Plugin Page

How can I use optional parameters in a T-SQL stored procedure?

Five years late to the party.

It is mentioned in the provided links of the accepted answer, but I think it deserves an explicit answer on SO - dynamically building the query based on provided parameters. E.g.:

Setup

-- drop table Person
create table Person
(
    PersonId INT NOT NULL IDENTITY(1, 1) CONSTRAINT PK_Person PRIMARY KEY,
    FirstName NVARCHAR(64) NOT NULL,
    LastName NVARCHAR(64) NOT NULL,
    Title NVARCHAR(64) NULL
)
GO

INSERT INTO Person (FirstName, LastName, Title)
VALUES ('Dick', 'Ormsby', 'Mr'), ('Serena', 'Kroeger', 'Ms'), 
    ('Marina', 'Losoya', 'Mrs'), ('Shakita', 'Grate', 'Ms'), 
    ('Bethann', 'Zellner', 'Ms'), ('Dexter', 'Shaw', 'Mr'),
    ('Zona', 'Halligan', 'Ms'), ('Fiona', 'Cassity', 'Ms'),
    ('Sherron', 'Janowski', 'Ms'), ('Melinda', 'Cormier', 'Ms')
GO

Procedure

ALTER PROCEDURE spDoSearch
    @FirstName varchar(64) = null,
    @LastName varchar(64) = null,
    @Title varchar(64) = null,
    @TopCount INT = 100
AS
BEGIN
    DECLARE @SQL NVARCHAR(4000) = '
        SELECT TOP ' + CAST(@TopCount AS VARCHAR) + ' *
        FROM Person
        WHERE 1 = 1'

    PRINT @SQL

    IF (@FirstName IS NOT NULL) SET @SQL = @SQL + ' AND FirstName = @FirstName'
    IF (@LastName IS NOT NULL) SET @SQL = @SQL + ' AND FirstName = @LastName'
    IF (@Title IS NOT NULL) SET @SQL = @SQL + ' AND Title = @Title'

    EXEC sp_executesql @SQL, N'@TopCount INT, @FirstName varchar(25), @LastName varchar(25), @Title varchar(64)', 
         @TopCount, @FirstName, @LastName, @Title
END
GO

Usage

exec spDoSearch @TopCount = 3
exec spDoSearch @FirstName = 'Dick'

Pros:

  • easy to write and understand
  • flexibility - easily generate the query for trickier filterings (e.g. dynamic TOP)

Cons:

  • possible performance problems depending on provided parameters, indexes and data volume

Not direct answer, but related to the problem aka the big picture

Usually, these filtering stored procedures do not float around, but are being called from some service layer. This leaves the option of moving away business logic (filtering) from SQL to service layer.

One example is using LINQ2SQL to generate the query based on provided filters:

    public IList<SomeServiceModel> GetServiceModels(CustomFilter filters)
    {
        var query = DataAccess.SomeRepository.AllNoTracking;

        // partial and insensitive search 
        if (!string.IsNullOrWhiteSpace(filters.SomeName))
            query = query.Where(item => item.SomeName.IndexOf(filters.SomeName, StringComparison.OrdinalIgnoreCase) != -1);
        // filter by multiple selection
        if ((filters.CreatedByList?.Count ?? 0) > 0)
            query = query.Where(item => filters.CreatedByList.Contains(item.CreatedById));
        if (filters.EnabledOnly)
            query = query.Where(item => item.IsEnabled);

        var modelList = query.ToList();
        var serviceModelList = MappingService.MapEx<SomeDataModel, SomeServiceModel>(modelList);
        return serviceModelList;
    }

Pros:

  • dynamically generated query based on provided filters. No parameter sniffing or recompile hints needed
  • somewhat easier to write for those in the OOP world
  • typically performance friendly, since "simple" queries will be issued (appropriate indexes are still needed though)

Cons:

  • LINQ2QL limitations may be reached and forcing a downgrade to LINQ2Objects or going back to pure SQL solution depending on the case
  • careless writing of LINQ might generate awful queries (or many queries, if navigation properties loaded)

Is Ruby pass by reference or by value?

Try this:--

1.object_id
#=> 3

2.object_id
#=> 5

a = 1
#=> 1
a.object_id
#=> 3

b = 2
#=> 2
b.object_id
#=> 5

identifier a contains object_id 3 for value object 1 and identifier b contains object_id 5 for value object 2.

Now do this:--

a.object_id = 5
#=> error

a = b
#value(object_id) at b copies itself as value(object_id) at a. value object 2 has object_id 5
#=> 2

a.object_id 
#=> 5

Now, a and b both contain same object_id 5 which refers to value object 2. So, Ruby variable contains object_ids to refer to value objects.

Doing following also gives error:--

c
#=> error

but doing this won't give error:--

5.object_id
#=> 11

c = 5
#=> value object 5 provides return type for variable c and saves 5.object_id i.e. 11 at c
#=> 5
c.object_id
#=> 11 

a = c.object_id
#=> object_id of c as a value object changes value at a
#=> 11
11.object_id
#=> 23
a.object_id == 11.object_id
#=> true

a
#=> Value at a
#=> 11

Here identifier a returns value object 11 whose object id is 23 i.e. object_id 23 is at identifier a, Now we see an example by using method.

def foo(arg)
  p arg
  p arg.object_id
end
#=> nil
11.object_id
#=> 23
x = 11
#=> 11
x.object_id
#=> 23
foo(x)
#=> 11
#=> 23

arg in foo is assigned with return value of x. It clearly shows that argument is passed by value 11, and value 11 being itself an object has unique object id 23.

Now see this also:--

def foo(arg)
  p arg
  p arg.object_id
  arg = 12
  p arg
  p arg.object_id
end

#=> nil
11.object_id
#=> 23
x = 11
#=> 11
x.object_id
#=> 23
foo(x)
#=> 11
#=> 23
#=> 12
#=> 25
x
#=> 11
x.object_id
#=> 23

Here, identifier arg first contains object_id 23 to refer 11 and after internal assignment with value object 12, it contains object_id 25. But it does not change value referenced by identifier x used in calling method.

Hence, Ruby is pass by value and Ruby variables do not contain values but do contain reference to value object.

One line if-condition-assignment

You can definitely use num1 = (20 if someBoolValue else num1) if you want.

Convert List<DerivedClass> to List<BaseClass>

I personally like to create libs with extensions to the classes

public static List<TTo> Cast<TFrom, TTo>(List<TFrom> fromlist)
  where TFrom : class 
  where TTo : class
{
  return fromlist.ConvertAll(x => x as TTo);
}

getFilesDir() vs Environment.getDataDirectory()

Try this

getExternalFilesDir(Environment.getDataDirectory().getAbsolutePath()).getAbsolutePath()