Programs & Examples On #Ref parameters

JavaScript string encryption and decryption?

I created an insecure but simple text cipher/decipher util. No dependencies with any external library.

These are the functions

const cipher = salt => {
    const textToChars = text => text.split('').map(c => c.charCodeAt(0));
    const byteHex = n => ("0" + Number(n).toString(16)).substr(-2);
    const applySaltToChar = code => textToChars(salt).reduce((a,b) => a ^ b, code);

    return text => text.split('')
        .map(textToChars)
        .map(applySaltToChar)
        .map(byteHex)
        .join('');
}

const decipher = salt => {
    const textToChars = text => text.split('').map(c => c.charCodeAt(0));
    const applySaltToChar = code => textToChars(salt).reduce((a,b) => a ^ b, code);
    return encoded => encoded.match(/.{1,2}/g)
        .map(hex => parseInt(hex, 16))
        .map(applySaltToChar)
        .map(charCode => String.fromCharCode(charCode))
        .join('');
}

And you can use them as follows:

// To create a cipher
const myCipher = cipher('mySecretSalt')

//Then cipher any text:
myCipher('the secret string')   // --> "7c606d287b6d6b7a6d7c287b7c7a61666f"

//To decipher, you need to create a decipher and use it:
const myDecipher = decipher('mySecretSalt')
myDecipher("7c606d287b6d6b7a6d7c287b7c7a61666f")    // --> 'the secret string'

Press TAB and then ENTER key in Selenium WebDriver

WebElement webElement = driver.findElement(By.xpath(""));

//Enter the xpath or ID.

     webElement.sendKeys("");

//Input the string to pass.

     webElement.sendKeys(Keys.TAB);

//This will enter the string which you want to pass and will press "Tab" button .

When should the xlsm or xlsb formats be used?

Just for posterity, here's the text from several external sources regarding the Excel file formats. Some of these have been mentioned in other answers to this question but without reproducing the essential content.

1. From Doug Mahugh, August 22, 2006:

...the new XLSB binary format. Like Open XML, it’s a full-fidelity file format that can store anything you can create in Excel, but the XLSB format is optimized for performance in ways that aren’t possible with a pure XML format.

The XLSB format (also sometimes referred to as BIFF12, as in “binary file format for Office 12”) uses the same Open Packaging Convention used by the Open XML formats and XPS. So it’s basically a ZIP container, and you can open it with any ZIP tool to see what’s inside. But instead of .XML parts within the package, you’ll find .BIN parts...

This article also refers to documentation about the BIN format, too lengthy to reproduce here.

2. From MSDN Archive, August 29, 2006 which in turn cites an already-missing blog post regarding the XLSB format:

Even though we’ve done a lot of work to make sure that our XML formats open quickly and efficiently, this binary format is still more efficient for Excel to open and save, and can lead to some performance improvements for workbooks that contain a lot of data, or that would require a lot of XML parsing during the Open process. (In fact, we’ve found that the new binary format is faster than the old XLS format in many cases.) Also, there is no macro-free version of this file format – all XLSB files can contain macros (VBA and XLM). In all other respects, it is functionally equivalent to the XML file format above:

File size – file size of both formats is approximately the same, since both formats are saved to disk using zip compression Architecture – both formats use the same packaging structure, and both have the same part-level structures. Feature support – both formats support exactly the same feature set Runtime performance – once loaded into memory, the file format has no effect on application/calculation speed Converters – both formats will have identical converter support

How to read the value of a private field from a different class in Java?

One other option that hasn't been mentioned yet: use Groovy. Groovy allows you to access private instance variables as a side effect of the design of the language. Whether or not you have a getter for the field, you can just use

def obj = new IWasDesignedPoorly()
def hashTable = obj.getStuffIWant()

Formula to determine brightness of RGB color

To determine the brightness of a color with R, I convert the RGB system color in HSV system color.

In my script, I use the HEX system code before for other reason, but you can start also with RGB system code with rgb2hsv {grDevices}. The documentation is here.

Here is this part of my code:

 sample <- c("#010101", "#303030", "#A6A4A4", "#020202", "#010100")
 hsvc <-rgb2hsv(col2rgb(sample)) # convert HEX to HSV
 value <- as.data.frame(hsvc) # create data.frame
 value <- value[3,] # extract the information of brightness
 order(value) # ordrer the color by brightness

Writing a new line to file in PHP (line feed)

Replace '\n' with "\n". The escape sequence is not recognized when you use '.

See the manual.

For the question of how to write line endings, see the note here. Basically, different operating systems have different conventions for line endings. Windows uses "\r\n", unix based operating systems use "\n". You should stick to one convention (I'd chose "\n") and open your file in binary mode (fopen should get "wb", not "w").

How to show google.com in an iframe?

You can solve using Google CSE (Custom Searche Engine), which can be easily inserted into an iframe. You can create your own search engine, that search selected sites or also in entire Google's database.

The results can be styled as you prefer, also similar to Google style. Google CSE works with web and images search.

google.php

<script>
  (function() {
    var cx = 'xxxxxxxxxxxxxxxxxxxxxx';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(gcse, s);
  })();
</script>
<gcse:searchresults-only></gcse:searchresults-only>

yourpage.php

<iframe src="google.php?q=<?php echo urlencode('your query'); ?>"></iframe>

How to Ping External IP from Java Android

Pink ip Address

  public static int pingHost(String host, int timeout) throws IOException,
        InterruptedException {
    Runtime runtime = Runtime.getRuntime();
    timeout /= 1000;
    String cmd = "ping -c 1 -W " + timeout + " " + host;
    Process proc = runtime.exec(cmd);
    Log.d(TAG, cmd);
    proc.waitFor();
    int exit = proc.exitValue();
    return exit;
}
   Ping a host and return an int value of 0 or 1 or 2 0=success, 1=fail,
   * 2=error

Android Studio - How to Change Android SDK Path

Make your life easy with shortcut keys
ctrl+shift+alt+S
or

by going to file->project structure:
enter image description here

it will open this window, where you can select your SDK
enter image description here

How to preview an image before and after upload?

On input type=file add an event onchange="preview()"

For the function preview() type:

thumb.src=URL.createObjectURL(event.target.files[0]);

Live example:

_x000D_
_x000D_
function preview() {
   thumb.src=URL.createObjectURL(event.target.files[0]);
}
_x000D_
<form>
    <input type="file" onchange="preview()">
    <img id="thumb" src="" width="150px"/>
</form>
_x000D_
_x000D_
_x000D_

How can I list the scheduled jobs running in my database?

Because the SCHEDULER_ADMIN role is a powerful role allowing a grantee to execute code as any user, you should consider granting individual Scheduler system privileges instead. Object and system privileges are granted using regular SQL grant syntax. An example is if the database administrator issues the following statement:

GRANT CREATE JOB TO scott;

After this statement is executed, scott can create jobs, schedules, or programs in his schema.

copied from http://docs.oracle.com/cd/B19306_01/server.102/b14231/schedadmin.htm#i1006239

Summing radio input values

Your javascript is executed before the HTML is generated, so it doesn't "see" the ungenerated INPUT elements. For jQuery, you would either stick the Javascript at the end of the HTML or wrap it like this:

<script type="text/javascript">   $(function() { //jQuery trick to say after all the HTML is parsed.     $("input[type=radio]").click(function() {       var total = 0;       $("input[type=radio]:checked").each(function() {         total += parseFloat($(this).val());       });        $("#totalSum").val(total);     });   }); </script> 

EDIT: This code works for me

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body>   <strong>Choose a base package:</strong>   <input id="item_0" type="radio" name="pkg" value="1942" />Base Package 1 - $1942   <input id="item_1" type="radio" name="pkg" value="2313" />Base Package 2 - $2313   <input id="item_2" type="radio" name="pkg" value="2829" />Base Package 3 - $2829   <strong>Choose an add on:</strong>   <input id="item_10" type="radio" name="ext" value="0" />No add-on - +$0   <input id="item_12" type="radio" name="ext" value="2146" />Add-on 1 - (+$2146)   <input id="item_13" type="radio" name="ext" value="2455" />Add-on 2 - (+$2455)   <input id="item_14" type="radio" name="ext" value="2764" />Add-on 3 - (+$2764)   <input id="item_15" type="radio" name="ext" value="3073" />Add-on 4 - (+$3073)   <input id="item_16" type="radio" name="ext" value="3382" />Add-on 5 - (+$3382)   <input id="item_17" type="radio" name="ext" value="3691" />Add-on 6 - (+$3691)   <strong>Your total is:</strong>   <input id="totalSum" type="text" name="totalSum" readonly="readonly" size="5" value="" />   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>   <script type="text/javascript">       $("input[type=radio]").click(function() {         var total = 0;         $("input[type=radio]:checked").each(function() {           total += parseFloat($(this).val());         });          $("#totalSum").val(total);       });     </script> </body> </html> 

@Directive vs @Component in Angular

A @Component requires a view whereas a @Directive does not.

Directives

I liken a @Directive to an Angular 1.0 directive with the option restrict: 'A' (Directives aren't limited to attribute usage.) Directives add behaviour to an existing DOM element or an existing component instance. One example use case for a directive would be to log a click on an element.

import {Directive} from '@angular/core';

@Directive({
    selector: "[logOnClick]",
    hostListeners: {
        'click': 'onClick()',
    },
})
class LogOnClick {
    constructor() {}
    onClick() { console.log('Element clicked!'); }
}

Which would be used like so:

<button logOnClick>I log when clicked!</button>

Components

A component, rather than adding/modifying behaviour, actually creates its own view (hierarchy of DOM elements) with attached behaviour. An example use case for this might be a contact card component:

import {Component, View} from '@angular/core';

@Component({
  selector: 'contact-card',
  template: `
    <div>
      <h1>{{name}}</h1>
      <p>{{city}}</p>
    </div>
  `
})
class ContactCard {
  @Input() name: string
  @Input() city: string
  constructor() {}
}

Which would be used like so:

<contact-card [name]="'foo'" [city]="'bar'"></contact-card>

ContactCard is a reusable UI component that we could use anywhere in our application, even within other components. These basically make up the UI building blocks of our applications.

In summary

Write a component when you want to create a reusable set of DOM elements of UI with custom behaviour. Write a directive when you want to write reusable behaviour to supplement existing DOM elements.

Sources:

`getchar()` gives the same output as the input string

According to the definition of getchar(), it reads a character from the standard input. Unfortunately stdin is mistaken for keyboard which might not be the case for getchar. getchar uses a buffer as stdin and reads a single character at a time. In your case since there is no EOF, the getchar and putchar are running multiple times and it looks to you as it the whole string is being printed out at a time. Make a small change and you will understand:

putchar(c);
printf("\n");     
c = getchar();

Now look at the output compared to the original code.

Another example that will explain you the concept of getchar and buffered stdin :

void main(){
int c;
printf("Enter character");
c = getchar();
putchar();
c = getchar();
putchar();
}

Enter two characters in the first case. The second time when getchar is running are you entering any character? NO but still putchar works.

This ultimately means there is a buffer and when ever you are typing something and click enter this goes and settles in the buffer. getchar uses this buffer as stdin.

The ResourceConfig instance does not contain any root resource classes

Had the same issue and found out it was a problem with the way I deployed my source code. As the error message says: "...does not contain any root resource classes". So it couldn't find any resource classes in the configured package. I just deployed the classes wrong - that's why it didn't pick it up.

I forgot to deploy my class files in the /WEB-INF/classes directory of the WAR - initially I just had it directly in the root of the WAR file. So when it looked for resource classes it didn't find them - because they existed in a different (wrong) location.

How to reset index in a pandas dataframe?

data1.reset_index(inplace=True)

How do I install Keras and Theano in Anaconda Python on Windows?

Anaconda with Windows

  • Run anaconda prompt with administrator privilages
  • conda update conda
  • conda update --all
  • conda install mingw libpython
  • conda install theano

After conda commands it's required to accept process - Proceed ([y]/n)?

What are all the possible values for HTTP "Content-Type" header?

If you are using jaxrs or any other, then there will be a class called mediatype.User interceptor before sending the request and compare it against this.

Easy way of running the same junit test over and over?

In JUnit 5 it is much simpler by using @RepeatedTest

@RepeatedTest is used to signal that the annotated method is a test template method that should be repeated a specified number of times.

    @RepeatedTest(3) // Runs N Times
    public void test_Prime() {
    }

More info on www.baeldung.com

How to convert decimal to hexadecimal in JavaScript

var number = 3200;
var hexString = number.toString(16);

The 16 is the radix and there are 16 values in a hexadecimal number :-)

Remove grid, background color, and top and right borders from ggplot2

I followed Andrew's answer, but I also had to follow https://stackoverflow.com/a/35833548 and set the x and y axes separately due to a bug in my version of ggplot (v2.1.0).

Instead of

theme(axis.line = element_line(color = 'black'))

I used

theme(axis.line.x = element_line(color="black", size = 2),
    axis.line.y = element_line(color="black", size = 2))

How to move an entire div element up x pixels?

$('div').css({
    position: 'relative',
    top: '-15px'
});

Eclipse - Failed to create the java virtual machine

Try to open eclipse.ini and replace

-Xmx1024m

with

-Xmx512m

My java version is 1.7 as you can see below

-Dosgi.requiredJavaVersion=1.7

so i didn't modify that parameter.

This worked for me ;-)

How can I set the maximum length of 6 and minimum length of 6 in a textbox?

You can't set a minimum length on a text field. Otherwise, users wouldn't be able to type in the first five characters.

Your best bet is to validate the input when the form is submitted to ensure that the length is six.

maxlength is not a validation attribute. It is designed to prevent the user from physically typing in more than six characters. The corresponding minlengh is not in scope of the HTML specification, because its implementation would render the textbox unusable.

What is managed or unmanaged code in programming?

Managed code runs inside the environment of CLR i.e. .NET runtime.In short all IL are managed code.But if you are using some third party software example VB6 or VC++ component they are unmanaged code as .NET runtime (CLR) does not have control over the source code execution of the language.

SQL NVARCHAR and VARCHAR Limits

declare @p varbinary(max)
set @p = 0x
declare @local table (col text)

SELECT   @p = @p + 0x3B + CONVERT(varbinary(100), Email)
 FROM tbCarsList
 where email <> ''
 group by email
 order by email

 set @p = substring(@p, 2, 100000)

 insert @local values(cast(@p as varchar(max)))
 select DATALENGTH(col) as collen, col from @local

result collen > 8000, length col value is more than 8000 chars

java.lang.ClassNotFoundException: Didn't find class on path: dexpathlist

Just Change your folder name from lib to libs ,

Then you will see some error marks in your project, to resolve this rightClick on project >

Properties > Java Build Path > libraries :

Remove all the library with red marks on it, then apply > ok > after that clean your project . TADA see the magic :)

How to get domain URL and application name?

The following code might be useful for web application using JavaScript.

var newURL = window.location.protocol + "//"  + window.location.host + "" + window.location.pathname;

newURL = newURL.substring(0,newURL.indexOf(""));

Closing database connections in Java

Actually, it is best if you use a try-with-resources block and Java will close all of the connections for you when you exit the try block.

You should do this with any object that implements AutoClosable.

try (Connection connection = getDatabaseConnection(); Statement statement = connection.createStatement()) {
    String sqlToExecute = "SELECT * FROM persons";
    try (ResultSet resultSet = statement.execute(sqlToExecute)) {
        if (resultSet.next()) {
            System.out.println(resultSet.getString("name");
        }
    }
} catch (SQLException e) {
    System.out.println("Failed to select persons.");
}

The call to getDatabaseConnection is just made up. Replace it with a call that gets you a JDBC SQL connection or a connection from a pool.

super() in Java

Source article: Java: Calling super()


Yes. super(...) will invoke the constructor of the super-class.

Illustration:

enter image description here


Stand alone example:

class Animal {
    public Animal(String arg) {
        System.out.println("Constructing an animal: " + arg);
    }
}

class Dog extends Animal {
    public Dog() {
        super("From Dog constructor");
        System.out.println("Constructing a dog.");
    }
}

public class Test {
    public static void main(String[] a) {
        new Dog();
    }
}

Prints:

Constructing an animal: From Dog constructor
Constructing a dog.

Pull all images from a specified directory and then display them

You can display all image from a folder using simple php script. Suppose folder name “images” and put some image in this folder and then use any text editor and paste this code and run this script. This is php code

    <?php
     $files = glob("images/*.*");
     for ($i=0; $i<count($files); $i++)
      {
        $image = $files[$i];
        $supported_file = array(
                'gif',
                'jpg',
                'jpeg',
                'png'
         );

         $ext = strtolower(pathinfo($image, PATHINFO_EXTENSION));
         if (in_array($ext, $supported_file)) {
            echo basename($image)."<br />"; // show only image name if you want to show full path then use this code // echo $image."<br />";
             echo '<img src="'.$image .'" alt="Random image" />'."<br /><br />";
            } else {
                continue;
            }
          }
       ?>

if you do not check image type then use this code

<?php
$files = glob("images/*.*");
for ($i = 0; $i < count($files); $i++) {
    $image = $files[$i];
    echo basename($image) . "<br />"; // show only image name if you want to show full path then use this code // echo $image."<br />";
    echo '<img src="' . $image . '" alt="Random image" />' . "<br /><br />";

}
?>

How do I get the old value of a changed cell in Excel VBA?

Here's a way I've used in the past. Please note that you have to add a reference to the Microsoft Scripting Runtime so you can use the Dictionary object - if you don't want to add that reference you can do this with Collections but they're slower and there's no elegant way to check .Exists (you have to trap the error).

Dim OldVals As New Dictionary
Private Sub Worksheet_Change(ByVal Target As Range)
Dim cell As Range
    For Each cell In Target
        If OldVals.Exists(cell.Address) Then
            Debug.Print "New value of " & cell.Address & " is " & cell.Value & "; old value was " & OldVals(cell.Address)
        Else
            Debug.Print "No old value for " + cell.Address
        End If
        OldVals(cell.Address) = cell.Value
    Next
End Sub

Like any similar method, this has its problems - first off, it won't know the "old" value until the value has actually been changed. To fix this you'd need to trap the Open event on the workbook and go through Sheet.UsedRange populating OldVals. Also, it will lose all its data if you reset the VBA project by stopping the debugger or some such.

Disable vertical sync for glxgears

For Intel graphics and AMD/ATI opensource graphics drivers

Find the "Device" section of /etc/X11/xorg.conf which contains one of the following directives:

  • Driver "intel"
  • Driver "radeon"
  • Driver "fglrx"

And add the following line to that section:

Option     "SwapbuffersWait"       "false"

And run your application with vblank_mode environment variable set to 0:

$ vblank_mode=0 glxgears

For Nvidia graphics with the proprietary Nvidia driver

$ echo "0/SyncToVBlank=0" >> ~/.nvidia-settings-rc

The same change can be made in the nvidia-settings GUI by unchecking the option at X Screen 0 / OpenGL Settings / Sync to VBlank. Or, if you'd like to just test the setting without modifying your ~/.nvidia-settings-rc file you can do something like:

$ nvidia-settings --load-config-only --assign="SyncToVBlank=0"  # disable vertical sync
$ glxgears  # test it out
$ nvidia-settings --load-config-only  # restore your original vertical sync setting

Source file not compiled Dev C++

You can always try doing it manually from the command prompt. Navigate to the path of the file and type:

gcc filename.c -o filename

mysql_fetch_array() expects parameter 1 to be resource problem

The most likely cause is an error in mysql_query(). Have you checked to make sure it worked? Output the value of $result and mysql_error(). You may have misspelled something, selected the wrong database, have a permissions issue, etc. So:

$id = (int)$_GET['id']; // this also sanitizes it
$sql = "SELECT * FROM student WHERE idno = $id";
$result = mysql_query($sql);
if (!$result) {
  die("Error running $sql: " . mysql_error());
}

Sanitizing $_GET['id'] is really important. You can use mysql_real_escape_string() but casting it to an int is sufficient for integers. Basically you want to avoid SQL injection.

Switch between python 2.7 and python 3.5 on Mac OS X

If you want to use Apple’s system install of Python 2.7, be aware that it doesn’t quite follow the naming standards laid out in PEP 394.

In particular, it includes the optional symlinks with suffix 2.7 that you’re told not to rely on, and does not include the recommended symlinks with suffix 2 that you’re told you should rely on.


If you want to fix this, while sticking with Apple’s Python, you can create your own symlinks:

$ cd <somewhere writable and in your PATH>
$ ln -s /usr/bin/python python2

Or aliases in your bash config:

alias python2 python2.7

And you can do likewise for Apple’s 2to3, easy_install, etc. if you need them.

You shouldn’t try to put these symlinks into /usr/bin, and definitely don’t try to rename what’s already there, or to change the distutils setup to something more PEP-compliant. Those files are all part of the OS, and can be used by other parts of the OS, and your changes can be overwritten on even a minor update from 10.13.5 to 10.13.6 or something, so leave them alone and work around them as described above.


Alternatively, you could:

  • Just use python2.7 instead of python2 on the command line and in your shbangs and so on.
  • Use virtual environments or conda environments. The global python, python3, python2, etc. don’t matter when you’re always using the activated environment’s local python.
  • Stop using Apple’s 2.7 and instead install a whole other 2.7 alongside it, as most of the other answers suggest. (I don’t know why so many of them are also suggesting that you install a second 3.6. That’s just going to add even more confusion, for no benefit.)

What does .shape[] do in "for i in range(Y.shape[0])"?

The shape attribute for numpy arrays returns the dimensions of the array. If Y has n rows and m columns, then Y.shape is (n,m). So Y.shape[0] is n.

In [46]: Y = np.arange(12).reshape(3,4)

In [47]: Y
Out[47]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

In [48]: Y.shape
Out[48]: (3, 4)

In [49]: Y.shape[0]
Out[49]: 3

How do you get the length of a string?

You don't need to use jquery.

var myString = 'abc';
var n = myString.length;

n will be 3.

relative path in require_once doesn't work

for php version 5.2.17 __DIR__ will not work it will only works with php 5.3

But for older version of php dirname(__FILE__) perfectly

For example write like this

require_once dirname(__FILE__) . '/db_config.php';

iOS app with framework crashed on device, dyld: Library not loaded, Xcode 6 Beta

  1. Go to file in xcode -> Workspace settings
  2. Click the arrow next to which appears /Users/apple/Library/Developer/Xcode/DerivedData
  3. Select the Derived data and move it to Trash.
  4. Quite the xcode and reopen it.
  5. Clean the project and run again.

Above steps resolved my issuses.

Printing 1 to 1000 without loop or conditionals

Compile time recursion! :P

#include <iostream>
template<int N>
struct NumberGeneration{
  static void out(std::ostream& os)
  {
    NumberGeneration<N-1>::out(os);
    os << N << std::endl;
  }
};
template<>
struct NumberGeneration<1>{
  static void out(std::ostream& os)
  {
    os << 1 << std::endl;
  }
};
int main(){
   NumberGeneration<1000>::out(std::cout);
}

pip install mysql-python fails with EnvironmentError: mysql_config not found

In Mac OS, I simply ran this in terminal to fix:

export PATH=$PATH:/usr/local/mysql/bin

This is the quickest fix I found - it adds it to the path, but I think you're better off adding it permanently (ie add it to /etc/paths) if you plan to install MySQL-python in another environment.

(tested in OSX Mountain Lion)

Determine whether a key is present in a dictionary

if 'name' in mydict:

is the preferred, pythonic version. Use of has_key() is discouraged, and this method has been removed in Python 3.

What is the difference between float and double?

Huge difference.

As the name implies, a double has 2x the precision of float[1]. In general a double has 15 decimal digits of precision, while float has 7.

Here's how the number of digits are calculated:

double has 52 mantissa bits + 1 hidden bit: log(253)÷log(10) = 15.95 digits

float has 23 mantissa bits + 1 hidden bit: log(224)÷log(10) = 7.22 digits

This precision loss could lead to greater truncation errors being accumulated when repeated calculations are done, e.g.

float a = 1.f / 81;
float b = 0;
for (int i = 0; i < 729; ++ i)
    b += a;
printf("%.7g\n", b); // prints 9.000023

while

double a = 1.0 / 81;
double b = 0;
for (int i = 0; i < 729; ++ i)
    b += a;
printf("%.15g\n", b); // prints 8.99999999999996

Also, the maximum value of float is about 3e38, but double is about 1.7e308, so using float can hit "infinity" (i.e. a special floating-point number) much more easily than double for something simple, e.g. computing the factorial of 60.

During testing, maybe a few test cases contain these huge numbers, which may cause your programs to fail if you use floats.


Of course, sometimes, even double isn't accurate enough, hence we sometimes have long double[1] (the above example gives 9.000000000000000066 on Mac), but all floating point types suffer from round-off errors, so if precision is very important (e.g. money processing) you should use int or a fraction class.


Furthermore, don't use += to sum lots of floating point numbers, as the errors accumulate quickly. If you're using Python, use fsum. Otherwise, try to implement the Kahan summation algorithm.


[1]: The C and C++ standards do not specify the representation of float, double and long double. It is possible that all three are implemented as IEEE double-precision. Nevertheless, for most architectures (gcc, MSVC; x86, x64, ARM) float is indeed a IEEE single-precision floating point number (binary32), and double is a IEEE double-precision floating point number (binary64).

"Please provide a valid cache path" error in laravel

You need to create folders inside "framework". Please Follow these steps:

cd storage/
mkdir -p framework/{sessions,views,cache}

You also need to set permissions to allow Laravel to write data in this directory.

chmod -R 775 framework
chown -R www-data:www-data framework

Setting environment variables in Linux using Bash

I think you're looking for export - though I could be wrong.. I've never played with tcsh before. Use the following syntax:

export VARIABLE=value

How to import and export components using React + ES6 + webpack?

Wrapping components with braces if no default exports:

import {MyNavbar} from './comp/my-navbar.jsx';

or import multiple components from single module file

import {MyNavbar1, MyNavbar2} from './module';

HTTP Content-Type Header and JSON

Content-Type: application/json is just the content header. The content header is just information about the type of returned data, ex::JSON,image(png,jpg,etc..),html.

Keep in mind, that JSON in JavaScript is an array or object. If you want to see all the data, use console.log instead of alert:

alert(response.text); // Will alert "[object Object]" string
console.log(response.text); // Will log all data objects

If you want to alert the original JSON content as a string, then add single quotation marks ('):

echo "'" . json_encode(array('text' => 'omrele')) . "'";
// alert(response.text) will alert {"text":"omrele"}

Do not use double quotes. It will confuse JavaScript, because JSON uses double quotes on each value and key:

echo '<script>var returndata=';
echo '"' . json_encode(array('text' => 'omrele')) . '"';
echo ';</script>';

// It will return the wrong JavaScript code:
<script>var returndata="{"text":"omrele"}";</script>

Oracle insert if not exists statement

The correct way to insert something (in Oracle) based on another record already existing is by using the MERGE statement.

Please note that this question has already been answered here on SO:

How to make a select with array contains value clause in psql

SELECT * FROM table WHERE arr && '{s}'::text[];

Compare two arrays for containment.

Override browser form-filling and input highlighting with HTML/CSS

Since the browser searches for password type fields, another workaround is to include a hidden field at the beginning of your form:

<!-- unused field to stop browsers from overriding form style -->
<input type='password' style = 'display:none' />

Why would an Enum implement an Interface?

For example if you have a Logger enum. Then you should have the logger methods such as debug, info, warning and error in the interface. It makes your code loosely coupled.

JQuery: 'Uncaught TypeError: Illegal invocation' at ajax request - several elements

Thanks to the talk with Sarfraz we could figure out the solution.

The problem was that I was passing an HTML element instead of its value, which is actually what I wanted to do (in fact in my php code I need that value as a foreign key for querying my cities table and filter correct entries).

So, instead of:

var data = {
        'mode': 'filter_city',
        'id_A': e[e.selectedIndex]
};

it should be:

var data = {
        'mode': 'filter_city',
        'id_A': e[e.selectedIndex].value
};

Note: check Jason Kulatunga's answer, it quotes JQuery doc to explain why passing an HTML element was causing troubles.

Erase the current printed console line

there is a simple trick you can work here but it need preparation before you print, you have to put what ever you wants to print in a variable and then print so you will know the length to remove the string.here is an example.

#include <iostream>
#include <string> //actually this thing is not nessasory in tdm-gcc

using namespace  std;

int main(){

//create string variable

string str="Starting count";

//loop for printing numbers

    for(int i =0;i<=50000;i++){

        //get previous string length and clear it from screen with backspace charactor

        cout << string(str.length(),'\b');

        //create string line

        str="Starting count " +to_string(i);

        //print the new line in same spot

        cout <<str ;
    }

}

ASP.NET 4.5 has not been registered on the Web server

I had the exact same problem, despite ASP.NET 4.5 appearing as installed under "Turn Windows Features On/Off". I tried everything until I finally removed ASP.NET 3.5 and 4.5 completely from under "Turn Windows Features On/Off", rebooted my PC and reinstalled them Again. That solved the problem.

Unexpected end of file error

Goto SolutionExplorer (should be already visible, if not use menu: View->SolutionExplorer).

Find your .cxx file in the solution tree, right click on it and choose "Properties" from the popup menu. You will get window with your file's properties.

Using tree on the left side go to the "C++/Precompiled Headers" section. On the right side of the window you'll get three properties. Set property named "Create/Use Precompiled Header" to the value of "Not Using Precompiled Headers".

phonegap open link in browser

I'm using PhoneGap Build (v3.4.0), with focus on iOS, and I needed to have this entry in my config.xml for PhoneGap to recognize the InAppBrowser plug-in.

<gap:plugin name="org.apache.cordova.inappbrowser" />

After that, using window.open(url, target) should work as expected, as documented here.

Using filesystem in node.js with async / await

I have this little helping module that exports promisified versions of fs functions

const fs = require("fs");
const {promisify} = require("util")

module.exports = {
  readdir: promisify(fs.readdir),
  readFile: promisify(fs.readFile),
  writeFile: promisify(fs.writeFile)
  // etc...
};

.NET HashTable Vs Dictionary - Can the Dictionary be as fast?

Dictionaries have the advantage of being a generic type, which makes it type safe and a bit faster due to lack of need for boxing. The following comparison table (constructed using the answers found in a similar SO question post) illustrates some of the other reasons that support dictionaries over hash tables (or vice versa).

How do I mock an autowired @Value field in Spring with Mockito?

You can use this magic Spring Test annotation :

@TestPropertySource(properties = { "my.spring.property=20" }) 

see org.springframework.test.context.TestPropertySource

For example, this is the test class :

@ContextConfiguration(classes = { MyTestClass.Config.class })
@TestPropertySource(properties = { "my.spring.property=20" })
public class MyTestClass {

  public static class Config {
    @Bean
    MyClass getMyClass() {
      return new MyClass ();
    }
  }

  @Resource
  private MyClass myClass ;

  @Test
  public void myTest() {
   ...

And this is the class with the property :

@Component
public class MyClass {

  @Value("${my.spring.property}")
  private int mySpringProperty;
   ...

How to test an Internet connection with bash?

The top voted answer does not work for MacOS so for those on a mac, I've successfully tested this:

GATEWAY=`route -n get default | grep gateway`
if [ -z "$GATEWAY" ]
  then
    echo error
else
  ping -q -t 1 -c 1 `echo $GATEWAY | cut -d ':' -f 2` > /dev/null && echo ok || echo error
fi

tested on MacOS High Sierra 10.12.6

How to find which version of Oracle is installed on a Linux server (In terminal)

A bit manual searching but its an alternative way...
Find the Oracle home or where the installation files for Oracle is installed on your linux server.

cd / <-- Goto root directory
find . -print| grep -i dbm*.sql

Result varies on how you installed Oracle but mine displays this

/db/oracle

Goto the folder

less /db/oracle/db1/sqlplus/doc/README.htm

scroll down and you should see something like this

SQL*Plus Release Notes - Release 11.2.0.2

Plotting using a CSV file

You can also plot to a png file using gnuplot (which is free):

terminal commands

gnuplot> set title '<title>'
gnuplot> set ylabel '<yLabel>'
gnuplot> set xlabel '<xLabel>'
gnuplot> set grid
gnuplot> set term png
gnuplot> set output '<Output file name>.png'
gnuplot> plot '<fromfile.csv>'

note: you always need to give the right extension (.png here) at set output

Then it is also possible that the ouput is not lines, because your data is not continues. To fix this simply change the 'plot' line to:

plot '<Fromfile.csv>' with line lt -1 lw 2

More line editing options (dashes and line color ect.) at: http://gnuplot.sourceforge.net/demo_canvas/dashcolor.html

  • gnuplot is available in most linux distros via the package manager (e.g. on an apt based distro, run apt-get install gnuplot)
  • gnuplot is available in windows via Cygwin
  • gnuplot is available on macOS via homebrew (run brew install gnuplot)

java IO Exception: Stream Closed

Don't call write.close() in writeToFile().

How a thread should close itself in Java?

If you want to terminate the thread, then just returning is fine. You do NOT need to call Thread.currentThread().interrupt() (it will not do anything bad though. It's just that you don't need to.) This is because interrupt() is basically used to notify the owner of the thread (well, not 100% accurate, but sort of). Because you are the owner of the thread, and you decided to terminate the thread, there is no one to notify, so you don't need to call it.

By the way, why in the first case we need to use currentThread? Is Thread does not refer to the current thread?

Yes, it doesn't. I guess it can be confusing because e.g. Thread.sleep() affects the current thread, but Thread.sleep() is a static method.

If you are NOT the owner of the thread (e.g. if you have not extended Thread and coded a Runnable etc.) you should do

Thread.currentThread().interrupt();
return;

This way, whatever code that called your runnable will know the thread is interrupted = (normally) should stop whatever it is doing and terminate. As I said earlier, it is just a mechanism of communication though. The owner might simply ignore the interrupted status and do nothing.. but if you do set the interrupted status, somebody might thank you for that in the future.

For the same reason, you should never do

Catch(InterruptedException ie){
     //ignore
}

Because if you do, you are stopping the message there. Instead one should do

Catch(InterruptedException ie){
    Thread.currentThread().interrupt();//preserve the message
    return;//Stop doing whatever I am doing and terminate
}

How do I find a default constraint using INFORMATION_SCHEMA?

WHILE EXISTS( 
    SELECT * FROM  sys.all_columns 
    INNER JOIN sys.tables ST  ON all_columns.object_id = ST.object_id
    INNER JOIN sys.schemas ON ST.schema_id = schemas.schema_id
    INNER JOIN sys.default_constraints ON all_columns.default_object_id = default_constraints.object_id
    WHERE 
    schemas.name = 'dbo'
    AND ST.name = 'MyTable'
)
BEGIN 
DECLARE @SQL NVARCHAR(MAX) = N'';

SET @SQL = (  SELECT TOP 1
     'ALTER TABLE ['+  schemas.name + '].[' + ST.name + '] DROP CONSTRAINT ' + default_constraints.name + ';'
   FROM 
      sys.all_columns

         INNER JOIN
      sys.tables ST
         ON all_columns.object_id = ST.object_id

         INNER JOIN 
      sys.schemas
         ON ST.schema_id = schemas.schema_id

         INNER JOIN
      sys.default_constraints
         ON all_columns.default_object_id = default_constraints.object_id

   WHERE 
         schemas.name = 'dbo'
      AND ST.name = 'MyTable'
      )
   PRINT @SQL
   EXECUTE sp_executesql @SQL 

   --End if Error 
   IF @@ERROR <> 0 
   BREAK
END 

jQuery each loop in table row

Use immediate children selector >:

$('#tblOne > tbody  > tr')

Description: Selects all direct child elements specified by "child" of elements specified by "parent".

Histogram with Logarithmic Scale and custom breaks

A histogram is a poor-man's density estimate. Note that in your call to hist() using default arguments, you get frequencies not probabilities -- add ,prob=TRUE to the call if you want probabilities.

As for the log axis problem, don't use 'x' if you do not want the x-axis transformed:

plot(mydata_hist$count, log="y", type='h', lwd=10, lend=2)

gets you bars on a log-y scale -- the look-and-feel is still a little different but can probably be tweaked.

Lastly, you can also do hist(log(x), ...) to get a histogram of the log of your data.

Number of visitors on a specific page

As Blexy already answered, go to "Behavior > Site Content > All Pages".

Just pay attention that "Behavior" appears two times in the left sidebar and we need to click on the second option:

                                                     sidebar

Big O, how do you calculate/approximate it?

As to "how do you calculate" Big O, this is part of Computational complexity theory. For some (many) special cases you may be able to come with some simple heuristics (like multiplying loop counts for nested loops), esp. when all you want is any upper bound estimation, and you do not mind if it is too pessimistic - which I guess is probably what your question is about.

If you really want to answer your question for any algorithm the best you can do is to apply the theory. Besides of simplistic "worst case" analysis I have found Amortized analysis very useful in practice.

reading from stdin in c++

You have not defined the variable input_line.

Add this:

string input_line;

And add this include.

#include <string>

Here is the full example. I also removed the semi-colon after the while loop, and you should have getline inside the while to properly detect the end of the stream.

#include <iostream>
#include <string>

int main() {
    for (std::string line; std::getline(std::cin, line);) {
        std::cout << line << std::endl;
    }
    return 0;
}

How to include JavaScript file or library in Chrome console?

var el = document.createElement("script"),
loaded = false;
el.onload = el.onreadystatechange = function () {
  if ((el.readyState && el.readyState !== "complete" && el.readyState !== "loaded") || loaded) {
    return false;
  }
  el.onload = el.onreadystatechange = null;
  loaded = true;
  // done!
};
el.async = true;
el.src = path;
var hhead = document.getElementsByTagName('head')[0];
hhead.insertBefore(el, hhead.firstChild);

Checking Date format from a string in C#

https://msdn.microsoft.com/es-es/library/h9b85w22(v=vs.110).aspx

string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", 
                     "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", 
                     "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", 
                     "M/d/yyyy h:mm", "M/d/yyyy h:mm", 
                     "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"};
  string[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM", 
                          "5/1/2009 6:32:00", "05/01/2009 06:32", 
                          "05/01/2009 06:32:00 PM", "05/01/2009 06:32:00"}; 
  DateTime dateValue;

  foreach (string dateString in dateStrings)
  {
     if (DateTime.TryParseExact(dateString, formats, 
                                new CultureInfo("en-US"), 
                                DateTimeStyles.None, 
                                out dateValue))
        Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
     else
        Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
  }

What does "Changes not staged for commit" mean

Try following int git bash

1.git add -u :/

2.git commit -m "your commit message"

  1. git push -u origin master

Note:if you have not initialized your repo.

First of all

git init 

and follow above mentioned steps in order. This worked for me

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

How do I start PowerShell from Windows Explorer?

The following is a concise (and updated) summation of the earlier solutions. Here's what to do:

Add these strings and their respective parent keys:

pwrshell\(Default) < Open PowerShell Here
pwrshell\command\(Default) < powershell -NoExit -Command Set-Location -LiteralPath '%V'
pwrshelladmin\(Default) < Open PowerShell (Admin)
pwrshelladmin\command\(Default) < powershell -Command Start-Process -verb runAs -ArgumentList '-NoExit','cd','%V' powershell

at these locations

HKCR\Directory\shell (for folders)
HKCR\Directory\Background\shell (Explorer window)
HKCR\Drive\shell (for root drives)

That's it. Add the "Extended" strings for the commands only to be visible if you hold the "Shift" key, everything else is superfluous.

Images can't contain alpha channels or transparencies

i was able to use imageoptim to remove alpha channel and compress png files.

TypeScript: casting HTMLElement

To end up with:

  • an actual Array object (not a NodeList dressed up as an Array)
  • a list that is guaranteed to only include HTMLElements, not Nodes force-casted to HTMLElements
  • a warm fuzzy feeling to do The Right Thing

Try this:

let nodeList : NodeList = document.getElementsByTagName('script');
let elementList : Array<HTMLElement> = [];

if (nodeList) {
    for (let i = 0; i < nodeList.length; i++) {
        let node : Node = nodeList[i];

        // Make sure it's really an Element
        if (node.nodeType == Node.ELEMENT_NODE) {
            elementList.push(node as HTMLElement);
        }
    }
}

Enjoy.

How do I move a redis database from one server to another?

It is also possible to migrate data using the SLAVEOF command:

SLAVEOF old_instance_name old_instance_port

Check that you have receive the keys with KEYS *. You could test the new instance by any other way too, and when you are done just turn replication of:

SLAVEOF NO ONE

set div height using jquery (stretch div height)

$(document).ready(function(){ contsize();});
$(window).bind("resize",function(){contsize();});

function contsize()
{
var h = window.innerHeight;
var calculatecontsize = h - 70;/*if header and footer heights= 35 then total 70px*/ 
$('#content').css({"height":calculatecontsize + "px"} );
}

Appending an id to a list if not already present in a string

There are a couple things going on with your example. You have a list containing a string of numbers and newline characters:

list = ['350882 348521 350166\r\n']

And you are trying to find a number ID within this list:

id = 348521
if id not in list:
    ...

Your first conditional is always going to pass, because it will be looking for integer 348521 in list which has one element at index list[0] with the string value of '350882 348521 350166\r\n', so integer 348521 will be added to that list, making it a list of two elements: a string and an integer, as your output shows.

To reiterate: list is searched for id, not the string in list's first element.

If you were trying to find if the string representation of '348521' was contained within the larger string contained within your list, you could do the following, noting that you would need to do this for each element in list:

if str(id) not in list[0]: # list[0]: '350882 348521 350166\r\n'
    ...                    #                  ^^^^^^

However be aware that you would need to wrap str(id) with whitespace for the search, otherwise it would also match:

2348521999
 ^^^^^^

It is unclear whether you want your "list" to be a "string of integers separated by whitespace" or if you really want a list of integers.

If all you are trying to accomplish is to have a list of IDs, and to add IDs to that list only if they are not already contained, (and if the order of the elements in the list is not important,) then a set would be the best data structure to use.

ids = set(
    [int(id) for id in '350882 348521 350166\r\n'.strip().split(' ')]
)

# Adding an ID already in the set has no effect
ids.add(348521)

If the ordering of the IDs in the string is important then I would keep your IDs in a standard list and use your conditional check:

ids = [int(id) for id in '350882 348521 350166\r\n'.strip().split(' ')]

if 348521 not in ids:
    ...

How to view the list of compile errors in IntelliJ?

I think this comes closest to what you wish:

(From IntelliJ IDEA Q&A for Eclipse Users):

enter image description here

The above can be combined with a recently introduced option in Compiler settings to get a view very similar to that of Eclipse.

Things to do:

  1. Switch to 'Problems' view in the Project pane:

    enter image description here

  2. Enable the setting to compile the project automatically :

    enter image description here

  3. Finally, look at the Problems view:

    enter image description here

Here is a comparison of what the same project (with a compilation error) looks like in Intellij IDEA 13.xx and Eclipse Kepler:

enter image description here

enter image description here

Relevant Links: The maven project shown above : https://github.com/ajorpheus/CompileTimeErrors
FAQ For 'Eclipse Mode' / 'Automatically Compile' a project : http://devnet.jetbrains.com/docs/DOC-1122

How do I insert values into a Map<K, V>?

The syntax is

data.put("John","Taxi driver");

What's the actual use of 'fail' in JUnit test case?

This is how I use the Fail method.

There are three states that your test case can end up in

  1. Passed : The function under test executed successfully and returned data as expected
  2. Not Passed : The function under test executed successfully but the returned data was not as expected
  3. Failed : The function did not execute successfully and this was not

intended (Unlike negative test cases that expect a exception to occur).

If you are using eclipse there three states are indicated by a Green, Blue and red marker respectively.

I use the fail operation for the the third scenario.

e.g. : public Integer add(integer a, Integer b) { return new Integer(a.intValue() + b.intValue())}

  1. Passed Case : a = new Interger(1), b= new Integer(2) and the function returned 3
  2. Not Passed Case: a = new Interger(1), b= new Integer(2) and the function returned soem value other than 3
  3. Failed Case : a =null , b= null and the function throws a NullPointerException

Creating watermark using html and css

To make it fixed: Try this way,

jsFiddleLink: http://jsfiddle.net/PERtY/

<div class="body">This is a sample body This is a sample body
    This is a sample body
    This is a sample body
    This is a sample body
    This is a sample body
    This is a sample body
    This is a sample bodyThis is a sample bodyThis is a sample body
    This is a sample body
    This is a sample body
    This is a sample body
    This is a sample body
    This is a sample body
    This is a sample body
    This is a sample body
    v
    This is a sample body
    This is a sample body
    This is a sample body
    This is a sample body
    This is a sample body
    This is a sample body
    <div class="watermark">
           Sample Watermark
    </div>
    This is a sample body
    This is a sample bodyThis is a sample bodyThis is a sample body
</div>



.watermark {
    opacity: 0.5;
    color: BLACK;
    position: fixed;
    top: auto;
    left: 80%;
}

To use absolute:

.watermark {
    opacity: 0.5;
    color: BLACK;
    position: absolute;
    bottom: 0;
    right: 0;
}

jsFiddle: http://jsfiddle.net/6YSXC/

How to convert all text to lowercase in Vim

use ggguG

gg: goes to the first line.

gu: change to lowercase.

G: goes to the last line.

EntityType has no key defined error

The reason why EF framework prompt 'no key' is that EF framework needs a primary key in database. To declaratively tell EF which property the key is, you add a [Key] annotation. Or, the quickest way, add an ID property. Then, the EF framework will take ID as the primary key by default.

TypeError: coercing to Unicode: need string or buffer

You're trying to pass file objects as filenames. Try using

infile = '110331_HS1A_1_rtTA.result'
outfile = '2.txt'

at the top of your code.

(Not only does the doubled usage of open() cause that problem with trying to open the file again, it also means that infile and outfile are never closed during the course of execution, though they'll probably get closed once the program ends.)

Angularjs: Get element in controller

$element is one of four locals that $compileProvider gives to $controllerProvider which then gets given to $injector. The injector injects locals in your controller function only if asked.

The four locals are:

  • $scope
  • $element
  • $attrs
  • $transclude

The official documentation: AngularJS $compile Service API Reference - controller

The source code from Github angular.js/compile.js:

 function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope) {
    var elementControllers = createMap();
    for (var controllerKey in controllerDirectives) {
      var directive = controllerDirectives[controllerKey];
      var locals = {
        $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
        $element: $element,
        $attrs: attrs,
        $transclude: transcludeFn
      };

      var controller = directive.controller;
      if (controller == '@') {
        controller = attrs[directive.name];
      }

      var controllerInstance = $controller(controller, locals, true, directive.controllerAs);

WCFTestClient The HTTP request is unauthorized with client authentication scheme 'Anonymous'

Try providing username and password in your client like below

client.ClientCredentials.UserName.UserName = @"Domain\username"; client.ClientCredentials.UserName.Password = "password";

How to convert string to IP address and vice versa

I'm not sure if I understood the question properly.

Anyway, are you looking for this:

std::string ip ="192.168.1.54";
std::stringstream s(ip);
int a,b,c,d; //to store the 4 ints
char ch; //to temporarily store the '.'
s >> a >> ch >> b >> ch >> c >> ch >> d;
std::cout << a << "  " << b << "  " << c << "  "<< d;

Output:

192  168  1  54

How to let PHP to create subdomain automatically for each user?

In addition to configuration changes on your WWW server to handle the new subdomain, your code would need to be making changes to your DNS records. So, unless you're running your own BIND (or similar), you'll need to figure out how to access your name server provider's configuration. If they don't offer some sort of API, this might get tricky.

Update: yes, I would check with your registrar if they're also providing the name server service (as is often the case). I've never explored this option before but I suspect most of the consumer registrars do not. I Googled for GoDaddy APIs and GoDaddy DNS APIs but wasn't able to turn anything up, so I guess the best option would be to check out the online help with your provider, and if that doesn't answer the question, get a hold of their support staff.

reducing number of plot ticks

There's a set_ticks() function for axis objects.

excel delete row if column contains value from to-remove-list

Here is how I would do it if working with a large number of "to remove" values that would take a long time to manually remove.

  • -Put Original List in Column A -Put To Remove list in Column B -Select both columns, then "Conditional Formatting"
    -Select "Hightlight Cells Rules" --> "Duplicate Values"
    -The duplicates should be hightlighted in both columns
    -Then select Column A and then "Sort & Filter" ---> "Custom Sort"
    -In the dialog box that appears, select the middle option "Sort On" and pick "Cell Color"
    -Then select the next option "Sort Order" and choose "No Cell Color" "On bottom"
    -All the highlighted cells should be at the top of the list. -Select all the highlighted cells by scrolling down the list, then click delete.

Is it safe to clean docker/overlay2/

Backgroud

The blame for the issue can be split between our misconfiguration of container volumes, and a problem with docker leaking (failing to release) temporary data written to these volumes. We should be mapping (either to host folders or other persistent storage claims) all of out container's temporary / logs / scratch folders where our apps write frequently and/or heavily. Docker does not take responsibility for the cleanup of all automatically created so-called EmptyDirs located by default in /var/lib/docker/overlay2/*/diff/*. Contents of these "non-persistent" folders should be purged automatically by docker after container is stopped, but apparently are not (they may be even impossible to purge from the host side if the container is still running - and it can be running for months at a time).

Workaround

A workaround requires careful manual cleanup, and while already described elsewhere, you still may find some hints from my case study, which I tried to make as instructive and generalizable as possible.

So what happened is the culprit app (in my case clair-scanner) managed to write over a few months hundreds of gigs of data to the /diff/tmp subfolder of docker's overlay2

du -sch /var/lib/docker/overlay2/<long random folder name seen as bloated in df -haT>/diff/tmp

271G total

So as all those subfolders in /diff/tmp were pretty self-explanatory (all were of the form clair-scanner-* and had obsolete creation dates), I stopped the associated container (docker stop clair) and carefully removed these obsolete subfolders from diff/tmp, starting prudently with a single (oldest) one, and testing the impact on docker engine (which did require restart [systemctl restart docker] to reclaim disk space):

rm -rf $(ls -at /var/lib/docker/overlay2/<long random folder name seen as bloated in df -haT>/diff/tmp | grep clair-scanner | tail -1)

I reclaimed hundreds of gigs of disk space without the need to re-install docker or purge its entire folders. All running containers did have to be stopped at one point, because docker daemon restart was required to reclaim disk space, so make sure first your failover containers are running correctly on an/other node/s). I wish though that the docker prune command could cover the obsolete /diff/tmp (or even /diff/*) data as well (via yet another switch).

It's a 3-year-old issue now, you can read its rich and colorful history on Docker forums, where a variant aimed at application logs of the above solution was proposed in 2019 and seems to have worked in several setups: https://forums.docker.com/t/some-way-to-clean-up-identify-contents-of-var-lib-docker-overlay/30604

How do I stretch a background image to cover the entire HTML element?

The following code I use mostly for achieving the asked effect:

body {
    background-image: url('../images/bg.jpg');
    background-repeat: no-repeat;
    background-size: 100%;
}

Hibernate openSession() vs getCurrentSession()

As explained in this forum post, 1 and 2 are related. If you set hibernate.current_session_context_class to thread and then implement something like a servlet filter that opens the session - then you can access that session anywhere else by using the SessionFactory.getCurrentSession().

SessionFactory.openSession() always opens a new session that you have to close once you are done with the operations. SessionFactory.getCurrentSession() returns a session bound to a context - you don't need to close this.

If you are using Spring or EJBs to manage transactions you can configure them to open / close sessions along with the transactions.

You should never use one session per web app - session is not a thread safe object - cannot be shared by multiple threads. You should always use "one session per request" or "one session per transaction"

What does elementFormDefault do in XSD?

elementFormDefault="qualified" is used to control the usage of namespaces in XML instance documents (.xml file), rather than namespaces in the schema document itself (.xsd file).

By specifying elementFormDefault="qualified" we enforce namespace declaration to be used in documents validated with this schema.

It is common practice to specify this value to declare that the elements should be qualified rather than unqualified. However, since attributeFormDefault="unqualified" is the default value, it doesn't need to be specified in the schema document, if one does not want to qualify the namespaces.

convert base64 to image in javascript/jquery

One quick and easy way:

function paintSvgToCanvas(uSvg, uCanvas) {

    var pbx = document.createElement('img');

    pbx.style.width  = uSvg.style.width;
    pbx.style.height = uSvg.style.height;

    pbx.src = 'data:image/svg+xml;base64,' + window.btoa(uSvg.outerHTML);
    uCanvas.getContext('2d').drawImage(pbx, 0, 0);

}

C# Clear all items in ListView

Try this ...

myListView.DataSource = null;
myListView.Items.Clear();

Force the origin to start at 0

xlim and ylim don't cut it here. You need to use expand_limits, scale_x_continuous, and scale_y_continuous. Try:

df <- data.frame(x = 1:5, y = 1:5)
p <- ggplot(df, aes(x, y)) + geom_point()
p <- p + expand_limits(x = 0, y = 0)
p # not what you are looking for

enter image description here

p + scale_x_continuous(expand = c(0, 0)) + scale_y_continuous(expand = c(0, 0))

enter image description here

You may need to adjust things a little to make sure points are not getting cut off (see, for example, the point at x = 5 and y = 5.

CSS3's border-radius property and border-collapse:collapse don't mix. How can I use border-radius to create a collapsed table with rounded corners?

As Ian said, the solution is to nest the table inside a div and set it like that:

.table_wrapper {
  border-radius: 5px;
  overflow: hidden;
}

With overflow:hidden, the square corners won't bleed through the div.

Get keys of a Typescript interface as array of strings

This should work

var IMyTable: Array<keyof IMyTable> = ["id", "title", "createdAt", "isDeleted"];

or

var IMyTable: (keyof IMyTable)[] = ["id", "title", "createdAt", "isDeleted"];

How do you clone a Git repository into a specific folder?

Regarding this line from the original post:

"I know how to move the files after I've cloned the repo, but this seems to break git"

I am able to do that and I don't see any issues so far with my add, commit, push, pull operations.

This approach is stated above, but just not broken down into steps. Here's the steps that work for me:

  1. clone the repo into any fresh temporary folder
  2. cd into that root folder you just cloned locally
  3. copy the entire contents of the folder, including the /.git directory - into any existing folder you like; (say an eclipse project that you want to merge with your repo)

The existing folder you just copied the files into , is now ready to interact with git.

How to modify values of JsonObject / JsonArray directly?

public static JSONObject convertFileToJSON(String fileName, String username, List<String> list)
            throws FileNotFoundException, IOException, org.json.simple.parser.ParseException {
        JSONObject json = new JSONObject();
        String jsonStr = new String(Files.readAllBytes(Paths.get(fileName)));
        json = new JSONObject(jsonStr);
        System.out.println(json);
        JSONArray jsonArray = json.getJSONArray("users");
        JSONArray finalJsonArray = new JSONArray();
        /**
         * Get User form setNewUser method
         */
        //finalJsonArray.put(setNewUserPreference());
        boolean has = true;
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            finalJsonArray.put(jsonObject);
            String username2 = jsonObject.getString("userName");
            if (username2.equals(username)) {
                has = true;
            }
            System.out.println("user name  are :" + username2);
            JSONObject jsonObject2 = jsonObject.getJSONObject("languages");
            String eng = jsonObject2.getString("Eng");
            String fin = jsonObject2.getString("Fin");
            String ger = jsonObject2.getString("Ger");
            jsonObject2.put("Eng", "ChangeEnglishValueCheckForLongValue");
            System.out.println(" Eng : " + eng + "  Fin " + fin + "  ger : " + ger);
        }
        System.out.println("Final JSON Array \n" + json);
        jsonArray.put(setNewUserPreference());
        return json;
    }

Cannot deserialize the current JSON array (e.g. [1,2,3])

You can use this to solve your problem:

private async void btn_Go_Click(object sender, RoutedEventArgs e)
{
    HttpClient webClient = new HttpClient();
    Uri uri = new Uri("http://www.school-link.net/webservice/get_student/?id=" + txtVCode.Text);
    HttpResponseMessage response = await webClient.GetAsync(uri);
    var jsonString = await response.Content.ReadAsStringAsync();
    var _Data = JsonConvert.DeserializeObject <List<Student>>(jsonString);
    foreach (Student Student in _Data)
    {
        tb1.Text = Student.student_name;
    }
}

Get the (last part of) current directory name in C#

You can try below code :

Path.GetFileName(userpath)

How can I echo a newline in a batch file?

If you need to put results to a file, you can use

(echo a & echo. & echo b) > file_containing_multiple_lines.txt

How do you run a single test/spec file in RSpec?

I was having trouble getting any of these examples to work, maybe because the post is old and the commands have changed?

After some poking around I found this works:

rspec spec/models/user_spec.rb

That will run just the single file and provides useful output in the terminal.

How to convert string to char array in C++?

If you're using C++11 or above, I'd suggest using std::snprintf over std::strcpy or std::strncpy because of its safety (i.e., you determine how many characters can be written to your buffer) and because it null-terminates the string for you (so you don't have to worry about it). It would be like this:

#include <string>
#include <cstdio>

std::string tmp = "cat";
char tab2[1024];
std::snprintf(tab2, sizeof(tab2), "%s", tmp.c_str());

In C++17, you have this alternative:

#include <string>
#include <cstdio>
#include <iterator>

std::string tmp = "cat";
char tab2[1024];
std::snprintf(tab2, std::size(tab2), "%s", tmp.c_str());

Difference between single and double quotes in Bash

There is a clear distinction between the usage of ' ' and " ".

When ' ' is used around anything, there is no "transformation or translation" done. It is printed as it is.

With " ", whatever it surrounds, is "translated or transformed" into its value.

By translation/ transformation I mean the following: Anything within the single quotes will not be "translated" to their values. They will be taken as they are inside quotes. Example: a=23, then echo '$a' will produce $a on standard output. Whereas echo "$a" will produce 23 on standard output.

Pandas rename column by position?

You can do this:

df.rename(columns={ df.columns[1]: "whatever" })

href overrides ng-click in Angular.js

I'll add for you an example that work for me and you can change it as you want.

I add the bellow code inside my controller.

     $scope.showNumberFct = function(){
        alert("Work!!!!");
     }

and for my view page I add the bellow code.

<a  href="" ng-model="showNumber" ng-click="showNumberFct()" ng-init="showNumber = false" >Click Me!!!</a>

Copy Notepad++ text with formatting?

Horrible to look for this failure:

Copy .dll to here:

\Program Files\Notepad++\plugins --> put it here

Restart the notepad++

and now you are able to use the copy commands!!!

Get width height of remote image from url

Get image size with jQuery

function getMeta(url){
    $("<img/>",{
        load : function(){
            alert(this.width+' '+this.height);
        },
        src  : url
    });
}

Get image size with JavaScript

function getMeta(url){   
    var img = new Image();
    img.onload = function(){
        alert( this.width+' '+ this.height );
    };
    img.src = url;
}

Get image size with JavaScript (modern browsers, IE9+ )

function getMeta(url){   
    var img = new Image();
    img.addEventListener("load", function(){
        alert( this.naturalWidth +' '+ this.naturalHeight );
    });
    img.src = url;
}

Use the above simply as: getMeta( "http://example.com/img.jpg" );

https://developer.mozilla.org/en/docs/Web/API/HTMLImageElement

Fast and simple String encrypt/decrypt in JAVA

Update

the library already have Java/Kotlin support, see github.


Original

To simplify I did a class to be used simply, I added it on Encryption library to use it you just do as follow:

Add the gradle library:

compile 'se.simbio.encryption:library:2.0.0'

and use it:

Encryption encryption = Encryption.getDefault("Key", "Salt", new byte[16]);
String encrypted = encryption.encryptOrNull("top secret string");
String decrypted = encryption.decryptOrNull(encrypted);

if you not want add the Encryption library you can just copy the following class to your project. If you are in an android project you need to import android Base64 in this class, if you are in a pure java project you need to add this class manually you can get it here

Encryption.java

package se.simbio.encryption;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * A class to make more easy and simple the encrypt routines, this is the core of Encryption library
 */
public class Encryption {

    /**
     * The Builder used to create the Encryption instance and that contains the information about
     * encryption specifications, this instance need to be private and careful managed
     */
    private final Builder mBuilder;

    /**
     * The private and unique constructor, you should use the Encryption.Builder to build your own
     * instance or get the default proving just the sensible information about encryption
     */
    private Encryption(Builder builder) {
        mBuilder = builder;
    }

    /**
     * @return an default encryption instance or {@code null} if occur some Exception, you can
     * create yur own Encryption instance using the Encryption.Builder
     */
    public static Encryption getDefault(String key, String salt, byte[] iv) {
        try {
            return Builder.getDefaultBuilder(key, salt, iv).build();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Encrypt a String
     *
     * @param data the String to be encrypted
     *
     * @return the encrypted String or {@code null} if you send the data as {@code null}
     *
     * @throws UnsupportedEncodingException       if the Builder charset name is not supported or if
     *                                            the Builder charset name is not supported
     * @throws NoSuchAlgorithmException           if the Builder digest algorithm is not available
     *                                            or if this has no installed provider that can
     *                                            provide the requested by the Builder secret key
     *                                            type or it is {@code null}, empty or in an invalid
     *                                            format
     * @throws NoSuchPaddingException             if no installed provider can provide the padding
     *                                            scheme in the Builder digest algorithm
     * @throws InvalidAlgorithmParameterException if the specified parameters are inappropriate for
     *                                            the cipher
     * @throws InvalidKeyException                if the specified key can not be used to initialize
     *                                            the cipher instance
     * @throws InvalidKeySpecException            if the specified key specification cannot be used
     *                                            to generate a secret key
     * @throws BadPaddingException                if the padding of the data does not match the
     *                                            padding scheme
     * @throws IllegalBlockSizeException          if the size of the resulting bytes is not a
     *                                            multiple of the cipher block size
     * @throws NullPointerException               if the Builder digest algorithm is {@code null} or
     *                                            if the specified Builder secret key type is
     *                                            {@code null}
     * @throws IllegalStateException              if the cipher instance is not initialized for
     *                                            encryption or decryption
     */
    public String encrypt(String data) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, InvalidKeySpecException, BadPaddingException, IllegalBlockSizeException {
        if (data == null) return null;
        SecretKey secretKey = getSecretKey(hashTheKey(mBuilder.getKey()));
        byte[] dataBytes = data.getBytes(mBuilder.getCharsetName());
        Cipher cipher = Cipher.getInstance(mBuilder.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, mBuilder.getIvParameterSpec(), mBuilder.getSecureRandom());
        return Base64.encodeToString(cipher.doFinal(dataBytes), mBuilder.getBase64Mode());
    }

    /**
     * This is a sugar method that calls encrypt method and catch the exceptions returning
     * {@code null} when it occurs and logging the error
     *
     * @param data the String to be encrypted
     *
     * @return the encrypted String or {@code null} if you send the data as {@code null}
     */
    public String encryptOrNull(String data) {
        try {
            return encrypt(data);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * This is a sugar method that calls encrypt method in background, it is a good idea to use this
     * one instead the default method because encryption can take several time and with this method
     * the process occurs in a AsyncTask, other advantage is the Callback with separated methods,
     * one for success and other for the exception
     *
     * @param data     the String to be encrypted
     * @param callback the Callback to handle the results
     */
    public void encryptAsync(final String data, final Callback callback) {
        if (callback == null) return;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String encrypt = encrypt(data);
                    if (encrypt == null) {
                        callback.onError(new Exception("Encrypt return null, it normally occurs when you send a null data"));
                    }
                    callback.onSuccess(encrypt);
                } catch (Exception e) {
                    callback.onError(e);
                }
            }
        }).start();
    }

    /**
     * Decrypt a String
     *
     * @param data the String to be decrypted
     *
     * @return the decrypted String or {@code null} if you send the data as {@code null}
     *
     * @throws UnsupportedEncodingException       if the Builder charset name is not supported or if
     *                                            the Builder charset name is not supported
     * @throws NoSuchAlgorithmException           if the Builder digest algorithm is not available
     *                                            or if this has no installed provider that can
     *                                            provide the requested by the Builder secret key
     *                                            type or it is {@code null}, empty or in an invalid
     *                                            format
     * @throws NoSuchPaddingException             if no installed provider can provide the padding
     *                                            scheme in the Builder digest algorithm
     * @throws InvalidAlgorithmParameterException if the specified parameters are inappropriate for
     *                                            the cipher
     * @throws InvalidKeyException                if the specified key can not be used to initialize
     *                                            the cipher instance
     * @throws InvalidKeySpecException            if the specified key specification cannot be used
     *                                            to generate a secret key
     * @throws BadPaddingException                if the padding of the data does not match the
     *                                            padding scheme
     * @throws IllegalBlockSizeException          if the size of the resulting bytes is not a
     *                                            multiple of the cipher block size
     * @throws NullPointerException               if the Builder digest algorithm is {@code null} or
     *                                            if the specified Builder secret key type is
     *                                            {@code null}
     * @throws IllegalStateException              if the cipher instance is not initialized for
     *                                            encryption or decryption
     */
    public String decrypt(String data) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        if (data == null) return null;
        byte[] dataBytes = Base64.decode(data, mBuilder.getBase64Mode());
        SecretKey secretKey = getSecretKey(hashTheKey(mBuilder.getKey()));
        Cipher cipher = Cipher.getInstance(mBuilder.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, secretKey, mBuilder.getIvParameterSpec(), mBuilder.getSecureRandom());
        byte[] dataBytesDecrypted = (cipher.doFinal(dataBytes));
        return new String(dataBytesDecrypted);
    }

    /**
     * This is a sugar method that calls decrypt method and catch the exceptions returning
     * {@code null} when it occurs and logging the error
     *
     * @param data the String to be decrypted
     *
     * @return the decrypted String or {@code null} if you send the data as {@code null}
     */
    public String decryptOrNull(String data) {
        try {
            return decrypt(data);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * This is a sugar method that calls decrypt method in background, it is a good idea to use this
     * one instead the default method because decryption can take several time and with this method
     * the process occurs in a AsyncTask, other advantage is the Callback with separated methods,
     * one for success and other for the exception
     *
     * @param data     the String to be decrypted
     * @param callback the Callback to handle the results
     */
    public void decryptAsync(final String data, final Callback callback) {
        if (callback == null) return;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String decrypt = decrypt(data);
                    if (decrypt == null) {
                        callback.onError(new Exception("Decrypt return null, it normally occurs when you send a null data"));
                    }
                    callback.onSuccess(decrypt);
                } catch (Exception e) {
                    callback.onError(e);
                }
            }
        }).start();
    }

    /**
     * creates a 128bit salted aes key
     *
     * @param key encoded input key
     *
     * @return aes 128 bit salted key
     *
     * @throws NoSuchAlgorithmException     if no installed provider that can provide the requested
     *                                      by the Builder secret key type
     * @throws UnsupportedEncodingException if the Builder charset name is not supported
     * @throws InvalidKeySpecException      if the specified key specification cannot be used to
     *                                      generate a secret key
     * @throws NullPointerException         if the specified Builder secret key type is {@code null}
     */
    private SecretKey getSecretKey(char[] key) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException {
        SecretKeyFactory factory = SecretKeyFactory.getInstance(mBuilder.getSecretKeyType());
        KeySpec spec = new PBEKeySpec(key, mBuilder.getSalt().getBytes(mBuilder.getCharsetName()), mBuilder.getIterationCount(), mBuilder.getKeyLength());
        SecretKey tmp = factory.generateSecret(spec);
        return new SecretKeySpec(tmp.getEncoded(), mBuilder.getKeyAlgorithm());
    }

    /**
     * takes in a simple string and performs an sha1 hash
     * that is 128 bits long...we then base64 encode it
     * and return the char array
     *
     * @param key simple inputted string
     *
     * @return sha1 base64 encoded representation
     *
     * @throws UnsupportedEncodingException if the Builder charset name is not supported
     * @throws NoSuchAlgorithmException     if the Builder digest algorithm is not available
     * @throws NullPointerException         if the Builder digest algorithm is {@code null}
     */
    private char[] hashTheKey(String key) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        MessageDigest messageDigest = MessageDigest.getInstance(mBuilder.getDigestAlgorithm());
        messageDigest.update(key.getBytes(mBuilder.getCharsetName()));
        return Base64.encodeToString(messageDigest.digest(), Base64.NO_PADDING).toCharArray();
    }

    /**
     * When you encrypt or decrypt in callback mode you get noticed of result using this interface
     */
    public interface Callback {

        /**
         * Called when encrypt or decrypt job ends and the process was a success
         *
         * @param result the encrypted or decrypted String
         */
        void onSuccess(String result);

        /**
         * Called when encrypt or decrypt job ends and has occurred an error in the process
         *
         * @param exception the Exception related to the error
         */
        void onError(Exception exception);

    }

    /**
     * This class is used to create an Encryption instance, you should provide ALL data or start
     * with the Default Builder provided by the getDefaultBuilder method
     */
    public static class Builder {

        private byte[] mIv;
        private int mKeyLength;
        private int mBase64Mode;
        private int mIterationCount;
        private String mSalt;
        private String mKey;
        private String mAlgorithm;
        private String mKeyAlgorithm;
        private String mCharsetName;
        private String mSecretKeyType;
        private String mDigestAlgorithm;
        private String mSecureRandomAlgorithm;
        private SecureRandom mSecureRandom;
        private IvParameterSpec mIvParameterSpec;

        /**
         * @return an default builder with the follow defaults:
         * the default char set is UTF-8
         * the default base mode is Base64
         * the Secret Key Type is the PBKDF2WithHmacSHA1
         * the default salt is "some_salt" but can be anything
         * the default length of key is 128
         * the default iteration count is 65536
         * the default algorithm is AES in CBC mode and PKCS 5 Padding
         * the default secure random algorithm is SHA1PRNG
         * the default message digest algorithm SHA1
         */
        public static Builder getDefaultBuilder(String key, String salt, byte[] iv) {
            return new Builder()
                    .setIv(iv)
                    .setKey(key)
                    .setSalt(salt)
                    .setKeyLength(128)
                    .setKeyAlgorithm("AES")
                    .setCharsetName("UTF8")
                    .setIterationCount(1)
                    .setDigestAlgorithm("SHA1")
                    .setBase64Mode(Base64.DEFAULT)
                    .setAlgorithm("AES/CBC/PKCS5Padding")
                    .setSecureRandomAlgorithm("SHA1PRNG")
                    .setSecretKeyType("PBKDF2WithHmacSHA1");
        }

        /**
         * Build the Encryption with the provided information
         *
         * @return a new Encryption instance with provided information
         *
         * @throws NoSuchAlgorithmException if the specified SecureRandomAlgorithm is not available
         * @throws NullPointerException     if the SecureRandomAlgorithm is {@code null} or if the
         *                                  IV byte array is null
         */
        public Encryption build() throws NoSuchAlgorithmException {
            setSecureRandom(SecureRandom.getInstance(getSecureRandomAlgorithm()));
            setIvParameterSpec(new IvParameterSpec(getIv()));
            return new Encryption(this);
        }

        /**
         * @return the charset name
         */
        private String getCharsetName() {
            return mCharsetName;
        }

        /**
         * @param charsetName the new charset name
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setCharsetName(String charsetName) {
            mCharsetName = charsetName;
            return this;
        }

        /**
         * @return the algorithm
         */
        private String getAlgorithm() {
            return mAlgorithm;
        }

        /**
         * @param algorithm the algorithm to be used
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setAlgorithm(String algorithm) {
            mAlgorithm = algorithm;
            return this;
        }

        /**
         * @return the key algorithm
         */
        private String getKeyAlgorithm() {
            return mKeyAlgorithm;
        }

        /**
         * @param keyAlgorithm the keyAlgorithm to be used in keys
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setKeyAlgorithm(String keyAlgorithm) {
            mKeyAlgorithm = keyAlgorithm;
            return this;
        }

        /**
         * @return the Base 64 mode
         */
        private int getBase64Mode() {
            return mBase64Mode;
        }

        /**
         * @param base64Mode set the base 64 mode
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setBase64Mode(int base64Mode) {
            mBase64Mode = base64Mode;
            return this;
        }

        /**
         * @return the type of aes key that will be created, on KITKAT+ the API has changed, if you
         * are getting problems please @see <a href="http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html">http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html</a>
         */
        private String getSecretKeyType() {
            return mSecretKeyType;
        }

        /**
         * @param secretKeyType the type of AES key that will be created, on KITKAT+ the API has
         *                      changed, if you are getting problems please @see <a href="http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html">http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html</a>
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setSecretKeyType(String secretKeyType) {
            mSecretKeyType = secretKeyType;
            return this;
        }

        /**
         * @return the value used for salting
         */
        private String getSalt() {
            return mSalt;
        }

        /**
         * @param salt the value used for salting
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setSalt(String salt) {
            mSalt = salt;
            return this;
        }

        /**
         * @return the key
         */
        private String getKey() {
            return mKey;
        }

        /**
         * @param key the key.
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setKey(String key) {
            mKey = key;
            return this;
        }

        /**
         * @return the length of key
         */
        private int getKeyLength() {
            return mKeyLength;
        }

        /**
         * @param keyLength the length of key
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setKeyLength(int keyLength) {
            mKeyLength = keyLength;
            return this;
        }

        /**
         * @return the number of times the password is hashed
         */
        private int getIterationCount() {
            return mIterationCount;
        }

        /**
         * @param iterationCount the number of times the password is hashed
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setIterationCount(int iterationCount) {
            mIterationCount = iterationCount;
            return this;
        }

        /**
         * @return the algorithm used to generate the secure random
         */
        private String getSecureRandomAlgorithm() {
            return mSecureRandomAlgorithm;
        }

        /**
         * @param secureRandomAlgorithm the algorithm to generate the secure random
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setSecureRandomAlgorithm(String secureRandomAlgorithm) {
            mSecureRandomAlgorithm = secureRandomAlgorithm;
            return this;
        }

        /**
         * @return the IvParameterSpec bytes array
         */
        private byte[] getIv() {
            return mIv;
        }

        /**
         * @param iv the byte array to create a new IvParameterSpec
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setIv(byte[] iv) {
            mIv = iv;
            return this;
        }

        /**
         * @return the SecureRandom
         */
        private SecureRandom getSecureRandom() {
            return mSecureRandom;
        }

        /**
         * @param secureRandom the Secure Random
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setSecureRandom(SecureRandom secureRandom) {
            mSecureRandom = secureRandom;
            return this;
        }

        /**
         * @return the IvParameterSpec
         */
        private IvParameterSpec getIvParameterSpec() {
            return mIvParameterSpec;
        }

        /**
         * @param ivParameterSpec the IvParameterSpec
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setIvParameterSpec(IvParameterSpec ivParameterSpec) {
            mIvParameterSpec = ivParameterSpec;
            return this;
        }

        /**
         * @return the message digest algorithm
         */
        private String getDigestAlgorithm() {
            return mDigestAlgorithm;
        }

        /**
         * @param digestAlgorithm the algorithm to be used to get message digest instance
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setDigestAlgorithm(String digestAlgorithm) {
            mDigestAlgorithm = digestAlgorithm;
            return this;
        }

    }

}    

What operator is <> in VBA

Not Equal To


Before C came along and popularized !=, languages tended to use <> for not equal to.

At least, the various dialects of Basic did, and they predate C.

An even older and more unusual case is Fortran, which uses .NE., as in X .NE. Y.

ArrayList filter

Iterate through the list and check if contains your string "How" and if it does then remove. You can use following code:

// need to construct a new ArrayList otherwise remove operation will not be supported
List<String> list = new ArrayList<String>(Arrays.asList(new String[] 
                                  {"How are you?", "How you doing?","Joe", "Mike"}));
System.out.println("List Before: " + list);
for (Iterator<String> it=list.iterator(); it.hasNext();) {
    if (!it.next().contains("How"))
        it.remove(); // NOTE: Iterator's remove method, not ArrayList's, is used.
}
System.out.println("List After: " + list);

OUTPUT:

List Before: [How are you?, How you doing?, Joe, Mike]
List After: [How are you?, How you doing?]

How to replace comma (,) with a dot (.) using java

in the java src you can add a new tool like this:

public static String remplaceVirguleParpoint(String chaine) {
       return chaine.replaceAll(",", "\\.");
}

How to block until an event is fired in c#

If the current method is async then you can use TaskCompletionSource. Create a field that the event handler and the current method can access.

    TaskCompletionSource<bool> tcs = null;

    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        tcs = new TaskCompletionSource<bool>();
        await tcs.Task;
        WelcomeTitle.Text = "Finished work";
    }

    private void Button_Click2(object sender, RoutedEventArgs e)
    {
        tcs?.TrySetResult(true);
    }

This example uses a form that has a textblock named WelcomeTitle and two buttons. When the first button is clicked it starts the click event but stops at the await line. When the second button is clicked the task is completed and the WelcomeTitle text is updated. If you want to timeout as well then change

await tcs.Task;

to

await Task.WhenAny(tcs.Task, Task.Delay(25000));
if (tcs.Task.IsCompleted)
    WelcomeTitle.Text = "Task Completed";
else
    WelcomeTitle.Text = "Task Timed Out";

What is the difference between Scrum and Agile Development?

Waterfall methodology is a sequential design process. This means that as each of the eight stages (conception, initiation, analysis, design, construction, testing, implementation, and maintenance) are completed, the developers move on to the next step.

As this process is sequential, once a step has been completed, developers can’t go back to a previous step – not without scratching the whole project and starting from the beginning. There’s no room for change or error, so a project outcome and an extensive plan must be set in the beginning and then followed careful

ACP Agile Certification came about as a “solution” to the disadvantages of the waterfall methodology. Instead of a sequential design process, the Agile methodology follows an incremental approach. Developers start off with a simplistic project design, and then begin to work on small modules. The work on these modules is done in weekly or monthly sprints, and at the end of each sprint, project priorities are evaluated and tests are run. These sprints allow for bugs to be discovered, and customer feedback to be incorporated into the design before the next sprint is run.

The process, with its lack of initial design and steps, is often criticized for its collaborative nature that focuses on principles rather than process.

SQL Statement with multiple SETs and WHEREs

Nope, this is how you do it:

UPDATE table SET ID = 111111259 WHERE ID = 2555

UPDATE table SET ID = 111111261 WHERE ID = 2724

UPDATE table SET ID = 111111263 WHERE ID = 2021

UPDATE table SET ID = 111111264 WHERE ID = 2017

What is your single most favorite command-line trick using Bash?

You can use the watch command in conjunction with another command to look for changes. An example of this was when I was testing my router, and I wanted to get up-to-date numbers on stuff like signal-to-noise ratio, etc.

watch --interval=10 lynx -dump http://dslrouter/stats.html

How to force C# .net app to run only one instance in Windows?

This is what I use in my application:

static void Main()
{
  bool mutexCreated = false;
  System.Threading.Mutex mutex = new System.Threading.Mutex( true, @"Local\slimCODE.slimKEYS.exe", out mutexCreated );

  if( !mutexCreated )
  {
    if( MessageBox.Show(
      "slimKEYS is already running. Hotkeys cannot be shared between different instances. Are you sure you wish to run this second instance?",
      "slimKEYS already running",
      MessageBoxButtons.YesNo,
      MessageBoxIcon.Question ) != DialogResult.Yes )
    {
      mutex.Close();
      return;
    }
  }

  // The usual stuff with Application.Run()

  mutex.Close();
}

Can we create an instance of an interface in Java?

No in my opinion , you can create a reference variable of an interface but you can not create an instance of an interface just like an abstract class.

What are the most common font-sizes for H1-H6 tags

It would depend on the browser's default stylesheet. You can view an (unofficial) table of CSS2.1 User Agent stylesheet defaults here.

Based on the page listed above, the default sizes look something like this:

    IE7     IE8     FF2         FF3         Opera   Safari 3.1
H1  24pt    2em     32px        32px        32px    32px       
H2  18pt    1.5em   24px        24px        24px    24px
H3  13.55pt 1.17em  18.7333px   18.7167px   18px    19px
H4  n/a     n/a     n/a         n/a         n/a     n/a
H5  10pt    0.83em  13.2667px   13.2833px   13px    13px
H6  7.55pt  0.67em  10.7333px   10.7167px   10px    11px

Also worth taking a look at is the default stylesheet for HTML 4. The W3C recommends using these styles as the default. An abridged excerpt:

h1 { font-size: 2em; }
h2 { font-size: 1.5em; }
h3 { font-size: 1.17em; }
h4 { font-size: 1.12em; }
h5 { font-size: .83em; }
h6 { font-size: .75em; }

Hope this information is helpful.

Sending HTTP Post request with SOAP action using org.apache.http

Here is the example i have tried and it is working for me:

Create the XML file SoapRequestFile.xml

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
       <soapenv:Header/>
       <soapenv:Body>
          <tem:GetConversionRate>
             <!--Optional:-->
             <tem:CurrencyFrom>USD</tem:CurrencyFrom>
             <!--Optional:-->
             <tem:CurrencyTo>INR</tem:CurrencyTo>
             <tem:RateDate>2018-12-07</tem:RateDate>
          </tem:GetConversionRate>
       </soapenv:Body>
    </soapenv:Envelope>

And here the code in java:

import java.io.File;
import java.io.FileInputStream;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Assert;
import org.testng.annotations.Test;

import io.restassured.path.json.JsonPath;
import io.restassured.path.xml.XmlPath;
@Test
            public void getMethod() throws Exception  {
                //wsdl file :http://currencyconverter.kowabunga.net/converter.asmx?wsdl
                File soapRequestFile = new File(".\\SOAPRequest\\SoapRequestFile.xml");

                CloseableHttpClient client = HttpClients.createDefault(); //create client
                HttpPost request = new HttpPost("http://currencyconverter.kowabunga.net/converter.asmx"); //Create the request
                request.addHeader("Content-Type", "text/xml"); //adding header
                request.setEntity(new InputStreamEntity(new FileInputStream(soapRequestFile)));
                CloseableHttpResponse response =  client.execute(request);//Execute the command

                int statusCode=response.getStatusLine().getStatusCode();//Get the status code and assert
                System.out.println("Status code: " +statusCode );
                Assert.assertEquals(200, statusCode);

                String responseString = EntityUtils.toString(response.getEntity(),"UTF-8");//Getting the Response body
                System.out.println(responseString);


                XmlPath jsXpath= new XmlPath(responseString);//Converting string into xml path to assert
                String rate=jsXpath.getString("GetConversionRateResult");
                System.out.println("rate returned is: " +  rate);



        }

How to check if command line tools is installed

10.14 Mojave Update:

See Yosemite Update.

10.13 High Sierra Update:

See Yosemite Update.

10.12 Sierra Update:

See Yosemite Update.

10.11 El Capitan Update:

See Yosemite Update.

10.10 Yosemite Update:

Just enter in gcc or make on the command line! OSX will know that you do not have the command line tools and prompt you to install them!

To check if they exist, xcode-select -p will print the directory. Alternatively, the return value will be 2 if they do NOT exist, and 0 if they do. To just print the return value (thanks @Andy):

xcode-select -p 1>/dev/null;echo $?

10.9 Mavericks Update:

Use pkgutil --pkg-info=com.apple.pkg.CLTools_Executables

10.8 Update:

Option 1: Rob Napier suggested to use pkgutil --pkg-info=com.apple.pkg.DeveloperToolsCLI, which is probably cleaner.

Option 2: Check inside /var/db/receipts/com.apple.pkg.DeveloperToolsCLI.plist for a reference to com.apple.pkg.DeveloperToolsCLI and it will list the version 4.5.0.

[Mar 12 17:04] [jnovack@yourmom ~]$ defaults read /var/db/receipts/com.apple.pkg.DeveloperToolsCLI.plist
{
    InstallDate = "2012-12-26 22:45:54 +0000";
    InstallPrefixPath = "/";
    InstallProcessName = Xcode;
    PackageFileName = "DeveloperToolsCLI.pkg";
    PackageGroups =     (
        "com.apple.FindSystemFiles.pkg-group",
        "com.apple.DevToolsBoth.pkg-group",
        "com.apple.DevToolsNonRelocatableShared.pkg-group"
    );
    PackageIdentifier = "com.apple.pkg.DeveloperToolsCLI";
    PackageVersion = "4.5.0.0.1.1249367152";
    PathACLs =     {
        Library = "!#acl 1\\ngroup:ABCDEFAB-CDEF-ABCD-EFAB-CDEF0000000C:everyone:12:deny:delete\\n";
        System = "!#acl 1\\ngroup:ABCDEFAB-CDEF-ABCD-EFAB-CDEF0000000C:everyone:12:deny:delete\\n";
    };
}

Java SSLException: hostname in certificate didn't match

In httpclient-4.3.3.jar, there is another HttpClient to use:

public static void main (String[] args) throws Exception {
    // org.apache.http.client.HttpClient client = new DefaultHttpClient();
    org.apache.http.client.HttpClient client = HttpClientBuilder.create().build();
    System.out.println("HttpClient = " + client.getClass().toString());
    org.apache.http.client.methods.HttpPost post = new HttpPost("https://www.rideforrainbows.org/");
    org.apache.http.HttpResponse response = client.execute(post);
    java.io.InputStream is = response.getEntity().getContent();
    java.io.BufferedReader rd = new java.io.BufferedReader(new java.io.InputStreamReader(is));
    String line;
    while ((line = rd.readLine()) != null) { 
        System.out.println(line);
    }
}

This HttpClientBuilder.create().build() will return org.apache.http.impl.client.InternalHttpClient. It can handle the this hostname in certificate didn't match issue.

PHP Foreach Arrays and objects

Looping over arrays and objects is a pretty common task, and it's good that you're wanting to learn how to do it. Generally speaking you can do a foreach loop which cycles over each member, assigning it a new temporary name, and then lets you handle that particular member via that name:

foreach ($arr as $item) {
    echo $item->sm_id;
}

In this example each of our values in the $arr will be accessed in order as $item. So we can print our values directly off of that. We could also include the index if we wanted:

foreach ($arr as $index => $item) {
    echo "Item at index {$index} has sm_id value {$item->sm_id}";
}

How do I access command line arguments in Python?

If you call it like this: $ python myfile.py var1 var2 var3

import sys

var1 = sys.argv[1]
var2 = sys.argv[2]
var3 = sys.argv[3]

Similar to arrays you also have sys.argv[0] which is always the current working directory.

How to escape the % (percent) sign in C's printf?

As others have said, %% will escape the %.

Note, however, that you should never do this:

char c[100];
char *c2;
...
printf(c); /* OR */
printf(c2);

Whenever you have to print a string, always, always, always print it using

printf("%s", c)

to prevent an embedded % from causing problems [memory violations, segfault, etc]

What is difference between @RequestBody and @RequestParam?

@RequestParam annotated parameters get linked to specific Servlet request parameters. Parameter values are converted to the declared method argument type. This annotation indicates that a method parameter should be bound to a web request parameter.

For example Angular request for Spring RequestParam(s) would look like that:

$http.post('http://localhost:7777/scan/l/register?username="Johny"&password="123123"&auth=true')
      .success(function (data, status, headers, config) {
                        ...
                    })

Endpoint with RequestParam:

@RequestMapping(method = RequestMethod.POST, value = "/register")
public Map<String, String> register(Model uiModel,
                                    @RequestParam String username,
                                    @RequestParam String password,
                                    @RequestParam boolean auth,
                                    HttpServletRequest httpServletRequest) {...

@RequestBody annotated parameters get linked to the HTTP request body. Parameter values are converted to the declared method argument type using HttpMessageConverters. This annotation indicates a method parameter should be bound to the body of the web request.

For example Angular request for Spring RequestBody would look like that:

$scope.user = {
            username: "foo",
            auth: true,
            password: "bar"
        };    
$http.post('http://localhost:7777/scan/l/register', $scope.user).
                        success(function (data, status, headers, config) {
                            ...
                        })

Endpoint with RequestBody:

@RequestMapping(method = RequestMethod.POST, produces = "application/json", 
                value = "/register")
public Map<String, String> register(Model uiModel,
                                    @RequestBody User user,
                                    HttpServletRequest httpServletRequest) {... 

Hope this helps.

In Python, what happens when you import inside of a function?

The very first time you import goo from anywhere (inside or outside a function), goo.py (or other importable form) is loaded and sys.modules['goo'] is set to the module object thus built. Any future import within the same run of the program (again, whether inside or outside a function) just look up sys.modules['goo'] and bind it to barename goo in the appropriate scope. The dict lookup and name binding are very fast operations.

Assuming the very first import gets totally amortized over the program's run anyway, having the "appropriate scope" be module-level means each use of goo.this, goo.that, etc, is two dict lookups -- one for goo and one for the attribute name. Having it be "function level" pays one extra local-variable setting per run of the function (even faster than the dictionary lookup part!) but saves one dict lookup (exchanging it for a local-variable lookup, blazingly fast) for each goo.this (etc) access, basically halving the time such lookups take.

We're talking about a few nanoseconds one way or another, so it's hardly a worthwhile optimization. The one potentially substantial advantage of having the import within a function is when that function may well not be needed at all in a given run of the program, e.g., that function deals with errors, anomalies, and rare situations in general; if that's the case, any run that does not need the functionality will not even perform the import (and that's a saving of microseconds, not just nanoseconds), only runs that do need the functionality will pay the (modest but measurable) price.

It's still an optimization that's only worthwhile in pretty extreme situations, and there are many others I would consider before trying to squeeze out microseconds in this way.

Most pythonic way to delete a file which may not exist

os.path.exists returns True for folders as well as files. Consider using os.path.isfile to check for whether the file exists instead.

What is the difference between '/' and '//' when used for division?

The answer of the equation is rounded to the next smaller integer or float with .0 as decimal point.

>>>print 5//2
2
>>> print 5.0//2
2.0
>>>print 5//2.0
2.0
>>>print 5.0//2.0
2.0

jQuery: Uncheck other checkbox on one checked

I wanted to add an answer if the checkboxes are being generated in a loop. For example if your structure is like this (Assuming you are using server side constructs on your View, like a foreach loop):

<li id="checkboxlist" class="list-group-item card">
  <div class="checkbox checkbox-inline">
    <label><input type="checkbox" id="checkbox1">Checkbox 1</label>
    <label><input type="checkbox" id="checkbox2">Checkbox 2</label>
  </div>
</li>

<li id="checkboxlist" class="list-group-item card">
  <div class="checkbox checkbox-inline">
    <label><input type="checkbox" id="checkbox1">Checkbox 1</label>
    <label><input type="checkbox" id="checkbox2">Checkbox 2</label>
  </div>
</li>

Corresponding Jquery:

$(".list-group-item").each(function (i, li) {
  var currentli = $(li);
  $(currentli).find("#checkbox1").on('change', function () {
       $(currentli).find("#checkbox2").not(this).prop('checked',false);
  });

  $(currentli).find("#checkbox2").on('change', function () {
       $(currentli).find("#checkbox1").not(this).prop('checked', false);
  });
});

Working DEMO: https://jsfiddle.net/gr67qk20/

Error Importing SSL certificate : Not an X.509 Certificate

I changed 3 things and then it works:

  1. There is a column of spaces, I removed them
  2. Changed the line break from windows CRLF to linux LF
  3. Removed the empty line at the end.

Java Ordered Map

Modern Java version of Steffi Keran's answer

public class Solution {
    public static void main(String[] args) {
        // create a simple hash map and insert some key-value pairs into it
        Map<String, Integer> map = new HashMap<>();
        map.put("Python", 3);
        map.put("C", 0);
        map.put("JavaScript", 4);
        map.put("C++", 1);
        map.put("Golang", 5);
        map.put("Java", 2);
        // Create a linked list from the above map entries
        List<Map.Entry<String, Integer>> list = new LinkedList<>(map.entrySet());
        // sort the linked list using Collections.sort()
        list.sort(Comparator.comparing(Map.Entry::getValue));
        list.forEach(System.out::println);
    }
}

jQuery UI Accordion Expand/Collapse All

I second bigvax comment earlier but you need to make sure that you add

        jQuery("#jQueryUIAccordion").({ active: false,
                              collapsible: true });

otherwise you wont be able to open the first accordion after collapsing them.

    $('.close').click(function () {
    $('.ui-accordion-header').removeClass('ui-accordion-header-active ui-state-active ui-corner-top').addClass('ui-corner-all').attr({'aria-selected':'false','tabindex':'-1'});
    $('.ui-accordion-header .ui-icon').removeClass('ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-e');
    $('.ui-accordion-content').removeClass('ui-accordion-content-active').attr({'aria-expanded':'false','aria-hidden':'true'}).hide();
   }

How do I make a burn down chart in Excel?

Say your data set is in Columns A and B of the first sheet.

  1. On Insert ribbon, pick chart type as "Line with Markers"
  2. Right-click on chart, "Select Data...". Select your data in columns without column labels, so your data range would be something like =Sheet1!$A$2:$B$5.
  3. Profit! I mean you're done :-) You might want to change 'Series1' label Excel generates with an actual book name, you can do so in the above "Select Data" dialog.

You can do this with multiple books too - as long as their "pages remaining" data points are tracked on the same dates (e.g. Book2 data would be in Column C, etc...) Books will be represented by additional series.

Removing html5 required attribute with jQuery

_x000D_
_x000D_
$('#id').removeAttr('required');?????
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

How to view method information in Android Studio?

The easiest and the most straightforward way:

To activate: File > Settings > Editor > General

For Mac OS X, Android Studio > Preferences > Editor > General and check Show quick documentation on mouse move:

Settings dialog with checked option

Other ways:

  • You can go into your IntelliJ's bin folder and search for idea.properties. Add this line to the document:

    auto.show.quick.doc=true

    Now you'll have the same floating docs window like in Eclipse.

  • You have to press CTRL+Q to see the Javadoc.

    You can pin the window and make the documentation appear every time you select a method with your mouse though.

Android Studio 1.0: You have to hold CTRL if you want to get hold of documentation window for e.g. scrolling documentation otherwise as you move your mouse away from method documentation window will disappear.

includes() not working in all browsers

Here is solution ( ref : https://www.cluemediator.com/object-doesnt-support-property-or-method-includes-in-ie )

if (!Array.prototype.includes) {
  Object.defineProperty(Array.prototype, 'includes', {
    value: function (searchElement, fromIndex) {

      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      // 1. Let O be ? ToObject(this value).
      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If len is 0, return false.
      if (len === 0) {
        return false;
      }

      // 4. Let n be ? ToInteger(fromIndex).
      //    (If fromIndex is undefined, this step produces the value 0.)
      var n = fromIndex | 0;

      // 5. If n = 0, then
      //  a. Let k be n.
      // 6. Else n < 0,
      //  a. Let k be len + n.
      //  b. If k < 0, let k be 0.
      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

      function sameValueZero(x, y) {
        return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
      }

      // 7. Repeat, while k < len
      while (k < len) {
        // a. Let elementK be the result of ? Get(O, ! ToString(k)).
        // b. If SameValueZero(searchElement, elementK) is true, return true.
        if (sameValueZero(o[k], searchElement)) {
          return true;
        }
        // c. Increase k by 1. 
        k++;
      }

      // 8. Return false
      return false;
    }
  });
}

POST an array from an HTML form without javascript

check this one out.

<input type="text" name="firstname">
<input type="text" name="lastname">
<input type="text" name="email">
<input type="text" name="address">

<input type="text" name="tree[tree1][fruit]">
<input type="text" name="tree[tree1][height]">

<input type="text" name="tree[tree2][fruit]">
<input type="text" name="tree[tree2][height]">

<input type="text" name="tree[tree3][fruit]">
<input type="text" name="tree[tree3][height]">

it should end up like this in the $_POST[] array (PHP format for easy visualization)

$_POST[] = array(
    'firstname'=>'value',
    'lastname'=>'value',
    'email'=>'value',
    'address'=>'value',
    'tree' => array(
        'tree1'=>array(
            'fruit'=>'value',
            'height'=>'value'
        ),
        'tree2'=>array(
            'fruit'=>'value',
            'height'=>'value'
        ),
        'tree3'=>array(
            'fruit'=>'value',
            'height'=>'value'
        )
    )
)

HTTP Error 403.14 - Forbidden - The Web server is configured to not list the contents of this directory

This could happen for any number of reasons. If you have tried through all of the above and still getting the same error, I have one more solution.

Another reason this could happen is that

  1. If you have the same code base running before you started to run the fresh solution, you might encounter this error. The reason is that IIS Express is trying to run on the same port as it was for the old solution which has the physical path registered for the application start URL.
  2. Since the IIS cannot figure out the physical path to run the solution, it might not be able to locate all the dlls required to start the application.

Solutions:

  1. Try to change the application port to default. For example., Use http://localhost/ instead of http://localhost:25836/

  2. Try changing to any other port if you have already used the default port for the previous application. ex: http://localhost:25364/ instead of http://localhost/

This will allow the IIS/IIS Express to point to the default bin path of the newer application you are trying to run which will have all the required dlls to start the application.

How do I programmatically get the GUID of an application in .NET 2.0

You should be able to read the GUID attribute of the assembly via reflection. This will get the GUID for the current assembly

Assembly asm = Assembly.GetExecutingAssembly();
var attribs = (asm.GetCustomAttributes(typeof(GuidAttribute), true));
Console.WriteLine((attribs[0] as GuidAttribute).Value);

You can replace the GuidAttribute with other attributes as well, if you want to read things like AssemblyTitle, AssemblyVersion, etc.

You can also load another assembly (Assembly.LoadFrom and all) instead of getting the current assembly - if you need to read these attributes of external assemblies (for example, when loading a plugin).

How to add manifest permission to an application?

That may be also interesting in context of adding INTERNET permission to your application:

Google has also given each app Internet access, effectively removing the Internet access permission. Oh, sure, Android developers still have to declare they want Internet access when putting together the app. But users can no longer see the Internet access permission when installing an app and current apps that don’t have Internet access can now gain Internet access with an automatic update without prompting you.

Source: http://www.howtogeek.com/190863/androids-app-permissions-were-just-simplified-now-theyre-much-less-secure/

Bottom line is that you still have to add INTERNET permission in manifest file but application will be updated on user's devices without asking them for new permission.

Understanding the map function

map creates a new list by applying a function to every element of the source:

xs = [1, 2, 3]

# all of those are equivalent — the output is [2, 4, 6]
# 1. map
ys = map(lambda x: x * 2, xs)
# 2. list comprehension
ys = [x * 2 for x in xs]
# 3. explicit loop
ys = []
for x in xs:
    ys.append(x * 2)

n-ary map is equivalent to zipping input iterables together and then applying the transformation function on every element of that intermediate zipped list. It's not a Cartesian product:

xs = [1, 2, 3]
ys = [2, 4, 6]

def f(x, y):
    return (x * 2, y // 2)

# output: [(2, 1), (4, 2), (6, 3)]
# 1. map
zs = map(f, xs, ys)
# 2. list comp
zs = [f(x, y) for x, y in zip(xs, ys)]
# 3. explicit loop
zs = []
for x, y in zip(xs, ys):
    zs.append(f(x, y))

I've used zip here, but map behaviour actually differs slightly when iterables aren't the same size — as noted in its documentation, it extends iterables to contain None.

The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "Scripts"

Please make sure you have typed correct spelling of using script section in view

the correct is

@section scripts{ //your script here}

if you typed @section script{ //your script here} this is wrong.

Disable keyboard on EditText

Just put this line inside the activity tag in manifest android:windowSoftInputMode="stateHidden"

SQL query to find Nth highest salary from a salary table

If you want to find nth Salary from a table (here n should be any thing like 1st or 2nd or 15th highest Salaries)

This is the Query for to find nth Salary:

SELECT DISTINCT Salary FROM tblemployee ORDER BY Salary DESC LIMIT 1 OFFSET (n-1)

If you want to find 8th highest salary, query should be :

SELECT DISTINCT Salary FROM tblemployee ORDER BY Salary DESC LIMIT 1 OFFSET 7

Note: OFFSET starts from 0th position, and hence use N-1 rule here

Set element width or height in Standards Mode

The style property lets you specify values for CSS properties.

The CSS width property takes a length as its value.

Lengths require units. In quirks mode, browsers tend to assume pixels if provided with an integer instead of a length. Specify units.

e1.style.width = "400px";

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

As another option, you can do look ups like:

class UserAdmin(admin.ModelAdmin):
    list_display = (..., 'get_author')

    def get_author(self, obj):
        return obj.book.author
    get_author.short_description = 'Author'
    get_author.admin_order_field = 'book__author'

How to install wget in macOS?

I update mac to Sierra , 10.12.3

My wget stop working.

When I tried to install by typing

brew install wget --with-libressl

I got the following warning

Warning: wget-1.19.1 already installed, it's just not linked.

Then tried to unsintall by typing

brew uninstall wget --with-libressl

Then I reinstalled by typing

brew install wget --with-libressl

Finally I got it worked.Thank God!

How do you change library location in R?

I'm late to the party but I encountered the same thing when I tried to get fancy and move my library and then had files being saved to a folder that was outdated:

.libloc <<- "C:/Program Files/rest_of_your_Library_FileName"

One other point to mention is that for Windows Computers, if you copy the address from Windows Explorer, you have to manually change the '\' to a '/' for the directory to be recognized.

Setting the default ssh key location

If you are only looking to point to a different location for you identity file, the you can modify your ~/.ssh/config file with the following entry:

IdentityFile ~/.foo/identity

man ssh_config to find other config options.

Use a.any() or a.all()

This should also work and is a closer answer to what is asked in the question:

for i in range(len(x)):
    if valeur.item(i) <= 0.6:
        print ("this works")
    else:   
        print ("valeur is too high")

How to add custom method to Spring Data JPA

The accepted answer works, but has three problems:

  • It uses an undocumented Spring Data feature when naming the custom implementation as AccountRepositoryImpl. The documentation clearly states that it has to be called AccountRepositoryCustomImpl, the custom interface name plus Impl
  • You cannot use constructor injection, only @Autowired, that are considered bad practice
  • You have a circular dependency inside of the custom implementation (that's why you cannot use constructor injection).

I found a way to make it perfect, though not without using another undocumented Spring Data feature:

public interface AccountRepository extends AccountRepositoryBasic,
                                           AccountRepositoryCustom 
{ 
}

public interface AccountRepositoryBasic extends JpaRepository<Account, Long>
{
    // standard Spring Data methods, like findByLogin
}

public interface AccountRepositoryCustom 
{
    public void customMethod();
}

public class AccountRepositoryCustomImpl implements AccountRepositoryCustom 
{
    private final AccountRepositoryBasic accountRepositoryBasic;

    // constructor-based injection
    public AccountRepositoryCustomImpl(
        AccountRepositoryBasic accountRepositoryBasic)
    {
        this.accountRepositoryBasic = accountRepositoryBasic;
    }

    public void customMethod() 
    {
        // we can call all basic Spring Data methods using
        // accountRepositoryBasic
    }
}

How do you modify the web.config appSettings at runtime?

I know this question is old, but I wanted to post an answer based on the current state of affairs in the ASP.NET\IIS world combined with my real world experience.

I recently spearheaded a project at my company where I wanted to consolidate and manage all of the appSettings & connectionStrings settings in our web.config files in one central place. I wanted to pursue an approach where our config settings were stored in ZooKeeper due to that projects maturity & stability. Not to mention that fact that ZooKeeper is by design a configuration & cluster managing application.

The project goals were very simple;

  1. get ASP.NET to communicate with ZooKeeper
  2. in Global.asax, Application_Start - pull web.config settings from ZooKeeper.

Upon getting passed the technical piece of getting ASP.NET to talk to ZooKeeper, I quickly found and hit a wall with the following code;

ConfigurationManager.AppSettings.Add(key_name, data_value)

That statement made the most logical sense since I wanted to ADD new settings to the appSettings collection. However, as the original poster (and many others) mentioned, this code call returns an Error stating that the collection is Read-Only.

After doing a bit of research and seeing all the different crazy ways people worked around this problem, I was very discouraged. Instead of giving up or settling for what appeared to be a less than ideal scenario, I decided to dig in and see if I was missing something.

With a little trial and error, I found the following code would do exactly what I wanted;

ConfigurationManager.AppSettings.Set(key_name, data_value)

Using this line of code, I am now able to load all 85 appSettings keys from ZooKeeper in my Application_Start.

In regards to general statements about changes to web.config triggering IIS recycles, I edited the following appPool settings to monitor the situation behind the scenes;

appPool-->Advanced Settings-->Recycling-->Disable Recycling for Configuration Changes = False
appPool-->Advanced Settings-->Recycling-->Generate Recycle Event Log Entry-->[For Each Setting] = True

With that combination of settings, if this process were to cause an appPool recycle, an Event Log entry should have be recorded, which it was not.

This leads me to conclude that it is possible, and indeed safe, to load an applications settings from a centralized storage medium.

I should mention that I am using IIS7.5 on Windows 7. The code will be getting deployed to IIS8 on Win2012. Should anything regarding this answer change, I will update this answer accordingly.

How to change the color of a button?

The RIGHT way...

The following methods actually work.

if you wish - using a theme
By default a buttons color is android:colorAccent. So, if you create a style like this...

<style name="Button.White" parent="ThemeOverlay.AppCompat">
    <item name="colorAccent">@android:color/white</item>
</style>

You can use it like this...

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:theme="@style/Button.White"
    />

alternatively - using a tint
You can simply add android:backgroundTint for API Level 21 and higher, or app:backgroundTint for API Level 7 and higher.

For more information, see this blog.

The problem with the accepted answer...

If you replace the background with a color you will loose the effect of the button, and the color will be applied to the entire area of the button. It will not respect the padding, shadow, and corner radius.

How to determine the installed webpack version

For those who are using yarn

yarn list webpack will do the trick

$ yarn list webpack
yarn list v0.27.5
+- [email protected]
Done in 1.24s.

Rendering HTML inside textarea

I have the same problem but in reverse, and the following solution. I want to put html from a div in a textarea (so I can edit some reactions on my website; I want to have the textarea in the same location.)

To put the content of this div in a textarea I use:

_x000D_
_x000D_
var content = $('#msg500').text();_x000D_
$('#msg500').wrapInner('<textarea>' + content + '</textarea>');
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="msg500">here some <strong>html</strong> <i>tags</i>.</div>
_x000D_
_x000D_
_x000D_

How do I parse a string to a float or int?

This is a corrected version of https://stackoverflow.com/a/33017514/5973334

This will try to parse a string and return either int or float depending on what the string represents. It might rise parsing exceptions or have some unexpected behaviour.

  def get_int_or_float(v):
        number_as_float = float(v)
        number_as_int = int(number_as_float)
        return number_as_int if number_as_float == number_as_int else 
        number_as_float

Why is my power operator (^) not working?

There is no way to use the ^ (Bitwise XOR) operator to calculate the power of a number. Therefore, in order to calculate the power of a number we have two options, either we use a while loop or the pow() function.

1. Using a while loop.

#include <stdio.h>

int main() {

    int base, expo;
    long long result = 1;

    printf("Enter a base no.: ");
    scanf("%d", &base);

    printf("Enter an exponent: ");
    scanf("%d", &expo);

    while (expo != 0) {
        result *= base;
        --expo;
    }

    printf("Answer = %lld", result);
    return 0;
}    
             

2. Using the pow() function

#include <math.h>
#include <stdio.h>

int main() {

    double base, exp, result;

    printf("Enter a base number: ");
    scanf("%lf", &base);

    printf("Enter an exponent: ");
    scanf("%lf", &exp);

    // calculate the power of our input numbers
    result = pow(base, exp);

    printf("%.1lf^%.1lf = %.2lf", base, exp, result);

    return 0;
}
     

Databinding an enum property to a ComboBox in WPF

My favorite way to do this is with a ValueConverter so that the ItemsSource and SelectedValue both bind to the same property. This requires no additional properties to keep your ViewModel nice and clean.

<ComboBox ItemsSource="{Binding Path=ExampleProperty, Converter={x:EnumToCollectionConverter}, Mode=OneTime}"
          SelectedValuePath="Value"
          DisplayMemberPath="Description"
          SelectedValue="{Binding Path=ExampleProperty}" />

And the definition of the Converter:

public static class EnumHelper
{
  public static string Description(this Enum e)
  {
    return (e.GetType()
             .GetField(e.ToString())
             .GetCustomAttributes(typeof(DescriptionAttribute), false)
             .FirstOrDefault() as DescriptionAttribute)?.Description ?? e.ToString();
  }
}

[ValueConversion(typeof(Enum), typeof(IEnumerable<ValueDescription>))]
public class EnumToCollectionConverter : MarkupExtension, IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
    return Enum.GetValues(value.GetType())
               .Cast<Enum>()
               .Select(e => new ValueDescription() { Value = e, Description = e.Description()})
               .ToList();
  }
  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
    return null;
  }
  public override object ProvideValue(IServiceProvider serviceProvider)
  {
    return this;
  }
}

This converter will work with any enum. ValueDescription is just a simple class with a Value property and a Description property. You could just as easily use a Tuple with Item1 and Item2, or a KeyValuePair with Key and Value instead of Value and Description or any other class of your choice as long as it has can hold an enum value and string description of that enum value.

I want to compare two lists in different worksheets in Excel to locate any duplicates

Without VBA...

If you can use a helper column, you can use the MATCH function to test if a value in one column exists in another column (or in another column on another worksheet). It will return an Error if there is no match

To simply identify duplicates, use a helper column

Assume data in Sheet1, Column A, and another list in Sheet2, Column A. In your helper column, row 1, place the following formula:

=If(IsError(Match(A1, 'Sheet2'!A:A,False)),"","Duplicate")

Drag/copy this forumla down, and it should identify the duplicates.

To highlight cells, use conditional formatting:

With some tinkering, you can use this MATCH function in a Conditional Formatting rule which would highlight duplicate values. I would probably do this instead of using a helper column, although the helper column is a great way to "see" results before you make the conditional formatting rule.

Something like:

=NOT(ISERROR(MATCH(A1, 'Sheet2'!A:A,FALSE)))

Conditional formatting for Excel 2010

For Excel 2007 and prior, you cannot use conditional formatting rules that reference other worksheets. In this case, use the helper column and set your formatting rule in column A like:

=B1="Duplicate"

This screenshot is from the 2010 UI, but the same rule should work in 2007/2003 Excel.

Conditional formatting using helper column for rule

Effect of using sys.path.insert(0, path) and sys.path(append) when loading modules

I'm quite a beginner in Python and I found the answer of Anand was very good but quite complicated to me, so I try to reformulate :

1) insert and append methods are not specific to sys.path and as in other languages they add an item into a list or array and :
* append(item) add item to the end of the list,
* insert(n, item) inserts the item at the nth position in the list (0 at the beginning, 1 after the first element, etc ...).

2) As Anand said, python search the import files in each directory of the path in the order of the path, so :
* If you have no file name collisions, the order of the path has no impact,
* If you look after a function already defined in the path and you use append to add your path, you will not get your function but the predefined one.

But I think that it is better to use append and not insert to not overload the standard behaviour of Python, and use non-ambiguous names for your files and methods.

How do I catch an Ajax query post error?

You have to log the responseText:

$.ajax({
    type: 'POST',
    url: 'status.ajax.php',
    data: {
    deviceId: id
  }
})
.done(
 function (data) {
  //your code
 }
)
.fail(function (data) {
      console.log( "Ajax failed: " + data['responseText'] );
})

Singleton design pattern vs Singleton beans in Spring container

Singleton scope in Spring means that this bean will be instantiated only once by Spring. In contrast to the prototype scope (new instance each time), request scope (once per request), session scope (once per HTTP session).

Singleton scope has technically nothing to do with the singleton design pattern. You don't have to implement your beans as singletons for them to be put in the singleton scope.

How to add anything in <head> through jquery/javascript?

Create a temporary element (e. g. DIV), assign your HTML code to its innerHTML property, and then append its child nodes to the HEAD element one by one. For example, like this:

var temp = document.createElement('div');

temp.innerHTML = '<link rel="stylesheet" href="example.css" />'
               + '<script src="foobar.js"><\/script> ';

var head = document.head;

while (temp.firstChild) {
    head.appendChild(temp.firstChild);
}

Compared with rewriting entire HEAD contents via its innerHTML, this wouldn’t affect existing child elements of the HEAD element in any way.

Note that scripts inserted this way are apparently not executed automatically, while styles are applied successfully. So if you need scripts to be executed, you should load JS files using Ajax and then execute their contents using eval().

PHP: How to get current time in hour:minute:second?

You can have both formats as an argument to the function date():

date("d-m-Y H:i:s")

Check the manual for more info : http://php.net/manual/en/function.date.php

As pointed out by @ThomasVdBerge to display minutes you need the 'i' character

Python requests - print entire http request (raw)?

import requests

response = requests.post('http://httpbin.org/post', data={'key1':'value1'})
print(response.request.url)
print(response.request.body)
print(response.request.headers)

Response objects have a .request property which is the original PreparedRequest object that was sent.

Javascript can't find element by id?

The script is performed before the DOM of the body is built. Put it all into a function and call it from the onload of the body-element.

How to run console application from Windows Service?

Does your console app require user interaction? If so, that's a serious no-no and you should redesign your application. While there are some hacks to make this sort of work in older versions of the OS, this is guaranteed to break in the future.

If your app does not require user interaction, then perhaps your problem is related to the user the service is running as. Try making sure that you run as the correct user, or that the user and/or resources you are using have the right permissions.

If you require some kind of user-interaction, then you will need to create a client application and communicate with the service and/or sub-application via rpc, sockets, or named pipes.

Running Tensorflow in Jupyter Notebook

I came up with your case. This is how I sort it out

  1. Install Anaconda
  2. Create a virtual environment - conda create -n tensor flow
  3. Go inside your virtual environment - Source activate tensorflow
  4. Inside that install tensorflow. You can install it using pip
  5. Finish install

So then the next thing, when you launch it:

  1. If you are not inside the virtual environment type - Source Activate Tensorflow
  2. Then inside this again install your Jupiter notebook and Pandas libraries, because there can be some missing in this virtual environment

Inside the virtual environment just type:

  1. pip install jupyter notebook
  2. pip install pandas

Then you can launch jupyter notebook saying:

  1. jupyter notebook
  2. Select the correct terminal python 3 or 2
  3. Then import those modules

What characters are valid for JavaScript variable names?

To quote Valid JavaScript variable names, my write-up summarizing the relevant spec sections:

An identifier must start with $, _, or any character in the Unicode categories “Uppercase letter (Lu)”, “Lowercase letter (Ll)”, “Titlecase letter (Lt)”, “Modifier letter (Lm)”, “Other letter (Lo)”, or “Letter number (Nl)”.

The rest of the string can contain the same characters, plus any U+200C zero width non-joiner characters, U+200D zero width joiner characters, and characters in the Unicode categories “Non-spacing mark (Mn)”, “Spacing combining mark (Mc)”, “Decimal digit number (Nd)”, or “Connector punctuation (Pc)”.

I’ve also created a tool that will tell you if any string that you enter is a valid JavaScript variable name according to ECMAScript 5.1 and Unicode 6.1:

JavaScript variable name validator


P.S. To give you an idea of how wrong Anthony Mills' answer is: if you were to summarize all these rules in a single ASCII-only regular expression for JavaScript, it would be 11,236 characters long. Here it is:

// ES5.1 / Unicode 6.1
/^(?!(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$)[$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc][$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc0-9\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19b0-\u19c0\u19c8\u19c9\u19d0-\u19d9\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1dc0-\u1de6\u1dfc-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f]*$/

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

This is a terrible way to do it but it avoids creating a definition. It fulfills the requirement to stick with the basic Python3 library.

# Adjust from UST to Eastern Standard Time (dynamic)
# df.my_localtime should already be in datetime format, so just in case
df['my_localtime'] = pd.to_datetime.df['my_localtime']

df['my_localtime'] = df['my_localtime'].dt.tz_localize('UTC').dt.tz_convert('America/New_York').astype(str)
df['my_localtime'] = pd.to_datetime(df.my_localtime.str[:-6])

How can I hide or encrypt JavaScript code?

One of the best compressors (not specifically an obfuscator) is the YUI Compressor.

Convert Time DataType into AM PM Format:

This returns like 11:30 AM

select CONVERT(VARCHAR(5), FromTime, 108) + ' ' + RIGHT(CONVERT(VARCHAR(30), FromTime, 9),2)
from tablename

Logging in Scala

Haven't tried it yet, but Configgy looks promising for both configuration and logging:

http://github.com/robey/configgy/tree/master

Dynamically updating plot in matplotlib

Here is a way which allows to remove points after a certain number of points plotted:

import matplotlib.pyplot as plt
# generate axes object
ax = plt.axes()

# set limits
plt.xlim(0,10) 
plt.ylim(0,10)

for i in range(10):        
     # add something to axes    
     ax.scatter([i], [i]) 
     ax.plot([i], [i+1], 'rx')

     # draw the plot
     plt.draw() 
     plt.pause(0.01) #is necessary for the plot to update for some reason

     # start removing points if you don't want all shown
     if i>2:
         ax.lines[0].remove()
         ax.collections[0].remove()

Java Webservice Client (Best way)

I have had good success using Spring WS for the client end of a web service app - see http://static.springsource.org/spring-ws/sites/1.5/reference/html/client.html

My project uses a combination of:

  • XMLBeans (generated from a simple Maven job using the xmlbeans-maven-plugin)

  • Spring WS - using marshalSendAndReceive() reduces the code down to one line for sending and receiving

  • some Dozer - mapping the complex XMLBeans to simple beans for the client GUI

remove kernel on jupyter notebook

You can delete it in the terminal via:

jupyter kernelspec uninstall yourKernel

where yourKernel is the name of the kernel you want to delete.

Changing the highlight color when selecting text in an HTML text input

I realise this is an old question but for anyone who does come across it this can be done using contenteditable as shown in this JSFiddle.

Kudos to Alex who mentioned this in the comments (I didn't see that until now!)

How do I retrieve query parameters in Spring Boot?

In Spring boot: 2.1.6, you can use like below:

    @GetMapping("/orders")
    @ApiOperation(value = "retrieve orders", response = OrderResponse.class, responseContainer = "List")
    public List<OrderResponse> getOrders(
            @RequestParam(value = "creationDateTimeFrom", required = true) String creationDateTimeFrom,
            @RequestParam(value = "creationDateTimeTo", required = true) String creationDateTimeTo,
            @RequestParam(value = "location_id", required = true) String location_id) {

        // TODO...

        return response;

@ApiOperation is an annotation that comes from Swagger api, It is used for documenting the apis.

How do I change Android Studio editor's background color?

You can change it by going File => Settings (Shortcut CTRL+ ALT+ S) , from Left panel Choose Appearance , Now from Right Panel choose theme.

enter image description here

Android Studio 2.1

Preference -> Search for Appearance -> UI options , Click on DropDown Theme

enter image description here

Android 2.2

Android studio -> File -> Settings -> Appearance & Behavior -> Look for UI Options

EDIT :

Import External Themes

You can download custom theme from this website. Choose your theme, download it. To set theme Go to Android studio -> File -> Import Settings -> Choose the .jar file downloaded.

'Connect-MsolService' is not recognized as the name of a cmdlet

This issue can occur if the Azure Active Directory Module for Windows PowerShell isn't loaded correctly.

To resolve this issue, follow these steps.
1.Install the Azure Active Directory Module for Windows PowerShell on the computer (if it isn't already installed). To install the Azure Active Directory Module for Windows PowerShell, go to the following Microsoft website:
Manage Azure AD using Windows PowerShell

2.If the MSOnline module isn't present, use Windows PowerShell to import the MSOnline module.

Import-Module MSOnline 

After it complete, we can use this command to check it.

PS C:\Users> Get-Module -ListAvailable -Name MSOnline*


    Directory: C:\windows\system32\WindowsPowerShell\v1.0\Modules


ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   1.1.166.0  MSOnline                            {Get-MsolDevice, Remove-MsolDevice, Enable-MsolDevice, Disable-MsolDevice...}
Manifest   1.1.166.0  MSOnlineExtended                    {Get-MsolDevice, Remove-MsolDevice, Enable-MsolDevice, Disable-MsolDevice...}

More information about this issue, please refer to it.


Update:

We should import azure AD powershell to VS 2015, we can add tool and select Azure AD powershell.

enter image description here

How to retrieve an Oracle directory path?

select directory_path from dba_directories where upper(directory_name) = 'CSVDIR'

Document Root PHP

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

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

how to call a variable in code behind to aspx page

The HelloFromCsharp.aspx look like this

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="HelloFromCsharp.aspx.cs" Inherits="Test.HelloFromCsharp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <p>
       <%= clients%>
    </p>
    </form>
</body>
</html>

And the HelloFromCsharp.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Test
{
    public partial class HelloFromCsharp : System.Web.UI.Page
    {
        public string clients;
        protected void Page_Load(object sender, EventArgs e)
        {
            clients = "Hello From C#";
        }
    }
}

How to use java.net.URLConnection to fire and handle HTTP requests?

When working with HTTP it's almost always more useful to refer to HttpURLConnection rather than the base class URLConnection (since URLConnection is an abstract class when you ask for URLConnection.openConnection() on a HTTP URL that's what you'll get back anyway).

Then you can instead of relying on URLConnection#setDoOutput(true) to implicitly set the request method to POST instead do httpURLConnection.setRequestMethod("POST") which some might find more natural (and which also allows you to specify other request methods such as PUT, DELETE, ...).

It also provides useful HTTP constants so you can do:

int responseCode = httpURLConnection.getResponseCode();

if (responseCode == HttpURLConnection.HTTP_OK) {

Installing NumPy and SciPy on 64-bit Windows (with Pip)

If you are on windows , you wouldn't need wheel anyway! You can directly install package by downloading the 32-bit package as win32 from this link [http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy] and then move that downloaded package to cmd's current directory and open cmd and write following codepip install numpy-1.13.1+mkl-cp36-cp36m-win32.whl then do it same for scipy

For 64-bit you need to install mingw-w64 as it is gcc and compiles numpy and scipy as precompiled status.

Currently it works fine with 32-bit.So I had opted for win32 package both for numpy+mkl and scipy in that link.

Hope This works! Give a try

Error: Cannot find module 'webpack'

If you have installed a node package and are still getting message that the package is undefined, you might have an issue with the PATH linking to the binary. Just to clarify a binary and executable essentially do the same thing, which is to execute a package or application. ei webpack... executes the node package webpack.

In both Windows and Linux there is a global binary folder. In Windows I believe it's something like C://Windows/System32 and in Linux it's usr/bin. When you open the terminal/command prompt, the profile of it links the PATH variable to the global bin folder so you are able to execute packages/applications from it.

My best guess is that installing webpack globally may not have successfully put the executable file in the global binary folder. Without the executable there, you will get an error message. It could be another issue, but it is safe to say the that if you are here reading this, running webpack globally is not working for you.

My resolution to this problem is to do away with running webpack globally and link the PATH to the node_module binary folder, which is /node_modules/.bin.

WINDOWS: add node_modules/.bin to your PATH. Here is a tutorial on how to change the PATH variable in windows.

LINUX: Go to your project root and execute this...

export PATH=$PWD/node_modules/.bin:$PATH 

In Linux you will have to execute this command every time you open your terminal. This link here shows you how to make a change to your PATH variable permanent.

Why did Servlet.service() for servlet jsp throw this exception?

I had this error; it happened somewhat spontaneously, and the page would halt in the browser in the middle of an HTML tag (not a section of code). It was baffling!

Turns out, I let a variable go out of scope and the garbage collector swept it away and then I tried to use it. Thus the seemingly-random timing.

To give a more concrete example... Inside a method, I had something like:

Foo[] foos = new Foo[20];
// fill up the "foos" array...
return Arrays.asList(foos); // this returns type List<Foo>

Now in my JSP page, I called that method and used the List object returned by it. The List object is backed by that "foos" array; but, the array went out of scope when I returned from the method (since it is a local variable). So shortly after returning, the garbage collector swept away the "foos" array, and my access to the List caused a NullPointerException since its underlying array was now wiped away.

I actually wondered, as I wrote the above method, whether that would happen.

The even deeper underlying problem was premature optimization. I wanted a list, but I knew I would have exactly 20 elements, so I figured I'd try to be more efficient than new ArrayList<Foo>(20) which only sets an initial size of 20 but can possibly be less efficient than the method I used. So of course, to fix it, I just created my ArrayList, filled it up, and returned it. No more strange error.

java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonFactory

As of jackson 2.7.4 (or earlier maybe), the class is in jacskon-jaxrs-base.jar, which is contained in jackson-jaxrs-json-provider

Random alpha-numeric string in JavaScript?

Nice and simple, and not limited to a certain number of characters:

let len = 20, str = "";
while(str.length < len) str += Math.random().toString(36).substr(2);
str = str.substr(0, len);

How do I import material design library to Android Studio?

build.gradle

implementation 'com.google.android.material:material:1.2.0-alpha02'

styles.xml

 <!-- Base application theme. -->
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>