Programs & Examples On #Classification

In machine learning and statistics, classification is the problem of identifying which of a set of categories a new observation belongs to, on the basis of a training set of data containing observations whose category membership (label) is known.

A simple explanation of Naive Bayes Classification

Naive Bayes: Naive Bayes comes under supervising machine learning which used to make classifications of data sets. It is used to predict things based on its prior knowledge and independence assumptions.

They call it naive because it’s assumptions (it assumes that all of the features in the dataset are equally important and independent) are really optimistic and rarely true in most real-world applications.

It is classification algorithm which makes the decision for the unknown data set. It is based on Bayes Theorem which describe the probability of an event based on its prior knowledge.

Below diagram shows how naive Bayes works

enter image description here

Formula to predict NB:

enter image description here

How to use Naive Bayes Algorithm ?

Let's take an example of how N.B woks

Step 1: First we find out Likelihood of table which shows the probability of yes or no in below diagram. Step 2: Find the posterior probability of each class.

enter image description here

Problem: Find out the possibility of whether the player plays in Rainy condition?

P(Yes|Rainy) = P(Rainy|Yes) * P(Yes) / P(Rainy)

P(Rainy|Yes) = 2/9 = 0.222
P(Yes) = 9/14 = 0.64
P(Rainy) = 5/14 = 0.36

Now, P(Yes|Rainy) = 0.222*0.64/0.36 = 0.39 which is lower probability which means chances of the match played is low.

For more reference refer these blog.

Refer GitHub Repository Naive-Bayes-Examples

Scikit-learn train_test_split with indices

You can use pandas dataframes or series as Julien said but if you want to restrict your-self to numpy you can pass an additional array of indices:

from sklearn.model_selection import train_test_split
import numpy as np
n_samples, n_features, n_classes = 10, 2, 2
data = np.random.randn(n_samples, n_features)  # 10 training examples
labels = np.random.randint(n_classes, size=n_samples)  # 10 labels
indices = np.arange(n_samples)
x1, x2, y1, y2, idx1, idx2 = train_test_split(
    data, labels, indices, test_size=0.2)

FailedPreconditionError: Attempting to use uninitialized in Tensorflow

tf.initialize_all_variables() is deprecated. Instead initialize tensorflow variables with:

tf.global_variables_initializer()

A common example usage is:

with tf.Session() as sess:
     sess.run(tf.global_variables_initializer())

Scikit-learn: How to obtain True Positive, True Negative, False Positive and False Negative

if you have more than one classes in your classifier, you might want to use pandas-ml at that part. Confusion Matrix of pandas-ml give more detailed information. check that

RESULT

Save classifier to disk in scikit-learn

sklearn.externals.joblib has been deprecated since 0.21 and will be removed in v0.23:

/usr/local/lib/python3.7/site-packages/sklearn/externals/joblib/init.py:15: FutureWarning: sklearn.externals.joblib is deprecated in 0.21 and will be removed in 0.23. Please import this functionality directly from joblib, which can be installed with: pip install joblib. If this warning is raised when loading pickled models, you may need to re-serialize those models with scikit-learn 0.21+.
warnings.warn(msg, category=FutureWarning)


Therefore, you need to install joblib:

pip install joblib

and finally write the model to disk:

import joblib
from sklearn.datasets import load_digits
from sklearn.linear_model import SGDClassifier


digits = load_digits()
clf = SGDClassifier().fit(digits.data, digits.target)

with open('myClassifier.joblib.pkl', 'wb') as f:
    joblib.dump(clf, f, compress=9)

Now in order to read the dumped file all you need to run is:

with open('myClassifier.joblib.pkl', 'rb') as f:
    my_clf = joblib.load(f)

What are advantages of Artificial Neural Networks over Support Vector Machines?

We should also consider that the SVM system can be applied directly to non-metric spaces, such as the set of labeled graphs or strings. In fact, the internal kernel function can be generalized properly to virtually any kind of input, provided that the positive definiteness requirement of the kernel is satisfied. On the other hand, to be able to use an ANN on a set of labeled graphs, explicit embedding procedures must be considered.

Difference between classification and clustering in data mining?

Classification – Predicts categorical class labels – Classifies data (constructs a model) based on a training set and the values (class labels) in a class label attribute – Uses the model in classifying new data

Cluster: a collection of data objects – Similar to one another within the same cluster – Dissimilar to the objects in other clusters

UIDevice uniqueIdentifier deprecated - What to do now?

Create your own UUID and then store it in the Keychain. Thus it persists even when your app gets uninstalled. In many cases it also persists even if the user migrates between devices (e.g. full backup and restore to another device).

Effectively it becomes a unique user identifier as far as you're concerned. (even better than device identifier).

Example:

I am defining a custom method for creating a UUID as :

- (NSString *)createNewUUID 
{
    CFUUIDRef theUUID = CFUUIDCreate(NULL);
    CFStringRef string = CFUUIDCreateString(NULL, theUUID);
    CFRelease(theUUID);
    return [(NSString *)string autorelease];
}

You can then store it in KEYCHAIN on the very first launch of your app. So that after first launch, we can simply use it from keychain, no need to regenerate it. The main reason for using Keychain to store is: When you set the UUID to the Keychain, it will persist even if the user completely uninstalls the App and then installs it again. . So, this is the permanent way of storing it, which means the key will be unique all the way.

     #import "SSKeychain.h"
     #import <Security/Security.h>

On applictaion launch include the following code :

 // getting the unique key (if present ) from keychain , assuming "your app identifier" as a key
       NSString *retrieveuuid = [SSKeychain passwordForService:@"your app identifier" account:@"user"];
      if (retrieveuuid == nil) { // if this is the first time app lunching , create key for device
        NSString *uuid  = [self createNewUUID];
// save newly created key to Keychain
        [SSKeychain setPassword:uuid forService:@"your app identifier" account:@"user"];
// this is the one time process
}

Download SSKeychain.m and .h file from sskeychain and Drag SSKeychain.m and .h file to your project and add "Security.framework" to your project. To use UUID afterwards simply use :

NSString *retrieveuuid = [SSKeychain passwordForService:@"your app identifier" account:@"user"];

Accessing all items in the JToken

If you know the structure of the json that you're receiving then I'd suggest having a class structure that mirrors what you're receiving in json.

Then you can call its something like this...

AddressMap addressMap = JsonConvert.DeserializeObject<AddressMap>(json);

(Where json is a string containing the json in question)

If you don't know the format of the json you've receiving then it gets a bit more complicated and you'd probably need to manually parse it.

check out http://www.hanselman.com/blog/NuGetPackageOfTheWeek4DeserializingJSONWithJsonNET.aspx for more info

Only allow Numbers in input Tag without Javascript

Try this with the + after [0-9]:

input type="text" pattern="[0-9]+" title="number only"

org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person]

Note:

  1. Its not necessary to specify table name in Person.hbm.xml (........) when you are creating table with same as class name. Also applicable to fields.

  2. While creating "person" table in your respective database,make sure that whatever FILEDS names you specified in Person.hbm.xml must match with table COLUMNS names ELSE you wil get above error.

Python function pointer

def f(a,b):
    return a+b

xx = 'f'
print eval('%s(%s,%s)'%(xx,2,3))

OUTPUT

 5

Leave out quotes when copying from cell

My solution when I hit the quotes issue was to strip carriage returns from the end of my cells' text. Because of these carriage returns (inserted by an external program), Excel was adding quotes to the entire string.

How can I round down a number in Javascript?

Round towards negative infinity - Math.floor()

+3.5 => +3.0
-3.5 => -4.0

Round towards zero can be done using Math.trunc(). Older browsers do not support this function. If you need to support these, you can use Math.ceil() for negative numbers and Math.floor() for positive numbers.

+3.5 => +3.0 using Math.floor()
-3.5 => -3.0 using Math.ceil()

Java GUI frameworks. What to choose? Swing, SWT, AWT, SwingX, JGoodies, JavaFX, Apache Pivot?

you forgot for Java Desktop Aplication based on JSR296 as built-in Swing Framework in NetBeans

excluding AWT and JavaFX are all of your desribed frameworks are based on Swing, if you'll start with Swing then you'd be understand (clearly) for all these Swing's (Based Frameworks)

ATW, SWT (Eclipse), Java Desktop Aplication(Netbeans), SwingX, JGoodies

all there frameworks (I don't know something more about JGoodies) incl. JavaFX haven't long time any progress, lots of Swing's Based Frameworks are stoped, if not then without newest version

just my view - best of them is SwingX, but required deepest knowledge about Swing,

Look and Feel for Swing's Based Frameworks

Get Current date & time with [NSDate date]

NSLocale* currentLocale = [NSLocale currentLocale];
[[NSDate date] descriptionWithLocale:currentLocale];  

or use

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// or @"yyyy-MM-dd hh:mm:ss a" if you prefer the time with AM/PM 
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);

Why am I getting "Unable to find manifest signing certificate in the certificate store" in my Excel Addin?

The issue of erroneous leftover entries in the .csproj file still occurs with VS2015update3 and can also occur if you try to change the signing certificate for a different one (even if that is one generated using the 'new' option in the certificate selection dropdown). The advice in the accepted answer (mark as not signed, save, unload project, edit .csproj, remove the properties relating to the old certificates/thumbprints/keys & reload project, set certificate) is reliable.

add elements to object array

You can use class System.Array for add new element:

Array.Resize(ref objArray, objArray.Length + 1);
objArray[objArray.Length - 1] = new Someobject();

Mysql database sync between two databases

Have a look at Schema and Data Comparison tools in dbForge Studio for MySQL. These tool will help you to compare, to see the differences, generate a synchronization script and synchronize two databases.

How to prevent a browser from storing passwords

I just change the type attribute of the field password to hidden before the click event:

document.getElementById("password").setAttribute("type", "hidden");
document.getElementById("save").click();

How to draw an overlay on a SurfaceView used by Camera on Android?

I think you should call the super.draw() method first before you do anything in surfaceView's draw method.

How to set the value of a hidden field from a controller in mvc

if you are not using model as per your question you can do like this

@Html.Hidden("hdnFlag" , new {id = "hdnFlag", value = "hdnFlag_value" })

else if you are using model (considering passing model has hdnFlag property), you can use this approch

@Html.HiddenFor(model => model.hdnFlag, new { value = Model.hdnFlag})

Application.WorksheetFunction.Match method

You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.

I used CountIf below, but there is lots of different ways to check existence of a value in a range.

Public Sub test()

Dim rng As Range
Dim aNumber As Long

aNumber = 666

Set rng = Sheet5.Range("B16:B615")

    If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then

        rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)

    Else
        MsgBox aNumber & " does not exist in range " & rng.Address
    End If

End Sub

ALTERNATIVE WAY

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Long

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    If Not IsError(Application.Match(aNumber, rng, 0)) Then
        rowNum = Application.Match(aNumber, rng, 0)
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

OR

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Variant

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    rowNum = Application.Match(aNumber, rng, 0)

    If Not IsError(rowNum) Then
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

default web page width - 1024px or 980px?

This is a bit of an open ended question since screen sizes are changing all the time and what might have been correct two years ago would likely be out of date now.

I use Twitter Bootstrap 3 at present and it uses a fluid grid system designed to work at sizes ranging from mobile/very small all the way up to the huge wide screen monitors that are now available.

Currently the upper default in BS3 is 1200px which translates to a container width of 1144px after taking account of margins and padding of the grids elements.

In my experience, modern designers are working to a width of around 1366px for desktop. All recent designs I've been given to implement have been 1366px.

Note also that you can customise the BS3 grid quite heavily. For example we will use a 32 column grid with 4px gutter in our sites/designs going forwards.

Ultimately the decision on page width needs to be made based on your website analytics and the screen sizes that your visitors typically use.

Android Studio - mergeDebugResources exception

I had the same problem and managed to solve, it simply downgrade your gradle version like this:

dependencies {
    classpath 'com.android.tools.build:gradle:YOUR_GRADLE_VERSION'
}

to

dependencies {
    classpath 'com.android.tools.build:gradle:OLDER_GRADLE_VERSION_THAT_YOUR'
}

for example:

YOUR_GRADLE_VERSION = 3.0.0

OLDER_GRADLE_VERSION_THAT_YOUR = 2.3.2

In Java, how to find if first character in a string is upper case without regex

String yourString = "yadayada";
if (Character.isUpperCase(yourString.charAt(0))) {
    // print something
} else {
    // print something else
}

Draggable div without jQuery UI

here's another way of making a draggable object that is centered to the click

http://jsfiddle.net/pixelass/fDcZS/

function endMove() {
    $(this).removeClass('movable');
}

function startMove() {
    $('.movable').on('mousemove', function(event) {
        var thisX = event.pageX - $(this).width() / 2,
            thisY = event.pageY - $(this).height() / 2;

        $('.movable').offset({
            left: thisX,
            top: thisY
        });
    });
}
$(document).ready(function() {
    $("#containerDiv").on('mousedown', function() {
        $(this).addClass('movable');
        startMove();
    }).on('mouseup', function() {
        $(this).removeClass('movable');
        endMove();
    });

});

CSS

#containerDiv {
    background:#333;
    position:absolute;
    width:200px;
    height:100px;
}

Function for C++ struct

Yes, a struct is identical to a class except for the default access level (member-wise and inheritance-wise). (and the extra meaning class carries when used with a template)

Every functionality supported by a class is consequently supported by a struct. You'd use methods the same as you'd use them for a class.

struct foo {
  int bar;
  foo() : bar(3) {}   //look, a constructor
  int getBar() 
  { 
    return bar; 
  }
};

foo f;
int y = f.getBar(); // y is 3

Python requests library how to pass Authorization header with single token

I was looking for something similar and came across this. It looks like in the first option you mentioned

r = requests.get('<MY_URI>', auth=('<MY_TOKEN>'))

"auth" takes two parameters: username and password, so the actual statement should be

r=requests.get('<MY_URI>', auth=('<YOUR_USERNAME>', '<YOUR_PASSWORD>'))

In my case, there was no password, so I left the second parameter in auth field empty as shown below:

r=requests.get('<MY_URI', auth=('MY_USERNAME', ''))

Hope this helps somebody :)

Get current category ID of the active page

I use the get_queried_object function to get the current category on a category.php template page.

$current_category = get_queried_object();

Jordan Eldredge is right, get_the_category is not suitable here.

Vertical Align Center in Bootstrap 4

you can vertically align your container by making the parent container flex and adding align-items:center:

body {
  display:flex;
  align-items:center;
}

Updated Pen

Copy a variable's value into another

The reason for this is simple. JavaScript uses refereces, so when you assign b = a you are assigning a reference to b thus when updating a you are also updating b

I found this on stackoverflow and will help prevent things like this in the future by just calling this method if you want to do a deep copy of an object.

function clone(obj) {
    // Handle the 3 simple types, and null or undefined
    if (null == obj || "object" != typeof obj) return obj;

    // Handle Date
    if (obj instanceof Date) {
        var copy = new Date();
        copy.setTime(obj.getTime());
        return copy;
    }

    // Handle Array
    if (obj instanceof Array) {
        var copy = [];
        for (var i = 0, len = obj.length; i < len; i++) {
            copy[i] = clone(obj[i]);
        }
        return copy;
    }

    // Handle Object
    if (obj instanceof Object) {
        var copy = {};
        for (var attr in obj) {
            if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
        }
        return copy;
    }

    throw new Error("Unable to copy obj! Its type isn't supported.");
}

Detect if an element is visible with jQuery

There's no need, just use fadeToggle() on the element:

$('#testElement').fadeToggle('fast');

Here's a demo.

MySQL 1062 - Duplicate entry '0' for key 'PRIMARY'

You need to specify the primary key as auto-increment

CREATE TABLE `momento_distribution`
  (
     `momento_id`       INT(11) NOT NULL AUTO_INCREMENT,
     `momento_idmember` INT(11) NOT NULL,
     `created_at`       DATETIME DEFAULT NULL,
     `updated_at`       DATETIME DEFAULT NULL,
     `unread`           TINYINT(1) DEFAULT '1',
     `accepted`         VARCHAR(10) NOT NULL DEFAULT 'pending',
     `ext_member`       VARCHAR(255) DEFAULT NULL,
     PRIMARY KEY (`momento_id`, `momento_idmember`),
     KEY `momento_distribution_FI_2` (`momento_idmember`),
     KEY `accepted` (`accepted`, `ext_member`)
  )
ENGINE=InnoDB
DEFAULT CHARSET=latin1$$

With regards to comment below, how about:

ALTER TABLE `momento_distribution`
  CHANGE COLUMN `id` `id` INT(11) NOT NULL AUTO_INCREMENT,
  DROP PRIMARY KEY,
  ADD PRIMARY KEY (`id`);

A PRIMARY KEY is a unique index, so if it contains duplicates, you cannot assign the column to be unique index, so you may need to create a new column altogether

Error Message : Cannot find or open the PDB file

Working with VS 2013. Try the following Tools -> Options -> Debugging -> Output Window -> Module Load Messages -> Off It will disable the display of modules loaded.

The way to check a HDFS directory's size?

hadoop fs -du -s -h /path/to/dir displays a directory's size in readable form.

Convert byte[] to char[]

byte[] a = new byte[50];

char [] cArray= System.Text.Encoding.ASCII.GetString(a).ToCharArray();

From the URL thedixon posted

http://bytes.com/topic/c-sharp/answers/250261-byte-char

You cannot ToCharArray the byte without converting it to a string first.

To quote Jon Skeet there

There's no need for the copying here - just use Encoding.GetChars. However, there's no guarantee that ASCII is going to be the appropriate encoding to use.

Case insensitive string compare in LINQ-to-SQL

Remember that there is a difference between whether the query works and whether it works efficiently! A LINQ statement gets converted to T-SQL when the target of the statement is SQL Server, so you need to think about the T-SQL that would be produced.

Using String.Equals will most likely (I am guessing) bring back all of the rows from SQL Server and then do the comparison in .NET, because it is a .NET expression that cannot be translated into T-SQL.

In other words using an expression will increase your data access and remove your ability to make use of indexes. It will work on small tables and you won't notice the difference. On a large table it could perform very badly.

That's one of the problems that exists with LINQ; people no longer think about how the statements they write will be fulfilled.

In this case there isn't a way to do what you want without using an expression - not even in T-SQL. Therefore you may not be able to do this more efficiently. Even the T-SQL answer given above (using variables with collation) will most likely result in indexes being ignored, but if it is a big table then it is worth running the statement and looking at the execution plan to see if an index was used.

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

If you're just playing around in local mode, you can drop metastore DB and reinstate it:

rm -rf metastore_db/
$HIVE_HOME/bin/schematool -initSchema -dbType derby

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

jQuery .scrollTop(); + animation

for this you can use callback method

body.animate({
      scrollTop:0
    }, 500, 
    function(){} // callback method use this space how you like
);

How to give a Linux user sudo access?

Edit /etc/sudoers file either manually or using the visudo application. Remember: System reads /etc/sudoers file from top to the bottom, so you could overwrite a particular setting by putting the next one below. So to be on the safe side - define your access setting at the bottom.

pip is not able to install packages correctly: Permission denied error

On a Mac, you need to use this command:

STATIC_DEPS=true sudo pip install lxml

trying to align html button at the center of the my page

You can center a button without using text-align on the parent div by simple using margin:auto; display:block;

For example:

HTML

<div>
  <button>Submit</button>
</div>

CSS

button {
  margin:auto;
  display:block;
}

SEE IT IN ACTION: CodePen

How to change cursor from pointer to finger using jQuery?

$('selector').css('cursor', 'pointer'); // 'default' to revert

I know that may be confusing per your original question, but the "finger" cursor is actually called "pointer".

The normal arrow cursor is just "default".

all possible default pointer looks DEMO

Install Qt on Ubuntu

Install Qt

sudo apt-get install build-essential

sudo apt-get install qtcreator

sudo apt-get install qt5-default

Install documentation and examples If Qt Creator is installed thanks to the Ubuntu Sofware Center or thanks to the synaptic package manager, documentation for Qt Creator is not installed. Hitting the F1 key will show you the following message : "No documentation available". This can easily be solved by installing the Qt documentation:

sudo apt-get install qt5-doc

sudo apt-get install qt5-doc-html qtbase5-doc-html

sudo apt-get install qtbase5-examples

Restart Qt Creator to make the documentation available.

Error while loading shared libraries

Problem:

radiusd: error while loading shared libraries: libfreeradius-radius-2.1.10.so: cannot open shared object file: No such file or directory

Reason:

Actually, the libraries have been installed in a place where dynamic linker cannot find it.

Solution:

While this is not a guarantee but using the following command may help you solve the “cannot open shared object file” error:

sudo /sbin/ldconfig -v

http://www.lucidarme.me/how-install-documentation-for-qt-creator/

https://ubuntuforums.org/showthread.php?t=2199929

https://itsfoss.com/error-while-loading-shared-libraries/

ModelSim-Altera error

downcast and upcast

Answer 1 : Yes it called upcasting but the way you do it is not modern way. Upcasting can be performed implicitly you don't need any conversion. So just writing Employee emp = mgr; is enough for upcasting.

Answer 2 : If you create object of Manager class we can say that manager is an employee. Because class Manager : Employee depicts Is-A relationship between Employee Class and Manager Class. So we can say that every manager is an employee.

But if we create object of Employee class we can not say that this employee is manager because class Employee is a class which is not inheriting any other class. So you can not directly downcast that Employee Class object to Manager Class object.

So answer is, if you want to downcast from Employee Class object to Manager Class object, first you must have object of Manager Class first then you can upcast it and then you can downcast it.

How to fix a header on scroll

custom scroll Header Fixed in shopify:

$(window).scroll(function(){
  var sticky = $('.site-header'),
      scroll = $(window).scrollTop();

  if (scroll >= 100) sticky.addClass('fixed');
  else sticky.removeClass('fixed');
})


css:


header.site-header.border-bottom.logo--left.fixed {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 9;
}

Oracle "SQL Error: Missing IN or OUT parameter at index:: 1"

I had a similar error on my side when I was using JDBC in Java code.

According to this website (the second awnser) it suggest that you are trying to execute the query with a missing parameter.

For instance :

exec SomeStoredProcedureThatReturnsASite( :L_kSite );

You are trying to execute the query without the last parameter.

Maybe in SQLPlus it doesn't have the same requirements, so it might have been a luck that it worked there.

Jquery Ajax, return success/error from mvc.net controller

Use Json class instead of Content as shown following:

    //  When I want to return an error:
    if (!isFileSupported)
    {
        Response.StatusCode = (int) HttpStatusCode.BadRequest;
        return Json("The attached file is not supported", MediaTypeNames.Text.Plain);
    }
    else
    {
        //  When I want to return sucess:
        Response.StatusCode = (int)HttpStatusCode.OK; 
        return Json("Message sent!", MediaTypeNames.Text.Plain);
    }

Also set contentType:

contentType: 'application/json; charset=utf-8',

http://localhost:50070 does not work HADOOP

For recent hadoop versions (I'm using 2.7.1)

The start\stop scripts are located in the sbin folder. The scripts are:

  • ./sbin/start-dfs.sh
  • ./sbin/stop-dfs.sh
  • ./sbin/start-yarn.sh
  • ./sbin/stop-yarn.sh

I didn't have to do anything with yarn though to get the NameNodeServer instance running.

Now my mistake was that I didn't format the NameNodeServer HDFS.

bin/hdfs namenode -format

I'm not quite sure what that does at the moment but it obviously prepares the space on which the NameNodeServer will use to operate.

Is there an operator to calculate percentage in Python?

There is no such operator in Python, but it is trivial to implement on your own. In practice in computing, percentages are not nearly as useful as a modulo, so no language that I can think of implements one.

R dplyr: Drop multiple columns

Be careful with the select() function, because it's used both in the dplyr and MASS packages, so if MASS is loaded, select() may not work properly. To find out what packages are loaded, type sessionInfo() and look for it in the "other attached packages:" section. If it is loaded, type detach( "package:MASS", unload = TRUE ), and your select() function should work again.

Cleanest way to build an SQL string in Java

I tend to use Spring's Named JDBC Parameters so I can write a standard string like "select * from blah where colX=':someValue'"; I think that's pretty readable.

An alternative would be to supply the string in a separate .sql file and read the contents in using a utility method.

Oh, also worth having a look at Squill: https://squill.dev.java.net/docs/tutorial.html

Loop structure inside gnuplot?

There sure is (in gnuplot 4.4+):

plot for [i=1:1000] 'data'.i.'.txt' using 1:2 title 'Flow '.i

The variable i can be interpreted as a variable or a string, so you could do something like

plot for [i=1:1000] 'data'.i.'.txt' using 1:($2+i) title 'Flow '.i

if you want to have lines offset from each other.

Type help iteration at the gnuplot command line for more info.

Also be sure to see @DarioP's answer about the do for syntax; that gives you something closer to a traditional for loop.

Android Starting Service at Boot Time , How to restart service class after device Reboot?

Your receiver:

public class MyReceiver extends BroadcastReceiver {   

    @Override
    public void onReceive(Context context, Intent intent) {

     Intent myIntent = new Intent(context, YourService.class);
     context.startService(myIntent);

    }
}

Your AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.broadcast.receiver.example"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true">

        <activity android:name=".BR_Example"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    <!-- Declaring broadcast receiver for BOOT_COMPLETED event. -->
        <receiver android:name=".MyReceiver" android:enabled="true" android:exported="false">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>

    </application>

    <!-- Adding the permission -->
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

</manifest>

Are there bookmarks in Visual Studio Code?

You need to do this via an extension as of the version 1.8.1.

  1. Go to View ? Extensions. This will open Extensions Panel.

  2. Type bookmark to list all related extensions.

  3. Install


I personally like "Numbered Bookmarks" - it is pretty simple and powerful.

Go to the line you need to create a bookmark.

Click Ctrl + Shift + [some number]

Ex: Ctrl + Shift + 2

Now you can jump to this line from anywhere by pressing Ctrl + number

Ex: Ctrl + 2

Pandas "Can only compare identically-labeled DataFrame objects" error

When you compare two DataFrames, you must ensure that the number of records in the first DataFrame matches with the number of records in the second DataFrame. In our example, each of the two DataFrames had 4 records, with 4 products and 4 prices.

If, for example, one of the DataFrames had 5 products, while the other DataFrame had 4 products, and you tried to run the comparison, you would get the following error:

ValueError: Can only compare identically-labeled Series objects

this should work

import pandas as pd
import numpy as np

firstProductSet = {'Product1': ['Computer','Phone','Printer','Desk'],
                   'Price1': [1200,800,200,350]
                   }
df1 = pd.DataFrame(firstProductSet,columns= ['Product1', 'Price1'])


secondProductSet = {'Product2': ['Computer','Phone','Printer','Desk'],
                    'Price2': [900,800,300,350]
                    }
df2 = pd.DataFrame(secondProductSet,columns= ['Product2', 'Price2'])


df1['Price2'] = df2['Price2'] #add the Price2 column from df2 to df1

df1['pricesMatch?'] = np.where(df1['Price1'] == df2['Price2'], 'True', 'False')  #create new column in df1 to check if prices match
df1['priceDiff?'] = np.where(df1['Price1'] == df2['Price2'], 0, df1['Price1'] - df2['Price2']) #create new column in df1 for price diff 
print (df1)

example from https://datatofish.com/compare-values-dataframes/

Using the Underscore module with Node.js

The Node REPL uses the underscore variable to hold the result of the last operation, so it conflicts with the Underscore library's use of the same variable. Try something like this:

Admin-MacBook-Pro:test admin$ node
> _und = require("./underscore-min")
{ [Function]
  _: [Circular],
  VERSION: '1.1.4',
  forEach: [Function],
  each: [Function],
  map: [Function],
  inject: [Function],
  (...more functions...)
  templateSettings: { evaluate: /<%([\s\S]+?)%>/g, interpolate: /<%=([\s\S]+?)%>/g },
  template: [Function] }
> _und.max([1,2,3])
3
> _und.max([4,5,6])
6

Moment.js - two dates difference in number of days

the diff method returns the difference in milliseconds. Instantiating moment(diff) isn't meaningful.

You can define a variable :

var dayInMilliseconds = 1000 * 60 * 60 * 24;

and then use it like so :

diff / dayInMilliseconds // --> 15

Edit

actually, this is built into the diff method, dubes' answer is better

Spring: return @ResponseBody "ResponseEntity<List<JSONObject>>"

I am late for this but i want put some more solution relevant to this.

 @GetMapping
public ResponseEntity<List<JSONObject>> getRole() {
    return ResponseEntity.ok(service.getRole());
}

Managing jQuery plugin dependency in webpack

Add this to your plugins array in webpack.config.js

new webpack.ProvidePlugin({
    'window.jQuery': 'jquery',
    'window.$': 'jquery',
})

then require jquery normally

require('jquery');

If pain persists getting other scripts to see it, try explicitly placing it in the global context via (in the entry js)

window.$ = jQuery;

How do I get TimeSpan in minutes given two Dates?

TimeSpan span = end-start;
double totalMinutes = span.TotalMinutes;

How to change the default browser to debug with in Visual Studio 2008?

An easier way to do this is simply by selecting the arrow next to the Start Debugging:

the Start Debugging

Then in the Drop Down goto Web Browser and select the browser you would like to debug the site with, you can also select Browse with... to set the default as explained in other answers.

Concatenating strings doesn't work as expected

std::string a = "Hello ";
std::string b = "World ";
std::string c = a;
c.append(b);

Correct way to populate an Array with a Range in Ruby

Sounds like you're doing this:

0..10.to_a

The warning is from Fixnum#to_a, not from Range#to_a. Try this instead:

(0..10).to_a

How can I clear event subscriptions in C#?

Setting the event to null inside the class works. When you dispose a class you should always set the event to null, the GC has problems with events and may not clean up the disposed class if it has dangling events.

'JSON' is undefined error in JavaScript in Internet Explorer

Check for extra commas in your JSON response. If the last element of an array has a comma, this will break in IE

fatal: Unable to create temporary file '/home/username/git/myrepo.git/./objects/pack/tmp_pack_XXXXXX': Permission denied

It would seem like your user doesn't have permission to write to that directory on the server. Please make sure that the permissions are correct. The user will need write permissions on that directory.

What are good message queue options for nodejs?

Here's a couple of recommendations I can make:

node-amqp: A RabbitMQ client that I have successfully used in combination with Socket.IO to make a real-time multi-player game and chat application amongst other things. Seems reliable enough.

zeromq.node: If you want to go down the non-brokered route this might be worth a look. More work to implement functionality but your more likely to get lower latency and higher throughput.

Negative list index?

Negative numbers mean that you count from the right instead of the left. So, list[-1] refers to the last element, list[-2] is the second-last, and so on.

Border color on default input style

You can use jquery for this by utilizing addClass() method

CSS

 .defaultInput
    {
     width: 100px;
     height:25px;
     padding: 5px;
    }

.error
{
 border:1px solid red;
}

<input type="text" class="defaultInput"/>

Jquery Code

$(document).ready({
  $('.defaultInput').focus(function(){
       $(this).addClass('error');
  });
});

Update: You can remove that error class using

$('.defaultInput').removeClass('error');

It won't remove that default style. It will remove .error class only

How to pause javascript code execution for 2 seconds

You can use setTimeout to do this

function myFunction() {
    // your code to run after the timeout
}

// stop for sometime if needed
setTimeout(myFunction, 5000);

Javascript one line If...else...else if statement

This is use mostly for assigning variable, and it uses binomial conditioning eg.

var time = Date().getHours(); // or something

var clockTime = time > 12 ? 'PM' : 'AM' ;

There is no ElseIf, for the sake of development don't use chaining, you can use switch which is much faster if you have multiple conditioning in .js

How to launch multiple Internet Explorer windows/tabs from batch file?

There is a setting in the IE options that controls whether it should open new links in an existing window or in a new window. I'm not sure if you can control it from the command line but maybe changing this option would be enough for you.

In IE7 it looks like the option is "Reuse windows for launching shortcuts (when tabbed browsing is disabled)".

How to check if ZooKeeper is running or up from command prompt?

enter the below command to verify if zookeeper is running :

echo "ruok" | nc localhost 2181 ; echo 

expected response: imok

Case statement in MySQL

Yes, something like this:

SELECT
    id,
    action_heading,
    CASE
        WHEN action_type = 'Income' THEN action_amount
        ELSE NULL
    END AS income_amt,
    CASE
        WHEN action_type = 'Expense' THEN action_amount
        ELSE NULL
    END AS expense_amt

FROM tbl_transaction;

As other answers have pointed out, MySQL also has the IF() function to do this using less verbose syntax. I generally try to avoid this because it is a MySQL-specific extension to SQL that isn't generally supported elsewhere. CASE is standard SQL and is much more portable across different database engines, and I prefer to write portable queries as much as possible, only using engine-specific extensions when the portable alternative is considerably slower or less convenient.

Password Protect a SQLite DB. Is it possible?

You can use the built-in encryption of the sqlite .net provider (System.Data.SQLite). See more details at http://web.archive.org/web/20070813071554/http://sqlite.phxsoftware.com/forums/t/130.aspx

To encrypt an existing unencrypted database, or to change the password of an encrypted database, open the database and then use the ChangePassword() function of SQLiteConnection:

// Opens an unencrypted database
SQLiteConnection cnn = new SQLiteConnection("Data Source=c:\\test.db3");
cnn.Open();
// Encrypts the database. The connection remains valid and usable afterwards.
cnn.ChangePassword("mypassword");

To decrypt an existing encrypted database call ChangePassword() with a NULL or "" password:

// Opens an encrypted database
SQLiteConnection cnn = new SQLiteConnection("Data Source=c:\\test.db3;Password=mypassword");
cnn.Open();
// Removes the encryption on an encrypted database.
cnn.ChangePassword(null);

To open an existing encrypted database, or to create a new encrypted database, specify a password in the ConnectionString as shown in the previous example, or call the SetPassword() function before opening a new SQLiteConnection. Passwords specified in the ConnectionString must be cleartext, but passwords supplied in the SetPassword() function may be binary byte arrays.

// Opens an encrypted database by calling SetPassword()
SQLiteConnection cnn = new SQLiteConnection("Data Source=c:\\test.db3");
cnn.SetPassword(new byte[] { 0xFF, 0xEE, 0xDD, 0x10, 0x20, 0x30 });
cnn.Open();
// The connection is now usable

By default, the ATTACH keyword will use the same encryption key as the main database when attaching another database file to an existing connection. To change this behavior, you use the KEY modifier as follows:

If you are attaching an encrypted database using a cleartext password:

// Attach to a database using a different key than the main database
SQLiteConnection cnn = new SQLiteConnection("Data Source=c:\\test.db3");
cnn.Open();
cmd = new SQLiteCommand("ATTACH DATABASE 'c:\\pwd.db3' AS [Protected] KEY 'mypassword'", cnn);
cmd.ExecuteNonQuery();

To attach an encrypted database using a binary password:

// Attach to a database encrypted with a binary key
SQLiteConnection cnn = new SQLiteConnection("Data Source=c:\\test.db3");
cnn.Open();
cmd = new SQLiteCommand("ATTACH DATABASE 'c:\\pwd.db3' AS [Protected] KEY X'FFEEDD102030'", cnn);
cmd.ExecuteNonQuery();

Windows equivalent of the 'tail' command

you can also use Git bash where head and tail are emulated as well

Sorted collection in Java

If you just want to sort a list, use any kind of List and use Collections.sort(). If you want to make sure elements in the list are unique and always sorted, use a SortedSet.

Delete everything in a MongoDB database

Here are some useful delete operations for mongodb using mongo shell

To delete particular document in collections: db.mycollection.remove( {name:"stack"} )

To delete all documents in collections: db.mycollection.remove()

To delete any particular collection : db.mycollection.drop()

to delete database : first go to that database by use mydb command and then

db.dropDatabase()

Is there a simple, elegant way to define singletons?

A slightly different approach to implement the singleton in Python is the borg pattern by Alex Martelli (Google employee and Python genius).

class Borg:
    __shared_state = {}
    def __init__(self):
        self.__dict__ = self.__shared_state

So instead of forcing all instances to have the same identity, they share state.

PHP Parse HTML code

Use PHP Document Object Model:

<?php
   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   $DOM = new DOMDocument;
   $DOM->loadHTML($str);

   //get all H1
   $items = $DOM->getElementsByTagName('h1');

   //display all H1 text
   for ($i = 0; $i < $items->length; $i++)
        echo $items->item($i)->nodeValue . "<br/>";
?>

This outputs as:

 T1
 T2
 T3

[EDIT]: After OP Clarification:

If you want the content like Lorem ipsum. etc, you can directly use this regex:

<?php
   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);
?>

this outputs:

Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG

How do I get an empty array of any size in python?

also you can extend that with extend method of list.

a= []
a.extend([None]*10)
a.extend([None]*20)

What Are Some Good .NET Profilers?

I've been working with JetBrains dotTrace for WinForms and Console Apps (not tested on ASP.net yet), and it works quite well:

They recently also added a "Personal License" that is significantly cheaper than the corporate one. Still, if anyone else knows some cheaper or even free ones, I'd like to hear as well :-)

Convert string to Color in C#

I've used something like this before:

        public static T CreateFromString<T>(string stringToCreateFrom) {

        T output = Activator.CreateInstance<T>();

        if (!output.GetType().IsEnum)
            throw new IllegalTypeException();

        try {
            output = (T) Enum.Parse(typeof (T), stringToCreateFrom, true);
        }
        catch (Exception ex) {
            string error = "Cannot parse '" + stringToCreateFrom + "' to enum '" + typeof (T).FullName + "'";
            _logger.Error(error, ex);
            throw new IllegalArgumentException(error, ex);
        }

        return output;
    }

Another Repeated column in mapping for entity error

We have resolved the circular dependency(Parent-child Entities) by mapping the child entity instead of parent entity in Grails 4(GORM).

Example:

Class Person {
    String name
}

Class Employee extends Person{
    String empId
}

//Before my code 
Class Address {
    static belongsTo = [person: Person]
}

//We changed our Address class to:
Class Address {
    static belongsTo = [person: Employee]
}

How do I import a CSV file in R?

You would use the read.csv function; for example:

dat = read.csv("spam.csv", header = TRUE)

You can also reference this tutorial for more details.

Note: make sure the .csv file to read is in your working directory (using getwd()) or specify the right path to file. If you want, you can set the current directory using setwd.

How to read data from excel file using c#

Save the Excel file to CSV, and read the resulting file with C# using a CSV reader library like FileHelpers.

.htaccess redirect http to https

Replace your domain with domainname.com , it's working with me .

RewriteEngine On
RewriteCond %{HTTP_HOST} ^domainname\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.domainname.com/$1 [R,L]

Is there a common Java utility to break a list into batches?

You can use below code to get the batch of list.

Iterable<List<T>> batchIds = Iterables.partition(list, batchSize);

You need to import Google Guava library to use above code.

What is the standard way to add N seconds to datetime.time in Python?

As others here have stated, you can just use full datetime objects throughout:

from datetime import datetime, date, time, timedelta
sometime = time(8,00) # 8am
later = (datetime.combine(date.today(), sometime) + timedelta(seconds=3)).time()

However, I think it's worth explaining why full datetime objects are required. Consider what would happen if I added 2 hours to 11pm. What's the correct behavior? An exception, because you can't have a time larger than 11:59pm? Should it wrap back around?

Different programmers will expect different things, so whichever result they picked would surprise a lot of people. Worse yet, programmers would write code that worked just fine when they tested it initially, and then have it break later by doing something unexpected. This is very bad, which is why you're not allowed to add timedelta objects to time objects.

How do you use String.substringWithRange? (or, how do Ranges work in Swift?)

Well, I had the same issue and solved with the "bridgeToObjectiveC()" function:

var helloworld = "Hello World!"
var world = helloworld.bridgeToObjectiveC().substringWithRange(NSMakeRange(6,6))
println("\(world)") // should print World!

Please note that in the example, substringWithRange in conjunction with NSMakeRange take the part of the string starting at index 6 (character "W") and finishing at index 6 + 6 positions ahead (character "!")

Cheers.

CFNetwork SSLHandshake failed iOS 9

In iOS 10+, the TLS string MUST be of the form "TLSv1.0". It can't just be "1.0". (Sigh)


The following combination of the other Answers works.

Let's say you are trying to connect to a host (YOUR_HOST.COM) that only has TLS 1.0.

Add these to your app's Info.plist

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>YOUR_HOST.COM</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSTemporaryExceptionMinimumTLSVersion</key>
            <string>TLSv1.0</string>
            <key>NSTemporaryExceptionRequiresForwardSecrecy</key>
            <false/>
        </dict>
    </dict>
</dict>

"Operation must use an updateable query" error in MS Access

set permission on application directory solve this issue with me

To set this permission, right click on the App_Data folder (or whichever other folder you have put the file in) and select Properties. Look for the Security tab. If you can't see it, you need to go to My Computer, then click Tools and choose Folder Options.... then click the View tab. Scroll to the bottom and uncheck "Use simple file sharing (recommended)". Back to the Security tab, you need to add the relevant account to the Group or User Names box. Click Add.... then click Advanced, then Find Now. The appropriate account should be listed. Double click it to add it to the Group or User Names box, then check the Modify option in the permissions. That's it. You are done.

Convert a python UTC datetime to a local datetime using only python standard library?

You can't do it with only the standard library as the standard library doesn't have any timezones. You need pytz or dateutil.

>>> from datetime import datetime
>>> now = datetime.utcnow()
>>> from dateutil import tz
>>> HERE = tz.tzlocal()
>>> UTC = tz.gettz('UTC')

The Conversion:
>>> gmt = now.replace(tzinfo=UTC)
>>> gmt.astimezone(HERE)
datetime.datetime(2010, 12, 30, 15, 51, 22, 114668, tzinfo=tzlocal())

Or well, you can do it without pytz or dateutil by implementing your own timezones. But that would be silly.

jQuery function to get all unique elements from an array?

Plain JavaScript modern solution if you don't need IE support (Array.from is not supported in IE).

You can use combination of Set and Array.from.

_x000D_
_x000D_
const arr = [1, 1, 11, 2, 4, 2, 5, 3, 1];_x000D_
const set = new Set(arr);_x000D_
const uniqueArr = Array.from(set);_x000D_
_x000D_
console.log(uniqueArr);
_x000D_
_x000D_
_x000D_

The Set object lets you store unique values of any type, whether primitive values or object references.

The Array.from() method creates a new Array instance from an array-like or iterable object.

Also Array.from() can be replaced with spread operator.

_x000D_
_x000D_
const arr = [1, 1, 11, 2, 4, 2, 5, 3, 1];_x000D_
const set = new Set(arr);_x000D_
const uniqueArr = [...set];_x000D_
_x000D_
console.log(uniqueArr);
_x000D_
_x000D_
_x000D_

Get immediate first child element

Both these will give you the first child node:

console.log(parentElement.firstChild); // or
console.log(parentElement.childNodes[0]);

If you need the first child that is an element node then use:

console.log(parentElement.children[0]);

Edit

Ah, I see your problem now; parentElement is an array.

If you know that getElementsByClassName will only return one result, which it seems you do, you should use [0] to dearray (yes, I made that word up) the element:

var parentElement = document.getElementsByClassName("uniqueClassName")[0];

Load image from resources area of project in C#

Strangely enough, from poking in the designer I find what seems to be a much simpler approach:

The image seems to be available from .Properties.Resources.

I'm simply using an image as all I'm interested in is pasting it into a control with an image on it.

(Net 4.0, VS2010.)

Posting a File and Associated Data to a RESTful WebService preferably as JSON

Here is my approach API (i use example) - as you can see, you I don't use any file_id (uploaded file identifier to the server) in API:

  1. Create photo object on server:

     POST: /projects/{project_id}/photos   
     body: { name: "some_schema.jpg", comment: "blah"}
     response: photo_id
    
  2. Upload file (note that file is in singular form because it is only one per photo):

     POST: /projects/{project_id}/photos/{photo_id}/file
     body: file to upload
     response: -
    

And then for instance:

  1. Read photos list

     GET: /projects/{project_id}/photos
     response: [ photo, photo, photo, ... ] (array of objects)
    
  2. Read some photo details

     GET: /projects/{project_id}/photos/{photo_id}
     response: { id: 666, name: 'some_schema.jpg', comment:'blah'} (photo object)
    
  3. Read photo file

     GET: /projects/{project_id}/photos/{photo_id}/file
     response: file content
    

So the conclusion is that, first you create an object (photo) by POST, and then you send second request with the file (again POST). To not have problems with CACHE in this approach we assume that we can only delete old photos and add new - no update binary photo files (because new binary file is in fact... NEW photo). However if you need to be able to update binary files and cache them, then in point 4 return also fileId and change 5 to GET: /projects/{project_id}/photos/{photo_id}/files/{fileId}.

Angular 2 How to redirect to 404 or other path if the path does not exist

As shaishab roy says, in the cheat sheet you can find the answer.

But in his answer, the given response was :

{path: '/home/...', name: 'Home', component: HomeComponent}
{path: '/', redirectTo: ['Home']},
{path: '/user/...', name: 'User', component: UserComponent},
{path: '/404', name: 'NotFound', component: NotFoundComponent},

{path: '/*path', redirectTo: ['NotFound']}

For some reasons, it doesn't works on my side, so I tried instead :

{path: '/**', redirectTo: ['NotFound']}

and it works. Be careful and don't forget that you need to put it at the end, or else you will often have the 404 error page ;).

counting number of directories in a specific directory

Run stat -c %h folder and subtract 2 from the result. This employs only a single subprocess as opposed to the 2 (or even 3) required by most of the other solutions here (typically find plus wc).

Using sh/bash:

cnt=$((`stat -c %h folder` - 2))
echo $cnt   # 'echo' is a sh/bash builtin, not an additional process

Using csh/tcsh:

@ cnt = `stat -c %h folder` - 2
echo $cnt   # 'echo' is a csh/tcsh builtin, not an additional process


Explanation: stat -c %h folder prints the number of hardlinks to folder, and each subfolder under folder contains a ../ entry which is a hardlink back to folder. You must subtract 2 because there are two additional hardlinks in the count:

  1. folder's own self-referential ./ entry, and
  2. folder's parent's link to folder

Can't create handler inside thread which has not called Looper.prepare()

All the answers above are correct, but I think this is the easiest example possible:

public class ExampleActivity extends Activity {
    private Handler handler;
    private ProgressBar progress;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        progress = (ProgressBar) findViewById(R.id.progressBar1);
        handler = new Handler();
    }

    public void clickAButton(View view) {
        // Do something that takes a while
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                handler.post(new Runnable() { // This thread runs in the UI
                    @Override
                    public void run() {
                        progress.setProgress("anything"); // Update the UI
                    }
                });
            }
        };
        new Thread(runnable).start();
    }
}

What this does is update a progress bar in the UI thread from a completely different thread passed through the post() method of the handler declared in the activity.

Hope it helps!

Python 3 TypeError: must be str, not bytes with sys.stdout.write()

Python 3 handles strings a bit different. Originally there was just one type for strings: str. When unicode gained traction in the '90s the new unicode type was added to handle Unicode without breaking pre-existing code1. This is effectively the same as str but with multibyte support.

In Python 3 there are two different types:

  • The bytes type. This is just a sequence of bytes, Python doesn't know anything about how to interpret this as characters.
  • The str type. This is also a sequence of bytes, but Python knows how to interpret those bytes as characters.
  • The separate unicode type was dropped. str now supports unicode.

In Python 2 implicitly assuming an encoding could cause a lot of problems; you could end up using the wrong encoding, or the data may not have an encoding at all (e.g. it’s a PNG image).
Explicitly telling Python which encoding to use (or explicitly telling it to guess) is often a lot better and much more in line with the "Python philosophy" of "explicit is better than implicit".

This change is incompatible with Python 2 as many return values have changed, leading to subtle problems like this one; it's probably the main reason why Python 3 adoption has been so slow. Since Python doesn't have static typing2 it's impossible to change this automatically with a script (such as the bundled 2to3).

  • You can convert str to bytes with bytes('h€llo', 'utf-8'); this should produce b'H\xe2\x82\xacllo'. Note how one character was converted to three bytes.
  • You can convert bytes to str with b'H\xe2\x82\xacllo'.decode('utf-8').

Of course, UTF-8 may not be the correct character set in your case, so be sure to use the correct one.

In your specific piece of code, nextline is of type bytes, not str, reading stdout and stdin from subprocess changed in Python 3 from str to bytes. This is because Python can't be sure which encoding this uses. It probably uses the same as sys.stdin.encoding (the encoding of your system), but it can't be sure.

You need to replace:

sys.stdout.write(nextline)

with:

sys.stdout.write(nextline.decode('utf-8'))

or maybe:

sys.stdout.write(nextline.decode(sys.stdout.encoding))

You will also need to modify if nextline == '' to if nextline == b'' since:

>>> '' == b''
False

Also see the Python 3 ChangeLog, PEP 358, and PEP 3112.


1 There are some neat tricks you can do with ASCII that you can't do with multibyte character sets; the most famous example is the "xor with space to switch case" (e.g. chr(ord('a') ^ ord(' ')) == 'A') and "set 6th bit to make a control character" (e.g. ord('\t') + ord('@') == ord('I')). ASCII was designed in a time when manipulating individual bits was an operation with a non-negligible performance impact.

2 Yes, you can use function annotations, but it's a comparatively new feature and little used.

Java Pass Method as Parameter

I appreciate the answers above but I was able to achieve the same behavior using the method below; an idea borrowed from Javascript callbacks. I'm open to correction though so far so good (in production).

The idea is to use the return type of the function in the signature, meaning that the yield has to be static.

Below is a function that runs a process with a timeout.

public static void timeoutFunction(String fnReturnVal) {

    Object p = null; // whatever object you need here

    String threadSleeptime = null;

    Config config;

    try {
        config = ConfigReader.getConfigProperties();
        threadSleeptime = config.getThreadSleepTime();

    } catch (Exception e) {
        log.error(e);
        log.error("");
        log.error("Defaulting thread sleep time to 105000 miliseconds.");
        log.error("");
        threadSleeptime = "100000";
    }

    ExecutorService executor = Executors.newCachedThreadPool();
    Callable<Object> task = new Callable<Object>() {
        public Object call() {
            // Do job here using --- fnReturnVal --- and return appropriate value
            return null;
        }
    };
    Future<Object> future = executor.submit(task);

    try {
        p = future.get(Integer.parseInt(threadSleeptime), TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        log.error(e + ". The function timed out after [" + threadSleeptime
                + "] miliseconds before a response was received.");
    } finally {
        // if task has started then don't stop it
        future.cancel(false);
    }
}

private static String returnString() {
    return "hello";
}

public static void main(String[] args) {
    timeoutFunction(returnString());
}

Named tuple and default values for optional keyword arguments

Combining approaches of @Denis and @Mark:

from collections import namedtuple
import inspect

class Node(namedtuple('Node', 'left right val')):
    __slots__ = ()
    def __new__(cls, *args, **kwargs):
        args_list = inspect.getargspec(super(Node, cls).__new__).args[len(args)+1:]
        params = {key: kwargs.get(key) for key in args_list + kwargs.keys()}
        return super(Node, cls).__new__(cls, *args, **params) 

That should support creating the tuple with positional arguments and also with mixed cases. Test cases:

>>> print Node()
Node(left=None, right=None, val=None)

>>> print Node(1,2,3)
Node(left=1, right=2, val=3)

>>> print Node(1, right=2)
Node(left=1, right=2, val=None)

>>> print Node(1, right=2, val=100)
Node(left=1, right=2, val=100)

>>> print Node(left=1, right=2, val=100)
Node(left=1, right=2, val=100)

>>> print Node(left=1, right=2)
Node(left=1, right=2, val=None)

but also support TypeError:

>>> Node(1, left=2)
TypeError: __new__() got multiple values for keyword argument 'left'

How to set a cell to NaN in a pandas dataframe

You can use replace:

df['y'] = df['y'].replace({'N/A': np.nan})

Also be aware of the inplace parameter for replace. You can do something like:

df.replace({'N/A': np.nan}, inplace=True)

This will replace all instances in the df without creating a copy.

Similarly, if you run into other types of unknown values such as empty string or None value:

df['y'] = df['y'].replace({'': np.nan})

df['y'] = df['y'].replace({None: np.nan})

Reference: Pandas Latest - Replace

"A connection attempt failed because the connected party did not properly respond after a period of time" using WebClient

setting the proxy address explicitly in web.config solved my problem

<system.net> 
    <defaultProxy> 
            <proxy usesystemdefault = "false" proxyaddress="http://address:port" bypassonlocal="false"/> 
    </defaultProxy> 
</system.net>

Resolving the “TCP error code 10060: A connection attempt failed…” while consuming a web service

MAX(DATE) - SQL ORACLE

Oracle 9i+ (maybe 8i too) has FIRST/LAST aggregate functions, that make computation over groups of rows according to row's rank in group. Assuming all rows as one group, you'll get what you want without subqueries:

SELECT
  max(MEMBSHIP_ID)
  keep (
      dense_rank first
      order by paym_date desc NULLS LAST
  ) as LATEST_MEMBER_ID
FROM user_payment
WHERE user_id=1

Pythonic way to print list items

OP's question is: does something like following exists, if not then why

print(p) for p in myList # doesn't work, OP's intuition

answer is, it does exist which is:

[p for p in myList] #works perfectly

Basically, use [] for list comprehension and get rid of print to avoiding printing None. To see why print prints None see this

How can I get the value of a registry key from within a batch script?

Great level of solutions here.

My little grain of salt as the solution @Patrick Cuff did not work out of the box; I had 2 problems

  • I use Windows 7 => changed to "skip=2"
  • The value of the registry value had a space in it Value Value = C:\Program Files\...

Here is the solution I found: taking 4 tokens and setting ValueValue to %%C and %%D. (Thanks @Ivan!)

setlocal ENABLEEXTENSIONS
set KEY_NAME="HKEY_CURRENT_USER\Software\Microsoft\Command Processor"
set VALUE_NAME=DefaultColor

FOR /F "usebackq skip=2 tokens=1-4" %%A IN (`REG QUERY %KEY_NAME% /v %VALUE_NAME% 2^>nul`) DO (
    set ValueName=%%A
    set ValueType=%%B
    set ValueValue=%%C %%D
)

if defined ValueName (
    @echo Value Name = %ValueName%
    @echo Value Type = %ValueType%
    @echo Value Value = %ValueValue%
) else (
    @echo "%KEY_NAME:"=%\%VALUE_NAME%" not found.
)

Split string based on a regular expression

When you use re.split and the split pattern contains capturing groups, the groups are retained in the output. If you don't want this, use a non-capturing group instead.

What are best practices for REST nested resources?

Rails provides a solution to this: shallow nesting.

I think this is a good because when you deal directly with a known resource, there's no need to use nested routes, as has been discussed in other answers here.

How to call javascript from a href?

The proper way to invoke javascript code when clicking a link would be to add an onclick handler:

<a href="#" onclick="myFunction()">LinkText</a>

Although an even "more proper" way would be to get it out of the html all together and add the handler with another javascript when the dom is loaded.

Get public/external IP address?

checkip.dyndns.org is not always works correctly. For example, for my machine it shows internal after-NAT address:

Current IP Address: 192.168.1.120

I think its happening, because of I have my local DNS-zone behind NAT, and my browser sends to checkip its local IP address, which is returned back.

Also, http is heavy weight and text oriented TCP-based protocol, so not very suitable for quick and efficient regular request for external IP address. I suggest to use UDP-based, binary STUN, especially designed for this purposes:

http://en.wikipedia.org/wiki/STUN

STUN-server is like "UDP mirror". You looking to it, and see "how I looks".

There is many public STUN-servers over the world, where you can request your external IP. For example, see here:

http://www.voip-info.org/wiki/view/STUN

You can download any STUN-client library, from Internet, for example, here:

http://www.codeproject.com/Articles/18492/STUN-Client

And use it.

Redirect from an HTML page

I use a script which redirects the user from index.html to relative url of Login Page

<html>
  <head>
    <title>index.html</title>
  </head>
  <body onload="document.getElementById('lnkhome').click();">
    <a href="/Pages/Login.aspx" id="lnkhome">Go to Login Page<a>
  </body>
</html>

How to load/edit/run/save text files (.py) into an IPython notebook cell?

Drag and drop a Python file in the Ipython notebooks "home" notebooks table, click upload. This will create a new notebook with only one cell containing your .py file content

Else copy/paste from your favorite editor ;)

ORA-12505, TNS:listener does not currently know of SID given in connect descriptor

I encounter this problem because I did kill task to "Oracle" task in the Task Manager. To fix it you need to open the cmd -> type: services.msc -> the window with all services will open -> find service "OracleServiceXE" -> right click: start.

How do you format the day of the month to say "11th", "21st" or "23rd" (ordinal indicator)?

private String getCurrentDateInSpecificFormat(Calendar currentCalDate) {
    String dayNumberSuffix = getDayNumberSuffix(currentCalDate.get(Calendar.DAY_OF_MONTH));
    DateFormat dateFormat = new SimpleDateFormat(" d'" + dayNumberSuffix + "' MMMM yyyy");
    return dateFormat.format(currentCalDate.getTime());
}

private String getDayNumberSuffix(int day) {
    if (day >= 11 && day <= 13) {
        return "th";
    }
    switch (day % 10) {
    case 1:
        return "st";
    case 2:
        return "nd";
    case 3:
        return "rd";
    default:
        return "th";
    }
}

Which version of MVC am I using?

In Solution Explorer open packages.config and find Microsoft.AspNet.MVC:

package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net461"

From the above we can see it's an Asp.Net MVC 5.2.3 Version.

Moreover packages.config file also helps us to track all the installed packages with their respective versions.

How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption

This message digital envelope routines: EVP_DecryptFInal_ex: bad decrypt can also occur when you encrypt and decrypt with an incompatible versions of openssl.

The issue I was having was that I was encrypting on Windows which had version 1.1.0 and then decrypting on a generic Linux system which had 1.0.2g.

It is not a very helpful error message!


Working solution:

A possible solution from @AndrewSavinykh that worked for many (see the comments):

Default digest has changed between those versions from md5 to sha256. One can specify the default digest on the command line as -md sha256 or -md md5 respectively

The Android emulator is not starting, showing "invalid command-line parameter"

emulator-arm.exe error, couldn't run. Problem was that my laptop has 2 graphic cards and was selected only one (the performance one) from Nvidia 555M. By selecting the other graphic card from Nvidia mediu,(selected base Intel card) the emulator started!

SSH to Elastic Beanstalk instance

Elastic Beanstalk can bind a single EC2 keypair to an instance profile. A manual solution to have multiple users ssh into EBS is to add their public keys in authorized_keys file.

Scheduled run of stored procedure on SQL server

Yes, if you use the SQL Server Agent.

Open your Enterprise Manager, and go to the Management folder under the SQL Server instance you are interested in. There you will see the SQL Server Agent, and underneath that you will see a Jobs section.

Here you can create a new job and you will see a list of steps you will need to create. When you create a new step, you can specify the step to actually run a stored procedure (type TSQL Script). Choose the database, and then for the command section put in something like:

exec MyStoredProcedure

That's the overview, post back here if you need any further advice.

[I actually thought I might get in first on this one, boy was I wrong :)]

How Big can a Python List Get?

There is no limitation of list number. The main reason which causes your error is the RAM. Please upgrade your memory size.

How do I get the size of a java.sql.ResultSet?

I was having the same problem. Using ResultSet.first() in this way just after the execution solved it:

if(rs.first()){
    // Do your job
} else {
    // No rows take some actions
}

Documentation (link):

boolean first()
    throws SQLException

Moves the cursor to the first row in this ResultSet object.

Returns:

true if the cursor is on a valid row; false if there are no rows in the result set

Throws:

SQLException - if a database access error occurs; this method is called on a closed result set or the result set type is TYPE_FORWARD_ONLY

SQLFeatureNotSupportedException - if the JDBC driver does not support this method

Since:

1.2

What's the purpose of META-INF?

You can also place static resources in there.

In example:

META-INF/resources/button.jpg 

and get them in web3.0-container via

http://localhost/myapp/button.jpg

> Read more

The /META-INF/MANIFEST.MF has a special meaning:

  1. If you run a jar using java -jar myjar.jar org.myserver.MyMainClass you can move the main class definition into the jar so you can shrink the call into java -jar myjar.jar.
  2. You can define Metainformations to packages if you use java.lang.Package.getPackage("org.myserver").getImplementationTitle().
  3. You can reference digital certificates you like to use in Applet/Webstart mode.

MySQL WHERE IN ()

you must have record in table or array record in database.

example:

SELECT * FROM tabel_record
WHERE table_record.fieldName IN (SELECT fieldName FROM table_reference);

CSS background image in :after element

A couple things

(a) you cant have both background-color and background, background will always win. in the example below, i combined them through shorthand, but this will produce the color only as a fallback method when the image does not show.

(b) no-scroll does not work, i don't believe it is a valid property of a background-image. try something like fixed:

.button:after {
    content: "";
    width: 30px;
    height: 30px;
    background:red url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") no-repeat -30px -50px fixed;
    top: 10px;
    right: 5px;
    position: absolute;
    display: inline-block;
}

I updated your jsFiddle to this and it showed the image.

Remove querystring from URL

var path = "path/to/myfile.png?foo=bar#hash";

console.log(
    path.replace(/(\?.*)|(#.*)/g, "")
);

What is the best way to tell if a character is a letter or number in Java without using regexes?

I'm looking for a function that checks only if it's one of the Latin letters or a decimal number. Since char c = 255, which in printable version is + and considered as a letter by Character.isLetter(c). This function I think is what most developers are looking for:

private static boolean isLetterOrDigit(char c) {
    return (c >= 'a' && c <= 'z') ||
           (c >= 'A' && c <= 'Z') ||
           (c >= '0' && c <= '9');
}

Where do alpha testers download Google Play Android apps?

Google play store provides closed testing track to test your application with a limited set of testers pre-defined in the tester's list known as Alpha Testing. Here are some important things to be considered to use alpha testing.

Important

After publishing an alpha/beta app for the first time, it may take a few hours for your test link to be available to testers. If you publish additional changes, they may take several hours to be available for testers

Managing Testers for Alpha Testing

Manage Testers

  1. The Screenshot is most recent as of answering this question. You can see the manage testers for closed alpha testing, You can add and remove tester one by one or you can use CSV file to bulk add and remove. The list of defined email addresses will be eligible for testing the app, here you can a control whom to provide the app for testing. Hence, this is known as Closed Testing.
  2. You can see the link(washed out by red line), once your app available to test, your testers can download and test the app by going to the below-given link. For that Google will ask once to the tester for joining the testing program. Once they have joined the program, they will receive an app update. As stated by store, it may take 24 hours to make an app available for testing.
  3. Once your app available, Your invited testers can join the test by going the link https://play.google.com/apps/testing/YOUR PACKAGE NAME

Managing App Releases

Manage Release for Alpha

  1. After the Manage testers card, there is a card for manage release, from here you can manage your alpha releases and roll-out them to production by clicking the button at the top of the card once they well tested. This process of rolling out from testing to production/public is known as stagged roll-out. In stagged roll-out, the publisher publishes by the percentage of users, to better analyze the user response.
  2. You can also manage multiple alpha release app versions from here, at the bottom of the screenshot you can see that I have once more apk build version being served as alpha test app.

Managing Closed Track Testing Availability

Alpha Country Availibility

  1. Apart from the user based control, you have one more control over the availability of the app for a test in the country. You can add limited countries tester to the app. suppose your list of the testers are from multiple countries and you want the application to be tested in your country only, rather removing testers from the testing list, you can go through Alpha Country Availability. It gives more precise control over testers.
  2. Here, In Screenshot, my app is available worldwide states that my testers (from testers list) can test the app in all countries.

Powershell: count members of a AD group

If you cannot utilize the ActiveDirectory Module or the Get-ADGroupMember cmdlet, you can do it with the LDAP "in chain"-matching rule:

$GroupDN = "CN=MyGroup,OU=Groups,DC=mydomain,DC=tld"
$LDAPFilter = "(&(objectClass=user)(objectCategory=Person)(memberOf:1.2.840.113556.1.4.1941:=$GroupDN))"

# Ideally using an instance of adsisearcher here:
Get-ADObject -LDAPFilter $LDAPFilter

See MSDN for additional LDAP matching rules implemented in Active Directory

How can I populate a select dropdown list from a JSON feed with AngularJS?

The proper way to do it is using the ng-options directive. The HTML would look like this.

<select ng-model="selectedTestAccount" 
        ng-options="item.Id as item.Name for item in testAccounts">
    <option value="">Select Account</option>
</select>

JavaScript:

angular.module('test', []).controller('DemoCtrl', function ($scope, $http) {
    $scope.selectedTestAccount = null;
    $scope.testAccounts = [];

    $http({
            method: 'GET',
            url: '/Admin/GetTestAccounts',
            data: { applicationId: 3 }
        }).success(function (result) {
        $scope.testAccounts = result;
    });
});

You'll also need to ensure angular is run on your html and that your module is loaded.

<html ng-app="test">
    <body ng-controller="DemoCtrl">
    ....
    </body>
</html>

Convert np.array of type float64 to type uint8 scaling values

Considering that you are using OpenCV, the best way to convert between data types is to use normalize function.

img_n = cv2.normalize(src=img, dst=None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)

However, if you don't want to use OpenCV, you can do this in numpy

def convert(img, target_type_min, target_type_max, target_type):
    imin = img.min()
    imax = img.max()

    a = (target_type_max - target_type_min) / (imax - imin)
    b = target_type_max - a * imax
    new_img = (a * img + b).astype(target_type)
    return new_img

And then use it like this

imgu8 = convert(img16u, 0, 255, np.uint8)

This is based on the answer that I found on crossvalidated board in comments under this solution https://stats.stackexchange.com/a/70808/277040

What are public, private and protected in object oriented programming?

All the three are access modifiers and keywords which are used in a class. Anything declared in public can be used by any object within the class or outside the class,variables in private can only be used by the objects within the class and could not be changed through direct access(as it can change through functions like friend function).Anything defined under protected section can be used by the class and their just derived class.

How do I run a Java program from the command line on Windows?

On Windows 7 I had to do the following:

quick way

  1. Install JDK http://www.oracle.com/technetwork/java/javase/downloads
  2. in windows, browse into "C:\Program Files\Java\jdk1.8.0_91\bin" (or wherever the latest version of JDK is installed), hold down shift and right click on a blank area within the window and do "open command window here" and this will give you a command line and access to all the BIN tools. "javac" is not by default in the windows system PATH environment variable.
  3. Follow comments above about how to compile the file ("javac MyFile.java" then "java MyFile") https://stackoverflow.com/a/33149828/194872

long way

  1. Install JDK http://www.oracle.com/technetwork/java/javase/downloads/index.html
  2. After installing, in edits the Windows PATH environment variable and adds the following to the path C:\ProgramData\Oracle\Java\javapath. Within this folder are symbolic links to a handful of java executables but "javac" is NOT one of them so when trying to run "javac" from Windows command line it throws an error.
  3. I edited the path: Control Panel -> System -> Advanced tab -> "Environment Variables..." button -> scroll down to "Path", highlight and edit -> replaced the "C:\ProgramData\Oracle\Java\javapath" with a direct path to the java BIN folder "C:\Program Files\Java\jdk1.8.0_91\bin".
  4. This likely breaks when you upgrade your JDK installation but you have access to all the command line tools now.

  5. Follow comments above about how to compile the file ("javac MyFile.java" then "java MyFile") https://stackoverflow.com/a/33149828/194872

Running Jupyter via command line on Windows

In Windows 10 you can use ipython notebook. It works for me.

How to Convert Datetime to Date in dd/MM/yyyy format

Give a different alias

SELECT  Convert(varchar,A.InsertDate,103) as converted_Tran_Date from table as A
order by A.InsertDate 

Merge r brings error "'by' must specify uniquely valid columns"

Rather give names of the column on which you want to merge:

exporttab <- merge(x=dwd_nogap, y=dwd_gap, by.x='x1', by.y='x2', fill=-9999)

How to add lines to end of file on Linux

The easiest way is to redirect the output of the echo by >>:

echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile

Html attributes for EditorFor() in ASP.NET MVC

Just create your own template for the type in Views/Shared/EditorTemplates/MyTypeEditor.vbhtml

@ModelType MyType

@ModelType MyType
@Code
    Dim name As String = ViewData("ControlId")
    If String.IsNullOrEmpty(name) Then
        name = "MyTypeEditor"
    End If
End Code

' Mark-up for MyType Editor
@Html.TextBox(name, Model, New With {.style = "width:65px;background-color:yellow"})

Invoke editor from your view with the model property:

@Html.EditorFor(Function(m) m.MyTypeProperty, "MyTypeEditor", New {.ControlId = "uniqueId"})

Pardon the VB syntax. That's just how we roll.

XPath contains(text(),'some string') doesn't work when used with node with more than one Text subnode

It took me a little while but finally figured out. Custom xpath that contains some text below worked perfectly for me.

//a[contains(text(),'JB-')]

Nested iframes, AKA Iframe Inception

var iframeInner = jQuery(iframe).find('iframe').contents();

var iframeContent = jQuery(iframeInner).contents().find('#element');

iframeInner contains elements from

<div id="element">other markup goes here</div> 

and iframeContent will find for elements which are inside of

 <div id="element">other markup goes here</div> 

(find doesn't search on current element) that's why it is returning null.

Calling a class method raises a TypeError in Python

Try this:

class mystuff:
    def average(_,a,b,c): #get the average of three numbers
            result=a+b+c
            result=result/3
            return result

#now use the function average from the mystuff class
print mystuff.average(9,18,27)

or this:

class mystuff:
    def average(self,a,b,c): #get the average of three numbers
            result=a+b+c
            result=result/3
            return result

#now use the function average from the mystuff class
print mystuff.average(9,18,27)

Override devise registrations controller

I believe there is a better solution than rewrite the RegistrationsController. I did exactly the same thing (I just have Organization instead of Company).

If you set properly your nested form, at model and view level, everything works like a charm.

My User model:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable, :lockable and :timeoutable
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

  has_many :owned_organizations, :class_name => 'Organization', :foreign_key => :owner_id

  has_many :organization_memberships
  has_many :organizations, :through => :organization_memberships

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me, :name, :username, :owned_organizations_attributes

  accepts_nested_attributes_for :owned_organizations
  ...
end

My Organization Model:

class Organization < ActiveRecord::Base
  belongs_to :owner, :class_name => 'User'
  has_many :organization_memberships
  has_many :users, :through => :organization_memberships
  has_many :contracts

  attr_accessor :plan_name

  after_create :set_owner_membership, :set_contract
  ...
end

My view : 'devise/registrations/new.html.erb'

<h2>Sign up</h2>

<% resource.owned_organizations.build if resource.owned_organizations.empty? %>
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>

  <p><%= f.label :name %><br />
    <%= f.text_field :name %></p>

  <p><%= f.label :email %><br />
    <%= f.text_field :email %></p>

  <p><%= f.label :username %><br />
    <%= f.text_field :username %></p>

  <p><%= f.label :password %><br />
    <%= f.password_field :password %></p>

  <p><%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation %></p>

  <%= f.fields_for :owned_organizations do |organization_form| %>

    <p><%= organization_form.label :name %><br />
      <%= organization_form.text_field :name %></p>

    <p><%= organization_form.label :subdomain %><br />
      <%= organization_form.text_field :subdomain %></p>

    <%= organization_form.hidden_field :plan_name, :value => params[:plan] %>

  <% end %>

  <p><%= f.submit "Sign up" %></p>
<% end %>

<%= render :partial => "devise/shared/links" %>

Magento addFieldToFilter: Two fields, match as OR, not AND

Thanks Anda, your post has been a great help!! However the OR sentence didnt' quite work for me and I was getting an error: getCollection() "invalid argument supplied for foreach".

So this is what I ended with (notice the attribute being specified 3 times instead of 2 in this case):

  $collection->addFieldToFilter('attribute', array(  
    array('attribute'=>'my_field1','eq'=>'my_value1'),            
    array('attribute'=>'my_field2','eq'=>'my_value2') ));

addFieldToFilter first requires a field and then condition -> link.

Select from one table where not in another

Expanding on Sjoerd's anti-join, you can also use the easy to understand SELECT WHERE X NOT IN (SELECT) pattern.

SELECT pm.id FROM r2r.partmaster pm
WHERE pm.id NOT IN (SELECT pd.part_num FROM wpsapi4.product_details pd)

Note that you only need to use ` backticks on reserved words, names with spaces and such, not with normal column names.

On MySQL 5+ this kind of query runs pretty fast.
On MySQL 3/4 it's slow.

Make sure you have indexes on the fields in question
You need to have an index on pm.id, pd.part_num.

Get a file name from a path

The task is fairly simple as the base filename is just the part of the string starting at the last delimeter for folders:

std::string base_filename = path.substr(path.find_last_of("/\\") + 1)

If the extension is to be removed as well the only thing to do is find the last . and take a substr to this point

std::string::size_type const p(base_filename.find_last_of('.'));
std::string file_without_extension = base_filename.substr(0, p);

Perhaps there should be a check to cope with files solely consisting of extensions (ie .bashrc...)

If you split this up into seperate functions you're flexible to reuse the single tasks:

template<class T>
T base_name(T const & path, T const & delims = "/\\")
{
  return path.substr(path.find_last_of(delims) + 1);
}
template<class T>
T remove_extension(T const & filename)
{
  typename T::size_type const p(filename.find_last_of('.'));
  return p > 0 && p != T::npos ? filename.substr(0, p) : filename;
}

The code is templated to be able to use it with different std::basic_string instances (i.e. std::string & std::wstring...)

The downside of the templation is the requirement to specify the template parameter if a const char * is passed to the functions.

So you could either:

A) Use only std::string instead of templating the code

std::string base_name(std::string const & path)
{
  return path.substr(path.find_last_of("/\\") + 1);
}

B) Provide wrapping function using std::string (as intermediates which will likely be inlined / optimized away)

inline std::string string_base_name(std::string const & path)
{
  return base_name(path);
}

C) Specify the template parameter when calling with const char *.

std::string base = base_name<std::string>("some/path/file.ext");

Result

std::string filepath = "C:\\MyDirectory\\MyFile.bat";
std::cout << remove_extension(base_name(filepath)) << std::endl;

Prints

MyFile

How to make a machine trust a self-signed Java application

I had the same problem, but i solved it from Java Control Panel-->Security-->SecurityLevel:MEDIUM. Just so, no Manage certificates, imports ,exports etc..

How to disable gradle 'offline mode' in android studio?

Edit. As noted in the comments, this is no longer working with the latest Android Studio releases.

The latest Android studio seems to only reference to "Offline mode" via the keymap, but toggling this does not seem to change anything anymore.


In Android Studio open the settings and search for offline it will find the Gradle category which contains Offline work. You can disable it there.

Gradle Offline work

The character encoding of the HTML document was not declared

I have same problem with the most basic situation and my problem was solved with inserting this meta in the head:

<meta charset="UTF-8">

the character encoding (which is actually UTF-8) of the html document was not declared

My docker container has no internet

If you're on OSX, you might need to restart your machine after installing Docker. This has been an issue at times.

Fix columns in horizontal scrolling

Demo: http://www.jqueryscript.net/demo/jQuery-Plugin-For-Fixed-Table-Header-Footer-Columns-TableHeadFixer/

HTML

<h2>TableHeadFixer Fix Left Column</h2>

<div id="parent">
    <table id="fixTable" class="table">
        <thead>
            <tr>
                <th>Ano</th>
                <th>Jan</th>
                <th>Fev</th>
                <th>Mar</th>
                <th>Abr</th>
                <th>Maio</th>
                <th>Total</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
        </tbody>
    </table>
</div>

JS

    $(document).ready(function() {
        $("#fixTable").tableHeadFixer({"head" : false, "right" : 1}); 
    });

CSS

    #parent {
        height: 300px;
    }

    #fixTable {
        width: 1800px !important;
    }

https://jsfiddle.net/5gfuqqc4/

access key and value of object using *ngFor

As in latest release of Angular (v6.1.0) , Angular Team has added new built in pipe for the same named as keyvalue pipe to help you iterate through objects, maps, and arrays, in the common module of angular package. For example -

<div *ngFor="let item of testObject | keyvalue">
    Key: <b>{{item.key}}</b> and Value: <b>{{item.value}}</b>
</div>

Working Forked Example

check it out here for more useful information -

If you are using Angular v5 or below or you want to achieve using pipe follow this answer

Swift GET request with parameters

Swift 3:

extension URL {
    func getQueryItemValueForKey(key: String) -> String? {
        guard let components = NSURLComponents(url: self, resolvingAgainstBaseURL: false) else {
              return nil
        }

        guard let queryItems = components.queryItems else { return nil }
     return queryItems.filter {
                 $0.name.lowercased() == key.lowercased()
                 }.first?.value
    }
}

I used it to get the image name for UIImagePickerController in func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]):

var originalFilename = ""
if let url = info[UIImagePickerControllerReferenceURL] as? URL, let imageIdentifier = url.getQueryItemValueForKey(key: "id") {
    originalFilename = imageIdentifier + ".png"
    print("file name : \(originalFilename)")
}

How can I select records ONLY from yesterday?

to_char(tran_date, 'yyyy-mm-dd') = to_char(sysdate-1, 'yyyy-mm-dd')

How to kill MySQL connections

mysql> SHOW PROCESSLIST;
+-----+------+-----------------+------+---------+------+-------+---------------+
| Id  | User | Host            | db   | Command | Time | State | Info      |
+-----+------+-----------------+------+---------+------+-------+----------------+
| 143 | root | localhost:61179 | cds  | Query   |    0 | init  | SHOW PROCESSLIST |
| 192 | root | localhost:53793 | cds  | Sleep   |    4 |       | NULL      |
+-----+------+-----------------+------+---------+------+-------+----------------+
2 rows in set (0.00 sec)

mysql> KILL 192;
Query OK, 0 rows affected (0.00 sec)

USER 192 :

mysql> SELECT * FROM exept;
+----+
| id |
+----+
|  1 |
+----+
1 row in set (0.00 sec)

mysql> SELECT * FROM exept;
ERROR 2013 (HY000): Lost connection to MySQL server during query

Swing vs JavaFx for desktop applications

I'd look around to find some (3rd party?) components that do what you want. I've had to create custom Swing components for an agenda view where you can book multiple resources, as well as an Excel-like grid that works well with keyboard navigation and so on. I had a terrible time getting them to work nicely because I needed to delve into many of Swing's many intricacies whenever I came upon a problem. Mouse and focus behaviour and a lot of other things can be very difficult to get right, especially for a casual Swing user. I would hope that JavaFX is a bit more future-orientated and smooth out of the box.

Why do I get an error instantiating an interface?

You cannot instantiate an abstract class or interface. You must inherit it, if its an abstract class, or implement it if it's an interface. e.g.

...
private class User : IUser
{
  ...
}

User u = new User();

Regular expression [Any number]

var mask = /^\d+$/;
if ( myString.exec(mask) ){
   /* That's a number */
}

How to recursively find the latest modified file in a directory?

Instead of sorting the results and keeping only the last modified ones, you could use awk to print only the one with greatest modification time (in unix time):

find . -type f -printf "%T@\0%p\0" | awk '
    {
        if ($0>max) {
            max=$0; 
            getline mostrecent
        } else 
            getline
    } 
    END{print mostrecent}' RS='\0'

This should be a faster way to solve your problem if the number of files is big enough.

I have used the NUL character (i.e. '\0') because, theoretically, a filename may contain any character (including space and newline) but that.

If you don't have such pathological filenames in your system you can use the newline character as well:

find . -type f -printf "%T@\n%p\n" | awk '
    {
        if ($0>max) {
            max=$0; 
            getline mostrecent
        } else 
            getline
    } 
    END{print mostrecent}' RS='\n'

In addition, this works in mawk too.

Loop through columns and add string lengths as new columns

You need to use [[, the programmatic equivalent of $. Otherwise, for example, when i is col1, R will look for df$i instead of df$col1.

for(i in names(df)){
  df[[paste(i, 'length', sep="_")]] <- str_length(df[[i]])
}

Difference between object and class in Scala

Scala class same as Java Class but scala not gives you any entry method in class, like main method in java. The main method associated with object keyword. You can think of the object keyword as creating a singleton object of a class that is defined implicitly.

more information check this article class and object keyword in scala programming

JSTL if tag for equal strings

<c:if test="${ansokanInfo.pSystem eq 'NAT'}">

How to get name of calling function/method in PHP?

For me debug_backtrace was hitting my memory limit, and I wanted to use this in production to log and email errors as they happen.

Instead I found this solution which works brilliantly!

// Make a new exception at the point you want to trace, and trace it!
$e = new Exception;
var_dump($e->getTraceAsString());

// Outputs the following 
#2 /usr/share/php/PHPUnit/Framework/TestCase.php(626): SeriesHelperTest->setUp()
#3 /usr/share/php/PHPUnit/Framework/TestResult.php(666): PHPUnit_Framework_TestCase->runBare()
#4 /usr/share/php/PHPUnit/Framework/TestCase.php(576): PHPUnit_Framework_TestResult->run(Object(SeriesHelperTest))
#5 /usr/share/php/PHPUnit/Framework/TestSuite.php(757): PHPUnit_Framework_TestCase->run(Object(PHPUnit_Framework_TestResult))
#6 /usr/share/php/PHPUnit/Framework/TestSuite.php(733): PHPUnit_Framework_TestSuite->runTest(Object(SeriesHelperTest), Object(PHPUnit_Framework_TestResult))
#7 /usr/share/php/PHPUnit/TextUI/TestRunner.php(305): PHPUnit_Framework_TestSuite->run(Object(PHPUnit_Framework_TestResult), false, Array, Array, false)
#8 /usr/share/php/PHPUnit/TextUI/Command.php(188): PHPUnit_TextUI_TestRunner->doRun(Object(PHPUnit_Framework_TestSuite), Array)
#9 /usr/share/php/PHPUnit/TextUI/Command.php(129): PHPUnit_TextUI_Command->run(Array, true)
#10 /usr/bin/phpunit(53): PHPUnit_TextUI_Command::main()
#11 {main}"

Undoing accidental git stash pop

From git stash --help

Recovering stashes that were cleared/dropped erroneously
   If you mistakenly drop or clear stashes, they cannot be recovered through the normal safety mechanisms. However, you can try the
   following incantation to get a list of stashes that are still in your repository, but not reachable any more:

       git fsck --unreachable |
       grep commit | cut -d\  -f3 |
       xargs git log --merges --no-walk --grep=WIP

This helped me better than the accepted answer with the same scenario.

How to obfuscate Python code effectively?

so that it isn't human-readable?

i mean all the file is encoded !! when you open it you can't understand anything .. ! that what i want

As maximum, you can compile your sources into bytecode and then distribute only bytecode. But even this is reversible. Bytecode can be decompiled into semi-readable sources.

Base64 is trivial to decode for anyone, so it cannot serve as actual protection and will 'hide' sources only from complete PC illiterates. Moreover, if you plan to actually run that code by any means, you would have to include decoder right into the script (or another script in your distribution, which would needed to be run by legitimate user), and that would immediately give away your encoding/encryption.

Obfuscation techniques usually involve comments/docs stripping, name mangling, trash code insertion, and so on, so even if you decompile bytecode, you get not very readable sources. But they will be Python sources nevertheless and Python is not good at becoming unreadable mess.

If you absolutely need to protect some functionality, I'd suggest going with compiled languages, like C or C++, compiling and distributing .so/.dll, and then using Python bindings to protected code.

What is the difference between HTTP_HOST and SERVER_NAME in PHP?

It took me a while to understand what people meant by 'SERVER_NAME is more reliable'. I use a shared server and does not have access to virtual host directives. So, I use mod_rewrite in .htaccess to map different HTTP_HOSTs to different directories. In that case, it is HTTP_HOST that is meaningful.

The situation is similar if one uses name-based virtual hosts: the ServerName directive within a virtual host simply says which hostname will be mapped to this virtual host. The bottom line is that, in both cases, the hostname provided by the client during the request (HTTP_HOST), must be matched with a name within the server, which is itself mapped to a directory. Whether the mapping is done with virtual host directives or with htaccess mod_rewrite rules is secondary here. In these cases, HTTP_HOST will be the same as SERVER_NAME. I am glad that Apache is configured that way.

However, the situation is different with IP-based virtual hosts. In this case and only in this case, SERVER_NAME and HTTP_HOST can be different, because now the client selects the server by the IP, not by the name. Indeed, there might be special configurations where this is important.

So, starting from now, I will use SERVER_NAME, just in case my code is ported in these special configurations.

HTTP Status 405 - Method Not Allowed Error for Rest API

Add

@Produces({"image/jpeg,image/png"})

to

@POST
@Path("/pdf")
@Consumes({ MediaType.MULTIPART_FORM_DATA })
@Produces({"image/jpeg,image/png"})
//@Produces("text/plain")
public Response uploadPdfFile(@FormDataParam("file") InputStream fileInputStream,@FormDataParam("file") FormDataContentDisposition fileMetaData) throws Exception {
    ...
}

VBA Excel Provide current Date in Text box

Set the value from code on showing the form, not in the design-timeProperties for the text box.

Private Sub UserForm_Activate()
    Me.txtDate.Value = Format(Date, "mm/dd/yy")
End Sub

ActiveRecord OR query

in Rails 3, it should be

Model.where("column = ? or other_column = ?", value, other_value)

This also includes raw sql but I dont think there is a way in ActiveRecord to do OR operation. Your question is not a noob question.

How to make a DIV always float on the screen in top right corner?

Use position:fixed, as previously stated, IE6 doesn't recognize position:fixed, but with some css magic you can get IE6 to behave:

html, body {
    height: 100%;
    overflow:auto;
}
body #fixedElement {
    position:fixed !important;
    position: absolute; /*ie6 */
    bottom: 0;
}

The !important flag makes it so you don't have to use a conditional comment for IE. This will have #fixedElement use position:fixed in all browsers but IE, and in IE, position:absolute will take effect with bottom:0. This will simulate position:fixed for IE6

How can I generate an MD5 hash?

import java.security.MessageDigest

val digest = MessageDigest.getInstance("MD5")

//Quick MD5 of text
val text = "MD5 this text!"
val md5hash1 = digest.digest(text.getBytes).map("%02x".format(_)).mkString

//MD5 of text with updates
digest.update("MD5 ".getBytes())
digest.update("this ".getBytes())
digest.update("text!".getBytes())
val md5hash2 = digest.digest().map(0xFF & _).map("%02x".format(_)).mkString

//Output
println(md5hash1 + " should be the same as " + md5hash2)

How to change Tkinter Button state from disabled to normal?

I think a quick way to change the options of a widget is using the configure method.

In your case, it would look like this:

self.x.configure(state=NORMAL)

How do I iterate over an NSArray?

Here is how you declare an array of strings and iterate over them:

NSArray *langs = @[@"es", @"en", @"pt", @"it", @"fr"];

for (int i = 0; i < [langs count]; i++) {
  NSString *lang = (NSString*) [langs objectAtIndex:i];
  NSLog(@"%@, ",lang);
}

How can I use Oracle SQL developer to run stored procedures?

Not only is there a way to do this, there is more than one way to do this (which I concede is not very Pythonic, but then SQL*Developer is written in Java ).

I have a procedure with this signature: get_maxsal_by_dept( dno number, maxsal out number).

I highlight it in the SQL*Developer Object Navigator, invoke the right-click menu and chose Run. (I could use ctrl+F11.) This spawns a pop-up window with a test harness. (Note: If the stored procedure lives in a package, you'll need to right-click the package, not the icon below the package containing the procedure's name; you will then select the sproc from the package's "Target" list when the test harness appears.) In this example, the test harness will display the following:

DECLARE
  DNO NUMBER;
  MAXSAL NUMBER;
BEGIN
  DNO := NULL;

  GET_MAXSAL_BY_DEPT(
    DNO => DNO,
    MAXSAL => MAXSAL
  );
  DBMS_OUTPUT.PUT_LINE('MAXSAL = ' || MAXSAL);
END;

I set the variable DNO to 50 and press okay. In the Running - Log pane (bottom right-hand corner unless you've closed/moved/hidden it) I can see the following output:

Connecting to the database apc.
MAXSAL = 4500
Process exited.
Disconnecting from the database apc. 

To be fair the runner is less friendly for functions which return a Ref Cursor, like this one: get_emps_by_dept (dno number) return sys_refcursor.

DECLARE
  DNO NUMBER;
  v_Return sys_refcursor;
BEGIN
  DNO := 50;

  v_Return := GET_EMPS_BY_DEPT(
    DNO => DNO
  );
  -- Modify the code to output the variable
  -- DBMS_OUTPUT.PUT_LINE('v_Return = ' || v_Return);
END;

However, at least it offers the chance to save any changes to file, so we can retain our investment in tweaking the harness...

DECLARE
  DNO NUMBER;
  v_Return sys_refcursor;
  v_rec emp%rowtype;
BEGIN
  DNO := 50;

  v_Return := GET_EMPS_BY_DEPT(
    DNO => DNO
  );

  loop
    fetch v_Return into v_rec;
    exit when v_Return%notfound;
    DBMS_OUTPUT.PUT_LINE('name = ' || v_rec.ename);
  end loop;
END;

The output from the same location:

Connecting to the database apc.
name = TRICHLER
name = VERREYNNE
name = FEUERSTEIN
name = PODER
Process exited.
Disconnecting from the database apc. 

Alternatively we can use the old SQLPLus commands in the SQLDeveloper worksheet:

var rc refcursor 
exec :rc := get_emps_by_dept(30) 
print rc

In that case the output appears in Script Output pane (default location is the tab to the right of the Results tab).

The very earliest versions of the IDE did not support much in the way of SQL*Plus. However, all of the above commands have been supported since 1.2.1. Refer to the matrix in the online documentation for more info.


"When I type just var rc refcursor; and select it and run it, I get this error (GUI):"

There is a feature - or a bug - in the way the worksheet interprets SQLPlus commands. It presumes SQLPlus commands are part of a script. So, if we enter a line of SQL*Plus, say var rc refcursor and click Execute Statement (or F9 ) the worksheet hurls ORA-900 because that is not an executable statement i.e. it's not SQL . What we need to do is click Run Script (or F5 ), even for a single line of SQL*Plus.


"I am so close ... please help."

You program is a procedure with a signature of five mandatory parameters. You are getting an error because you are calling it as a function, and with just the one parameter:

exec :rc := get_account(1)

What you need is something like the following. I have used the named notation for clarity.

var ret1 number
var tran_cnt number
var msg_cnt number
var rc refcursor

exec :tran_cnt := 0
exec :msg_cnt := 123

exec get_account (Vret_val => :ret1, 
                  Vtran_count => :tran_cnt, 
                  Vmessage_count => :msg_cnt, 
                  Vaccount_id   => 1,
                  rc1 => :rc )

print tran_count 
print rc

That is, you need a variable for each OUT or IN OUT parameter. IN parameters can be passed as literals. The first two EXEC statements assign values to a couple of the IN OUT parameters. The third EXEC calls the procedure. Procedures don't return a value (unlike functions) so we don't use an assignment syntax. Lastly this script displays the value of a couple of the variables mapped to OUT parameters.

Convert pandas Series to DataFrame

Rather than create 2 temporary dfs you can just pass these as params within a dict using the DataFrame constructor:

pd.DataFrame({'email':sf.index, 'list':sf.values})

There are lots of ways to construct a df, see the docs

Angular redirect to login page

Usage with the final router

With the introduction of the new router it became easier to guard the routes. You must define a guard, which acts as a service, and add it to the route.

import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';
import { UserService } from '../../auth';

@Injectable()
export class LoggedInGuard implements CanActivate {
  constructor(user: UserService) {
    this._user = user;
  }

  canActivate() {
    return this._user.isLoggedIn();
  }
}

Now pass the LoggedInGuard to the route and also add it to the providers array of the module.

import { LoginComponent } from './components/login.component';
import { HomeComponent } from './components/home.component';
import { LoggedInGuard } from './guards/loggedin.guard';

const routes = [
    { path: '', component: HomeComponent, canActivate: [LoggedInGuard] },
    { path: 'login', component: LoginComponent },
];

The module declaration:

@NgModule({
  declarations: [AppComponent, HomeComponent, LoginComponent]
  imports: [HttpModule, BrowserModule, RouterModule.forRoot(routes)],
  providers: [UserService, LoggedInGuard],
  bootstrap: [AppComponent]
})
class AppModule {}

Detailed blog post about how it works with the final release: https://medium.com/@blacksonic86/angular-2-authentication-revisited-611bf7373bf9

Usage with the deprecated router

A more robust solution is to extend the RouterOutlet and when activating a route check if the user is logged in. This way you don't have to copy and paste your directive to every component. Plus redirecting based on a subcomponent can be misleading.

@Directive({
  selector: 'router-outlet'
})
export class LoggedInRouterOutlet extends RouterOutlet {
  publicRoutes: Array;
  private parentRouter: Router;
  private userService: UserService;

  constructor(
    _elementRef: ElementRef, _loader: DynamicComponentLoader,
    _parentRouter: Router, @Attribute('name') nameAttr: string,
    userService: UserService
  ) {
    super(_elementRef, _loader, _parentRouter, nameAttr);

    this.parentRouter = _parentRouter;
    this.userService = userService;
    this.publicRoutes = [
      '', 'login', 'signup'
    ];
  }

  activate(instruction: ComponentInstruction) {
    if (this._canActivate(instruction.urlPath)) {
      return super.activate(instruction);
    }

    this.parentRouter.navigate(['Login']);
  }

  _canActivate(url) {
    return this.publicRoutes.indexOf(url) !== -1 || this.userService.isLoggedIn()
  }
}

The UserService stands for the place where your business logic resides whether the user is logged in or not. You can add it easily with DI in the constructor.

When the user navigates to a new url on your website, the activate method is called with the current Instruction. From it you can grab the url and decide whether it is allowed or not. If not just redirect to the login page.

One last thing remain to make it work, is to pass it to our main component instead of the built in one.

@Component({
  selector: 'app',
  directives: [LoggedInRouterOutlet],
  template: template
})
@RouteConfig(...)
export class AppComponent { }

This solution can not be used with the @CanActive lifecycle decorator, because if the function passed to it resolves false, the activate method of the RouterOutlet won't be called.

Also wrote a detailed blog post about it: https://medium.com/@blacksonic86/authentication-in-angular-2-958052c64492

Remove a JSON attribute

The selected answer would work for as long as you know the key itself that you want to delete but if it should be truly dynamic you would need to use the [] notation instead of the dot notation.

For example:

var keyToDelete = "key1";
var myObj = {"test": {"key1": "value", "key2": "value"}}

//that will not work.
delete myObj.test.keyToDelete 

instead you would need to use:

delete myObj.test[keyToDelete];

Substitute the dot notation with [] notation for those values that you want evaluated before being deleted.

How to use ConcurrentLinkedQueue?

This is probably what you're looking for in terms of thread safety & "prettyness" when trying to consume everything in the queue:

for (YourObject obj = queue.poll(); obj != null; obj = queue.poll()) {
}

This will guarantee that you quit when the queue is empty, and that you continue to pop objects off of it as long as it's not empty.

javascript cell number validation

Verify this code : It works on change of phone number field in ms crm 2016 form .

function validatePhoneNumber() {

    var mob = Xrm.Page.getAttribute("gen_phone").getValue();
    var length = mob.length;
    if (length < 10 || length > 10) {
        alert("Please Enter 10 Digit Number:");
        Xrm.Page.getAttribute("gen_phone").setValue(null);
        return true;
    }
    if (mob > 31 && (mob < 48 || mob > 57)) {} else {
        alert("Please Enter 10 Digit Number:");
        Xrm.Page.getAttribute("gen_phone").setValue(null);
        return true;
    }
}

Metadata file '.dll' could not be found

For me the problem was an error that didn't come up in the build output, namely I had two utility classes that were in different namespaces initially. I changed the namespace of the second one to match the first one's (without knowing there was another one utility class in the first one), and that's when this error started to come up.

I imagine the build output error surfaced, because the Logic Layer library DLL file could not be built, and the main application couldn't find it.

The solution was to change back the second utility class to a different namespace and that's when the real build errors started to pour in. After sorting them out the build went through just fine.

As an overview, if any of the previous solutions doesn't work for you, you might have suppressed errors in the code that Visual Studio is not showing, so try to retrack your coding steps and check for any irregularities.

PS: This was in Visual Studio 2015 Community Edition

How to save and extract session data in codeigniter

In codeigniter we are able to store session values in a database. In the config.php file make the sess_use_database variable true

$config['sess_use_database'] = TRUE;
$config['sess_table_name'] = 'ci_sessions';

and create a ci_session table in the database

CREATE TABLE IF NOT EXISTS  `ci_sessions` (
    session_id varchar(40) DEFAULT '0' NOT NULL,
    ip_address varchar(45) DEFAULT '0' NOT NULL,
    user_agent varchar(120) NOT NULL,
    last_activity int(10) unsigned DEFAULT 0 NOT NULL,
    user_data text NOT NULL,
    PRIMARY KEY (session_id),
    KEY `last_activity_idx` (`last_activity`)
);

For more details and reference, click here

Access IP Camera in Python OpenCV

Getting the correct URL for your camera seems to be the actual challenge! I'm putting my working URL here, it might help someone. The camera is EZVIZ C1C with exact model cs-c1c-d0-1d2wf. The working URL is

rtsp://admin:[email protected]/h264_stream

where SZGBZT is the verification code found at the bottom of the camera. admin is always admin regardless of any settings or users you have.

The final code will be

video_capture = cv2.VideoCapture('rtsp://admin:[email protected]/h264_stream')

Is it possible to use pip to install a package from a private GitHub repository?

You can do it directly with the HTTPS URL like this:

pip install git+https://github.com/username/repo.git

This also works just appending that line in the requirements.txt in a Django project, for instance.

How to get the index of a maximum element in a NumPy array along one axis

argmax() will only return the first occurrence for each row. http://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html

If you ever need to do this for a shaped array, this works better than unravel:

import numpy as np
a = np.array([[1,2,3], [4,3,1]])  # Can be of any shape
indices = np.where(a == a.max())

You can also change your conditions:

indices = np.where(a >= 1.5)

The above gives you results in the form that you asked for. Alternatively, you can convert to a list of x,y coordinates by:

x_y_coords =  zip(indices[0], indices[1])

mysql query: SELECT DISTINCT column1, GROUP BY column2

Somehow your requirement sounds a bit contradictory ..

group by name (which is basically a distinct on name plus readiness to aggregate) and then a distinct on IP

What do you think should happen if two people (names) worked from the same IP within the time period specified?


Did you try this?

SELECT name, COUNT(name), time, price, ip, SUM(price) 
  FROM tablename 
 WHERE time >= $yesterday AND time <$today 
GROUP BY name,ip

PHP7 : install ext-dom issue

simply run

sudo apt install php-xml

its worked for me

Basic Ajax send/receive with node.js

I was facing following error with code (nodejs 0.10.13), provided by ampersand:

origin is not allowed by access-control-allow-origin

Issue was resolved changing

response.writeHead(200, {"Content-Type": "text/plain"});

to

response.writeHead(200, {
                 'Content-Type': 'text/html',
                 'Access-Control-Allow-Origin' : '*'});

Why is the <center> tag deprecated in HTML?

What I do is take common tasks like centering or floating and make CSS classes out of them. When I do that I can use them throughout any of the pages. I can also call as many as I want on the same element.

.text_center {text-align: center;}
.center {margin: auto 0px;}
.float_left {float: left;}

Now I can use them in my HTML code to perform simple tasks.

<p class="text_center">Some Text</p>

How do I use cx_freeze?

  • Add import sys as the new topline
  • You misspelled "executables" on the last line.
  • Remove script = on last line.

The code should now look like:

import sys
from cx_Freeze import setup, Executable

setup(
    name = "On Dijkstra's Algorithm",
    version = "3.1",
    description = "A Dijkstra's Algorithm help tool.",
    executables = [Executable("Main.py", base = "Win32GUI")])

Use the command prompt (cmd) to run python setup.py build. (Run this command from the folder containing setup.py.) Notice the build parameter we added at the end of the script call.

Flask Download a File

You need to make sure that the value you pass to the directory argument is an absolute path, corrected for the current location of your application.

The best way to do this is to configure UPLOAD_FOLDER as a relative path (no leading slash), then make it absolute by prepending current_app.root_path:

@app.route('/uploads/<path:filename>', methods=['GET', 'POST'])
def download(filename):
    uploads = os.path.join(current_app.root_path, app.config['UPLOAD_FOLDER'])
    return send_from_directory(directory=uploads, filename=filename)

It is important to reiterate that UPLOAD_FOLDER must be relative for this to work, e.g. not start with a /.

A relative path could work but relies too much on the current working directory being set to the place where your Flask code lives. This may not always be the case.

SQL Server : converting varchar to INT

This question has got 91,000 views so perhaps many people are looking for a more generic solution to the issue in the title "error converting varchar to INT"

If you are on SQL Server 2012+ one way of handling this invalid data is to use TRY_CAST

SELECT TRY_CAST (userID AS INT)
FROM   audit 

On previous versions you could use

SELECT CASE
         WHEN ISNUMERIC(RTRIM(userID) + '.0e0') = 1
              AND LEN(userID) <= 11
           THEN CAST(userID AS INT)
       END
FROM   audit 

Both return NULL if the value cannot be cast.

In the specific case that you have in your question with known bad values I would use the following however.

CAST(REPLACE(userID COLLATE Latin1_General_Bin, CHAR(0),'') AS INT)

Trying to replace the null character is often problematic except if using a binary collation.

Serializing PHP object to JSON

I spent some hours on the same problem. My object to convert contains many others whose definitions I'm not supposed to touch (API), so I've came up with a solution which could be slow I guess, but I'm using it for development purposes.

This one converts any object to array

function objToArr($o) {
$s = '<?php
class base {
    public static function __set_state($array) {
        return $array;
    }
}
function __autoload($class) {
    eval("class $class extends base {}");
}
$a = '.var_export($o,true).';
var_export($a);
';
$f = './tmp_'.uniqid().'.php';
file_put_contents($f,$s);
chmod($f,0755);
$r = eval('return '.shell_exec('php -f '.$f).';');
unlink($f);
return $r;
}

This converts any object to stdClass

class base {
    public static function __set_state($array) {
        return (object)$array;
    }
}
function objToStd($o) {
$s = '<?php
class base {
    public static function __set_state($array) {
        $o = new self;
        foreach($array as $k => $v) $o->$k = $v;
        return $o;
    }
}
function __autoload($class) {
    eval("class $class extends base {}");
}
$a = '.var_export($o,true).';
var_export($a);
';
$f = './tmp_'.uniqid().'.php';
file_put_contents($f,$s);
chmod($f,0755);
$r = eval('return '.shell_exec('php -f '.$f).';');
unlink($f);
return $r;
}

HTML5 Canvas and Anti-aliasing

If you need pixel level control over canvas you can do using createImageData and putImageData.

HTML:

<canvas id="qrCode" width="200", height="200">
  QR Code
</canvas>

And JavaScript:

function setPixel(imageData, pixelData) {
  var index = (pixelData.x + pixelData.y * imageData.width) * 4;
    imageData.data[index+0] = pixelData.r;
    imageData.data[index+1] = pixelData.g;
    imageData.data[index+2] = pixelData.b;
    imageData.data[index+3] = pixelData.a;
}

element = document.getElementById("qrCode");
c = element.getContext("2d");

pixcelSize = 4;
width = element.width;
height = element.height;


imageData = c.createImageData(width, height);

for (i = 0; i < 1000; i++) {
  x = Math.random() * width / pixcelSize | 0; // |0 to Int32
  y = Math.random() * height / pixcelSize| 0;

  for(j=0;j < pixcelSize; j++){
    for(k=0;k < pixcelSize; k++){
     setPixel( imageData, {
         x: x * pixcelSize + j,  
         y: y * pixcelSize + k,
         r: 0 | 0,
         g: 0 | 0,
         b: 0 * 256 | 0,
         a: 255 // 255 opaque
       });
      }
  }
}

c.putImageData(imageData, 0, 0);

Working sample here

An unhandled exception of type 'System.IO.FileNotFoundException' occurred in Unknown Module

First check - is the working directory the directory that the application is running in:

  • Right-click on your project and select Properties.
  • Click the Debug tab.
  • Confirm that the Working directory is either empty or equal to the bin\debug directory.

If this isn't the problem, then ask if Autodesk.Navisworks.Timeliner.dll is requiring another DLL which is not there. If Timeliner.dll is not a .NET assembly, you can determine the required imports using the command utility DUMPBIN.

dumpbin /imports Autodesk.Navisworks.Timeliner.dll

If it is a .NET assembly, there are a number of tools that can check dependencies.

Reflector has already been mentioned, and I use JustDecompile from Telerik.


Also see this question

Defined Edges With CSS3 Filter Blur

Insert the image inside a with position: relative; and overflow: hidden;

HTML

<div><img src="#"></div>

CSS

div {
    position: relative;
    overflow: hidden;
}
img {
    filter: blur(5px);
        -webkit-filter: blur(5px);
        -moz-filter: blur(5px);
        -o-filter: blur(5px);
        -ms-filter: blur(5px);
}

This also works on variable sizes elements, like dynamic div's.

How Long Does it Take to Learn Java for a Complete Newbie?

It depends on how hard you want to work, but yes it's possible. The problem you are going to have is that you have to learn to program along with learning java. These are two very different things. Programming is knowing how to read and write logic and Java is a language you write it in. If you have a math or physics background, this is going to be a lot easier, as you are already exposed to thinking in such a manner.

If you don't have books on beginning Java I would go buy one of those.

I would also pick up the book Code (I would try and get through this in a few days, if not over the weekend if possible). Actually with 10 weeks I would do this first as it will be a foundation for what you'll need to know to program Java.

With 10 weeks, you are going to have to pretty much study every night to get the hang of it by the time you go to class. My best advice is that when you take the class, take lots of notes, and don't expect to understand everything. Most of what gets thrown at you there will probably go over your head at first and you'll forget. That's ok. After the class if over, go back and review the notes etc until it starts to make sense.

How to print pandas DataFrame without index

If you just want a string/json to print it can be solved with:

print(df.to_string(index=False))

Buf if you want to serialize the data too or even send to a MongoDB, would be better to do something like:

document = df.to_dict(orient='list')

There are 6 ways by now to orient the data, check more in the panda docs which better fits you.

Oracle date "Between" Query

Following query also can be used:

select * 
  from t23
 where trunc(start_date) between trunc(to_date('01/15/2010','mm/dd/yyyy')) and trunc(to_date('01/17/2010','mm/dd/yyyy'))

Why use Ruby's attr_accessor, attr_reader and attr_writer?

You may use the different accessors to communicate your intent to someone reading your code, and make it easier to write classes which will work correctly no matter how their public API is called.

class Person
  attr_accessor :age
  ...
end

Here, I can see that I may both read and write the age.

class Person
  attr_reader :age
  ...
end

Here, I can see that I may only read the age. Imagine that it is set by the constructor of this class and after that remains constant. If there were a mutator (writer) for age and the class were written assuming that age, once set, does not change, then a bug could result from code calling that mutator.

But what is happening behind the scenes?

If you write:

attr_writer :age

That gets translated into:

def age=(value)
  @age = value
end

If you write:

attr_reader :age

That gets translated into:

def age
  @age
end

If you write:

attr_accessor :age

That gets translated into:

def age=(value)
  @age = value
end

def age
  @age
end

Knowing that, here's another way to think about it: If you did not have the attr_... helpers, and had to write the accessors yourself, would you write any more accessors than your class needed? For example, if age only needed to be read, would you also write a method allowing it to be written?

Commenting out code blocks in Atom

with all my respect with the comments above, no need to use a package :

1) click on Atom 
1.2) then ATL => the menu bar appear 
1.3) File > Settings  => settings appear
1.4) Keybindings > Search keybinding input => fill "comment"
1.5) you will see :

keybindings panel in atom editor

if you want to change the configuration, you just have to parameter your keymap file

How do I pretty-print existing JSON data with Java?

If you are using jackson you can easily achieve this with configuring a SerializationFeature in your ObjectMapper:

com.fasterxml.jackson.databind.ObjectMapper mapper = new ObjectMapper();

mapper.configure(SerializationFeature.INDENT_OUTPUT, true);

mapper.writeValueAsString(<yourObject>);

Thats it.

javascript regular expression to check for IP addresses

The answers over allow leading zeros in Ip address, and that it is not correct. For example ("123.045.067.089"should return false).

The correct way to do it like that.

 function isValidIP(ipaddress) {  
if (/^(25[0-5]|2[0-4][0-9]|[1]?[1-9][1-9]?)\.(25[0-5]|2[0-4][0-9]|[1]?[1-9][1-9]?)\.(25[0-5]|2[0-4][0-9]|[1]?[1-9][1-9]?)\.(25[0-5]|2[0-4][0-9]|[1]?[1-9][1-9]?)$/.test(ipaddress)) {  
  return (true)  
}   
return (false) } 

This function will not allow zero to lead IP addresses.