Programs & Examples On #Root

On Unix-like systems, a special user account used for system administration.

vagrant login as root by default

Note: Only use this method for local development, it's not secure. You can setup password and ssh config while provisioning the box. For example with debian/stretch64 box this is my provision script:

config.vm.provision "shell", inline: <<-SHELL
    echo -e "vagrant\nvagrant" | passwd root
    echo "PermitRootLogin yes" >> /etc/ssh/sshd_config
    sed -in 's/PasswordAuthentication no/PasswordAuthentication yes/g' /etc/ssh/sshd_config
    service ssh restart
SHELL

This will set root password to vagrant and permit root login with password. If you are using private_network say with ip address 192.168.10.37 then you can ssh with ssh [email protected]

You may need to change that echo and sed commands depending on the default sshd_config file.

Determine if running on a rooted device

In my application I was checking if device is rooted or not by executing "su" command. But today I've removed this part of my code. Why?

Because my application became a memory killer. How? Let me tell you my story.

There were some complaints that my application was slowing down devices(Of course I thought that can not be true). I tried to figure out why. So I used MAT to get heap dumps and analyze, and everything seemed perfect. But after relaunching my app many times I realized that device is really getting slower and stopping my application didn't make it faster (unless I restart device). I analyzed dump files again while device is very slow. But everything was still perfect for dump file. Then I did what must be done at first. I listed processes.

$ adb shell ps

Surprize; there were many processes for my application (with my application's process tag at manifest). Some of them was zombie some of them not.

With a sample application which has a single Activity and executes just "su" command, I realized that a zombie process is being created on every launch of application. At first these zombies allocate 0KB but than something happens and zombie processes are holding nearly same KBs as my application's main process and they became standart processes.

There is a bug report for same issue on bugs.sun.com: http://bugs.sun.com/view_bug.do?bug_id=6474073 this explains if command is not found zombies are going to be created with exec() method. But I still don't understand why and how can they become standart processes and hold significant KBs. (This is not happening all the time)

You can try if you want with code sample below;

String commandToExecute = "su";
executeShellCommand(commandToExecute);

Simple command execution method;

private boolean executeShellCommand(String command){
    Process process = null;            
    try{
        process = Runtime.getRuntime().exec(command);
        return true;
    } catch (Exception e) {
        return false;
    } finally{
        if(process != null){
            try{
                process.destroy();
            }catch (Exception e) {
            }
        }
    }
}

To sum up; I have no advice for you to determine if device is rooted or not. But if I were you I would not use Runtime.getRuntime().exec().

By the way; RootTools.isRootAvailable() causes same problem.

SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost'

MySQL makes a difference between "localhost" and "127.0.0.1".

It might be possible that 'root'@'localhost' is not allowed because there is an entry in the user table that will only allow root login from 127.0.0.1.

This could also explain why some application on your server can connect to the database and some not because there are different ways of connecting to the database. And you currently do not allow it through "localhost".

phpMyAdmin - can't connect - invalid setings - ever since I added a root password - locked out

I faced the same problem after executing the following command in mysql

UPDATE mysql.user SET Password=PASSWORD('blablabla') WHERE User='root'; FLUSH PRIVILEGES;

what I did:

open cmd

type

cd c:\xampp\mysql\bin mysql.exe -u root --password

after that mysql will prompt u

Enter password:blablabla

once youre in mysql, type

UPDATE mysql.user SET Password=PASSWORD('') WHERE User='root'; FLUSH PRIVILEGES;

Note: this time the password is left empty...

make sure in your config.inc.php the following is set

$cfg['Servers'][$i]['password'] = '';

$cfg['Servers'][$i]['AllowNoPasswordRoot'] = true; 

after that I can see my phpmyadmin...

Root user/sudo equivalent in Cygwin?

A very simple way to have a cygwin shell and corresponding subshells to operate with administrator privileges is to change the properties of the link which opens the initial shell.

The following is valid for Windows 7+ (perhaps for previous versions too, but I've not checked)

I usually start the cygwin shell from a cygwin-link in the start button (or desktop). Then, I changed the properties of the cygwin-link in the tabs

/Compatibility/Privilege Level/

and checked the box,

"Run this program as an administrator"

This allows the cygwin shell to open with administrator privileges and the corresponding subshells too.

How to set the context path of a web application in Tomcat 7.0

<Context docBase="yourAppName" path="" reloadable="true">

go to Tomcat server.xml file and set path blank

How to restart adb from root to user mode?

For quick steps just check summary. If interested to know details, go on to read below.

adb is a daemon. Doing ps adb we can see its process.

shell@grouper:/ $ ps adb
USER     PID   PPID  VSIZE  RSS     WCHAN    PC        NAME
shell     133   1     4636   212   ffffffff 00000000 S /sbin/adbd

I just checked what additional property variables it is using when adb is running as root and user.

adb user mode :

shell@grouper:/ $ getprop | grep adb                                         
[init.svc.adbd]: [running]
[persist.sys.usb.config]: [mtp,adb]
[ro.adb.secure]: [1]
[sys.usb.config]: [mtp,adb]
[sys.usb.state]: [mtp,adb]

adb root mode :

shell@grouper:/ # getprop | grep adb                                         
[init.svc.adbd]: [running]
[persist.sys.usb.config]: [mtp,adb]
[ro.adb.secure]: [1]
[service.adb.root]: [1]
[sys.usb.config]: [mtp,adb]
[sys.usb.state]: [mtp,adb]

We can see that service.adb.root is a new prop variable that came up when we did adb root.

So, to change back adb to user from root, I went ahead and made this 0

setprop service.adb.root 0

But this did not change anything.

Then I went ahead and killed the process (with an intention to restart the process). The pid of adbd process in my device is 133

kill -9 133

I exited from shell automatically after I had killed the process.

I did adb shell again it was in user mode.

SUMMARY :

So, we have 3 very simple steps.

  1. Enter adb shell as a root.
  2. setprop service.adb.root 0
  3. kill -9 (pid of adbd)

After these steps just re-enter the shell with adb shell and you are back on your device as a user.

Document Root PHP

The Easiest way to do it is to have good site structure and write it as a constant.

DEFINE("BACK_ROOT","/var/www/");

MySQL user DB does not have password columns - Installing MySQL on OSX

Thank you for your help. Just in case if people are still having problems, try this.

For MySQL version 5.6 and under

Have you forgotten your Mac OS X 'ROOT' password  and need to reset it?  Follow these 4 simple steps:

  1.  Stop the mysqld server.  Typically this can be done by from 'System Prefrences' > MySQL > 'Stop MySQL Server'
  2.  Start the server in safe mode with privilege bypass      From a terminal:      sudo /usr/local/mysql/bin/mysqld_safe --skip-grant-tables
  3.  In a new terminal window:      sudo /usr/local/mysql/bin/mysql -u root      UPDATE mysql.user SET Password=PASSWORD('NewPassword') WHERE User='root';      FLUSH PRIVILEGES;      \q
  4.  Stop the mysqld server again and restart it in normal mode.

For MySQL version 5.7 and up

  1.  Stop the mysqld server.  Typically this can be done by from 'System Prefrences' > MySQL > 'Stop MySQL Server'
  2.  Start the server in safe mode with privilege bypass      From a terminal:      sudo /usr/local/mysql/bin/mysqld_safe --skip-grant-tables
  3.  In a new terminal window:            sudo /usr/local/mysql/bin/mysql -u root      UPDATE mysql.user SET authentication_string=PASSWORD('NewPassword') WHERE User='root';      FLUSH PRIVILEGES;      \q      
  4.  Stop the mysqld server again and restart it in normal mode.

How to get root access on Android emulator?

I know this question is pretty old. But we can able to get root in Emulator with the help of Magisk by following https://github.com/shakalaca/MagiskOnEmulator

Basically, it patch initrd.img(if present) and ramdisk.img for working with Magisk.

How to parse a String containing XML in Java and retrieve the value of the root node?

You could also use tools provided by the base JRE:

String msg = "<message>HELLO!</message>";
DocumentBuilder newDocumentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document parse = newDocumentBuilder.parse(new ByteArrayInputStream(msg.getBytes()));
System.out.println(parse.getFirstChild().getTextContent());

How to get domain root url in Laravel 4?

My hint:

  1. FIND IF EXISTS in .env:

    APP_URL=http://yourhost.dev

  2. REPLACE TO (OR ADD)

    APP_DOMAIN=yourhost.dev

  3. FIND in config/app.php:

    'url' => env('APP_URL'),

  4. REPLACE TO

    'domain' => env('APP_DOMAIN'),

    'url' => 'http://' . env('APP_DOMAIN'),

  5. USE:

    Config::get('app.domain'); // yourhost.dev

    Config::get('app.url') // http://yourhost.dev

  6. Do your magic!

Connect to docker container as user other than root

This solved my use case that is: "Compile webpack stuff in nodejs container on Windows running Docker Desktop with WSL2 and have the built assets under your currently logged in user."

docker run -u 1000 -v "$PWD":/build -w /build node:10.23 /bin/sh -c 'npm install && npm run build'

Based on the answer by eigenfield. Thank you!

Also this material helped me understand what is going on.

Import Certificate to Trusted Root but not to Personal [Command Line]

Look at the documentation of certutil.exe and -addstore option.

I tried

certutil -addstore "Root" "c:\cacert.cer"

and it worked well (meaning The certificate landed in Trusted Root of LocalMachine store).

EDIT:

If there are multiple certificates in a pfx file (key + corresponding certificate and a CA certificate) then this command worked well for me:

certutil -importpfx c:\somepfx.pfx

EDIT2:

To import CA certificate to Intermediate Certification Authorities store run following command

certutil -addstore "CA" "c:\intermediate_cacert.cer"

adb shell su works but adb root does not

I use for enter su mode in abd shell

adb shell "su"

A terminal command for a rooted Android to remount /System as read/write

Instead of

mount -o rw,remount /system/

use

mount -o rw,remount /system

mind the '/' at the end of the command. you ask why this matters? /system/ is the directory under /system while /system is the volume name.

Android: adbd cannot run as root in production builds

You have to grant the Superuser right to the shell app (com.anroid.shell). In my case, I use Magisk to root my phone Nexsus 6P (Oreo 8.1). So I can grant Superuser right in the Magisk Manager app, whih is in the left upper option menu.

adb remount permission denied, but able to access super user in shell -- android

Try

adb root
adb remount

to start the adb demon as root and ensure partitions are mounted in read-write mode (the essential part is adb root). After pushing, revoke root permissions again using:

adb unroot

How to check if running as root in a bash script

Check for root:

ROOT_UID=0   # Root has $UID 0.

if [ "$UID" -eq "$ROOT_UID" ]
then
  echo "You are root."
else
  echo "You are just an ordinary user."
fi

exit 0

Tested and running in root.

Is there a way for non-root processes to bind to "privileged" ports on Linux?

Use the privbind utility: it allows an unprivileged application to bind to reserved ports.

How do I get the APK of an installed app without root access?

I found a way to get the APK's package name in a non-root device. it's not so elegant, but works all the time.

Step 1: on your device, open the target APK

Step 2: on PC cmd window, type this commands:

 adb shell dumpsys activity a > dump.txt

because the output of this command is numerous, redirect to a file is recommended.

Step 3: open this dump.txt file with any editor.

for device befor Android 4.4:
the beginning of the file would be looked like this:

ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)  
  Main stack:  
  * TaskRecord{41aa9ed0 #4 A com.tencent.mm U 0}  
    numActivities=1 rootWasReset=true userId=0  
    affinity=com.tencent.mm  
    intent={act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10600000 cmp=com.tencent.mm/.ui.LauncherUI}  
    realActivity=com.tencent.mm/.ui.LauncherUI  
    askedCompatMode=false  
    lastThumbnail=null lastDescription=null  
    lastActiveTime=19915965 (inactive for 10s)  
    * Hist #9: ActivityRecord{41ba1a30 u0 com.tencent.mm/.ui.LauncherUI}  
        packageName=com.tencent.mm processName=com.tencent.mm 

the package name is in the 3rd line, com.tencent.mm for this example.

for Android 4.4 and later:
the dumpsys output has changed a little. try search "Stack #1", the package name would be very close below it.

Also, search "baseDir", you will find the full path of the apk file!

Viewing root access files/folders of android on windows

You can use Eclipse DDMS perspective to see connected devices and browse through files, you can also pull and push files to the device. You can also do a bunch of stuff using DDMS, this link explains a little bit more of DDMS uses.

EDIT:

If you just want to copy a database you can locate the database on eclipse DDMS file explorer, select it and then pull the database from the device to your computer.

MySQL root password change

For me, only these steps could help me setting the root password on version 8.0.19:

mysql
SELECT user,authentication_string FROM mysql.user;
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your_pass_here';
FLUSH PRIVILEGES;
SELECT user,authentication_string FROM mysql.user;

If you can see changes for the root user, then it works. Source: https://www.digitalocean.com/community/questions/can-t-set-root-password-mysql-server

Access Denied for User 'root'@'localhost' (using password: YES) - No Privileges?

in mysql 5.7 the password field has been replaced with authentication_string so you would do something like this instead

update user set authentication_string=PASSWORD("root") where User='root';

See this link MySQL user DB does not have password columns - Installing MySQL on OSX

install / uninstall APKs programmatically (PackageManager vs Intents)

If you're using Kotlin, API 14+, and just wish to show uninstall dialog for your app:

startActivity(Intent(Intent.ACTION_UNINSTALL_PACKAGE).apply {
    data = Uri.parse("package:$packageName")
})

You can change packageName to any other package name if you want to prompt the user to uninstall another app on the device

How do I find out where login scripts live?

The default location for logon scripts is the netlogon share of a domain controller. On the server this is located:

%SystemRoot%'SYSVOL'sysvol''scripts

It can presumably be changes from this default but I've never met anyone that had a reason to.

To get list of domain controllers programatically see this article: http://www.microsoft.com/technet/scriptcenter/resources/qanda/dec04/hey1216.mspx

Powershell import-module doesn't find modules

I experienced the same error and tried numerous things before I succeeded. The solution was to prepend the path of the script to the relative path of the module like this:

// Note that .Path will only be available during script-execution
$ScriptPath = Split-Path $MyInvocation.MyCommand.Path

Import-Module $ScriptPath\Modules\Builder.psm1

Btw you should take a look at http://msdn.microsoft.com/en-us/library/dd878284(v=vs.85).aspx which states:

Beginning in Windows PowerShell 3.0, modules are imported automatically when any cmdlet or function in the module is used in a command. This feature works on any module in a directory that this included in the value of the PSModulePath environment variable ($env:PSModulePath)

How to get Current Directory?

You should provide a valid buffer placeholder. that is:

TCHAR s[100];
DWORD a = GetCurrentDirectory(100, s);

Disallow Twitter Bootstrap modal window from closing

Just set the backdrop property to 'static'.

$('#myModal').modal({
  backdrop: 'static',
  keyboard: true
})

You may also want to set the keyboard property to false because that prevents the modal from being closed by pressing the Esc key on the keyboard.

$('#myModal').modal({
  backdrop: 'static',
  keyboard: false
})

myModal is the ID of the div that contains your modal content.

Wait Until File Is Completely Written

When the file is writing in binary(byte by byte),create FileStream and above solutions Not working,because file is ready and wrotted in every bytes,so in this Situation you need other workaround like this: Do this when file created or you want to start processing on file

long fileSize = 0;
currentFile = new FileInfo(path);

while (fileSize < currentFile.Length)//check size is stable or increased
{
  fileSize = currentFile.Length;//get current size
  System.Threading.Thread.Sleep(500);//wait a moment for processing copy
  currentFile.Refresh();//refresh length value
}

//Now file is ready for any process!

How to add bootstrap to an angular-cli project

angular-cli now has a dedicated wiki page where you can find everything you need. TLDR, install bootstrap via npm and add the styles link to "styles" section in your .angular-cli.json file

JQuery - File attributes

To get the filenames, use:

var files = document.getElementById('inputElementID').files;

Using jQuery (since you already are) you can adapt this to the following:

$('input[type="file"][multiple]').change(
    function(e){
        var files = this.files;
        for (i=0;i<files.length;i++){
            console.log(files[i].fileName + ' (' + files[i].fileSize + ').');
        }
        return false;
    });

JS Fiddle demo.

How to go up a level in the src path of a URL in HTML?

If you store stylesheets/images in a folder so that multiple websites can use them, or you want to re-use the same files on another site on the same server, I have found that my browser/Apache does not allow me to go to any parent folder above the website root URL. This seems obvious for security reasons - one should not be able to browse around on the server any place other than the specified web folders.

Eg. does not work: www.mywebsite.com/../images

As a workaround, I use Symlinks:

Go to the directory of www.mywebsite.com Run the command ln -s ../images images

Now www.mywebsite.com/images will point to www.mywebsite.com/../images

List of all unique characters in a string?

char_seen = []
for char in string:
    if char not in char_seen:
        char_seen.append(char)
print(''.join(char_seen))

This will preserve the order in which alphabets are coming,

output will be

abcd

How to put a jpg or png image into a button in HTML

<input type= "image" id=" " onclick=" " src=" " />

it works.

Write in body request with HttpClient

Extending your code (assuming that the XML you want to send is in xmlString) :

String xmlString = "</xml>";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(this.url);
httpRequest.setHeader("Content-Type", "application/xml");
StringEntity xmlEntity = new StringEntity(xmlString);
httpRequest.setEntity(xmlEntity );
HttpResponse httpresponse = httpclient.execute(httppost);

Static methods - How to call a method from another method?

OK the main difference between class methods and static methods is:

  • class method has its own identity, that's why they have to be called from within an INSTANCE.
  • on the other hand static method can be shared between multiple instances so that it must be called from within THE CLASS

How open PowerShell as administrator from the run window

Windows 10 appears to have a keyboard shortcut. According to How to open elevated command prompt in Windows 10 you can press ctrl + shift + enter from the search or start menu after typing cmd for the search term.

image of win 10 start menu
(source: winaero.com)

jQuery hyperlinks - href value?

Why use a <a href>? I solve it like this:

<span class='a'>fake link</span>

And style it with:

.a {text-decoration:underline; cursor:pointer;}

You can easily access it with jQuery:

$(".a").click();

What can be the reasons of connection refused errors?

Check at the server side that it is listening at the port 2080. First try to confirm it on the server machine by issuing telnet to that port:

telnet localhost 2080

If it is listening, it is able to respond.

Catch an exception thrown by an async void method

The reason the exception is not caught is because the Foo() method has a void return type and so when await is called, it simply returns. As DoFoo() is not awaiting the completion of Foo, the exception handler cannot be used.

This opens up a simpler solution if you can change the method signatures - alter Foo() so that it returns type Task and then DoFoo() can await Foo(), as in this code:

public async Task Foo() {
    var x = await DoSomethingThatThrows();
}

public async void DoFoo() {
    try {
        await Foo();
    } catch (ProtocolException ex) {
        // This will catch exceptions from DoSomethingThatThrows
    }
}

XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header

This CORS issue wasn't further elaborated (for other causes).

I'm having this issue currently under different reason. My front end is returning 'Access-Control-Allow-Origin' header error as well.

Just that I've pointed the wrong URL so this header wasn't reflected properly (in which i kept presume it did). localhost (front end) -> call to non secured http (supposed to be https), make sure the API end point from front end is pointing to the correct protocol.

show validation error messages on submit in angularjs

I like the solution from realcrowd the best.

HTML:

<form role="form" id="form" name="form" autocomplete="off" novalidate rc-submit="signup()">
<div class="form-group" ng-class="{'has-error':  rc.form.hasError(form.firstName)}">
    <label for="firstName">Your First Name</label>
    <input type="text" id="firstName" name="firstName" class="form-control input-sm" placeholder="First Name" ng-maxlength="40" required="required" ng-model="owner.name.first"/>
    <div class="help-block" ng-show="rc.form.hasError(form.firstName)">{{rc.form.getErrMsg(form.firstName)}}</div>
</div>
</form>

javascript:

//define custom submit directive
var rcSubmitDirective = {
'rcSubmit': ['$parse', function ($parse) {
    return {
        restrict: 'A',
        require: ['rcSubmit', '?form'],
        controller: ['$scope', function ($scope) {
            this.attempted = false;

            var formController = null;

            this.setAttempted = function() {
                this.attempted = true;
            };

            this.setFormController = function(controller) {
              formController = controller;
            };

            this.hasError = function (fieldModelController) {
                if (!formController) return false;

                if (fieldModelController) {
                    return fieldModelController.$invalid && this.attempted;
                } else {
                    return formController && formController.$invalid && this.attempted;
                }
            };
            this.getErrMsg=function(ctrl){
                var e=ctrl.$error;
                var errMsg;
                if (e.required){
                    errMsg='Please enter a value';
                }
                return errMsg;
            }
        }],
        compile: function(cElement, cAttributes, transclude) {
            return {
                pre: function(scope, formElement, attributes, controllers) {

                    var submitController = controllers[0];
                    var formController = (controllers.length > 1) ? controllers[1] : null;

                    submitController.setFormController(formController);

                    scope.rc = scope.rc || {};
                    scope.rc[attributes.name] = submitController;
                },
                post: function(scope, formElement, attributes, controllers) {

                    var submitController = controllers[0];
                    var formController = (controllers.length > 1) ? controllers[1] : null;
                    var fn = $parse(attributes.rcSubmit);

                    formElement.bind('submit', function (event) {
                        submitController.setAttempted();
                        if (!scope.$$phase) scope.$apply();

                        if (!formController.$valid) return false;

                        scope.$apply(function() {
                            fn(scope, {$event:event});
                        });
                    });
                }
          };
        }
    };
}]
};
app.directive(rcSubmitDirective);

Printf width specifier to maintain precision of floating-point value

To my knowledge, there is a well diffused algorithm allowing to output to the necessary number of significant digits such that when scanning the string back in, the original floating point value is acquired in dtoa.c written by Daniel Gay, which is available here on Netlib (see also the associated paper). This code is used e.g. in Python, MySQL, Scilab, and many others.

Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"

I removed the old web library such that are spring framework libraries. And build a new path of the libraries. Then it works.

How to change the default background color white to something else in twitter bootstrap

how to change background color in html & css with class

example:

on html you write

<div class="pad_menu">
</div>

on css

.pad_menu {
   padding: 100px;
   background-color: #A9FFCB;
}

so your background will be change to Magic Mint, if you want to know the code of the color, i suggest you visit https://coolors.co. Hope this useful :)

Adding a rule in iptables in debian to open a new port

About your command line:

root@debian:/# sudo iptables -A INPUT -p tcp --dport 3306 --jump ACCEPT
root@debian:/# iptables-save
  • You are already authenticated as root so sudo is redundant there.

  • You are missing the -j or --jump just before the ACCEPT parameter (just tought that was a typo and you are inserting it correctly).

About yout question:

If you are inserting the iptables rule correctly as you pointed it in the question, maybe the issue is related to the hypervisor (virtual machine provider) you are using.

If you provide the hypervisor name (VirtualBox, VMWare?) I can further guide you on this but here are some suggestions you can try first:

check your vmachine network settings and:

  • if it is set to NAT, then you won't be able to connect from your base machine to the vmachine.

  • if it is set to Hosted, you have to configure first its network settings, it is usually to provide them an IP in the range 192.168.56.0/24, since is the default the hypervisors use for this.

  • if it is set to Bridge, same as Hosted but you can configure it whenever IP range makes sense for you configuration.

Hope this helps.

Xcode source automatic formatting

In xcode, you can use this shortcut to Re-indent your source code

Go to file, which has indent issues, and follow this :

  • Cmd + A to select all source codes

  • Ctrl + I to re-indent

Hope this helps.

Enum Naming Convention - Plural

Coming in a bit late...

There's an important difference between your question and the one you mention (which I asked ;-):

You put the enum definition out of the class, which allows you to have the same name for the enum and the property:

public enum EntityType { 
  Type1, Type2 
} 

public class SomeClass { 
  public EntityType EntityType {get; set;} // This is legal

}

In this case, I'd follow the MS guidelins and use a singular name for the enum (plural for flags). It's probaby the easiest solution.

My problem (in the other question) is when the enum is defined in the scope of the class, preventing the use of a property named exactly after the enum.

disable Bootstrap's Collapse open/close animation

If you find the 1px jump before expanding and after collapsing when using the CSS solution a bit annoying, here's a simple JavaScript solution for Bootstrap 3...

Just add this somewhere in your code:

$(document).ready(
    $('.collapse').on('show.bs.collapse hide.bs.collapse', function(e) {
        e.preventDefault();
    }),
    $('[data-toggle="collapse"]').on('click', function(e) {
        e.preventDefault();
        $($(this).data('target')).toggleClass('in');
    })
);

Fast check for NaN in NumPy

Ray's solution is good. However, on my machine it is about 2.5x faster to use numpy.sum in place of numpy.min:

In [13]: %timeit np.isnan(np.min(x))
1000 loops, best of 3: 244 us per loop

In [14]: %timeit np.isnan(np.sum(x))
10000 loops, best of 3: 97.3 us per loop

Unlike min, sum doesn't require branching, which on modern hardware tends to be pretty expensive. This is probably the reason why sum is faster.

edit The above test was performed with a single NaN right in the middle of the array.

It is interesting to note that min is slower in the presence of NaNs than in their absence. It also seems to get slower as NaNs get closer to the start of the array. On the other hand, sum's throughput seems constant regardless of whether there are NaNs and where they're located:

In [40]: x = np.random.rand(100000)

In [41]: %timeit np.isnan(np.min(x))
10000 loops, best of 3: 153 us per loop

In [42]: %timeit np.isnan(np.sum(x))
10000 loops, best of 3: 95.9 us per loop

In [43]: x[50000] = np.nan

In [44]: %timeit np.isnan(np.min(x))
1000 loops, best of 3: 239 us per loop

In [45]: %timeit np.isnan(np.sum(x))
10000 loops, best of 3: 95.8 us per loop

In [46]: x[0] = np.nan

In [47]: %timeit np.isnan(np.min(x))
1000 loops, best of 3: 326 us per loop

In [48]: %timeit np.isnan(np.sum(x))
10000 loops, best of 3: 95.9 us per loop

Custom seekbar (thumb size, color and background)

android:minHeight android:maxHeight is important for that.

<SeekBar
    android:id="@+id/pb"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:maxHeight="2dp"
    android:minHeight="2dp"
    android:progressDrawable="@drawable/seekbar_bg"
    android:thumb="@drawable/seekbar_thumb"
    android:max="100"
    android:progress="50"/>

seekbar_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background">
        <shape>
            <corners android:radius="3dp" />
            <solid android:color="#ECF0F1" />
        </shape>
    </item>
    <item android:id="@android:id/secondaryProgress">
        <clip>
            <shape>
                <corners android:radius="3dp" />
                <solid android:color="#C6CACE" />
            </shape>
        </clip>
    </item>
    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <corners android:radius="3dp" />
                <solid android:color="#16BC5C" />
            </shape>
        </clip>
    </item>
</layer-list>

seekbar_thumb.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="#16BC5C" />
    <stroke
        android:width="1dp"
        android:color="#16BC5C" />
    <size
        android:height="20dp"
        android:width="20dp" />
</shape>

How to initialize a struct in accordance with C programming language standards

This can be done in different ways:

MY_TYPE a = { true, 1, 0.1 };

MY_TYPE a = { .stuff = 0.1, .flag = true, .value = 1 }; //designated initializer, not available in c++

MY_TYPE a;
a = (MY_TYPE) { true,  1, 0.1 };

MY_TYPE m (true, 1, 0.1); //works in C++, not available in C

Also, you can define member while declaring structure.

#include <stdio.h>

struct MY_TYPE
{
    int a;
    int b;
}m = {5,6};

int main()
{
    printf("%d  %d\n",m.a,m.b);    
    return 0;
}

Adding a newline into a string in C#

The previous answers come close, but to meet the actual requirement that the @ symbol stay close, you'd want that to be str.Replace("@", "@" + System.Environment.NewLine). That will keep the @ symbol and add the appropriate newline character(s) for the current platform.

How to create NSIndexPath for TableView

Obligatory answer in Swift : NSIndexPath(forRow:row, inSection: section)

You will notice that NSIndexPath.indexPathForRow(row, inSection: section) is not available in swift and you must use the first method to construct the indexPath.

Declaring a variable and setting its value from a SELECT query in Oracle

SELECT INTO

DECLARE
   the_variable NUMBER;

BEGIN
   SELECT my_column INTO the_variable FROM my_table;
END;

Make sure that the query only returns a single row:

By default, a SELECT INTO statement must return only one row. Otherwise, PL/SQL raises the predefined exception TOO_MANY_ROWS and the values of the variables in the INTO clause are undefined. Make sure your WHERE clause is specific enough to only match one row

If no rows are returned, PL/SQL raises NO_DATA_FOUND. You can guard against this exception by selecting the result of an aggregate function, such as COUNT(*) or AVG(), where practical. These functions are guaranteed to return a single value, even if no rows match the condition.

A SELECT ... BULK COLLECT INTO statement can return multiple rows. You must set up collection variables to hold the results. You can declare associative arrays or nested tables that grow as needed to hold the entire result set.

The implicit cursor SQL and its attributes %NOTFOUND, %FOUND, %ROWCOUNT, and %ISOPEN provide information about the execution of a SELECT INTO statement.

What's the fastest way to delete a large folder in Windows?

Using Windows Command Prompt:

rmdir /s /q folder

Using Powershell:

powershell -Command "Remove-Item -LiteralPath 'folder' -Force -Recurse"

Note that in more cases del and rmdir wil leave you with leftover files, where Powershell manages to delete the files.

Bat file to run a .exe at the command prompt

Just stick in a file and call it "ServiceModelSamples.bat" or something.

You could add "@echo off" as line one, so the command doesn't get printed to the screen:

@echo off
svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceModelSamples/service

The transaction log for database is full. To find out why space in the log cannot be reused, see the log_reuse_wait_desc column in sys.databases

As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:

WHILE EXISTS (SELECT 1 
              FROM   YourTable 
              WHERE  <yourCondition>) 
  DELETE TOP(10000) FROM YourTable 
  WHERE  <yourCondition>

How to copy Java Collections list

List b = new ArrayList(a.size())

doesn't set the size. It sets the initial capacity (being how many elements it can fit in before it needs to resize). A simpler way of copying in this case is:

List b = new ArrayList(a);

Is it ok to run docker from inside docker?

It's OK to run Docker-in-Docker (DinD) and in fact Docker (the company) has an official DinD image for this.

The caveat however is that it requires a privileged container, which depending on your security needs may not be a viable alternative.

The alternative solution of running Docker using sibling containers (aka Docker-out-of-Docker or DooD) does not require a privileged container, but has a few drawbacks that stem from the fact that you are launching the container from within a context that is different from that one in which it's running (i.e., you launch the container from within a container, yet it's running at the host's level, not inside the container).

I wrote a blog describing the pros/cons of DinD vs DooD here.

Having said this, Nestybox (a startup I just founded) is working on a solution that runs true Docker-in-Docker securely (without using privileged containers). You can check it out at www.nestybox.com.

Parameter binding on left joins with array in Laravel Query Builder

You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw(), ensure that you binding the parameters.

Try the following:

$array = array(1,2,3);       $query = DB::table('offers');             $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used');             $query->leftJoin('user_offer_collection', function ($join) use ($array)             {                 $join->on('user_offer_collection.offers_id', '=', 'offers.id')                       ->whereIn('user_offer_collection.user_id', $array);             });       $query->get(); 

How to download a file with Node.js (without using third-party libraries)?

?So if you use pipeline, it would close all other streams and make sure that there are no memory leaks.

Working example:

const http = require('http');
const { pipeline } = require('stream');
const fs = require('fs');

const file = fs.createWriteStream('./file.jpg');

http.get('http://via.placeholder.com/150/92c952', response => {
  pipeline(
    response,
    file,
    err => {
      if (err)
        console.error('Pipeline failed.', err);
      else
        console.log('Pipeline succeeded.');
    }
  );
});

From my answer to "What's the difference between .pipe and .pipeline on streams".

How to change the text of a button in jQuery?

    $( "#btnAddProfile" ).on( "click",function(event){
    $( event.target ).html( "Save" );
});

File size exceeds configured limit (2560000), code insight features not available

This is built from Álvaro González's answer and How to increase IDE memory limit in IntelliJ IDEA on Mac?

Go to Help > Edit Custom Properties

Add:

idea.max.intellisense.filesize=999999

Restart the IDE.

How to set the focus for a particular field in a Bootstrap modal, once it appears

Seems it is because modal animation is enabled (fade in class of the dialog), after calling .modal('show'), the dialog is not immediately visible, so it can't get focus at this time.

I can think of two ways to solve this problem:

  1. Remove fade from class, so the dialog is immediately visible after calling .modal('show'). You can see http://codebins.com/bin/4ldqp7x/4 for demo. (Sorry @keyur, I mistakenly edited and saved as new version of your example)
  2. Call focus() in shown event like what @keyur wrote.

How to use refs in React with Typescript

Since React 16.3 the way to add refs is to use React.createRef as Jeff Bowen pointed in his answer. However you can take advantage of Typescript to better type your ref.

In your example you're using ref on input element. So they way I would do it is:

class SomeComponent extends React.Component<IProps, IState> {
    private inputRef: React.RefObject<HTMLInputElement>;
    constructor() {
        ...
        this.inputRef = React.createRef();
    }

    ...

    render() {
        <input type="text" ref={this.inputRef} />;
    }
}

By doing this when you want to make use of that ref you have access to all input methods:

someMethod() {
    this.inputRef.current.focus(); // 'current' is input node, autocompletion, yay!
}

You can use it on custom components as well:

private componentRef: React.RefObject<React.Component<IProps>>;

and then have, for example, access to props :

this.componentRef.current.props; // 'props' satisfy IProps interface

Fastest way to extract frames using ffmpeg?

I tried it. 3600 frame in 32 seconds. your method is really slow. You should try this.

ffmpeg -i file.mpg -s 240x135 -vf fps=1 %d.jpg

using "if" and "else" Stored Procedures MySQL

I think that this construct: if exists (select... is specific for MS SQL. In MySQL EXISTS predicate tells you whether the subquery finds any rows and it's used like this: SELECT column1 FROM t1 WHERE EXISTS (SELECT * FROM t2);

You can rewrite the above lines of code like this:

DELIMITER $$

CREATE PROCEDURE `checando`(in nombrecillo varchar(30), in contrilla varchar(30), out resultado int)

BEGIN
    DECLARE count_prim INT;
    DECLARE count_sec INT;

    SELECT COUNT(*) INTO count_prim FROM compas WHERE nombre = nombrecillo AND contrasenia = contrilla;
    SELECT COUNT(*) INTO count_sec FROM FROM compas WHERE nombre = nombrecillo;

    if (count_prim > 0) then
        set resultado = 0;
    elseif (count_sec > 0) then
        set resultado = -1;
    else 
        set resultado = -2;
    end if;
    SELECT resultado;
END

How to fix "set SameSite cookie to none" warning?

>= PHP 7.3

setcookie('key', 'value', ['samesite' => 'None', 'secure' => true]);

< PHP 7.3

exploit the path
setcookie('key', 'value', time()+(7*24*3600), "/; SameSite=None; Secure");

Emitting javascript

echo "<script>document.cookie('key=value; SameSite=None; Secure');</script>";

Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?

Try x-1 in (i for i in range(x)) for large x values, which uses a generator comprehension to avoid invoking the range.__contains__ optimisation.

C++ template typedef

C++11 added alias declarations, which are generalization of typedef, allowing templates:

template <size_t N>
using Vector = Matrix<N, 1>;

The type Vector<3> is equivalent to Matrix<3, 1>.


In C++03, the closest approximation was:

template <size_t N>
struct Vector
{
    typedef Matrix<N, 1> type;
};

Here, the type Vector<3>::type is equivalent to Matrix<3, 1>.

How to empty a list?

lst *= 0

has the same effect as

lst[:] = []

It's a little simpler and maybe easier to remember. Other than that there's not much to say

The efficiency seems to be about the same

Setting default value for TypeScript object passed as argument

No, TypeScript doesn't have a natural way of setting defaults for properties of an object defined like that where one has a default and the other does not. You could define a richer structure:

class Name {
    constructor(public first : string, 
        public last: string = "Smith") {

    }
}

And use that in place of the inline type definition.

function sayName(name: Name) {
    alert(name.first + " " + name.last);
}

You can't do something like this unfortunately:

function sayName(name : { first: string; last?:string } 
       /* and then assign a default object matching the signature */  
       = { first: null, last: 'Smith' }) {

} 

As it would only set the default if name was undefined.

PHP Echo text Color

How about writing out some escape sequences?

echo "\033[01;31m Request has been sent. Please wait for my reply! \033[0m";

Won't work through browser though, only from console ;))

printf \t option

A tab is a tab. How many spaces it consumes is a display issue, and depends on the settings of your shell.

If you want to control the width of your data, then you could use the width sub-specifiers in the printf format string. Eg. :

printf("%5d", 2);

It's not a complete solution (if the value is longer than 5 characters, it will not be truncated), but might be ok for your needs.

If you want complete control, you'll probably have to implement it yourself.

How to add a class with React.js?

Since you already have <Tags> component calling a function on its parent, you do not need additional state: simply pass the filter to the <Tags> component as a prop, and use this in rendering your buttons. Like so:

Change your render function inside your <Tags> component to:

render: function() {
  return <div className = "tags">
    <button className = {this._checkActiveBtn('')} onClick = {this.setFilter.bind(this, '')}>All</button>
    <button className = {this._checkActiveBtn('male')} onClick = {this.setFilter.bind(this, 'male')}>male</button>
    <button className = {this._checkActiveBtn('female')} onClick = {this.setFilter.bind(this, 'female')}>female</button>
    <button className = {this._checkActiveBtn('blonde')} onClick = {this.setFilter.bind(this, 'blonde')}>blonde</button>
  </div>
},

And add a function inside <Tags>:

_checkActiveBtn: function(filterName) {
  return (filterName == this.props.activeFilter) ? "btn active" : "btn";
}

And inside your <List> component, pass the filter state to the <tags> component as a prop:

return <div>
  <h2>Kids Finder</h2> 
  <Tags filter = {this.state.filter} onChangeFilter = {this.changeFilter} />
  {list}
</div>

Then it should work as intended. Codepen here (hope the link works)

How to give a Blob uploaded as FormData a file name?

When you are using Google Chrome you can use/abuse the Google Filesystem API for this. Here you can create a file with a specified name and write the content of a blob to it. Then you can return the result to the user.

I have not found a good way for Firefox yet; probably a small piece of Flash like downloadify is required to name a blob.

IE10 has a msSaveBlob() function in the BlobBuilder.

Maybe this is more for downloading a blob, but it is related.

Android - shadow on text?

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:padding="20dp" >

    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:shadowColor="#000"
        android:shadowDx="0"
        android:shadowDy="0"
        android:shadowRadius="50"
        android:text="Text Shadow Example1"
        android:textColor="#FBFBFB"
        android:textSize="28dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/textview2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Text Shadow Example2"
        android:textColor="#FBFBFB"
        android:textSize="28dp"
        android:textStyle="bold" />

</LinearLayout>

In the above XML layout code, the textview1 is given with Shadow effect in the layout. below are the configuration items are

android:shadowDx – specifies the X-axis offset of shadow. You can give -/+ values, where -Dx draws a shadow on the left of text and +Dx on the right

android:shadowDy – it specifies the Y-axis offset of shadow. -Dy specifies a shadow above the text and +Dy specifies below the text.

android:shadowRadius – specifies how much the shadow should be blurred at the edges. Provide a small value if shadow needs to be prominent. android:shadowColor – specifies the shadow color


Shadow Effect on Android TextView pragmatically

Use below code snippet to get the shadow effect on the second TextView pragmatically.

TextView textv = (TextView) findViewById(R.id.textview2);
textv.setShadowLayer(30, 0, 0, Color.RED);        

Output :

enter image description here

allowing only alphabets in text box using java script

:::::HTML:::::

<input type="text" onkeypress="return lettersValidate(event)" />

Only letters no spaces

::::JS::::::::

// ===================== Allow - Only Letters ===============================================================

function lettersValidate(key) {
    var keycode = (key.which) ? key.which : key.keyCode;

    if ((keycode > 64 && keycode < 91) || (keycode > 96 && keycode < 123))  
    {     
           return true;    
    }
    else
    {
        return false;
    }
         
}
 

Put Excel-VBA code in module or sheet?

I would suggest separating your code based on the functionality and purpose specific to each sheet or module. In this manner, you would only put code relative to a sheet's UI inside the sheet's module and only put code related to modules in respective modules. Also, use separate modules to encapsulate code that is shared or reused among several different sheets.

For example, let's say you multiple sheets that are responsible for displaying data from a database in a special way. What kinds of functionality do we have in this situation? We have functionality related to each specific sheet, tasks related to getting data from the database, and tasks related to populating a sheet with data. In this case, I might start with a module for the data access, a module for populating a sheet with data, and within each sheet I'd have code for accessing code in those modules.

It might be laid out like this.

Module: DataAccess:

Function GetData(strTableName As String, strCondition1 As String) As Recordset
    'Code Related to getting data from the database'
End Function

Module: PopulateSheet:

Sub PopulateASheet(wsSheet As Worksheet, rs As Recordset)
    'Code to populate a worksheet '
End Function

Sheet: Sheet1 Code:

Sub GetDataAndPopulate()
    'Sample Code'
     Dim rs As New Recordset
     Dim ws As Worksheet
     Dim strParam As String
     Set ws = ActiveSheet
     strParam = ws.Range("A1").Value

     Set rs = GetData("Orders",strParam)

     PopulateASheet ws, rs
End Sub

Sub Button1_Click()
    Call GetDataAndPopulate
End Sub

Connecting to local SQL Server database using C#

If you're using SQL Server express, change

SqlConnection conn = new SqlConnection("Server=localhost;" 
       + "Database=Database1;");

to

SqlConnection conn = new SqlConnection("Server=localhost\SQLExpress;" 
       + "Database=Database1;");

That, and hundreds more connection strings can be found at http://www.connectionstrings.com/

How do I make a request using HTTP basic authentication with PHP curl?

Yahoo has a tutorial on making calls to their REST services using PHP:

Make Yahoo! Web Service REST Calls with PHP

I have not used it myself, but Yahoo is Yahoo and should guarantee for at least some level of quality. They don't seem to cover PUT and DELETE requests, though.

Also, the User Contributed Notes to curl_exec() and others contain lots of good information.

String to object in JS

Since JSON.parse() method requires the Object keys to be enclosed within quotes for it to work correctly, we would first have to convert the string into a JSON formatted string before calling JSON.parse() method.

_x000D_
_x000D_
var obj = '{ firstName:"John", lastName:"Doe" }';_x000D_
_x000D_
var jsonStr = obj.replace(/(\w+:)|(\w+ :)/g, function(matchedStr) {_x000D_
  return '"' + matchedStr.substring(0, matchedStr.length - 1) + '":';_x000D_
});_x000D_
_x000D_
obj = JSON.parse(jsonStr); //converts to a regular object_x000D_
_x000D_
console.log(obj.firstName); // expected output: John_x000D_
console.log(obj.lastName); // expected output: Doe
_x000D_
_x000D_
_x000D_

This would work even if the string has a complex object (like the following) and it would still convert correctly. Just make sure that the string itself is enclosed within single quotes.

_x000D_
_x000D_
var strObj = '{ name:"John Doe", age:33, favorites:{ sports:["hoops", "baseball"], movies:["star wars", "taxi driver"]  }}';_x000D_
_x000D_
var jsonStr = strObj.replace(/(\w+:)|(\w+ :)/g, function(s) {_x000D_
  return '"' + s.substring(0, s.length-1) + '":';_x000D_
});_x000D_
_x000D_
var obj = JSON.parse(jsonStr);_x000D_
console.log(obj.favorites.movies[0]); // expected output: star wars
_x000D_
_x000D_
_x000D_

jQuery Uncaught TypeError: Cannot read property 'fn' of undefined (anonymous function)

I too had the "Uncaught TypeError: Cannot read property 'fn' of undefined" with:

$.fn.circleType = function(options) {

CODE...

};

But fixed it by wrapping it in a document ready function:

jQuery(document).ready.circleType = function(options) {

CODE...

};

Combine two data frames by rows (rbind) when they have different sets of columns

You could also just pull out the common column names.

> cols <- intersect(colnames(df1), colnames(df2))
> rbind(df1[,cols], df2[,cols])

How to get sp_executesql result into a variable?

If you have OUTPUT parameters you can do

DECLARE @retval int   
DECLARE @sSQL nvarchar(500);
DECLARE @ParmDefinition nvarchar(500);

DECLARE @tablename nvarchar(50)  
SELECT @tablename = N'products'  

SELECT @sSQL = N'SELECT @retvalOUT = MAX(ID) FROM ' + @tablename;  
SET @ParmDefinition = N'@retvalOUT int OUTPUT';

EXEC sp_executesql @sSQL, @ParmDefinition, @retvalOUT=@retval OUTPUT;

SELECT @retval;

But if you don't, and can not modify the SP:

-- Assuming that your SP return 1 value
create table #temptable (ID int null)
insert into #temptable exec mysp 'Value1', 'Value2'
select * from #temptable

Not pretty, but works.

How to pass multiple parameter to @Directives (@Components) in Angular with TypeScript?

Another neat option is to use the Directive as an element and not as an attribute.

@Directive({
   selector: 'app-directive'
})
export class InformativeDirective implements AfterViewInit {

    @Input()
    public first: string;

    @Input()
    public second: string;

    ngAfterViewInit(): void {
       console.log(`Values: ${this.first}, ${this.second}`);
    }
}

And this directive can be used like that:

<app-someKindOfComponent>
    <app-directive [first]="'first 1'" [second]="'second 1'">A</app-directive>
    <app-directive [first]="'First 2'" [second]="'second 2'">B</app-directive>
    <app-directive [first]="'First 3'" [second]="'second 3'">C</app-directive>
</app-someKindOfComponent>`

Simple, neat and powerful.

Should I always use a parallel stream when possible?

Never parallelize an infinite stream with a limit. Here is what happens:

    public static void main(String[] args) {
        // let's count to 1 in parallel
        System.out.println(
            IntStream.iterate(0, i -> i + 1)
                .parallel()
                .skip(1)
                .findFirst()
                .getAsInt());
    }

Result

    Exception in thread "main" java.lang.OutOfMemoryError
        at ...
        at java.base/java.util.stream.IntPipeline.findFirst(IntPipeline.java:528)
        at InfiniteTest.main(InfiniteTest.java:24)
    Caused by: java.lang.OutOfMemoryError: Java heap space
        at java.base/java.util.stream.SpinedBuffer$OfInt.newArray(SpinedBuffer.java:750)
        at ...

Same if you use .limit(...)

Explanation here: Java 8, using .parallel in a stream causes OOM error

Similarly, don't use parallel if the stream is ordered and has much more elements than you want to process, e.g.

public static void main(String[] args) {
    // let's count to 1 in parallel
    System.out.println(
            IntStream.range(1, 1000_000_000)
                    .parallel()
                    .skip(100)
                    .findFirst()
                    .getAsInt());
}

This may run much longer because the parallel threads may work on plenty of number ranges instead of the crucial one 0-100, causing this to take very long time.

Obtain smallest value from array in Javascript?

_x000D_
_x000D_
function smallest(){_x000D_
  if(arguments[0] instanceof Array)_x000D_
    arguments = arguments[0];_x000D_
_x000D_
  return Math.min.apply( Math, arguments );_x000D_
}_x000D_
function largest(){_x000D_
  if(arguments[0] instanceof Array)_x000D_
    arguments = arguments[0];_x000D_
_x000D_
  return Math.max.apply( Math, arguments );_x000D_
}_x000D_
var min = smallest(10, 11, 12, 13);_x000D_
var max = largest([10, 11, 12, 13]);_x000D_
_x000D_
console.log("Smallest: "+ min +", Largest: "+ max);
_x000D_
_x000D_
_x000D_

Convert blob URL to normal URL

As the previous answer have said, there is no way to decode it back to url, even when you try to see it from the chrome devtools panel, the url may be still encoded as blob.

However, it's possible to get the data, another way to obtain the data is to put it into an anchor and directly download it.

<a href="blob:http://example.com/xxxx-xxxx-xxxx-xxxx" download>download</a>

Insert this to the page containing blob url and click the button, you get the content.

Another way is to intercept the ajax call via a proxy server, then you could view the true image url.

IntelliJ can't recognize JavaFX 11 with OpenJDK 11

The issue that JavaFX is no longer part of JDK 11. The following solution works using IntelliJ (haven't tried it with NetBeans):

  1. Add JavaFX Global Library as a dependency:

    Settings -> Project Structure -> Module. In module go to the Dependencies tab, and click the add "+" sign -> Library -> Java-> choose JavaFX from the list and click Add Selected, then Apply settings.

  2. Right click source file (src) in your JavaFX project, and create a new module-info.java file. Inside the file write the following code :

    module YourProjectName { 
        requires javafx.fxml;
        requires javafx.controls;
        requires javafx.graphics;
        opens sample;
    }
    

    These 2 steps will solve all your issues with JavaFX, I assure you.

Reference : There's a You Tube tutorial made by The Learn Programming channel, will explain all the details above in just 5 minutes. I also recommend watching it to solve your problem: https://www.youtube.com/watch?v=WtOgoomDewo

How do I count the number of occurrences of a char in a String?

Well, with a quite similar task I stumbled upon this Thread. I did not see any programming language restriction and since groovy runs on a java vm: Here is how I was able to solve my Problem using Groovy.

"a.b.c.".count(".")

done.

Remove a cookie

$cookie_name = "my cookie";
$cookie_value = "my value";
$cookie_new_value = "my new value";

// Create a cookie,
setcookie($cookie_name, $cookie_value , time() + (86400 * 30), "/"); //86400 = 24 hours in seconds

// Get value in a cookie,
$cookie_value = $_COOKIE[$cookie_name];

// Update a cookie,
setcookie($cookie_name, $cookie_new_value , time() + (86400 * 30), "/");

// Delete a cookie,
setcookie($cookie_name, '' , time() - 3600, "/"); //  time() - 3600 means, set the cookie expiration date to the past hour.

What's the difference between an argument and a parameter?

Parameters are variables that are used to store the data that's passed into a function for the function to use. Arguments are the actual data that's passed into a function when it is invoked:

// x and y are parameters in this function declaration
function add(x, y) {
  // function body
  var sum = x + y;
  return sum; // return statement
}

// 1 and 2 are passed into the function as arguments
var sum = add(1, 2);

WAMP shows error 'MSVCR100.dll' is missing when install

For me problem did not resolve even after installing VC++ re-distributions. I had to manually download MSVCR110.dll file from https://www.dll-files.com/msvcr110.dll.html and placed it in c:/ > windows > system32 and it worked correctly.

How can you debug a CORS request with cURL?

Updated answer that covers most cases

curl -H "Access-Control-Request-Method: GET" -H "Origin: http://localhost" --head http://www.example.com/
  1. Replace http://www.example.com/ with URL you want to test.
  2. If response includes Access-Control-Allow-* then your resource supports CORS.

Rationale for alternative answer

I google this question every now and then and the accepted answer is never what I need. First it prints response body which is a lot of text. Adding --head outputs only headers. Second when testing S3 URLs we need to provide additional header -H "Access-Control-Request-Method: GET".

Hope this will save time.

Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

I encountered the same error and got stalled with a pyspark dataframe for few days, I was able to resolve it successfully by filling na values with 0 since I was comparing integer values from 2 fields.

Google OAuth 2 authorization - Error: redirect_uri_mismatch

To make it work on localhost and if using for web-server, do provide

Authorized JavaScript origins (Client ID for web appication)
e.g. http://localhost:4200

Convert nested Python dict to object?

Here is another way to implement SilentGhost's original suggestion:

def dict2obj(d):
  if isinstance(d, dict):
    n = {}
    for item in d:
      if isinstance(d[item], dict):
        n[item] = dict2obj(d[item])
      elif isinstance(d[item], (list, tuple)):
        n[item] = [dict2obj(elem) for elem in d[item]]
      else:
        n[item] = d[item]
    return type('obj_from_dict', (object,), n)
  else:
    return d

Why is the use of alloca() not considered good practice?

One issue is that it isn't standard, although it's widely supported. Other things being equal, I'd always use a standard function rather than a common compiler extension.

Phonegap Cordova installation Windows

Running the CMD as Administrator on Windows got me going and I think it only makes perfect sense because people don't really ever make an effort to install their stuff in a custom directory. So when you install node.js in Windows directory and then try to install PhoneGap on a Unelevated CMD it has a hard time setting the path variables.

ActiveRecord: size vs count

As the other answers state:

  • count will perform an SQL COUNT query
  • length will calculate the length of the resulting array
  • size will try to pick the most appropriate of the two to avoid excessive queries

But there is one more thing. We noticed a case where size acts differently to count/lengthaltogether, and I thought I'd share it since it is rare enough to be overlooked.

  • If you use a :counter_cache on a has_many association, size will use the cached count directly, and not make an extra query at all.

    class Image < ActiveRecord::Base
      belongs_to :product, counter_cache: true
    end
    
    class Product < ActiveRecord::Base
      has_many :images
    end
    
    > product = Product.first  # query, load product into memory
    > product.images.size      # no query, reads the :images_count column
    > product.images.count     # query, SQL COUNT
    > product.images.length    # query, loads images into memory
    

This behaviour is documented in the Rails Guides, but I either missed it the first time or forgot about it.

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

One answer I'm missing here: Multi-layer perceptron is able to find relation between features. For example it is necessary in computer vision when a raw image is provided to the learning algorithm and now Sophisticated features are calculated. Essentially the intermediate levels can calculate new unknown features.

How do I get the backtrace for all the threads in GDB?

Generally, the backtrace is used to get the stack of the current thread, but if there is a necessity to get the stack trace of all the threads, use the following command.

thread apply all bt

Using Get-childitem to get a list of files modified in the last 3 days

Try this:

(Get-ChildItem -Path c:\pstbak\*.* -Filter *.pst | ? {
  $_.LastWriteTime -gt (Get-Date).AddDays(-3) 
}).Count

Java; String replace (using regular expressions)?

Try this, may not be the best way. but it works

String str = "5 * x^3 - 6 * x^1 + 1";
str = str.replaceAll("(?x)(\\d+)(\\s+?\\*?\\s+?)(\\w+?)(\\^+?)(\\d+?)", "$1$3<sup>$5</sup>");
System.out.println(str);

Correct mime type for .mp4

According to RFC 4337 § 2, video/mp4 is indeed the correct Content-Type for MPEG-4 video.

Generally, you can find official MIME definitions by searching for the file extension and "IETF" or "RFC". The RFC (Request for Comments) articles published by the IETF (Internet Engineering Taskforce) define many Internet standards, including MIME types.

Gradients on UIView and UILabels On iPhone

This is what I got working- set UIButton in xCode's IB to transparent/clear, and no bg image.

UIColor *pinkDarkOp = [UIColor colorWithRed:0.9f green:0.53f blue:0.69f alpha:1.0];
UIColor *pinkLightOp = [UIColor colorWithRed:0.79f green:0.45f blue:0.57f alpha:1.0];

CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = [[shareWordButton layer] bounds];
gradient.cornerRadius = 7;
gradient.colors = [NSArray arrayWithObjects:
                   (id)pinkDarkOp.CGColor,
                   (id)pinkLightOp.CGColor,
                   nil];
gradient.locations = [NSArray arrayWithObjects:
                      [NSNumber numberWithFloat:0.0f],
                      [NSNumber numberWithFloat:0.7],
                      nil];

[[recordButton layer] insertSublayer:gradient atIndex:0];

Align div with fixed position on the right side

You can simply do this:

.test {
  position: -webkit-sticky; /* Safari */
  position: sticky;
  right: 0;
}

Unable to access JSON property with "-" dash

In addition to this answer, note that in Node.js if you access JSON with the array syntax [] all nested JSON keys should follow that syntax

This is the wrong way

json.first.second.third['comment']

and will will give you the 'undefined' error.

This is the correct way

json['first']['second']['third']['comment'] 

Spark: Add column to dataframe conditionally

Try withColumn with the function when as follows:

val sqlContext = new SQLContext(sc)
import sqlContext.implicits._ // for `toDF` and $""
import org.apache.spark.sql.functions._ // for `when`

val df = sc.parallelize(Seq((4, "blah", 2), (2, "", 3), (56, "foo", 3), (100, null, 5)))
    .toDF("A", "B", "C")

val newDf = df.withColumn("D", when($"B".isNull or $"B" === "", 0).otherwise(1))

newDf.show() shows

+---+----+---+---+
|  A|   B|  C|  D|
+---+----+---+---+
|  4|blah|  2|  1|
|  2|    |  3|  0|
| 56| foo|  3|  1|
|100|null|  5|  0|
+---+----+---+---+

I added the (100, null, 5) row for testing the isNull case.

I tried this code with Spark 1.6.0 but as commented in the code of when, it works on the versions after 1.4.0.

Redirect From Action Filter Attribute

I am using MVC4, I used following approach to redirect a custom html screen upon authorization breach.

Extend AuthorizeAttribute say CutomAuthorizer override the OnAuthorization and HandleUnauthorizedRequest

Register the CustomAuthorizer in the RegisterGlobalFilters.

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{

    filters.Add(new CustomAuthorizer());
}

upon identifying the unAuthorized access call HandleUnauthorizedRequestand redirect to the concerned controller action as shown below.


public class CustomAuthorizer : AuthorizeAttribute
{

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        bool isAuthorized = IsAuthorized(filterContext); // check authorization
        base.OnAuthorization(filterContext);
        if (!isAuthorized && !filterContext.ActionDescriptor.ActionName.Equals("Unauthorized", StringComparison.InvariantCultureIgnoreCase)
            && !filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.Equals("LogOn", StringComparison.InvariantCultureIgnoreCase))
        {

            HandleUnauthorizedRequest(filterContext);

        }
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result =
       new RedirectToRouteResult(
           new RouteValueDictionary{{ "controller", "LogOn" },
                                          { "action", "Unauthorized" }

                                         });

    }
}

How can I wait for 10 second without locking application UI in android

do this on a new thread (seperate it from main thread)

 new Thread(new Runnable() {
     @Override
     public void run() {
        // TODO Auto-generated method stub
     }
}).run();

get the value of DisplayName attribute

If instead

[DisplayName("Something To Name")]

you use

[Display(Name = "Something To Name")]

Just do this:

private string GetDisplayName(Class1 class1)
{
    string displayName = string.Empty;

    string propertyName = class1.Name.GetType().Name;

    CustomAttributeData displayAttribute = class1.GetType().GetProperty(propertyName).CustomAttributes.FirstOrDefault(x => x.AttributeType.Name == "DisplayAttribute");

    if (displayAttribute != null)
    {
        displayName = displayAttribute.NamedArguments.FirstOrDefault().TypedValue.Value;
    }

    return displayName;
}

Get most recent file in a directory on Linux

using R recursive option .. you may consider this as enhancement for good answers here

ls -arRtlh | tail -50

Bash: infinite sleep (infinite blocking)

tail does not block

As always: For everything there is an answer which is short, easy to understand, easy to follow and completely wrong. Here tail -f /dev/null falls into this category ;)

If you look at it with strace tail -f /dev/null you will notice, that this solution is far from blocking! It's probably even worse than the sleep solution in the question, as it uses (under Linux) precious resources like the inotify system. Also other processes which write to /dev/null make tail loop. (On my Ubuntu64 16.10 this adds several 10 syscalls per second on an already busy system.)

The question was for a blocking command

Unfortunately, there is no such thing ..

Read: I do not know any way to archive this with the shell directly.

Everything (even sleep infinity) can be interrupted by some signal. So if you want to be really sure it does not exceptionally return, it must run in a loop, like you already did for your sleep. Please note, that (on Linux) /bin/sleep apparently is capped at 24 days (have a look at strace sleep infinity), hence the best you can do probably is:

while :; do sleep 2073600; done

(Note that I believe sleep loops internally for higher values than 24 days, but this means: It is not blocking, it is very slowly looping. So why not move this loop to the outside?)

.. but you can come quite near with an unnamed fifo

You can create something which really blocks as long as there are no signals send to the process. Following uses bash 4, 2 PIDs and 1 fifo:

bash -c 'coproc { exec >&-; read; }; eval exec "${COPROC[0]}<&-"; wait'

You can check that this really blocks with strace if you like:

strace -ff bash -c '..see above..'

How this was constructed

read blocks if there is no input data (see some other answers). However, the tty (aka. stdin) usually is not a good source, as it is closed when the user logs out. Also it might steal some input from the tty. Not nice.

To make read block, we need to wait for something like a fifo which will never return anything. In bash 4 there is a command which can exactly provide us with such a fifo: coproc. If we also wait the blocking read (which is our coproc), we are done. Sadly this needs to keep open two PIDs and a fifo.

Variant with a named fifo

If you do not bother using a named fifo, you can do this as follows:

mkfifo "$HOME/.pause.fifo" 2>/dev/null; read <"$HOME/.pause.fifo"

Not using a loop on the read is a bit sloppy, but you can reuse this fifo as often as you like and make the reads terminat using touch "$HOME/.pause.fifo" (if there are more than a single read waiting, all are terminated at once).

Or use the Linux pause() syscall

For the infinite blocking there is a Linux kernel call, called pause(), which does what we want: Wait forever (until a signal arrives). However there is no userspace program for this (yet).

C

Create such a program is easy. Here is a snippet to create a very small Linux program called pause which pauses indefinitely (needs diet, gcc etc.):

printf '#include <unistd.h>\nint main(){for(;;)pause();}' > pause.c;
diet -Os cc pause.c -o pause;
strip -s pause;
ls -al pause

python

If you do not want to compile something yourself, but you have python installed, you can use this under Linux:

python -c 'while 1: import ctypes; ctypes.CDLL(None).pause()'

(Note: Use exec python -c ... to replace the current shell, this frees one PID. The solution can be improved with some IO redirection as well, freeing unused FDs. This is up to you.)

How this works (I think): ctypes.CDLL(None) loads the standard C library and runs the pause() function in it within some additional loop. Less efficient than the C version, but works.

My recommendation for you:

Stay at the looping sleep. It's easy to understand, very portable, and blocks most of the time.

Composer: file_put_contents(./composer.json): failed to open stream: Permission denied

I faced this issue as well but in my case, I was in wrong directory. Check the directory you are working

How to use protractor to check if an element is visible?

Something to consider

.isDisplayed() assumes the element is present (exists in the DOM)

so if you do

expect($('[ng-show=saving]').isDisplayed()).toBe(true);

but the element is not present, then instead of graceful failed expectation, $('[ng-show=saving]').isDisplayed() will throw an error causing the rest of it block not executed

Solution

If you assume, the element you're checking may not be present for any reason on the page, then go with a safe way below

/**
*  element is Present and is Displayed
*  @param    {ElementFinder}      $element       Locator of element
*  @return   {boolean}
*/
let isDisplayed = function ($element) {
  return (await $element.isPresent()) && (await $element.isDisplayed())
}

and use

expect(await isDisplayed( $('[ng-show=saving]') )).toBe(true);

Is double square brackets [[ ]] preferable over single square brackets [ ] in Bash?

[[ ]] double brackets are unsuported under certain version of SunOS and totally unsuported inside function declarations by : GNU bash, version 2.02.0(1)-release (sparc-sun-solaris2.6)

PHP - Extracting a property from an array of objects

You can do it easily with ouzo goodies

$result = array_map(Functions::extract()->id, $arr);

or with Arrays (from ouzo goodies)

$result = Arrays::map($arr, Functions::extract()->id);

Check out: http://ouzo.readthedocs.org/en/latest/utils/functions.html#extract

See also functional programming with ouzo (I cannot post a link).

URL encoding in Android

you can use below methods

public static String parseUrl(String surl) throws Exception
{
    URL u = new URL(surl);
    return new URI(u.getProtocol(), u.getAuthority(), u.getPath(), u.getQuery(), u.getRef()).toString();
}

or

public String parseURL(String url, Map<String, String> params)
{
    Builder builder = Uri.parse(url).buildUpon();
    for (String key : params.keySet())
    {
        builder.appendQueryParameter(key, params.get(key));
    }
    return builder.build().toString();
}

the second one is better than first.

How can I add new item to the String array?

You can't. A Java array has a fixed length. If you need a resizable array, use a java.util.ArrayList<String>.

BTW, your code is invalid: you don't initialize the array before using it.

"The certificate chain was issued by an authority that is not trusted" when connecting DB in VM Role from Azure website

If you're seeing this error message when attempting to connect using SSMS, add TrustServerCertificate=True to the Additional Connection Parameters.

What do pty and tty mean?

tty: teletype. Usually refers to the serial ports of a computer, to which terminals were attached.

pty: pseudoteletype. Kernel provided pseudoserial port connected to programs emulating terminals, such as xterm, or screen.

Linking static libraries to other static libraries

On Linux or MingW, with GNU toolchain:

ar -M <<EOM
    CREATE libab.a
    ADDLIB liba.a
    ADDLIB libb.a
    SAVE
    END
EOM
ranlib libab.a

Of if you do not delete liba.a and libb.a, you can make a "thin archive":

ar crsT libab.a liba.a libb.a

On Windows, with MSVC toolchain:

lib.exe /OUT:libab.lib liba.lib libb.lib

How to take column-slices of dataframe in pandas

Also, Given a DataFrame

data

as in your example, if you would like to extract column a and d only (e.i. the 1st and the 4th column), iloc mothod from the pandas dataframe is what you need and could be used very effectively. All you need to know is the index of the columns you would like to extract. For example:

>>> data.iloc[:,[0,3]]

will give you

          a         d
0  0.883283  0.100975
1  0.614313  0.221731
2  0.438963  0.224361
3  0.466078  0.703347
4  0.955285  0.114033
5  0.268443  0.416996
6  0.613241  0.327548
7  0.370784  0.359159
8  0.692708  0.659410
9  0.806624  0.875476

How can I determine if an image has loaded, using Javascript/jQuery?

Any comments on this one?

...

doShow = function(){
  if($('#img_id').attr('complete')){
    alert('Image is loaded!');
  } else {
    window.setTimeout('doShow()',100);
  }
};

$('#img_id').attr('src','image.jpg');

doShow();

...

Seems like works everywhere...

Proper way to restrict text input values (e.g. only numbers)

In HTML in <input> field write: (keypress)="onlyNumberKey($event)"

and in ts file write:

onlyNumberKey(event) {
    return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57;
}

How to pick element inside iframe using document.getElementById

document.getElementById('myframe1').contentWindow.document.getElementById('x')

Fiddle

contentWindow is supported by all browsers including the older versions of IE.

Note that if the iframe's src is from another domain, you won't be able to access its content due to the Same Origin Policy.

How do I extract value from Json

String jsonErrorString=((HttpClientErrorException)exception).getResponseBodyAsString();
JSONObject jsonObj=null;
String errorDetails=null;
String status=null;
try {
        jsonObj = new JSONObject(jsonErrorString);
        int index =jsonObj.getString("detail").indexOf(":");
                errorDetails=jsonObj.getString("detail").substring(index);
                status=jsonObj.getString("status");

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            item.put("status", status);
            item.put("errordetailMsg", errorDetails);

How to change the size of the radio button using CSS?

Resizing the default widget doesn’t work in all browsers, but you can make custom radio buttons with JavaScript. One of the ways is to create hidden radio buttons and then place your own images on your page. Clicking on these images changes the images (replaces the clicked image with an image with a radio button in a selected state and replaces the other images with radio buttons in an unselected state) and selects the new radio button.

Anyway, there is documentation on this subject. For example, read this: Styling Checkboxes and Radio Buttons with CSS and JavaScript.

Stop an input field in a form from being submitted

You could insert input fields without "name" attribute:

<input type="text" id="in-between" />

Or you could simply remove them once the form is submitted (in jQuery):

$("form").submit(function() {
   $(this).children('#in-between').remove();
});

Change the "From:" address in Unix "mail"

I derived this from all the above answers. Nothing worked for me when I tried each one of them. I did lot of trail and error by combining all the above answers and concluded on this. I am not sure if this works for you but it worked for me on Ununtu 12.04 and RHEL 5.4.

echo "This is the body of the mail" | mail -s 'This is the subject' '<[email protected]>,<[email protected]>' -- -F '<SenderName>' -f '<[email protected]>'

One can send the mail to any number of people by adding any number of receiver id's and the mail is sent by SenderName from [email protected]

Hope this helps.

How do you add an SDK to Android Studio?

I followed almost the same instructions by @Mason G. Zhwiti , but had to instead navigate to this folder to find the SDK:

/Users/{my-username}/Library/Android/sdk

I'm using Android Studio v1.2.2 on Mac OS

PowerShell: how to grep command output?

Your problem is that alias emits a stream of AliasInfo objects, rather than a stream of strings. This does what I think you want.

alias | out-string -stream | select-string Alias

or as a function

function grep {
  $input | out-string -stream | select-string $args
}

alias | grep Alias

When you don't handle things that are in the pipeline (like when you just ran 'alias'), the shell knows to use the ToString() method on each object (or use the output formats specified in the ETS info).

Woocommerce, get current product id

Since WooCommerce 2.2 you are able to simply use the wc_get_product Method. As an argument you can pass the ID or simply leave it empty if you're already in the loop.

wc_get_product()->get_id();

OR with 2 lines

$product = wc_get_product();
$id = $product->get_id();

Why doesn't Java offer operator overloading?

I think this may have been a conscious design choice to force developers to create functions whose names clearly communicate their intentions. In C++ developers would overload operators with functionality that would often have no relation to the commonly accepted nature of the given operator, making it nearly impossible to determine what a piece of code does without looking at the definition of the operator.

How to perform a LEFT JOIN in SQL Server between two SELECT statements?

Try this:

SELECT user.userID, edge.TailUser, edge.Weight 
FROM user
LEFT JOIN edge ON edge.HeadUser = User.UserID
WHERE edge.HeadUser=5043

OR

AND edge.HeadUser=5043

instead of WHERE clausule.

nvm keeps "forgetting" node in new terminal session

The top rated solutions didn't seem to work for me. My solution is below:

  1. Uninstall nvm completely using homebrew:brew uninstall nvm
  2. Reinstall brew install nvm
  3. In Terminal, follow the steps below(these are also listed when installing nvm via homebrew):

    mkdir ~/.nvm cp $(brew --prefix nvm)/nvm-exec ~/.nvm/ export NVM_DIR=~/.nvm source $(brew --prefix nvm)/nvm.sh

The steps outlined above will add NVM's working directory to your $HOME path, copy nvm-exec to NVM's working directory and add to $HOME/.bashrc, $HOME/.zshrc, or your shell's equivalent configuration file.(again taken from whats listed on an NVM install using homebrew)

How to check if all inputs are not empty with jQuery

You can achive this with Regex and Replace or with just trimming.

Regex example:

if ($('input').val().replace(/[\s]/, '') == '') {
    alert('Input is not filled!');
}

With this replace() function you replace white spaces with nothing (removing white spaces).

Trimming Example:

if ($('input').val().trim() == '') {
    alert('Input is not filled!');
}

trim() function removes the leading and trailing white space and line terminator characters from a string.

Load external css file like scripts in jquery which is compatible in ie also

$("head").append("<link>");
var css = $("head").children(":last");
css.attr({
      rel:  "stylesheet",
      type: "text/css",
      href: "address_of_your_css"
});

How can I account for period (AM/PM) using strftime?

>>> from datetime import datetime
>>> print(datetime.today().strftime("%H:%M %p"))
15:31 AM

Try replacing %I with %H.

What is a NullPointerException, and how do I fix it?

What is a NullPointerException?

A good place to start is the JavaDocs. They have this covered:

Thrown when an application attempts to use null in a case where an object is required. These include:

  • Calling the instance method of a null object.
  • Accessing or modifying the field of a null object.
  • Taking the length of null as if it were an array.
  • Accessing or modifying the slots of null as if it were an array.
  • Throwing null as if it were a Throwable value.

Applications should throw instances of this class to indicate other illegal uses of the null object.

It is also the case that if you attempt to use a null reference with synchronized, that will also throw this exception, per the JLS:

SynchronizedStatement:
    synchronized ( Expression ) Block
  • Otherwise, if the value of the Expression is null, a NullPointerException is thrown.

How do I fix it?

So you have a NullPointerException. How do you fix it? Let's take a simple example which throws a NullPointerException:

public class Printer {
    private String name;

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

    public void print() {
        printString(name);
    }

    private void printString(String s) {
        System.out.println(s + " (" + s.length() + ")");
    }

    public static void main(String[] args) {
        Printer printer = new Printer();
        printer.print();
    }
}

Identify the null values

The first step is identifying exactly which values are causing the exception. For this, we need to do some debugging. It's important to learn to read a stacktrace. This will show you where the exception was thrown:

Exception in thread "main" java.lang.NullPointerException
    at Printer.printString(Printer.java:13)
    at Printer.print(Printer.java:9)
    at Printer.main(Printer.java:19)

Here, we see that the exception is thrown on line 13 (in the printString method). Look at the line and check which values are null by adding logging statements or using a debugger. We find out that s is null, and calling the length method on it throws the exception. We can see that the program stops throwing the exception when s.length() is removed from the method.

Trace where these values come from

Next check where this value comes from. By following the callers of the method, we see that s is passed in with printString(name) in the print() method, and this.name is null.

Trace where these values should be set

Where is this.name set? In the setName(String) method. With some more debugging, we can see that this method isn't called at all. If the method was called, make sure to check the order that these methods are called, and the set method isn't called after the print method.

This is enough to give us a solution: add a call to printer.setName() before calling printer.print().

Other fixes

The variable can have a default value (and setName can prevent it being set to null):

private String name = "";

Either the print or printString method can check for null, for example:

printString((name == null) ? "" : name);

Or you can design the class so that name always has a non-null value:

public class Printer {
    private final String name;

    public Printer(String name) {
        this.name = Objects.requireNonNull(name);
    }

    public void print() {
        printString(name);
    }

    private void printString(String s) {
        System.out.println(s + " (" + s.length() + ")");
    }

    public static void main(String[] args) {
        Printer printer = new Printer("123");
        printer.print();
    }
}

See also:

I still can't find the problem

If you tried to debug the problem and still don't have a solution, you can post a question for more help, but make sure to include what you've tried so far. At a minimum, include the stacktrace in the question, and mark the important line numbers in the code. Also, try simplifying the code first (see SSCCE).

javax.faces.application.ViewExpiredException: View could not be restored

I add the following configuration to web.xml and it got resolved.

<context-param>
    <param-name>com.sun.faces.numberOfViewsInSession</param-name>
    <param-value>500</param-value>
</context-param>
<context-param>
    <param-name>com.sun.faces.numberOfLogicalViews</param-name>
    <param-value>500</param-value>
</context-param>

How to find column names for all tables in all databases in SQL Server

Try this:

select 
    o.name,c.name 
    from sys.columns            c
        inner join sys.objects  o on c.object_id=o.object_id
    order by o.name,c.column_id

With resulting column names this would be:

select 
     o.name as [Table], c.name as [Column]
     from sys.columns            c
         inner join sys.objects  o on c.object_id=o.object_id
     --where c.name = 'column you want to find'
     order by o.name,c.name

Or for more detail:

SELECT
    s.name as ColumnName
        ,sh.name+'.'+o.name AS ObjectName
        ,o.type_desc AS ObjectType
        ,CASE
             WHEN t.name IN ('char','varchar') THEN t.name+'('+CASE WHEN s.max_length<0 then 'MAX' ELSE CONVERT(varchar(10),s.max_length) END+')'
             WHEN t.name IN ('nvarchar','nchar') THEN t.name+'('+CASE WHEN s.max_length<0 then 'MAX' ELSE CONVERT(varchar(10),s.max_length/2) END+')'
            WHEN t.name IN ('numeric') THEN t.name+'('+CONVERT(varchar(10),s.precision)+','+CONVERT(varchar(10),s.scale)+')'
             ELSE t.name
         END AS DataType

        ,CASE
             WHEN s.is_nullable=1 THEN 'NULL'
            ELSE 'NOT NULL'
        END AS Nullable
        ,CASE
             WHEN ic.column_id IS NULL THEN ''
             ELSE ' identity('+ISNULL(CONVERT(varchar(10),ic.seed_value),'')+','+ISNULL(CONVERT(varchar(10),ic.increment_value),'')+')='+ISNULL(CONVERT(varchar(10),ic.last_value),'null')
         END
        +CASE
             WHEN sc.column_id IS NULL THEN ''
             ELSE ' computed('+ISNULL(sc.definition,'')+')'
         END
        +CASE
             WHEN cc.object_id IS NULL THEN ''
             ELSE ' check('+ISNULL(cc.definition,'')+')'
         END
            AS MiscInfo
    FROM sys.columns                           s
        INNER JOIN sys.types                   t ON s.system_type_id=t.user_type_id and t.is_user_defined=0
        INNER JOIN sys.objects                 o ON s.object_id=o.object_id
        INNER JOIN sys.schemas                sh on o.schema_id=sh.schema_id
        LEFT OUTER JOIN sys.identity_columns  ic ON s.object_id=ic.object_id AND s.column_id=ic.column_id
        LEFT OUTER JOIN sys.computed_columns  sc ON s.object_id=sc.object_id AND s.column_id=sc.column_id
        LEFT OUTER JOIN sys.check_constraints cc ON s.object_id=cc.parent_object_id AND s.column_id=cc.parent_column_id
    ORDER BY sh.name+'.'+o.name,s.column_id

EDIT
Here is a basic example to get all columns in all databases:

DECLARE @SQL varchar(max)
SET @SQL=''
SELECT @SQL=@SQL+'UNION
select 
'''+d.name+'.''+sh.name+''.''+o.name,c.name,c.column_id
from '+d.name+'.sys.columns            c
    inner join '+d.name+'.sys.objects  o on c.object_id=o.object_id
    INNER JOIN '+d.name+'.sys.schemas  sh on o.schema_id=sh.schema_id
'
FROM sys.databases d
SELECT @SQL=RIGHT(@SQL,LEN(@SQL)-5)+'order by 1,3'
--print @SQL
EXEC (@SQL)

EDIT SQL Server 2000 version

DECLARE @SQL varchar(8000)
SET @SQL=''
SELECT @SQL=@SQL+'UNION
select 
'''+d.name+'.''+sh.name+''.''+o.name,c.name,c.colid
from '+d.name+'..syscolumns            c
    inner join sysobjects  o on c.id=o.id
    INNER JOIN sysusers  sh on o.uid=sh.uid
'
FROM master.dbo.sysdatabases d
SELECT @SQL=RIGHT(@SQL,LEN(@SQL)-5)+'order by 1,3'
--print @SQL
EXEC (@SQL)

EDIT
Based on some comments, here is a version using sp_MSforeachdb:

sp_MSforeachdb 'select 
    ''?'' AS DatabaseName, o.name AS TableName,c.name AS ColumnName
    from sys.columns            c
        inner join ?.sys.objects  o on c.object_id=o.object_id
    --WHERE ''?'' NOT IN (''master'',''msdb'',''tempdb'',''model'')
    order by o.name,c.column_id'

Android update activity UI from service

Clyde's solution works, but it is a broadcast, which I am pretty sure will be less efficient than calling a method directly. I could be mistaken, but I think the broadcasts are meant more for inter-application communication.

I'm assuming you already know how to bind a service with an Activity. I do something sort of like the code below to handle this kind of problem:

class MyService extends Service {
    MyFragment mMyFragment = null;
    MyFragment mMyOtherFragment = null;

    private void networkLoop() {
        ...

        //received new data for list.
        if(myFragment != null)
            myFragment.updateList();
        }

        ...

        //received new data for textView
        if(myFragment !=null)
            myFragment.updateText();

        ...

        //received new data for textView
        if(myOtherFragment !=null)
            myOtherFragment.updateSomething();

        ...
    }
}


class MyFragment extends Fragment {

    public void onResume() {
        super.onResume()
        //Assuming your activity bound to your service
        getActivity().mMyService.mMyFragment=this;
    }

    public void onPause() {
        super.onPause()
        //Assuming your activity bound to your service
        getActivity().mMyService.mMyFragment=null;
    }

    public void updateList() {
        runOnUiThread(new Runnable() {
            public void run() {
                //Update the list.
            }
        });
    }

    public void updateText() {
       //as above
    }
}

class MyOtherFragment extends Fragment {
             public void onResume() {
        super.onResume()
        //Assuming your activity bound to your service
        getActivity().mMyService.mMyOtherFragment=this;
    }

    public void onPause() {
        super.onPause()
        //Assuming your activity bound to your service
        getActivity().mMyService.mMyOtherFragment=null;
    }

    public void updateSomething() {//etc... }
}

I left out bits for thread safety, which is essential. Make sure to use locks or something like that when checking and using or changing the fragment references on the service.

NPM Install Error:Unexpected end of JSON input while parsing near '...nt-webpack-plugin":"0'

Just faced the issue of Unexpected end of JSON input while parsing near.. while adding the 'radium' package in my React App. As a matter of fact, I am facing this issue even when trying to update the NPM to the latest version.

Anyways, NPM didn't work after clearing the cache and it also won't update to the latest version right now but adding the package via Yarn did the trick for me.

So, if you are in a hurry to solve this issue but you are not able to, then give yarn a try instead of npm.

Happy Coding!

Update

After trying few things finally sudo npm cache clean --force worked for me.

This can be a temporary glitch in your network or with something else in the npm registry.

Excel VBA Run-time error '424': Object Required when trying to copy TextBox

The issue is with this line

 xlo.Worksheets(1).Cells(2, 2) = TextBox1.Text

You have the textbox defined at some other location which you are not using here. Excel is unable to find the textbox object in the current sheet while this textbox was defined in xlw.

Hence replace this with

 xlo.Worksheets(1).Cells(2, 2) = worksheets("xlw").TextBox1.Text 

Comparing floating point number to zero

No.

Equality is equality.

The function you wrote will not test two doubles for equality, as its name promises. It will only test if two doubles are "close enough" to each other.

If you really want to test two doubles for equality, use this one:

inline bool isEqual(double x, double y)
{
   return x == y;
}

Coding standards usually recommend against comparing two doubles for exact equality. But that is a different subject. If you actually want to compare two doubles for exact equality, x == y is the code you want.

10.000000000000001 is not equal to 10.0, no matter what they tell you.

An example of using exact equality is when a particular value of a double is used as a synonym of some special state, such as "pending calulation" or "no data available". This is possible only if the actual numeric values after that pending calculation are only a subset of the possible values of a double. The most typical particular case is when that value is nonnegative, and you use -1.0 as an (exact) representation of a "pending calculation" or "no data available". You could represent that with a constant:

const double NO_DATA = -1.0;

double myData = getSomeDataWhichIsAlwaysNonNegative(someParameters);

if (myData != NO_DATA)
{
    ...
}

Which is faster: Stack allocation or Heap allocation

I think the lifetime is crucial, and whether the thing being allocated has to be constructed in a complex way. For example, in transaction-driven modeling, you usually have to fill in and pass in a transaction structure with a bunch of fields to operation functions. Look at the OSCI SystemC TLM-2.0 standard for an example.

Allocating these on the stack close to the call to the operation tends to cause enormous overhead, as the construction is expensive. The good way there is to allocate on the heap and reuse the transaction objects either by pooling or a simple policy like "this module only needs one transaction object ever".

This is many times faster than allocating the object on each operation call.

The reason is simply that the object has an expensive construction and a fairly long useful lifetime.

I would say: try both and see what works best in your case, because it can really depend on the behavior of your code.

What's the difference between a Future and a Promise?

According to this discussion, Promise has finally been called CompletableFuture for inclusion in Java 8, and its javadoc explains:

A Future that may be explicitly completed (setting its value and status), and may be used as a CompletionStage, supporting dependent functions and actions that trigger upon its completion.

An example is also given on the list:

f.then((s -> aStringFunction(s)).thenAsync(s -> ...);

Note that the final API is slightly different but allows similar asynchronous execution:

CompletableFuture<String> f = ...;
f.thenApply(this::modifyString).thenAccept(System.out::println);

How can I convert a date to GMT?

Based on the accepted answer and the second highest scoring answer both are not perfect according to the comment so I mixed both to get something perfect:

_x000D_
_x000D_
var date = new Date(); //Current timestamp_x000D_
date = date.toGMTString(); _x000D_
//Based on the time zone where the date was created_x000D_
console.log(date);_x000D_
_x000D_
/*based on the comment getTimezoneOffset returns an offset based _x000D_
on the date it is called on, and the time zone of the computer the code is_x000D_
 running on. It does not supply the offset passed in when constructing a _x000D_
date from a string. */_x000D_
_x000D_
date = new Date(date); //will convert to present timestamp offset_x000D_
date = new Date(date.getTime() + (date.getTimezoneOffset() * 60 * 1000)); _x000D_
console.log(date);
_x000D_
_x000D_
_x000D_

How to find elements with 'value=x'?

The following worked for me:

$("[id=attached_docs][value=123]")

Understanding inplace=True

The way I use it is

# Have to assign back to dataframe (because it is a new copy)
df = df.some_operation(inplace=False) 

Or

# No need to assign back to dataframe (because it is on the same copy)
df.some_operation(inplace=True)

CONCLUSION:

 if inplace is False
      Assign to a new variable;
 else
      No need to assign

Resize jqGrid when browser is resized?

Been using this in production for some time now without any complaints (May take some tweaking to look right on your site.. for instance, subtracting the width of a sidebar, etc)

$(window).bind('resize', function() {
    $("#jqgrid").setGridWidth($(window).width());
}).trigger('resize');

How can I switch to a tag/branch in hg?

Once you have cloned the repo, you have everything: you can then hg up branchname or hg up tagname to update your working copy.

UP: hg up is a shortcut of hg update, which also has hg checkout alias for people with git habits.

What is the purpose of willSet and didSet in Swift?

Getter and setter are sometimes too heavy to implement just to observe proper value changes. Usually this needs extra temporary variable handling and extra checks, and you will want to avoid even those tiny labour if you write hundreds of getters and setters. These stuffs are for the situation.

How do I disable "missing docstring" warnings at a file-level in Pylint?

  1. Ctrl + Shift + P

  2. Then type and click on > preferences:configure language specific settings

  3. and then type "python" after that. Paste the code

     {
         "python.linting.pylintArgs": [
             "--load-plugins=pylint_django", "--errors-only"
         ],
     }
    

Make Iframe to fit 100% of container's remaining height

We use a JavaScript to solve this problem; here is the source.


var buffer = 20; //scroll bar buffer
var iframe = document.getElementById('ifm');

function pageY(elem) {
    return elem.offsetParent ? (elem.offsetTop + pageY(elem.offsetParent)) : elem.offsetTop;
}

function resizeIframe() {
    var height = document.documentElement.clientHeight;
    height -= pageY(document.getElementById('ifm'))+ buffer ;
    height = (height < 0) ? 0 : height;
    document.getElementById('ifm').style.height = height + 'px';
}

// .onload doesn't work with IE8 and older.
if (iframe.attachEvent) {
    iframe.attachEvent("onload", resizeIframe);
} else {
    iframe.onload=resizeIframe;
}

window.onresize = resizeIframe;

Note: ifm is the iframe ID

pageY() was created by John Resig (the author of jQuery)

How to force remounting on React components?

I'm working on Crud for my app. This is how I did it Got Reactstrap as my dependency.

import React, { useState, setState } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import firebase from 'firebase';
// import { LifeCrud } from '../CRUD/Crud';
import { Row, Card, Col, Button } from 'reactstrap';
import InsuranceActionInput from '../CRUD/InsuranceActionInput';

const LifeActionCreate = () => {
  let [newLifeActionLabel, setNewLifeActionLabel] = React.useState();

  const onCreate = e => {
    const db = firebase.firestore();

    db.collection('actions').add({
      label: newLifeActionLabel
    });
    alert('New Life Insurance Added');
    setNewLifeActionLabel('');
  };

  return (
    <Card style={{ padding: '15px' }}>
      <form onSubmit={onCreate}>
        <label>Name</label>
        <input
          value={newLifeActionLabel}
          onChange={e => {
            setNewLifeActionLabel(e.target.value);
          }}
          placeholder={'Name'}
        />

        <Button onClick={onCreate}>Create</Button>
      </form>
    </Card>
  );
};

Some React Hooks in there

Creating a search form in PHP to search a database?

try this out let me know what happens.

Form:

<form action="form.php" method="post"> 
Search: <input type="text" name="term" /><br /> 
<input type="submit" value="Submit" /> 
</form> 

Form.php:

$term = mysql_real_escape_string($_REQUEST['term']);    

$sql = "SELECT * FROM liam WHERE Description LIKE '%".$term."%'";
$r_query = mysql_query($sql);

while ($row = mysql_fetch_array($r_query)){ 
echo 'Primary key: ' .$row['PRIMARYKEY']; 
echo '<br /> Code: ' .$row['Code']; 
echo '<br /> Description: '.$row['Description']; 
echo '<br /> Category: '.$row['Category']; 
echo '<br /> Cut Size: '.$row['CutSize'];  
} 

Edit: Cleaned it up a little more.

Final Cut (my test file):

<?php
$db_hostname = 'localhost';
$db_username = 'demo';
$db_password = 'demo';
$db_database = 'demo';

// Database Connection String
$con = mysql_connect($db_hostname,$db_username,$db_password);
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db($db_database, $con);
?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
<form action="" method="post">  
Search: <input type="text" name="term" /><br />  
<input type="submit" value="Submit" />  
</form>  
<?php
if (!empty($_REQUEST['term'])) {

$term = mysql_real_escape_string($_REQUEST['term']);     

$sql = "SELECT * FROM liam WHERE Description LIKE '%".$term."%'"; 
$r_query = mysql_query($sql); 

while ($row = mysql_fetch_array($r_query)){  
echo 'Primary key: ' .$row['PRIMARYKEY'];  
echo '<br /> Code: ' .$row['Code'];  
echo '<br /> Description: '.$row['Description'];  
echo '<br /> Category: '.$row['Category'];  
echo '<br /> Cut Size: '.$row['CutSize'];   
}  

}
?>
    </body>
</html>

How to copy the first few lines of a giant file, and add a line of text at the end of it using some Linux commands?

The head command can get the first n lines. Variations are:

head -7 file
head -n 7 file
head -7l file

which will get the first 7 lines of the file called "file". The command to use depends on your version of head. Linux will work with the first one.

To append lines to the end of the same file, use:

echo 'first line to add' >>file
echo 'second line to add' >>file
echo 'third line to add' >>file

or:

echo 'first line to add
second line to add
third line to add' >>file

to do it in one hit.

So, tying these two ideas together, if you wanted to get the first 10 lines of the input.txt file to output.txt and append a line with five "=" characters, you could use something like:

( head -10 input.txt ; echo '=====' ) > output.txt

In this case, we do both operations in a sub-shell so as to consolidate the output streams into one, which is then used to create or overwrite the output file.

Installing a plain plugin jar in Eclipse 3.5

For Eclipse Mars (I've just verified that) you to do this (assuming that C:\eclipseMarsEE is root folder of your Eclipse):

  1. Add plugins folder to C:\eclipseMarsEE\dropins so that it looks like: C:\eclipseMarsEE\dropins\plugins
  2. Then add plugin you want to install into that folder: C:\eclipseMarsEE\dropins\plugins\someplugin.jar
  3. Start Eclipse with clean option.
  4. If you are using shortcut on desktop then just right click on Eclipse icon > Properties and in Target field add: -clean like this: C:\eclipseMarsEE\eclipse.exe -clean

enter image description here

  1. Start Eclipse and verify that your plugin works.
  2. Remove -clean option from Target field.

How to round the minute of a datetime object

Not the best for speed when the exception is caught, however this would work.

def _minute10(dt=datetime.utcnow()):
    try:
        return dt.replace(minute=round(dt.minute, -1))
    except ValueError:
        return dt.replace(minute=0) + timedelta(hours=1)

Timings

%timeit _minute10(datetime(2016, 12, 31, 23, 55))
100000 loops, best of 3: 5.12 µs per loop

%timeit _minute10(datetime(2016, 12, 31, 23, 31))
100000 loops, best of 3: 2.21 µs per loop

Windows 7 SDK installation failure

One of the things to also keep in mind is that when you have Visual Studio 2010 SP1 installed some C++ compilers and libraries may have been removed. There's been an update made available by Microsoft to make sure those are brought back to your system.

Install this update to restore the Visual C++ compilers and libraries that may have been removed when Visual Studio 2010 Service Pack 1 (SP1) was installed. The compilers and libraries are part of the Microsoft Windows Software Development Kit for Windows 7 and the .NET Framework 4 (later referred to as the Windows SDK 7.1).

Also, when you read the VS2010 SP1 README you'll also notice that some notes have been made in regards to the Windows 7 SDK (See section 2.2.1) installation. It may be that one of these conditions may apply to you and therefore may need to uncheck the C++ compiler-checkbox as the SDK installer will attempt to install an older version of compilers ÓR you may need to uninstall VS2010 SP1 and re-run the SDK 7.1 installation, repair or modification.

Condition 1: If the Visual C++ Compilers checkbox is selected when the Windows SDK 7.1 is installed, repaired, or modified after Visual Studio 2010 SP1 has been installed, the error may be encountered and some selected components may not be installed.

Workaround: Clear the Visual C++ Compilers checkbox before you run the Windows SDK 7.1 installation, repair, or modification.

Condition 2: If the Visual C++ Compilers checkbox is selected when the Windows SDK 7.1 is installed, repaired, or modified after Visual Studio 2010 has been installed but Visual Studio 2010 SP1 has not been uninstalled, the error may be encountered.

Workaround: Uninstall Visual Studio 2010 SP1 and then rerun the Windows SDK 7.1 installation, repair, or modification.

However, even then I found that I still needed to uninstall any existing Visual C++ 2010 redistributables, as has been suggested by mgrandi.

How do I add a reference to the MySQL connector for .NET?

When you download the connector/NET choose Select Platform = .NET & Mono (not windows!)

PHP strtotime +1 month adding an extra month

It's jumping to March because today is 29th Jan, and adding a month gives 29th Feb, which doesn't exist, so it's moving to the next valid date.

This will happen on the 31st of a lot of months as well, but is obviously more noticable in the case of January to Feburary because Feb is shorter.

If you're not interested in the day of month and just want it to give the next month, you should specify the input date as the first of the current month. This will always give you the correct answer if you add a month.

For the same reason, if you want to always get the last day of the next month, you should start by calculating the first of the month after the one you want, and subtracting a day.

Can an html element have multiple ids?

No you cannot have multiple ids for a single tag, but I have seen a tag with a name attribute and an id attribute which are treated the same by some applications.

How to do error logging in CodeIgniter (PHP)

In config.php add or edit the following lines to this:
------------------------------------------------------
$config['log_threshold'] = 4; // (1/2/3)
$config['log_path'] = '/home/path/to/application/logs/';

Run this command in the terminal:
----------------------------------
sudo chmod -R 777 /home/path/to/application/logs/

Open File in Another Directory (Python)

from pathlib import Path

data_folder = Path("source_data/text_files/")
file_to_open = data_folder / "raw_data.txt"

f = open(file_to_open)
print(f.read())

How can I parse a String to BigDecimal?

Try this

// Create a DecimalFormat that fits your requirements
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(',');
symbols.setDecimalSeparator('.');
String pattern = "#,##0.0#";
DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
decimalFormat.setParseBigDecimal(true);

// parse the string
BigDecimal bigDecimal = (BigDecimal) decimalFormat.parse("10,692,467,440,017.120");
System.out.println(bigDecimal);

If you are building an application with I18N support you should use DecimalFormatSymbols(Locale)

Also keep in mind that decimalFormat.parse can throw a ParseException so you need to handle it (with try/catch) or throw it and let another part of your program handle it

Webpack not excluding node_modules

From your config file, it seems like you're only excluding node_modules from being parsed with babel-loader, but not from being bundled.

In order to exclude node_modules and native node libraries from bundling, you need to:

  1. Add target: 'node' to your webpack.config.js. This will exclude native node modules (path, fs, etc.) from being bundled.
  2. Use webpack-node-externals in order to exclude other node_modules.

So your result config file should look like:

var nodeExternals = require('webpack-node-externals');
...
module.exports = {
    ...
    target: 'node', // in order to ignore built-in modules like path, fs, etc. 
    externals: [nodeExternals()], // in order to ignore all modules in node_modules folder 
    ...
};

How do I center a window onscreen in C#?

 Centering a form in runtime

1.Set following property of Form:
   -> StartPosition : CenterScreen
   -> WindowState: Normal

This will center the form at runtime but if form size is bigger then expected, do second step.

2. Add Custom Size after InitializeComponent();

public Form1()
{
    InitializeComponent();
    this.Size = new Size(800, 600);
}

MySQL ERROR 1045 (28000): Access denied for user 'bill'@'localhost' (using password: YES)

Okay, I'm not sure but probably this is my.cnf file inside mysql installation directory is the culprit. Comment out this line and the problem might be resolved.

bind-address = 127.0.0.1

nginx - nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)

i fixed this by running sudo apachectl stop - turns out apache was running in the background and prevented nginx from starting on the desired port.

On ubuntu run sudo /etc/init.d/apache2 stop

Java generating Strings with placeholders

See String.format method.

String s = "hello %s!";
s = String.format(s, "world");
assertEquals(s, "hello world!"); // should be true

Scroll Element into View with Selenium

Use the driver to send keys like the pagedown or downarrow key to bring the element into view. I know it's too simple a solution and might not be applicable in all cases.

Why is my toFixed() function not working?

I tried function toFixed(2) many times. Every time console shows "toFixed() is not a function".

but how I resolved is By using Math.round()

eg:

if ($(this).attr('name') == 'time') {
    var value = parseFloat($(this).val());
    value = Math.round(value*100)/100; // 10 defines 1 decimals, 100 for 2, 1000 for 3
    alert(value);
}

this thing surely works for me and it might help you guys too...

Is it possible to have SSL certificate for IP address, not domain name?

The short answer is yes, as long as it is a public IP address.

Issuance of certificates to reserved IP addresses is not allowed, and all certificates previously issued to reserved IP addresses were revoked as of 1 October 2016.

According to the CA Browser forum, there may be compatibility issues with certificates for IP addresses unless the IP address is in both the commonName and subjectAltName fields. This is due to legacy SSL implementations which are not aligned with RFC 5280, notably, Windows OS prior to Windows 10.


Sources:

  1. Guidance on IP Addresses In Certificates CA Browser Forum
  2. Baseline Requirements 1.4.1 CA Browser Forum
  3. The (soon to be) not-so Common Name unmitigatedrisk.com
  4. RFC 5280 IETF

Note: an earlier version of this answer stated that all IP address certificates would be revoked on 1 October 2016. Thanks to Navin for pointing out the error.

batch/bat to copy folder and content at once

I suspect that the xcopy command is the magic bullet you're looking for.

It can copy files, directories, and even entire drives while preserving the original directory hierarchy. There are also a handful of additional options available, compared to the basic copy command.

Check out the documentation here.

If your batch file only needs to run on Windows Vista or later, you can use robocopy instead, which is an even more powerful tool than xcopy, and is now built into the operating system. It's documentation is available here.

How to subscribe to an event on a service in Angular2?

Using alpha 28, I accomplished programmatically subscribing to event emitters by way of the eventEmitter.toRx().subscribe(..) method. As it is not intuitive, it may perhaps change in a future release.

Loop over html table and get checked checkboxes (JQuery)

Use this instead:

$('#save').click(function () {
    $('#mytable').find('input[type="checkbox"]:checked') //...
});

Let me explain you what the selector does: input[type="checkbox"] means that this will match each <input /> with type attribute type equals to checkbox After that: :checked will match all checked checkboxes.

You can loop over these checkboxes with:

$('#save').click(function () {
    $('#mytable').find('input[type="checkbox"]:checked').each(function () {
       //this is the current checkbox
    });
});

Here is demo in JSFiddle.


And here is a demo which solves exactly your problem http://jsfiddle.net/DuE8K/1/.

$('#save').click(function () {
    $('#mytable').find('tr').each(function () {
        var row = $(this);
        if (row.find('input[type="checkbox"]').is(':checked') &&
            row.find('textarea').val().length <= 0) {
            alert('You must fill the text area!');
        }
    });
});

Pass an array of integers to ASP.NET Web API?

You may try this code for you to take comma separated values / an array of values to get back a JSON from webAPI

 public class CategoryController : ApiController
 {
     public List<Category> Get(String categoryIDs)
     {
         List<Category> categoryRepo = new List<Category>();

         String[] idRepo = categoryIDs.Split(',');

         foreach (var id in idRepo)
         {
             categoryRepo.Add(new Category()
             {
                 CategoryID = id,
                 CategoryName = String.Format("Category_{0}", id)
             });
         }
         return categoryRepo;
     }
 }

 public class Category
 {
     public String CategoryID { get; set; }
     public String CategoryName { get; set; }
 } 

Output :

[
{"CategoryID":"4","CategoryName":"Category_4"}, 
{"CategoryID":"5","CategoryName":"Category_5"}, 
{"CategoryID":"3","CategoryName":"Category_3"} 
]

Find non-ASCII characters in varchar columns using SQL Server

This script searches for non-ascii characters in one column. It generates a string of all valid characters, here code point 32 to 127. Then it searches for rows that don't match the list:

declare @str varchar(128)
declare @i int
set @str = ''
set @i = 32
while @i <= 127
    begin
    set @str = @str + '|' + char(@i)
    set @i = @i + 1
    end

select  col1
from    YourTable
where   col1 like '%[^' + @str + ']%' escape '|'

"installation of package 'FILE_PATH' had non-zero exit status" in R

I was having a similar problem trying to install a package called AED. I tried using the install.packages() command:

install.packages('FILE_PATH', repos=NULL, type = "source")

but kept getting the following warning message:

Warning message:
In install.packages("/Users/blahblah/R-2.14.0/AED",  :
installation of package ‘/Users/blahblah/R-2.14.0/AED’ had
non-zero exit status

It turned out the folder 'AED' had another folder inside of it that hadn't been uncompressed. I just uncompressed it and tried installing the package again and it worked.

How to hide image broken Icon using only CSS/HTML?

Missing images will either just display nothing, or display a [ ? ] style box when their source cannot be found. Instead you may want to replace that with a "missing image" graphic that you are sure exists so there is better visual feedback that something is wrong. Or, you might want to hide it entirely. This is possible, because images that a browser can't find fire off an "error" JavaScript event we can watch for.

    //Replace source
    $('img').error(function(){
            $(this).attr('src', 'missing.png');
    });

   //Or, hide them
   $("img").error(function(){
           $(this).hide();
   });

Additionally, you may wish to trigger some kind of Ajax action to send an email to a site admin when this occurs.

How to Execute a Python File in Notepad ++?

I started using Notepad++ for Python very recently and I found this method very easy. Once you are ready to run the code,right-click on the tab of your code in Notepad++ window and select "Open Containing Folder in cmd". This will open the Command Prompt into the folder where the current program is stored. All you need to do now is to execute:

python

This was done on Notepad++ (Build 10 Jan 2015).

I can't add the screenshots, so here's a blog post with the screenshots - http://coder-decoder.blogspot.in/2015/03/using-notepad-in-windows-to-edit-and.html

Ruby replace string with captured regex pattern

 "foobar".gsub(/(o+)/){|s|s+'ball'}
 #=> "fooballbar"

How to programmatically log out from Facebook SDK 3.0 without using Facebook login/logout button?

Yup, As @luizfelippe mentioned Session class has been removed since SDK 4.0. We need to use LoginManager.

I just looked into LoginButton class for logout. They are making this kind of check. They logs out only if accessToken is not null. So, I think its better to have this in our code too..

AccessToken accessToken = AccessToken.getCurrentAccessToken();
if(accessToken != null){
    LoginManager.getInstance().logOut();
}

PHP compare time

To see of the curent time is greater or equal to 14:08:10 do this:

if (time() >= strtotime("14:08:10")) {
  echo "ok";
}

Depending on your input sources, make sure to account for timezone.

See PHP time() and PHP strtotime()

Angular cli generate a service and include the provider in one step

In Angular 5.12 and latest Angular CLI, do

ng generate service my-service -m app.module

Find the differences between 2 Excel worksheets?

I found this command line utility that doesn't show the GUI output but gave me what I needed: https://github.com/na-ka-na/ExcelCompare

Sample output (taken from the project's readme file):

> excel_cmp xxx.xlsx yyy.xlsx
DIFF  Cell at     Sheet1!A1 => 'a' v/s 'aa'
EXTRA Cell in WB1 Sheet1!B1 => 'cc'
DIFF  Cell at     Sheet1!D4 => '4.0' v/s '14.0'
EXTRA Cell in WB2 Sheet1!J10 => 'j'
EXTRA Cell in WB1 Sheet1!K11 => 'k'
EXTRA Cell in WB1 Sheet2!A1 => 'abc'
EXTRA Cell in WB2 Sheet3!A1 => 'haha'
----------------- DIFF -------------------
Sheets: [Sheet1]
Rows: [1, 4]
Cols: [A, D]
----------------- EXTRA WB1 -------------------
Sheets: [Sheet1, Sheet2]
Rows: [1, 11]
Cols: [B, K, A]
----------------- EXTRA WB2 -------------------
Sheets: [Sheet1, Sheet3]
Rows: [10, 1]
Cols: [J, A]
-----------------------------------------
Excel files xxx.xlsx and yyy.xlsx differ

Android: No Activity found to handle Intent error? How it will resolve

Add the below to your manifest:

  <activity   android:name=".AppPreferenceActivity" android:label="@string/app_name">  
     <intent-filter> 
       <action android:name="com.scytec.datamobile.vd.gui.android.AppPreferenceActivity" />  
       <category android:name="android.intent.category.DEFAULT" />  
     </intent-filter>   
  </activity>

Converting VS2012 Solution to VS2010

Solution of VS2010 is supported by VS2012. Solution of VS2012 isn't supported by VS2010 --> one-way upgrade only. VS2012 doesn't support setup projects. Find here more about VS2010/VS2012 compatibility: http://msdn.microsoft.com/en-us/library/hh266747(v=vs.110).aspx

Getting index value on razor foreach

Take a look at this solution using Linq. His example is similar in that he needed different markup for every 3rd item.

foreach( var myItem in Model.Members.Select(x,i) => new {Member = x, Index = i){
    ...
}

How can I get zoom functionality for images?

Try using ZoomView for zooming any other view.

http://code.google.com/p/android-zoom-view/ it's easy, free and fun to use!

Closing JFrame with button click

You cat use setVisible () method of JFrame (and set visibility to false) or dispose () method which is more similar to close operation.

How to deal with page breaks when printing a large HTML table

I recently solved this problem with a good solution.

CSS:

.avoidBreak { 
    border: 2px solid;
    page-break-inside:avoid;
}

JS:

function Print(){
    $(".tableToPrint td, .tableToPrint th").each(function(){ $(this).css("width",  $(this).width() + "px")  });
    $(".tableToPrint tr").wrap("<div class='avoidBreak'></div>");
    window.print();
}

Works like a charm!

Sort objects in ArrayList by date?

Use the below approach to identify dates are sort or not

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");

boolean  decendingOrder = true;
    for(int index=0;index<date.size() - 1; index++) {
        if(simpleDateFormat.parse(date.get(index)).getTime() < simpleDateFormat.parse(date.get(index+1)).getTime()) {
            decendingOrder = false;
            break;
        }
    }
    if(decendingOrder) {
        System.out.println("Date are in Decending Order");
    }else {
        System.out.println("Date not in Decending Order");
    }       
}   

Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

After struggling for hours the only thing which worked was

sudo mysql.server start

Then do a secure installation with

mysql_secure_installation 

Then connect to the db via

mysql -uroot -p

Mysql is installed via homebrew and the version is

Server version: 5.7.21 Homebrew

Specifying the version might be helpful as the solution may be different based upon the version.

Correlation between two vectors?

Try xcorr, it's a built-in function in MATLAB for cross-correlation:

c = xcorr(A_1, A_2);

However, note that it requires the Signal Processing Toolbox installed. If not, you can look into the corrcoef command instead.

Get difference between two dates in months using Java

You can try this:

Calendar sDate = Calendar.getInstance();
Calendar eDate = Calendar.getInstance();
sDate.setTime(startDate.getTime());
eDate.setTime(endDate.getTime());
int difInMonths = sDate.get(Calendar.MONTH) - eDate.get(Calendar.MONTH);

I think this should work. I used something similar for my project and it worked for what I needed (year diff). You get a Calendar from a Date and just get the month's diff.

python mpl_toolkits installation issue

It doesn't work on Ubuntu 16.04, it seems that some libraries have been forgotten in the python installation package on this one. You should use package manager instead.

Solution

Uninstall matplotlib from pip then install it again with apt-get

python 2:

sudo pip uninstall matplotlib
sudo apt-get install python-matplotlib

python 3:

sudo pip3 uninstall matplotlib
sudo apt-get install python3-matplotlib

SQL Server: Importing database from .mdf?

See: How to: Attach a Database File to SQL Server Express

Login to the database via sqlcmd:

sqlcmd -S Server\Instance

And then issue the commands:

USE [master]
GO
CREATE DATABASE [database_name] ON 
( FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Data\<database name>.mdf' ),
( FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Data\<database name>.ldf' )
 FOR ATTACH ;
GO

Best practice for REST token-based authentication with JAX-RS and Jersey

How token-based authentication works

In token-based authentication, the client exchanges hard credentials (such as username and password) for a piece of data called token. For each request, instead of sending the hard credentials, the client will send the token to the server to perform authentication and then authorization.

In a few words, an authentication scheme based on tokens follow these steps:

  1. The client sends their credentials (username and password) to the server.
  2. The server authenticates the credentials and, if they are valid, generate a token for the user.
  3. The server stores the previously generated token in some storage along with the user identifier and an expiration date.
  4. The server sends the generated token to the client.
  5. The client sends the token to the server in each request.
  6. The server, in each request, extracts the token from the incoming request. With the token, the server looks up the user details to perform authentication.
    • If the token is valid, the server accepts the request.
    • If the token is invalid, the server refuses the request.
  7. Once the authentication has been performed, the server performs authorization.
  8. The server can provide an endpoint to refresh tokens.

Note: The step 3 is not required if the server has issued a signed token (such as JWT, which allows you to perform stateless authentication).

What you can do with JAX-RS 2.0 (Jersey, RESTEasy and Apache CXF)

This solution uses only the JAX-RS 2.0 API, avoiding any vendor specific solution. So, it should work with JAX-RS 2.0 implementations, such as Jersey, RESTEasy and Apache CXF.

It is worthwhile to mention that if you are using token-based authentication, you are not relying on the standard Java EE web application security mechanisms offered by the servlet container and configurable via application's web.xml descriptor. It's a custom authentication.

Authenticating a user with their username and password and issuing a token

Create a JAX-RS resource method which receives and validates the credentials (username and password) and issue a token for the user:

@Path("/authentication")
public class AuthenticationEndpoint {

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response authenticateUser(@FormParam("username") String username, 
                                     @FormParam("password") String password) {

        try {

            // Authenticate the user using the credentials provided
            authenticate(username, password);

            // Issue a token for the user
            String token = issueToken(username);

            // Return the token on the response
            return Response.ok(token).build();

        } catch (Exception e) {
            return Response.status(Response.Status.FORBIDDEN).build();
        }      
    }

    private void authenticate(String username, String password) throws Exception {
        // Authenticate against a database, LDAP, file or whatever
        // Throw an Exception if the credentials are invalid
    }

    private String issueToken(String username) {
        // Issue a token (can be a random String persisted to a database or a JWT token)
        // The issued token must be associated to a user
        // Return the issued token
    }
}

If any exceptions are thrown when validating the credentials, a response with the status 403 (Forbidden) will be returned.

If the credentials are successfully validated, a response with the status 200 (OK) will be returned and the issued token will be sent to the client in the response payload. The client must send the token to the server in every request.

When consuming application/x-www-form-urlencoded, the client must to send the credentials in the following format in the request payload:

username=admin&password=123456

Instead of form params, it's possible to wrap the username and the password into a class:

public class Credentials implements Serializable {

    private String username;
    private String password;

    // Getters and setters omitted
}

And then consume it as JSON:

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response authenticateUser(Credentials credentials) {

    String username = credentials.getUsername();
    String password = credentials.getPassword();

    // Authenticate the user, issue a token and return a response
}

Using this approach, the client must to send the credentials in the following format in the payload of the request:

{
  "username": "admin",
  "password": "123456"
}

Extracting the token from the request and validating it

The client should send the token in the standard HTTP Authorization header of the request. For example:

Authorization: Bearer <token-goes-here>

The name of the standard HTTP header is unfortunate because it carries authentication information, not authorization. However, it's the standard HTTP header for sending credentials to the server.

JAX-RS provides @NameBinding, a meta-annotation used to create other annotations to bind filters and interceptors to resource classes and methods. Define a @Secured annotation as following:

@NameBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Secured { }

The above defined name-binding annotation will be used to decorate a filter class, which implements ContainerRequestFilter, allowing you to intercept the request before it be handled by a resource method. The ContainerRequestContext can be used to access the HTTP request headers and then extract the token:

@Secured
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {

    private static final String REALM = "example";
    private static final String AUTHENTICATION_SCHEME = "Bearer";

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        // Get the Authorization header from the request
        String authorizationHeader =
                requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);

        // Validate the Authorization header
        if (!isTokenBasedAuthentication(authorizationHeader)) {
            abortWithUnauthorized(requestContext);
            return;
        }

        // Extract the token from the Authorization header
        String token = authorizationHeader
                            .substring(AUTHENTICATION_SCHEME.length()).trim();

        try {

            // Validate the token
            validateToken(token);

        } catch (Exception e) {
            abortWithUnauthorized(requestContext);
        }
    }

    private boolean isTokenBasedAuthentication(String authorizationHeader) {

        // Check if the Authorization header is valid
        // It must not be null and must be prefixed with "Bearer" plus a whitespace
        // The authentication scheme comparison must be case-insensitive
        return authorizationHeader != null && authorizationHeader.toLowerCase()
                    .startsWith(AUTHENTICATION_SCHEME.toLowerCase() + " ");
    }

    private void abortWithUnauthorized(ContainerRequestContext requestContext) {

        // Abort the filter chain with a 401 status code response
        // The WWW-Authenticate header is sent along with the response
        requestContext.abortWith(
                Response.status(Response.Status.UNAUTHORIZED)
                        .header(HttpHeaders.WWW_AUTHENTICATE, 
                                AUTHENTICATION_SCHEME + " realm=\"" + REALM + "\"")
                        .build());
    }

    private void validateToken(String token) throws Exception {
        // Check if the token was issued by the server and if it's not expired
        // Throw an Exception if the token is invalid
    }
}

If any problems happen during the token validation, a response with the status 401 (Unauthorized) will be returned. Otherwise the request will proceed to a resource method.

Securing your REST endpoints

To bind the authentication filter to resource methods or resource classes, annotate them with the @Secured annotation created above. For the methods and/or classes that are annotated, the filter will be executed. It means that such endpoints will only be reached if the request is performed with a valid token.

If some methods or classes do not need authentication, simply do not annotate them:

@Path("/example")
public class ExampleResource {

    @GET
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response myUnsecuredMethod(@PathParam("id") Long id) {
        // This method is not annotated with @Secured
        // The authentication filter won't be executed before invoking this method
        ...
    }

    @DELETE
    @Secured
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response mySecuredMethod(@PathParam("id") Long id) {
        // This method is annotated with @Secured
        // The authentication filter will be executed before invoking this method
        // The HTTP request must be performed with a valid token
        ...
    }
}

In the example shown above, the filter will be executed only for the mySecuredMethod(Long) method because it's annotated with @Secured.

Identifying the current user

It's very likely that you will need to know the user who is performing the request agains your REST API. The following approaches can be used to achieve it:

Overriding the security context of the current request

Within your ContainerRequestFilter.filter(ContainerRequestContext) method, a new SecurityContext instance can be set for the current request. Then override the SecurityContext.getUserPrincipal(), returning a Principal instance:

final SecurityContext currentSecurityContext = requestContext.getSecurityContext();
requestContext.setSecurityContext(new SecurityContext() {

        @Override
        public Principal getUserPrincipal() {
            return () -> username;
        }

    @Override
    public boolean isUserInRole(String role) {
        return true;
    }

    @Override
    public boolean isSecure() {
        return currentSecurityContext.isSecure();
    }

    @Override
    public String getAuthenticationScheme() {
        return AUTHENTICATION_SCHEME;
    }
});

Use the token to look up the user identifier (username), which will be the Principal's name.

Inject the SecurityContext in any JAX-RS resource class:

@Context
SecurityContext securityContext;

The same can be done in a JAX-RS resource method:

@GET
@Secured
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response myMethod(@PathParam("id") Long id, 
                         @Context SecurityContext securityContext) {
    ...
}

And then get the Principal:

Principal principal = securityContext.getUserPrincipal();
String username = principal.getName();

Using CDI (Context and Dependency Injection)

If, for some reason, you don't want to override the SecurityContext, you can use CDI (Context and Dependency Injection), which provides useful features such as events and producers.

Create a CDI qualifier:

@Qualifier
@Retention(RUNTIME)
@Target({ METHOD, FIELD, PARAMETER })
public @interface AuthenticatedUser { }

In your AuthenticationFilter created above, inject an Event annotated with @AuthenticatedUser:

@Inject
@AuthenticatedUser
Event<String> userAuthenticatedEvent;

If the authentication succeeds, fire the event passing the username as parameter (remember, the token is issued for a user and the token will be used to look up the user identifier):

userAuthenticatedEvent.fire(username);

It's very likely that there's a class that represents a user in your application. Let's call this class User.

Create a CDI bean to handle the authentication event, find a User instance with the correspondent username and assign it to the authenticatedUser producer field:

@RequestScoped
public class AuthenticatedUserProducer {

    @Produces
    @RequestScoped
    @AuthenticatedUser
    private User authenticatedUser;

    public void handleAuthenticationEvent(@Observes @AuthenticatedUser String username) {
        this.authenticatedUser = findUser(username);
    }

    private User findUser(String username) {
        // Hit the the database or a service to find a user by its username and return it
        // Return the User instance
    }
}

The authenticatedUser field produces a User instance that can be injected into container managed beans, such as JAX-RS services, CDI beans, servlets and EJBs. Use the following piece of code to inject a User instance (in fact, it's a CDI proxy):

@Inject
@AuthenticatedUser
User authenticatedUser;

Note that the CDI @Produces annotation is different from the JAX-RS @Produces annotation:

Be sure you use the CDI @Produces annotation in your AuthenticatedUserProducer bean.

The key here is the bean annotated with @RequestScoped, allowing you to share data between filters and your beans. If you don't wan't to use events, you can modify the filter to store the authenticated user in a request scoped bean and then read it from your JAX-RS resource classes.

Compared to the approach that overrides the SecurityContext, the CDI approach allows you to get the authenticated user from beans other than JAX-RS resources and providers.

Supporting role-based authorization

Please refer to my other answer for details on how to support role-based authorization.

Issuing tokens

A token can be:

  • Opaque: Reveals no details other than the value itself (like a random string)
  • Self-contained: Contains details about the token itself (like JWT).

See details below:

Random string as token

A token can be issued by generating a random string and persisting it to a database along with the user identifier and an expiration date. A good example of how to generate a random string in Java can be seen here. You also could use:

Random random = new SecureRandom();
String token = new BigInteger(130, random).toString(32);

JWT (JSON Web Token)

JWT (JSON Web Token) is a standard method for representing claims securely between two parties and is defined by the RFC 7519.

It's a self-contained token and it enables you to store details in claims. These claims are stored in the token payload which is a JSON encoded as Base64. Here are some claims registered in the RFC 7519 and what they mean (read the full RFC for further details):

  • iss: Principal that issued the token.
  • sub: Principal that is the subject of the JWT.
  • exp: Expiration date for the token.
  • nbf: Time on which the token will start to be accepted for processing.
  • iat: Time on which the token was issued.
  • jti: Unique identifier for the token.

Be aware that you must not store sensitive data, such as passwords, in the token.

The payload can be read by the client and the integrity of the token can be easily checked by verifying its signature on the server. The signature is what prevents the token from being tampered with.

You won't need to persist JWT tokens if you don't need to track them. Althought, by persisting the tokens, you will have the possibility of invalidating and revoking the access of them. To keep the track of JWT tokens, instead of persisting the whole token on the server, you could persist the token identifier (jti claim) along with some other details such as the user you issued the token for, the expiration date, etc.

When persisting tokens, always consider removing the old ones in order to prevent your database from growing indefinitely.

Using JWT

There are a few Java libraries to issue and validate JWT tokens such as:

To find some other great resources to work with JWT, have a look at http://jwt.io.

Handling token revocation with JWT

If you want to revoke tokens, you must keep the track of them. You don't need to store the whole token on server side, store only the token identifier (that must be unique) and some metadata if you need. For the token identifier you could use UUID.

The jti claim should be used to store the token identifier on the token. When validating the token, ensure that it has not been revoked by checking the value of the jti claim against the token identifiers you have on server side.

For security purposes, revoke all the tokens for a user when they change their password.

Additional information

  • It doesn't matter which type of authentication you decide to use. Always do it on the top of a HTTPS connection to prevent the man-in-the-middle attack.
  • Take a look at this question from Information Security for more information about tokens.
  • In this article you will find some useful information about token-based authentication.

jQuery UI DatePicker to show year only

In 2018,

$('#datepicker').datepicker({
    format: "yyyy",
    weekStart: 1,
    orientation: "bottom",
    language: "{{ app.request.locale }}",
    keyboardNavigation: false,
    viewMode: "years",
    minViewMode: "years"
});

Using jq to parse and display multiple fields in a json serially

This will produce an array of names

> jq '[ .users[] | (.first + " " + .last) ]' ~/test.json

[
  "Stevie Wonder",
  "Michael Jackson"
]

Editing the date formatting of x-axis tick labels in matplotlib

From the package matplotlib.dates as shown in this example the date format can be applied to the axis label and ticks for plot.

Below I have given an example for labeling axis ticks for multiplots

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd

df = pd.read_csv('US_temp.csv')
plt.plot(df['Date'],df_f['MINT'],label='Min Temp.')
plt.plot(df['Date'],df_f['MAXT'],label='Max Temp.')
plt.legend()
####### Use the below functions #######
dtFmt = mdates.DateFormatter('%b') # define the formatting
plt.gca().xaxis.set_major_formatter(dtFmt) # apply the format to the desired axis
plt.show()

As simple as that

How to force DNS refresh for a website?

you can't force refresh but you can forward all old ip requests to new one. for a website:

replace [OLD_IP] with old server's ip

replace [NEW_IP] with new server's ip

run & win.

echo "1" > /proc/sys/net/ipv4/ip_forward

iptables -t nat -A PREROUTING -d [OLD_IP] -p tcp --dport 80 -j DNAT --to-destination [NEW_IP]:80

iptables -t nat -A PREROUTING -d [OLD_IP] -p tcp --dport 443 -j DNAT --to-destination [NEW_IP]:443

iptables -t nat -A POSTROUTING -j MASQUERADE

Which Ruby version am I really running?

The ruby version 1.8.7 seems to be your system ruby.

Normally you can choose the ruby version you'd like, if you are using rvm with following. Simple change into your directory in a new terminal and type in:

rvm use 2.0.0

You can find more details about rvm here: http://rvm.io Open the website and scroll down, you will see a few helpful links. "Setting up default rubies" for example could help you.

Update: To set the ruby as default:

rvm use 2.0.0 --default

How can I send a Firebase Cloud Messaging notification without use the Firebase Console?

If you want to send push notifications from android check out my blog post

Send Push Notifications from 1 android phone to another with out server.

sending push notification is nothing but a post request to https://fcm.googleapis.com/fcm/send

code snippet using volley:

    JSONObject json = new JSONObject();
 try {
 JSONObject userData=new JSONObject();
 userData.put("title","your title");
 userData.put("body","your body");

json.put("data",userData);
json.put("to", receiverFirebaseToken);
 }
 catch (JSONException e) {
 e.printStackTrace();
 }

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("https://fcm.googleapis.com/fcm/send", json, new Response.Listener<JSONObject>() {
 @Override
 public void onResponse(JSONObject response) {

Log.i("onResponse", "" + response.toString());
 }
 }, new Response.ErrorListener() {
 @Override
 public void onErrorResponse(VolleyError error) {

}
 }) {
 @Override
 public Map<String, String> getHeaders() throws AuthFailureError {

Map<String, String> params = new HashMap<String, String>();
 params.put("Authorizationey=" + SERVER_API_KEY);
 params.put("Content-Typepplication/json");
 return params;
 }
 };
 MySingleton.getInstance(context).addToRequestQueue(jsonObjectRequest);

I suggest you all to check out my blog post for complete details.

How can I uninstall npm modules in Node.js?

I found this out the hard way, even if it is seemingly obvious.

I initially tried to loop through the node_modules directory running npm uninstall module-name with a simple for loop in a script. I found out it will not work if you call the full path, e.g.,

npm uninstall module-name

was working, but

npm uninstall /full/path/to/node_modules/module-name 

was not working.

Output ("echo") a variable to a text file

Note: The answer below is written from the perspective of Windows PowerShell.
However, it applies to the cross-platform PowerShell Core edition (v6+) as well, except that the latter - commendably - consistently defaults to BOM-less UTF-8 character encoding, which is the most widely compatible one across platforms and cultures.
.


To complement bigtv's helpful answer helpful answer with a more concise alternative and background information:

# > $file is effectively the same as | Out-File $file
# Objects are written the same way they display in the console.
# Default character encoding is UTF-16LE (mostly 2 bytes per char.), with BOM.
# Use Out-File -Encoding <name> to change the encoding.
$env:computername > $file

# Set-Content calls .ToString() on each object to output.
# Default character encoding is "ANSI" (culture-specific, single-byte).
# Use Set-Content -Encoding <name> to change the encoding.
# Use Set-Content rather than Add-Content; the latter is for *appending* to a file.
$env:computername | Set-Content $file 

When outputting to a text file, you have 2 fundamental choices that use different object representations and, in Windows PowerShell (as opposed to PowerShell Core), also employ different default character encodings:

  • Out-File (or >) / Out-File -Append (or >>):

    • Suitable for output objects of any type, because PowerShell's default output formatting is applied to the output objects.

      • In other words: you get the same output as when printing to the console.
    • The default encoding, which can be changed with the -Encoding parameter, is Unicode, which is UTF-16LE in which most characters are encoded as 2 bytes. The advantage of a Unicode encoding such as UTF-16LE is that it is a global alphabet, capable of encoding all characters from all human languages.

      • In PSv5.1+, you can change the encoding used by > and >>, via the $PSDefaultParameterValues preference variable, taking advantage of the fact that > and >> are now effectively aliases of Out-File and Out-File -Append. To change to UTF-8, for instance, use:
        $PSDefaultParameterValues['Out-File:Encoding']='UTF8'
  • Set-Content / Add-Content:

    • For writing strings and instances of types known to have meaningful string representations, such as the .NET primitive data types (Booleans, integers, ...).

      • .psobject.ToString() method is called on each output object, which results in meaningless representations for types that don't explicitly implement a meaningful representation; [hashtable] instances are an example:
        @{ one = 1 } | Set-Content t.txt writes literal System.Collections.Hashtable to t.txt, which is the result of @{ one = 1 }.ToString().
    • The default encoding, which can be changed with the -Encoding parameter, is Default, which is the system's "ANSI" code page, a the single-byte culture-specific legacy encoding for non-Unicode applications, most commonly Windows-1252.
      Note that the documentation currently incorrectly claims that ASCII is the default encoding.

    • Note that Add-Content's purpose is to append content to an existing file, and it is only equivalent to Set-Content if the target file doesn't exist yet.
      Furthermore, the default or specified encoding is blindly applied, irrespective of the file's existing contents' encoding.

Out-File / > / Set-Content / Add-Content all act culture-sensitively, i.e., they produce representations suitable for the current culture (locale), if available (though custom formatting data is free to define its own, culture-invariant representation - see Get-Help about_format.ps1xml). This contrasts with PowerShell's string expansion (string interpolation in double-quoted strings), which is culture-invariant - see this answer of mine.

As for performance: Since Set-Content doesn't have to apply default formatting to its input, it performs better.


As for the OP's symptom with Add-Content:

Since $env:COMPUTERNAME cannot contain non-ASCII characters, Add-Content's output, using "ANSI" encoding, should not result in ? characters in the output, and the likeliest explanation is that the ? were part of the preexisting content in output file $file, which Add-Content appended to.

SSRS Conditional Formatting Switch or IIF

To dynamically change the color of a text box goto properties, goto font/Color and set the following expression

=SWITCH(Fields!CurrentRiskLevel.Value = "Low", "Green",
Fields!CurrentRiskLevel.Value = "Moderate", "Blue",
Fields!CurrentRiskLevel.Value = "Medium", "Yellow",
Fields!CurrentRiskLevel.Value = "High", "Orange",
Fields!CurrentRiskLevel.Value = "Very High", "Red"
)

Same way for tolerance

=SWITCH(Fields!Tolerance.Value = "Low", "Red",
Fields!Tolerance.Value = "Moderate", "Orange",
Fields!Tolerance.Value = "Medium", "Yellow",
Fields!Tolerance.Value = "High", "Blue",
Fields!Tolerance.Value = "Very High", "Green")

Adding Multiple Values in ArrayList at a single index

@Ahamed has a point, but if you're insisting on using lists so you can have three arraylist like this:

ArrayList<Integer> first = new ArrayList<Integer>(Arrays.AsList(100,100,100,100,100));
ArrayList<Integer> second = new ArrayList<Integer>(Arrays.AsList(50,35,25,45,65));
ArrayList<Integer> third = new ArrayList<Integer>();

for(int i = 0; i < first.size(); i++) {
      third.add(first.get(i));
      third.add(second.get(i));
}

Edit: If you have those values on your list that below:

List<double[]> values = new ArrayList<double[]>(2);

what you want to do is combine them, right? You can try something like this: (I assume that both array are same sized, otherwise you need to use two for statement)

ArrayList<Double> yourArray = new ArrayList<Double>();
for(int i = 0; i < values.get(0).length; i++) {
    yourArray.add(values.get(0)[i]);
    yourArray.add(values.get(1)[i]);
}

How to access iOS simulator camera

Simulator doesn't have a Camera. If you want to access a camera you need a device. You can't test camera on simulator. You can only check the photo and video gallery.

Binding a list in @RequestParam

One way you could accomplish this (in a hackish way) is to create a wrapper class for the List. Like this:

class ListWrapper {
     List<String> myList; 
     // getters and setters
}

Then your controller method signature would look like this:

public String controllerMethod(ListWrapper wrapper) {
    ....
}

No need to use the @RequestParam or @ModelAttribute annotation if the collection name you pass in the request matches the collection field name of the wrapper class, in my example your request parameters should look like this:

myList[0]     : 'myValue1'
myList[1]     : 'myValue2'
myList[2]     : 'myValue3'
otherParam    : 'otherValue'
anotherParam  : 'anotherValue'

How to gzip all files in all sub-directories into one compressed file in bash

there are lots of compression methods that work recursively command line and its good to know who the end audience is.

i.e. if it is to be sent to someone running windows then zip would probably be best:

zip -r file.zip folder_to_zip

unzip filenname.zip

for other linux users or your self tar is great

tar -cvzf filename.tar.gz folder

tar -cvjf filename.tar.bz2 folder  # even more compression

#change the -c to -x to above to extract

One must be careful with tar and how things are tarred up/extracted, for example if I run

cd ~
tar -cvzf passwd.tar.gz /etc/passwd
tar: Removing leading `/' from member names
/etc/passwd


pwd

/home/myusername

tar -xvzf passwd.tar.gz

this will create /home/myusername/etc/passwd

unsure if all versions of tar do this:

 Removing leading `/' from member names

How to stop C# console applications from closing automatically?

Console.ReadLine() to wait for the user to Enter or Console.ReadKey to wait for any key.

How to link to apps on the app store

Try this way

http://itunes.apple.com/lookup?id="your app ID here" return json.From this, find key "trackViewUrl" and value is the desired url. use this url(just replace https:// with itms-apps://).This works just fine.

For example if your app ID is xyz then go to this link http://itunes.apple.com/lookup?id=xyz

Then find the url for key "trackViewUrl".This is the url for your app in app store and to use this url in xcode try this

NSString *iTunesLink = @"itms-apps://itunes.apple.com/us/app/Your app name/id Your app ID?mt=8&uo=4";
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:iTunesLink]];

Thanks

How to perform a fade animation on Activity transition?

you can also add animation in your activity, in onCreate method like below becasue overridePendingTransition is not working with some mobile, or it depends on device settings...

View view = findViewById(android.R.id.content);
Animation mLoadAnimation = AnimationUtils.loadAnimation(getApplicationContext(), android.R.anim.fade_in);
mLoadAnimation.setDuration(2000);
view.startAnimation(mLoadAnimation);

@ variables in Ruby on Rails

Use @title in your controllers when you want your variable to be available in your views.

The explanation is that @title is an instance variable while title is a local variable. Rails makes instance variables from controllers available to views because the template code (erb, haml, etc) is executed within the scope of the current controller instance.