Programs & Examples On #Sha

SHA (Secure Hash Algorithm) is a family of digest algorithms (i.e. cryptographic hashes), i.e. checksum functions that are hard to forge. The recommended digest algorithms these days are SHA-1 and SHA-2 (which covers both SHA-256 and SHA-512). MD5 is a deprecated alternative.

Is it possible to decrypt SHA1

SHA1 is a cryptographic hash function, so the intention of the design was to avoid what you are trying to do.

However, breaking a SHA1 hash is technically possible. You can do so by just trying to guess what was hashed. This brute-force approach is of course not efficient, but that's pretty much the only way.

So to answer your question: yes, it is possible, but you need significant computing power. Some researchers estimate that it costs $70k - $120k.

As far as we can tell today, there is also no other way but to guess the hashed input. This is because operations such as mod eliminate information from your input. Suppose you calculate mod 5 and you get 0. What was the input? Was it 0, 5 or 500? You see, you can't really 'go back' in this case.

php mysqli_connect: authentication method unknown to the client [caching_sha2_password]

I think it is not useful to configure the mysql server without caching_sha2_password encryption, we have to find a way to publish, send or obtain secure information through the network. As you see in the code below I dont use variable $db_name, and Im using a user in mysql server with standar configuration password. Just create a Standar user password and config all privilages. it works, but how i said without segurity.

<?php
$db_name="db";
$mysql_username="root";
$mysql_password="****";
$server_name="localhost";
$conn=mysqli_connect($server_name,$mysql_username,$mysql_password);

if ($conn) {
    echo "connetion success";
}
else{
    echo mysqli_error($conn);
}

?>

How long to brute force a salted SHA-512 hash? (salt provided)

I want to know the time to brute force for when the password is a dictionary word and also when it is not a dictionary word.

Dictionary password

Ballpark figure: there are about 1,000,000 English words, and if a hacker can compute about 10,000 SHA-512 hashes a second (update: see comment by CodesInChaos, this estimate is very low), 1,000,000 / 10,000 = 100 seconds. So it would take just over a minute to crack a single-word dictionary password for a single user. If the user concatenates two dictionary words, you're in the area of a few days, but still very possible if the attacker is cares enough. More than that and it starts getting tough.

Random password

If the password is a truly random sequence of alpha-numeric characters, upper and lower case, then the number of possible passwords of length N is 60^N (there are 60 possible characters). We'll do the calculation the other direction this time; we'll ask: What length of password could we crack given a specific length of time? Just use this formula:

N = Log60(t * 10,000) where t is the time spent calculating hashes in seconds (again assuming 10,000 hashes a second).

1 minute:    3.2
5 minute:    3.6
30 minutes:  4.1
2 hours:     4.4
3 days:      5.2

So given a 3 days we'd be able to crack the password if it's 5 characters long.

This is all very ball-park, but you get the idea. Update: see comment below, it's actually possible to crack much longer passwords than this.

What's going on here?

Let's clear up some misconceptions:

  • The salt doesn't make it slower to calculate hashes, it just means they have to crack each user's password individually, and pre-computed hash tables (buzz-word: rainbow tables) are made completely useless. If you don't have a precomputed hash-table, and you're only cracking one password hash, salting doesn't make any difference.

  • SHA-512 isn't designed to be hard to brute-force. Better hashing algorithms like BCrypt, PBKDF2 or SCrypt can be configured to take much longer to compute, and an average computer might only be able to compute 10-20 hashes a second. Read This excellent answer about password hashing if you haven't already.

  • update: As written in the comment by CodesInChaos, even high entropy passwords (around 10 characters) could be bruteforced if using the right hardware to calculate SHA-512 hashes.


Notes on accepted answer:

The accepted answer as of September 2014 is incorrect and dangerously wrong:

In your case, breaking the hash algorithm is equivalent to finding a collision in the hash algorithm. That means you don't need to find the password itself (which would be a preimage attack)... Finding a collision using a birthday attack takes O(2^n/2) time, where n is the output length of the hash function in bits.

The birthday attack is completely irrelevant to cracking a given hash. And this is in fact a perfect example of a preimage attack. That formula and the next couple of paragraphs result in dangerously high and completely meaningless values for an attack time. As demonstrated above it's perfectly possible to crack salted dictionary passwords in minutes.

The low entropy of typical passwords makes it possible that there is a relatively high chance of one of your users using a password from a relatively small database of common passwords...

That's why generally hashing and salting alone is not enough, you need to install other safety mechanisms as well. You should use an artificially slowed down entropy-enducing method such as PBKDF2 described in PKCS#5...

Yes, please use an algorithm that is slow to compute, but what is "entropy-enducing"? Putting a low entropy password through a hash doesn't increase entropy. It should preserve entropy, but you can't make a rubbish password better with a hash, it doesn't work like that. A weak password put through PBKDF2 is still a weak password.

How to get current date in 'YYYY-MM-DD' format in ASP.NET?

Which WebControl are you using? Did you try?

DateTime.Now.ToString("yyyy-MM-dd");

org.springframework.beans.factory.BeanCreationException: Error creating bean with name

you need to add jar file in your build path..

commons-dbcp-1.1-RC2.jar

or any version of that..!!!!

ADDED : also make sure you have commons-pool-1.1.jar too in your build path.

ADDED: sorry saw complete list of jar late... may be version clashes might be there.. better check out..!!! just an assumption.

Using $state methods with $stateChangeStart toState and fromState in Angular ui-router

Suggestion 1

When you add an object to $stateProvider.state that object is then passed with the state. So you can add additional properties which you can read later on when needed.

Example route configuration

$stateProvider
.state('public', {
    abstract: true,
    module: 'public'
})
.state('public.login', {
    url: '/login',
    module: 'public'
})
.state('tool', {
    abstract: true,
    module: 'private'
})
.state('tool.suggestions', {
    url: '/suggestions',
    module: 'private'
});

The $stateChangeStart event gives you acces to the toState and fromState objects. These state objects will contain the configuration properties.

Example check for the custom module property

$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
    if (toState.module === 'private' && !$cookies.Session) {
        // If logged out and transitioning to a logged in page:
        e.preventDefault();
        $state.go('public.login');
    } else if (toState.module === 'public' && $cookies.Session) {
        // If logged in and transitioning to a logged out page:
        e.preventDefault();
        $state.go('tool.suggestions');
    };
});

I didn't change the logic of the cookies because I think that is out of scope for your question.

Suggestion 2

You can create a Helper to get you this to work more modular.

Value publicStates

myApp.value('publicStates', function(){
    return {
      module: 'public',
      routes: [{
        name: 'login', 
        config: { 
          url: '/login'
        }
      }]
    };
});

Value privateStates

myApp.value('privateStates', function(){
    return {
      module: 'private',
      routes: [{
        name: 'suggestions', 
        config: { 
          url: '/suggestions'
        }
      }]
    };
});

The Helper

myApp.provider('stateshelperConfig', function () {
  this.config = {
    // These are the properties we need to set
    // $stateProvider: undefined
    process: function (stateConfigs){
      var module = stateConfigs.module;
      $stateProvider = this.$stateProvider;
      $stateProvider.state(module, {
        abstract: true,
        module: module
      });
      angular.forEach(stateConfigs, function (route){
        route.config.module = module;
        $stateProvider.state(module + route.name, route.config);
      });
    }
  };

  this.$get = function () {
    return {
      config: this.config
    };
  };
});

Now you can use the helper to add the state configuration to your state configuration.

myApp.config(['$stateProvider', '$urlRouterProvider', 
    'stateshelperConfigProvider', 'publicStates', 'privateStates',
  function ($stateProvider, $urlRouterProvider, helper, publicStates, privateStates) {
    helper.config.$stateProvider = $stateProvider;
    helper.process(publicStates);
    helper.process(privateStates);
}]);

This way you can abstract the repeated code, and come up with a more modular solution.

Note: the code above isn't tested

What's the equivalent of Java's Thread.sleep() in JavaScript?

setTimeout would not hold and resume on your own thread however Thread.sleep does. There is no actual equal in Javascript

Can you write virtual functions / methods in Java?

Yes, you can write virtual "functions" in Java.

Chrome: Uncaught SyntaxError: Unexpected end of input

This particular error is one annoying fact about . In most cases your JavaScript is broken in some way. For example missing a } or something like that.

Example given, this will yield "Unexpected end of input" too:

eval('[{"test": 4}') // notice the missing ]

But the root cause of the problems seems to be that the requested JSON url has a Content-Type of text/html which Chrome apparently tries to parse as HTML, which then results in the unexpected end of input due to the fact that the included image tags are being parsed.

Try setting the Content-Type to text/plain I think it should fix the issues.

Nonetheless, V8 could do a better Job about telling one exactly where the input ended unexpectedly.

How to create custom button in Android using XML Styles

Copy-pasted from a recipe written by "Adrián Santalla" on androidcookbook.com: https://www.androidcookbook.com/Recipe.seam?recipeId=3307

1. Create an XML file that represents the button states

Create an xml into drawable called 'button.xml' to name the button states:

<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_enabled="false"
        android:drawable="@drawable/button_disabled" />
    <item
        android:state_pressed="true"
        android:state_enabled="true"
        android:drawable="@drawable/button_pressed" />
    <item
        android:state_focused="true"
        android:state_enabled="true"
        android:drawable="@drawable/button_focused" />
    <item
        android:state_enabled="true"
        android:drawable="@drawable/button_enabled" />
</selector>

2. Create an XML file that represents each button state

Create one xml file for each of the four button states. All of them should be under drawables folder. Let's follow the names set in the button.xml file.

button_enabled.xml:

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <gradient
        android:startColor="#00CCFF"
        android:centerColor="#0000CC"
        android:endColor="#00CCFF"
        android:angle="90"/>
    <padding android:left="7dp"
        android:top="7dp"
        android:right="7dp"
        android:bottom="7dp" />
    <stroke
        android:width="2dip"
        android:color="#FFFFFF" />
    <corners android:radius= "8dp" />
</shape>

button_focused.xml:

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <gradient
        android:startColor="#F7D358"
        android:centerColor="#DF7401"
        android:endColor="#F7D358"
        android:angle="90"/>
    <padding android:left="7dp"
        android:top="7dp"
        android:right="7dp"
        android:bottom="7dp" />
    <stroke
        android:width="2dip"
        android:color="#FFFFFF" />
    <corners android:radius= "8dp" />
</shape>

button_pressed.xml:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <gradient
        android:startColor="#0000CC"
        android:centerColor="#00CCFF"
        android:endColor="#0000CC"
        android:angle="90"/>
    <padding android:left="7dp"
        android:top="7dp"
        android:right="7dp"
        android:bottom="7dp" />
    <stroke
        android:width="2dip"
        android:color="#FFFFFF" />
    <corners android:radius= "8dp" />
</shape>

button_disabled.xml:

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <gradient
        android:startColor="#F2F2F2"
        android:centerColor="#A4A4A4"
        android:endColor="#F2F2F2"
        android:angle="90"/>
    <padding android:left="7dp"
        android:top="7dp"
        android:right="7dp"
        android:bottom="7dp" />
    <stroke
        android:width="2dip"
        android:color="#FFFFFF" />
    <corners android:radius= "8dp" />
</shape>

3. Create an XML file that represents the button style

Once you have created the files mentioned above, it's time to create your application button style. Now, you need to create a new XML file, called styles.xml (if you don't have it yet) where you can include more custom styles, into de values directory.

This file will contain the new button style of your application. You need to set your new button style features in it. Note that one of those features, the background of your new style, should be set with a reference to the button (button.xml) drawable that was created in the first step. To refer to the new button style we use the name attribute.

The example below show the content of the styles.xml file:

<resources>
    <style name="button" parent="@android:style/Widget.Button">
        <item name="android:gravity">center_vertical|center_horizontal</item>
        <item name="android:textColor">#FFFFFFFF</item>
        <item name="android:shadowColor">#FF000000</item>
        <item name="android:shadowDx">0</item>
        <item name="android:shadowDy">-1</item>
        <item name="android:shadowRadius">0.2</item>
        <item name="android:textSize">16dip</item>
        <item name="android:textStyle">bold</item>
        <item name="android:background">@drawable/button</item>
        <item name="android:focusable">true</item>
        <item name="android:clickable">true</item>
    </style>
</resources>

4. Create an XML with your own custom application theme

Finally, you need to override the default Android button style. For that, you need to create a new XML file, called themes.xml (if you don't have it yet), into the values directory and override the default Android button style.

The example below show the content of the themes.xml:

<resources>
    <style name="YourApplicationTheme" parent="android:style/Theme.NoTitleBar">
        <item name="android:buttonStyle">@style/button</item>
    </style>
</resources>

Hope you guys can have the same luck as I had with this, when I was looking for custom buttons. Enjoy.

Handling InterruptedException in Java

I would say in some cases it's ok to do nothing. Probably not something you should be doing by default, but in case there should be no way for the interrupt to happen, I'm not sure what else to do (probably logging error, but that does not affect program flow).

One case would be in case you have a task (blocking) queue. In case you have a daemon Thread handling these tasks and you do not interrupt the Thread by yourself (to my knowledge the jvm does not interrupt daemon threads on jvm shutdown), I see no way for the interrupt to happen, and therefore it could be just ignored. (I do know that a daemon thread may be killed by the jvm at any time and therefore are unsuitable in some cases).

EDIT: Another case might be guarded blocks, at least based on Oracle's tutorial at: http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html

Cast Object to Generic Type for returning

I stumble upon this question and it grabbed my interest. The accepted answer is completely correct, but I thought I do provide my findings at JVM byte code level to explain why the OP encounter the ClassCastException.

I have the code which is pretty much the same as OP's code:

public static <T> T convertInstanceOfObject(Object o) {
    try {
       return (T) o;
    } catch (ClassCastException e) {
        return null;
    }
}

public static void main(String[] args) {
    String k = convertInstanceOfObject(345435.34);
    System.out.println(k);
}

and the corresponding byte code is:

public static <T> T convertInstanceOfObject(java.lang.Object);
    Code:
       0: aload_0
       1: areturn
       2: astore_1
       3: aconst_null
       4: areturn
    Exception table:
       from    to  target type
           0     1     2   Class java/lang/ClassCastException

  public static void main(java.lang.String[]);
    Code:
       0: ldc2_w        #3                  // double 345435.34d
       3: invokestatic  #5                  // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
       6: invokestatic  #6                  // Method convertInstanceOfObject:(Ljava/lang/Object;)Ljava/lang/Object;
       9: checkcast     #7                  // class java/lang/String
      12: astore_1
      13: getstatic     #8                  // Field java/lang/System.out:Ljava/io/PrintStream;
      16: aload_1
      17: invokevirtual #9                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      20: return

Notice that checkcast byte code instruction happens in the main method not the convertInstanceOfObject and convertInstanceOfObject method does not have any instruction that can throw ClassCastException. Because the main method does not catch the ClassCastException hence when you execute the main method you will get a ClassCastException and not the expectation of printing null.

Now I modify the code to the accepted answer:

public static <T> T convertInstanceOfObject(Object o, Class<T> clazz) {
        try {
            return clazz.cast(o);
        } catch (ClassCastException e) {
            return null;
        }
    }
    public static void main(String[] args) {
        String k = convertInstanceOfObject(345435.34, String.class);
        System.out.println(k);
    }

The corresponding byte code is:

public static <T> T convertInstanceOfObject(java.lang.Object, java.lang.Class<T>);
    Code:
       0: aload_1
       1: aload_0
       2: invokevirtual #2                  // Method java/lang/Class.cast:(Ljava/lang/Object;)Ljava/lang/Object;
       5: areturn
       6: astore_2
       7: aconst_null
       8: areturn
    Exception table:
       from    to  target type
           0     5     6   Class java/lang/ClassCastException

  public static void main(java.lang.String[]);
    Code:
       0: ldc2_w        #4                  // double 345435.34d
       3: invokestatic  #6                  // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
       6: ldc           #7                  // class java/lang/String
       8: invokestatic  #8                  // Method convertInstanceOfObject:(Ljava/lang/Object;Ljava/lang/Class;)Ljava/lang/Object;
      11: checkcast     #7                  // class java/lang/String
      14: astore_1
      15: getstatic     #9                  // Field java/lang/System.out:Ljava/io/PrintStream;
      18: aload_1
      19: invokevirtual #10                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      22: return

Notice that there is an invokevirtual instruction in the convertInstanceOfObject method that calls Class.cast() method which throws ClassCastException which will be catch by the catch(ClassCastException e) bock and return null; hence, "null" is printed to console without any exception.

How do I check out a specific version of a submodule using 'git submodule'?

Step 1: Add the submodule

   git submodule add git://some_repository.git some_repository

Step 2: Fix the submodule to a particular commit

By default the new submodule will be tracking HEAD of the master branch, but it will NOT be updated as you update your primary repository. In order to change the submodule to track a particular commit or different branch, change directory to the submodule folder and switch branches just like you would in a normal repository.

   git checkout -b some_branch origin/some_branch

Now the submodule is fixed on the development branch instead of HEAD of master.

From Two Guys Arguing — Tie Git Submodules to a Particular Commit or Branch .

Object does not support item assignment error

The error seems clear: model objects do not support item assignment. MyModel.objects.latest('id')['foo'] = 'bar' will throw this same error.

It's a little confusing that your model instance is called projectForm...

To reproduce your first block of code in a loop, you need to use setattr

for k,v in session_results.iteritems():
    setattr(projectForm, k, v)

Java Byte Array to String to Byte Array

String coolString = "cool string";

byte[] byteArray = coolString.getBytes();

String reconstitutedString = new String(byteArray);

System.out.println(reconstitutedString);

That outputs "cool string" to the console.

It's pretty darn easy.

How do I show running processes in Oracle DB?

I suspect you would just want to grab a few columns from V$SESSION and the SQL statement from V$SQL. Assuming you want to exclude the background processes that Oracle itself is running

SELECT sess.process, sess.status, sess.username, sess.schemaname, sql.sql_text
  FROM v$session sess,
       v$sql     sql
 WHERE sql.sql_id(+) = sess.sql_id
   AND sess.type     = 'USER'

The outer join is to handle those sessions that aren't currently active, assuming you want those. You could also get the sql_fulltext column from V$SQL which will have the full SQL statement rather than the first 1000 characters, but that is a CLOB and so likely a bit more complicated to deal with.

Realistically, you probably want to look at everything that is available in V$SESSION because it's likely that you can get a lot more information than SP_WHO provides.

Set folder for classpath

Use the command as

java -classpath ".;C:\MyLibs\a\*;D:\MyLibs\b\*" <your-class-name>

The above command will set the mentioned paths to classpath only once for executing the class named TestClass.

If you want to execute more then one classes, then you can follow this

set classpath=".;C:\MyLibs\a\*;D:\MyLibs\b\*"

After this you can execute as many classes as you want just by simply typing

java <your-class-name>

The above command will work till you close the command prompt. But after closing the command prompt, if you will reopen the command prompt and try to execute some classes, then you have to again set the classpath with the help of any of the above two mentioned methods.(First method for executing one class and second one for executing more classes)

If you want to set the classpth only once so that it could work for everytime, then do as follows

1. Right click on "My Computer" icon
2. Go to the "properties"
3. Go to the "Advanced System Settings" or "Advance Settings"
4. Go to the "Environment Variable"
5. Create a new variable at the user variable by giving the information as below
    a.  Variable Name-     classpath
    b.  Variable Value-    .;C:\program files\jdk 1.6.0\bin;C:\MyLibs\a\';C:\MyLibs\b\*
6.Apply this and you are done.

Remember this will work every time. You don't need to explicitly set the classpath again and again.

NOTE: If you want to add some other libs after some day, then don't forget to add a semi-colon at the end of the "variable-value" of the "Environment Variable" and then type the path of your new libs after the semi-colon. Because semi-colon separates the paths of different directories.

Hope this will help you.

Error: "The sandbox is not in sync with the Podfile.lock..." after installing RestKit with cocoapods

If you download the project from github or copy from other place, then the dependencies library do not exists, there will be this issue.

You just need to cd to the project/project_name directory in terminal , use ls to check whether there is a Podfile file.

if there exists the Podfile, you just need to install the dependencyies:

pod install

How do I create a user account for basic authentication?

I know this is a really old question but I wanted to add a bit of explanation that I discovered the hard way (this is n00b information).

"Basic Authentication" shares the same accounts that you have on your local computer or network. If you leave the domain and realm empty, local accounts are what are actually being used. So to add a new account you follow the exact process you would for adding a normal new user account to your local computer (as answered by JoshM or shown here). If you enter a domain and realm you can create network accounts in your local active directory and these are what will be used to log the user in and out.

Because it has been around for so long, basic authentication is generally compatible with any browser/system out there but it does have to major flaws:

  • user and password are sent in the clear (except over SSL)
  • you need to have a user account for each user or client

For more information about basic authentication or user accounts see the following MSDN page.

How to convert nanoseconds to seconds using the TimeUnit enum?

In Java 8 or Kotlin, I use Duration.ofNanos(1_000_000_000) like

val duration = Duration.ofNanos(1_000_000_000)
logger.info(String.format("%d %02dm %02ds %03d",
                elapse, duration.toMinutes(), duration.toSeconds(), duration.toMillis()))

Read more https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html

How to change the default encoding to UTF-8 for Apache?

Place AddDefaultCharset UTF-8 into /etc/apache2/conf.d/charset. In fact, it's already there. You just have to uncomment it by removing the preceding #.

Sum values from an array of key-value pairs in JavaScript

Creating a sum method would work nicely, e.g. you could add the sum function to Array

Array.prototype.sum = function(selector) {
    if (typeof selector !== 'function') {
        selector = function(item) {
            return item;
        }
    }
    var sum = 0;
    for (var i = 0; i < this.length; i++) {
        sum += parseFloat(selector(this[i]));
    }
    return sum;
};

then you could do

> [1,2,3].sum()
6

and in your case

> myData.sum(function(item) { return item[1]; });
23

Edit: Extending the builtins can be frowned upon because if everyone did it we would get things unexpectedly overriding each other (namespace collisions). you could add the sum function to some module and accept an array as an argument if you like. that could mean changing the signature to myModule.sum = function(arr, selector) { then this would become arr

Get $_POST from multiple checkboxes

It's pretty simple. Pay attention and you'll get it right away! :)

You will create a html array, which will be then sent to php array. Your html code will look like this:

<input type="checkbox" name="check_list[1]" alt="Checkbox" value="checked">
<input type="checkbox" name="check_list[2]" alt="Checkbox" value="checked">
<input type="checkbox" name="check_list[3]" alt="Checkbox" value="checked">

Where [1] [2] [3] are the IDs of your messages, meaning that you will echo your $row['Report ID'] in their place.

Then, when you submit the form, your PHP array will look like this:

print_r($check_list)

[1] => checked [3] => checked

Depending on which were checked and which were not.

I'm sure you can continue from this point forward.

Bootstrap 3.0 Popovers and tooltips

If you're using Rails and ActiveAdmin, this is going to be your problem: https://github.com/seyhunak/twitter-bootstrap-rails/issues/450 Basically, a conflict with active_admin.js

This is the solution: https://stackoverflow.com/a/11745446/264084 (Karen's answer) tldr: Move active_admin assets into the "vendor" directory.

Android Stop Emulator from Command Line

FOR MAC:

  1. Run:
ps -ax | grep emulator 

which gives you a wider result something like:

 6617 ??         9:05.54 /Users/nav/Library/Android/sdk/emulator/qemu/darwin-x86_64/qemu-system-x86_64 -netdelay none -netspeed full -avd Nexus_One_API_29
 6619 ??         0:06.10 /Users/nav/Library/Android/sdk/emulator/emulator64-crash-service -pipe com.google.AndroidEmulator.CrashService.6617 -ppid 6617 -data-dir /tmp/android-nav/
 6658 ??         0:07.93 /Users/nav/Library/Android/sdk/emulator/lib64/qt/libexec/QtWebEngineProcess --type=renderer --disable-accelerated-video-decode --disable-gpu-memory-buffer-video-frames --disable-pepper-3d-image-chromium --enable-threaded-compositing --file-url-path-alias=/gen=/Users/nav/Library/Android/sdk/emulator/lib64/qt/libexec/gen --enable-features=AllowContentInitiatedDataUrlNavigations --disable-features=MacV2Sandbox,MojoVideoCapture,SurfaceSynchronization,UseVideoCaptureApiForDevToolsSnapshots --disable-gpu-compositing --service-pipe-token=15570406721898250245 --lang=en-US --webengine-schemes=qrc:sLV --num-raster-threads=4 --enable-main-frame-before-activation --service-request-channel-token=15570406721898250245 --renderer-client-id=2
 6659 ??         0:01.11 /Users/nav/Library/Android/sdk/emulator/lib64/qt/libexec/QtWebEngineProcess --type=renderer --disable-accelerated-video-decode --disable-gpu-memory-buffer-video-frames --disable-pepper-3d-image-chromium --enable-threaded-compositing --file-url-path-alias=/gen=/Users/nav/Library/Android/sdk/emulator/lib64/qt/libexec/gen --enable-features=AllowContentInitiatedDataUrlNavigations --disable-features=MacV2Sandbox,MojoVideoCapture,SurfaceSynchronization,UseVideoCaptureApiForDevToolsSnapshots --disable-gpu-compositing --service-pipe-token=--lang=en-US --webengine-schemes=qrc:sLV --num-raster-threads=4 --enable-main-frame-before-activation --service-request-channel-token=  --renderer-client-id=3
10030 ttys000    0:00.00 grep emulator
  1. The first (left) column is the process ID (PID) that you are looking for.

  2. Find the first PID (in the above example, it's 6617).

  3. Force kill that process:

kill -9 PID

In my case, the command is:

kill -9 6617
  1. Usually, killing the first process in enough to stop the emulator, but if that doesn't work, try killing other processes as well.

Detect WebBrowser complete page loading

Note the url in DocumentCompleted can be different than navigating url due to server transfer or url normalization (e.g. you navigate to www.microsoft.com and got http://www.microsoft.com in documentcomplete)

In pages with no frames, this event fires one time after loading is complete. In pages with multiple frames, this event fires for each navigating frame (note navigation is supported inside a frame, for instance clicking a link in a frame could navigate the frame to another page). The highest level navigating frame, which may or may not be the top level browser, fires the final DocumentComplete event.

In native code you would compare the sender of the DocumentComplete event to determine if the event is the final event in the navigation or not. However in Windows Forms the sender parameter is not wrapped by WebBrowserDocumentCompletedEventArgs. You can either sink the native event to get the parameter's value, or check the readystate property of the browser or frame documents in the DocumentCompleted event handler to see if all frames are in the ready state.

There is a prolblem with the readystate method as if a download manager is present and the navigation is to a downloadable file, the navigation could be cancelled by the download manager and the readystate won't become complete.

The controller for path was not found or does not implement IController

I've found it.

When a page, that is located inside an area, wants to access a controller that is located outside of this area (such as a shared layout page or a certain page inside a different area), the area of this controller needs to be added. Since the common controller is not in a specific area but part of the main project, you have to leave area empty:

@Html.Action("MenuItems", "Common", new {area="" }) 

The above needs to be added to all of the actions and actionlinks since the layout page is shared throughout the various areas.

It's exactly the same problem as here: ASP.NET MVC Areas with shared layout

Edit: To be clear, this is marked as the answer because it was the answer for my problem. The above answers might solve the causes that trigger the same error.

Get the current year in JavaScript

Create a new Date() object and call getFullYear():

new Date().getFullYear()
// returns the current year

Hijacking the accepted answer to provide some basic example context like a footer that always shows the current year:

<footer>
    &copy; <span id="year"></span>
</footer>

Somewhere else executed after the HTML above has been loaded:

<script>
    document.getElementById("year").innerHTML = new Date().getFullYear();
</script>

_x000D_
_x000D_
document.getElementById("year").innerHTML = new Date().getFullYear();
_x000D_
footer {_x000D_
  text-align: center;_x000D_
  font-family: sans-serif;_x000D_
}
_x000D_
<footer>_x000D_
    &copy; <span id="year">2018</span> by FooBar_x000D_
</footer>
_x000D_
_x000D_
_x000D_

Playing m3u8 Files with HTML Video Tag

You can use video js library for easily play HLS video's. It allows to directly play videos

<!-- CSS  -->
 <link href="https://vjs.zencdn.net/7.2.3/video-js.css" rel="stylesheet">


<!-- HTML -->
<video id='hls-example'  class="video-js vjs-default-skin" width="400" height="300" controls>
<source type="application/x-mpegURL" src="http://www.streambox.fr/playlists/test_001/stream.m3u8">
</video>


<!-- JS code -->
<!-- If you'd like to support IE8 (for Video.js versions prior to v7) -->
<script src="https://vjs.zencdn.net/ie8/ie8-version/videojs-ie8.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/videojs-contrib-hls/5.14.1/videojs-contrib-hls.js"></script>
<script src="https://vjs.zencdn.net/7.2.3/video.js"></script>

<script>
var player = videojs('hls-example');
player.play();
</script>

GitHub Video Js

UL or DIV vertical scrollbar

Sometimes it is not eligible to set height to pixel values. However, it is possible to show vertical scrollbar through setting height of div to 100% and overflow to auto.

Let me show an example:

<div id="content" style="height: 100%; overflow: auto">
  <p>some text</p>
  <ul>
    <li>text</li>
    .....
    <li>text</li>
</div>

How to avoid the "divide by zero" error in SQL?

EDIT: I'm getting a lot of downvotes on this recently...so I thought I'd just add a note that this answer was written before the question underwent it's most recent edit, where returning null was highlighted as an option...which seems very acceptable. Some of my answer was addressed to concerns like that of Edwardo, in the comments, who seemed to be advocating returning a 0. This is the case I was railing against.

ANSWER: I think there's an underlying issue here, which is that division by 0 is not legal. It's an indication that something is fundementally wrong. If you're dividing by zero, you're trying to do something that doesn't make sense mathematically, so no numeric answer you can get will be valid. (Use of null in this case is reasonable, as it is not a value that will be used in later mathematical calculations).

So Edwardo asks in the comments "what if the user puts in a 0?", and he advocates that it should be okay to get a 0 in return. If the user puts zero in the amount, and you want 0 returned when they do that, then you should put in code at the business rules level to catch that value and return 0...not have some special case where division by 0 = 0.

That's a subtle difference, but it's important...because the next time someone calls your function and expects it to do the right thing, and it does something funky that isn't mathematically correct, but just handles the particular edge case it's got a good chance of biting someone later. You're not really dividing by 0...you're just returning an bad answer to a bad question.

Imagine I'm coding something, and I screw it up. I should be reading in a radiation measurement scaling value, but in a strange edge case I didn't anticipate, I read in 0. I then drop my value into your function...you return me a 0! Hurray, no radiation! Except it's really there and it's just that I was passing in a bad value...but I have no idea. I want division to throw the error because it's the flag that something is wrong.

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

You need to specify the primary key as auto-increment

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

With regards to comment below, how about:

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

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

How do I capture the output into a variable from an external process in PowerShell?

If all you are trying to do is capture the output from a command, then this will work well.

I use it for changing system time, as [timezoneinfo]::local always produces the same information, even after you have made changes to the system. This is the only way I can validate and log the change in time zone:

$NewTime = (powershell.exe -command [timezoneinfo]::local)
$NewTime | Tee-Object -FilePath $strLFpath\$strLFName -Append

Meaning that I have to open a new PowerShell session to reload the system variables.

Adding delay between execution of two following lines

This line calls the selector secondMethod after 3 seconds:

[self performSelector:@selector(secondMethod) withObject:nil afterDelay:3.0 ];

Use it on your second operation with your desired delay. If you have a lot of code, place it in its own method and call that method with performSelector:. It wont block the UI like sleep

Edit: If you do not want a second method you could add a category to be able to use blocks with performSelector:

@implementation NSObject (PerformBlockAfterDelay)

- (void)performBlock:(void (^)(void))block 
          afterDelay:(NSTimeInterval)delay
{
    block = [block copy];
    [self performSelector:@selector(fireBlockAfterDelay:) 
               withObject:block 
               afterDelay:delay];
}

- (void)fireBlockAfterDelay:(void (^)(void))block
{
    block();
}

@end

Or perhaps even cleaner:

void RunBlockAfterDelay(NSTimeInterval delay, void (^block)(void))
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC*delay),
      dispatch_get_current_queue(), block);
}

Spring: how do I inject an HttpServletRequest into a request-scoped bean?

As suggested here you can also inject the HttpServletRequest as a method param, e.g.:

public MyResponseObject myApiMethod(HttpServletRequest request, ...) {
    ...
}

Stopping a JavaScript function when a certain condition is met

Return is how you exit out of a function body. You are using the correct approach.

I suppose, depending on how your application is structured, you could also use throw. That would typically require that your calls to your function are wrapped in a try / catch block.

how to open *.sdf files?

Try LINQPad, it works for SQL Server, MySQL, SQLite and also SDF (SQL CE 4.0). Best of all it's free!

LINQPad

Steps with version 4.35.1:

  1. click 'Add Connection'

  2. Click Next with 'Build data context automatically' and 'Default(LINQ to SQL)' selected.

  3. Under 'Provider' choose 'SQL CE 4.0'.

  4. Under 'Database' with 'Attach database file' selected, choose 'Browse' to select your .sdf file.

  5. Click 'OK'.

  6. Voila! It should show the tables in .sdf and be able to query it via right clicking the table or writing LINQ code in your favorite .NET language or even SQL. How cool is that?

syntaxerror: unexpected character after line continuation character in python

Replace

f = open(D\\python\\HW\\2_1 - Copy.cp,"r");

by

f = open("D:\\python\\HW\\2_1 - Copy.cp", "r")

  1. File path needs to be a string (constant)
  2. need colon in Windows file path
  3. space after comma for better style
  4. ; after statement is allowed but fugly.

What tutorial are you using?

Android - java.lang.SecurityException: Permission Denial: starting Intent

This is only for android studio

So I ran into this problem recently. The issue was in the build/run configuration. Apparently android studio had chosen an activity in my project as the launch activity thus disregarding my choice in the manifest file.

Click on the module name just to the left of the run button and click on "Edit configurations..." Now make sure "Launch default Activity" is selected.

The funny thing when I got this error was that I could still launch the app with from the device and it starts with the preferred Activity. But launching from the IDE seemed impossible.

ImportError: No module named mysql.connector using Python2

I used the following command to install python mysql-connector in Mac. it works

pip install mysql-connector-python-rf

Get column index from label in a data frame

The following will do it:

which(colnames(df)=="B")

Concat strings by & and + in VB.Net

& and + are both concatenation operators but when you specify an integer while using +, vb.net tries to cast "Hello" into integer to do an addition. If you change "Hello" with "123", you will get the result 124.

How to upload files to server using Putty (ssh)

You need an scp client. Putty is not one. You can use WinSCP or PSCP. Both are free software.

ImportError: No module named _ssl

Since --with-ssl is not recognized anymore I just installed the libssl-dev. For debian based systems:

sudo apt-get install libssl-dev 

For CentOS and RHEL

sudo yum install openssl-devel

To restart the make first clean up by:

make clean

Then start again and execute the following commands one after the other:

./configure
make
make test
make install

For further information on OpenSSL visit the Ubuntu Help Page on OpenSSL.

Converting an int or String to a char array on Arduino

You can convert it to char* if you don't need a modifiable string by using:

(char*) yourString.c_str();

This would be very useful when you want to publish a String variable via MQTT in arduino.

Can we define min-margin and max-margin, max-padding and min-padding in css?

See this CodePen https://codepen.io/ella301/pen/vYLNmVg which I created. I used 3 CSS functions min, max and calc to make sure the left and right paddings are fluid between minimum 20px and maximum 120px.

 padding: 20px max(min(120px, calc((100% - 1198px) / 2)), 20px);

Hope it helps!

.NET console application as Windows service

I use a service class that follows the standard pattern prescribed by ServiceBase, and tack on helpers to easy F5 debugging. This keeps service data defined within the service, making them easy to find and their lifetimes easy to manage.

I normally create a Windows application with the structure below. I don't create a console application; that way I don't get a big black box popping in my face every time I run the app. I stay in in the debugger where all the action is. I use Debug.WriteLine so that the messages go to the output window, which docks nicely and stays visible after the app terminates.

I usually don't bother add debug code for stopping; I just use the debugger instead. If I do need to debug stopping, I make the project a console app, add a Stop forwarder method, and call it after a call to Console.ReadKey.

public class Service : ServiceBase
{
    protected override void OnStart(string[] args)
    {
        // Start logic here.
    }

    protected override void OnStop()
    {
        // Stop logic here.
    }

    static void Main(string[] args)
    {
        using (var service = new Service()) {
            if (Environment.UserInteractive) {
                service.Start();
                Thread.Sleep(Timeout.Infinite);
            } else
                Run(service);
        }
    }
    public void Start() => OnStart(null);
}

Timer for Python game

This is the Shortest Way I know of doing it:

def stopWatch():
        import time
        a = 0
        hours = 0
        while a < 1:
            for minutes in range(0, 60):
                for seconds in range(0, 60):
                    time.sleep(1)
                    print(hours,":", minutes,":", seconds)
        hours = hours + 1

What causes imported Maven project in Eclipse to use Java 1.5 instead of Java 1.6 by default and how can I ensure it doesn't?

If you want to make sure that newly created projects or imported projects in Eclipse use another default java version than Java 1.5, you can change the configuration in the maven-compiler-plugin.

  • Go to the folder .m2/repository/org/apache/maven/plugins/maven-compiler-plugin/3.1
  • Open maven-compiler-plugin-3.1.jar with a zip program.
  • Go to META-INF/maven and open the plugin.xml
  • In the following lines:
    <source implementation="java.lang.String" default-value="1.5">${maven.compiler.source}</source>
    <target implementation="java.lang.String" default-value="1.5">${maven.compiler.target}</target>

  • change the default-value to 1.6 or 1.8 or whatever you like.

  • Save the file and make sure it is written back to the zip file.

From now on all new Maven projects use the java version you specified.

Information is from the following blog post: https://sandocean.wordpress.com/2019/03/22/directly-generating-maven-projects-in-eclipse-with-java-version-newer-than-1-5/

JFrame.dispose() vs System.exit()

System.exit(); causes the Java VM to terminate completely.

JFrame.dispose(); causes the JFrame window to be destroyed and cleaned up by the operating system. According to the documentation, this can cause the Java VM to terminate if there are no other Windows available, but this should really just be seen as a side effect rather than the norm.

The one you choose really depends on your situation. If you want to terminate everything in the current Java VM, you should use System.exit() and everything will be cleaned up. If you only want to destroy the current window, with the side effect that it will close the Java VM if this is the only window, then use JFrame.dispose().

Python spacing and aligning strings

Try %*s and %-*s and prefix each string with the column width:

>>> print "Location: %-*s  Revision: %s" % (20,"10-10-10-10","1")
Location: 10-10-10-10           Revision: 1
>>> print "District: %-*s  Date: %s" % (20,"Tower","May 16, 2012")
District: Tower                 Date: May 16, 2012

What is the difference between exit and return?

the return statement exits from the current function and exit() exits from the program

they are the same when used in main() function

also return is a statement while exit() is a function which requires stdlb.h header file

Permission denied (publickey) when SSH Access to Amazon EC2 instance

i had same error but different situation. to me it happened out of the blue after a lot of time i could ssh successfully to my remote computer out there. after a lot of searching the solution to my problem were file permissions. it is strange of course because i didn't change any permissions in my computer or the remote one belonging to the ssh's files/directories. so from the good archlinux wiki here it is:

For the local machine do this:

$ chmod 700 ~/
$ chmod 700 ~/.ssh
$ chmod 600 ~/.ssh/id_ecdsa

For the remote machine do that:

$ chmod 700 ~/
$ chmod 700 ~/.ssh
$ chmod 600 ~/.ssh/authorized_keys

after that my ssh started to working again without the permission denied (publickey) thing.

Should I use window.navigate or document.location in JavaScript?

Late joining this conversation to shed light on a mildly interesting factoid for web-facing, analytics-aware websites. Passing the mic over to Michael Papworth:

https://github.com/michaelpapworth/jQuery.navigate

"When using website analytics, window.location is not sufficient due to the referer not being passed on the request. The plugin resolves this and allows for both aliased and parametrised URLs."

If one examines the code what it does is this:

   var methods = {
            'goTo': function (url) {
                // instead of using window.location to navigate away
                // we use an ephimeral link to click on and thus ensure
                // the referer (current url) is always passed on to the request
                $('<a></a>').attr("href", url)[0].click();
            },
            ...
   };

Neato!

Set date input field's max date to today

JavaScript only simple solution

_x000D_
_x000D_
datePickerId.max = new Date().toISOString().split("T")[0];
_x000D_
<input type="date" id="datePickerId" />
_x000D_
_x000D_
_x000D_

How to remove docker completely from ubuntu 14.04

sudo apt-get remove docker docker-engine docker.io containerd runc
sudo rm -rf /var/lib/docker
sudo apt-get autoclean
sudo apt-get update

How exactly does the python any() function work?

It's because the iterable is

(x > 0 for x in list)

Note that x > 0 returns either True or False and thus you have an iterable of booleans.

String replacement in java, similar to a velocity template

I threw together a small test implementation of this. The basic idea is to call format and pass in the format string, and a map of objects, and the names that they have locally.

The output of the following is:

My dog is named fido, and Jane Doe owns him.

public class StringFormatter {

    private static final String fieldStart = "\\$\\{";
    private static final String fieldEnd = "\\}";

    private static final String regex = fieldStart + "([^}]+)" + fieldEnd;
    private static final Pattern pattern = Pattern.compile(regex);

    public static String format(String format, Map<String, Object> objects) {
        Matcher m = pattern.matcher(format);
        String result = format;
        while (m.find()) {
            String[] found = m.group(1).split("\\.");
            Object o = objects.get(found[0]);
            Field f = o.getClass().getField(found[1]);
            String newVal = f.get(o).toString();
            result = result.replaceFirst(regex, newVal);
        }
        return result;
    }

    static class Dog {
        public String name;
        public String owner;
        public String gender;
    }

    public static void main(String[] args) {
        Dog d = new Dog();
        d.name = "fido";
        d.owner = "Jane Doe";
        d.gender = "him";
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("d", d);
        System.out.println(
           StringFormatter.format(
                "My dog is named ${d.name}, and ${d.owner} owns ${d.gender}.", 
                map));
    }
}

Note: This doesn't compile due to unhandled exceptions. But it makes the code much easier to read.

Also, I don't like that you have to construct the map yourself in the code, but I don't know how to get the names of the local variables programatically. The best way to do it, is to remember to put the object in the map as soon as you create it.

The following example produces the results that you want from your example:

public static void main(String[] args) {
    Map<String, Object> map = new HashMap<String, Object>();
    Site site = new Site();
    map.put("site", site);
    site.name = "StackOverflow.com";
    User user = new User();
    map.put("user", user);
    user.name = "jjnguy";
    System.out.println(
         format("Hello ${user.name},\n\tWelcome to ${site.name}. ", map));
}

I should also mention that I have no idea what Velocity is, so I hope this answer is relevant.

How do I determine the size of an object in Python?

For numpy arrays, getsizeof doesn't work - for me it always returns 40 for some reason:

from pylab import *
from sys import getsizeof
A = rand(10)
B = rand(10000)

Then (in ipython):

In [64]: getsizeof(A)
Out[64]: 40

In [65]: getsizeof(B)
Out[65]: 40

Happily, though:

In [66]: A.nbytes
Out[66]: 80

In [67]: B.nbytes
Out[67]: 80000

Redirect pages in JSP?

Hello there: If you need more control on where the link should redirect to, you could use this solution.

Ie. If the user is clicking in the CHECKOUT link, but you want to send him/her to checkout page if its registered(logged in) or registration page if he/she isn't.

You could use JSTL core LIKE:

<!--include the library-->
<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>

<%--create a var to store link--%>
<core:set var="linkToRedirect">
  <%--test the condition you need--%>
  <core:choose>
    <core:when test="${USER IS REGISTER}">
      checkout.jsp
    </core:when>
    <core:otherwise>
      registration.jsp
    </core:otherwise>
  </core:choose>
</core:set>

EXPLAINING: is the same as...

 //pseudo code
 if(condition == true)
   set linkToRedirect = checkout.jsp
 else
   set linkToRedirect = registration.jsp

THEN: in simple HTML...

<a href="your.domain.com/${linkToRedirect}">CHECKOUT</a>

Dropping connected users in Oracle database

Sometimes Oracle drop user takes long time to execute. In that case user might be connected to the database. Better you can kill user session and drop the user.

SQL> select 'alter system kill session ''' || sid || ',' || serial# || ''' immediate;' from v$session where username ='&USERNAME';

SQL> DROP USER barbie CASCADE;

Clear ComboBox selected text

Try specifying the actual index of the item you want erase the text from and set it's Text equal to "".

myComboBox[this.SelectedIndex].Text = ""

or

myComboBox.selectedIndex.Text = ""

I don't remember the exact syntax but it's something along those lines.

SQL JOIN vs IN performance?

A interesting writeup on the logical differences: SQL Server: JOIN vs IN vs EXISTS - the logical difference

I am pretty sure that assuming that the relations and indexes are maintained a Join will perform better overall (more effort goes into working with that operation then others). If you think about it conceptually then its the difference between 2 queries and 1 query.

You need to hook it up to the Query Analyzer and try it and see the difference. Also look at the Query Execution Plan and try to minimize steps.

Base64 Decoding in iOS 7+

In case you want to write fallback code, decoding from base64 has been present in iOS since the very beginning by caveat of NSURL:

NSURL *URL = [NSURL URLWithString:
      [NSString stringWithFormat:@"data:application/octet-stream;base64,%@",
           base64String]];

return [NSData dataWithContentsOfURL:URL];

Confirmation dialog on ng-click - AngularJS

In today's date this solution works for me:

/**
 * A generic confirmation for risky actions.
 * Usage: Add attributes: ng-really-message="Are you sure"? ng-really-click="takeAction()" function
 */
angular.module('app').directive('ngReallyClick', [function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.bind('click', function() {
                var message = attrs.ngReallyMessage;
                if (message && confirm(message)) {
                    scope.$apply(attrs.ngReallyClick);
                }
            });
        }
    }
}]);

Credits:https://gist.github.com/asafge/7430497#file-ng-really-js

How does cookie based authentication work?

Cookie-Based Authentication

Cookies based Authentication works normally in these 4 steps-

  1. The user provides a username and password in the login form and clicks Log In.
  2. After the request is made, the server validate the user on the backend by querying in the database. If the request is valid, it will create a session by using the user information fetched from the database and store them, for each session a unique id called session Id is created ,by default session Id is will be given to client through the Browser.
  3. Browser will submit this session Id on each subsequent requests, the session ID is verified against the database, based on this session id website will identify the session belonging to which client and then give access the request.

  4. Once a user logs out of the app, the session is destroyed both client-side and server-side.

How to implement authenticated routes in React Router 4?

The solution which ultimately worked best for my organization is detailed below, it just adds a check on render for the sysadmin route and redirects the user to a different main path of the application if they are not allowed to be in the page.

SysAdminRoute.tsx

import React from 'react';
import { Route, Redirect, RouteProps } from 'react-router-dom';
import AuthService from '../services/AuthService';
import { appSectionPageUrls } from './appSectionPageUrls';
interface IProps extends RouteProps {}
export const SysAdminRoute = (props: IProps) => {
    var authService = new AuthService();
    if (!authService.getIsSysAdmin()) { //example
        authService.logout();
        return (<Redirect to={{
            pathname: appSectionPageUrls.site //front-facing
        }} />);
    }
    return (<Route {...props} />);
}

There are 3 main routes for our implementation, the public facing /site, the logged in client /app, and sys admin tools at /sysadmin. You get redirected based on your 'authiness' and this is the page at /sysadmin.

SysAdminNav.tsx

<Switch>
    <SysAdminRoute exact path={sysadminUrls.someSysAdminUrl} render={() => <SomeSysAdminUrl/> } />
    //etc
</Switch>

CSS3 transition doesn't work with display property

max-height

.PrimaryNav-container {
...
max-height: 0;
overflow: hidden;
transition: max-height 0.3s ease;
...
}

.PrimaryNav.PrimaryNav--isOpen .PrimaryNav-container {
max-height: 300px;
}

https://www.codehive.io/boards/bUoLvRg

Writing string to a file on a new line every time

You can do this in two ways:

f.write("text to write\n")

or, depending on your Python version (2 or 3):

print >>f, "text to write"         # Python 2.x
print("text to write", file=f)     # Python 3.x

Find nginx version?

My guess is it's not in your path.
in bash, try:
echo $PATH
and
sudo which nginx
And see if the folder containing nginx is also in your $PATH variable.
If not, either add the folder to your path environment variable, or create an alias (and put it in your .bashrc) ooor your could create a link i guess.
or sudo nginx -v if you just want that...

Global keyboard capture in C# application

private void buttonHook_Click(object sender, EventArgs e)
{
    // Hooks only into specified Keys (here "A" and "B").
    // (***) Use this constructor

    _globalKeyboardHook = new GlobalKeyboardHook(new Keys[] { Keys.A, Keys.B });

    // Hooks into all keys.
    // (***) Or this - not both

    _globalKeyboardHook = new GlobalKeyboardHook();
    _globalKeyboardHook.KeyboardPressed += OnKeyPressed;
}

And then is working fine.

Better way of getting time in milliseconds in javascript?

Try Date.now().

The skipping is most likely due to garbage collection. Typically garbage collection can be avoided by reusing variables as much as possible, but I can't say specifically what methods you can use to reduce garbage collection pauses.

How to get the separate digits of an int number?

I think this will be the most useful way to get digits:

public int[] getDigitsOf(int num)
{        
    int digitCount = Integer.toString(num).length();

    if (num < 0) 
        digitCount--;           

    int[] result = new int[digitCount];

    while (digitCount-- >0) {
        result[digitCount] = num % 10;
        num /= 10;
    }        
    return result;
}

Then you can get digits in a simple way:

int number = 12345;
int[] digits = getDigitsOf(number);

for (int i = 0; i < digits.length; i++) {
    System.out.println(digits[i]);
}

or more simply:

int number = 12345;
for (int i = 0; i < getDigitsOf(number).length; i++) {
    System.out.println(  getDigitsOf(number)[i]  );
}

Notice the last method calls getDigitsOf method too much time. So it will be slower. You should create an int array and then call the getDigitsOf method once, just like in second code block.

In the following code, you can reverse to process. This code puts all digits together to make the number:

public int digitsToInt(int[] digits)
{
    int digitCount = digits.length;
    int result = 0;

    for (int i = 0; i < digitCount; i++) {
        result = result * 10;
        result += digits[i];
    }

    return result;
}

Both methods I have provided works for negative numbers too.

Difference between Parameters.Add(string, object) and Parameters.AddWithValue

There is no difference in terms of functionality. In fact, both do this:

return this.Add(new SqlParameter(parameterName, value));

The reason they deprecated the old one in favor of AddWithValue is to add additional clarity, as well as because the second parameter is object, which makes it not immediately obvious to some people which overload of Add was being called, and they resulted in wildly different behavior.

Take a look at this example:

 SqlCommand command = new SqlCommand();
 command.Parameters.Add("@name", 0);

At first glance, it looks like it is calling the Add(string name, object value) overload, but it isn't. It's calling the Add(string name, SqlDbType type) overload! This is because 0 is implicitly convertible to enum types. So these two lines:

 command.Parameters.Add("@name", 0);

and

 command.Parameters.Add("@name", 1);

Actually result in two different methods being called. 1 is not convertible to an enum implicitly, so it chooses the object overload. With 0, it chooses the enum overload.

How does HTTP_USER_AGENT work?

The user agent string is a text that the browsers themselves send to the webserver to identify themselves, so that websites can send different content based on the browser or based on browser compatibility.

Mozilla is a browser rendering engine (the one at the core of Firefox) and the fact that Chrome and IE contain the string Mozilla/4 or /5 identifies them as being compatible with that rendering engine.

How can I plot separate Pandas DataFrames as subplots?

You can manually create the subplots with matplotlib, and then plot the dataframes on a specific subplot using the ax keyword. For example for 4 subplots (2x2):

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=2, ncols=2)

df1.plot(ax=axes[0,0])
df2.plot(ax=axes[0,1])
...

Here axes is an array which holds the different subplot axes, and you can access one just by indexing axes.
If you want a shared x-axis, then you can provide sharex=True to plt.subplots.

How to convert WebResponse.GetResponseStream return into a string?

You can create a StreamReader around the stream, then call StreamReader.ReadToEnd().

StreamReader responseReader = new StreamReader(request.GetResponse().GetResponseStream());
var responseData = responseReader.ReadToEnd();

Password Protect a SQLite DB. Is it possible?

You can encrypt your SQLite database with the SEE addon. This way you prevent unauthorized access/modification.

Quoting SQLite documentation:

The SQLite Encryption Extension (SEE) is an enhanced version of SQLite that encrypts database files using 128-bit or 256-Bit AES to help prevent unauthorized access or modification. The entire database file is encrypted so that to an outside observer, the database file appears to contain white noise. There is nothing that identifies the file as an SQLite database.

You can find more info about this addon in this link.

Copy a file in a sane, safe and efficient way

Too many!

The "ANSI C" way buffer is redundant, since a FILE is already buffered. (The size of this internal buffer is what BUFSIZ actually defines.)

The "OWN-BUFFER-C++-WAY" will be slow as it goes through fstream, which does a lot of virtual dispatching, and again maintains internal buffers or each stream object. (The "COPY-ALGORITHM-C++-WAY" does not suffer this, as the streambuf_iterator class bypasses the stream layer.)

I prefer the "COPY-ALGORITHM-C++-WAY", but without constructing an fstream, just create bare std::filebuf instances when no actual formatting is needed.

For raw performance, you can't beat POSIX file descriptors. It's ugly but portable and fast on any platform.

The Linux way appears to be incredibly fast — perhaps the OS let the function return before I/O was finished? In any case, that's not portable enough for many applications.

EDIT: Ah, "native Linux" may be improving performance by interleaving reads and writes with asynchronous I/O. Letting commands pile up can help the disk driver decide when is best to seek. You might try Boost Asio or pthreads for comparison. As for "can't beat POSIX file descriptors"… well that's true if you're doing anything with the data, not just blindly copying.

Does bootstrap have builtin padding and margin classes?

Bootstrap has many facility of classes to easily style elements if HTML. It includes a various of padding and margin classes for modification of the appearance of the element.

.m-0 { margin:0!important; }
.m-1 { margin:.25rem!important; }
.m-2 { margin:.5rem!important; }
.m-3 { margin:1rem!important; }
.m-4 { margin:1.5rem!important; }
.m-5 { margin:3rem!important; }

.mt-0 { margin-top:0!important; }
.mr-0 { margin-right:0!important; }
.mb-0 { margin-bottom:0!important; }
.ml-0 { margin-left:0!important; }
.mx-0 { margin-left:0!immortant;margin-right:0!immortant; }
.my-0 { margin-top:0!important;margin-bottom:0!important; }

.mt-1 { margin-top:.25rem!important; }
.mr-1 { margin-right:.25rem!important; }
.mb-1 { margin-bottom:.25rem!important; }
.ml-1 { margin-left:.25rem!important; }
.mx-1 { margin-left:.25rem!important;margin-right:.25rem!important; }
.my-1 { margin-top:.25rem!important;margin-bottom:.25rem!important; }

.mt-2 { margin-top:.5rem!important; }
.mr-2 { margin-right:.5rem!important; }
.mb-2 { margin-bottom:.5rem!important; }
.ml-2 { margin-left:.5rem!important; }
.mx-2 { margin-right:.5rem!important;margin-left:.5rem!important; }
.my-2 { margin-top:.5rem!important;margin-bottom:.5rem!important; }

.mt-3 { margin-top:1rem!important; }
.mr-3 { margin-right:1rem!important; }
.mb-3 { margin-bottom:1rem!important; }
.ml-3 { margin-left:1rem!important; }
.mx-3 { margin-right:1rem!important;margin-left:1rem!important; }
.my-3 { margin-bottom:1rem!important;margin-top:1rem!important; }

.mt-4 { margin-top:1.5rem!important; }
.mr-4 { margin-right:1.5rem!important; }
.mb-4 { margin-bottom:1.5rem!important; }
.ml-4 { margin-left:1.5rem!important; }
.mx-4 { margin-right:1.5rem!important;margin-left:1.5rem!important; }
.my-4 { margin-top:1.5rem!important;margin-bottom:1.5rem!important; }

.mt-5 { margin-top:3rem!important; }
.mr-5 { margin-right:3rem!important; }
.mb-5 { margin-bottom:3rem!important; }
.ml-5 { margin-left:3rem!important; }
.mx-5 { margin-right:3rem!important;margin-left:3rem!important; }
.my-5 { margin-top:3rem!important;margin-bottom:3rem!important; }

.mt-auto { margin-top:auto!important; }
.mr-auto { margin-right:auto!important; }
.mb-auto { margin-bottom:auto!important; }
.ml-auto { margin-left:auto!important; }
.mx-auto { margin-right:auto!important;margin-left:auto!important; }
.my-auto { margin-bottom:auto!important;margin-top:auto!important; }

.p-0 { padding:0!important; }
.p-1 { padding:.25rem!important; }
.p-2 { padding:.5rem!important; }
.p-3 { padding:1rem!important; }
.p-4 { padding:1.5rem!important; }
.p-5 { padding:3rem!important; }

.pt-0 { padding-top:0!important; }
.pr-0 { padding-right:0!important; }
.pb-0 { padding-bottom:0!important; }
.pl-0 { padding-left:0!important; }                             
.px-0 { padding-left:0!important;padding-right:0!important; }
.py-0 { padding-top:0!important;padding-bottom:0!important; }

.pt-1 { padding-top:.25rem!important; }         
.pr-1 { padding-right:.25rem!important; }                       
.pb-1 { padding-bottom:.25rem!important; }      
.pl-1 { padding-left:.25rem!important; }                            
.px-1 { padding-left:.25rem!important;padding-right:.25rem!important; }
.py-1 { padding-top:.25rem!important;padding-bottom:.25rem!important; }

.pt-2 { padding-top:.5rem!important; }                                              
.pr-2 { padding-right:.5rem!important; }                                
.pb-2 { padding-bottom:.5rem!important; }               
.pl-2 { padding-left:.5rem!important; }                                             
.px-2 { padding-right:.5rem!important;padding-left:.5rem!important; }
.py-2 { padding-top:.5rem!important;padding-bottom:.5rem!important; }

.pt-3 { padding-top:1rem!important; }                               
.pr-3 { padding-right:1rem!important; }             
.pb-3 { padding-bottom:1rem!important; }                
.pl-3 { padding-left:1rem!important; }                              
.py-3 { padding-bottom:1rem!important;padding-top:1rem!important; }
.px-3 { padding-right:1rem!important;padding-left:1rem!important; }

.pt-4 { padding-top:1.5rem!important; }                             
.pr-4 { padding-right:1.5rem!important; }               
.pb-4 { padding-bottom:1.5rem!important; }              
.pl-4 { padding-left:1.5rem!important; }                                
.px-4 { padding-right:1.5rem!important;padding-left:1.5rem!important; }
.py-4 { padding-top:1.5rem!important;padding-bottom:1.5rem!important; }

.pt-5 { padding-top:3rem!important; }   
.pr-5 { padding-right:3rem!important; } 
.pb-5 { padding-bottom:3rem!important; }    
.pl-5 { padding-left:3rem!important; }  
.px-5 { padding-right:3rem!important;padding-left:3rem!important; }
.py-5 { padding-top:3rem!important;padding-bottom:3rem!important; }

https://jsfiddle.net/ssuryar/x47bca1u/

Auto increment in MongoDB to store sequence of Unique User ID

I had a similar issue, namely I was interested in generating unique numbers, which can be used as identifiers, but doesn't have to. I came up with the following solution. First to initialize the collection:

fun create(mongo: MongoTemplate) {
        mongo.db.getCollection("sequence")
                .insertOne(Document(mapOf("_id" to "globalCounter", "sequenceValue" to 0L)))
    }

An then a service that return unique (and ascending) numbers:

@Service
class IdCounter(val mongoTemplate: MongoTemplate) {

    companion object {
        const val collection = "sequence"
    }

    private val idField = "_id"
    private val idValue = "globalCounter"
    private val sequence = "sequenceValue"

    fun nextValue(): Long {
        val filter = Document(mapOf(idField to idValue))
        val update = Document("\$inc", Document(mapOf(sequence to 1)))
        val updated: Document = mongoTemplate.db.getCollection(collection).findOneAndUpdate(filter, update)!!
        return updated[sequence] as Long
    }
}

I believe that id doesn't have the weaknesses related to concurrent environment that some of the other solutions may suffer from.

DECODE( ) function in SQL Server

If I understand the question correctly, you want the equivalent of decode but in T-SQL

Select YourFieldAliasName =
CASE PC_SL_LDGR_CODE
    WHEN '02' THEN 'DR'
    ELSE 'CR'
END

How to get Last record from Sqlite?

If you have already got the cursor, then this is how you may get the last record from cursor:

cursor.moveToPosition(cursor.getCount() - 1);
//then use cursor to read values

Disabled UIButton not faded or grey

Set title color for different states:

@IBOutlet weak var loginButton: UIButton! {
        didSet {
            loginButton.setTitleColor(UIColor.init(white: 1, alpha: 0.3), for: .disabled)
            loginButton.setTitleColor(UIColor.init(white: 1, alpha: 1), for: .normal)
        }
    }

Usage: (text color will get change automatically)

loginButton.isEnabled = false

enter image description here

How to clear a chart from a canvas so that hover events cannot be triggered?

This worked for me. Add a call to clearChart, at the top oF your updateChart()

`function clearChart() {
    event.preventDefault();
    var parent = document.getElementById('parent-canvas');
    var child = document.getElementById('myChart');          
    parent.removeChild(child);            
    parent.innerHTML ='<canvas id="myChart" width="350" height="99" ></canvas>';             
    return;
}`

for-in statement

In Typescript 1.5 and later, you can use for..of as opposed to for..in

var numbers = [1, 2, 3];

for (var number of numbers) {
    console.log(number);
}

How to clear the Entry widget after a button is pressed in Tkinter?

if none of the above is working you can use this->

idAssignedToEntryWidget.delete(first = 0, last = UpperLimitAssignedToEntryWidget)

for e.g. ->

id assigned is = en then

en.delete(first =0, last =100)

Creating a border like this using :before And :after Pseudo-Elements In CSS?

See the following snippet, is this what you want?

_x000D_
_x000D_
body {
    background: silver;
    padding: 0 10px;
}

#content:after {
    height: 10px;
    display: block;
    width: 100px;
    background: #808080;
    border-right: 1px white;
    content: '';
}

#footer:before {
    display: block;
    content: '';
    background: silver;
    height: 10px;
    margin-top: -20px;
    margin-left: 101px;
}

#content {
    background: white;
}


#footer {
    padding-top: 10px;
    background: #404040;
}

p {
    padding: 100px;
    text-align: center;
}

#footer p {
    color: white;
}
_x000D_
<body>
    <div id="content"><p>#content</p></div>
    <div id="footer"><p>#footer</p></div>
</body>
_x000D_
_x000D_
_x000D_

JSFiddle

Fetch frame count with ffmpeg

to build on stu's answer. here's how i found the frame rate for a video from my mobile phone. i ran the following command for a while. i let the frame count get up to about ~ 10,000 before i got impatient and hit ^C:

$ ffmpeg -i 2013-07-07\ 12.00.59.mp4 -f null /dev/null 2>&1
...
Press [q] to stop, [?] for help
[null @ 0x7fcc80836000] Encoder did not produce proper pts, making some up.
frame= 7989 fps= 92 q=0.0 Lsize=N/A time=00:04:26.30 bitrate=N/A dup=10 drop=0    
video:749kB audio:49828kB subtitle:0 global headers:0kB muxing overhead -100.000042%
Received signal 2: terminating.
$

then, i grabbed two pieces of information from that line which starts with "frame=", the frame count, 7989, and the time, 00:04:26.30. You first need to convert the time into seconds and then divide the number of frames by seconds to get "frames per second". "frames per second" is your frame rate.

$ bc -l
0*60*60 + 4*60 + 26.3
266.3

7989/(4*60+26.3)
30.00000000000000000000
$

the framerate for my video is 30 fps.

How do I access (read, write) Google Sheets spreadsheets with Python?

I think you're looking at the cell-based feeds section in that API doc page. Then you can just use the PUT/ GET requests within your Python script, using either commands.getstatusoutput or subprocess.

How do I get the first element from an IEnumerable<T> in .net?

Well, you didn't specify which version of .Net you're using.

Assuming you have 3.5, another way is the ElementAt method:

var e = enumerable.ElementAt(0);

How to run a C# application at Windows startup?

OK here are my 2 cents: try passing path with each backslash as double backslash. I have found sometimes calling WIN API requires that.

How do I pass multiple parameters in Objective-C?

(int) add: (int) numberOne plus: (int) numberTwo ;
(returnType) functionPrimaryName : (returnTypeOfArgumentOne) argumentName functionSecondaryNa

me:

(returnTypeOfSecontArgument) secondArgumentName ;

as in other languages we use following syntax void add(int one, int second) but way of assigning arguments in OBJ_c is different as described above

Convert a PHP object to an associative array

$Menu = new Admin_Model_DbTable_Menu(); 
$row = $Menu->fetchRow($Menu->select()->where('id = ?', $id));
$Addmenu = new Admin_Form_Addmenu(); 
$Addmenu->populate($row->toArray());

Can anybody tell me details about hs_err_pid.log file generated when Tomcat crashes?

A very very good document regarding this topic is Troubleshooting Guide for Java from (originally) Sun. See the chapter "Troubleshooting System Crashes" for information about hs_err_pid* Files.

See Appendix C - Fatal Error Log

Per the guide, by default the file will be created in the working directory of the process if possible, or in the system temporary directory otherwise. A specific location can be chosen by passing in the -XX:ErrorFile product flag. It says:

If the -XX:ErrorFile= file flag is not specified, the system attempts to create the file in the working directory of the process. In the event that the file cannot be created in the working directory (insufficient space, permission problem, or other issue), the file is created in the temporary directory for the operating system.

How can I get the height and width of an uiimage?

    import func AVFoundation.AVMakeRect

    let imageRect = AVMakeRect(aspectRatio: self.image!.size, insideRect: self.bounds)

    x = imageRect.minX

    y = imageRect.minY

How to change root logging level programmatically for logback

using logback 1.1.3 I had to do the following (Scala code):

import ch.qos.logback.classic.Logger
import org.slf4j.LoggerFactory    
...
val root: Logger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME).asInstanceOf[Logger]

How do I increase modal width in Angular UI Bootstrap?

You can do this in very simple way using size property of angular modal.

var modal = $modal.open({
                    templateUrl: "/partials/welcome",
                    controller: "welcomeCtrl",
                    backdrop: "static",
                    scope: $scope,
                    size:'lg' // you can try different width like 'sm', 'md'
                });

<button> vs. <input type="button" />. Which to use?

Quoting the Forms Page in the HTML manual:

Buttons created with the BUTTON element function just like buttons created with the INPUT element, but they offer richer rendering possibilities: the BUTTON element may have content. For example, a BUTTON element that contains an image functions like and may resemble an INPUT element whose type is set to "image", but the BUTTON element type allows content.

Pure CSS scroll animation

You can use my script from CodePen by just wrapping all the content within a .levit-container DIV.

~function  () {
    function Smooth () {
        this.$container = document.querySelector('.levit-container');
        this.$placeholder = document.createElement('div');
    }

    Smooth.prototype.init = function () {
        var instance = this;

        setContainer.call(instance);
        setPlaceholder.call(instance);
        bindEvents.call(instance);
    }

    function bindEvents () {
        window.addEventListener('scroll', handleScroll.bind(this), false);
    }

    function setContainer () {
        var style = this.$container.style;

        style.position = 'fixed';
        style.width = '100%';
        style.top = '0';
        style.left = '0';
        style.transition = '0.5s ease-out';
    }

    function setPlaceholder () {
        var instance = this,
                $container = instance.$container,
                $placeholder = instance.$placeholder;

        $placeholder.setAttribute('class', 'levit-placeholder');
        $placeholder.style.height = $container.offsetHeight + 'px';
        document.body.insertBefore($placeholder, $container);
    }

    function handleScroll () {
        this.$container.style.transform = 'translateZ(0) translateY(' + (window.scrollY * (- 1)) + 'px)';
    }

    var smooth = new Smooth();
    smooth.init();
}();

https://codepen.io/acauamontiel/pen/zxxebb?editors=0010

Declare a variable as Decimal

The best way is to declare the variable as a Single or a Double depending on the precision you need. The data type Single utilizes 4 Bytes and has the range of -3.402823E38 to 1.401298E45. Double uses 8 Bytes.

You can declare as follows:

Dim decAsdf as Single

or

Dim decAsdf as Double

Here is an example which displays a message box with the value of the variable after calculation. All you have to do is put it in a module and run it.

Sub doubleDataTypeExample()
Dim doubleTest As Double


doubleTest = 0.0000045 * 0.005 * 0.01

MsgBox "doubleTest = " & doubleTest
End Sub

CryptographicException 'Keyset does not exist', but only through WCF

I just reinstalled my certificate in local machine and then it is working fine

The target ... overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig

In your project, find Target -> Build Settings -> Other Linker Flags, select Other Linker Flags, press delete(Mac Keyboard)/Backspace(Normal keyboard) to recover the setting. It works for me.

Example:

Before enter image description here

After enter image description here

jQuery append and remove dynamic table row

live view Link Jsfiddle

vary simple way you can solve it ..... take a look my new collected code.

 $(document).ready(function(){
            $(".add-row").click(function(){
                var name = $("#name").val();
                var email = $("#email").val();
                var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + name + "</td><td>" + email + "</td></tr>";
                $("table tbody").append(markup);
            });

            // Find and remove selected table rows
            $(".delete-row").click(function(){
                $("table tbody").find('input[name="record"]').each(function(){
                    if($(this).is(":checked")){
                        $(this).parents("tr").remove();
                    }
                });
            });
        });   

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $(".add-row").click(function() {_x000D_
    var name = $("#name").val();_x000D_
    var email = $("#email").val();_x000D_
    var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + name + "</td><td>" + email + "</td></tr>";_x000D_
    $("table tbody").append(markup);_x000D_
  });_x000D_
_x000D_
  // Find and remove selected table rows_x000D_
  $(".delete-row").click(function() {_x000D_
    $("table tbody").find('input[name="record"]').each(function() {_x000D_
      if ($(this).is(":checked")) {_x000D_
        $(this).parents("tr").remove();_x000D_
      }_x000D_
    });_x000D_
  });_x000D_
});
_x000D_
form {_x000D_
  margin: 20px 0;_x000D_
}_x000D_
form input,_x000D_
button {_x000D_
  padding: 6px;_x000D_
  font-size: 18px;_x000D_
}_x000D_
table {_x000D_
  width: 100%;_x000D_
  margin-bottom: 20px;_x000D_
  border-collapse: collapse;_x000D_
  background: #fff;_x000D_
}_x000D_
table,_x000D_
th,_x000D_
td {_x000D_
  border: 1px solid #cdcdcd;_x000D_
}_x000D_
table th,_x000D_
table td {_x000D_
  padding: 10px;_x000D_
  text-align: left;_x000D_
}_x000D_
body {_x000D_
  background: #ccc;_x000D_
}_x000D_
.add-row,_x000D_
.delete-row {_x000D_
  font-size: 16px;_x000D_
  font-weight: 600;_x000D_
  padding: 8px 16px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form>_x000D_
  <input type="text" id="name" placeholder="Name">_x000D_
  <input type="text" id="email" placeholder="Email">_x000D_
  <input type="button" class="add-row" value="Add Row">_x000D_
</form>_x000D_
<table>_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Select</th>_x000D_
      <th>Name</th>_x000D_
      <th>Email</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>_x000D_
        <input type="checkbox" name="record">_x000D_
      </td>_x000D_
      <td>Peter Parker</td>_x000D_
      <td>[email protected]</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>_x000D_
<button type="button" class="delete-row">Delete Row</button>
_x000D_
_x000D_
_x000D_

Access restriction: The type 'Application' is not API (restriction on required library rt.jar)

I'm using eclipse neon 3. I just wanted to use javafx.application.Application, so I followed Christian Hujer's answer above and it worked. Just some tips: the access rules are very similar to the import statement. For me, the access rules I added was "javafx/application/**". Just replace the dot in the import statement with forward slash and that's the rule. Hope that helps.

Convert command line arguments into an array in Bash

The importance of the double quotes is worth emphasizing. Suppose an argument contains whitespace.

Code:

#!/bin/bash
printf 'arguments:%s\n' "$@"
declare -a arrayGOOD=( "$@" )
declare -a arrayBAAD=(  $@  )

printf '\n%s:\n' arrayGOOD
declare -p arrayGOOD
arrayGOODlength=${#arrayGOOD[@]}
for (( i=1; i<${arrayGOODlength}+1; i++ ));
do
   echo "${arrayGOOD[$i-1]}"
done

printf '\n%s:\n' arrayBAAD
declare -p arrayBAAD
arrayBAADlength=${#arrayBAAD[@]}
for (( i=1; i<${arrayBAADlength}+1; i++ ));
do
   echo "${arrayBAAD[$i-1]}"
done

Output:

> ./bash-array-practice.sh 'The dog ate the "flea" -- and ' the mouse.
arguments:The dog ate the "flea" -- and 
arguments:the
arguments:mouse.

arrayGOOD:
declare -a arrayGOOD='([0]="The dog ate the \"flea\" -- and " [1]="the" [2]="mouse.")'
The dog ate the "flea" -- and 
the
mouse.

arrayBAAD:
declare -a arrayBAAD='([0]="The" [1]="dog" [2]="ate" [3]="the" [4]="\"flea\"" [5]="--" [6]="and" [7]="the" [8]="mouse.")'
The
dog
ate
the
"flea"
--
and
the
mouse.
> 

Convert String to Integer in XSLT 1.0

XSLT 1.0 does not have an integer data type, only double. You can use number() to convert a string to a number.

How does #include <bits/stdc++.h> work in C++?

#include <bits/stdc++.h> is an implementation file for a precompiled header.

From, software engineering perspective, it is a good idea to minimize the include. If you use it actually includes a lot of files, which your program may not need, thus increase both compile-time and program size unnecessarily. [edit: as pointed out by @Swordfish in the comments that the output program size remains unaffected. But still, it's good practice to include only the libraries you actually need, unless it's some competitive competition]

But in contests, using this file is a good idea, when you want to reduce the time wasted in doing chores; especially when your rank is time-sensitive.

It works in most online judges, programming contest environments, including ACM-ICPC (Sub-Regionals, Regionals, and World Finals) and many online judges.

The disadvantages of it are that it:

  • increases the compilation time.
  • uses an internal non-standard header file of the GNU C++ library, and so will not compile in MSVC, XCode, and many other compilers

Mismatched anonymous define() module

Like AlienWebguy said, per the docs, require.js can blow up if

  • You have an anonymous define ("modules that call define() with no string ID") in its own script tag (I assume actually they mean anywhere in global scope)
  • You have modules that have conflicting names
  • You use loader plugins or anonymous modules but don't use require.js's optimizer to bundle them

I had this problem while including bundles built with browserify alongside require.js modules. The solution was to either:

A. load the non-require.js standalone bundles in script tags before require.js is loaded, or

B. load them using require.js (instead of a script tag)

ASP.NET MVC: No parameterless constructor defined for this object

I had the same problem.

Just Removed HttpFileCollectionBase files from Post Action method argument and added like HttpFileCollectionBase files = Request.Files; in method body.

AlertDialog styling - how to change style (color) of title, message, etc

Remove the panel background

 <item name="android:windowBackground">@color/transparent_color</item> 
 <color name="transparent_color">#00000000</color>

This is Mystyle:

 <style name="ThemeDialogCustom">
    <item name="android:windowFrame">@null</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
    <item name="android:windowBackground">@color/transparent_color</item>
    <item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
    <item name="android:colorBackgroundCacheHint">@null</item>
</style>

Which i have added to the constructor.

Add textColor :

<item name="android:textColor">#ff0000</item>

How to run html file on localhost?

You can install Xampp and run apache serve and place your file to www folder and access your file at localhost/{file name} or simply at localhost if your file is named index.html

Difference between mkdir() and mkdirs() in java for java.io.File

mkdirs() also creates parent directories in the path this File represents.

javadocs for mkdirs():

Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.

javadocs for mkdir():

Creates the directory named by this abstract pathname.

Example:

File  f = new File("non_existing_dir/someDir");
System.out.println(f.mkdir());
System.out.println(f.mkdirs());

will yield false for the first [and no dir will be created], and true for the second, and you will have created non_existing_dir/someDir

$.ajax - dataType

(ps: the answer given by Nick Craver is incorrect)

contentType specifies the format of data being sent to the server as part of request(it can be sent as part of response too, more on that later).

dataType specifies the expected format of data to be received by the client(browser).

Both are not interchangable.

  • contentType is the header sent to the server, specifying the format of data(i.e the content of message body) being being to the server. This is used with POST and PUT requests. Usually when u send POST request, the message body comprises of passed in parameters like:

==============================

Sample request:

POST /search HTTP/1.1 
Content-Type: application/x-www-form-urlencoded 
<<other header>>

name=sam&age=35

==============================

The last line above "name=sam&age=35" is the message body and contentType specifies it as application/x-www-form-urlencoded since we are passing the form parameters in the message body. However we aren't limited to just sending the parameters, we can send json, xml,... like this(sending different types of data is especially useful with RESTful web services):

==============================

Sample request:

POST /orders HTTP/1.1
Content-Type: application/xml
<<other header>>

<order>
   <total>$199.02</total>
   <date>December 22, 2008 06:56</date>
...
</order>

==============================

So the ContentType this time is: application/xml, cause that's what we are sending. The above examples showed sample request, similarly the response send from the server can also have the Content-Type header specifying what the server is sending like this:

==============================

sample response:

HTTP/1.1 201 Created
Content-Type: application/xml
<<other headers>>

<order id="233">
   <link rel="self" href="http://example.com/orders/133"/>
   <total>$199.02</total>
   <date>December 22, 2008 06:56</date>
...
</order>

==============================

  • dataType specifies the format of response to expect. Its related to Accept header. JQuery will try to infer it based on the Content-Type of the response.

==============================

Sample request:

GET /someFolder/index.html HTTP/1.1
Host: mysite.org
Accept: application/xml
<<other headers>>

==============================

Above request is expecting XML from the server.

Regarding your question,

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

Here you are sending json data using UTF8 character set, and you expect back json data from the server. As per the JQuery docs for dataType,

The json type parses the fetched data file as a JavaScript object and returns the constructed object as the result data.

So what you get in success handler is proper javascript object(JQuery converts the json object for you)

whereas

contentType: "application/json",
dataType: "text",

Here you are sending json data, since you haven't mentioned the encoding, as per the JQuery docs,

If no charset is specified, data will be transmitted to the server using the server's default charset; you must decode this appropriately on the server side.

and since dataType is specified as text, what you get in success handler is plain text, as per the docs for dataType,

The text and xml types return the data with no processing. The data is simply passed on to the success handler

How to search JSON tree with jQuery

I found ifaour's example of jQuery.each() to be helpful, but would add that jQuery.each() can be broken (that is, stopped) by returning false at the point where you've found what you're searching for:

$.each(json.people.person, function(i, v) {
        if (v.name == "Peter") {
            // found it...
            alert(v.age);
            return false; // stops the loop
        }
});

How can I decode HTML characters in C#?

To decode HTML take a look below code

string s = "Svendborg V&#230;rft A/S";
string a = HttpUtility.HtmlDecode(s);
Response.Write(a);

Output is like

 Svendborg Værft A/S

How to select the first row of each group?

The solution below does only one groupBy and extract the rows of your dataframe that contain the maxValue in one shot. No need for further Joins, or Windows.

import org.apache.spark.sql.Row
import org.apache.spark.sql.catalyst.encoders.RowEncoder
import org.apache.spark.sql.DataFrame

//df is the dataframe with Day, Category, TotalValue

implicit val dfEnc = RowEncoder(df.schema)

val res: DataFrame = df.groupByKey{(r) => r.getInt(0)}.mapGroups[Row]{(day: Int, rows: Iterator[Row]) => i.maxBy{(r) => r.getDouble(2)}}

How to update a record using sequelize for node?

This solution is deprecated

failure|fail|error() is deprecated and will be removed in 2.1, please use promise-style instead.

so you have to use

Project.update(

    // Set Attribute values 
    {
        title: 'a very different title now'
    },

    // Where clause / criteria 
    {
        _id: 1
    }

).then(function() {

    console.log("Project with id =1 updated successfully!");

}).catch(function(e) {
    console.log("Project update failed !");
})

And you can use .complete() as well

Regards

How to rename a pane in tmux?

For those scripting tmux, there is a command called rename-window so e.g.

tmux rename-window -t <window> <newname>

How to set password for Redis?

How to set redis password ?

step 1. stop redis server using below command /etc/init.d/redis-server stop

step 2.enter command : sudo nano /etc/redis/redis.conf

step 3.find # requirepass foobared word and remove # and change foobared to YOUR PASSWORD

ex. requirepass root

How to get the current time in Google spreadsheet using script editor?

use the JavaScript Date() object. There are a number of ways to get the time, date, timestamps, etc from the object. (Reference)

function myFunction() {
  var d = new Date();
  var timeStamp = d.getTime();  // Number of ms since Jan 1, 1970

  // OR:

  var currentTime = d.toLocaleTimeString(); // "12:35 PM", for instance
}

SQL Server - Convert date field to UTC

We can convert ServerZone DateTime to UTC and UTC to ServerZone DateTime

Simply run the following scripts to understand the conversion then modify as what you need

--Get Server's TimeZone
DECLARE @ServerTimeZone VARCHAR(50)
EXEC MASTER.dbo.xp_regread 'HKEY_LOCAL_MACHINE',
'SYSTEM\CurrentControlSet\Control\TimeZoneInformation',
'TimeZoneKeyName',@ServerTimeZone OUT

-- ServerZone to UTC DATETIME
DECLARE @CurrentServerZoneDateTime DATETIME = GETDATE()
DECLARE @UTCDateTime  DATETIME =  @CurrentServerZoneDateTime AT TIME ZONE @ServerTimeZone AT TIME ZONE 'UTC' 
--(OR)
--DECLARE @UTCDateTime  DATETIME = GETUTCDATE()
SELECT @CurrentServerZoneDateTime AS CURRENTZONEDATE,@UTCDateTime AS UTCDATE

-- UTC to ServerZone DATETIME
SET @CurrentServerZoneDateTime = @UTCDateTime AT TIME ZONE 'UTC' AT TIME ZONE @ServerTimeZone
SELECT @UTCDateTime AS UTCDATE,@CurrentServerZoneDateTime AS CURRENTZONEDATE

Note: This(AT TIME ZONE) working on only SQL Server 2016+ and this advantage is automatically considering Daylight while converting to particular Time zone

React Router Pass Param to Component

Use the component:

<Route exact path="/details/:id" component={DetailsPage} />

And you should be able to access the id using:

this.props.match.params.id

Inside the DetailsPage component

Serialize form data to JSON

You can do this:

_x000D_
_x000D_
function onSubmit( form ){_x000D_
  var data = JSON.stringify( $(form).serializeArray() ); //  <-----------_x000D_
_x000D_
  console.log( data );_x000D_
  return false; //don't submit_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<form onsubmit='return onSubmit(this)'>_x000D_
  <input name='user' placeholder='user'><br>_x000D_
  <input name='password' type='password' placeholder='password'><br>_x000D_
  <button type='submit'>Try</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

see this: http://www.json.org/js.html

How can I find the latitude and longitude from address?

The following code will work for google apiv2:

public void convertAddress() {
    if (address != null && !address.isEmpty()) {
        try {
            List<Address> addressList = geoCoder.getFromLocationName(address, 1);
            if (addressList != null && addressList.size() > 0) {
                double lat = addressList.get(0).getLatitude();
                double lng = addressList.get(0).getLongitude();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } // end catch
    } // end if
} // end convertAddress

Where address is the String (123 Testing Rd City State zip) you want to convert to LatLng.

How to pretty print nested dictionaries?

As others have posted, you can use recursion/dfs to print the nested dictionary data and call recursively if it is a dictionary; otherwise print the data.

def print_json(data):
    if type(data) == dict:
            for k, v in data.items():
                    print k
                    print_json(v)
    else:
            print data

Pass arguments into C program from command line

Take a look at the getopt library; it's pretty much the gold standard for this sort of thing.

Docker: How to use bash with an Alpine based docker image?

RUN /bin/sh -c "apk add --no-cache bash"

worked for me.

How to iterate (keys, values) in JavaScript?

You can use JavaScript forEach Loop:

myMap.forEach((value, key) => {
    console.log('value: ', value);
    console.log('key: ', key);
});

Testing if value is a function

If it's a string, you could assume / hope it's always of the form

return SomeFunction(arguments);

parse for the function name, and then see if that function is defined using

if (window[functionName]) { 
    // do stuff
}

How to get the excel file name / path in VBA

this is a simple alternative that gives all responses, Fullname, Path, filename.

Dim FilePath, FileOnly, PathOnly As String

FilePath = ThisWorkbook.FullName
FileOnly = ThisWorkbook.Name
PathOnly = Left(FilePath, Len(FilePath) - Len(FileOnly))

Android Reading from an Input stream efficiently

Another possibility with Guava:

dependency: compile 'com.google.guava:guava:11.0.2'

import com.google.common.io.ByteStreams;
...

String total = new String(ByteStreams.toByteArray(inputStream ));

Javascript onHover event

If you use the JQuery library you can use the .hover() event which merges the mouseover and mouseout event and helps you with the timing and child elements:

$(this).hover(function(){},function(){});

The first function is the start of the hover and the next is the end. Read more at: http://docs.jquery.com/Events/hover

Typescript : Property does not exist on type 'object'

If your object could contain any key/value pairs, you could declare an interface called keyable like :

interface keyable {
    [key: string]: any  
}

then use it as follows :

let countryProviders: keyable[];

or

let countryProviders: Array<keyable>;

What does the "@" symbol do in SQL?

You may be used to MySQL's syntax: Microsoft SQL @ is the same as the MySQL's ?

PHP class not found but it's included

My fail might be useful to someone, so I thought I would post as I finally figured out what the issue was. I was autoloading classes like this:

define("PROJECT_PATH", __DIR__);

// Autoload class definitions
function my_autoload($class) {
    if(preg_match('/\A\w+\Z/', $class)) {
        include(PROJECT_PATH . '/classes/' . $class . '.class.php');
    }
}
spl_autoload_register('my_autoload');

In my /classes folder I had 4 classes:

dbobject.class.php
meeting.class.php
session.class.php
user.class.php

When I later created a new class called:

cscmeeting.class.php

I started getting the can't load DbObject class. I simply could not figure out what was wrong. As soon as I deleted cscmeeting.class.php from the directory, it worked again.

I finally realized that it was looping through the directory alphabetically and prior to cscmeeting.class.php the first class that got loaded was cscmeeting.class.php since it started with D. But when I add the new class, which starts with C it would load that first and it extended the DbObject class. So it chocked every time.

I ended up naming my DbObject class to _dbobject.class.php and it always loads that first.

I realize my naming conventions are probably not great and that's why I was having issues. But I'm new to OOP so doing my best.

Create an array with same element repeated multiple times

No easier way. You need to make a loop and push elements into the array.

Declare global variables in Visual Studio 2010 and VB.NET

Okay. I finally found what actually works to answer the question that seems to be asked;

"When needing many modules and forms, how can I declare a variable to be public to all of them such that they each reference the same variable?"

Amazingly to me, I spent considerable time searching the web for that seemingly simple question, finding nothing but vagueness that left me still getting errors.

But thanks to Cody Gray's link to an example, I was able to discern a proper answer;


Situation; You have multiple Modules and/or Forms and want to reference a particular variable from each or all.

"A" way that works; On one module place the following code (wherein "DefineGlobals" is an arbitrarily chosen name);

Public Module DefineGlobals

Public Parts As Integer                 'Assembled-particle count
Public FirstPrtAff As Long              'Addr into Link List 
End Module

And then in each Module/Form in need of addressing that variable "Parts", place the following code (as an example of the "InitForm2" form);

Public Class InitForm2
Private Sub InitForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    Parts = Parts + 3

End Sub

End Class

And perhaps another Form; Public Class FormX

Sub CreateAff()

   Parts = 1000

End Sub 

 End Class

That type of coding seems to have worked on my VB2008 Express and seems to be all needed at the moment (void of any unknown files being loaded in the background) even though I have found no end to the "Oh btw..." surprise details. And I'm certain a greater degree of standardization would be preferred, but the first task is simply to get something working at all, with or without standards.

Nothing beats exact and well worded, explicit examples.

Thanks again, Cody

How to access the GET parameters after "?" in Express?

Use req.query, for getting he value in query string parameter in the route. Refer req.query. Say if in a route, http://localhost:3000/?name=satyam you want to get value for name parameter, then your 'Get' route handler will go like this :-

app.get('/', function(req, res){
    console.log(req.query.name);
    res.send('Response send to client::'+req.query.name);

});

How to Detect cause of 503 Service Temporarily Unavailable error and handle it?

There is of course some apache log files. Search in your apache configuration files for 'Log' keyword, you'll certainly find plenty of them. Depending on your OS and installation places may vary (in a Typical Linux server it would be /var/log/apache2/[access|error].log).

Having a 503 error in Apache usually means the proxied page/service is not available. I assume you're using tomcat and that means tomcat is either not responding to apache (timeout?) or not even available (down? crashed?). So chances are that it's a configuration error in the way to connect apache and tomcat or an application inside tomcat that is not even sending a response for apache.

Sometimes, in production servers, it can as well be that you get too much traffic for the tomcat server, apache handle more request than the proxyied service (tomcat) can accept so the backend became unavailable.

How to compare types

http://msdn.microsoft.com/en-us/library/system.type.gettype.aspx

Console.WriteLine("typeField is a {0}", typeField.GetType());

which would give you something like

typeField is a String

typeField is a DateTime

or

http://msdn.microsoft.com/en-us/library/58918ffs(v=vs.71).aspx

Facebook Graph API : get larger pictures in one request

Hum... I think I've found a solution.

In fact, in can just request

https://graph.facebook.com/me/friends?fields=id,name

According to http://developers.facebook.com/docs/reference/api/ (section "Pictures"), url of profile's photos can be built with the user id

For example, assuming user id is in $id :

"http://graph.facebook.com/$id/picture?type=square"
"http://graph.facebook.com/$id/picture?type=small"
"http://graph.facebook.com/$id/picture?type=normal"
"http://graph.facebook.com/$id/picture?type=large"

But it's not the final image URL, so if someone have a better solution, i would be glad to know :)

Troubleshooting BadImageFormatException

When building apps for 32-bit or 64-bit platform (My experience is with Visual Studio 2010), don't rely on the Configuration Manager to set the correct platform for the executable. Even if the CM has x86 selected for the application, check the project properties (Build tab): it might still say "Any CPU" there. And if you run an "Any CPU" executable on a 64-bit platform, it will run in 64-bit mode and refuse to load your accompanying DLLs that were built for the x86 platform.

How to get a table creation script in MySQL Workbench?

  1. Open MySQL Workbench (6.3 CE)
  2. In "Navigator" select "Management"
  3. Then select "Data Export" (Here select the table whose create script you wish to export)
  4. In Drop down select "Dump Structure and Data"
  5. Select checkbox "Include Create Schema"
  6. Click the button "Start Export" Once export is complete it will display the location in which exported file is dumped in your system. Go to the location and open the exported file to find table creation script.

Or Check https://dev.mysql.com/doc/workbench/en/wb-admin-export-import-management.html

How to sort a HashSet?

Based on the answer given by @LazerBanana i will put my own example of a Set sorted by the Id of the Object:

Set<Clazz> yourSet = [...];

yourSet.stream().sorted(new Comparator<Clazz>() {
    @Override
    public int compare(Clazz o1, Clazz o2) {
        return o1.getId().compareTo(o2.getId());
    }
}).collect(Collectors.toList()); // Returns the sorted List (using toSet() wont work)

Apply Calibri (Body) font to text

If there is space between the letters of the font, you need to use quote.

font-family:"Calibri (Body)";

How to get ip address of a server on Centos 7 in bash

Enter the command ip addr at the console

enter image description here

How to return a complex JSON response with Node.js?

[Edit] After reviewing the Mongoose documentation, it looks like you can send each query result as a separate chunk; the web server uses chunked transfer encoding by default so all you have to do is wrap an array around the items to make it a valid JSON object.

Roughly (untested):

app.get('/users/:email/messages/unread', function(req, res, next) {
  var firstItem=true, query=MessageInfo.find(/*...*/);
  res.writeHead(200, {'Content-Type': 'application/json'});
  query.each(function(docs) {
    // Start the JSON array or separate the next element.
    res.write(firstItem ? (firstItem=false,'[') : ',');
    res.write(JSON.stringify({ msgId: msg.fileName }));
  });
  res.end(']'); // End the JSON array and response.
});

Alternatively, as you mention, you can simply send the array contents as-is. In this case the response body will be buffered and sent immediately, which may consume a large amount of additional memory (above what is required to store the results themselves) for large result sets. For example:

// ...
var query = MessageInfo.find(/*...*/);
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(query.map(function(x){ return x.fileName })));

Error: invalid operands of types ‘const char [35]’ and ‘const char [2]’ to binary ‘operator+’

In line 2, there's a std::string involved (name). There are operations defined for char[] + std::string, std::string + char[], etc. "Hello " + name gives a std::string, which is added to " you are ", giving another string, etc.

In line 3, you're saying

char[] + char[] + char[]

and you can't just add arrays to each other.

Get the latest record with filter in Django

You can do comparison with this down here.

image

latest('created') is same as order_by('-created').first() Please correct me if I am wrong

How do I "select Android SDK" in Android Studio?

Give SDK path in local.properties file as

sdk.dir=C\:\\Users\\System43\\AppData\\Local\\Android\\sdk

and give latest version in compilesdk in gradle file.

How to define a Sql Server connection string to use in VB.NET?

Standard Security:

Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;

Trusted Connection:

Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;

will be glad if it helps.

Regards.

How do I keep a label centered in WinForms?

You could try out the following code snippet:

private Point CenterOfMenuPanel<T>(T control, int height=0) where T:Control {
    Point center = new Point( 
        MenuPanel.Size.Width / 2 - control.Width * 2,
        height != 0 ? height : MenuPanel.Size.Height / 2 - control.Height / 2);

    return center;
}

It's Really Center

enter image description here

Change the color of a bullet in a html list?

The bullet gets its color from the text. So if you want to have a different color bullet than text in your list you'll have to add some markup.

Wrap the list text in a span:

<ul>
  <li><span>item #1</span></li>
  <li><span>item #2</span></li>
  <li><span>item #3</span></li>
</ul>

Then modify your style rules slightly:

li {
  color: red; /* bullet color */
}
li span {
  color: black; /* text color */
}

How do I print the percent sign(%) in c

there's no explanation in this topic why to print a percentage sign one must type %% and not for example escape character with percentage - \%.

from comp.lang.c FAQ list · Question 12.6 :

The reason it's tricky to print % signs with printf is that % is essentially printf's escape character. Whenever printf sees a %, it expects it to be followed by a character telling it what to do next. The two-character sequence %% is defined to print a single %.

To understand why \% can't work, remember that the backslash \ is the compiler's escape character, and controls how the compiler interprets source code characters at compile time. In this case, however, we want to control how printf interprets its format string at run-time. As far as the compiler is concerned, the escape sequence \% is undefined, and probably results in a single % character. It would be unlikely for both the \ and the % to make it through to printf, even if printf were prepared to treat the \ specially.

so the reason why one must type printf("%%"); to print single % is that's what is defined in printf function. % is an escape character of printf's, and \ of compiler.

Android device chooser - My device seems offline

Removing the USB cable for about 5 seconds and reconnecting also solves the problem. Maybe you have to try one or two times.

Count the number of Occurrences of a Word in a String

The string contains that string all the time when looping through it. You don't want to ++ because what this is doing right now is just getting the length of the string if it contains " "male cat"

You need to indexOf() / substring()

Kind of get what i am saying?

SSIS cannot convert because a potential loss of data

I had the same issue, multiple data type values in single column, package load only numeric values. Remains all it updated as null.

Solution

To fix this changing the excel data type is one of the solution. In Excel Copy the column data and paste in different file. Delete that column and insert new column as Text datatype and paste that copied data in new column.

Now in ssis package delete and recreate the Excel source and destination table change the column data type as varchar.

This will work.

Trying to get the average of a count resultset

You just can put your query as a subquery:

SELECT avg(count)
  FROM 
    (
    SELECT COUNT (*) AS Count
      FROM Table T
     WHERE T.Update_time =
               (SELECT MAX (B.Update_time )
                  FROM Table B
                 WHERE (B.Id = T.Id))
    GROUP BY T.Grouping
    ) as counts

Edit: I think this should be the same:

SELECT count(*) / count(distinct T.Grouping)
  FROM Table T
 WHERE T.Update_time =
           (SELECT MAX (B.Update_time)
              FROM Table B
             WHERE (B.Id = T.Id))

regular expression to match exactly 5 digits

I am reading a text file and want to use regex below to pull out numbers with exactly 5 digit, ignoring alphabets.

Try this...

var str = 'f 34 545 323 12345 54321 123456',
    matches = str.match(/\b\d{5}\b/g);

console.log(matches); // ["12345", "54321"]

jsFiddle.

The word boundary \b is your friend here.

Update

My regex will get a number like this 12345, but not like a12345. The other answers provide great regexes if you require the latter.

How to replace all special character into a string using C#

Yes, you can use regular expressions in C#.

Using regular expressions with C#:

using System.Text.RegularExpressions;

string your_String = "Hello@Hello&Hello(Hello)";
string my_String =  Regex.Replace(your_String, @"[^0-9a-zA-Z]+", ",");

sql select with column name like

Blorgbeard had a great answer for SQL server. If you have a MySQL server like mine then the following will allow you to select the information from columns where the name is like some key phrase. You just have to substitute the table name, database name, and keyword.

SET @columnnames = (SELECT concat("`",GROUP_CONCAT(`COLUMN_NAME` SEPARATOR "`, `"),"`") 
FROM `INFORMATION_SCHEMA`.`COLUMNS` 
WHERE `TABLE_SCHEMA`='your_database' 
    AND `TABLE_NAME`='your_table'
    AND COLUMN_NAME LIKE "%keyword%");

SET @burrito = CONCAT("SELECT ",@columnnames," FROM your_table");

PREPARE result FROM @burrito;
EXECUTE result;

AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https

If for whatever reason you cannot have the files hosted from a webserver and still need some sort of way of loading partials, you can resort to using the ngTemplate directive.

This way, you can include your markup inside script tags in your index.html file and not have to include the markup as part of the actual directive.

Add this to your index.html

<script type='text/ng-template' id='tpl-productColour'>
 <div class="list-group-item">
    <h3>Hello <em class="pull-right">Brother</em></h3>
</div>
</script>

Then, in your directive:

app.directive('productColor', function() {
      return {
          restrict: 'E', //Element Directive
          //template: 'tpl-productColour'
          templateUrl: 'tpl-productColour'
      };
   }
  );

TypeError: tuple indices must be integers, not str

The Problem is how you access row

Specifically row["waocs"] and row["pool_number"] of ocs[row["pool_number"]]=int(row["waocs"])

If you look up the official-documentation of fetchall() you find.

The method fetches all (or all remaining) rows of a query result set and returns a list of tuples.

Therefore you have to access the values of rows with row[__integer__] like row[0]

CSS transition shorthand with multiple properties?

I made it work with this:

.element {
   transition: height 3s ease-out, width 5s ease-in;
}

In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?

WebSockets is definitely the future.

Long polling is a dirty workaround to prevent creating connections for each request like AJAX does -- but long polling was created when WebSockets didn't exist. Now due to WebSockets, long polling is going away.

WebRTC allows for peer-to-peer communication.

I recommend learning WebSockets.

Comparison:

of different communication techniques on the web

  • AJAX - requestresponse. Creates a connection to the server, sends request headers with optional data, gets a response from the server, and closes the connection. Supported in all major browsers.

  • Long poll - requestwaitresponse. Creates a connection to the server like AJAX does, but maintains a keep-alive connection open for some time (not long though). During connection, the open client can receive data from the server. The client has to reconnect periodically after the connection is closed, due to timeouts or data eof. On server side it is still treated like an HTTP request, same as AJAX, except the answer on request will happen now or some time in the future, defined by the application logic. support chart (full) | wikipedia

  • WebSockets - clientserver. Create a TCP connection to the server, and keep it open as long as needed. The server or client can easily close the connection. The client goes through an HTTP compatible handshake process. If it succeeds, then the server and client can exchange data in both directions at any time. It is efficient if the application requires frequent data exchange in both ways. WebSockets do have data framing that includes masking for each message sent from client to server, so data is simply encrypted. support chart (very good) | wikipedia

  • WebRTC - peerpeer. Transport to establish communication between clients and is transport-agnostic, so it can use UDP, TCP or even more abstract layers. This is generally used for high volume data transfer, such as video/audio streaming, where reliability is secondary and a few frames or reduction in quality progression can be sacrificed in favour of response time and, at least, some data transfer. Both sides (peers) can push data to each other independently. While it can be used totally independent from any centralised servers, it still requires some way of exchanging endPoints data, where in most cases developers still use centralised servers to "link" peers. This is required only to exchange essential data for establishing a connection, after which a centralised server is not required. support chart (medium) | wikipedia

  • Server-Sent Events - clientserver. Client establishes persistent and long-term connection to server. Only the server can send data to a client. If the client wants to send data to the server, it would require the use of another technology/protocol to do so. This protocol is HTTP compatible and simple to implement in most server-side platforms. This is a preferable protocol to be used instead of Long Polling. support chart (good, except IE) | wikipedia

Advantages:

The main advantage of WebSockets server-side, is that it is not an HTTP request (after handshake), but a proper message based communication protocol. This enables you to achieve huge performance and architecture advantages. For example, in node.js, you can share the same memory for different socket connections, so they can each access shared variables. Therefore, you don't need to use a database as an exchange point in the middle (like with AJAX or Long Polling with a language like PHP). You can store data in RAM, or even republish between sockets straight away.

Security considerations

People are often concerned about the security of WebSockets. The reality is that it makes little difference or even puts WebSockets as better option. First of all, with AJAX, there is a higher chance of MITM, as each request is a new TCP connection that is traversing through internet infrastructure. With WebSockets, once it's connected it is far more challenging to intercept in between, with additionally enforced frame masking when data is streamed from client to server as well as additional compression, which requires more effort to probe data. All modern protocols support both: HTTP and HTTPS (encrypted).

P.S.

Remember that WebSockets generally have a very different approach of logic for networking, more like real-time games had all this time, and not like http.

Char array in a struct - incompatible assignment?

You can use strcpy to populate it. You can also initialize it from another struct.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct name {
    char first[20];
    char last[20];
};

int main() {
    struct name sara;
    struct name other;

    strcpy(sara.first,"Sara");
    strcpy(sara.last, "Black");

    other = sara;

    printf("struct: %s\t%s\n", sara.first, sara.last);
    printf("other struct: %s\t%s\n", other.first, other.last);

}

how to make negative numbers into positive

a *= (-1);

problem solved. If there is a smaller solution for a problem, then why you guys going for a complex solution. Please direct people to use the base logic also because then only the people can train their programming logic.

jQuery multiple events to trigger the same function

The answer by Tatu is how I would intuitively do it, but I have experienced some problems in Internet Explorer with this way of nesting/binding the events, even though it is done through the .on() method.

I havn't been able to pinpoint exactly which versions of jQuery this is the problem with. But I sometimes see the problem in the following versions:

  • 2.0.2
  • 1.10.1
  • 1.6.4
  • Mobile 1.3.0b1
  • Mobile 1.4.2
  • Mobile 1.2.0

My workaround have been to first define the function,

function myFunction() {
    ...
}

and then handle the events individually

// Call individually due to IE not handling binds properly
$(window).on("scroll", myFunction);
$(window).on("resize", myFunction);

This is not the prettiest solution, but it works for me, and I thought I would put it out there to help others that might stumble upon this issue

Retrieving the first digit of a number

This example works for any double, not just positive integers and takes into account negative numbers or those less than one. For example, 0.000053 would return 5.

private static int getMostSignificantDigit(double value) {
    value = Math.abs(value);
    if (value == 0) return 0;
    while (value < 1) value *= 10;
    char firstChar = String.valueOf(value).charAt(0);
    return Integer.parseInt(firstChar + "");
}

To get the first digit, this sticks with String manipulation as it is far easier to read.

Redirecting to a page after submitting form in HTML

What you could do is, a validation of the values, for example:

if the value of the input of fullanme is greater than some value length and if the value of the input of address is greater than some value length then redirect to a new page, otherwise shows an error for the input.

_x000D_
_x000D_
// We access to the inputs by their id's
let fullname = document.getElementById("fullname");
let address = document.getElementById("address");

// Error messages
let errorElement = document.getElementById("name_error");
let errorElementAddress = document.getElementById("address_error");

// Form
let contactForm = document.getElementById("form");

// Event listener
contactForm.addEventListener("submit", function (e) {
  let messageName = [];
  let messageAddress = [];
  
    if (fullname.value === "" || fullname.value === null) {
    messageName.push("* This field is required");
  }

  if (address.value === "" || address.value === null) {
    messageAddress.push("* This field is required");
  }

  // Statement to shows the errors
  if (messageName.length || messageAddress.length > 0) {
    e.preventDefault();
    errorElement.innerText = messageName;
    errorElementAddress.innerText = messageAddress;
  }
  
   // if the values length is filled and it's greater than 2 then redirect to this page
    if (
    (fullname.value.length > 2,
    address.value.length > 2)
  ) {
    e.preventDefault();
    window.location.assign("https://www.google.com");
  }

});
_x000D_
.error {
  color: #000;
}

.input-container {
  display: flex;
  flex-direction: column;
  margin: 1rem auto;
}
_x000D_
<html>
  <body>
    <form id="form" method="POST">
    <div class="input-container">
    <label>Full name:</label>
      <input type="text" id="fullname" name="fullname">
      <div class="error" id="name_error"></div>
      </div>
      
      <div class="input-container">
      <label>Address:</label>
      <input type="text" id="address" name="address">
      <div class="error" id="address_error"></div>
      </div>
      <button type="submit" id="submit_button" value="Submit request" >Submit</button>
    </form>
  </body>
</html>
_x000D_
_x000D_
_x000D_

TypeError: unhashable type: 'numpy.ndarray'

Your variable energies probably has the wrong shape:

>>> from numpy import array
>>> set([1,2,3]) & set(range(2, 10))
set([2, 3])
>>> set(array([1,2,3])) & set(range(2,10))
set([2, 3])
>>> set(array([[1,2,3],])) & set(range(2,10))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'numpy.ndarray'

And that's what happens if you read columnar data using your approach:

>>> data
array([[  1.,   2.,   3.],
       [  3.,   4.,   5.],
       [  5.,   6.,   7.],
       [  8.,   9.,  10.]])
>>> hsplit(data,3)[0]
array([[ 1.],
       [ 3.],
       [ 5.],
       [ 8.]])

Probably you can simply use

>>> data[:,0]
array([ 1.,  3.,  5.,  8.])

instead.

(P.S. Your code looks like it's undecided about whether it's data or elementdata. I've assumed it's simply a typo.)

Python equivalent to 'hold on' in Matlab

Just call plt.show() at the end:

import numpy as np
import matplotlib.pyplot as plt

plt.axis([0,50,60,80])
for i in np.arange(1,5):
    z = 68 + 4 * np.random.randn(50)
    zm = np.cumsum(z) / range(1,len(z)+1)
    plt.plot(zm)    

n = np.arange(1,51)
su = 68 + 4 / np.sqrt(n)
sl = 68 - 4 / np.sqrt(n)

plt.plot(n,su,n,sl)

plt.show()

malloc an array of struct pointers

IMHO, this looks better:

Chess *array = malloc(size * sizeof(Chess)); // array of pointers of size `size`

for ( int i =0; i < SOME_VALUE; ++i )
{
    array[i] = (Chess) malloc(sizeof(Chess));
}

MySQL: Cloning a MySQL database on the same MySql instance

You could use (in pseudocode):

FOREACH tbl IN db_a:
    CREATE TABLE db_b.tbl LIKE db_a.tbl;
    INSERT INTO db_b.tbl SELECT * FROM db_a.tbl;

The reason I'm not using the CREATE TABLE ... SELECT ... syntax is to preserve indices. Of course this only copies tables. Views and procedures are not copied, although it can be done in the same manner.

See CREATE TABLE.

MongoDB: exception in initAndListen: 20 Attempted to create a lock file on a read-only directory: /data/db, terminating

Nice solutions, but I wonder why nobody is giving the solution for windows.

If you are using windows you just have to "Run as Administrator" the cmd.

Return a value if no rows are found in Microsoft tSQL

I liked James Jenkins reply with the ISNULL check, but I think he meant IFNULL. ISNULL does not have a second parameter like his syntax, but IFNULL has the second parameter after the expression being checked to substitute if a NULL is found.

PRINT statement in T-SQL

I recently ran into this, and it ended up being because I had a convert statement on a null variable. Since that was causing errors, the entire print statement was rendering as null, and not printing at all.

Example - This will fail:

declare @myID int=null
print 'First Statement: ' + convert(varchar(4), @myID)

Example - This will print:

declare @myID int=null
print 'Second Statement: ' +  coalesce(Convert(varchar(4), @myID),'@myID is null')

Complexities of binary tree traversals

Depth first traversal of a binary tree is of order O(n).

Algo -- <b>
    PreOrderTrav():-----------------T(n)<b>
    if root is null---------------O(1)<b>
      return null-----------------O(1)<b>
    else:-------------------------O(1)<b>
      print(root)-----------------O(1)<b>
      PreOrderTrav(root.left)-----T(n/2)<b>
      PreOrderTrav(root.right)----T(n/2)<b>

If the time complexity of the algo is T(n) then it can be written as T(n) = 2*T(n/2) + O(1). If we apply back substitution we will get T(n) = O(n).

How to find the type of an object in Go?

I found 3 ways to return a variable's type at runtime:

Using string formatting

func typeof(v interface{}) string {
    return fmt.Sprintf("%T", v)
}

Using reflect package

func typeof(v interface{}) string {
    return reflect.TypeOf(v).String()
}

Using type assertions

func typeof(v interface{}) string {
    switch v.(type) {
    case int:
        return "int"
    case float64:
        return "float64"
    //... etc
    default:
        return "unknown"
    }
}

Every method has a different best use case:

  • string formatting - short and low footprint (not necessary to import reflect package)

  • reflect package - when need more details about the type we have access to the full reflection capabilities

  • type assertions - allows grouping types, for example recognize all int32, int64, uint32, uint64 types as "int"

Increasing (or decreasing) the memory available to R processes

To increase the amount of memory allocated to R you can use memory.limit

memory.limit(size = ...)

Or

memory.size(max = ...)

About the arguments

  • size - numeric. If NA report the memory limit, otherwise request a new limit, in Mb. Only values of up to 4095 are allowed on 32-bit R builds, but see ‘Details’.
  • max - logical. If TRUE the maximum amount of memory obtained from the OS is reported, if FALSE the amount currently in use, if NA the memory limit.

iReport not starting using JRE 8

iReport does not work with java 8.

  • if not yet installed, download and install java 7
  • find the install dir of your iReport and open the file: ireport.conf

(you will find it here: iReport-x.x.x\etc\ )

change this line:

#jdkhome="/path/to/jdk"

to this (if not this is your java 7 install dir then replace the parameter value between ""s with your installed java 7's path):

jdkhome="C:\Program Files\Java\jdk1.7.0_67"

How to Batch Rename Files in a macOS Terminal?

In your specific case you can use the following bash command (bash is the default shell on macOS):

for f in *.png; do echo mv "$f" "${f/_*_/_}"; done

Note: If there's a chance that your filenames start with -, place -- before them[1]:
mv -- "$f" "${f/_*_/_}"

Note: echo is prepended to mv so as to perform a dry run. Remove it to perform actual renaming.

You can run it from the command line or use it in a script.

  • "${f/_*_/_}" is an application of bash parameter expansion: the (first) substring matching pattern _*_ is replaced with literal _, effectively cutting the middle token from the name.
  • Note that _*_ is a pattern (a wildcard expression, as also used for globbing), not a regular expression (to learn about patterns, run man bash and search for Pattern Matching).

If you find yourself batch-renaming files frequently, consider installing a specialized tool such as the Perl-based rename utility. On macOS you can install it using popular package manager Homebrew as follows:

brew install rename

Here's the equivalent of the command at the top using rename:

rename -n -e 's/_.*_/_/'  *.png

Again, this command performs a dry run; remove -n to perform actual renaming.

  • Similar to the bash solution, s/.../.../ performs text substitution, but - unlike in bash - true regular expressions are used.

[1] The purpose of special argument --, which is supported by most utilities, is to signal that subsequent arguments should be treated as operands (values), even if they look like options due to starting with -, as Jacob C. notes.

git repo says it's up-to-date after pull but files are not updated

Try this:

 git fetch --all
 git reset --hard origin/master

Explanation:

git fetch downloads the latest from remote without trying to merge or rebase anything.

Please let me know if you have any questions!

How to make a <div> always full screen?

Unfortunately, the height property in CSS is not as reliable as it should be. Therefore, Javascript will have to be used to set the height style of the element in question to the height of the users viewport. And yes, this can be done without absolute positioning...

<!DOCTYPE html>

<html>
  <head>
    <title>Test by Josh</title>
    <style type="text/css">
      * { padding:0; margin:0; }
      #test { background:#aaa; height:100%; width:100%; }
    </style>
    <script type="text/javascript">
      window.onload = function() {
        var height = getViewportHeight();

        alert("This is what it looks like before the Javascript. Click OK to set the height.");

        if(height > 0)
          document.getElementById("test").style.height = height + "px";
      }

      function getViewportHeight() {
        var h = 0;

        if(self.innerHeight)
          h = window.innerHeight;
        else if(document.documentElement && document.documentElement.clientHeight)
          h = document.documentElement.clientHeight;
        else if(document.body) 
          h = document.body.clientHeight;

        return h;
      }
    </script>
  </head>
  <body>
    <div id="test">
      <h1>Test</h1>
    </div>
  </body>
</html>

array filter in python?

set(A)-set(subset_of_A) gives your the intended result set, but it won't retain the original order. The following is order preserving:

[a for a in A if not a in subset_of_A]

Using underscores in Java variables and method names

  • I happen to like leading underscores for (private) instance variables, it seems easier to read and distinguish.Of course this thing can get you into trouble with edge cases (e.g. public instance variables (not common, I know) - either way you name them you're arguably breaking your naming convention:
  • private int _my_int; public int myInt;? _my_int? )

-as much as I like the _style of this and think it's readable I find it's arguably more trouble than it's worth, as it's uncommon and it's likely not to match anything else in the codebase you're using.

-automated code generation (e.g. eclipse's generate getters, setters) aren't likely to understand this so you'll have to fix it by hand or muck with eclipse enough to get it to recognize.

Ultimately, you're going against the rest of the (java) world's prefs and are likely to have some annoyances from that. And as previous posters have mentioned, consistency in the codebase trumps all of the above issues.

How do you express binary literals in Python?

>>> print int('01010101111',2)
687
>>> print int('11111111',2)
255

Another way.

Add hover text without javascript like we hover on a user's reputation

This can also be done in CSS, for more customisability:

_x000D_
_x000D_
.hoverable {
  position: relative;
}

.hoverable>.hoverable__tooltip {
  display: none;
}

.hoverable:hover>.hoverable__tooltip {
  display: inline;
  position: absolute;
  top: 1em;
  left: 1em;
  background: #888;
  border: 1px solid black;
}
_x000D_
<div class="hoverable">
  <span class="hoverable__main">Main text</span>
  <span class="hoverable__tooltip">Hover text</span>
</div>
_x000D_
_x000D_
_x000D_

(Obviously, styling can be improved)

Access denied; you need (at least one of) the SUPER privilege(s) for this operation

Need to set "on" server parameter "log_bin_trust_function_creators" on server side. This one you can easily find on left side blade if it is azure maria db.

How to use OR condition in a JavaScript IF statement?

here is my example:

if(userAnswer==="Yes"||"yes"||"YeS"){
 console.log("Too Bad!");   
}

This says that if the answer is Yes yes or YeS than the same thing will happen

Search an Oracle database for tables with specific column names?

The data you want is in the "cols" meta-data table:

SELECT * FROM COLS WHERE COLUMN_NAME = 'id'

This one will give you a list of tables that have all of the columns you want:

select distinct
  C1.TABLE_NAME
from
  cols c1
  inner join
  cols c2
  on C1.TABLE_NAME = C2.TABLE_NAME
  inner join
  cols c3
  on C2.TABLE_NAME = C3.TABLE_NAME
  inner join
  cols c4
  on C3.TABLE_NAME = C4.TABLE_NAME  
  inner join
  tab t
  on T.TNAME = C1.TABLE_NAME
where T.TABTYPE = 'TABLE' --could be 'VIEW' if you wanted
  and upper(C1.COLUMN_NAME) like upper('%id%')
  and upper(C2.COLUMN_NAME) like upper('%fname%')
  and upper(C3.COLUMN_NAME) like upper('%lname%')
  and upper(C4.COLUMN_NAME) like upper('%address%')  

To do this in a different schema, just specify the schema in front of the table, as in

SELECT * FROM SCHEMA1.COLS WHERE COLUMN_NAME LIKE '%ID%';

If you want to combine the searches of many schemas into one output result, then you could do this:

SELECT DISTINCT
  'SCHEMA1' AS SCHEMA_NAME
 ,TABLE_NAME
FROM SCHEMA1.COLS
WHERE COLUMN_NAME LIKE '%ID%'
UNION
SELECT DISTINCT
  'SCHEMA2' AS SCHEMA_NAME
 ,TABLE_NAME
FROM SCHEMA2.COLS
WHERE COLUMN_NAME LIKE '%ID%'

Convert A String (like testing123) To Binary In Java

public class HexadecimalToBinaryAndLong{
  public static void main(String[] args) throws IOException{
    BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter the hexa value!");
    String hex = bf.readLine();
    int i = Integer.parseInt(hex);               //hex to decimal
    String by = Integer.toBinaryString(i);       //decimal to binary
    System.out.println("This is Binary: " + by);
    }
}

How to remove padding around buttons in Android?

My solution was set to 0 the insetTop and insetBottom properties.

<android.support.design.button.MaterialButton
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:insetTop="0dp"
        android:insetBottom="0dp"
        android:text="@string/view_video"
        android:textColor="@color/white"/>

Maven fails to find local artifact

I had DependencyResolutionException in Ubuntu Linux when I've installed local artifacts via a shell script. The solution was to delete the local artifacts and install them again "manually" - calling mvn install:install-file via terminal.

How to launch an Activity from another Application in Android

Steps to launch new activity as follows:

1.Get intent for package

2.If intent is null redirect user to playstore

3.If intent is not null open activity

public void launchNewActivity(Context context, String packageName) {
    Intent intent = null;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.CUPCAKE) {
        intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
    }
    if (intent == null) {
        try {
            intent = new Intent(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setData(Uri.parse("market://details?id=" + packageName));
            context.startActivity(intent);
        } catch (android.content.ActivityNotFoundException anfe) {
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + packageName)));
        }
    } else {
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }
}

JDK was not found on the computer for NetBeans 6.5

For Netbeans 9.0

1)open netbeans.conf file using notepad inside etc folder

2)Search "netbeans_jdkhome" line and uncomment it by removing '#' from start

3)locate your jdk and replace file path

For example

enter image description here

ReferenceError: document is not defined (in plain JavaScript)

Try adding the script element just before the /body tag like that

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" type="text/css" href="css/quiz.css" />
</head>
<body>

    <div id="divid">Next</div>
    <script type="text/javascript" src="js/quiz.js"></script>
</body>
</html>