Programs & Examples On #Salt creation

How to set default values for Angular 2 component properties?

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

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

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

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

  @Input() newCar: car = {};

  constructor() {}

  ngOnInit(): void {

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

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

SQL Developer is returning only the date, not the time. How do I fix this?

Can you try this?

Go to Tools> Preferences > Database > NLS and set the Date Format as MM/DD/YYYY HH24:MI:SS

How can I add a class to a DOM element in JavaScript?

It is also worth taking a look at:

var el = document.getElementById('hello');
if(el) {
    el.className += el.className ? ' someClass' : 'someClass';
}

PostgreSQL: days/months/years between two dates

SELECT
  AGE('2012-03-05', '2010-04-01'),
  DATE_PART('year', AGE('2012-03-05', '2010-04-01')) AS years,
  DATE_PART('month', AGE('2012-03-05', '2010-04-01')) AS months,
  DATE_PART('day', AGE('2012-03-05', '2010-04-01')) AS days;

This will give you full years, month, days ... between two dates:

          age          | years | months | days
-----------------------+-------+--------+------
 1 year 11 mons 4 days |     1 |     11 |    4

More detailed datediff information.

Cannot implicitly convert type 'string' to 'System.Threading.Tasks.Task<string>'

The listed return type of the method is Task<string>. You're trying to return a string. They are not the same, nor is there an implicit conversion from string to Task<string>, hence the error.

You're likely confusing this with an async method in which the return value is automatically wrapped in a Task by the compiler. Currently that method is not an async method. You almost certainly meant to do this:

private async Task<string> methodAsync() 
{
    await Task.Delay(10000);
    return "Hello";
}

There are two key changes. First, the method is marked as async, which means the return type is wrapped in a Task, making the method compile. Next, we don't want to do a blocking wait. As a general rule, when using the await model always avoid blocking waits when you can. Task.Delay is a task that will be completed after the specified number of milliseconds. By await-ing that task we are effectively performing a non-blocking wait for that time (in actuality the remainder of the method is a continuation of that task).

If you prefer a 4.0 way of doing it, without using await , you can do this:

private Task<string> methodAsync() 
{
    return Task.Delay(10000)
        .ContinueWith(t => "Hello");
}

The first version will compile down to something that is more or less like this, but it will have some extra boilerplate code in their for supporting error handling and other functionality of await we aren't leveraging here.

If your Thread.Sleep(10000) is really meant to just be a placeholder for some long running method, as opposed to just a way of waiting for a while, then you'll need to ensure that the work is done in another thread, instead of the current context. The easiest way of doing that is through Task.Run:

private Task<string> methodAsync() 
{
    return Task.Run(()=>
        {
            SomeLongRunningMethod();
            return "Hello";
        });
}

Or more likely:

private Task<string> methodAsync() 
{
    return Task.Run(()=>
        {
            return SomeLongRunningMethodThatReturnsAString();
        });
}

Fixing a systemd service 203/EXEC failure (no such file or directory)

If that is a copy/paste from your script, you've permuted this line:

#!/usr/env/bin bash

There's no #!/usr/env/bin, you meant #!/usr/bin/env.

What is the regex for "Any positive integer, excluding 0"

^[1-9]*$ is the simplest I can think of

JavaScript DOM remove element

Using Node.removeChild() does the job for you, simply use something like this:

var leftSection = document.getElementById('left-section');
leftSection.parentNode.removeChild(leftSection);

In DOM 4, the remove method applied, but there is a poor browser support according to W3C:

The method node.remove() is implemented in the DOM 4 specification. But because of poor browser support, you should not use it.

But you can use remove method if you using jQuery...

$('#left-section').remove(); //using remove method in jQuery

Also in new frameworks like you can use conditions to remove an element, for example *ngIf in Angular and in React, rendering different views, depends on the conditions...

Why does this AttributeError in python occur?

The default namespace in Python is "__main__". When you use import scipy, Python creates a separate namespace as your module name. The rule in Pyhton is: when you want to call an attribute from another namespaces you have to use the fully qualified attribute name.

Where and how is the _ViewStart.cshtml layout file linked?

From ScottGu's blog:

Starting with the ASP.NET MVC 3 Beta release, you can now add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:

The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default:

Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).

Important: Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set. For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops. Or if we were building a CMS system or common shared app that is used across multiple customers we could select different layouts to use depending on the customer (or their role) when accessing the site.

This enables a lot of UI flexibility. It also allows you to more easily write view logic once, and avoid repeating it in multiple places.

Also see this.


In a more general sense this ability of MVC framework to "know" about _Viewstart.cshtml is called "Coding by convention".

Convention over configuration (also known as coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility. The phrase essentially means a developer only needs to specify unconventional aspects of the application. For example, if there's a class Sale in the model, the corresponding table in the database is called “sales” by default. It is only if one deviates from this convention, such as calling the table “products_sold”, that one needs to write code regarding these names.

Wikipedia

There's no magic to it. Its just been written into the core codebase of the MVC framework and is therefore something that MVC "knows" about. That why you don't find it in the .config files or elsewhere; it's actually in the MVC code. You can however override to alter or null out these conventions.

Ajax passing data to php script

You are sending a POST AJAX request so use $albumname = $_POST['album']; on your server to fetch the value. Also I would recommend you writing the request like this in order to ensure proper encoding:

$.ajax({  
    type: 'POST',  
    url: 'test.php', 
    data: { album: this.title },
    success: function(response) {
        content.html(response);
    }
});

or in its shorter form:

$.post('test.php', { album: this.title }, function() {
    content.html(response);
});

and if you wanted to use a GET request:

$.ajax({  
    type: 'GET',
    url: 'test.php', 
    data: { album: this.title },
    success: function(response) {
        content.html(response);
    }
});

or in its shorter form:

$.get('test.php', { album: this.title }, function() {
    content.html(response);
});

and now on your server you wil be able to use $albumname = $_GET['album'];. Be careful though with AJAX GET requests as they might be cached by some browsers. To avoid caching them you could set the cache: false setting.

Sort divs in jQuery based on attribute 'data-sort'?

I made this into a jQuery function:

jQuery.fn.sortDivs = function sortDivs() {
    $("> div", this[0]).sort(dec_sort).appendTo(this[0]);
    function dec_sort(a, b){ return ($(b).data("sort")) < ($(a).data("sort")) ? 1 : -1; }
}

So you have a big div like "#boo" and all your little divs inside of there:

$("#boo").sortDivs();

You need the "? 1 : -1" because of a bug in Chrome, without this it won't sort more than 10 divs! http://blog.rodneyrehm.de/archives/14-Sorting-Were-Doing-It-Wrong.html

List all employee's names and their managers by manager name using an inner join

You have an incorrect ON clause at the join, this works:

inner join Employees m on e.mgr = m.EmpId;

The mgr column references the EmpId column.

DEMO

Installing Python 3 on RHEL

I see all the answers as either asking to compile python3 from code or installing the binary RPM package. Here is another answer to enable EPEL (Extra Packages for Enterprise Linux) and then install python using yum. Steps for RHEL 7.5 (Maipo)

yum install wget –y
wget https://dl.fedoraproject.org/pub/epel/7/x86_64/Packages/e/epel-release-7-XX.noarch.rpm # Verify actual RPM name by browsing dir over browser
rpm –ivh epel-*.rpm
yum install python36

Also see link

How to disable Google Chrome auto update?

For Mac OS, you'll have to remove permissions, but leave the directory

$ sudo chown root:wheel GoogleSoftwareUpdate
$ sudo chmod = GoogleSoftwareUpdate

Rounding Bigdecimal values with 2 Decimal Places

You may try this:

public static void main(String[] args) {
    BigDecimal a = new BigDecimal("10.12345");
    System.out.println(toPrecision(a, 2));
}

private static BigDecimal toPrecision(BigDecimal dec, int precision) {
    String plain = dec.movePointRight(precision).toPlainString();
    return new BigDecimal(plain.substring(0, plain.indexOf("."))).movePointLeft(precision);
}

OUTPUT:

10.12

How to keep environment variables when using sudo

For individual variables you want to make available on a one off basis you can make it part of the command.

sudo http_proxy=$http_proxy wget "http://stackoverflow.com"

How can I get a character in a string by index?

Do you mean like this

int index = 2;
string s = "hello";
Console.WriteLine(s[index]);

string also implements IEnumberable<char> so you can also enumerate it like this

foreach (char c in s)
    Console.WriteLine(c);

Nested ng-repeat

If you have a big nested JSON object and using it across several screens, you might face performance issues in page loading. I always go for small individual JSON objects and query the related objects as lazy load only where they are required.

you can achieve it using ng-init

<td class="lectureClass" ng-repeat="s in sessions" ng-init='presenters=getPresenters(s.id)'>
      {{s.name}}
      <div class="presenterClass" ng-repeat="p in presenters">
          {{p.name}}
      </div>
</td> 

The code on the controller side should look like below

$scope.getPresenters = function(id) {
    return SessionPresenters.get({id: id});
};

While the API factory is as follows:

angular.module('tryme3App').factory('SessionPresenters', function ($resource, DateUtils) {

        return $resource('api/session.Presenters/:id', {}, {
            'query': { method: 'GET', isArray: true},
            'get': {
                method: 'GET', isArray: true
            },
            'update': { method:'PUT' }
        });
    });

How to prevent going back to the previous activity?

My suggestion would be to finish the activity that you don't want the users to go back to. For instance, in your sign in activity, right after you call startActivity, call finish(). When the users hit the back button, they will not be able to go to the sign in activity because it has been killed off the stack.

How to use find command to find all files with extensions from list?

find -E /path/to -regex ".*\.(jpg|gif|png|jpeg)" > log

The -E saves you from having to escape the parens and pipes in your regex.

changing kafka retention period during runtime

log.retention.hours is a property of a broker which is used as a default value when a topic is created. When you change configurations of currently running topic using kafka-topics.sh, you should specify a topic-level property.

A topic-level property for log retention time is retention.ms.

From Topic-level configuration in Kafka 0.8.1 documentation:

  • Property: retention.ms
  • Default: 7 days
  • Server Default Property: log.retention.minutes
  • Description: This configuration controls the maximum time we will retain a log before we will discard old log segments to free up space if we are using the "delete" retention policy. This represents an SLA on how soon consumers must read their data.

So the correct command depends on the version. Up to 0.8.2 (although docs still show its use up to 0.10.1) use kafka-topics.sh --alter and after 0.10.2 (or perhaps from 0.9.0 going forward) use kafka-configs.sh --alter

$ bin/kafka-topics.sh --zookeeper zk.yoursite.com --alter --topic as-access --config retention.ms=86400000
 

You can check whether the configuration is properly applied with the following command.

$ bin/kafka-topics.sh --describe --zookeeper zk.yoursite.com --topic as-access

Then you will see something like below.

Topic:as-access  PartitionCount:3  ReplicationFactor:3  Configs:retention.ms=86400000

How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception

The others are right about making the driver JAR available to your servlet container. My comment was meant to suggest that you verify from the command line whether the driver itself is intact.

Rather than an empty main(), try something like this, adapted from the included documentation:

public class LoadDriver {
    public static void main(String[] args) throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
    }
}

On my platform, I'd do this:

$ ls mysql-connector-java-5.1.12-bin.jar 
mysql-connector-java-5.1.12-bin.jar
$ javac LoadDriver.java 
$ java -cp mysql-connector-java-5.1.12-bin.jar:. LoadDriver

On your platform, you need to use ; as the path separator, as discussed here and here.

How to upgrade pip3?

pip3 install --upgrade pip worked for me

How can I confirm a database is Oracle & what version it is using SQL?

If your instance is down, you are look for version information in alert.log

Or another crude way is to look into Oracle binary, If DB in hosted on Linux, try strings on Oracle binary.

strings -a $ORACLE_HOME/bin/oracle |grep RDBMS | grep RELEASE

Converting Secret Key into a String and Vice Versa

You don't want to use .toString().

Notice that SecretKey inherits from java.security.Key, which itself inherits from Serializable. So the key here (no pun intended) is to serialize the key into a ByteArrayOutputStream, get the byte[] array and store it into the db. The reverse process would be to get the byte[] array off the db, create a ByteArrayInputStream offf the byte[] array, and deserialize the SecretKey off it...

... or even simpler, just use the .getEncoded() method inherited from java.security.Key (which is a parent interface of SecretKey). This method returns the encoded byte[] array off Key/SecretKey, which you can store or retrieve from the database.

This is all assuming your SecretKey implementation supports encoding. Otherwise, getEncoded() will return null.

edit:

You should look at the Key/SecretKey javadocs (available right at the start of a google page):

http://download.oracle.com/javase/6/docs/api/java/security/Key.html

Or this from CodeRanch (also found with the same google search):

http://www.coderanch.com/t/429127/java/java/Convertion-between-SecretKey-String-or

Node package ( Grunt ) installed but not available

  1. Instala grunt de manera global: sudo npm install -g grunt-cli --unsafe-perm=true --allow-root

  2. Try to run grunt.

  3. If you have this message:

Warning:

You need to have Ruby and Sass installed and in your PATH for this task to work.

More info: https://github.com/gruntjs/grunt-contrib-sass

Used --force, continuing.

3.1. Check that you have ruby installed (mac, you should have it): ruby -v

crop text too long inside div

You can use:

overflow:hidden;

to hide the text outside the zone.

Note that it may cut the last letter (so a part of the last letter will still be displayed). A nicer way is to display an ellipsis at the end. You can do it by using text-overflow:

overflow: hidden;
white-space: nowrap; /* Don't forget this one */
text-overflow: ellipsis;

python-dev installation error: ImportError: No module named apt_pkg

  1. Check your default Python 3 version:
python --version
Python 3.7.5
  1. cd into /usr/lib/python3/dist-packages and check the apt_pkg.* files. You will find that there is none for your default Python version:
ll apt_pkg.*
apt_pkg.cpython-36m-x86_64-linux-gnu.so
  1. Create the symlink:
sudo ln -s apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.cpython-37m-x86_64- linux-gnu.so 

Close Android Application

I don't think you can do it in one line of code. Try opening your activities with startActivityForResult. As the result you can pass something like a CLOSE_FLAG, which will inform your parent activity that its child activity has finished.

That said, you should probably read this answer.

Exit codes in Python

From the documentation for sys.exit:

The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0-127, and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors.

One example where exit codes are used are in shell scripts. In Bash you can check the special variable $? for the last exit status:

me@mini:~$ python -c ""; echo $?
0
me@mini:~$ python -c "import sys; sys.exit(0)"; echo $?
0
me@mini:~$ python -c "import sys; sys.exit(43)"; echo $?
43

Personally I try to use the exit codes I find in /usr/include/asm-generic/errno.h (on a Linux system), but I don't know if this is the right thing to do.

Where is Android Studio layout preview?

For those struggling in Android Studio 3.6:

enter image description here

Exception Error c0000005 in VC++

I was having the same problem while running bulk tests for an assignment. Turns out when I relocated some iostream operations (printing to console) from class constructor to a method in class it was solved.

I assume it was something to do with iostream manipulations in the constructor.

Here is the fix:

// Before
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {
    cout << "Some text I was printing.." << endl;
};


// After
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {

};

Please feel free to explain more what the error is behind the scenes since it goes beyond my cpp knowledge.

javascript regular expression to check for IP addresses

/^(?!.*\.$)((?!0\d)(1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$/

Full credit to oriadam. I would have commented below his/her answer to suggest the double zero change I made, but I do not have enough reputation here yet...

change:

Connect to SQL Server database from Node.js

msnodesql is working out great for me. Here is a sample:

var mssql = require('msnodesql'), 
    express = require('express'),
    app = express(),
    nconf = require('nconf')

nconf.env()
     .file({ file: 'config.json' });

var conn = nconf.get("SQL_CONN");   
var conn_str = "Driver={SQL Server Native Client 11.0};Server=server.name.here;Database=Product;Trusted_Connection={Yes}";

app.get('/api/brands', function(req, res){
    var data = [];
    var jsonObject = {};    

    mssql.open(conn_str, function (err, conn) {
        if (err) {
            console.log("Error opening the connection!");
            return;
        }
        conn.queryRaw("dbo.storedproc", function (err, results) {
        if(err) {
                   console.log(err);
                   res.send(500, "Cannot retrieve records.");
                }
       else {
             //res.json(results);

             for (var i = 0; i < results.rows.length; i++) {
                 var jsonObject = new Object()
                 for (var j = 0; j < results.meta.length; j++) { 

                    paramName = results.meta[j].name;
                    paramValue = results.rows[i][j]; 
                    jsonObject[paramName] = paramValue;

                    }
                    data.push(jsonObject);  //This is a js object we are jsonizing not real json until res.send             
            } 

                res.send(data);

            }       
        });
    });
});

Composer - the requested PHP extension mbstring is missing from your system

I set the PHPRC variable and uncommented zend_extension=php_opcache.dll in php.ini and all works well.

commands not found on zsh

For me just restarting my terminal seemed to fix the issue.

How do I read image data from a URL in Python?

I use the requests library. It seems to be more robust.

from PIL import Image
import requests
from StringIO import StringIO

response = requests.get(url)
img = Image.open(StringIO(response.content))

java.math.BigInteger cannot be cast to java.lang.Integer

java.lang.Integer is not a super class of BigInteger. Both BigInteger and Integer do inherit from java.lang.Number, so you could cast to a java.lang.Number.

See the java docs http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Number.html

How can I tell jackson to ignore a property for which I don't have control over the source code?

I had a similar issue, but it was related to Hibernate's bi-directional relationships. I wanted to show one side of the relationship and programmatically ignore the other, depending on what view I was dealing with. If you can't do that, you end up with nasty StackOverflowExceptions. For instance, if I had these objects

public class A{
  Long id;
  String name;
  List<B> children;
}

public class B{
  Long id;
  A parent;
}

I would want to programmatically ignore the parent field in B if I were looking at A, and ignore the children field in A if I were looking at B.

I started off using mixins to do this, but that very quickly becomes horrible; you have so many useless classes laying around that exist solely to format data. I ended up writing my own serializer to handle this in a cleaner way: https://github.com/monitorjbl/json-view.

It allows you programmatically specify what fields to ignore:

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(JsonView.class, new JsonViewSerializer());
mapper.registerModule(module);

List<A> list = getListOfA();
String json = mapper.writeValueAsString(JsonView.with(list)
    .onClass(B.class, match()
        .exclude("parent")));

It also lets you easily specify very simplified views through wildcard matchers:

String json = mapper.writeValueAsString(JsonView.with(list)
    .onClass(A.class, match()
        .exclude("*")
         .include("id", "name")));

In my original case, the need for simple views like this was to show the bare minimum about the parent/child, but it also became useful for our role-based security. Less privileged views of objects needed to return less information about the object.

All of this comes from the serializer, but I was using Spring MVC in my app. To get it to properly handle these cases, I wrote an integration that you can drop in to existing Spring controller classes:

@Controller
public class JsonController {
  private JsonResult json = JsonResult.instance();
  @Autowired
  private TestObjectService service;

  @RequestMapping(method = RequestMethod.GET, value = "/bean")
  @ResponseBody
  public List<TestObject> getTestObject() {
    List<TestObject> list = service.list();

    return json.use(JsonView.with(list)
        .onClass(TestObject.class, Match.match()
            .exclude("int1")
            .include("ignoredDirect")))
        .returnValue();
  }
}

Both are available on Maven Central. I hope it helps someone else out there, this is a particularly ugly problem with Jackson that didn't have a good solution for my case.

ng-mouseover and leave to toggle item using mouse in angularjs

A little late here, but I've found this to be a common problem worth a custom directive to handle. Here's how that might look:

  .directive('toggleOnHover', function(){
    return {
      restrict: 'A',
      link: link
    };

    function link(scope, elem, attrs){
      elem.on('mouseenter', applyToggleExp);
      elem.on('mouseleave', applyToggleExp);

      function applyToggleExp(){
        scope.$apply(attrs.toggleOnHover);
      }
    }

  });

You can use it like this:

<li toggle-on-hover="editableProp = !editableProp">edit</li> 

The declared package does not match the expected package ""

I had this problem - the other classes within my package were fine, but one class had the error against it. There was nothing wrong with the package declaration.

I fixed it by doing refactor->move and moved the class to another package temporarily, then refactor->move back to the original package.

Showing an image from console in Python

In Xterm-compatible terminals, you can show the image directly in the terminal. See my answer to "PPM image to ASCII art in Python"

ImageMagick's "logo:" image in Xterm (show picture in new tab for full size viewing)

Java JRE 64-bit download for Windows?

Might this be the download you are looking for?

  1. Go to the Java SE Downloads Page.
  2. Scroll down a tad look for the main table with the header of "Java Platform, Standard Edition"
  3. Click the JRE Download Button (JRE is the runtime component. JDK is the developer's kit).
  4. Select the appropriate download (all platforms and 32/64 bit downloads are listed)

How do I subscribe to all topics of a MQTT broker

Subscribing to # gives you a subscription to everything except for topics that start with a $ (these are normally control topics anyway).

It is better to know what you are subscribing to first though, of course, and note that some broker configurations may disallow subscribing to # explicitly.

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

What you want is this (actually the exact inverse of the currently accepted answer):

git checkout email
git merge --strategy-option=theirs staging  

What this does is:

  • email branch files will now be exactly the same as staging branch
  • email branch's history will be maintained
  • staging branch's history will be added to email history

As added value, if you don't want all of staging branch's history, you can use squash to summarize it into a single commit message.

git checkout email
git merge --squash --strategy-option=theirs staging  
git commit -m "Single commit message for squash branch's history here'

So in summary, what this second version does is:

  • email branch files will now be exactly the same as staging branch
  • email branch's history will be maintained
  • A single commit will be added on top of email branch's history. This commit will represent ALL the changes that took place in the staging branch

What is unit testing and how do you do it?

What...

A methodology for automaticaly testing code against a battery of tests, designed to enforce desired outcomes and manage change.

A "unit" in this sense is the smallest atomic component of the code that makes sense to test, typically a method of some class for example. Part of this process is building up stub objects (or "mocks") which allow you to work with a unit as an independant object.

How...

Almost always, the process of unit-testing is built into an IDE (or through extensions) such that it executes the tests with every compile. A number of frameworks exist for assisting the creation of unit tests (and indeed mock objcts), often named fooUnit (cf. jUnit, xUnit, nUnit). These frameworks provide a formalised way to create tests.

As a process, test driven development (TDD) is often the motivation for unit testing (but unit testing does not require TDD) which supposes that the tests are a part of the spec definition, and therefore requires that they are written first, with code only written to "solve" these tests.

When...

Almost always. Very small, throwaway projects may not be worth it, but only if you're quite sure they really are throwaway. In theory every object orientated program is unit testable, but some design pattrns make this difficult. Notoriously, the singleton pattern is problematic, where conversely dependancy injection frameworks are very much unit testing oriented.

Measuring execution time of a function in C++

  • It is a very easy to use method in C++11.
  • We can use std::chrono::high_resolution_clock from header
  • We can write a method to print the method execution time in a much readable form.

For example, to find the all the prime numbers between 1 and 100 million, it takes approximately 1 minute and 40 seconds. So the execution time get printed as:

Execution Time: 1 Minutes, 40 Seconds, 715 MicroSeconds, 715000 NanoSeconds

The code is here:

#include <iostream>
#include <chrono>

using namespace std;
using namespace std::chrono;

typedef high_resolution_clock Clock;
typedef Clock::time_point ClockTime;

void findPrime(long n, string file);
void printExecutionTime(ClockTime start_time, ClockTime end_time);

int main()
{
    long n = long(1E+8);  // N = 100 million

    ClockTime start_time = Clock::now();

    // Write all the prime numbers from 1 to N to the file "prime.txt"
    findPrime(n, "C:\\prime.txt"); 

    ClockTime end_time = Clock::now();

    printExecutionTime(start_time, end_time);
}

void printExecutionTime(ClockTime start_time, ClockTime end_time)
{
    auto execution_time_ns = duration_cast<nanoseconds>(end_time - start_time).count();
    auto execution_time_ms = duration_cast<microseconds>(end_time - start_time).count();
    auto execution_time_sec = duration_cast<seconds>(end_time - start_time).count();
    auto execution_time_min = duration_cast<minutes>(end_time - start_time).count();
    auto execution_time_hour = duration_cast<hours>(end_time - start_time).count();

    cout << "\nExecution Time: ";
    if(execution_time_hour > 0)
    cout << "" << execution_time_hour << " Hours, ";
    if(execution_time_min > 0)
    cout << "" << execution_time_min % 60 << " Minutes, ";
    if(execution_time_sec > 0)
    cout << "" << execution_time_sec % 60 << " Seconds, ";
    if(execution_time_ms > 0)
    cout << "" << execution_time_ms % long(1E+3) << " MicroSeconds, ";
    if(execution_time_ns > 0)
    cout << "" << execution_time_ns % long(1E+6) << " NanoSeconds, ";
}

How to kill all processes matching a name?

If you want to execute the output of a command, you can put it inside $(...), however for your specific task take a look at the killall and pkill commands.

Pointer vs. Reference

Pass by const reference unless there is a reason you wish to change/keep the contents you are passing in.

This will be the most efficient method in most cases.

Make sure you use const on each parameter you do not wish to change, as this not only protects you from doing something stupid in the function, it gives a good indication to other users what the function does to the passed in values. This includes making a pointer const when you only want to change whats pointed to...

Refresh Page C# ASP.NET

Use:

Response.Redirect(Request.RawUrl, true);

Android SDK location should not contain whitespace, as this cause problems with NDK tools

Simply....If you are not using NDK, there is no problem at all. On the other this is just warning not an error. With warning you can go ahead but not errors. Any it's better to adjust the whitespaces. E.g if your SDK is at C:\program file\Android studio. There is a whitespaces "program file". There are 2 simple methods: 1. Remove the whitespaces 2. Install at another location which don't have whitespaces.

CSS background image alt attribute

Background images sure can present data! In fact, this is often recommended where presenting visual icons is more compact and user-friendly than an equivalent list of text blurbs. Any use of image sprites can benefit from this approach.

It is quite common for hotel listings icons to display amenities. Imagine a page which listed 50 hotel and each hotel had 10 amenities. A CSS Sprite would be perfect for this sort of thing -- better user experience because it's faster. But how do you implement ALT tags for these images? Example site.

The answer is that they don't use alt text at all, but instead use the title attribute on the containing div.

HTML

<div class="hotwire-fitness" title="Fitness Centre"></div>

CSS

.hotwire-fitness {
    float: left;
    margin-right: 5px;
    background: url(/prostyle/images/new_amenities.png) -71px 0;
    width: 21px;
    height: 21px;
}

According to the W3C (see links above), the title attribute serves much of the same purpose as the alt attribute

Title

Values of the title attribute may be rendered by user agents in a variety of ways. For instance, visual browsers frequently display the title as a "tool tip" (a short message that appears when the pointing device pauses over an object). Audio user agents may speak the title information in a similar context. For example, setting the attribute on a link allows user agents (visual and non-visual) to tell users about the nature of the linked resource:

alt

The alt attribute is defined in a set of tags (namely, img, area and optionally for input and applet) to allow you to provide a text equivalent for the object.

A text equivalent brings the following benefits to your website and its visitors in the following common situations:

  • nowadays, Web browsers are available in a very wide variety of platforms with very different capacities; some cannot display images at all or only a restricted set of type of images; some can be configured to not load images. If your code has the alt attribute set in its images, most of these browsers will display the description you gave instead of the images
  • some of your visitors cannot see images, be they blind, color-blind, low-sighted; the alt attribute is of great help for those people that can rely on it to have a good idea of what's on your page
  • search engine bots belong to the two above categories: if you want your website to be indexed as well as it deserves, use the alt attribute to make sure that they won't miss important sections of your pages.

What is a good pattern for using a Global Mutex in C#?

A solution (for WPF) without WaitOne because it can cause an AbandonedMutexException. This solution uses the Mutex constructor that returns the createdNew boolean to check if the mutex is already created. It also uses the GetType().GUID so renaming an executable doesn't allow multiple instances.

Global vs local mutex see note in: https://docs.microsoft.com/en-us/dotnet/api/system.threading.mutex?view=netframework-4.8

private Mutex mutex;
private bool mutexCreated;

public App()
{
    string mutexId = $"Global\\{GetType().GUID}";
    mutex = new Mutex(true, mutexId, out mutexCreated);
}

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);
    if (!mutexCreated)
    {
        MessageBox.Show("Already started!");
        Shutdown();
    }
}

Because Mutex implements IDisposable it is released automatically but for completeness call dispose:

protected override void OnExit(ExitEventArgs e)
{
    base.OnExit(e);
    mutex.Dispose();
}

Move everything into a base class and add the allowEveryoneRule from the accepted answer. Also added ReleaseMutex though it doesn't look like it's really needed because it is released automatically by the OS (what if the application crashes and never calls ReleaseMutex would you need to reboot?).

public class SingleApplication : Application
{
    private Mutex mutex;
    private bool mutexCreated;

    public SingleApplication()
    {
        string mutexId = $"Global\\{GetType().GUID}";

        MutexAccessRule allowEveryoneRule = new MutexAccessRule(
            new SecurityIdentifier(WellKnownSidType.WorldSid, null),
            MutexRights.FullControl, 
            AccessControlType.Allow);
        MutexSecurity securitySettings = new MutexSecurity();
        securitySettings.AddAccessRule(allowEveryoneRule);

        // initiallyOwned: true == false + mutex.WaitOne()
        mutex = new Mutex(initiallyOwned: true, mutexId, out mutexCreated, securitySettings);        
    }

    protected override void OnExit(ExitEventArgs e)
    {
        base.OnExit(e);
        if (mutexCreated)
        {
            try
            {
                mutex.ReleaseMutex();
            }
            catch (ApplicationException ex)
            {
                MessageBox.Show(ex.Message, ex.GetType().FullName, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        mutex.Dispose();
    }

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        if (!mutexCreated)
        {
            MessageBox.Show("Already started!");
            Shutdown();
        }
    }
}

Angular 2 - How to navigate to another route using this.router.parent.navigate('/about')?

You should use

this.router.parent.navigate(['/About']);

As well as specifying the route path, you can also specify your route's name:

{ path:'/About', name: 'About',   ... }

this.router.parent.navigate(['About']);

Redirecting to authentication dialog - "An error occurred. Please try again later"

If your all code is working properly then to remove such type of error go to Facebook Developers Apps and disable sandbox mode.

Checking if a folder exists using a .bat file

For a file:

if exist yourfilename (
  echo Yes 
) else (
  echo No
)

Replace yourfilename with the name of your file.

For a directory:

if exist yourfoldername\ (
  echo Yes 
) else (
  echo No
)

Replace yourfoldername with the name of your folder.

A trailing backslash (\) seems to be enough to distinguish between directories and ordinary files.

Changing a specific column name in pandas DataFrame

What about?

df.columns.values[2] = "new_name"

What is the difference between a HashMap and a TreeMap?

HashMap is implemented by Hash Table while TreeMap is implemented by Red-Black tree. The main difference between HashMap and TreeMap actually reflect the main difference between a Hash and a Binary Tree , that is, when iterating, TreeMap guarantee can the key order which is determined by either element's compareTo() method or a comparator set in the TreeMap's constructor.

Take a look at following diagram.

enter image description here

How to sort List<Integer>?

You can use Collections for to sort data:

import java.util.Collections;
import java.util.ArrayList;
import java.util.List;

public class tes
{
    public static void main(String args[])
    {
        List<Integer> lList = new ArrayList<Integer>();

        lList.add(4);       
        lList.add(1);
        lList.add(7);
        lList.add(2);
        lList.add(9);
        lList.add(1);
        lList.add(5);

        Collections.sort(lList);

        for(int i=0; i<lList.size();i++ )
        {
            System.out.println(lList.get(i));
        }

    }
}

Getting JavaScript object key list

_x000D_
_x000D_
var obj = {_x000D_
   key1: 'value1',_x000D_
   key2: 'value2',_x000D_
   key3: 'value3',_x000D_
   key4: 'value4'_x000D_
}_x000D_
var keys = Object.keys(obj);_x000D_
console.log('obj contains ' + keys.length + ' keys: '+  keys);
_x000D_
_x000D_
_x000D_

It's supported on most major browsers now.

How to obtain the location of cacerts of the default java installation?

In MacOS Mojave, the location is:

/Library/Java/JavaVirtualMachines/jdk1.8.0_192.jdk/Contents/Home/jre/lib/security/cacerts 

If using sdkman to manage java versions, the cacerts is in

~/.sdkman/candidates/java/current/jre/lib/security

How to run jenkins as a different user

The "Issue 2" answer given by @Sagar works for the majority of git servers such as gitorious.

However, there will be a name clash in a system like gitolite where the public ssh keys are checked in as files named with the username, ie keydir/jenkins.pub. What if there are multiple jenkins servers that need to access the same gitolite server?

(Note: this is about running the Jenkins daemon not running a build job as a user (addressed by @Sagar's "Issue 1").)

So in this case you do need to run the Jenkins daemon as a different user.

There are two steps:

Step 1

The main thing is to update the JENKINS_USER environment variable. Here's a patch showing how to change the user to ptran.

BEGIN PATCH
--- etc/default/jenkins.old     2011-10-28 17:46:54.410305099 -0700
+++ etc/default/jenkins 2011-10-28 17:47:01.670369300 -0700
@@ -13,7 +13,7 @@
 PIDFILE=/var/run/jenkins/jenkins.pid

 # user id to be invoked as (otherwise will run as root; not wise!)
-JENKINS_USER=jenkins
+JENKINS_USER=ptran

 # location of the jenkins war file
 JENKINS_WAR=/usr/share/jenkins/jenkins.war
--- etc/init.d/jenkins.old      2011-10-28 17:47:20.878539172 -0700
+++ etc/init.d/jenkins  2011-10-28 17:47:47.510774714 -0700
@@ -23,7 +23,7 @@

 #DAEMON=$JENKINS_SH
 DAEMON=/usr/bin/daemon
-DAEMON_ARGS="--name=$NAME --inherit --env=JENKINS_HOME=$JENKINS_HOME --output=$JENKINS_LOG -   -pidfile=$PIDFILE" 
+DAEMON_ARGS="--name=$JENKINS_USER --inherit --env=JENKINS_HOME=$JENKINS_HOME --output=$JENKINS_LOG --pidfile=$PIDFILE" 

 SU=/bin/su
END PATCH

Step 2

Update ownership of jenkins directories:

chown -R ptran /var/log/jenkins
chown -R ptran /var/lib/jenkins
chown -R ptran /var/run/jenkins
chown -R ptran /var/cache/jenkins

Step 3

Restart jenkins

sudo service jenkins restart

Tab Escape Character?

For someone who needs quick reference of C# Escape Sequences that can be used in string literals:

\t     Horizontal tab (ASCII code value: 9)

\n     Line feed (ASCII code value: 10)

\r     Carriage return (ASCII code value: 13)

\'     Single quotation mark

\"     Double quotation mark

\\     Backslash

\?     Literal question mark

\x12     ASCII character in hexadecimal notation (e.g. for 0x12)

\x1234     Unicode character in hexadecimal notation (e.g. for 0x1234)

It's worth mentioning that these (in most cases) are universal codes. So \t is 9 and \n is 10 char value on Windows and Linux. But newline sequence is not universal. On Windows it's \n\r and on Linux it's just \n. That's why it's best to use Environment.Newline which gets adjusted to current OS settings. With .Net Core it gets really important.

How to get a context in a recycler view adapter

You have a few options here:

  1. Pass Context as an argument to FeedAdapter and keep it as class field
  2. Use dependency injection to inject Context when you need it. I strongly suggest reading about it. There is a great tool for that -- Dagger by Square
  3. Get it from any View object. In your case this might work for you:

    holder.pub_image.getContext()

    As pub_image is a ImageView.

Give all permissions to a user on a PostgreSQL database

GRANT ALL PRIVILEGES ON DATABASE "my_db" to my_user;

Insert a new row into DataTable

You can do this, I am using

DataTable 1.10.5

using this code:

var versionNo = $.fn.dataTable.version;
alert(versionNo);

This is how I insert new record on my DataTable using row.add (My table has 10 columns), which can also includes HTML tag elements:

function fncInsertNew() {
            var table = $('#tblRecord').DataTable();

            table.row.add([
                    "Tiger Nixon",
                    "System Architect",
                    "$3,120",
                    "2011/04/25",
                    "Edinburgh",
                    "5421",
                    "Tiger Nixon",
                    "System Architect",
                    "$3,120",
                    "<p>Hello</p>"
            ]).draw();
        }

For multiple inserts at the same time, use rows.add instead:

var table = $('#tblRecord').DataTable();

table.rows.add( [ {
        "Tiger Nixon",
        "System Architect",
        "$3,120",
        "2011/04/25",
        "Edinburgh",
        "5421"
    }, {
        "Garrett Winters",
        "Director",
        "$5,300",
        "2011/07/25",
        "Edinburgh",
        "8422"
    }]).draw();

How to multiply duration by integer?

int32 and time.Duration are different types. You need to convert the int32 to a time.Duration, such as time.Sleep(time.Duration(rand.Int31n(1000)) * time.Millisecond).

How can I change property names when serializing with Json.net?

If you don't have access to the classes to change the properties, or don't want to always use the same rename property, renaming can also be done by creating a custom resolver.

For example, if you have a class called MyCustomObject, that has a property called LongPropertyName, you can use a custom resolver like this…

public class CustomDataContractResolver : DefaultContractResolver
{
  public static readonly CustomDataContractResolver Instance = new CustomDataContractResolver ();

  protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
  {
    var property = base.CreateProperty(member, memberSerialization);
    if (property.DeclaringType == typeof(MyCustomObject))
    {
      if (property.PropertyName.Equals("LongPropertyName", StringComparison.OrdinalIgnoreCase))
      {
        property.PropertyName = "Short";
      }
    }
    return property;
  }
}

Then call for serialization and supply the resolver:

 var result = JsonConvert.SerializeObject(myCustomObjectInstance,
                new JsonSerializerSettings { ContractResolver = CustomDataContractResolver.Instance });

And the result will be shortened to {"Short":"prop value"} instead of {"LongPropertyName":"prop value"}

More info on custom resolvers here

AngularJS access scope from outside js function

We need to use Angular Js built in function $apply to acsess scope variables or functions outside the controller function.

This can be done in two ways :

|*| Method 1 : Using Id :

<div id="nameNgsDivUid" ng-app="">
    <a onclick="actNgsFnc()"> Activate Angular Scope</a><br><br>
    {{ nameNgsVar }}
</div>

<script type="text/javascript">

    var nameNgsDivVar = document.getElementById('nameNgsDivUid')

    function actNgsFnc()
    {
        var scopeNgsVar = angular.element(nameNgsDivVar).scope();
        scopeNgsVar.$apply(function()
        {
            scopeNgsVar.nameNgsVar = "Tst Txt";
        })
    }

</script>

|*| Method 2 : Using init of ng-controller :

<div ng-app="nameNgsApp" ng-controller="nameNgsCtl">
    <a onclick="actNgsFnc()"> Activate Angular Scope</a><br><br>
    {{ nameNgsVar }}
</div>

<script type="text/javascript">

    var scopeNgsVar;
    var nameNgsAppVar=angular.module("nameNgsApp",[])
    nameNgsAppVar.controller("nameNgsCtl",function($scope)
    {
        scopeNgsVar=$scope;
    })

    function actNgsFnc()
    {
        scopeNgsVar.$apply(function()
        {
            scopeNgsVar.nameNgsVar = "Tst Txt";
        })
    }

</script>

Check if a record exists in the database

MySqlCommand cmd = new MySqlCommand("select * from table where user = '" + user.Text + "'", con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds1 = new DataSet();
da.Fill(ds1);
int i = ds1.Tables[0].Rows.Count;
if (i > 0) {
    // Exist
}
else {
    // Add 
}

Pip Install not installing into correct directory?

From the comments to the original question, it seems that you have multiple versions of python installed and that pip just goes to the wrong version.

First, to know which version of python you're using, just type which python. You should either see:

which python
/Library/Frameworks/Python.framework/Versions/2.7/bin/python

if you're going to the right version of python, or:

which python
/usr/bin/python

If you're going to the 'wrong' version. To make pip go to the right version, you first have to change the path:

 export PATH=/Library/Frameworks/Python.framework/Versions/2.7/bin/python:${PATH}

typing 'which python' would now get you to the right result. Next, install pip (if it's not already installed for this installation of python). Finally, use it. you should be fine now.

Redirect output of mongo query to a csv file

I know this question is old but I spend an hour trying to export a complex query to csv and I wanted to share my thoughts. First I couldn't get any of the json to csv converters to work (although this one looked promising). What I ended up doing was manually writing the csv file in my mongo script.

This is a simple version but essentially what I did:

print("name,id,email");
db.User.find().forEach(function(user){
  print(user.name+","+user._id.valueOf()+","+user.email);
});

This I just piped the query to stdout

mongo test export.js > out.csv

where test is the name of the database I use.

How can one develop iPhone apps in Java?

To add to this there's: http://www.oracle.com/technetwork/developer-tools/adf-mobile/overview/index.html

A Java & HTML5 Based Framework for Developing
Oracle ADF Mobile enables developers to build and extend enterprise applications for iOS and Android from a single code base. Based on a hybrid mobile architecture, ADF Mobile supports access to native device services, enables offline applications and protects enterprise investments from future technology shifts.

Clang vs GCC for my Linux Development project

I think clang could be an alternative.

GCC and clang have some differences on expressions like a+++++a, and I've got many different answers with my peer who use clang on Mac while I use gcc.

GCC has become the standard, and clang could be an alternative. Because GCC is very stable and clang is still under developing.

Getting 404 Not Found error while trying to use ErrorDocument

The ErrorDocument directive, when supplied a local URL path, expects the path to be fully qualified from the DocumentRoot. In your case, this means that the actual path to the ErrorDocument is

ErrorDocument 404 /hellothere/error/404page.html

SQL RANK() over PARTITION on joined tables

As the rank doesn't depend at all from the contacts

RANKED_RSLTS

 QRY_ID  |  RES_ID  |  SCORE |  RANK
-------------------------------------
   A     |    1     |    15  |   3
   A     |    2     |    32  |   1
   A     |    3     |    29  |   2
   C     |    7     |    61  |   1
   C     |    9     |    30  |   2

Thus :

SELECT
    C.*
    ,R.SCORE
    ,MYRANK
FROM CONTACTS C LEFT JOIN
(SELECT  *,
 MYRANK = RANK() OVER (PARTITION BY QRY_ID ORDER BY SCORE DESC)
  FROM RSLTS)  R
ON C.RES_ID = R.RES_ID
AND C.QRY_ID = R.QRY_ID

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

If the type implements IDisposable, it automatically disposes that type.

Given:

public class SomeDisposableType : IDisposable
{
   ...implmentation details...
}

These are equivalent:

SomeDisposableType t = new SomeDisposableType();
try {
    OperateOnType(t);
}
finally {
    if (t != null) {
        ((IDisposable)t).Dispose();
    }
}
using (SomeDisposableType u = new SomeDisposableType()) {
    OperateOnType(u);
}

The second is easier to read and maintain.

There is no argument given that corresponds to the required formal parameter - .NET Error

You have a constructor which takes 2 parameters. You should write something like:

new ErrorEventArg(errorMsv, lastQuery)

It's less code and easier to read.

EDIT

Or, in order for your way to work, you can try writing a default constructor for ErrorEventArg which would have no parameters, like this:

public ErrorEventArg() {}

PostgreSQL delete with inner join

Just use a subquery with INNER JOIN, LEFT JOIN or smth else:

DELETE FROM m_productprice
WHERE m_product_id IN
(
  SELECT B.m_product_id
  FROM   m_productprice  B
    INNER JOIN m_product C 
    ON   B.m_product_id = C.m_product_id
  WHERE  C.upc = '7094' 
  AND    B.m_pricelist_version_id = '1000020'
)

to optimize the query,

Bootstrap 4 - Glyphicons migration?

Bootstrap 4 files do not come with the glyphicon support. But you can simply open up your bootstrap.css or bootstrap.min.css and paste this code which I came across here.

@font-face{font-family:'Glyphicons Halflings';src:url('https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.eot');src:url('https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'),url('https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.woff') format('woff'),url('https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.ttf') format('truetype'),url('https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');}.glyphicon{position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';font-style:normal;font-weight:normal;line-height:1;-webkit-font-smoothing:antialiased;}
.glyphicon-asterisk:before{content:"\2a";}
.glyphicon-plus:before{content:"\2b";}
.glyphicon-euro:before{content:"\20ac";}
.glyphicon-minus:before{content:"\2212";}
.glyphicon-cloud:before{content:"\2601";}
.glyphicon-envelope:before{content:"\2709";}
.glyphicon-pencil:before{content:"\270f";}
.glyphicon-glass:before{content:"\e001";}
.glyphicon-music:before{content:"\e002";}
.glyphicon-search:before{content:"\e003";}
.glyphicon-heart:before{content:"\e005";}
.glyphicon-star:before{content:"\e006";}
.glyphicon-star-empty:before{content:"\e007";}
.glyphicon-user:before{content:"\e008";}
.glyphicon-film:before{content:"\e009";}
.glyphicon-th-large:before{content:"\e010";}
.glyphicon-th:before{content:"\e011";}
.glyphicon-th-list:before{content:"\e012";}
.glyphicon-ok:before{content:"\e013";}
.glyphicon-remove:before{content:"\e014";}
.glyphicon-zoom-in:before{content:"\e015";}
.glyphicon-zoom-out:before{content:"\e016";}
.glyphicon-off:before{content:"\e017";}
.glyphicon-signal:before{content:"\e018";}
.glyphicon-cog:before{content:"\e019";}
.glyphicon-trash:before{content:"\e020";}
.glyphicon-home:before{content:"\e021";}
.glyphicon-file:before{content:"\e022";}
.glyphicon-time:before{content:"\e023";}
.glyphicon-road:before{content:"\e024";}
.glyphicon-download-alt:before{content:"\e025";}
.glyphicon-download:before{content:"\e026";}
.glyphicon-upload:before{content:"\e027";}
.glyphicon-inbox:before{content:"\e028";}
.glyphicon-play-circle:before{content:"\e029";}
.glyphicon-repeat:before{content:"\e030";}
.glyphicon-refresh:before{content:"\e031";}
.glyphicon-list-alt:before{content:"\e032";}
.glyphicon-flag:before{content:"\e034";}
.glyphicon-headphones:before{content:"\e035";}
.glyphicon-volume-off:before{content:"\e036";}
.glyphicon-volume-down:before{content:"\e037";}
.glyphicon-volume-up:before{content:"\e038";}
.glyphicon-qrcode:before{content:"\e039";}
.glyphicon-barcode:before{content:"\e040";}
.glyphicon-tag:before{content:"\e041";}
.glyphicon-tags:before{content:"\e042";}
.glyphicon-book:before{content:"\e043";}
.glyphicon-print:before{content:"\e045";}
.glyphicon-font:before{content:"\e047";}
.glyphicon-bold:before{content:"\e048";}
.glyphicon-italic:before{content:"\e049";}
.glyphicon-text-height:before{content:"\e050";}
.glyphicon-text-width:before{content:"\e051";}
.glyphicon-align-left:before{content:"\e052";}
.glyphicon-align-center:before{content:"\e053";}
.glyphicon-align-right:before{content:"\e054";}
.glyphicon-align-justify:before{content:"\e055";}
.glyphicon-list:before{content:"\e056";}
.glyphicon-indent-left:before{content:"\e057";}
.glyphicon-indent-right:before{content:"\e058";}
.glyphicon-facetime-video:before{content:"\e059";}
.glyphicon-picture:before{content:"\e060";}
.glyphicon-map-marker:before{content:"\e062";}
.glyphicon-adjust:before{content:"\e063";}
.glyphicon-tint:before{content:"\e064";}
.glyphicon-edit:before{content:"\e065";}
.glyphicon-share:before{content:"\e066";}
.glyphicon-check:before{content:"\e067";}
.glyphicon-move:before{content:"\e068";}
.glyphicon-step-backward:before{content:"\e069";}
.glyphicon-fast-backward:before{content:"\e070";}
.glyphicon-backward:before{content:"\e071";}
.glyphicon-play:before{content:"\e072";}
.glyphicon-pause:before{content:"\e073";}
.glyphicon-stop:before{content:"\e074";}
.glyphicon-forward:before{content:"\e075";}
.glyphicon-fast-forward:before{content:"\e076";}
.glyphicon-step-forward:before{content:"\e077";}
.glyphicon-eject:before{content:"\e078";}
.glyphicon-chevron-left:before{content:"\e079";}
.glyphicon-chevron-right:before{content:"\e080";}
.glyphicon-plus-sign:before{content:"\e081";}
.glyphicon-minus-sign:before{content:"\e082";}
.glyphicon-remove-sign:before{content:"\e083";}
.glyphicon-ok-sign:before{content:"\e084";}
.glyphicon-question-sign:before{content:"\e085";}
.glyphicon-info-sign:before{content:"\e086";}
.glyphicon-screenshot:before{content:"\e087";}
.glyphicon-remove-circle:before{content:"\e088";}
.glyphicon-ok-circle:before{content:"\e089";}
.glyphicon-ban-circle:before{content:"\e090";}
.glyphicon-arrow-left:before{content:"\e091";}
.glyphicon-arrow-right:before{content:"\e092";}
.glyphicon-arrow-up:before{content:"\e093";}
.glyphicon-arrow-down:before{content:"\e094";}
.glyphicon-share-alt:before{content:"\e095";}
.glyphicon-resize-full:before{content:"\e096";}
.glyphicon-resize-small:before{content:"\e097";}
.glyphicon-exclamation-sign:before{content:"\e101";}
.glyphicon-gift:before{content:"\e102";}
.glyphicon-leaf:before{content:"\e103";}
.glyphicon-eye-open:before{content:"\e105";}
.glyphicon-eye-close:before{content:"\e106";}
.glyphicon-warning-sign:before{content:"\e107";}
.glyphicon-plane:before{content:"\e108";}
.glyphicon-random:before{content:"\e110";}
.glyphicon-comment:before{content:"\e111";}
.glyphicon-magnet:before{content:"\e112";}
.glyphicon-chevron-up:before{content:"\e113";}
.glyphicon-chevron-down:before{content:"\e114";}
.glyphicon-retweet:before{content:"\e115";}
.glyphicon-shopping-cart:before{content:"\e116";}
.glyphicon-folder-close:before{content:"\e117";}
.glyphicon-folder-open:before{content:"\e118";}
.glyphicon-resize-vertical:before{content:"\e119";}
.glyphicon-resize-horizontal:before{content:"\e120";}
.glyphicon-hdd:before{content:"\e121";}
.glyphicon-bullhorn:before{content:"\e122";}
.glyphicon-certificate:before{content:"\e124";}
.glyphicon-thumbs-up:before{content:"\e125";}
.glyphicon-thumbs-down:before{content:"\e126";}
.glyphicon-hand-right:before{content:"\e127";}
.glyphicon-hand-left:before{content:"\e128";}
.glyphicon-hand-up:before{content:"\e129";}
.glyphicon-hand-down:before{content:"\e130";}
.glyphicon-circle-arrow-right:before{content:"\e131";}
.glyphicon-circle-arrow-left:before{content:"\e132";}
.glyphicon-circle-arrow-up:before{content:"\e133";}
.glyphicon-circle-arrow-down:before{content:"\e134";}
.glyphicon-globe:before{content:"\e135";}
.glyphicon-tasks:before{content:"\e137";}
.glyphicon-filter:before{content:"\e138";}
.glyphicon-fullscreen:before{content:"\e140";}
.glyphicon-dashboard:before{content:"\e141";}
.glyphicon-heart-empty:before{content:"\e143";}
.glyphicon-link:before{content:"\e144";}
.glyphicon-phone:before{content:"\e145";}
.glyphicon-usd:before{content:"\e148";}
.glyphicon-gbp:before{content:"\e149";}
.glyphicon-sort:before{content:"\e150";}
.glyphicon-sort-by-alphabet:before{content:"\e151";}
.glyphicon-sort-by-alphabet-alt:before{content:"\e152";}
.glyphicon-sort-by-order:before{content:"\e153";}
.glyphicon-sort-by-order-alt:before{content:"\e154";}
.glyphicon-sort-by-attributes:before{content:"\e155";}
.glyphicon-sort-by-attributes-alt:before{content:"\e156";}
.glyphicon-unchecked:before{content:"\e157";}
.glyphicon-expand:before{content:"\e158";}
.glyphicon-collapse-down:before{content:"\e159";}
.glyphicon-collapse-up:before{content:"\e160";}
.glyphicon-log-in:before{content:"\e161";}
.glyphicon-flash:before{content:"\e162";}
.glyphicon-log-out:before{content:"\e163";}
.glyphicon-new-window:before{content:"\e164";}
.glyphicon-record:before{content:"\e165";}
.glyphicon-save:before{content:"\e166";}
.glyphicon-open:before{content:"\e167";}
.glyphicon-saved:before{content:"\e168";}
.glyphicon-import:before{content:"\e169";}
.glyphicon-export:before{content:"\e170";}
.glyphicon-send:before{content:"\e171";}
.glyphicon-floppy-disk:before{content:"\e172";}
.glyphicon-floppy-saved:before{content:"\e173";}
.glyphicon-floppy-remove:before{content:"\e174";}
.glyphicon-floppy-save:before{content:"\e175";}
.glyphicon-floppy-open:before{content:"\e176";}
.glyphicon-credit-card:before{content:"\e177";}
.glyphicon-transfer:before{content:"\e178";}
.glyphicon-cutlery:before{content:"\e179";}
.glyphicon-header:before{content:"\e180";}
.glyphicon-compressed:before{content:"\e181";}
.glyphicon-earphone:before{content:"\e182";}
.glyphicon-phone-alt:before{content:"\e183";}
.glyphicon-tower:before{content:"\e184";}
.glyphicon-stats:before{content:"\e185";}
.glyphicon-sd-video:before{content:"\e186";}
.glyphicon-hd-video:before{content:"\e187";}
.glyphicon-subtitles:before{content:"\e188";}
.glyphicon-sound-stereo:before{content:"\e189";}
.glyphicon-sound-dolby:before{content:"\e190";}
.glyphicon-sound-5-1:before{content:"\e191";}
.glyphicon-sound-6-1:before{content:"\e192";}
.glyphicon-sound-7-1:before{content:"\e193";}
.glyphicon-copyright-mark:before{content:"\e194";}
.glyphicon-registration-mark:before{content:"\e195";}
.glyphicon-cloud-download:before{content:"\e197";}
.glyphicon-cloud-upload:before{content:"\e198";}
.glyphicon-tree-conifer:before{content:"\e199";}
.glyphicon-tree-deciduous:before{content:"\e200";}
.glyphicon-briefcase:before{content:"\1f4bc";}
.glyphicon-calendar:before{content:"\1f4c5";}
.glyphicon-pushpin:before{content:"\1f4cc";}
.glyphicon-paperclip:before{content:"\1f4ce";}
.glyphicon-camera:before{content:"\1f4f7";}
.glyphicon-lock:before{content:"\1f512";}
.glyphicon-bell:before{content:"\1f514";}
.glyphicon-bookmark:before{content:"\1f516";}
.glyphicon-fire:before{content:"\1f525";}
.glyphicon-wrench:before{content:"\1f527";}

How do I kill this tomcat process in Terminal?

as @Aurand to said, tomcat is not running. you can use the

ps -ef |grep java | grep tomcat command to ignore the ps programs.

worked for me in the shell scripte files.

What is the difference between a deep copy and a shallow copy?

Shallow copy: Copies the member values from one object into another.

Deep Copy:    Copies the member values from one object into another.
                     Any pointer objects are duplicated and Deep Copied.

Example:

class String
{
     int   size;
     char* data;
};

String  s1("Ace");   // s1.size = 3 s1.data=0x0000F000

String  s2 = shallowCopy(s1);
 // s2.size =3 s2.data = 0X0000F000
String  s3 = deepCopy(s1);
 // s3.size =3 s3.data = 0x0000F00F
 //                      (With Ace copied to this location.)

Creating a comma separated list from IList<string> or IEnumerable<string>

Since I reached here while searching to join on a specific property of a list of objects (and not the ToString() of it) here's an addition to the accepted answer:

var commaDelimited = string.Join(",", students.Where(i => i.Category == studentCategory)
                                 .Select(i => i.FirstName));

How can I write to the console in PHP?

There is also a great Google Chrome extension, PHP Console, with a PHP library that allows you to:

  • See errors and exceptions in the Chrome JavaScript console and in the notification popups.
  • Dump any type of variable.
  • Execute PHP code remotely.
  • Protect access by password.
  • Group console logs by request.
  • Jump to error file:line in your text editor.
  • Copy error/debug data to the clipboard (for testers).

SQL Query to search schema of all tables

My favorite...

SELECT objParent.name AS parent, obj.name, col.*
FROM sysobjects obj 
    LEFT JOIN syscolumns col
        ON obj.id = col.id
    LEFT JOIN sysobjects objParent
        ON objParent.id = obj.parent_obj
WHERE col.name LIKE '%Comment%'
   OR obj.name LIKE '%Comment%'

Above I'm searching for "Comment".

Drop the percent signs if you want a direct match.

This searches tables, fields and things like primary key names, constraints, views, etc.

And when you want to search in StoredProcs after monkeying with the tables (and need to make the procs match), use the following...

SELECT name
FROM sys.procedures
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%Comment%'

Hope that helps, I find these two queries to be extremely useful.

How to filter array when object key value is in array

In 2019 using ES6:

_x000D_
_x000D_
const ids = [1, 4, 5],_x000D_
  data = {_x000D_
    records: [{_x000D_
      "empid": 1,_x000D_
      "fname": "X",_x000D_
      "lname": "Y"_x000D_
    }, {_x000D_
      "empid": 2,_x000D_
      "fname": "A",_x000D_
      "lname": "Y"_x000D_
    }, {_x000D_
      "empid": 3,_x000D_
      "fname": "B",_x000D_
      "lname": "Y"_x000D_
    }, {_x000D_
      "empid": 4,_x000D_
      "fname": "C",_x000D_
      "lname": "Y"_x000D_
    }, {_x000D_
      "empid": 5,_x000D_
      "fname": "C",_x000D_
      "lname": "Y"_x000D_
    }]_x000D_
  };_x000D_
_x000D_
_x000D_
data.records = data.records.filter( i => ids.includes( i.empid ) );_x000D_
_x000D_
console.info( data );
_x000D_
_x000D_
_x000D_

Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList?

In Java 8 you can use Files.write() method with two arguments: Path and List<String>, something like this:

List<String> clubNames = clubs.stream()
    .map(Club::getName)
    .collect(Collectors.toList())

try {
    Files.write(Paths.get(fileName), clubNames);
} catch (IOException e) {
    log.error("Unable to write out names", e);
}

Selenium WebDriver: I want to overwrite value in field instead of appending to it with sendKeys using Java

Use this one, it is trusted solution and works well for all browsers:

protected void clearInput(WebElement webElement) {
    // isIE() - just checks is it IE or not - use your own implementation
    if (isIE() && "file".equals(webElement.getAttribute("type"))) {
        // workaround
        // if IE and input's type is file - do not try to clear it.
        // If you send:
        // - empty string - it will find file by empty path
        // - backspace char - it will process like a non-visible char
        // In both cases it will throw a bug.
        // 
        // Just replace it with new value when it is need to.
    } else {
        // if you have no StringUtils in project, check value still empty yet
        while (!StringUtils.isEmpty(webElement.getAttribute("value"))) {
            // "\u0008" - is backspace char
            webElement.sendKeys("\u0008");
        }
    }
}

If input has type="file" - do not clear it for IE. It will try to find file by empty path and will throw a bug.

More details you could find on my blog

New lines inside paragraph in README.md

If you want to be a little bit fancier you can also create it as an html list to create something like bullets or numbers using ul or ol.

<ul>
<li>Line 1</li>
<li>Line 2</li>
</ul>

Programmatically set TextBlock Foreground Color

 textBlock.Foreground = new SolidColorBrush(Colors.White);

Array.sort() doesn't sort numbers correctly

The default sort for arrays in Javascript is an alphabetical search. If you want a numerical sort, try something like this:

var a = [ 1, 100, 50, 2, 5];
a.sort(function(a,b) { return a - b; });

How do you get AngularJS to bind to the title attribute of an A tag?

The search query model lives in the scope defined by the ng-controller="whatever" directive. So if you want to bind the query model to <title>, you have to move the ngController declaration to an HTML element that is a common parent to both the body and title elements:

<html ng-app="phonecatApp" ng-controller="PhoneListCtrl">

Ref: https://docs.angularjs.org/tutorial/step_03

Capture screenshot of active window?

Works if the Desktop scaling is set.

public class ScreenCapture
{
    [DllImport("user32.dll")]
    private static extern IntPtr GetForegroundWindow();

    [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
    public static extern IntPtr GetDesktopWindow();

    [StructLayout(LayoutKind.Sequential)]
    private struct Rect
    {
        public int Left;
        public int Top;
        public int Right;
        public int Bottom;
    }

    [DllImport("user32.dll")]
    private static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect);

    public static Image CaptureDesktop()
    {
        return CaptureWindow(GetDesktopWindow());
    }

    public static Bitmap CaptureActiveWindow()
    {
        return CaptureWindow(GetForegroundWindow());
    }

    public static Bitmap CaptureWindow(IntPtr handle)
    {
        var rect = new Rect();
        GetWindowRect(handle, ref rect);
        GetScale getScale = new GetScale();
        var bounds = new Rectangle(rect.Left, rect.Top, (int)((rect.Right - rect.Left)* getScale.getScalingFactor()), (int)((rect.Bottom - rect.Top )* getScale.getScalingFactor()));
        var result = new Bitmap(bounds.Width, bounds.Height);

        using (var graphics = Graphics.FromImage(result))
        {
            graphics.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);
        }

        return result;
    }
}

SQL Server format decimal places with commas

without considering this to be a good idea...

select dbo.F_AddThousandSeparators(convert(varchar, convert(decimal(18, 4), 1234.1234567), 1))

Function

-- Author:      bummi
-- Create date: 20121106
CREATE FUNCTION F_AddThousandSeparators(@NumStr varchar(50)) 
RETURNS Varchar(50)
AS
BEGIN
declare @OutStr varchar(50)
declare @i int
declare @run int

Select @i=CHARINDEX('.',@NumStr)
if @i=0 
    begin
    set @i=LEN(@NumStr)
    Set @Outstr=''
    end
else
    begin   
     Set @Outstr=SUBSTRING(@NUmStr,@i,50)
     Set @i=@i -1
    end 


Set @run=0

While @i>0
    begin
      if @Run=3
        begin
          Set @Outstr=','+@Outstr
          Set @run=0
        end
      Set @Outstr=SUBSTRING(@NumStr,@i,1) +@Outstr  
      Set @i=@i-1
      Set @run=@run + 1     
    end

    RETURN @OutStr

END
GO

How to use conditional breakpoint in Eclipse?

Put your breakpoint. Right-click the breakpoint image on the margin and choose Breakpoint Properties:

enter image description here

Configure condition as you see fit:

enter image description here

How can I apply a function to every row/column of a matrix in MATLAB?

Many built-in operations like sum and prod are already able to operate across rows or columns, so you may be able to refactor the function you are applying to take advantage of this.

If that's not a viable option, one way to do it is to collect the rows or columns into cells using mat2cell or num2cell, then use cellfun to operate on the resulting cell array.

As an example, let's say you want to sum the columns of a matrix M. You can do this simply using sum:

M = magic(10);           %# A 10-by-10 matrix
columnSums = sum(M, 1);  %# A 1-by-10 vector of sums for each column

And here is how you would do this using the more complicated num2cell/cellfun option:

M = magic(10);                  %# A 10-by-10 matrix
C = num2cell(M, 1);             %# Collect the columns into cells
columnSums = cellfun(@sum, C);  %# A 1-by-10 vector of sums for each cell

Implementing a Custom Error page on an ASP.Net website

There are 2 ways to configure custom error pages for ASP.NET sites:

  1. Internet Information Services (IIS) Manager (the GUI)
  2. web.config file

This article explains how to do each:

The reason your error.aspx page is not displaying might be because you have an error in your web.config. Try this instead:

<configuration>
   <system.web>
      <customErrors defaultRedirect="error.aspx" mode="RemoteOnly">
         <error statusCode="404" redirect="error.aspx"/>
      </customErrors>
   </system.web>
</configuration>

You might need to make sure that Error Pages in IIS Manager - Feature Delegation is set to Read/Write:

IIS Manager: Feature Delegation panel

Also, this answer may help you configure the web.config file:

How do I temporarily disable triggers in PostgreSQL?

Alternatively, if you are wanting to disable all triggers, not just those on the USER table, you can use:

SET session_replication_role = replica;

This disables triggers for the current session.

To re-enable for the same session:

SET session_replication_role = DEFAULT;

Source: http://koo.fi/blog/2013/01/08/disable-postgresql-triggers-temporarily/

case in sql stored procedure on SQL Server

CASE isn't used for flow control... for this, you would need to use IF...

But, there's a set-based solution to this problem instead of the procedural approach:

UPDATE tblEmployee
SET 
  InOffice = CASE WHEN @NewStatus = 'InOffice' THEN -1 ELSE InOffice END,
  OutOffice = CASE WHEN @NewStatus = 'OutOffice' THEN -1 ELSE OutOffice END,
  Home = CASE WHEN @NewStatus = 'Home' THEN -1 ELSE Home END
WHERE EmpID = @EmpID

Note that the ELSE will preserves the original value if the @NewStatus condition isn't met.

How to get file path from OpenFileDialog and FolderBrowserDialog?

For OpenFileDialog:

OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = true;

if (choofdlog.ShowDialog() == DialogResult.OK)    
{     
    string sFileName = choofdlog.FileName; 
    string[] arrAllFiles = choofdlog.FileNames; //used when Multiselect = true           
}

For FolderBrowserDialog:

FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.Description = "Custom Description"; 

if (fbd.ShowDialog() == DialogResult.OK)
{
    string sSelectedPath = fbd.SelectedPath;
}

To access selected folder and selected file name you can declare both string at class level.

namespace filereplacer
{
   public partial class Form1 : Form
   {
      string sSelectedFile;
      string sSelectedFolder;

      public Form1()
      {
         InitializeComponent();
      }

      private void direc_Click(object sender, EventArgs e)
      {
         FolderBrowserDialog fbd = new FolderBrowserDialog();
         //fbd.Description = "Custom Description"; //not mandatory

         if (fbd.ShowDialog() == DialogResult.OK)      
               sSelectedFolder = fbd.SelectedPath;
         else
               sSelectedFolder = string.Empty;    
      }

      private void choof_Click(object sender, EventArgs e)
      {
         OpenFileDialog choofdlog = new OpenFileDialog();
         choofdlog.Filter = "All Files (*.*)|*.*";
         choofdlog.FilterIndex = 1;
         choofdlog.Multiselect = true;

         if (choofdlog.ShowDialog() == DialogResult.OK)                 
             sSelectedFile = choofdlog.FileName;            
         else
             sSelectedFile = string.Empty;       
      }

      private void replacebtn_Click(object sender, EventArgs e)
      {
          if(sSelectedFolder != string.Empty && sSelectedFile != string.Empty)
          {
               //use selected folder path and file path
          }
      }
      ....
}

NOTE:

As you have kept choofdlog.Multiselect=true;, that means in the OpenFileDialog() you are able to select multiple files (by pressing ctrl key and left mouse click for selection).

In that case you could get all selected files in string[]:

At Class Level:

string[] arrAllFiles;

Locate this line (when Multiselect=true this line gives first file only):

sSelectedFile = choofdlog.FileName; 

To get all files use this:

arrAllFiles = choofdlog.FileNames; //this line gives array of all selected files

Node.js Logging

You can also use npmlog by issacs, recommended in https://npmjs.org/doc/coding-style.html.

You can find this module here https://github.com/isaacs/npmlog

What is the difference between Sublime text and Github's Atom

I'm working in little extreme environment; edit files on remote filesystem (external network, surely) that is mounted on my Laptop thru ssh(aka. sshfs). Regardless why I'm doing like this, also though its cumbersome responsiveness, it's fairly edible when I'm using Sublime Text 2.

I tried on Atom after reading this post, but it turned out to be somewhat painful to me; Atom seems that it doesn't cache directory structure so efficiently. Every time I expand a folder on Tree View, the UI froze for a short time, 2~3 seconds, maybe fetching file system info. Yes, it's because I'm using remote filesystem. But Sublime handles this more efficient, at least it doesn't freeze every time I expand a folder, so less painful.

I think Atom is hell nice for free, and my story is trivial that might be enhanced someday, but it would be helpful to someone at this time.

--

added on 8/26/2014

Recently, I changed my laptop from Macbook Air 2010 late to Macbook Pro 13" 2013 late. It has likely 4 times faster CPU and much enhancements in performance. I want to mention my opinion is about in the case WHEN YOU MOUNT REMOTE FILE SYSTEM. (using OS X Mavericks, most recent version of Atom, FUSE 2.7.3 / OSXFUSE 2.6.4 / sshfs 2.5.0, and remote system is Ubuntu server) Eventually, UI freeze gets pretty shorter, but it is still there. Specifically, to open a folder with many folder/files in it and index it is requires certain amount of time. Also, if you expand a folder full of files, it just falters. (when collapsing the folder, it doesn't)

According to @EliDuenisch , it seems not happen on Linux Mint. I'm not sure but it might be from difference between OSes. Surely, if you work on local file system, you don't have to care about this issue at all.

Checking if a SQL Server login already exists

First you have to check login existence using syslogins view:

IF NOT EXISTS 
    (SELECT name  
     FROM master.sys.server_principals
     WHERE name = 'YourLoginName')
BEGIN
    CREATE LOGIN [YourLoginName] WITH PASSWORD = N'password'
END

Then you have to check your database existence:

USE your_dbname

IF NOT EXISTS
    (SELECT name
     FROM sys.database_principals
     WHERE name = 'your_dbname')
BEGIN
    CREATE USER [your_dbname] FOR LOGIN [YourLoginName] 
END

How to set the width of a RaisedButton in Flutter?

we use Row or Column, Expanded, Container and the element to use example RaisedButton

 body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.symmetric(vertical: 10.0),
                ),
                Row(
                  children: <Widget>[
                    Expanded(
                      flex: 2, // we define the width of the button
                      child: Container(
                        // height: 50, we define the height of the button
                        child: Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 10.0),
                          child: RaisedButton(
                            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                            textColor: Colors.white,
                            color: Colors.blue,
                            onPressed: () {
                              // Method to execute
                            },
                            child: Text('Copy'),
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      flex: 2, // we define the width of the button
                      child: Container(
                        // height: 50, we define the height of the button
                        child: Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 10.0),
                          child: RaisedButton(
                            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                            textColor: Colors.white,
                            color: Colors.green,
                            onPressed: () {
                              // Method to execute
                            },
                            child: Text('Paste'),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),

Is there a way to avoid null check before the for-each loop iteration starts?

If possible, you should design your code such that the collections aren't null in the first place.

null collections are bad practice (for this reason); you should use empty collections instead. (eg, Collections.emptyList())

Alternatively, you could make a wrapper class that implements Iterable and takes a collections, and handles a null collection.
You could then write foreach(T obj : new Nullable<T>(list1))

newline in <td title="">

Using &#xA; Works in Chrome to create separate lines in a tooltip.

How to get all the AD groups for a particular user?

This is how I list all the groups (direct and indirect) for a specific Distinguished Name:

The string 1.2.840.113556.1.4.1941 specifies LDAP_MATCHING_RULE_IN_CHAIN.

This rule is limited to filters that apply to the DN. This is a special "extended" match operator that walks the chain of ancestry in objects all the way to the root until it finds a match.

This method is 25 times faster than the UserPrincipal.GetGroups() method in my testing.

Note: The primary group (typically Domain Users) is not returned by this or GetGroups() method. To get the primary group name too, I've confirmed this method works.

Additionally, I found this list of LDAP filters extremely useful.

private IEnumerable<string> GetGroupsForDistinguishedName(DirectoryEntry domainDirectoryEntry, string distinguishedName)
{
    var groups = new List<string>();
    if (!string.IsNullOrEmpty(distinguishedName))
    {
        var getGroupsFilterForDn = $"(&(objectCategory=group)(member:1.2.840.113556.1.4.1941:={distinguishedName}))";
        using (DirectorySearcher dirSearch = new DirectorySearcher(domainDirectoryEntry))
        {
            dirSearch.Filter = getGroupsFilterForDn;
            dirSearch.PropertiesToLoad.Add("name");

            using (var results = dirSearch.FindAll())
            {
                foreach (SearchResult result in results)
                {
                    if (result.Properties.Contains("name"))
                        groups.Add((string)result.Properties["name"][0]);
                }
            }
        }
    }

    return groups;
}

Find stored procedure by name

You can use:

select * 
from 
   sys.procedures 
where 
   name like '%name_of_proc%'

if you need the code you can look in the syscomments table

select text 
from 
    syscomments c
    inner join sys.procedures p on p.object_id = c.object_id
where 
    p.name like '%name_of_proc%'

Edit Update:

you can can also use the ansi standard version

SELECT * 
FROM 
    INFORMATION_SCHEMA.ROUTINES 
WHERE 
    ROUTINE_NAME LIKE '%name_of_proc%'

How do I escape reserved words used as column names? MySQL/Create Table

If you are interested in portability between different SQL servers you should use ANSI SQL queries. String escaping in ANSI SQL is done by using double quotes ("). Unfortunately, this escaping method is not portable to MySQL, unless it is set in ANSI compatibility mode.

Personally, I always start my MySQL server with the --sql-mode='ANSI' argument since this allows for both methods for escaping. If you are writing queries that are going to be executed in a MySQL server that was not setup / is controlled by you, here is what you can do:

  • Write all you SQL queries in ANSI SQL
  • Enclose them in the following MySQL specific queries:

    SET @OLD_SQL_MODE=@@SQL_MODE;
    SET SESSION SQL_MODE='ANSI';
    -- ANSI SQL queries
    SET SESSION SQL_MODE=@OLD_SQL_MODE;
    

This way the only MySQL specific queries are at the beginning and the end of your .sql script. If you what to ship them for a different server just remove these 3 queries and you're all set. Even more conveniently you could create a script named: script_mysql.sql that would contain the above mode setting queries, source a script_ansi.sql script and reset the mode.

Is it possible to change the location of packages for NuGet?

In order to change the path for projects using PackageReference instead of packages.config you need to use globalPackagesFolder

From https://docs.microsoft.com/en-us/nuget/reference/nuget-config-file

globalPackagesFolder (projects using PackageReference only)

The location of the default global packages folder. The default is %userprofile%.nuget\packages (Windows) or ~/.nuget/packages (Mac/Linux). A relative path can be used in project-specific nuget.config files. This setting is overridden by the NUGET_PACKAGES environment variable, which takes precedence.

repositoryPath (packages.config only)

The location in which to install NuGet packages instead of the default $(Solutiondir)/packages folder. A relative path can be used in project-specific nuget.config files. This setting is overridden by the NUGET_PACKAGES environment variable, which takes precedence.

<config>
    <add key="globalPackagesFolder" value="c:\packageReferences" />
    <add key="repositoryPath" value="c:\packagesConfig" />
</config>

I put Nuget.config next to my solution file and it worked.

Datatable to html Table

I have seen some solutions here worth noting, as Omer Eldan posted. but here follows. ASP C#

using System.Data;
using System.Web.UI.HtmlControls;

public static Table DataTableToHTMLTable(DataTable dt, bool includeHeaders)
{
    Table tbl = new Table();
    TableRow tr = null;
    TableCell cell = null;

    int rows = dt.Rows.Count;
    int cols = dt.Columns.Count;

    if (includeHeaders)
    {
        TableHeaderRow htr = new TableHeaderRow();
        TableHeaderCell hcell = null;
        for (int i = 0; i < cols; i++)
        {
            hcell = new TableHeaderCell();
            hcell.Text = dt.Columns[i].ColumnName.ToString();
            htr.Cells.Add(hcell);
        }
        tbl.Rows.Add(htr);
    }

    for (int j = 0; j < rows; j++)
    {
        tr = new TableRow();
        for (int k = 0; k < cols; k++)
        {
            cell = new TableCell();
            cell.Text = dt.Rows[j][k].ToString();
            tr.Cells.Add(cell);
        }
        tbl.Rows.Add(tr);
    }
    return tbl;
}

why this solution? Because you can easily just add this to a panel ie:

panel.Controls.Add(DataTableToHTMLTable(dtExample,true));

Second question , why do you have one column datatables and not just array's? Are you sure that these DataTables are uniform, because if the data is jagged then it's no use. If You really have to join these DataTables, there is many examples of Linq operations, or just use (beware though of same name columns as this will conflict in both linq operations and this solution if not handled):

public DataTable joinUniformTable(DataTable dt1, DataTable dt2)
{
    int dt2ColsCount = dt2.Columns.Count;
    int dt1lRowsCount = dt1.Rows.Count;

    DataColumn column;
    for (int i = 0; i < dt2ColsCount; i++)
    {
        column = new DataColumn();
        string colName = dt2.Columns[i].ColumnName;
        System.Type colType = dt2.Columns[i].DataType;
        column.ColumnName = colName;
        column.DataType = colType;
        dt1.Columns.Add(column);

        for (int j = 0; j < dt1lRowsCount; j++)
        {
            dt1.Rows[j][colName] = dt2.Rows[j][colName];
        }
    }
    return dt1;
}

and your solution would look something like:

panel.Controls.Add(DataTableToHTMLTable(joinUniformTable(joinUniformTable(LivDT,BathDT),BedDT),true));

interpret the rest, and have fun.

center aligning a fixed position div

if you don't want to use the wrapper method. then you can do this:

.fixed_center_div {
  position: fixed;
  width: 200px;
  height: 200px;
  left: 50%;
  top: 50%;
  margin-left: -100px; /* 50% of width */
  margin-top: -100px; /* 50% of height */
}

C/C++ check if one bit is set in, i.e. int variable

if you just want a real hard coded way:

 #define IS_BIT3_SET(var) ( ((var) & 0x04) == 0x04 )

note this hw dependent and assumes this bit order 7654 3210 and var is 8 bit.

#include "stdafx.h"
#define IS_BIT3_SET(var) ( ((var) & 0x04) == 0x04 )
int _tmain(int argc, _TCHAR* argv[])
{
    int temp =0x5E;
    printf(" %d \n", IS_BIT3_SET(temp));
    temp = 0x00;
    printf(" %d \n", IS_BIT3_SET(temp));
    temp = 0x04;
    printf(" %d \n", IS_BIT3_SET(temp));
    temp = 0xfb;
    printf(" %d \n", IS_BIT3_SET(temp));
    scanf("waitng %d",&temp);

    return 0;
}

Results in:

1 0 1 0

PermissionError: [WinError 5] Access is denied python using moviepy to write gif

I've run into this as well, solution is usually to be sure to run the program as an administrator (right click, run as administrator.)

IIS error, Unable to start debugging on the webserver

I've faced this problem, then I found out that i gotta run Visual Studio as admin in order to debug the project.

Hope it helps!

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

It's called the ternary operator. For some more info, here's another question I answered regarding this:

How to write an IF else statement without 'else'

How can Perl's print add a newline by default?

Perhaps you want to change your output record separator to linefeed with:

local $\ = "\n";

$ perl -e 'print q{hello};print q{goodbye}' | od -c
0000000    h   e   l   l   o   g   o   o   d   b   y   e                
0000014
$ perl -e '$\ = qq{\n}; print q{hello};print q{goodbye}' | od -c
0000000    h   e   l   l   o  \n   g   o   o   d   b   y   e  \n        
0000016

Update: my answer speaks to capability rather than advisability. I don't regard adding "\n" at the end of lines to be a "pesky" chore, but if someone really wants to avoid them, this is one way. If I had to maintain a bit of code that uses this technique, I'd probably refactor it out pronto.

C++ convert from 1 char to string?

All of

std::string s(1, c); std::cout << s << std::endl;

and

std::cout << std::string(1, c) << std::endl;

and

std::string s; s.push_back(c); std::cout << s << std::endl;

worked for me.

Html.RenderPartial() syntax with Razor

If you are given this format it takes like a link to another page or another link.partial view majorly used for renduring the html files from one place to another.

Determine installed PowerShell version

The easiest way to forget this page and never return to it is to learn the Get-Variable:

Get-Variable | where {$_.Name -Like '*version*'} | %{$_[0].Value}

There is no need to remember every variable. Just Get-Variable is enough (and "There should be something about version").

git replace local version with remote version

I would checkout the remote file from the "master" (the remote/origin repository) like this:

git checkout master <FileWithPath>

Example: git checkout master components/indexTest.html

Turn off deprecated errors in PHP 5.3

To only get those errors that cause the application to stop working, use:

error_reporting(E_ALL ^ (E_NOTICE | E_WARNING | E_DEPRECATED));

This will stop showing notices, warnings, and deprecated errors.

How to Maximize window in chrome using webDriver (python)

You could use ChromeOptions and set suitable argument:

options = ChromeOptions()
options.add_argument("--start-maximized")
driver = ChromeDriver(options)

hasNext in Python iterators?

You can tee the iterator using, itertools.tee, and check for StopIteration on the teed iterator.

Extract string between two strings in java

Your regex looks correct, but you're splitting with it instead of matching with it. You want something like this:

// Untested code
Matcher matcher = Pattern.compile("<%=(.*?)%>").matcher(str);
while (matcher.find()) {
    System.out.println(matcher.group());
}

Get the current time in C

If you just need the time without the date.

  time_t rawtime;
  struct tm * timeinfo;
  time( &rawtime );
  timeinfo = localtime( &rawtime );
  printf("%02d:%02d:%02d", timeinfo->tm_hour, timeinfo->tm_min, 
    timeinfo->tm_sec);

Leap year calculation

There are on average, roughly 365.2425 days in a year at the moment (the Earth is slowing down but let's ignore that for now).

The reason we have leap years every 4 years is because that gets us to 365.25 on average [(365+365+365+366) / 4 = 365.25, 1461 days in 4 years].

The reason we don't have leap years on the 100-multiples is to get us to 365.24 `[(1461 x 25 - 1) / 100 = 365.24, 36,524 days in 100 years.

Then the reason we once again have a leap year on 400-multiples is to get us to 365.2425 [(36,524 x 4 + 1) / 400 = 365.2425, 146,097 days in 400 years].

I believe there may be another rule at 3600-multiples but I've never coded for it (Y2K was one thing but planning for one and a half thousand years into the future is not necessary in my opinion - keep in mind I've been wrong before).

So, the rules are, in decreasing priority:

  • multiple of 400 is a leap year.
  • multiple of 100 is not a leap year.
  • multiple of 4 is a leap year.
  • anything else is not a leap year.

Need to find a max of three numbers in java

You should know more about java.lang.Math.max:

  1. java.lang.Math.max(arg1,arg2) only accepts 2 arguments but you are writing 3 arguments in your code.
  2. The 2 arguments should be double,int,long and float but your are writing String arguments in Math.max function. You need to parse them in the required type.

You code will produce compile time error because of above mismatches.

Try following updated code, that will solve your purpose:

import java.lang.Math;
import java.util.Scanner;
public class max {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Please input 3 integers: ");
        int x = Integer.parseInt(keyboard.nextLine());
        int y = Integer.parseInt(keyboard.nextLine());
        int z = Integer.parseInt(keyboard.nextLine());
        int max = Math.max(x,y);
        if(max>y){ //suppose x is max then compare x with z to find max number
            max = Math.max(x,z);    
        }
        else{ //if y is max then compare y with z to find max number
            max = Math.max(y,z);    
        }
        System.out.println("The max of three is: " + max);
    }
} 

How do I fix the indentation of an entire file in Vi?

Before pasting into the terminal, try :set paste and then :set nopaste after you're done. This will turn off the auto-indent, line-wrap and other features that are messing up your paste.

edit: Also, I should point out that a much better result than = indenting can usually be obtained by using an external program. For example, I run :%!perltidy all the time. astyle, cindent, etc. can also be used. And, of course, you can map those to a key stroke, and map different ones to the same keystroke depending on file type.

How to find an available port?

This works for me on Java 6

    ServerSocket serverSocket = new ServerSocket(0);
    System.out.println("listening on port " + serverSocket.getLocalPort());

Why doesn't Mockito mock static methods?

Mockito returns objects but static means "class level,not object level"So mockito will give null pointer exception for static.

Encrypt and Decrypt text with RSA in PHP

No application written in 2017 (or thereafter) that intends to incorporate serious cryptography should use RSA any more. There are better options for PHP public-key cryptography.

There are two big mistakes that people make when they decide to encrypt with RSA:

  1. Developers choose the wrong padding mode.
  2. Since RSA cannot, by itself, encrypt very long strings, developers will often break a string into small chunks and encrypt each chunk independently. Sort of like ECB mode.

The Best Alternative: sodium_crypto_box_seal() (libsodium)

$keypair = sodium_crypto_box_keypair();
$publicKey = sodium_crypto_box_publickey($keypair);
// ...
$encrypted = sodium_crypto_box_seal(
    $plaintextMessage,
    $publicKey
);
// ...
$decrypted = sodium_crypto_box_seal_open(
    $encrypted,
    $keypair
);

Simple and secure. Libsodium will be available in PHP 7.2, or through PECL for earlier versions of PHP. If you need a pure-PHP polyfill, get paragonie/sodium_compat.

Begrudgingly: Using RSA Properly

The only reason to use RSA in 2017 is, "I'm forbidden to install PECL extensions and therefore cannot use libsodium, and for some reason cannot use paragonie/sodium_compat either."

Your protocol should look something like this:

  1. Generate a random AES key.
  2. Encrypt your plaintext message with the AES key, using an AEAD encryption mode or, failing that, CBC then HMAC-SHA256.
  3. Encrypt your AES key (step 1) with your RSA public key, using RSAES-OAEP + MGF1-SHA256
  4. Concatenate your RSA-encrypted AES key (step 3) and AES-encrypted message (step 2).

Instead of implementing this yourself, check out EasyRSA.

Further reading: Doing RSA in PHP correctly.

Countdown timer using Moment js

In the last statement you are converting the duration to time which also considers the timezone. I assume that your timezone is +530, so 5 hours and 30 minutes gets added to 30 minutes. You can do as given below.

var eventTime= 1366549200; // Timestamp - Sun, 21 Apr 2013 13:00:00 GMT
var currentTime = 1366547400; // Timestamp - Sun, 21 Apr 2013 12:30:00 GMT
var diffTime = eventTime - currentTime;
var duration = moment.duration(diffTime*1000, 'milliseconds');
var interval = 1000;

setInterval(function(){
  duration = moment.duration(duration - interval, 'milliseconds');
    $('.countdown').text(duration.hours() + ":" + duration.minutes() + ":" + duration.seconds())
}, interval);

Run javascript script (.js file) in mongodb including another file inside js

To call external file you can use :

load ("path\file")

Exemple: if your file.js file is on your "Documents" file (on windows OS), you can type:

load ("C:\users\user_name\Documents\file.js")

How to send password securely over HTTP?

If your webhost allows it, or you will need to deal with sensitive data, then use HTTPS, period. (It's often required by the law afaik).

Otherwise if you want to do something over HTTP. I would do something like this.

  1. The server embeds its public key into the login page.
  2. The client populates the login form and clicks submit.
  3. An AJAX request gets the current timestamp from the server.
  4. Client side script concatenates the credentials, the timestamp and a salt (hashed from analog data eg. mouse movements, key press events), encrypts it using the public key.
  5. Submits the resulting hash.
  6. Server decrypts the hash
  7. Checks if the timestamp is recent enough (allows a short 5-10 second window only). Rejects the login if the timestamp is too old.
  8. Stores the hash for 20 seconds. Rejects the same hash for login during this interval.
  9. Authenticates the user.

So this way the password is protected and the same authentication hash cannot be replayed.

About the security of the session token. That's a bit harder. But it's possible to make reusing a stolen session token a bit harder.

  1. The server sets an extra session cookie which contains a random string.
  2. The browser sends back this cookie on the next request.
  3. The server checks the value in the cookie, if it's different then it destroys the session, otherwise all is okay.
  4. The server sets the cookie again with different text.

So if the session token got stolen, and a request is sent up by someone else, then on the original user's next request the session will be destroyed. So if the user actively browsing the site, clicking on links often, then the thief won't go far with the stolen token. This scheme can be fortified by requiring another authentication for the sensitive operations (like account deletion).

EDIT: Please note this doesn't prevent MITM attacks if the attacker sets up their own page with a different public key and proxies requests to the server. To protect against this the public key must be pinned in the browser's local storage or within the app to detect these kind of tricks.

About the implementation: RSA is probably to most known algorithm, but it's quite slow for long keys. I don't know how fast a PHP or Javascript implementation of would be. But probably there are a faster algorithms.

Java 'file.delete()' Is not Deleting Specified File

As other answers indicate, on Windows you cannot delete a file that is open. However one other thing that can stop a file from being deleted on Windows is if it is is mmap'd to a MappedByteBuffer (or DirectByteBuffer) -- if so, the file cannot be deleted until the byte buffer is garbage collected. There is some relatively safe code for forcibly closing (cleaning) a DirectByteBuffer before it is garbage collected here: https://github.com/classgraph/classgraph/blob/master/src/main/java/nonapi/io/github/classgraph/utils/FileUtils.java#L606 After cleaning the ByteBuffer, you can delete the file. However, make sure you never use the ByteBuffer again after cleaning it, or the JVM will crash.

Making a <button> that's a link in HTML

_x000D_
_x000D_
<a id="reset-authenticator" asp-page="./ResetAuthenticator"><input type="button" class="btn btn-primary" value="Reset app" /></a>
_x000D_
_x000D_
_x000D_

Selenium WebDriver How to Resolve Stale Element Reference Exception?

After deep investigation of the problem I found that error occurs selecting DIV elements that were added for Bootstrap only. Chrome browser removes such DIVS and the error occurs. It is enough to step down and select real element for fixing an error. For example, my modal dialog has structure:

<div class="modal-content" uib-modal-transclude="">
    <div class="modal-header">
        ...
    </div>
    <div class="modal-body">
        <form class="form-horizontal ...">
            ...
        </form>
    <div>
<div>

Selecting div class="modal-body" generates an error, selecting form ... works as it would.

Is it possible to use raw SQL within a Spring Repository

YES, You can do this on bellow ways:

1. By CrudRepository (Projection)

Spring Data Repositories usually return the domain model when using query methods. However, sometimes, you may need to alter the view of that model for various reasons.

Suppose your entity is like this :

    import javax.persistence.*;
    import java.math.BigDecimal;

    @Entity
    @Table(name = "USER_INFO_TEST")
    public class UserInfoTest {
        private int id;
        private String name;
        private String rollNo;

        public UserInfoTest() {
        }

        public UserInfoTest(int id, String name) {
        this.id = id;
        this.name = name;
        }

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "ID", nullable = false, precision = 0)
        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        @Basic
        @Column(name = "name", nullable = true)
        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Basic
        @Column(name = "roll_no", nullable = true)
        public String getRollNo() {
            return rollNo;
        }

        public void setRollNo(String rollNo) {
            this.rollNo = rollNo;
        }
    }

Now your Projection class is like bellow. It can those fields that you needed.

public interface IUserProjection {
     int getId();
     String getName();
     String getRollNo();
}

And Your Data Access Object(Dao) is like bellow :

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

import java.util.ArrayList;

public interface UserInfoTestDao extends CrudRepository<UserInfoTest,Integer> {
    @Query(value = "select id,name,roll_no from USER_INFO_TEST where rollNo = ?1", nativeQuery = true)
    ArrayList<IUserProjection> findUserUsingRollNo(String rollNo);
}

Now ArrayList<IUserProjection> findUserUsingRollNo(String rollNo) will give you the list of user.

2. Using EntityManager

Suppose your query is "select id,name from users where roll_no = 1001".

Here query will return a object with id and name column. Your Response class is like bellow:

Your Response class is like:

public class UserObject{
        int id;
        String name;
        String rollNo;

        public UserObject(Object[] columns) {
            this.id = (columns[0] != null)?((BigDecimal)columns[0]).intValue():0;
            this.name = (String) columns[1];
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getRollNo() {
            return rollNo;
        }

        public void setRollNo(String rollNo) {
            this.rollNo = rollNo;
        }
    }

here UserObject constructor will get a Object Array and set data with object.

public UserObject(Object[] columns) {
            this.id = (columns[0] != null)?((BigDecimal)columns[0]).intValue():0;
            this.name = (String) columns[1];
        }

Your query executing function is like bellow :

public UserObject getUserByRoll(EntityManager entityManager,String rollNo) {

        String queryStr = "select id,name from users where roll_no = ?1";
        try {
            Query query = entityManager.createNativeQuery(queryStr);
            query.setParameter(1, rollNo);

            return new UserObject((Object[]) query.getSingleResult());
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

Here you have to import bellow packages:

import javax.persistence.Query;
import javax.persistence.EntityManager;

Now your main class, you have to call this function. First get EntityManager and call this getUserByRoll(EntityManager entityManager,String rollNo) function. Calling procedure is given bellow:

Here is the Imports

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

get EntityManager from this way:

@PersistenceContext
private EntityManager entityManager;

UserObject userObject = getUserByRoll(entityManager,"1001");

Now you have data in this userObject.

Note:

query.getSingleResult() return a object array. You have to maintain the column position and data type with query column position.

select id,name from users where roll_no = 1001 

query return a array and it's [0] --> id and [1] -> name.

More info visit this thread and this Thread

Thanks :)

mysql: SOURCE error 2?

IF YOU ARE USING MYSQL INSIDE DOCKER

Note that if you are running MySQL inside docker then you must first copy the dump into your MySQL docker environment. To do that follow the steps below

  1. First, check and copy the container ID for your MySQL docker by:

    sudo docker ps

  2. Copy the SQL dump file into your container using:

    sudo docker cp /path/to/sql/file.sql MysqlDockerID:/

    This will copy the dump file into the docker root folder if you want to copy the file inside any other directory/path inside docker replace the '/' after 'MysqlDockerID:' with the path you want appropriate one.

  3. Now to interact with MySQL inside a running container run the following command:

    sudo docker exec -it MysqlDockerID bin/bash

  4. Now connect to the MySQL using the terminal by:

    mysql -u yourUserName -p

    This will now ask you for the password. Enter the correct password to proceed.

  5. List the databases available by:

    show Databases;

    This will list out the available databases

  6. Assuming your database name where you want to import dump to is 'MyDatabase'. Switch to that using:

    use MyDatabase

  7. Now you can import the file by typing:

    source file.sql

    Remember the above command works if you have copied your file into your root folder (using step 2). If you have copied it to any other path make sure you use that same path instead

Java 8 Distinct by property

We can also use RxJava (very powerful reactive extension library)

Observable.from(persons).distinct(Person::getName)

or

Observable.from(persons).distinct(p -> p.getName())

Passing command line arguments from Maven as properties in pom.xml

I used the properties plugin to solve this.

Properties are defined in the pom, and written out to a my.properties file, where they can then be accessed from your Java code.

In my case it is test code that needs to access this properties file, so in the pom the properties file is written to maven's testOutputDirectory:

<configuration>
    <outputFile>${project.build.testOutputDirectory}/my.properties</outputFile>
</configuration>

Use outputDirectory if you want properties to be accessible by your app code:

<configuration>
    <outputFile>${project.build.outputDirectory}/my.properties</outputFile>
</configuration>

For those looking for a fuller example (it took me a bit of fiddling to get this working as I didn't understand how naming of properties tags affects ability to retrieve them elsewhere in the pom file), my pom looks as follows:

<dependencies>
     <dependency>
      ...
     </dependency>
</dependencies>

<properties>
    <app.env>${app.env}</app.env>
    <app.port>${app.port}</app.port>
    <app.domain>${app.domain}</app.domain>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.20</version>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>properties-maven-plugin</artifactId>
            <version>1.0.0</version>
            <executions>
                <execution>
                    <phase>generate-resources</phase>
                    <goals>
                        <goal>write-project-properties</goal>
                    </goals>
                    <configuration>
                        <outputFile>${project.build.testOutputDirectory}/my.properties</outputFile>
                    </configuration>
                </execution>
            </executions>
        </plugin>

    </plugins>
</build>

And on the command line:

mvn clean test -Dapp.env=LOCAL -Dapp.domain=localhost -Dapp.port=9901

So these properties can be accessed from the Java code:

 java.io.InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("my.properties");
 java.util.Properties properties = new Properties();
 properties.load(inputStream);
 appPort = properties.getProperty("app.port");
 appDomain = properties.getProperty("app.domain");

Average of multiple columns

This works in MariaDB:

SELECT Req_ID, (R1+R2+R3+R4+R5)/5 AS Average
FROM Request
GROUP BY Req_ID;

Which loop is faster, while or for?

I find the fastest loop is a reverse while loop, e.g:

var i = myArray.length;
while(i--){
  // Do something
}

Scanning Java annotations at runtime

Google Reflections seems to be much faster than Spring. Found this feature request that adresses this difference: http://www.opensaga.org/jira/browse/OS-738

This is a reason to use Reflections as startup time of my application is really important during development. Reflections seems also to be very easy to use for my use case (find all implementers of an interface).

How to copy an object in Objective-C

There is also the use of the -> operator for copying. For Example:

-(id)copyWithZone:(NSZone*)zone
{
    MYClass* copy = [MYClass new];
    copy->_property1 = self->_property1;
    ...
    copy->_propertyN = self->_propertyN;
    return copy;
}

The reasoning here is the resulting copied object should reflect the state of the original object. The "." operator could introduce side effects as this one calls getters which in turn may contain logic.

Environ Function code samples for VBA

Some time when we use Environ() function we may get the Library or property not found error. Use VBA.Environ() or VBA.Environ$() to avoid the error.

How To Make Circle Custom Progress Bar in Android

I have solved this cool custom progress bar by creating the custom view. I have overriden the onDraw() method to draw the circles, filled arc and text on the canvas.

following is the custom progress bar

import android.annotation.TargetApi;

import android.content.Context;

import android.graphics.Canvas;

import android.graphics.Paint;

import android.graphics.Path;

import android.graphics.Rect;

import android.graphics.RectF;

import android.os.Build;

import android.util.AttributeSet;

import android.view.View;

import com.investorfinder.utils.UiUtils;


public class CustomProgressBar extends View {


private int max = 100;

private int progress;

private Path path = new Path();

int color = 0xff44C8E5;

private Paint paint;

private Paint mPaintProgress;

private RectF mRectF;

private Paint textPaint;

private String text = "0%";

private final Rect textBounds = new Rect();

private int centerY;

private int centerX;

private int swipeAndgle = 0;


public CustomProgressBar(Context context) {
    super(context);
    initUI();
}

public CustomProgressBar(Context context, AttributeSet attrs) {
    super(context, attrs);
    initUI();
}

public CustomProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    initUI();
}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public CustomProgressBar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
    initUI();
}

private void initUI() {
    paint = new Paint();
    paint.setAntiAlias(true);
    paint.setStrokeWidth(UiUtils.dpToPx(getContext(), 1));
    paint.setStyle(Paint.Style.STROKE);
    paint.setColor(color);


    mPaintProgress = new Paint();
    mPaintProgress.setAntiAlias(true);
    mPaintProgress.setStyle(Paint.Style.STROKE);
    mPaintProgress.setStrokeWidth(UiUtils.dpToPx(getContext(), 9));
    mPaintProgress.setColor(color);

    textPaint = new Paint();
    textPaint.setAntiAlias(true);
    textPaint.setStyle(Paint.Style.FILL);
    textPaint.setColor(color);
    textPaint.setStrokeWidth(2);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int viewWidth = MeasureSpec.getSize(widthMeasureSpec);
    int viewHeight = MeasureSpec.getSize(heightMeasureSpec);

    int radius = (Math.min(viewWidth, viewHeight) - UiUtils.dpToPx(getContext(), 2)) / 2;

    path.reset();

    centerX = viewWidth / 2;
    centerY = viewHeight / 2;
    path.addCircle(centerX, centerY, radius, Path.Direction.CW);

    int smallCirclRadius = radius - UiUtils.dpToPx(getContext(), 7);
    path.addCircle(centerX, centerY, smallCirclRadius, Path.Direction.CW);
    smallCirclRadius += UiUtils.dpToPx(getContext(), 4);

    mRectF = new RectF(centerX - smallCirclRadius, centerY - smallCirclRadius, centerX + smallCirclRadius, centerY + smallCirclRadius);

    textPaint.setTextSize(radius * 0.5f);
}


@Override
protected void onDraw(Canvas canvas) {


    super.onDraw(canvas);

    canvas.drawPath(path, paint);

    canvas.drawArc(mRectF, 270, swipeAndgle, false, mPaintProgress);

    drawTextCentred(canvas);

}

public void drawTextCentred(Canvas canvas) {

    textPaint.getTextBounds(text, 0, text.length(), textBounds);

    canvas.drawText(text, centerX - textBounds.exactCenterX(), centerY - textBounds.exactCenterY(), textPaint);
}

public void setMax(int max) {
    this.max = max;
}

public void setProgress(int progress) {
    this.progress = progress;

    int percentage = progress * 100 / max;

    swipeAndgle = percentage * 360 / 100;

    text = percentage + "%";

    invalidate();
}

public void setColor(int color) {
    this.color = color;
}
}

In layout XML

<com.your.package.name.CustomProgressBar
            android:id="@+id/progress_bar"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/txt_title"
            android:layout_marginRight="15dp" />

in activity

CustomProgressBar progressBar = (CustomProgressBar)findViewById(R.id.progress_bar);

    progressBar.setMax(9);

    progressBar.setProgress(5);

Find and replace string values in list

words = [w.replace('[br]', '<br />') for w in words]

These are called List Comprehensions.

how to get list of port which are in use on the server

Open up a command prompt then type...

netstat -a

Very Long If Statement in Python

Here is the example directly from PEP 8 on limiting line length:

class Rectangle(Blob):

    def __init__(self, width, height,
                 color='black', emphasis=None, highlight=0):
        if (width == 0 and height == 0 and
                color == 'red' and emphasis == 'strong' or
                highlight > 100):
            raise ValueError("sorry, you lose")
        if width == 0 and height == 0 and (color == 'red' or
                                           emphasis is None):
            raise ValueError("I don't think so -- values are %s, %s" %
                             (width, height))
        Blob.__init__(self, width, height,
                      color, emphasis, highlight)

How do I horizontally center a span element inside a div

I assume you want to center them on one line and not on two separate lines based on your fiddle. If that is the case, try the following css:

 div { background:red;
      overflow:hidden;
}
span { display:block;
       margin:0 auto;
       width:200px;
}
span a { padding:5px 10px;
         color:#fff;
         background:#222;
}

I removed the float since you want to center it, and then made the span surrounding the links centered by adding margin:0 auto to them. Finally, I added a static width to the span. This centers the links on one line within the red div.

How to SELECT the last 10 rows of an SQL table which has no ID field?

you can with code select 10 row from end of table. select * from (SELECT * FROM table1 order by id desc LIMIT 10) as table2 order by id"

How to use zIndex in react-native

UPDATE: Supposedly, zIndex has been added to the react-native library. I've been trying to get it to work without success. Check here for details of the fix.

How do I revert an SVN commit?

I tried the above, (svn merge) and you're right, it does jack. However

svn update -r <revision> <target> [-R]

seems to work, but isn't permanent (my svn is simply showing an old revision). So I had to

mv <target> <target backup>
svn update <target>
mv <target backup> <target>
svn commit -m "Reverted commit on <target>" <target>

In my particular case my target is interfaces/AngelInterface.php. I made changes to the file, committed them, updated the build computer ran the phpdoc compiler and found my changes were a waste of time. svn log interfaces/AngelInterface.php shows my change as r22060 and the previous commit on that file was r22059. So I can svn update -r 22059 interfaces/AngelInterface.php and I end up with code as it was in -r22059 again. Then :-

mv interfaces/AngelInterface.php interfaces/AngelInterface.php~
svn update interfaces/AngelInterface.php
mv interfaces/AngelInterface.php~ interfaces/AngelInterface.php
svn commit -m "reverted -r22060" interfaces/AngelInterface.php

Alternatively I could do the same thing on a directory, by specifying . -R in place of interfaces/AngelInterface.php in all the above.

How to send json data in POST request using C#

This works for me.

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new 

StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = new JavaScriptSerializer().Serialize(new
                {
                    Username = "myusername",
                    Password = "password"
                });

    streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}

How can I check if a MySQL table exists with PHP?

<?php 
$connection = mysqli_connect("localhost","root","","php_sample_login_register"); 

if ($connection){
        echo "DB is Connected <br>";
        $sql = "CREATE TABLE user(
            id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
            name VARCHAR(255)NOT NULL,
            email VARCHAR(255)NOT NULL,
            password VARCHAR(255) NOT NULL
            );";
        if(mysqli_query($connection,$sql)) {
            echo "Created user table";
        } else{
            echo "User table already exists";
        }
    } else {
        echo "error : DB isnot connected";
    } ?>

Draw a line in a div

_x000D_
_x000D_
$('.line').click(function() {_x000D_
  $(this).toggleClass('red');_x000D_
});
_x000D_
.line {_x000D_
  border: 0;_x000D_
  background-color: #000;_x000D_
  height: 3px;_x000D_
  cursor: pointer;_x000D_
}_x000D_
.red {_x000D_
  background-color: red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<hr class="line"></hr>_x000D_
<p>click the line</p>
_x000D_
_x000D_
_x000D_

Installed SSL certificate in certificate store, but it's not in IIS certificate list

I had similar issue and tried all possible combinations as well as accepted answer without any luck. Finally I found DigiCert SSL Utility which helped me to install certificate in couple clicks. You can download it here. Hope this answer will save some time for others.

Way to run Excel macros from command line or batch file?

You can launch Excel, open the workbook and run the macro from a VBScript file.

Copy the code below into Notepad.

Update the 'MyWorkbook.xls' and 'MyMacro' parameters.

Save it with a vbs extension and run it.

Option Explicit

On Error Resume Next

ExcelMacroExample

Sub ExcelMacroExample() 

  Dim xlApp 
  Dim xlBook 

  Set xlApp = CreateObject("Excel.Application") 
  Set xlBook = xlApp.Workbooks.Open("C:\MyWorkbook.xls", 0, True) 
  xlApp.Run "MyMacro"
  xlApp.Quit 

  Set xlBook = Nothing 
  Set xlApp = Nothing 

End Sub 

The key line that runs the macro is:

xlApp.Run "MyMacro"

How to format background color using twitter bootstrap?

Just add a div around the container so it looks like:

<div style="background: red;">
  <div class="container marketing">
    <h2 style="padding-top: 60px;"></h2>
  </div>
</div>

Executing a command stored in a variable from PowerShell

Here is yet another way without Invoke-Expression but with two variables (command:string and parameters:array). It works fine for me. Assume 7z.exe is in the system path.

$cmd = '7z.exe'
$prm = 'a', '-tzip', 'c:\temp\with space\test1.zip', 'C:\TEMP\with space\changelog'

& $cmd $prm

If the command is known (7z.exe) and only parameters are variable then this will do

$prm = 'a', '-tzip', 'c:\temp\with space\test1.zip', 'C:\TEMP\with space\changelog'

& 7z.exe $prm

BTW, Invoke-Expression with one parameter works for me, too, e.g. this works

$cmd = '& 7z.exe a -tzip "c:\temp\with space\test2.zip" "C:\TEMP\with space\changelog"'

Invoke-Expression $cmd

P.S. I usually prefer the way with a parameter array because it is easier to compose programmatically than to build an expression for Invoke-Expression.

check if file exists on remote host with ssh

On CentOS machine, the oneliner bash that worked for me was:

if ssh <servername> "stat <filename> > /dev/null 2>&1"; then echo "file exists"; else echo "file doesnt exits"; fi

It needed I/O redirection (as the top answer) as well as quotes around the command to be run on remote.

Select the top N values by group

Just sort by whatever (mpg for example, question is not clear on this)

mt <- mtcars[order(mtcars$mpg), ]

then use the by function to get the top n rows in each group

d <- by(mt, mt["cyl"], head, n=4)

If you want the result to be a data.frame:

Reduce(rbind, d)

Edit: Handling ties is more difficult, but if all ties are desired:

by(mt, mt["cyl"], function(x) x[rank(x$mpg) %in% sort(unique(rank(x$mpg)))[1:4], ])

Another approach is to break ties based on some other information, e.g.,

mt <- mtcars[order(mtcars$mpg, mtcars$hp), ]
by(mt, mt["cyl"], head, n=4)

How to set a transparent background of JPanel?

Alternatively, consider The Glass Pane, discussed in the article How to Use Root Panes. You could draw your "Feature" content in the glass pane's paintComponent() method.

Addendum: Working with the GlassPaneDemo, I added an image:

//Set up the content pane, where the "main GUI" lives.
frame.add(changeButton, BorderLayout.SOUTH);
frame.add(new JLabel(new ImageIcon("img.jpg")), BorderLayout.CENTER);

and altered the glass pane's paintComponent() method:

protected void paintComponent(Graphics g) {
    if (point != null) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(
            RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setComposite(AlphaComposite.getInstance(
            AlphaComposite.SRC_OVER, 0.3f));
        g2d.setColor(Color.yellow);
        g2d.fillOval(point.x, point.y, 120, 60);
    }
}

enter image description here

As noted here, Swing components must honor the opaque property; in this variation, the ImageIcon completely fills the BorderLayout.CENTER of the frame's default layout.

Which characters need to be escaped in HTML?

The exact answer depends on the context. In general, these characters must not be present (HTML 5.2 §3.2.4.2.5):

Text nodes and attribute values must consist of Unicode characters, must not contain U+0000 characters, must not contain permanently undefined Unicode characters (noncharacters), and must not contain control characters other than space characters. This specification includes extra constraints on the exact value of Text nodes and attribute values depending on their precise context.

For elements in HTML, the constraints of the Text content model also depends on the kind of element. For instance, an "<" inside a textarea element does not need to be escaped in HTML because textarea is an escapable raw text element.

These restrictions are scattered across the specification. E.g., attribute values (§8.1.2.3) must not contain an ambiguous ampersand and be either (i) empty, (ii) within single quotes (and thus must not contain U+0027 APOSTROPHE character '), (iii) within double quotes (must not contain U+0022 QUOTATION MARK character "), or (iv) unquoted — with the following restrictions:

... must not contain any literal space characters, any U+0022 QUOTATION MARK characters ("), U+0027 APOSTROPHE characters ('), U+003D EQUALS SIGN characters (=), U+003C LESS-THAN SIGN characters (<), U+003E GREATER-THAN SIGN characters (>), or U+0060 GRAVE ACCENT characters (`), and must not be the empty string.

What are the pros and cons of parquet format compared to other formats?

Tom's answer is quite detailed and exhaustive but you may also be interested in this simple study about Parquet vs Avro done at Allstate Insurance, summarized here:

"Overall, Parquet showed either similar or better results on every test [than Avro]. The query-performance differences on the larger datasets in Parquet’s favor are partly due to the compression results; when querying the wide dataset, Spark had to read 3.5x less data for Parquet than Avro. Avro did not perform well when processing the entire dataset, as suspected."

How to close the command line window after running a batch file?

I added the start and exit which works. Without both it was not working

start C:/Anaconda3/Library/bin/pyrcc4.exe -py3 {path}/Resourses.qrc -{path}/Resourses_rc.py
exit

Why is super.super.method(); not allowed in Java?

In addition to the very good points that others have made, I think there's another reason: what if the superclass does not have a superclass?

Since every class naturally extends (at least) Object, super.whatever() will always refer to a method in the superclass. But what if your class only extends Object - what would super.super refer to then? How should that behavior be handled - a compiler error, a NullPointer, etc?

I think the primary reason why this is not allowed is that it violates encapsulation, but this might be a small reason too.

Calculating the area under a curve given a set of coordinates, without knowing the function

If you have sklearn isntalled, a simple alternative is to use sklearn.metrics.auc

This computes the area under the curve using the trapezoidal rule given arbitrary x, and y array

import numpy as np
from sklearn.metrics import auc

dx = 5
xx = np.arange(1,100,dx)
yy = np.arange(1,100,dx)

print('computed AUC using sklearn.metrics.auc: {}'.format(auc(xx,yy)))
print('computed AUC using np.trapz: {}'.format(np.trapz(yy, dx = dx)))

both output the same area: 4607.5

the advantage of sklearn.metrics.auc is that it can accept arbitrarily-spaced 'x' array, just make sure it is ascending otherwise the results will be incorrect

What is Dependency Injection?

from Book Apress.Spring.Persistence.with.Hibernate.Oct.2010

The purpose of dependency injection is to decouple the work of resolving external software components from your application business logic.Without dependency injection, the details of how a component accesses required services can get muddled in with the component’s code. This not only increases the potential for errors, adds code bloat, and magnifies maintenance complexities; it couples components together more closely, making it difficult to modify dependencies when refactoring or testing.

How to pass parameter to click event in Jquery

As DOC says, you can pass data to the handler as next:

// say your selector and click handler looks something like this...
$("some selector").on('click',{param1: "Hello", param2: "World"}, cool_function);

// in your function, just grab the event object and go crazy...
function cool_function(event){
    alert(event.data.param1);
    alert(event.data.param2);

    // access element's id where click occur
    alert( event.target.id ); 
}

Calling a JSON API with Node.js

Unirest library simplifies this a lot. If you want to use it, you have to install unirest npm package. Then your code could look like this:

unirest.get("http://graph.facebook.com/517267866/?fields=picture")
  .send()
  .end(response=> {
    if (response.ok) {
      console.log("Got a response: ", response.body.picture)
    } else {
      console.log("Got an error: ", response.error)
    }
  })

Why is my CSS bundling not working with a bin deployed MVC4 app?

I had this issue while adding some packages from nuget and forgot to do an update

So first do an update of all packages installed in the project

Update-Package

In the Global.asax.cs add the following

BundleTable.EnableOptimizations = true;

Receive JSON POST with PHP

It is worth pointing out that if you use json_decode(file_get_contents("php://input")) (as others have mentioned), this will fail if the string is not valid JSON.

This can be simply resolved by first checking if the JSON is valid. i.e.

function isValidJSON($str) {
   json_decode($str);
   return json_last_error() == JSON_ERROR_NONE;
}

$json_params = file_get_contents("php://input");

if (strlen($json_params) > 0 && isValidJSON($json_params))
  $decoded_params = json_decode($json_params);

Edit: Note that removing strlen($json_params) above may result in subtle errors, as json_last_error() does not change when null or a blank string is passed, as shown here: http://ideone.com/va3u8U

How to convert md5 string to normal text?

The idea of MD5 is that is a one-way hashing, so it can't be once the original value has been passed through the hashing algorithm (if at all).

You could (potentially) create a database table with a pairing of the original and the MD5 values but I guess that's highly impractical and poses a major security risk.

break/exit script

You could use the stopifnot() function if you want the program to produce an error:

foo <- function(x) {
    stopifnot(x > 500)
    # rest of program
}

How to calculate modulus of large numbers?

Okay, so you want to calculate a^b mod m. First we'll take a naive approach and then see how we can refine it.

First, reduce a mod m. That means, find a number a1 so that 0 <= a1 < m and a = a1 mod m. Then repeatedly in a loop multiply by a1 and reduce again mod m. Thus, in pseudocode:

a1 = a reduced mod m
p = 1
for(int i = 1; i <= b; i++) {
    p *= a1
    p = p reduced mod m
}

By doing this, we avoid numbers larger than m^2. This is the key. The reason we avoid numbers larger than m^2 is because at every step 0 <= p < m and 0 <= a1 < m.

As an example, let's compute 5^55 mod 221. First, 5 is already reduced mod 221.

  1. 1 * 5 = 5 mod 221
  2. 5 * 5 = 25 mod 221
  3. 25 * 5 = 125 mod 221
  4. 125 * 5 = 183 mod 221
  5. 183 * 5 = 31 mod 221
  6. 31 * 5 = 155 mod 221
  7. 155 * 5 = 112 mod 221
  8. 112 * 5 = 118 mod 221
  9. 118 * 5 = 148 mod 221
  10. 148 * 5 = 77 mod 221
  11. 77 * 5 = 164 mod 221
  12. 164 * 5 = 157 mod 221
  13. 157 * 5 = 122 mod 221
  14. 122 * 5 = 168 mod 221
  15. 168 * 5 = 177 mod 221
  16. 177 * 5 = 1 mod 221
  17. 1 * 5 = 5 mod 221
  18. 5 * 5 = 25 mod 221
  19. 25 * 5 = 125 mod 221
  20. 125 * 5 = 183 mod 221
  21. 183 * 5 = 31 mod 221
  22. 31 * 5 = 155 mod 221
  23. 155 * 5 = 112 mod 221
  24. 112 * 5 = 118 mod 221
  25. 118 * 5 = 148 mod 221
  26. 148 * 5 = 77 mod 221
  27. 77 * 5 = 164 mod 221
  28. 164 * 5 = 157 mod 221
  29. 157 * 5 = 122 mod 221
  30. 122 * 5 = 168 mod 221
  31. 168 * 5 = 177 mod 221
  32. 177 * 5 = 1 mod 221
  33. 1 * 5 = 5 mod 221
  34. 5 * 5 = 25 mod 221
  35. 25 * 5 = 125 mod 221
  36. 125 * 5 = 183 mod 221
  37. 183 * 5 = 31 mod 221
  38. 31 * 5 = 155 mod 221
  39. 155 * 5 = 112 mod 221
  40. 112 * 5 = 118 mod 221
  41. 118 * 5 = 148 mod 221
  42. 148 * 5 = 77 mod 221
  43. 77 * 5 = 164 mod 221
  44. 164 * 5 = 157 mod 221
  45. 157 * 5 = 122 mod 221
  46. 122 * 5 = 168 mod 221
  47. 168 * 5 = 177 mod 221
  48. 177 * 5 = 1 mod 221
  49. 1 * 5 = 5 mod 221
  50. 5 * 5 = 25 mod 221
  51. 25 * 5 = 125 mod 221
  52. 125 * 5 = 183 mod 221
  53. 183 * 5 = 31 mod 221
  54. 31 * 5 = 155 mod 221
  55. 155 * 5 = 112 mod 221

Therefore, 5^55 = 112 mod 221.

Now, we can improve this by using exponentiation by squaring; this is the famous trick wherein we reduce exponentiation to requiring only log b multiplications instead of b. Note that with the algorithm that I described above, the exponentiation by squaring improvement, you end up with the right-to-left binary method.

a1 = a reduced mod m
p = 1
while (b > 0) {
     if (b is odd) {
         p *= a1
         p = p reduced mod m
     }
     b /= 2
     a1 = (a1 * a1) reduced mod m
}

Thus, since 55 = 110111 in binary

  1. 1 * (5^1 mod 221) = 5 mod 221
  2. 5 * (5^2 mod 221) = 125 mod 221
  3. 125 * (5^4 mod 221) = 112 mod 221
  4. 112 * (5^16 mod 221) = 112 mod 221
  5. 112 * (5^32 mod 221) = 112 mod 221

Therefore the answer is 5^55 = 112 mod 221. The reason this works is because

55 = 1 + 2 + 4 + 16 + 32

so that

5^55 = 5^(1 + 2 + 4 + 16 + 32) mod 221
     = 5^1 * 5^2 * 5^4 * 5^16 * 5^32 mod 221
     = 5 * 25 * 183 * 1 * 1 mod 221
     = 22875 mod 221
     = 112 mod 221

In the step where we calculate 5^1 mod 221, 5^2 mod 221, etc. we note that 5^(2^k) = 5^(2^(k-1)) * 5^(2^(k-1)) because 2^k = 2^(k-1) + 2^(k-1) so that we can first compute 5^1 and reduce mod 221, then square this and reduce mod 221 to obtain 5^2 mod 221, etc.

The above algorithm formalizes this idea.

Eclipse Generate Javadoc Wizard: what is "Javadoc Command"?

There are already useful answers to this question above, however there is one more possibility which I don't see being addressed here.

We should consider that the java is installed correctly (that's why eclipse could have been launched in the first place), and the JDK is also added correctly to the eclipse. So the issue might be for some reason (e.g. migration of eclipse to another OS) the path for javadoc is not right which you can easily check and modify in the javadoc wizard page. Here is detailed instructions:

  1. Open the javadoc wizard by Project->Generate Javadoc...
  2. In the javadoc wizard window make sure the javadoc command path is correct as illustrated in below screenshot:

EclipseJavadocWizard

How to pass parameter to a promise function

Even shorter

var foo = (user, pass) =>
  new Promise((resolve, reject) => {
    if (/* condition */) {
      resolve("Fine");
    } else {
      reject("Error message");
    }
  });

foo(user, pass).then(result => {
  /* process */
});

Position a CSS background image x pixels from the right?

Its been loong since this question has been asked, but I just ran into this problem and I got it by doing :

background-position:95% 50%;

Return None if Dictionary key is not available

If you want a more transparent solution, you can subclass dict to get this behavior:

class NoneDict(dict):
    def __getitem__(self, key):
        return dict.get(self, key)

>>> foo = NoneDict([(1,"asdf"), (2,"qwerty")])
>>> foo[1]
'asdf'
>>> foo[2]
'qwerty'
>>> foo[3] is None
True

Using C++ base class constructors?

No, that's not how it is done. Normal way to initialize the base class is in the initialization list :

class A
{
public: 
    A(int val) {}
};

class B : public A
{
public:
  B( int v) : A( v )
  {
  }
};


void main()
{
    B b(10);
}

How can I add a table of contents to a Jupyter / JupyterLab notebook?

JupyterLab ToC instructions

There are already many good answers to this question, but they often require tweaks to work properly with notebooks in JupyterLab. I wrote this answer to detail the possible ways of including a ToC in a notebook while working in and exporting from JupyterLab.

As a side panel

The jupyterlab-toc extension adds the ToC as a side panel that can number headings, collapse sections, and be used for navigation (see gif below for a demo). This extension is included by default since JupyterLab 3.0, in older version you can install it with the following command

jupyter labextension install @jupyterlab/toc

enter image description here


In the notebook as a cell

At the time being, this can either be done manually as in Matt Dancho's answer, or automatically via the toc2 jupyter notebook extension in the classic notebook interface.

First, install toc2 as part of the jupyter_contrib_nbextensions bundle:

conda install -c conda-forge jupyter_contrib_nbextensions

Then, launch JupyterLab, go to Help --> Launch Classic Notebook, and open the notebook in which you want to add the ToC. Click the toc2 symbol in the toolbar to bring up the floating ToC window (see the gif below if you can't find it), click the gear icon and check the box for "Add notebook ToC cell". Save the notebook and the ToC cell will be there when you open it in JupyterLab. The inserted cell is a markdown cell with html in it, it will not update automatically.

The default options of the toc2 can be configured in the "Nbextensions" tab in the classic notebook launch page. You can e.g. choose to number headings and to anchor the ToC as a side bar (which I personally think looks cleaner).

enter image description here


In an exported HTML file

nbconvert can be used to export notebooks to HTML following rules of how to format the exported HTML. The toc2 extension mentioned above adds an export format called html_toc, which can be used directly with nbconvert from the command line (after the toc2 extension has been installed):

jupyter nbconvert file.ipynb --to html_toc
# Append `--ExtractOutputPreprocessor.enabled=False`
# to get a single html file instead of a separate directory for images

Remember that shell commands can be added to notebook cells by prefacing them with an exclamation mark !, so you can stick this line in the last cell of the notebook and always have an HTML file with a ToC generated when you hit "Run all cells" (or whatever output you desire from nbconvert). This way, you could use jupyterlab-toc to navigate the notebook while you are working, and still get ToCs in the exported output without having to resort to using the classic notebook interface (for the purists among us).

Note that configuring the default toc2 options as described above, will not change the format of nbconver --to html_toc. You need to open the notebook in the classic notebook interface for the metadata to be written to the .ipynb file (nbconvert reads the metadata when exporting) Alternatively, you can add the metadata manually via the Notebook tools tab of the JupyterLab sidebar, e.g. something like:

    "toc": {
        "number_sections": false,
        "sideBar": true
    }

If you prefer a GUI-driven approach, you should be able to open the classic notebook and click File --> Save as HTML (with ToC) (although note that this menu item was not available for me).


The gifs above are linked from the respective documentation of the extensions.

How to request a random row in SQL?

In SQL Server you can combine TABLESAMPLE with NEWID() to get pretty good randomness and still have speed. This is especially useful if you really only want 1, or a small number, of rows.

SELECT TOP 1 * FROM [table] 
TABLESAMPLE (500 ROWS) 
ORDER BY NEWID()

The specified DSN contains an architecture mismatch between the Driver and Application. JAVA

Have you created the DSN first in Control Panel>Administrative Tools>ODBC>System DSN. Name it same as "myDatabase" and if i is asking for locating the database/access file specify the path using browse option. Once ur DSN will be created successfully you will be easily able to access ur DB.

How to Convert string "07:35" (HH:MM) to TimeSpan

While correct that this will work:

TimeSpan time = TimeSpan.Parse("07:35");

And if you are using it for validation...

TimeSpan time;
if (!TimeSpan.TryParse("07:35", out time))
{
    // handle validation error
}

Consider that TimeSpan is primarily intended to work with elapsed time, rather than time-of-day. It will accept values larger than 24 hours, and will accept negative values also.

If you need to validate that the input string is a valid time-of-day (>= 00:00 and < 24:00), then you should consider this instead:

DateTime dt;
if (!DateTime.TryParseExact("07:35", "HH:mm", CultureInfo.InvariantCulture, 
                                              DateTimeStyles.None, out dt))
{
    // handle validation error
}
TimeSpan time = dt.TimeOfDay;

As an added benefit, this will also parse 12-hour formatted times when an AM or PM is included, as long as you provide the appropriate format string, such as "h:mm tt".

How to automatically allow blocked content in IE?

Steps to configure IE to always allow blocked content:

  1. From Internet Explorer, select the Tools menu, then the Options...
  2. In the Internet Options dialog, select the Advanced tab...
  3. Scroll down until you see the Security options. Enable the checkbox "Allow active content to run in files on My Computer".

enter image description here

  1. Close the dialog, and quit Internet Explorer. The changes will take effect the next time you start IE.

The Blocked Content is a security feature of Windows XP Service Pack 2. If you do not have SP2 installed, then you will never see this message.

From: How To Allow Blocked Content on Internet Explorer

Disable browser 'Save Password' functionality

I tried above autocomplete="off" and yet anything successful. if you are using angular js my recommendation is to go with button and the ng-click.

<button type="button" class="" ng-click="vm.login()" />

This already have a accepted answer im adding this if someone cant solve the problem with the accepted answer he can go with my mechanism.

Thanks for the question and the answers.

Return a 2d array from a function

int** create2DArray(unsigned height, unsigned width)
{
     int** array2D = 0;
     array2D = new int*[height];

     for (int h = 0; h < height; h++)
     {
          array2D[h] = new int[width];

          for (int w = 0; w < width; w++)
          {
               // fill in some initial values
               // (filling in zeros would be more logic, but this is just for the example)
               array2D[h][w] = w + width * h;
          }
     }

     return array2D;
}

int main ()
{

    printf("Creating a 2D array2D\n");
    printf("\n");

    int height = 15;
    int width = 10;
    int** my2DArray = create2DArray(height, width);
    printf("Array sized [%i,%i] created.\n\n", height, width);

    // print contents of the array2D
    printf("Array contents: \n");

    for (int h = 0; h < height; h++)
    {
         for (int w = 0; w < width; w++)
         {
              printf("%i,", my2DArray[h][w]);
         }
         printf("\n");
    }

    return 0;
}

Remove NA values from a vector

?max shows you that there is an extra parameter na.rm that you can set to TRUE.

Apart from that, if you really want to remove the NAs, just use something like:

myvec[!is.na(myvec)]

No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

Many answer above are correct but same time convoluted with other aspects of authN/authZ. What actually resolves the exception in question is this line:

services.AddScheme<YourAuthenticationOptions, YourAuthenticationHandler>(YourAuthenticationSchemeName, options =>
    {
        options.YourProperty = yourValue;
    })

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

i had the same problem and it seems like i didn't initiate the button used with click listener, in other words id didn't te

How to execute a remote command over ssh with arguments?

This is an example that works on the AWS Cloud. The scenario is that some machine that booted from autoscaling needs to perform some action on another server, passing the newly spawned instance DNS via SSH

# Get the public DNS of the current machine (AWS specific)
MY_DNS=`curl -s http://169.254.169.254/latest/meta-data/public-hostname`


ssh \
    -o StrictHostKeyChecking=no \
    -i ~/.ssh/id_rsa \
    [email protected] \
<< EOF
cd ~/
echo "Hey I was just SSHed by ${MY_DNS}"
run_other_commands
# Newline is important before final EOF!

EOF

HashMap to return default value for non-found keys?

I needed to read the results returned from a server in JSON where I couldn't guarantee the fields would be present. I'm using class org.json.simple.JSONObject which is derived from HashMap. Here are some helper functions I employed:

public static String getString( final JSONObject response, 
                                final String key ) 
{ return getString( response, key, "" ); }  
public static String getString( final JSONObject response, 
                                final String key, final String defVal ) 
{ return response.containsKey( key ) ? (String)response.get( key ) : defVal; }

public static long getLong( final JSONObject response, 
                            final String key ) 
{ return getLong( response, key, 0 ); } 
public static long getLong( final JSONObject response, 
                            final String key, final long defVal ) 
{ return response.containsKey( key ) ? (long)response.get( key ) : defVal; }

public static float getFloat( final JSONObject response, 
                              final String key ) 
{ return getFloat( response, key, 0.0f ); } 
public static float getFloat( final JSONObject response, 
                              final String key, final float defVal ) 
{ return response.containsKey( key ) ? (float)response.get( key ) : defVal; }

public static List<JSONObject> getList( final JSONObject response, 
                                        final String key ) 
{ return getList( response, key, new ArrayList<JSONObject>() ); }   
public static List<JSONObject> getList( final JSONObject response, 
                                        final String key, final List<JSONObject> defVal ) { 
    try { return response.containsKey( key ) ? (List<JSONObject>) response.get( key ) : defVal; }
    catch( ClassCastException e ) { return defVal; }
}