Programs & Examples On #Wsat

Conditional Binding: if let error – Initializer for conditional binding must have Optional type

In a case where you are using a custom cell type, say ArticleCell, you might get an error that says :

    Initializer for conditional binding must have Optional type, not 'ArticleCell'

You will get this error if your line of code looks something like this:

    if let cell = tableView.dequeReusableCell(withIdentifier: "ArticleCell",for indexPath: indexPath) as! ArticleCell 

You can fix this error by doing the following :

    if let cell = tableView.dequeReusableCell(withIdentifier: "ArticleCell",for indexPath: indexPath) as ArticleCell?

If you check the above, you will see that the latter is using optional casting for a cell of type ArticleCell.

unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard

If the classic solutions (register identifier for class in code or IB) do not work: try to relaunch Xcode, turns out my storyboard stopped saving edits I was made, including setting the reuse identifier.

Refresh certain row of UITableView based on Int in Swift

    extension UITableView {
        /// Reloads a table view without losing track of what was selected.
        func reloadDataSavingSelections() {
            let selectedRows = indexPathsForSelectedRows

            reloadData()

            if let selectedRow = selectedRows {
                for indexPath in selectedRow {
                    selectRow(at: indexPath, animated: false, scrollPosition: .none)
                }
            }
        }
    }

tableView.reloadDataSavingSelections()

'Invalid update: invalid number of rows in section 0

You need to remove the object from your data array before you call deleteRowsAtIndexPaths:withRowAnimation:. So, your code should look like this:

// Editing of rows is enabled
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {

        //when delete is tapped
        [currentCart removeObjectAtIndex:indexPath.row];

        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

You can also simplify your code a little by using the array creation shortcut @[]:

[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];

Xcode error - Thread 1: signal SIGABRT

SIGABRT is, as stated in other answers, a general uncaught exception. You should definitely learn a little bit more about Objective-C. The problem is probably in your UITableViewDelegate method didSelectRowAtIndexPath.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

I can't tell you much more until you show us something of the code where you handle the table data source and delegate methods.

How to create NSIndexPath for TableView

indexPathForRow is a class method!

The code should read:

NSIndexPath *myIP = [NSIndexPath indexPathForRow:0 inSection:0] ;

Can you Run Xcode in Linux?

I think you need MonoTouch (not free!) for that plugin.

And no, there is no way to run Xcode on Linux.

Sorry for all the bad news. :)

NSRange from Swift Range?

I love the Swift language, but using NSAttributedString with a Swift Range that is not compatible with NSRange has made my head hurt for too long. So to get around all that garbage I devised the following methods to return an NSMutableAttributedString with the highlighted words set with your color.

This does not work for emojis. Modify if you must.

extension String {
    func getRanges(of string: String) -> [NSRange] {
        var ranges:[NSRange] = []
        if contains(string) {
            let words = self.components(separatedBy: " ")
            var position:Int = 0
            for word in words {
                if word.lowercased() == string.lowercased() {
                    let startIndex = position
                    let endIndex = word.characters.count
                    let range = NSMakeRange(startIndex, endIndex)
                    ranges.append(range)
                }
                position += (word.characters.count + 1) // +1 for space
            }
        }
        return ranges
    }
    func highlight(_ words: [String], this color: UIColor) -> NSMutableAttributedString {
        let attributedString = NSMutableAttributedString(string: self)
        for word in words {
            let ranges = getRanges(of: word)
            for range in ranges {
                attributedString.addAttributes([NSForegroundColorAttributeName: color], range: range)
            }
        }
        return attributedString
    }
}

Usage:

// The strings you're interested in
let string = "The dog ran after the cat"
let words = ["the", "ran"]

// Highlight words and get back attributed string
let attributedString = string.highlight(words, this: .yellow)

// Set attributed string
label.attributedText = attributedString

Convert string to Boolean in javascript

I would use a simple string comparison here, as far as I know there is no built in function for what you want to do (unless you want to resort to eval... which you don't).

var myBool = myString == "true";

Authentication plugin 'caching_sha2_password' is not supported

Please install below command using command prompt.

pip install mysql-connector-python

enter image description here

Fatal error: Class 'PHPMailer' not found

Just from reading what you have written, you will need to add the file class.phpmailer.php to your directory as well.

How do you get the width and height of a multi-dimensional array?

Some of the other posts are confused about which dimension is which. Here's an NUNIT test that shows how 2D arrays work in C#

[Test]
public void ArraysAreRowMajor()
{
    var myArray = new int[2,3]
        {
            {1, 2, 3},
            {4, 5, 6}
        };

    int rows = myArray.GetLength(0);
    int columns = myArray.GetLength(1);
    Assert.AreEqual(2,rows);
    Assert.AreEqual(3,columns);
    Assert.AreEqual(1,myArray[0,0]);
    Assert.AreEqual(2,myArray[0,1]);
    Assert.AreEqual(3,myArray[0,2]);
    Assert.AreEqual(4,myArray[1,0]);
    Assert.AreEqual(5,myArray[1,1]);
    Assert.AreEqual(6,myArray[1,2]);
}

Write / add data in JSON file using Node.js

Please try the following program. You might be expecting this output.

var fs = require('fs');

var data = {}
data.table = []
for (i=0; i <26 ; i++){
   var obj = {
       id: i,
       square: i * i
   }
   data.table.push(obj)
}
fs.writeFile ("input.json", JSON.stringify(data), function(err) {
    if (err) throw err;
    console.log('complete');
    }
);

Save this program in a javascript file, say, square.js.

Then run the program from command prompt using the command node square.js

What it does is, simply overwriting the existing file with new set of data, every time you execute the command.

Happy Coding.

Drawing rotated text on a HTML5 canvas

Like others have mentioned, you probably want to look at reusing an existing graphing solution, but rotating text isn't too difficult. The somewhat confusing bit (to me) is that you rotate the whole context and then draw on it:

ctx.rotate(Math.PI*2/(i*6));

The angle is in radians. The code is taken from this example, which I believe was made for the transformations part of the MDC canvas tutorial.

Please see the answer below for a more complete solution.

'0000-00-00 00:00:00' can not be represented as java.sql.Timestamp error

I know this is going to be a late answer, however here is the most correct answer.

In MySQL database, change your timestamp default value into CURRENT_TIMESTAMP. If you have old records with the fake value, you will have to manually fix them.

How do I create an average from a Ruby array?

You can choose one of the below solutions as you wish.

Bruteforce

[0,4,8,2,5,0,2,6].sum.to_f / [0,4,8,2,5,0,2,6].size.to_f

=> 3.375

Method

def avg(array)
  array.sum.to_f / array.size.to_f
end  

avg([0,4,8,2,5,0,2,6])
=> 3.375

Monkey Patching

class Array
  def avg
    sum.to_f / size.to_f
  end
end

[0,4,8,2,5,0,2,6].avg
=> 3.375

But I don't recommend to monkey patch the Array class, this practice is dangerous and can potentially lead to undesirable effects on your system.

For our good, ruby language provides a nice feature to overcome this problem, the Refinements, which is a safe way for monkey patching on ruby.

To simplify, with the Refinements you can monkey patch the Array class and the changes will only be available inside the scope of the class that is using the refinement! :)

You can use the refinement inside the class you are working on and you are ready to go.

Refinements

module ArrayRefinements
  refine Array do
    def avg
      sum.to_f / size.to_f
    end
  end
end

class MyClass
  using ArrayRefinements

  def test(array)
    array.avg
  end
end

MyClass.new.test([0,4,8,2,5,0,2,6])
=> 3.375

How to call a function after a div is ready?

To do something after certain div load from function .load(). I think this exactly what you need:

  $('#divIDer').load(document.URL +  ' #divIDer',function() {

       // call here what you want .....


       //example
       $('#mydata').show();
  });

Angular 2 @ViewChild annotation returns undefined

My solution to this was to move the ngIf from outside of the child component to inside of the child component on a div that wrapped the whole section of html. That way it was still getting hidden when it needed to be, but was able to load the component and I could reference it in the parent.

Get full path of the files in PowerShell

Get-ChildItem -Recurse *.txt | Format-Table FullName

That is what I used. I feel it is more understandable as it doesn't contain any loop syntax.

global variable for all controller and views

There are two options:

  1. Create a php class file inside app/libraries/YourClassFile.php

    a. Any function you create in it would be easily accessible in all the views and controllers.

    b. If it is a static function you can easily access it by the class name.

    c. Make sure you inclued "app/libraries" in autoload classmap in composer file.

  2. In app/config/app.php create a variable and you can reference the same using

    Config::get('variable_name');

Hope this helps.

Edit 1:

Example for my 1st point:

// app/libraries/DefaultFunctions.php

class DefaultFunctions{

    public static function getSomeValue(){
     // Fetch the Site Settings object
     $site_settings = Setting::all();
     return $site_settings; 
    }
}

//composer.json

"autoload": {
        "classmap": [
..
..
..  
        "app/libraries" // add the libraries to access globaly.
        ]
    }

 //YourController.php

   $default_functions  = new DefaultFunctions();
    $default_functions->getSomeValue();

Mysql command not found in OS X 10.7

I had same issue after installing mariadb via HomeBrew, brew doctor suggested to run brew link mariadb - which fixed the issue.

Facebook Graph API error code list

While there does not appear to be a public, Facebook-curated list of error codes available, a number of folks have taken it upon themselves to publish lists of known codes.

Take a look at StackOverflow #4348018 - List of Facebook error codes for a number of useful resources.

About .bash_profile, .bashrc, and where should alias be written in?

.bash_profile is loaded for a "login shell". I am not sure what that would be on OS X, but on Linux that is either X11 or a virtual terminal.

.bashrc is loaded every time you run Bash. That is where you should put stuff you want loaded whenever you open a new Terminal.app window.

I personally put everything in .bashrc so that I don't have to restart the application for changes to take effect.

Merge development branch with master

1) On branch Development, check git status using following command:

git status

There should be no uncommitted code. If it is, push your code on Development branch:

git add *

git commit -m "My initial commit message"

git push origin Development

2) On Development branch, run following two commands:

git branch -f master HEAD

git push -f origin master

It will push your Development branch code to master branch.

mysql_config not found when installing mysqldb python interface

In CentOS 7 instead of yum install mysql-devel do yum install mysql-community-devel

This does not require you to add the mysql repo.

img onclick call to JavaScript function

You should probably be using a more unobtrusive approach. Here's the benefits

  • Separation of functionality (the "behavior layer") from a Web page's structure/content and presentation
  • Best practices to avoid the problems of traditional JavaScript programming (such as browser inconsistencies and lack of scalability)
  • Progressive enhancement to support user agents that may not support advanced JavaScript functionality

Here's a jsfiddle demo

Your JavaScript

function exportToForm(a, b, c, d, e) {
  console.log(a, b, c, d, e);
}

var images = document.getElementsByTagName("img");

for (var i=0, len=images.length, img; i<len; i++) {
  img = images[i];
  img.addEventListener("click", function() {
    var a = img.getAttribute("data-a"),
        b = img.getAttribute("data-b"),
        c = img.getAttribute("data-c"),
        d = img.getAttribute("data-d"),
        e = img.getAttribute("data-e");

    exportToForm(a, b, c, d, e);
  });
}

Your images will look like this

<img data-a="1" data-b="2" data-c="3" data-d="4" data-e="5" src="image.jpg">

UnicodeEncodeError: 'charmap' codec can't encode characters

In Python 3.7, and running Windows 10 this worked (I am not sure whether it will work on other platforms and/or other versions of Python)

Replacing this line:

with open('filename', 'w') as f:

With this:

with open('filename', 'w', encoding='utf-8') as f:

The reason why it is working is because the encoding is changed to UTF-8 when using the file, so characters in UTF-8 are able to be converted to text, instead of returning an error when it encounters a UTF-8 character that is not suppord by the current encoding.

Printing out a number in assembly language?

mov al,3 ;print ?


mov dl,al

;call print service(2) to print from dl


mov ah,2
int 21h

;return to DOS


mov ah,76 ;76 = 4ch

int 21h ;call interrupt

Make .gitignore ignore everything except a few files

I also had some issues with the negation of single files. I was able to commit them, but my IDE (IntelliJ) always complained about ignored files, which are tracked.

git ls-files -i --exclude-from .gitignore

Displayed the two files, which I've excluded this way:

public/
!public/typo3conf/LocalConfiguration.php
!public/typo3conf/PackageStates.php

In the end, this worked for me:

public/*
!public/typo3conf/
public/typo3conf/*
!public/typo3conf/LocalConfiguration.php
!public/typo3conf/PackageStates.php

The key was the negation of the folder typo3conf/ first.

Also, it seems that the order of the statements doesn't matter. Instead, you need to explicitly negate all subfolders, before you can negate single files in it.

The folder !public/typo3conf/ and the folder contents public/typo3conf/* are two different things for .gitignore.

Great thread! This issue bothered me for a while ;)

SVN- How to commit multiple files in a single shot

You can use --targets ARG option where ARG is the name of textfile containing the targets for commit.

svn ci --targets myfiles.txt -m "another commit"

Import SQL file into mysql

From the mysql console:

mysql> use DATABASE_NAME;

mysql> source path/to/file.sql;


make sure there is no slash before path if you are referring to a relative path... it took me a while to realize that! lol

How to check if a String contains any of some strings

This is a "nicer solution" and quite simple

if(new string[] { "A", "B", ... }.Any(s=>myString.Contains(s)))

In Unix, how do you remove everything in the current directory and below it?

make sure you are in the correct directory

rm -rf *

Javascript array sort and unique

O[N^2] solutions are bad, especially when the data is already sorted, there is no need to do two nested loops for removing duplicates. One loop and comparing to the previous element will work great.

A simple solution with O[] of sort() would suffice. My solution is:

function sortUnique(arr, compareFunction) {
  let sorted = arr.sort(compareFunction);
  let result = sorted.filter(compareFunction
    ? function(val, i, a) { return (i == 0 || compareFunction(a[i-1], val) != 0); }
    : function(val, i, a) { return (i == 0 || a[i-1] !== val); }
  );
  return result;
}

BTW, can do something like this to have Array.sortUnique() method:

Array.prototype.sortUnique = function(compareFunction) {return sortUnique(this, compareFunction); }

Furthermore, sort() could be modified to remove second element if compare() function returns 0 (equal elements), though that code can become messy (need to revise loop boundaries in the flight). Besides, I stay away from making my own sort() functions in interpreted languages, since it will most certainly degrade the performance. So this addition is for the ECMA 2019+ consideration.

How to ftp with a batch file?

The answer by 0x90h helped a lot...

I saved this file as u.ftp:

open 10.155.8.215 
user
password
lcd /D "G:\Subfolder\"
cd  folder/
binary
mget file.csv
disconnect
quit

I then ran this command:

ftp -i -s:u.ftp

And it worked!!!

Thanks a lot man :)

Remove tracking branches no longer on remote

I found the answer here: How can I delete all git branches which have been merged?

git branch --merged | grep -v "\*" | xargs -n 1 git branch -d

Make sure we keep master

You can ensure that master, or any other branch for that matter, doesn't get removed by adding another grep after the first one. In that case you would go:

git branch --merged | grep -v "\*" | grep -v "YOUR_BRANCH_TO_KEEP" | xargs -n 1 git branch -d

So if we wanted to keep master, develop and staging for instance, we would go:

git branch --merged | grep -v "\*" | grep -v "master" | grep -v "develop" | grep -v "staging" | xargs -n 1 git branch -d

Make this an alias

Since it's a bit long, you might want to add an alias to your .zshrc or .bashrc. Mine is called gbpurge (for git branches purge):

alias gbpurge='git branch --merged | grep -v "\*" | grep -v "master" | grep -v "develop" | grep -v "staging" | xargs -n 1 git branch -d'

Then reload your .bashrc or .zshrc:

. ~/.bashrc

or

. ~/.zshrc

Gradle task - pass arguments to Java application

Sorry for answering so late.

I figured an answer alike to @xlm 's:

task run (type: JavaExec, dependsOn: classes){
    if(project.hasProperty('myargs')){
        args(myargs.split(','))
    }
    description = "Secure algorythm testing"
    main = "main.Test"
    classpath = sourceSets.main.runtimeClasspath
}

And invoke like:

gradle run -Pmyargs=-d,s

datatable jquery - table header width not aligned with body width

Simply wrap table tag element in a div with overflow auto and position relative. It will work in chrome and IE8. I've added height 400px in order to keep table size fixed even after reloading data.

table = $('<table cellpadding="0" cellspacing="0" border="0" class="display" id="datat"></table>').appendTo('#candidati').dataTable({
        //"sScrollY": "400px",//NO MORE REQUIRED - SEE wrap BELOW
        //"sScrollX": "100%",//NO MORE REQUIRED - SEE wrap BELOW
        //"bScrollCollapse": true,//NO MORE REQUIRED - SEE wrap BELOW
        //"bScrollAutoCss": true,//NO MORE REQUIRED - SEE wrap BELOW
        "sAjaxSource": "datass.php",
        "aoColumns": colf,
        "bJQueryUI": true,
        "sPaginationType": "two_button",
        "bProcessing": true,
        "bJQueryUI":true,
        "bPaginate": true,
        "table-layout": "fixed",
        "fnServerData": function(sSource, aoData, fnCallback, oSettings) {
            aoData.push({"name": "filters", "value": $.toJSON(getSearchFilters())});//inserisce i filtri
            oSettings.jqXHR = $.ajax({
                "dataType": 'JSON',
                "type": "POST",
                "url": sSource,
                "data": aoData,
                "success": fnCallback
            });
        },
        "fnRowCallback": function(nRow, aData, iDisplayIndex) {
            $(nRow).click(function() {
                $(".row_selected").removeClass("row_selected");
                $(this).addClass("row_selected");
                //mostra il detaglio
                showDetail(aData.CandidateID);
            });
        },
        "fnDrawCallback": function(oSettings) {

        },
        "aaSorting": [[1, 'asc']]
}).wrap("<div style='position:relative;overflow:auto;height:400px;'/>"); //correzione per il disallineamento dello header

How do I get my solution in Visual Studio back online in TFS?

i found another way without much effort.

Just simply right click your solution and then click undo pending changes.

Next, VS will ask you for acutally changed file where you want to undo or not specific file.

In this you can click no for such a file where actual change is happende, rest is just undoing. This will not lost your actual changes

How to use requirements.txt to install all dependencies in a python project

(Taken from my comment)

pip won't handle system level dependencies. You'll have to apt-get install libfreetype6-dev before continuing. (It even says so right in your output. Try skimming over it for such errors next time, usually build outputs are very detailed)

Perform .join on value in array of objects

Well you can always override the toString method of your objects:

var arr = [
    {name: "Joe", age: 22, toString: function(){return this.name;}},
    {name: "Kevin", age: 24, toString: function(){return this.name;}},
    {name: "Peter", age: 21, toString: function(){return this.name;}}
];

var result = arr.join(", ");
//result = "Joe, Kevin, Peter"

Jquery/Ajax Form Submission (enctype="multipart/form-data" ). Why does 'contentType:False' cause undefined index in PHP?

contentType option to false is used for multipart/form-data forms that pass files.

When one sets the contentType option to false, it forces jQuery not to add a Content-Type header, otherwise, the boundary string will be missing from it. Also, when submitting files via multipart/form-data, one must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.


To try and fix your issue:

Use jQuery's .serialize() method which creates a text string in standard URL-encoded notation.

You need to pass un-encoded data when using contentType: false.

Try using new FormData instead of .serialize():

  var formData = new FormData($(this)[0]);

See for yourself the difference of how your formData is passed to your php page by using console.log().

  var formData = new FormData($(this)[0]);
  console.log(formData);

  var formDataSerialized = $(this).serialize();
  console.log(formDataSerialized);

Enabling WiFi on Android Emulator

(Repeating here my answer elsewhere.)

In theory, linux (the kernel underlying android) has mac80211_hwsim driver, which simulates WiFi. It can be used to set up several WiFi devices (an acces point, and another WiFi device, and so on), which would make up a WiFi network.

It's useful for testing WiFi programs under linux. Possibly, even under user-mode linux or other isolated virtual "boxes" with linux.

In theory, this driver could be used for tests in the android systems where you don't have a real WiFi device (or don't want to use it), and also in some kind of android emulators. Perhaps, one can manage to use this driver in android-x86, or--for testing--in android-x86 run in VirtualBox.

java.lang.ClassCastException

A ClassCastException ocurrs when you try to cast an instance of an Object to a type that it is not. Casting only works when the casted object follows an "is a" relationship to the type you are trying to cast to. For Example

Apple myApple = new Apple();
Fruit myFruit = (Fruit)myApple;

This works because an apple 'is a' fruit. However if we reverse this.

Fruit myFruit = new Fruit();
Apple myApple = (Apple)myFruit;

This will throw a ClasCastException because a Fruit is not (always) an Apple.

It is good practice to guard any explicit casts with an instanceof check first:

if (myApple instanceof Fruit) {
  Fruit myFruit = (Fruit)myApple;
}

How to convert DateTime to/from specific string format (both ways, e.g. given Format is "yyyyMMdd")?

Parsing DateTime:

To parse a DateTime, use one of the following methods:

Alternatively, you may use try-parse pattern:

Read more about Custom Date and Time Format Strings.

Converting DateTime to a string:

To return a DateTime as a string in "yyyyMMdd" format, you may use ToString method.

  • Code snippet example: string date = DateTime.ToString("yyyyMMdd");
  • Note upper-cased M's refer to months and lower-cased m's to minutes.

Your case:

In your case, assuming you don't want to handle scenario when date is different format or misssing, it would be most convenient to use ParseExact:

string dateToParse = "20170506";
DateTime parsedDate = DateTime.ParseExact(dateToParse, 
                                          "yyyyMMdd",
                                          CultureInfo.InvariantCulture);

Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

These steps really help me:

Step 1: Create a directory in android/app/src/main/assets

Linux command: mkdir android/app/src/main/assets

Step 2: Rename index.android.js (in root directory) to index.js (Maybe there is an index.js file in which case you do not need to rename it) then run the following command:

react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

Step 3: Build your APK: react-native run-android

Please use index.js in latest version.

Enjoy :)

How to download the latest artifact from Artifactory repository?

Something like the following bash script will retrieve the lastest com.company:artifact snapshot from the snapshot repo:

# Artifactory location
server=http://artifactory.company.com/artifactory
repo=snapshot

# Maven artifact location
name=artifact
artifact=com/company/$name
path=$server/$repo/$artifact
version=$(curl -s $path/maven-metadata.xml | grep latest | sed "s/.*<latest>\([^<]*\)<\/latest>.*/\1/")
build=$(curl -s $path/$version/maven-metadata.xml | grep '<value>' | head -1 | sed "s/.*<value>\([^<]*\)<\/value>.*/\1/")
jar=$name-$build.jar
url=$path/$version/$jar

# Download
echo $url
wget -q -N $url

It feels a bit dirty, yes, but it gets the job done.

Can typescript export a function?

If you are using this for Angular, then export a function via a named export. Such as:

function someFunc(){}

export { someFunc as someFuncName }

otherwise, Angular will complain that object is not a function.

Wordpress 403/404 Errors: You don't have permission to access /wp-admin/themes.php on this server

Try to disable ModSecurity from your cPanel. Log into your cPanel. Find the category "Security". There you can find ModSecurity link.Click on it and disable it for the domain you are facing the 403 error.

Some 403 errors can be solved by this method too. Go to the wordpress dashboard, settings>permalink and just click save.

Hope this helped. :)

npm install won't install devDependencies

Check the NPM docs for install

With the --production flag (or when the NODE_ENV environment variable is set to production), npm will not install modules listed in devDependencies."

The --only={prod[uction]|dev[elopment]} argument will cause either only devDependencies or only non-devDependencies to be installed regardless of the NODE_ENV."

Have you tried

npm install --only=dev

If you are worried that your package.json might be incorrect, best thing to do is this. Create a new folder, and run:

npm init --yes

Then:

npm install --save-dev brunch@^2.0.4
npm install --save-dev cssnano-brunch@^1.1.5
npm install --save-dev javascript-brunch@^1.8.0
npm install --save-dev sass-brunch@^1.9.2
npm install --save-dev uglify-js-brunch@^1.7.8
npm install jquery@^2.1.4 --save

And you should be good to go! Otherwise, will keep posting other options.

Check your npm configuration:

npm config list

npm gets its config settings from the command line, environment variables, and npmrc files. So check environment variables, and the npmrc file.

Still failing?

Ok, create a new folder, ideally somewhere else on your filesystem. ie. not in same folder hierarchy. For instance, C:\myNewFolder - the closer to the base C: drive the better.

Then run:

npm init --yes

Now run:

npm install underscore --save

and finally:

npm install mocha --save-dev

Does everything work as expected?

What I am trying to do is understand whether your problem is global, or something local to the previous folder and dependencies.

How to use the toString method in Java?

The toString() method returns a textual representation of an object. A basic implementation is already included in java.lang.Object and so because all objects inherit from java.lang.Object it is guaranteed that every object in Java has this method.

Overriding the method is always a good idea, especially when it comes to debugging, because debuggers often show objects by the result of the toString() method. So use a meaningful implementation but use it for technical purposes. The application logic should use getters:

public class Contact {
  private String firstName;
  private String lastName;
  public Contact (String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  public String getFirstName() {return firstName;}
  public String getLastName() {return lastName;}

  public String getContact() {
    return firstName + " " + lastName;
  }

  @Override
  public String toString() {
    return "["+getContact()+"]";
  }
}

Advantages of SQL Server 2008 over SQL Server 2005?

SQL 2008 also allows you to disable lock escalation on specific tables. I have found this very useful on small frequently updated tables where locks can escalate causing concurrency issues. In SQL 2005, even with the ROWLOCK hint on delete statements locks can be escalated which can lead to deadlocks. In my testing, an application which I have developed had concurrency issues during small table manipulation due to lock escalation on SQL 2005. In SQL 2008 this problem went away.

It is still important to bear in mind the potential overhead of handling large numbers of row locks, but having the option to stop escalation when you want to is very useful.

How to resize a custom view programmatically?

if you are overriding onMeasure, don't forget to update the new sizes

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(newWidth, newHeight);
}

How to get df linux command output always in GB

If you also want it to be a command you can reference without remembering the arguments, you could simply alias it:

alias df-gb='df -BG'

So if you type:

df-gb

into a terminal, you'll get your intended output of the disk usage in GB.

EDIT: or even use just df -h to get it in a standard, human readable format.

http://www.thegeekstuff.com/2012/05/df-examples/

How to empty/destroy a session in rails?

to delete a user's session

session.delete(:user_id)

What's the most elegant way to cap a number to a segment?

a less "Math" oriented approach ,but should also work , this way, the < / > test is exposed (maybe more understandable than minimaxing) but it really depends on what you mean by "readable"

function clamp(num, min, max) {
  return num <= min ? min : num >= max ? max : num;
}

Getting the filenames of all files in a folder

Create a File object, passing the directory path to the constructor. Use the listFiles() to retrieve an array of File objects for each file in the directory, and then call the getName() method to get the filename.

List<String> results = new ArrayList<String>();


File[] files = new File("/path/to/the/directory").listFiles();
//If this pathname does not denote a directory, then listFiles() returns null. 

for (File file : files) {
    if (file.isFile()) {
        results.add(file.getName());
    }
}

How to find the location of the Scheduled Tasks folder

On newer versions of Windows (Windows 10 and Windows Server 2016) the tasks you create are located in C:\Windows\Tasks. They will have the extension .job

For example if you create the task "DoWork" it will create the task in

C:\Windows\Tasks\DoWork.job

Sending emails through SMTP with PHPMailer

Yes, you need OpenSSL to work correctly. My backup testing site worked, my live server didn't. Difference? Live server didn't have OpenSSL within PHP configuration.

how to convert string into dictionary in python 3.*?

  1. literal_eval, a somewhat safer version of eval (will only evaluate literals ie strings, lists etc):

    from ast import literal_eval
    
    python_dict = literal_eval("{'a': 1}")
    
  2. json.loads but it would require your string to use double quotes:

    import json
    
    python_dict = json.loads('{"a": 1}')
    

Make child div stretch across width of page

Since position: absolute; and viewport width were no options in my special case, there is another quick solution to solve the problem. The only condition is, that overflow in x-direction is not necessary for your website.

You can define negative margins for your element:

#help_panel {
    margin-left: -9999px;
    margin-right: -9999px;
}

But since we get overflow doing this, we have to avoid overflow in x-direction globally e.g. for body:

body {
    overflow-x: hidden;
}

You can set padding to choose the size of your content.

Note that this solution does not bring 100% width for content, but it is helpful in cases where you need e.g. a background color which has full width with a content still depending on container.

ASP.Net MVC Redirect To A Different View

 if (true)
 {
   return View();
 }
 else
 {
   return View("another view name");
 }

Switch to another branch without changing the workspace files

Simplest way to do is as follows:

git fetch && git checkout <branch_name>

SQL time difference between two dates result in hh:mm:ss

If you need a zero padded difference between 2 dates:

SELECT convert(varchar(2),FORMAT(DATEDIFF(s, @startDate, @endDate)/3600,'0#'))+':'    
   +convert(varchar(2),FORMAT(DATEDIFF(s, @startDate, @endDate)%3600/60,'0#'))+':'
   +convert(varchar(2),FORMAT(DATEDIFF(s, @startDate, @endDate)%60,'0#')) AS Duration

Clear back stack using fragments

I posted something similar here

From Joachim's answer, from Dianne Hackborn:

http://groups.google.com/group/android-developers/browse_thread/thread/d2a5c203dad6ec42

I ended up just using:

FragmentManager fm = getActivity().getSupportFragmentManager();
for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {    
    fm.popBackStack();
}

But could equally have used something like:

((AppCompatActivity)getContext()).getSupportFragmentManager().popBackStack(String name, FragmentManager.POP_BACK_STACK_INCLUSIVE)

Which will pop all states up to the named one. You can then just replace the fragment with what you want

Overlaying a DIV On Top Of HTML 5 Video

<div id="video_box">
  <div id="video_overlays"></div>
  <div>
    <video id="player" src="http://video.webmfiles.org/big-buck-bunny_trailer.webm" type="video/webm" onclick="this.play();">Your browser does not support this streaming content.</video>
  </div>
</div>

for this you need to just add css like this:

#video_overlays {
  position: absolute;
  background-color: rgba(0, 0, 0, 0.46);
  z-index: 2;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}
#video_box{position: relative;}

Cannot get to $rootScope

I don't suggest you to use syntax like you did. AngularJs lets you to have different functionalities as you want (run, config, service, factory, etc..), which are more professional.In this function you don't even have to inject that by yourself like

MainCtrl.$inject = ['$scope', '$rootScope', '$location', 'socket', ...];

you can use it, as you know.

What's the difference between primitive and reference types?

Primitives vs. References

First :-

Primitive types are the basic types of data: byte, short, int, long, float, double, boolean, char. Primitive variables store primitive values. Reference types are any instantiable class as well as arrays: String, Scanner, Random, Die, int[], String[], etc. Reference variables store addresses to locations in memory for where the data is stored.

Second:-

Primitive types store values but Reference type store handles to objects in heap space. Remember, reference variables are not pointers like you might have seen in C and C++, they are just handles to objects, so that you can access them and make some change on object's state.

Read more: http://javarevisited.blogspot.com/2015/09/difference-between-primitive-and-reference-variable-java.html#ixzz3xVBhi2cr

How can I run a html file from terminal?

This works :

browsername <filename>

Example: google-chrome index.html

enter image description here

Get User Selected Range

This depends on what you mean by "get the range of selection". If you mean getting the range address (like "A1:B1") then use the Address property of Selection object - as Michael stated Selection object is much like a Range object, so most properties and methods works on it.

Sub test()
    Dim myString As String
    myString = Selection.Address
End Sub

How can I truncate a datetime in SQL Server?

Oracle:

TRUNC(SYSDATE, 'MONTH')

SQL Server:

DATEADD(DAY, - DATEPART(DAY, DateField) + 1, DateField)

Could be similarly used for truncating minutes or hours from a date.

Reading in from System.in - Java

class myFileReaderThatStarts with arguments
{

 class MissingArgumentException extends Exception{      
      MissingArgumentException(String s)
  {
     super(s);
  }

   }    
public static void main(String[] args) throws MissingArgumentException
{
//You can test args array for value 
if(args.length>0)
{
    // do something with args[0]
}
else
{
// default in a path 
// or 
   throw new MissingArgumentException("You need to start this program with a path");
}
}

List all environment variables from the command line

If you want to see the environment variable you just set, you need to open a new command window.

Variables set with setx variables are available in future command windows only, not in the current command window. (Setx, Examples)

How to set top-left alignment for UILabel for iOS application?

The SOLabel works for me.

Swift 3 & 5:

This version has been updated from the original to allow support for RTL languages:

public class VerticalAlignLabel: UILabel {
    enum VerticalAlignment {
        case top
        case middle
        case bottom
    }

    var verticalAlignment : VerticalAlignment = .top {
        didSet {
            setNeedsDisplay()
        }
    }

    override public func textRect(forBounds bounds: CGRect, limitedToNumberOfLines: Int) -> CGRect {
        let rect = super.textRect(forBounds: bounds, limitedToNumberOfLines: limitedToNumberOfLines)

        if UIView.userInterfaceLayoutDirection(for: .unspecified) == .rightToLeft {
            switch verticalAlignment {
            case .top:
                return CGRect(x: self.bounds.size.width - rect.size.width, y: bounds.origin.y, width: rect.size.width, height: rect.size.height)
            case .middle:
                return CGRect(x: self.bounds.size.width - rect.size.width, y: bounds.origin.y + (bounds.size.height - rect.size.height) / 2, width: rect.size.width, height: rect.size.height)
            case .bottom:
                return CGRect(x: self.bounds.size.width - rect.size.width, y: bounds.origin.y + (bounds.size.height - rect.size.height), width: rect.size.width, height: rect.size.height)
            }
        } else {
            switch verticalAlignment {
            case .top:
                return CGRect(x: bounds.origin.x, y: bounds.origin.y, width: rect.size.width, height: rect.size.height)
            case .middle:
                return CGRect(x: bounds.origin.x, y: bounds.origin.y + (bounds.size.height - rect.size.height) / 2, width: rect.size.width, height: rect.size.height)
            case .bottom:
                return CGRect(x: bounds.origin.x, y: bounds.origin.y + (bounds.size.height - rect.size.height), width: rect.size.width, height: rect.size.height)
            }
        }
    }

    override public func drawText(in rect: CGRect) {
        let r = self.textRect(forBounds: rect, limitedToNumberOfLines: self.numberOfLines)
        super.drawText(in: r)
    }
}

Swift 1:

class UIVerticalAlignLabel: UILabel {

enum VerticalAlignment : Int {
    case VerticalAlignmentTop = 0
    case VerticalAlignmentMiddle = 1
    case VerticalAlignmentBottom = 2
}

var verticalAlignment : VerticalAlignment = .VerticalAlignmentTop {
    didSet {
        setNeedsDisplay()
    }
}

required init(coder aDecoder: NSCoder){
    super.init(coder: aDecoder)
}

override func textRectForBounds(bounds: CGRect, limitedToNumberOfLines: Int) -> CGRect {
    let rect = super.textRectForBounds(bounds, limitedToNumberOfLines: limitedToNumberOfLines)

    switch(verticalAlignment) {
        case .VerticalAlignmentTop:
            return CGRectMake(bounds.origin.x, bounds.origin.y, rect.size.width, rect.size.height)
        case .VerticalAlignmentMiddle:
            return CGRectMake(bounds.origin.x, bounds.origin.y + (bounds.size.height - rect.size.height) / 2, rect.size.width, rect.size.height)
        case .VerticalAlignmentBottom:
            return CGRectMake(bounds.origin.x, bounds.origin.y + (bounds.size.height - rect.size.height), rect.size.width, rect.size.height)
        default:
            return bounds
    }
}

override func drawTextInRect(rect: CGRect) {
    let r = self.textRectForBounds(rect, limitedToNumberOfLines: self.numberOfLines)
    super.drawTextInRect(r)
    }
}

How to compare dates in datetime fields in Postgresql?

When you compare update_date >= '2013-05-03' postgres casts values to the same type to compare values. So your '2013-05-03' was casted to '2013-05-03 00:00:00'.

So for update_date = '2013-05-03 14:45:00' your expression will be that:

'2013-05-03 14:45:00' >= '2013-05-03 00:00:00' AND '2013-05-03 14:45:00' <= '2013-05-03 00:00:00'

This is always false

To solve this problem cast update_date to date:

select * from table where update_date::date >= '2013-05-03' AND update_date::date <= '2013-05-03' -> Will return result

Javascript/jQuery detect if input is focused

Did you try:

$(this).is(':focus');

Take a look at Using jQuery to test if an input has focus it features some more examples

Horizontal Scroll Table in Bootstrap/CSS

You can also check for bootstrap datatable plugin as well for above issue.

It will have a large column table scrollable feature with lot of other options

$(document).ready(function() {
    $('#example').dataTable( {
        "scrollX": true
    } );
} );

for more info with example please check out this link

How do I make a delay in Java?

I know this is a very old post but this may help someone: You can create a method, so whenever you need to pause you can type pause(1000) or any other millisecond value:

public static void pause(int ms) {
    try {
        Thread.sleep(ms);
    } catch (InterruptedException e) {
        System.err.format("IOException: %s%n", e);
    }
}

This is inserted just above the public static void main(String[] args), inside the class. Then, to call on the method, type pause(ms) but replace ms with the number of milliseconds to pause. That way, you don't have to insert the entire try-catch statement whenever you want to pause.

Laravel Password & Password_Confirmation Validation

Try this:

'password' => 'required|min:6|confirmed',
'password_confirmation' => 'required|min:6'

Get current date in milliseconds

NSTimeInterval milisecondedDate = ([[NSDate date] timeIntervalSince1970] * 1000);

HTML span align center not working?

A div is a block element, and will span the width of the container unless a width is set. A span is an inline element, and will have the width of the text inside it. Currently, you are trying to set align as a CSS property. Align is an attribute.

<span align="center" style="border:1px solid red;">
    This is some text in a div element!
</span>

However, the align attribute is deprecated. You should use the CSS text-align property on the container.

<div style="text-align: center;">
    <span style="border:1px solid red;">
        This is some text in a div element!
    </span>
</div>

Why is lock(this) {...} bad?

Here's a much simpler illustration (taken from Question 34 here) why lock(this) is bad and may result in deadlocks when consumer of your class also try to lock on the object. Below, only one of three thread can proceed, the other two are deadlocked.

class SomeClass
{
    public void SomeMethod(int id)
    {
        **lock(this)**
        {
            while(true)
            {
                Console.WriteLine("SomeClass.SomeMethod #" + id);
            }
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        SomeClass o = new SomeClass();

        lock(o)
        {
            for (int threadId = 0; threadId < 3; threadId++)
            {
                Thread t = new Thread(() => {
                    o.SomeMethod(threadId);
                        });
                t.Start();
            }

            Console.WriteLine();
        }

To work around, this guy used Thread.TryMonitor (with timeout) instead of lock:

            Monitor.TryEnter(temp, millisecondsTimeout, ref lockWasTaken);
            if (lockWasTaken)
            {
                doAction();
            }
            else
            {
                throw new Exception("Could not get lock");
            }

https://blogs.appbeat.io/post/c-how-to-lock-without-deadlocks

Determining type of an object in ruby

you could also try: instance_of?

p 1.instance_of? Fixnum    #=> True
p "1".instance_of? String  #=> True
p [1,2].instance_of? Array #=> True

How to set 777 permission on a particular folder?

  1. Right click the folder, click on Properties.
  2. Click on the Security tab
  3. Add the name Everyone to the user list.

What is a 'Closure'?

A closure is a function that can reference state in another function. For example, in Python, this uses the closure "inner":

def outer (a):
    b = "variable in outer()"
    def inner (c):
        print a, b, c
    return inner

# Now the return value from outer() can be saved for later
func = outer ("test")
func (1) # prints "test variable in outer() 1

Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Problem solved, I've not added the index.html. Which is point out in the web.xml

enter image description here

Note: a project may have more than one web.xml file.

if there are another web.xml in

src/main/webapp/WEB-INF

Then you might need to add another index (this time index.jsp) to

src/main/webapp/WEB-INF/pages/

Update date + one year in mysql

This post helped me today, but I had to experiment to do what I needed. Here is what I found.

Should you want to add more complex time periods, for example 1 year and 15 days, you can use

UPDATE tablename SET datefieldname = curdate() + INTERVAL 15 DAY + INTERVAL 1 YEAR;

I found that using DATE_ADD doesn't allow for adding more than one interval. And there is no YEAR_DAYS interval keyword, though there are others that combine time periods. If you are adding times, use now() rather than curdate().

Storing query results into a variable and modifying it inside a Stored Procedure

Try this example

CREATE PROCEDURE MyProc
BEGIN
    --Stored Procedure variables
    Declare @maxOr int; 
    Declare @maxCa int; 

    --Getting query result in the variable (first variant of syntax)
    SET @maxOr = (SELECT MAX(orId) FROM [order]); 

    --Another variant of seting variable from query
    SELECT @maxCa=MAX(caId) FROM [cart]; 

    --Updating record through the variable
    INSERT INTO [order_cart] (orId,caId)
    VALUES(@maxOr, @maxCa); 

    --return values to the program as dataset
    SELECT
       @maxOr AS maxOr,
       @maxCa AS maxCa

    -- return one int value as "return value"
    RETURN @maxOr
END
GO

SQL-command to call the stored procedure

EXEC MyProc

Using pointer to char array, values in that array can be accessed?

Most people responding don't even seem to know what an array pointer is...

The problem is that you do pointer arithmetics with an array pointer: ptr + 1 will mean "jump 5 bytes ahead since ptr points at a 5 byte array".

Do like this instead:

#include <stdio.h>

int main()
{
  char (*ptr)[5];
  char arr[5] = {'a','b','c','d','e'};
  int i;

  ptr = &arr;
  for(i=0; i<5; i++)
  {
    printf("\nvalue: %c", (*ptr)[i]);
  }
}

Take the contents of what the array pointer points at and you get an array. So they work just like any pointer in C.

Difference between clean, gradlew clean

  1. ./gradlew clean

    Uses your project's gradle wrapper to execute your project's clean task. Usually, this just means the deletion of the build directory.

  2. ./gradlew clean assembleDebug

    Again, uses your project's gradle wrapper to execute the clean and assembleDebug tasks, respectively. So, it will clean first, then execute assembleDebug, after any non-up-to-date dependent tasks.

  3. ./gradlew clean :assembleDebug

    Is essentially the same as #2. The colon represents the task path. Task paths are essential in gradle multi-project's, not so much in this context. It means run the root project's assembleDebug task. Here, the root project is the only project.

  4. Android Studio --> Build --> Clean

    Is essentially the same as ./gradlew clean. See here.

For more info, I suggest taking the time to read through the Android docs, especially this one.

Any way to make plot points in scatterplot more transparent in R?

Otherwise, you have function alpha in package scales in which you can directly input your vector of colors (even if they are factors as in your example):

library(scales)
cols <- cut(z, 6, labels = c("pink", "red", "yellow", "blue", "green", "purple"))
plot(x, y, main= "Fragment recruitment plot - FR-HIT", 
     ylab = "Percent identity", xlab = "Base pair position", 
     col = alpha(cols, 0.4), pch=16) 
# For an alpha of 0.4, i. e. an opacity of 40%.

Android ListView selected item stay highlighted

To hold the color of listview item when you press it, include the following line in your listview item layout:

android:background="@drawable/bg_key"

Then define bg_key.xml in drawable folder like this:

<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item 
        android:state_selected="true"
        android:drawable="@color/pressed_color"/>
    <item
        android:drawable="@color/default_color" />
</selector>

Finally, include this in your ListView onClickListener:

listView.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,long arg3) {
        view.setSelected(true);
        ... // Anything
    }
});

This way, only one item will be color-selected at any time. You can define your color values in res/values/colors.xml with something like this:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="pressed_color">#4d90fe</color>
    <color name="default_color">#ffffff</color>
</resources>

Get only specific attributes with from Laravel Collection

I have now come up with an own solution to this:

1. Created a general function to extract specific attributes from arrays

The function below extract only specific attributes from an associative array, or an array of associative arrays (the last is what you get when doing $collection->toArray() in Laravel).

It can be used like this:

$data = array_extract( $collection->toArray(), ['id','url'] );

I am using the following functions:

function array_is_assoc( $array )
{
        return is_array( $array ) && array_diff_key( $array, array_keys(array_keys($array)) );
}



function array_extract( $array, $attributes )
{
    $data = [];

    if ( array_is_assoc( $array ) )
    {
        foreach ( $attributes as $attribute )
        {
            $data[ $attribute ] = $array[ $attribute ];
        }
    }
    else
    {
        foreach ( $array as $key => $values )
        {
            $data[ $key ] = [];

            foreach ( $attributes as $attribute )
            {
                $data[ $key ][ $attribute ] = $values[ $attribute ];
            }
        }   
    }

    return $data;   
}

This solution does not focus on performance implications on looping through the collections in large datasets.

2. Implement the above via a custom collection i Laravel

Since I would like to be able to simply do $collection->extract('id','url'); on any collection object, I have implemented a custom collection class.

First I created a general Model, which extends the Eloquent model, but uses a different collection class. All you models need to extend this custom model, and not the Eloquent Model then.

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model as EloquentModel;
use Lib\Collection;
class Model extends EloquentModel
{
    public function newCollection(array $models = [])
    {
        return new Collection( $models );
    }    
}
?>

Secondly I created the following custom collection class:

<?php
namespace Lib;
use Illuminate\Support\Collection as EloquentCollection;
class Collection extends EloquentCollection
{
    public function extract()
    {
        $attributes = func_get_args();
        return array_extract( $this->toArray(), $attributes );
    }
}   
?>

Lastly, all models should then extend your custom model instead, like such:

<?php
namespace App\Models;
class Article extends Model
{
...

Now the functions from no. 1 above are neatly used by the collection to make the $collection->extract() method available.

Excel "External table is not in the expected format."

If the file is read-only, just remove it and it should work again.

ImportError: No module named enum

Or run a pip install --upgrade pip enum34

Impersonate tag in Web.Config

You had the identity node as a child of authentication node. That was the issue. As in the example above, authentication and identity nodes must be children of the system.web node

Difference between "this" and"super" keywords in Java

Lets consider this situation

class Animal {
  void eat() {
    System.out.println("animal : eat");
  }
}

class Dog extends Animal {
  void eat() {
    System.out.println("dog : eat");
  }
  void anotherEat() {
    super.eat();
  }
}

public class Test {
  public static void main(String[] args) {
    Animal a = new Animal();
    a.eat();
    Dog d = new Dog();
    d.eat();
    d.anotherEat();
  }
}

The output is going to be

animal : eat
dog : eat
animal : eat

The third line is printing "animal:eat" because we are calling super.eat(). If we called this.eat(), it would have printed as "dog:eat".

Set transparent background of an imageview on Android

ImageView.setBackground(R.drawable.my_background);

ImageView.setBackgroundResource(R.color.colorPrimary);

ImageView.getImageAlpha();

ImageView.setAlpha(125); // transparency

What is the best way to remove accents (normalize) in a Python unicode string?

This handles not only accents, but also "strokes" (as in ø etc.):

import unicodedata as ud

def rmdiacritics(char):
    '''
    Return the base character of char, by "removing" any
    diacritics like accents or curls and strokes and the like.
    '''
    desc = ud.name(char)
    cutoff = desc.find(' WITH ')
    if cutoff != -1:
        desc = desc[:cutoff]
        try:
            char = ud.lookup(desc)
        except KeyError:
            pass  # removing "WITH ..." produced an invalid name
    return char

This is the most elegant way I can think of (and it has been mentioned by alexis in a comment on this page), although I don't think it is very elegant indeed. In fact, it's more of a hack, as pointed out in comments, since Unicode names are – really just names, they give no guarantee to be consistent or anything.

There are still special letters that are not handled by this, such as turned and inverted letters, since their unicode name does not contain 'WITH'. It depends on what you want to do anyway. I sometimes needed accent stripping for achieving dictionary sort order.

EDIT NOTE:

Incorporated suggestions from the comments (handling lookup errors, Python-3 code).

Difference Between One-to-Many, Many-to-One and Many-to-Many?

I would explain that way:

OneToOne - OneToOne relationship

@OneToOne
Person person;

@OneToOne
Nose nose;

OneToMany - ManyToOne relationship

@OneToMany
Shepherd> shepherd;

@ManyToOne
List<Sheep> sheeps;

ManyToMany - ManyToMany relationship

@ManyToMany
List<Traveler> travelers;

@ManyToMany
List<Destination> destinations;

T-SQL How to select only Second row from a table?

Use ROW_NUMBER() to number the rows, but use TOP to only process the first two.

try this:

DECLARE @YourTable table (YourColumn int)
INSERT @YourTable VALUES (5)
INSERT @YourTable VALUES (7)
INSERT @YourTable VALUES (9)
INSERT @YourTable VALUES (17)
INSERT @YourTable VALUES (25)

;WITH YourCTE AS
(
  SELECT TOP 2
    *, ROW_NUMBER() OVER(ORDER BY YourColumn) AS RowNumber
  FROM @YourTable
) 
SELECT *
FROM YourCTE
WHERE RowNumber=2

OUTPUT:

YourColumn  RowNumber
----------- --------------------
7           2

(1 row(s) affected)

Regular expression for address field validation

Here is the approach I have taken to finding addresses using regular expressions:

A set of patterns is useful to find many forms that we might expect from an address starting with simply a number followed by set of strings (ex. 1 Basic Road) and then getting more specific such as looking for "P.O. Box", "c/o", "attn:", etc.

Below is a simple test in python. The test will find all the addresses but not the last 4 items which are company names. This example is not comprehensive, but can be altered to suit your needs and catch examples you find in your data.

import re
strings = [
    '701 FIFTH AVE',
    '2157 Henderson Highway',
    'Attn: Patent Docketing',
    'HOLLYWOOD, FL 33022-2480',
    '1940 DUKE STREET',
    '111 MONUMENT CIRCLE, SUITE 3700',
    'c/o Armstrong Teasdale LLP',
    '1 Almaden Boulevard',
    '999 Peachtree Street NE',
    'P.O. BOX 2903',
    '2040 MAIN STREET',
    '300 North Meridian Street',
    '465 Columbus Avenue',
    '1441 SEAMIST DR.',
    '2000 PENNSYLVANIA AVENUE, N.W.',
    '465 Columbus Avenue',
    '28 STATE STREET',
    'P.O, Drawer 800889.',
    '2200 CLARENDON BLVD.',
    '840 NORTH PLANKINTON AVENUE',
    '1025 Connecticut Avenue, NW',
    '340 Commercial Street',
    '799 Ninth Street, NW',
    '11318 Lazarro Ln',
    'P.O, Box 65745',
    'c/o Ballard Spahr LLP',
    '8210 SOUTHPARK TERRACE',
    '1130 Connecticut Ave., NW, Suite 420',
    '465 Columbus Avenue',
    "BANNER & WITCOFF , LTD",
    "CHIP LAW GROUP",
    "HAMMER & ASSOCIATES, P.C.",
    "MH2 TECHNOLOGY LAW GROUP, LLP",
]

patterns = [
    "c\/o [\w ]{2,}",
    "C\/O [\w ]{2,}",
    "P.O\. [\w ]{2,}",
    "P.O\, [\w ]{2,}",
    "[\w\.]{2,5} BOX [\d]{2,8}",
    "^[#\d]{1,7} [\w ]{2,}",
    "[A-Z]{2,2} [\d]{5,5}",
    "Attn: [\w]{2,}",
    "ATTN: [\w]{2,}",
    "Attention: [\w]{2,}",
    "ATTENTION: [\w]{2,}"
]
contact_list = []
total_count = len(strings)
found_count = 0
for string in strings:
    pat_no = 1
    for pattern in patterns:
        match = re.search(pattern, string.strip())
        if match:
            print("Item found: " + match.group(0) + " | Pattern no: " + str(pat_no))
            found_count += 1
        pat_no += 1

print("-- Total: " + str(total_count) + " Found: " + str(found_count)) 

What is the difference between Spring, Struts, Hibernate, JavaServer Faces, Tapestry?

Generally...

Hibernate is used for handling database operations. There is a rich set of database utility functionality, which reduces your number of lines of code. Especially you have to read @Annotation of hibernate. It is an ORM framework and persistence layer.

Spring provides a rich set of the Injection based working mechanism. Currently, Spring is well-known. You have to also read about Spring AOP. There is a bridge between Struts and Hibernate. Mainly Spring provides this kind of utility.

Struts2 provides action based programming. There are a rich set of Struts tags. Struts prove action based programming so you have to maintain all the relevant control of your view.

In Addition, Tapestry is a different framework for Java. In which you have to handle only .tml (template file). You have to create two main files for any class. One is JAVA class and another one is its template. Both names are same. Tapestry automatically calls related classes.

"NOT IN" clause in LINQ to Entities

I took a list and used,

!MyList.Contains(table.columb.tostring())

Note: Make sure to use List and not Ilist

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

Make it simple:

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

for example in CSS:

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

or in SCSS:

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

Xcode stops working after set "xcode-select -switch"

You should be pointing it towards the Developer directory, not the Xcode application bundle. Run this:

sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer

With recent versions of Xcode, you can go to Xcode ? Preferences… ? Locations and pick one of the options for Command Line Tools to set the location.

Executors.newCachedThreadPool() versus Executors.newFixedThreadPool()

If you are not worried about an unbounded queue of Callable/Runnable tasks, you can use one of them. As suggested by bruno, I too prefer newFixedThreadPool to newCachedThreadPool over these two.

But ThreadPoolExecutor provides more flexible features compared to either newFixedThreadPool or newCachedThreadPool

ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, 
TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory,
RejectedExecutionHandler handler)

Advantages:

  1. You have full control of BlockingQueue size. It's not un-bounded, unlike the earlier two options. I won't get an out of memory error due to a huge pile-up of pending Callable/Runnable tasks when there is unexpected turbulence in the system.

  2. You can implement custom Rejection handling policy OR use one of the policies:

    1. In the default ThreadPoolExecutor.AbortPolicy, the handler throws a runtime RejectedExecutionException upon rejection.

    2. In ThreadPoolExecutor.CallerRunsPolicy, the thread that invokes execute itself runs the task. This provides a simple feedback control mechanism that will slow down the rate that new tasks are submitted.

    3. In ThreadPoolExecutor.DiscardPolicy, a task that cannot be executed is simply dropped.

    4. In ThreadPoolExecutor.DiscardOldestPolicy, if the executor is not shut down, the task at the head of the work queue is dropped, and then execution is retried (which can fail again, causing this to be repeated.)

  3. You can implement a custom Thread factory for the below use cases:

    1. To set a more descriptive thread name
    2. To set thread daemon status
    3. To set thread priority

GitHub - List commits by author

Just add ?author=<emailaddress> or ?author=<githubUserName> to the url when viewing the "commits" section of a repo.

Checkout multiple git repos into same Jenkins workspace

Checking out more than one repo at a time in a single workspace is possible with Jenkins + Git Plugin (maybe only in more recent versions?).

In section "Source-Code-Management", do not select "Git", but "Multiple SCMs" and add several git repositories.

Be sure that in all but one you add as an "Additional behavior" the action "Check out to a sub-directory" and specify an individual subdirectory.

Run bash command on jenkins pipeline

I'm sure that the above answers work perfectly. However, I had the difficulty of adding the double quotes as my bash lines where closer to 100. So, the following way helped me. (In a nutshell, no double quotes around each line of the shell)

Also, when I had "bash '''#!/bin/bash" within steps, I got the following error java.lang.NoSuchMethodError: No such DSL method '**bash**' found among steps

pipeline {
    agent none

    stages {

        stage ('Hello') {
            agent any

            steps {
                echo 'Hello, '

                sh '''#!/bin/bash

                    echo "Hello from bash"
                    echo "Who I'm $SHELL"
                '''
            }
        }
    }
}

The result of the above execution is

enter image description here

How to replace negative numbers in Pandas Data Frame by zero

Another clean option that I have found useful is pandas.DataFrame.mask which will "replace values where the condition is true."

Create the DataFrame:

In [2]: import pandas as pd

In [3]: df = pd.DataFrame({'a': [0, -1, 2], 'b': [-3, 2, 1]})

In [4]: df
Out[4]: 
   a  b
0  0 -3
1 -1  2
2  2  1

Replace negative numbers with 0:

In [5]: df.mask(df < 0, 0)
Out[5]: 
   a  b
0  0  0
1  0  2
2  2  1

Or, replace negative numbers with NaN, which I frequently need:

In [7]: df.mask(df < 0)
Out[7]: 
     a    b
0  0.0  NaN
1  NaN  2.0
2  2.0  1.0

AJAX Mailchimp signup form integration

For anyone looking for a solution on a modern stack:

import jsonp from 'jsonp';
import queryString from 'query-string';

// formData being an object with your form data like:
// { EMAIL: '[email protected]' }

jsonp(`//YOURMAILCHIMP.us10.list-manage.com/subscribe/post-json?u=YOURMAILCHIMPU&${queryString.stringify(formData)}`, { param: 'c' }, (err, data) => {
  console.log(err);
  console.log(data);
});

don't fail jenkins build if execute shell fails

Another one answer with some tips, can be helpful for somebody:

remember to separate your commands with the following rule:

command1 && command2 - means, that command2 will be executed, only if command1 success

command1 ; command2 - means, that command 2 will be executed despite on result of command1

for example:

String run_tests = sh(script: "set +e && cd ~/development/tests/ && gmake test ;set -e;echo 0 ", returnStdout: true).trim()
println run_tests 

will be executed successfully with set -e and echo 0 commands if gmake test failed (your tests failed), while the following code snipped:

String run_tests = sh(script: "set +e && cd ~/development/tests/ && gmake test && set -e && echo 0 ", returnStdout: true).trim()
println run_tests 

a bit wrong and commands set -e and echo 0 in&& gmake test && set -e && echo 0 will be skipped, with the println run_tests statement, because failed gmake test will abort the jenkins build. As workaround you can switch to returnStatus:true, but then you will miss the output from your command.

WPF User Control Parent

DependencyObject parent = ExVisualTreeHelper.FindVisualParent<UserControl>(this);

Flexbox not working in Internet Explorer 11

I have tested a full layout using flexbox it contains header, footer, main body with left, center and right panels and the panels can contain menu items or footer and headers that should scroll. Pretty complex

IE11 and even IE EDGE have some problems displaying the flex content but it can be overcome. I have tested it in most browsers and it seems to work.

Some fixed i have applies are IE11 height bug, Adding height:100vh and min-height:100% to the html/body. this also helps to not have to set height on container in the dom. Also make the body/html a flex container. Otherwise IE11 will compress the view.

html,body {
    display: flex;
    flex-flow:column nowrap;
    height:100vh; /* fix IE11 */
    min-height:100%; /* fix IE11 */  
}

A fix for IE EDGE that overflows the flex container: overflow:hidden on main flex container. if you remove the overflow, IE EDGE wil push the content out of the viewport instead of containing it inside the flex main container.

main{
    flex:1 1 auto;
    overflow:hidden; /* IE EDGE overflow fix */  
}

enter image description here

You can see my testing and example on my codepen page. I remarked the important css parts with the fixes i have applied and hope someone finds it useful.

Go to first line in a file in vim?

Go to first line

  • :1

  • or Ctrl + Home

Go to last line

  • :%

  • or Ctrl + End


Go to another line (f.i. 27)

  • :27

[Works On VIM 7.4 (2016) and 8.0 (2018)]

How to express a NOT IN query with ActiveRecord/Rails?

You can try something like:

Topic.find(:all, :conditions => ['forum_id not in (?)', @forums.map(&:id)])

You might need to do @forums.map(&:id).join(','). I can't remember if Rails will the argument into a CSV list if it is enumerable.

You could also do this:

# in topic.rb
named_scope :not_in_forums, lambda { |forums| { :conditions => ['forum_id not in (?)', forums.select(&:id).join(',')] }

# in your controller 
Topic.not_in_forums(@forums)

Declare a const array

For my needs I define static array, instead of impossible const and it works: public static string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };

C# refresh DataGridView when updating or inserted on another form

my datagridview is editonEnter mode . so it refresh only after i leave cell or after i revisit and exit cell twice.

to trigger this iimedately . i unfocus from datagridview . then refocus it.

 this.SelectNextControl(dgv1,true,true,false,true);    
 Application.DoEvents();    //this does magic
 dgv1.Focus();

anaconda/conda - install a specific package version

To install a specific package:

conda install <pkg>=<version>

eg:

conda install matplotlib=1.4.3

java.lang.ClassNotFoundException: com.fasterxml.jackson.annotation.JsonInclude$Value

this is a version problem change version > 2.4 to 1.9 solve it

<dependency>  
<groupId>com.fasterxml.jackson.jaxrs</groupId>  
<artifactId>jackson-jaxrs-xml-provider</artifactId>  
<version>2.4.1</version>  

to

<dependency>  
<groupId>org.codehaus.jackson</groupId>  
<artifactId>jackson-mapper-asl</artifactId>  
<version>1.9.4</version>  

C# Select elements in list as List of string

List<string> empnames = emplist.Select(e => e.Ename).ToList();

This is an example of Projection in Linq. Followed by a ToList to resolve the IEnumerable<string> into a List<string>.

Alternatively in Linq syntax (head compiled):

var empnamesEnum = from emp in emplist 
                   select emp.Ename;
List<string> empnames = empnamesEnum.ToList();

Projection is basically representing the current type of the enumerable as a new type. You can project to anonymous types, another known type by calling constructors etc, or an enumerable of one of the properties (as in your case).

For example, you can project an enumerable of Employee to an enumerable of Tuple<int, string> like so:

var tuples = emplist.Select(e => new Tuple<int, string>(e.EID, e.Ename));

Set focus on <input> element

I'm having same scenario, this worked for me but i'm not having the "hide/show" feature you have. So perhaps you could first check if you get the focus when you have the field always visible, and then try to solve why does not work when you change visibility (probably that's why you need to apply a sleep or a promise)

To set focus, this is the only change you need to do:

your Html mat input should be:

<input #yourControlName matInput>

in your TS class, reference like this in the variables section (

export class blabla...
    @ViewChild("yourControlName") yourControl : ElementRef;

Your button it's fine, calling:

  showSearch(){
       ///blabla... then finally:
       this.yourControl.nativeElement.focus();
}

and that's it. You can check this solution on this post that I found, so thanks to --> https://codeburst.io/focusing-on-form-elements-the-angular-way-e9a78725c04f

How do I write the 'cd' command in a makefile?

To change dir

foo: 
    $(MAKE) -C mydir

multi:
    $(MAKE) -C / -C my-custom-dir   ## Equivalent to /my-custom-dir

How to install the JDK on Ubuntu Linux

Please follow this step to install oracle JDK

  1. Download oracle JDK (Eg Java 8 for 64 bit machine jdk-8u241-linux-x64.tar.gz ) from Oracle
  2. Extract the *.tar.gz in home directory or preferred location
  3. Set Environment variable Eg Open terminal type sudo gedit ~/.bashrc Add following line at end of .bashrc file

    export JAVA_HOME=/opt/jdk1.8.0_241 #add your own jdk location

    export PATH=$PATH:$JAVA_HOME/bin

  4. Save and exit
  5. Finally source the .bashrc Eg source ~/.bashrc
  6. Now open a new terminal type jdk -version

what is the difference between uint16_t and unsigned short int incase of 64 bit processor?

uint16_t is guaranteed to be a unsigned integer that is 16 bits large

unsigned short int is guaranteed to be a unsigned short integer, where short integer is defined by the compiler (and potentially compiler flags) you are currently using. For most compilers for x86 hardware a short integer is 16 bits large.

Also note that per the ANSI C standard only the minimum size of 16 bits is defined, the maximum size is up to the developer of the compiler

Minimum Type Limits

Any compiler conforming to the Standard must also respect the following limits with respect to the range of values any particular type may accept. Note that these are lower limits: an implementation is free to exceed any or all of these. Note also that the minimum range for a char is dependent on whether or not a char is considered to be signed or unsigned.

Type Minimum Range

signed char     -127 to +127
unsigned char      0 to 255
short int     -32767 to +32767
unsigned short int 0 to 65535

Word-wrap in an HTML table

Tables wrap by default, so make sure the display of the table cells are table-cell:

td {
   display: table-cell;
}

Bubble Sort Homework

def bubble_sorted(arr:list):
    while True:
        for i in range(0,len(arr)-1):
            count = 0
            if arr[i] > arr[i+1]:
                count += 1
                arr[i], arr[i+1] = arr[i+1], arr[i]
        if count == 0:
            break
    return arr
arr = [30,20,80,40,50,10,60,70,90]
print(bubble_sorted(arr))
#[20, 30, 40, 50, 10, 60, 70, 80, 90]

Converting Varchar Value to Integer/Decimal Value in SQL Server

You are getting arithmetic overflow. this means you are trying to make a conversion impossible to be made. This error is thrown when you try to make a conversion and the destiny data type is not enough to convert the origin data. For example:

If you try to convert 100.52 to decimal(4,2) you will get this error. The number 100.52 requires 5 positions and 2 of them are decimal.

Try to change the decimal precision to something like 16,2 or higher. Try with few records first then use it to all your select.

openssl s_client using a proxy

You can use proxytunnel:

proxytunnel -p yourproxy:8080 -d www.google.com:443 -a 7000

and then you can do this:

openssl s_client -connect localhost:7000 -showcerts

Hope this can help you!

Write HTML string in JSON

You can, once you escape the HTML correctly. This page shows what needs to be done.

If using PHP, you could use json_encode()

Hope this helps :)

Terminating a Java Program

  1. System.exit() is a method that causes JVM to exit.
  2. return just returns the control to calling function.
  3. return 8 will return control and value 8 to calling method.

What does this error mean: "error: expected specifier-qualifier-list before 'type_name'"?

this error basically comes when you use the object before using it.

Getting the IP address of the current machine using Java

Since my system (like so many other systems) had various network interfaces.InetAddress.getLocalHost() or Inet4Address.getLocalHost() simply returned one that I did not desire. Therefore I had to use this naive approach.

InetAddress[] allAddresses = Inet4Address.getAllByName("YourComputerHostName");
        InetAddress desiredAddress;
        //In order to find the desired Ip to be routed by other modules (WiFi adapter)
        for (InetAddress address :
                allAddresses) {
            if (address.getHostAddress().startsWith("192.168.2")) {
                desiredAddress = address;
            }
        }
// Use the desired address for whatever purpose.

Just be careful that in this approach I already knew that my desired IP address is in 192.168.2 subnet.

Continue For loop

For i=1 To 10
    Do 
        'Do everything in here and

        If I_Dont_Want_Finish_This_Loop Then
            Exit Do
        End If 

        'Of course, if I do want to finish it,
        'I put more stuff here, and then...

    Loop While False 'quit after one loop
Next i

Swift how to sort array of custom objects by property value

If you are going to be sorting this array in more than one place, it may make sense to make your array type Comparable.

class MyImageType: Comparable, Printable {
    var fileID: Int

    // For Printable
    var description: String {
        get {
            return "ID: \(fileID)"
        }
    }

    init(fileID: Int) {
        self.fileID = fileID
    }
}

// For Comparable
func <(left: MyImageType, right: MyImageType) -> Bool {
    return left.fileID < right.fileID
}

// For Comparable
func ==(left: MyImageType, right: MyImageType) -> Bool {
    return left.fileID == right.fileID
}

let one = MyImageType(fileID: 1)
let two = MyImageType(fileID: 2)
let twoA = MyImageType(fileID: 2)
let three = MyImageType(fileID: 3)

let a1 = [one, three, two]

// return a sorted array
println(sorted(a1)) // "[ID: 1, ID: 2, ID: 3]"

var a2 = [two, one, twoA, three]

// sort the array 'in place'
sort(&a2)
println(a2) // "[ID: 1, ID: 2, ID: 2, ID: 3]"

Constant pointer vs Pointer to constant

Referncing from This Thread

Constant Pointers

Lets first understand what a constant pointer is. A constant pointer is a pointer that cannot change the address its holding. In other words, we can say that once a constant pointer points to a variable then it cannot point to any other variable.

A constant pointer is declared as follows :
<type of pointer> * const <name of pointer>
An example declaration would look like :
int * const ptr;
Lets take a small code to illustrate these type of pointers :

#include<stdio.h>

int main(void)
{
    int var1 = 0, var2 = 0;
    int *const ptr = &var1;
    ptr = &var2;
    printf("%d\n", *ptr);

    return 0;
} 

In the above example :

  • We declared two variables var1 and var2
  • A constant pointer ‘ptr’ was declared and made to point var1
  • Next, ptr is made to point var2.
  • Finally, we try to print the value ptr is pointing to.

Pointer to Constant

As evident from the name, a pointer through which one cannot change the value of variable it points is known as a pointer to constant. These type of pointers can change the address they point to but cannot change the value kept at those address.

A pointer to constant is defined as : const <type of pointer>* <name of pointer> An example of definition could be : const int* ptr; Lets take a small code to illustrate a pointer to a constant :

 #include<stdio.h>

int main(void)
{
    int var1 = 0;
    const int* ptr = &var1;
    *ptr = 1;
    printf("%d\n", *ptr);

    return 0;
} 

In the code above :

  • We defined a variable var1 with value 0
  • we defined a pointer to a constant which points to variable var1
  • Now, through this pointer we tried to change the value of var1
  • Used printf to print the new value.

Find a class somewhere inside dozens of JAR files?

#!/bin/bash

pattern=$1
shift

for jar in $(find $* -type f -name "*.jar")
do
  match=`jar -tvf $jar | grep $pattern`
  if [ ! -z "$match" ]
  then
    echo "Found in: $jar"
    echo "$match"
  fi
done

What is the use of the @Temporal annotation in Hibernate?

This annotation must be specified for persistent fields or properties of type java.util.Date and java.util.Calendar. It may only be specified for fields or properties of these types.

The Temporal annotation may be used in conjunction with the Basic annotation, the Id annotation, or the ElementCollection annotation (when the element collection value is of such a temporal type.

In plain Java APIs, the temporal precision of time is not defined. When dealing with temporal data, you might want to describe the expected precision in database. Temporal data can have DATE, TIME, or TIMESTAMP precision (i.e., the actual date, only the time, or both). Use the @Temporal annotation to fine tune that.

The temporal data is the data related to time. For example, in a content management system, the creation-date and last-updated date of an article are temporal data. In some cases, temporal data needs precision and you want to store precise date/time or both (TIMESTAMP) in database table.

The temporal precision is not specified in core Java APIs. @Temporal is a JPA annotation that converts back and forth between timestamp and java.util.Date. It also converts time-stamp into time. For example, in the snippet below, @Temporal(TemporalType.DATE) drops the time value and only preserves the date.

@Temporal(TemporalType.DATE)
private java.util.Date creationDate;

As per javadocs,

Annotation to declare an appropriate {@code TemporalType} on query method parameters. Note that this annotation can only be used on parameters of type {@link Date} with default TemporalType.DATE

[Information above collected from various sources]

How to create a .gitignore file

Here is a one liner version of linux "touch" in Windows

c:\<folder>\break > .gitignore

that will create a blank .gitignore file where you can edit and add items to ignore

C:\Users\test>dir .gitignore
 Volume in drive C is Windows
 Volume Serial Number is 9223-E93F

 Directory of C:\Users\test

18/04/2019  02:23 PM                 0 .gitignore
               1 File(s)              0 bytes
               0 Dir(s)  353,009,770,496 bytes free

C:\Users\test>

Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?

* This is a simple answer since I'm a beginner in Java *

Consider there are three classes X,Y and Z.

So we are inheriting like X extends Y, Z And both Y and Z is having a method alphabet() with same return type and arguments. This method alphabet() in Y says to display first alphabet and method alphabet in Z says display last alphabet. So here comes ambiguity when alphabet() is called by X. Whether it says to display first or last alphabet??? So java is not supporting multiple inheritance. In case of Interfaces, consider Y and Z as interfaces. So both will contain the declaration of method alphabet() but not the definition. It won't tell whether to display first alphabet or last alphabet or anything but just will declare a method alphabet(). So there is no reason to raise the ambiguity. We can define the method with anything we want inside class X.

So in a word, in Interfaces definition is done after implementation so no confusion.

How can I run PowerShell with the .NET 4 runtime?

If you don't want to modify the registry or app.config files, an alternate way is to create a simple .NET 4 console app that mimicks what PowerShell.exe does and hosts the PowerShell ConsoleShell.

See Option 2 – Hosting Windows PowerShell yourself

First, add a reference to the System.Management.Automation and Microsoft.PowerShell.ConsoleHost assemblies which can be found under %programfiles%\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0

Then use the following code:

using System;
using System.Management.Automation.Runspaces;
using Microsoft.PowerShell;

namespace PSHostCLRv4
{
    class Program
    {
        static int Main(string[] args)
        {
            var config = RunspaceConfiguration.Create();
                return ConsoleShell.Start(
                config,
                "Windows PowerShell - Hosted on CLR v4\nCopyright (C) 2010 Microsoft Corporation. All rights reserved.",
                "",
                args
            );
        }
    }
}

Can't connect to Postgresql on port 5432

You have to edit postgresql.conf file and change line with 'listen_addresses'.

This file you can find in the /etc/postgresql/9.3/main directory.

Default Ubuntu config have allowed only localhost (or 127.0.0.1) interface, which is sufficient for using, when every PostgreSQL client work on the same computer, as PostgreSQL server. If you want connect PostgreSQL server from other computers, you have change this config line in this way:

listen_addresses = '*'

Then you have edit pg_hba.conf file, too. In this file you have set, from which computers you can connect to this server and what method of authentication you can use. Usually you will need similar line:

host    all         all         192.168.1.0/24        md5

Please, read comments in this file...

EDIT:

After the editing postgresql.conf and pg_hba.conf you have to restart postgresql server.

EDIT2: Highlited configuration files.

Why std::cout instead of simply cout?

You probably had using namespace std; before in your code you did in class. That explicitly tells the precompiler to look for the symbols in std, which means you don't need to std::. Though it is good practice to std::cout instead of cout so you explicitly invoke std::cout every time. That way if you are using another library that redefines cout, you still have the std::cout behavior instead of some other custom behavior.

When is the @JsonProperty property used and what is it used for?

well for what its worth now... JsonProperty is ALSO used to specify getter and setter methods for the variable apart from usual serialization and deserialization. For example suppose you have a payload like this:

{
  "check": true
}

and a Deserializer class:

public class Check {

  @JsonProperty("check")    // It is needed else Jackson will look got getCheck method and will fail
  private Boolean check;

  public Boolean isCheck() {
     return check;
  }
}

Then in this case JsonProperty annotation is neeeded. However if you also have a method in the class

public class Check {

  //@JsonProperty("check")    Not needed anymore
  private Boolean check;

  public Boolean getCheck() {
     return check;
  }
}

Have a look at this documentation too: http://fasterxml.github.io/jackson-annotations/javadoc/2.3.0/com/fasterxml/jackson/annotation/JsonProperty.html

How to solve "The directory is not empty" error when running rmdir command in a batch script?

I can think of the following possible causes:

  1. there are files or subdirectories which need higher permissions
  2. there are files in use, not only by WSearch, but maybe by your virus scanner or anything else

For 1.) you can try runas /user:Administrator in order to get higher privileges or start the batch file as administrator via context menu. If that doesn't help, maybe even the administrator doesn't have the rights. Then you need to take over the ownership of the directory.

For 2.) download Process Explorer, click Find/Find handle or DLL... or press Ctrl+F, type the name of the directory and find out who uses it. Close the application which uses the directory, if possible.

How does HTTP_USER_AGENT work?

http://www.useragentstring.com/

Visit that page, it'll give you a good explanation of each element of your user agent.

Mozilla:

MozillaProductSlice. Claims to be a Mozilla based user agent, which is only true for Gecko browsers like Firefox and Netscape. For all other user agents it means 'Mozilla-compatible'. In modern browsers, this is only used for historical reasons. It has no real meaning anymore

Executing <script> injected by innerHTML after AJAX call

I used this code, it is working fine

var arr = MyDiv.getElementsByTagName('script')
for (var n = 0; n < arr.length; n++)
    eval(arr[n].innerHTML)//run script inside div

TLS 1.2 not working in cURL

TLS 1.2 is only supported since OpenSSL 1.0.1 (see the Major version releases section), you have to update your OpenSSL.

It is not necessary to set the CURLOPT_SSLVERSION option. The request involves a handshake which will apply the newest TLS version both server and client support. The server you request is using TLS 1.2, so your php_curl will use TLS 1.2 (by default) as well if your OpenSSL version is (or newer than) 1.0.1.

The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'

In my case this was actually a symptom of the server, hosted on AWS, lacking an IP for the external network. It would attempt to download namespaces from springframework.org and fail to make a connection.

Check if a property exists in a class

I got this error: "Type does not contain a definition for GetProperty" when tying the accepted answer.

This is what i ended up with:

using System.Reflection;

if (productModel.GetType().GetTypeInfo().GetDeclaredProperty(propertyName) != null)
{

}

How to highlight a current menu item?

Most important for me was not to change at all the bootstrap default code. Here it is my menu controller that search for menu options and then add the behavior we want.

file: header.js
function HeaderCtrl ($scope, $http, $location) {
  $scope.menuLinkList = [];
  defineFunctions($scope);
  addOnClickEventsToMenuOptions($scope, $location);
}

function defineFunctions ($scope) {
  $scope.menuOptionOnClickFunction = function () {
    for ( var index in $scope.menuLinkList) {
      var link = $scope.menuLinkList[index];
      if (this.hash === link.hash) {
        link.parentElement.className = 'active';
      } else {
        link.parentElement.className = '';
      }
    }
  };
}

function addOnClickEventsToMenuOptions ($scope, $location) {
  var liList = angular.element.find('li');
  for ( var index in liList) {
    var liElement = liList[index];
    var link = liElement.firstChild;
    link.onclick = $scope.menuOptionOnClickFunction;
    $scope.menuLinkList.push(link);
    var path = link.hash.replace("#", "");
    if ($location.path() === path) {
      link.parentElement.className = 'active';
    }
  }
}

     <script src="resources/js/app/header.js"></script>
 <div class="navbar navbar-fixed-top" ng:controller="HeaderCtrl">
    <div class="navbar-inner">
      <div class="container-fluid">
        <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
          <span class="icon-bar"></span> <span class="icon-bar"></span> 
<span     class="icon-bar"></span>
        </button>
        <a class="brand" href="#"> <img src="resources/img/fom-logo.png"
          style="width: 80px; height: auto;">
        </a>
        <div class="nav-collapse collapse">
          <ul class="nav">
            <li><a href="#/platforms">PLATFORMS</a></li>
            <li><a href="#/functionaltests">FUNCTIONAL TESTS</a></li>
          </ul> 
        </div>
      </div>
    </div>
  </div>

If statement in select (ORACLE)

SELECT (CASE WHEN ISSUE_DIVISION = ISSUE_DIVISION_2 THEN 1 ELSE 0 END) AS ISSUES
    --  <add any columns to outer select from inner query> 
  FROM
 (  -- your query here --
   select 'CARAT Issue Open' issue_comment, ...., ..., 
          substr(gcrs.stream_name,1,case when instr(gcrs.stream_name,' (')=0 then 100 else  instr(gcrs.stream_name,' (')-1 end) ISSUE_DIVISION,
          case when gcrs.STREAM_NAME like 'NON-GT%' THEN 'NON-GT' ELSE gcrs.STREAM_NAME END as ISSUE_DIVISION_2
     from ....
    where UPPER(ISSUE_STATUS) like '%OPEN%'
 )
 WHERE... -- optional --

Find distance between two points on map using Google Map API V2

THIS IS THE EASY AND PERFECT CODE FOR DURATION AND DISTANCE FINDING

  • Step 1;(add this and sync in your gradle)

    compile 'com.android.volley:volley:1.0.0'  
    
  • Step 2:(write this in your trigger method)

    public void clicked(View view) throws JSONException {  
    
         JSONObject locationJsonObject = new JSONObject();
                locationJsonObject.put("origin", "54.406505,18.67708");
                locationJsonObject.put("destination", "54.446251,18.570993");
                LatlngCalc(locationJsonObject);
    }
    
  • Step 3:(Copy & Paste in your class)

    private void LatlngCalc(JSONObject locationJsonObject) throws JSONException {
    
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
        String url = "http://maps.googleapis.com/maps/api/distancematrix/" +
                    "json?origins=" + locationJsonObject.getString("origin") + "&destinations=" + locationJsonObject.getString("destination") + "&mode=driving&" +
                    "language=en-EN&sensor=false";
    
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
    
                        mTextView.setText("Response is: " + response.substring(0, 500));
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mTextView.setText("That didn't work!");
            }
        });
        queue.add(stringRequest);  
    }
    

Get div's offsetTop positions in React

You may be encouraged to use the Element.getBoundingClientRect() method to get the top offset of your element. This method provides the full offset values (left, top, right, bottom, width, height) of your element in the viewport.

Check the John Resig's post describing how helpful this method is.

How to view user privileges using windows cmd?

Use whoami /priv command to list all the user privileges.

UICollectionView current visible cell index

converting @Anthony's answer to Swift 3.0 worked perfectly for me:

func scrollViewDidScroll(_ scrollView: UIScrollView) {

    var visibleRect = CGRect()
    visibleRect.origin = yourCollectionView.contentOffset
    visibleRect.size = yourCollectionView.bounds.size
    let visiblePoint = CGPoint(x: CGFloat(visibleRect.midX), y: CGFloat(visibleRect.midY))
    let visibleIndexPath: IndexPath? = yourCollectionView.indexPathForItem(at: visiblePoint)
    print("Visible cell's index is : \(visibleIndexPath?.row)!")
}

javascript: pause setTimeout();

I don't think you'll find anything better than clearTimeout. Anyway, you can always schedule another timeout later, instead 'resuming' it.

C++ How do I convert a std::chrono::time_point to long and back

time_point objects only support arithmetic with other time_point or duration objects.

You'll need to convert your long to a duration of specified units, then your code should work correctly.

React - How to get parameter value from query string?

In React Router v4 only withRoute is correct way

You can get access to the history object’s properties and the closest 's match via the withRouter higher-order component. withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.

import React from 'react'
import PropTypes from 'prop-types'
import { withRouter } from 'react-router'

// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  }

  render() {
    const { match, location, history } = this.props

    return (
      <div>You are now at {location.pathname}</div>
    )
  }
}

// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation)

https://reacttraining.com/react-router/web/api/withRouter

what does it mean "(include_path='.:/usr/share/pear:/usr/share/php')"?

Many developers include files by pointing to a remote URL, even if the file is within the local system. For example:

<php include("http://example.com/includes/example_include.php"); ?>

With allow_url_include disabled, this method does not work. Instead, the file must be included with a local path, and there are three methods of doing this:

By using a relative path, such as ../includes/example_include.php. By using an absolute path (also known as relative-from-root), such as /home/username/example.com/includes/example_include.php.

By using the PHP environment variable $_SERVER['DOCUMENT_ROOT'], which returns the absolute path to the web root directory. This is by far the best (and most portable) solution. The following example shows the environment variable in action.

Example Include

<?php include($_SERVER['DOCUMENT_ROOT']."/includes/example_include.php"); ?>

How to make a background 20% transparent on Android

All hex value from 100% to 0% alpha, You can set any color with alpha values mentioned below. e.g #FAFFFFFF(ARRGGBB)

100% — FF
99% — FC
98% — FA
97% — F7
96% — F5
95% — F2
94% — F0
93% — ED
92% — EB
91% — E8
90% — E6
89% — E3
88% — E0
87% — DE
86% — DB
85% — D9
84% — D6
83% — D4
82% — D1
81% — CF
80% — CC
79% — C9
78% — C7
77% — C4
76% — C2
75% — BF
74% — BD
73% — BA
72% — B8
71% — B5
70% — B3
69% — B0
68% — AD
67% — AB
66% — A8
65% — A6
64% — A3
63% — A1
62% — 9E
61% — 9C
60% — 99
59% — 96
58% — 94
57% — 91
56% — 8F
55% — 8C
54% — 8A
53% — 87
52% — 85
51% — 82
50% — 80
49% — 7D
48% — 7A
47% — 78
46% — 75
45% — 73
44% — 70
43% — 6E
42% — 6B
41% — 69
40% — 66
39% — 63
38% — 61
37% — 5E
36% — 5C
35% — 59
34% — 57
33% — 54
32% — 52
31% — 4F
30% — 4D
29% — 4A
28% — 47
27% — 45
26% — 42
25% — 40
24% — 3D
23% — 3B
22% — 38
21% — 36
20% — 33
19% — 30
18% — 2E
17% — 2B
16% — 29
15% — 26
14% — 24
13% — 21
12% — 1F
11% — 1C
10% — 1A
9% — 17
8% — 14
7% — 12
6% — 0F
5% — 0D
4% — 0A
3% — 08
2% — 05
1% — 03
0% — 00

Build error, This project references NuGet

This problem appeared for me when I was creating folders in the filesystem (not in my solution) and moved some projects around.

Turns out that the package paths are relative from the csproj files. So I had to change the "HintPath" of my references:

<Reference Include="EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
    <HintPath>..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll</HintPath>
    <Private>True</Private>
</Reference>

To:

<Reference Include="EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
    <HintPath>..\..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll</HintPath>
    <Private>True</Private>
</Reference>

Notice the double "..\" in 'HintPath'.

I also had to change my error conditions, for example I had to change:

<Error Condition="!Exists('..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props'))" />

To:

<Error Condition="!Exists('..\..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props'))" />

Again, notice the double "..\".

Changing the interval of SetInterval while it's running

Make new function:

// set Time interval
$("3000,18000").Multitimeout();

jQuery.fn.extend({
    Multitimeout: function () {
        var res = this.selector.split(",");
        $.each(res, function (index, val) { setTimeout(function () { 
            //...Call function
            temp();
        }, val); });
        return true;
    }
});

function temp()
{
    alert();
}

How to set selected item of Spinner by value, not by position?

If you set an XML array to the spinner in the XML layout you can do this

final Spinner hr = v.findViewById(R.id.chr);
final String[] hrs = getResources().getStringArray(R.array.hours);
if(myvalue!=null){
   for (int x = 0;x< hrs.length;x++){
      if(myvalue.equals(hrs[x])){
         hr.setSelection(x);
      }
   }
}

Hashcode and Equals for Hashset

You should read up on how to ensure that you've implemented equals and hashCode properly. This is a good starting point: What issues should be considered when overriding equals and hashCode in Java?

Downloading images with node.js

Building on the above, if anyone needs to handle errors in the write/read streams, I used this version. Note the stream.read() in case of a write error, it's required so we can finish reading and trigger close on the read stream.

var download = function(uri, filename, callback){
  request.head(uri, function(err, res, body){
    if (err) callback(err, filename);
    else {
        var stream = request(uri);
        stream.pipe(
            fs.createWriteStream(filename)
                .on('error', function(err){
                    callback(error, filename);
                    stream.read();
                })
            )
        .on('close', function() {
            callback(null, filename);
        });
    }
  });
};

Get the closest number out of an array

The most efficient would be a binary search. However even simple solutions can exit when the next number is a further match from the current. Nearly all solutions here are not taking into account that the array is ordered and iterating though the whole thing :/

_x000D_
_x000D_
const closest = (orderedArray, value, valueGetter = item => item) =>_x000D_
  orderedArray.find((item, i) =>_x000D_
    i === orderedArray.length - 1 ||_x000D_
    Math.abs(value - valueGetter(item)) < Math.abs(value - valueGetter(orderedArray[i + 1])));_x000D_
_x000D_
var data = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362];_x000D_
_x000D_
console.log('21 -> 2', closest(data, 21) === 2);_x000D_
console.log('22 -> 42', closest(data, 22) === 42); // equidistant between 2 and 42, select highest_x000D_
console.log('23 -> 42', closest(data, 23) === 42);_x000D_
console.log('80 -> 82', closest(data, 80) === 82);
_x000D_
_x000D_
_x000D_

This can be run on non-primitives too e.g. closest(data, 21, item => item.age)

Change find to findIndex to return the index in the array.

Check if input value is empty and display an alert

$('#submit').click(function(){
   if($('#myMessage').val() == ''){
      alert('Input can not be left blank');
   }
});

Update

If you don't want whitespace also u can remove them using jQuery.trim()

Description: Remove the whitespace from the beginning and end of a string.

$('#submit').click(function(){
   if($.trim($('#myMessage').val()) == ''){
      alert('Input can not be left blank');
   }
});

jquery multiple checkboxes array

You can use $.map() (or even the .map() function that operates on a jQuery object) to get an array of checked values. The unary (+) operator will cast the string to a number

var arr = $.map($('input:checkbox:checked'), function(e,i) {
    return +e.value;
});

console.log(arr);

Here's an example

Use NSInteger as array index

According to the error message, you declared myLoc as a pointer to an NSInteger (NSInteger *myLoc) rather than an actual NSInteger (NSInteger myLoc). It needs to be the latter.

How to flush output after each `echo` call?

This is my code: (work for PHP7)

private function closeConnection()
{
    @apache_setenv('no-gzip', 1);
    @ini_set('zlib.output_compression', 0);
    @ini_set('implicit_flush', 1);

    ignore_user_abort(true);
    set_time_limit(0);

    ob_start();
    // do initial processing here
    echo json_encode(['ans' => true]);

    header('Connection: close');
    header('Content-Length: ' . ob_get_length());
    ob_end_flush();
    ob_flush();
    flush();
}

"Could not find bundler" error

I resolved it by deleting Gemfile.lock and gem install bundler:2.2.0

Java - Abstract class to contain variables?

Of course. The whole idea of abstract classes is that they can contain some behaviour or data which you require all sub-classes to contain. Think of the simple example of WheeledVehicle - it should have a numWheels member variable. You want all sub classes to have this variable. Remember that abstract classes are a very useful feature when developing APIs, as they can ensure that people who extend your API won't break it.

How to create a cron job using Bash automatically without the interactive editor?

For a nice quick and dirty creation/replacement of a crontab from with a BASH script, I used this notation:

crontab <<EOF
00 09 * * 1-5 echo hello
EOF

reading HttpwebResponse json response, C#

I'd use RestSharp - https://github.com/restsharp/RestSharp

Create class to deserialize to:

public class MyObject {
    public string Id { get; set; }
    public string Text { get; set; }
    ...
}

And the code to get that object:

RestClient client = new RestClient("http://whatever.com");
RestRequest request = new RestRequest("path/to/object");
request.AddParameter("id", "123");

// The above code will make a request URL of 
// "http://whatever.com/path/to/object?id=123"
// You can pick and choose what you need

var response = client.Execute<MyObject>(request);

MyObject obj = response.Data;

Check out http://restsharp.org/ to get started.

Call web service in excel

Yes You Can!

I worked on a project that did that (see comment). Unfortunately no code samples from that one, but googling revealed these:

How you can integrate data from several Web services using Excel and VBA

STEP BY STEP: Consuming Web Services through VBA (Excel or Word)

VBA: Consume Soap Web Services

Generate .pem file used to set up Apple Push Notifications

Thanks! to all above answers. I hope you have a .p12 file. Now, open terminal write following command. Set terminal to the path where you have put .12 file.

$ openssl pkcs12 -in yourCertifcate.p12 -out pemAPNSCert.pem -nodes
Enter Import Password: <Just enter your certificate password>
MAC verified OK

Now your .pem file is generated.

Verify .pem file First, open the .pem in a text editor to view its content. The certificate content should be in format as shown below. Make sure the pem file contains both Certificate content(from BEGIN CERTIFICATE to END CERTIFICATE) as well as Certificate Private Key (from BEGIN PRIVATE KEY to END PRIVATE KEY) :

> Bag Attributes
>     friendlyName: Apple Push Services:<Bundle ID>
>     localKeyID: <> subject=<>
> -----BEGIN CERTIFICATE-----
> 
> <Certificate Content>
> 
> -----END CERTIFICATE----- Bag Attributes
>     friendlyName: <>
>     localKeyID: <> Key Attributes: <No Attributes>
> -----BEGIN PRIVATE KEY-----
> 
> <Certificate Private Key>
> 
> -----END PRIVATE KEY-----

Also, you check the validity of the certificate by going to SSLShopper Certificate Decoder and paste the Certificate Content (from BEGIN CERTIFICATE to END CERTIFICATE) to get all the info about the certificate as shown below:

enter image description here

How to see if a directory exists or not in Perl?

Use -d (full list of file tests)

if (-d "cgi-bin") {
    # directory called cgi-bin exists
}
elsif (-e "cgi-bin") {
    # cgi-bin exists but is not a directory
}
else {
    # nothing called cgi-bin exists
}

As a note, -e doesn't distinguish between files and directories. To check if something exists and is a plain file, use -f.

Setting UILabel text to bold

Use attributed string:

// Define attributes
let labelFont = UIFont(name: "HelveticaNeue-Bold", size: 18)
let attributes :Dictionary = [NSFontAttributeName : labelFont]

// Create attributed string
var attrString = NSAttributedString(string: "Foo", attributes:attributes)
label.attributedText = attrString

You need to define attributes.

Using attributed string you can mix colors, sizes, fonts etc within one text

Can a variable number of arguments be passed to a function?

Adding to the other excellent posts.

Sometimes you don't want to specify the number of arguments and want to use keys for them (the compiler will complain if one argument passed in a dictionary is not used in the method).

def manyArgs1(args):
  print args.a, args.b #note args.c is not used here

def manyArgs2(args):
  print args.c #note args.b and .c are not used here

class Args: pass

args = Args()
args.a = 1
args.b = 2
args.c = 3

manyArgs1(args) #outputs 1 2
manyArgs2(args) #outputs 3

Then you can do things like

myfuns = [manyArgs1, manyArgs2]
for fun in myfuns:
  fun(args)

Biggest advantage to using ASP.Net MVC vs web forms

Web forms also gain from greater maturity and support from third party control providers like Telerik.

What does <a href="#" class="view"> mean?

The href is probably generated in a javascript function. For example with jQuery:

$(function() {
    $('a.view').attr('href', 'http://www.google.com');
});

How to get number of rows inserted by a transaction

In case you need further info for your log/audit you can OUTPUT clause: This way, not only you keep the number of rows affected, but also what records.

As an example of the Output Clause during inserts: SQL Server list of insert identities

DECLARE @InsertedIDs table(ID int);

INSERT INTO YourTable
    OUTPUT INSERTED.ID
        INTO @InsertedIDs 
    SELECT ...

HTH

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

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

1 - Open Powershell (as Admin)

2 - Run:

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

3 - Run:

Install-PackageProvider -Name NuGet

The author is Niels Weistra: Microsoft Forum

C++ inheritance - inaccessible base?

By default, inheritance is private. You have to explicitly use public:

class Bar : public Foo

Create a temporary table in a SELECT statement without a separate CREATE TABLE

CREATE TEMPORARY TABLE IF NOT EXISTS table2 AS (SELECT * FROM table1)

From the manual found at http://dev.mysql.com/doc/refman/5.7/en/create-table.html

You can use the TEMPORARY keyword when creating a table. A TEMPORARY table is visible only to the current session, and is dropped automatically when the session is closed. This means that two different sessions can use the same temporary table name without conflicting with each other or with an existing non-TEMPORARY table of the same name. (The existing table is hidden until the temporary table is dropped.) To create temporary tables, you must have the CREATE TEMPORARY TABLES privilege.

Android Studio error: "Environment variable does not point to a valid JVM installation"

I solved this problem by making sure that the value of JAVA_HOME was the folder location in English

C:\Program Files\Java\jdk1.8.0_31

rather than the folder location that one can see/explorer browse in my Windows7 - Portuguese installation

C:\Programas\Java\jdk1.8.0_31

What is the best method to merge two PHP objects?

foreach($objectA as $k => $v) $objectB->$k = $v;

Detect current device with UI_USER_INTERFACE_IDIOM() in Swift

FYI, I have used UI_USER_INTERFACE_IDIOM() for my app written in Swift. The app can be compiled well with XCode 6.3.1 without any warning on that command, runs well on Simulator (with any selected devices) and on all my real devices (iPhone, iPad) with iOS versions from 7.1 to 8.3.

However, the app crashed on Apple reviewers' devices (and was refused). That took me few days to detect the problem with few more re-uploads to iTunes Connect.

Now I use UIDevice.currentDevice().userInterfaceIdiom instead and my app can survive from such crashes.

Type List vs type ArrayList in Java

For example you might decide a LinkedList is the best choice for your application, but then later decide ArrayList might be a better choice for performance reason.

Use:

List list = new ArrayList(100); // will be better also to set the initial capacity of a collection 

Instead of:

ArrayList list = new ArrayList();

For reference:

enter image description here

(posted mostly for Collection diagram)

Sum function in VBA

Range("A1").Function="=SUM(Range(Cells(2,1),Cells(3,2)))"

won't work because worksheet functions (when actually used on a worksheet) don't understand Range or Cell

Try

Range("A1").Formula="=SUM(" & Range(Cells(2,1),Cells(3,2)).Address(False,False) & ")"

Check an integer value is Null in c#

Nullable<T> (or ?) exposes a HasValue flag to denote if a value is set or the item is null.

Also, nullable types support ==:

if (Age == null)

The ?? is the null coalescing operator and doesn't result in a boolean expression, but a value returned:

int i = Age ?? 0;

So for your example:

if (age == null || age == 0)

Or:

if (age.GetValueOrDefault(0) == 0)

Or:

if ((age ?? 0) == 0)

Or ternary:

int i = age.HasValue ? age.Value : 0;

MySQL: Fastest way to count number of rows

This is the best query able to get the fastest results.

SELECT SQL_CALC_FOUND_ROWS 1 FROM `orders`;
SELECT FOUND_ROWS();

In my benchmark test: 0.448s

enter image description here

This query takes 4.835s

SELECT SQL_CALC_FOUND_ROWS * FROM `orders`;
SELECT FOUND_ROWS();

enter image description here

count * takes 25.675s

SELECT count(*) FROM `orders`;

enter image description here

permission denied - php unlink

in addition to all the answers that other friends have , if somebody who is looking this post is looking for a way to delete a "Folder" not a "file" , should take care that Folders must delete by php rmdir() function and if u want to delete a "Folder" by unlink() , u will encounter with a wrong Warning message that says "permission denied"

however u can make folders & files by mkdir() but the way u delete folders (rmdir()) is different from the way you delete files(unlink())

eventually as a fact:

in many programming languages, any permission related error may not directly means an actual permission issue

for example, if you want to readSync a file that doesn't exist with node fs module you will encounter a wrong EPERM error

Spring Boot yaml configuration for a list of strings

My guess is, that the @Value can not cope with "complex" types. You can go with a prop class like this:

@Component
@ConfigurationProperties('ignore')
class IgnoreSettings {
    List<String> filenames
}

Please note: This code is Groovy - not Java - to keep the example short! See the comments for tips how to adopt.

See the complete example https://github.com/christoph-frick/so-springboot-yaml-string-list

Is it possible to format an HTML tooltip (title attribute)?

Not sure if it works with all browsers or 3rd party tools, but I have had success just specifying "\n" in tooltips for newline, works with dhtmlx in at least ie11, firefox and chrome

for (var key in oPendingData) {
    var obj = oPendingData[key];
    this.cells(sRowID, nColInd).cell.title += "\n" + obj["ChangeUser"] + ": " + obj[sCol];
}

Python: SyntaxError: keyword can't be an expression

Using the Elastic search DSL API, you may hit the same error with

s = Search(using=client, index="my-index") \
    .query("match", category.keyword="Musician")

You can solve it by doing:

s = Search(using=client, index="my-index") \
    .query({"match": {"category.keyword":"Musician/Band"}})

Python - Using regex to find multiple matches and print them out

Using regexes for this purpose is the wrong approach. Since you are using python you have a really awesome library available to extract parts from HTML documents: BeautifulSoup.

How to get "wc -l" to print just the number of lines without file name?

Comparison of Techniques

I had a similar issue attempting to get a character count without the leading whitespace provided by wc, which led me to this page. After trying out the answers here, the following are the results from my personal testing on Mac (BSD Bash). Again, this is for character count; for line count you'd do wc -l. echo -n omits the trailing line break.

FOO="bar"
echo -n "$FOO" | wc -c                          # "       3"    (x)
echo -n "$FOO" | wc -c | bc                     # "3"           (v)
echo -n "$FOO" | wc -c | tr -d ' '              # "3"           (v)
echo -n "$FOO" | wc -c | awk '{print $1}'       # "3"           (v)
echo -n "$FOO" | wc -c | cut -d ' ' -f1         # "" for -f < 8 (x)
echo -n "$FOO" | wc -c | cut -d ' ' -f8         # "3"           (v)
echo -n "$FOO" | wc -c | perl -pe 's/^\s+//'    # "3"           (v)
echo -n "$FOO" | wc -c | grep -ch '^'           # "1"           (x)
echo $( printf '%s' "$FOO" | wc -c )            # "3"           (v)

I wouldn't rely on the cut -f* method in general since it requires that you know the exact number of leading spaces that any given output may have. And the grep one works for counting lines, but not characters.

bc is the most concise, and awk and perl seem a bit overkill, but they should all be relatively fast and portable enough.

Also note that some of these can be adapted to trim surrounding whitespace from general strings, as well (along with echo `echo $FOO`, another neat trick).

How do I fix the indentation of selected lines in Visual Studio

For the Mac users.

For selecting all of the code in the document => cmd+A

For formatting selected code => cmd+K, cmd+F

What is the difference between canonical name, simple name and class name in Java Class?

In addition to Nick Holt's observations, I ran a few cases for Array data type:

//primitive Array
int demo[] = new int[5];
Class<? extends int[]> clzz = demo.getClass();
System.out.println(clzz.getName());
System.out.println(clzz.getCanonicalName());
System.out.println(clzz.getSimpleName());       

System.out.println();


//Object Array
Integer demo[] = new Integer[5]; 
Class<? extends Integer[]> clzz = demo.getClass();
System.out.println(clzz.getName());
System.out.println(clzz.getCanonicalName());
System.out.println(clzz.getSimpleName());

Above code snippet prints:

[I
int[]
int[]

[Ljava.lang.Integer;
java.lang.Integer[]
Integer[]

Open a link in browser with java button?

Use the Desktop#browse(URI) method. It opens a URI in the user's default browser.

public static boolean openWebpage(URI uri) {
    Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
    if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
        try {
            desktop.browse(uri);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return false;
}

public static boolean openWebpage(URL url) {
    try {
        return openWebpage(url.toURI());
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    return false;
}